PackageManagerService.java revision 7281cf276ac084562c0382e4002b0ddce93c95b2
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 final int[] gids = permissionsState.computeGids(userId); 3220 final Set<String> permissions = permissionsState.getPermissions(userId); 3221 final PackageUserState state = ps.readUserState(userId); 3222 3223 return PackageParser.generatePackageInfo(p, gids, flags, 3224 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3225 } 3226 3227 @Override 3228 public void checkPackageStartable(String packageName, int userId) { 3229 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3230 3231 synchronized (mPackages) { 3232 final PackageSetting ps = mSettings.mPackages.get(packageName); 3233 if (ps == null) { 3234 throw new SecurityException("Package " + packageName + " was not found!"); 3235 } 3236 3237 if (!ps.getInstalled(userId)) { 3238 throw new SecurityException( 3239 "Package " + packageName + " was not installed for user " + userId + "!"); 3240 } 3241 3242 if (mSafeMode && !ps.isSystem()) { 3243 throw new SecurityException("Package " + packageName + " not a system app!"); 3244 } 3245 3246 if (mFrozenPackages.contains(packageName)) { 3247 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3248 } 3249 3250 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3251 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3252 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3253 } 3254 } 3255 } 3256 3257 @Override 3258 public boolean isPackageAvailable(String packageName, int userId) { 3259 if (!sUserManager.exists(userId)) return false; 3260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3261 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3262 synchronized (mPackages) { 3263 PackageParser.Package p = mPackages.get(packageName); 3264 if (p != null) { 3265 final PackageSetting ps = (PackageSetting) p.mExtras; 3266 if (ps != null) { 3267 final PackageUserState state = ps.readUserState(userId); 3268 if (state != null) { 3269 return PackageParser.isAvailable(state); 3270 } 3271 } 3272 } 3273 } 3274 return false; 3275 } 3276 3277 @Override 3278 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3279 if (!sUserManager.exists(userId)) return null; 3280 flags = updateFlagsForPackage(flags, userId, packageName); 3281 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3282 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3283 // reader 3284 synchronized (mPackages) { 3285 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3286 PackageParser.Package p = null; 3287 if (matchFactoryOnly) { 3288 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3289 if (ps != null) { 3290 return generatePackageInfo(ps, flags, userId); 3291 } 3292 } 3293 if (p == null) { 3294 p = mPackages.get(packageName); 3295 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3296 return null; 3297 } 3298 } 3299 if (DEBUG_PACKAGE_INFO) 3300 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3301 if (p != null) { 3302 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3303 } 3304 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3305 final PackageSetting ps = mSettings.mPackages.get(packageName); 3306 return generatePackageInfo(ps, flags, userId); 3307 } 3308 } 3309 return null; 3310 } 3311 3312 @Override 3313 public String[] currentToCanonicalPackageNames(String[] names) { 3314 String[] out = new String[names.length]; 3315 // reader 3316 synchronized (mPackages) { 3317 for (int i=names.length-1; i>=0; i--) { 3318 PackageSetting ps = mSettings.mPackages.get(names[i]); 3319 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3320 } 3321 } 3322 return out; 3323 } 3324 3325 @Override 3326 public String[] canonicalToCurrentPackageNames(String[] names) { 3327 String[] out = new String[names.length]; 3328 // reader 3329 synchronized (mPackages) { 3330 for (int i=names.length-1; i>=0; i--) { 3331 String cur = mSettings.mRenamedPackages.get(names[i]); 3332 out[i] = cur != null ? cur : names[i]; 3333 } 3334 } 3335 return out; 3336 } 3337 3338 @Override 3339 public int getPackageUid(String packageName, int flags, int userId) { 3340 if (!sUserManager.exists(userId)) return -1; 3341 flags = updateFlagsForPackage(flags, userId, packageName); 3342 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3343 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3344 3345 // reader 3346 synchronized (mPackages) { 3347 final PackageParser.Package p = mPackages.get(packageName); 3348 if (p != null && p.isMatch(flags)) { 3349 return UserHandle.getUid(userId, p.applicationInfo.uid); 3350 } 3351 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3352 final PackageSetting ps = mSettings.mPackages.get(packageName); 3353 if (ps != null && ps.isMatch(flags)) { 3354 return UserHandle.getUid(userId, ps.appId); 3355 } 3356 } 3357 } 3358 3359 return -1; 3360 } 3361 3362 @Override 3363 public int[] getPackageGids(String packageName, int flags, int userId) { 3364 if (!sUserManager.exists(userId)) return null; 3365 flags = updateFlagsForPackage(flags, userId, packageName); 3366 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3367 false /* requireFullPermission */, false /* checkShell */, 3368 "getPackageGids"); 3369 3370 // reader 3371 synchronized (mPackages) { 3372 final PackageParser.Package p = mPackages.get(packageName); 3373 if (p != null && p.isMatch(flags)) { 3374 PackageSetting ps = (PackageSetting) p.mExtras; 3375 return ps.getPermissionsState().computeGids(userId); 3376 } 3377 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3378 final PackageSetting ps = mSettings.mPackages.get(packageName); 3379 if (ps != null && ps.isMatch(flags)) { 3380 return ps.getPermissionsState().computeGids(userId); 3381 } 3382 } 3383 } 3384 3385 return null; 3386 } 3387 3388 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3389 if (bp.perm != null) { 3390 return PackageParser.generatePermissionInfo(bp.perm, flags); 3391 } 3392 PermissionInfo pi = new PermissionInfo(); 3393 pi.name = bp.name; 3394 pi.packageName = bp.sourcePackage; 3395 pi.nonLocalizedLabel = bp.name; 3396 pi.protectionLevel = bp.protectionLevel; 3397 return pi; 3398 } 3399 3400 @Override 3401 public PermissionInfo getPermissionInfo(String name, int flags) { 3402 // reader 3403 synchronized (mPackages) { 3404 final BasePermission p = mSettings.mPermissions.get(name); 3405 if (p != null) { 3406 return generatePermissionInfo(p, flags); 3407 } 3408 return null; 3409 } 3410 } 3411 3412 @Override 3413 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3414 int flags) { 3415 // reader 3416 synchronized (mPackages) { 3417 if (group != null && !mPermissionGroups.containsKey(group)) { 3418 // This is thrown as NameNotFoundException 3419 return null; 3420 } 3421 3422 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3423 for (BasePermission p : mSettings.mPermissions.values()) { 3424 if (group == null) { 3425 if (p.perm == null || p.perm.info.group == null) { 3426 out.add(generatePermissionInfo(p, flags)); 3427 } 3428 } else { 3429 if (p.perm != null && group.equals(p.perm.info.group)) { 3430 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3431 } 3432 } 3433 } 3434 return new ParceledListSlice<>(out); 3435 } 3436 } 3437 3438 @Override 3439 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3440 // reader 3441 synchronized (mPackages) { 3442 return PackageParser.generatePermissionGroupInfo( 3443 mPermissionGroups.get(name), flags); 3444 } 3445 } 3446 3447 @Override 3448 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3449 // reader 3450 synchronized (mPackages) { 3451 final int N = mPermissionGroups.size(); 3452 ArrayList<PermissionGroupInfo> out 3453 = new ArrayList<PermissionGroupInfo>(N); 3454 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3455 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3456 } 3457 return new ParceledListSlice<>(out); 3458 } 3459 } 3460 3461 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3462 int userId) { 3463 if (!sUserManager.exists(userId)) return null; 3464 PackageSetting ps = mSettings.mPackages.get(packageName); 3465 if (ps != null) { 3466 if (ps.pkg == null) { 3467 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3468 if (pInfo != null) { 3469 return pInfo.applicationInfo; 3470 } 3471 return null; 3472 } 3473 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3474 ps.readUserState(userId), userId); 3475 } 3476 return null; 3477 } 3478 3479 @Override 3480 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3481 if (!sUserManager.exists(userId)) return null; 3482 flags = updateFlagsForApplication(flags, userId, packageName); 3483 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3484 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3485 // writer 3486 synchronized (mPackages) { 3487 PackageParser.Package p = mPackages.get(packageName); 3488 if (DEBUG_PACKAGE_INFO) Log.v( 3489 TAG, "getApplicationInfo " + packageName 3490 + ": " + p); 3491 if (p != null) { 3492 PackageSetting ps = mSettings.mPackages.get(packageName); 3493 if (ps == null) return null; 3494 // Note: isEnabledLP() does not apply here - always return info 3495 return PackageParser.generateApplicationInfo( 3496 p, flags, ps.readUserState(userId), userId); 3497 } 3498 if ("android".equals(packageName)||"system".equals(packageName)) { 3499 return mAndroidApplication; 3500 } 3501 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3502 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3503 } 3504 } 3505 return null; 3506 } 3507 3508 @Override 3509 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3510 final IPackageDataObserver observer) { 3511 mContext.enforceCallingOrSelfPermission( 3512 android.Manifest.permission.CLEAR_APP_CACHE, null); 3513 // Queue up an async operation since clearing cache may take a little while. 3514 mHandler.post(new Runnable() { 3515 public void run() { 3516 mHandler.removeCallbacks(this); 3517 boolean success = true; 3518 synchronized (mInstallLock) { 3519 try { 3520 mInstaller.freeCache(volumeUuid, freeStorageSize); 3521 } catch (InstallerException e) { 3522 Slog.w(TAG, "Couldn't clear application caches: " + e); 3523 success = false; 3524 } 3525 } 3526 if (observer != null) { 3527 try { 3528 observer.onRemoveCompleted(null, success); 3529 } catch (RemoteException e) { 3530 Slog.w(TAG, "RemoveException when invoking call back"); 3531 } 3532 } 3533 } 3534 }); 3535 } 3536 3537 @Override 3538 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3539 final IntentSender pi) { 3540 mContext.enforceCallingOrSelfPermission( 3541 android.Manifest.permission.CLEAR_APP_CACHE, null); 3542 // Queue up an async operation since clearing cache may take a little while. 3543 mHandler.post(new Runnable() { 3544 public void run() { 3545 mHandler.removeCallbacks(this); 3546 boolean success = true; 3547 synchronized (mInstallLock) { 3548 try { 3549 mInstaller.freeCache(volumeUuid, freeStorageSize); 3550 } catch (InstallerException e) { 3551 Slog.w(TAG, "Couldn't clear application caches: " + e); 3552 success = false; 3553 } 3554 } 3555 if(pi != null) { 3556 try { 3557 // Callback via pending intent 3558 int code = success ? 1 : 0; 3559 pi.sendIntent(null, code, null, 3560 null, null); 3561 } catch (SendIntentException e1) { 3562 Slog.i(TAG, "Failed to send pending intent"); 3563 } 3564 } 3565 } 3566 }); 3567 } 3568 3569 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3570 synchronized (mInstallLock) { 3571 try { 3572 mInstaller.freeCache(volumeUuid, freeStorageSize); 3573 } catch (InstallerException e) { 3574 throw new IOException("Failed to free enough space", e); 3575 } 3576 } 3577 } 3578 3579 /** 3580 * Update given flags based on encryption status of current user. 3581 */ 3582 private int updateFlags(int flags, int userId) { 3583 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3584 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3585 // Caller expressed an explicit opinion about what encryption 3586 // aware/unaware components they want to see, so fall through and 3587 // give them what they want 3588 } else { 3589 // Caller expressed no opinion, so match based on user state 3590 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3591 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3592 } else { 3593 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3594 } 3595 } 3596 return flags; 3597 } 3598 3599 private UserManagerInternal getUserManagerInternal() { 3600 if (mUserManagerInternal == null) { 3601 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3602 } 3603 return mUserManagerInternal; 3604 } 3605 3606 /** 3607 * Update given flags when being used to request {@link PackageInfo}. 3608 */ 3609 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3610 boolean triaged = true; 3611 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3612 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3613 // Caller is asking for component details, so they'd better be 3614 // asking for specific encryption matching behavior, or be triaged 3615 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3616 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3617 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3618 triaged = false; 3619 } 3620 } 3621 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3622 | PackageManager.MATCH_SYSTEM_ONLY 3623 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3624 triaged = false; 3625 } 3626 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3627 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3628 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3629 } 3630 return updateFlags(flags, userId); 3631 } 3632 3633 /** 3634 * Update given flags when being used to request {@link ApplicationInfo}. 3635 */ 3636 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3637 return updateFlagsForPackage(flags, userId, cookie); 3638 } 3639 3640 /** 3641 * Update given flags when being used to request {@link ComponentInfo}. 3642 */ 3643 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3644 if (cookie instanceof Intent) { 3645 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3646 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3647 } 3648 } 3649 3650 boolean triaged = true; 3651 // Caller is asking for component details, so they'd better be 3652 // asking for specific encryption matching behavior, or be triaged 3653 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3654 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3655 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3656 triaged = false; 3657 } 3658 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3659 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3660 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3661 } 3662 3663 return updateFlags(flags, userId); 3664 } 3665 3666 /** 3667 * Update given flags when being used to request {@link ResolveInfo}. 3668 */ 3669 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3670 // Safe mode means we shouldn't match any third-party components 3671 if (mSafeMode) { 3672 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3673 } 3674 3675 return updateFlagsForComponent(flags, userId, cookie); 3676 } 3677 3678 @Override 3679 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3680 if (!sUserManager.exists(userId)) return null; 3681 flags = updateFlagsForComponent(flags, userId, component); 3682 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3683 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3684 synchronized (mPackages) { 3685 PackageParser.Activity a = mActivities.mActivities.get(component); 3686 3687 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3688 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3689 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3690 if (ps == null) return null; 3691 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3692 userId); 3693 } 3694 if (mResolveComponentName.equals(component)) { 3695 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3696 new PackageUserState(), userId); 3697 } 3698 } 3699 return null; 3700 } 3701 3702 @Override 3703 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3704 String resolvedType) { 3705 synchronized (mPackages) { 3706 if (component.equals(mResolveComponentName)) { 3707 // The resolver supports EVERYTHING! 3708 return true; 3709 } 3710 PackageParser.Activity a = mActivities.mActivities.get(component); 3711 if (a == null) { 3712 return false; 3713 } 3714 for (int i=0; i<a.intents.size(); i++) { 3715 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3716 intent.getData(), intent.getCategories(), TAG) >= 0) { 3717 return true; 3718 } 3719 } 3720 return false; 3721 } 3722 } 3723 3724 @Override 3725 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3726 if (!sUserManager.exists(userId)) return null; 3727 flags = updateFlagsForComponent(flags, userId, component); 3728 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3729 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3730 synchronized (mPackages) { 3731 PackageParser.Activity a = mReceivers.mActivities.get(component); 3732 if (DEBUG_PACKAGE_INFO) Log.v( 3733 TAG, "getReceiverInfo " + component + ": " + a); 3734 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3735 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3736 if (ps == null) return null; 3737 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3738 userId); 3739 } 3740 } 3741 return null; 3742 } 3743 3744 @Override 3745 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3746 if (!sUserManager.exists(userId)) return null; 3747 flags = updateFlagsForComponent(flags, userId, component); 3748 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3749 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3750 synchronized (mPackages) { 3751 PackageParser.Service s = mServices.mServices.get(component); 3752 if (DEBUG_PACKAGE_INFO) Log.v( 3753 TAG, "getServiceInfo " + component + ": " + s); 3754 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3755 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3756 if (ps == null) return null; 3757 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3758 userId); 3759 } 3760 } 3761 return null; 3762 } 3763 3764 @Override 3765 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3766 if (!sUserManager.exists(userId)) return null; 3767 flags = updateFlagsForComponent(flags, userId, component); 3768 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3769 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3770 synchronized (mPackages) { 3771 PackageParser.Provider p = mProviders.mProviders.get(component); 3772 if (DEBUG_PACKAGE_INFO) Log.v( 3773 TAG, "getProviderInfo " + component + ": " + p); 3774 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3775 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3776 if (ps == null) return null; 3777 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3778 userId); 3779 } 3780 } 3781 return null; 3782 } 3783 3784 @Override 3785 public String[] getSystemSharedLibraryNames() { 3786 Set<String> libSet; 3787 synchronized (mPackages) { 3788 libSet = mSharedLibraries.keySet(); 3789 int size = libSet.size(); 3790 if (size > 0) { 3791 String[] libs = new String[size]; 3792 libSet.toArray(libs); 3793 return libs; 3794 } 3795 } 3796 return null; 3797 } 3798 3799 @Override 3800 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3801 synchronized (mPackages) { 3802 return mServicesSystemSharedLibraryPackageName; 3803 } 3804 } 3805 3806 @Override 3807 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3808 synchronized (mPackages) { 3809 return mSharedSystemSharedLibraryPackageName; 3810 } 3811 } 3812 3813 @Override 3814 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3815 synchronized (mPackages) { 3816 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3817 3818 final FeatureInfo fi = new FeatureInfo(); 3819 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3820 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3821 res.add(fi); 3822 3823 return new ParceledListSlice<>(res); 3824 } 3825 } 3826 3827 @Override 3828 public boolean hasSystemFeature(String name, int version) { 3829 synchronized (mPackages) { 3830 final FeatureInfo feat = mAvailableFeatures.get(name); 3831 if (feat == null) { 3832 return false; 3833 } else { 3834 return feat.version >= version; 3835 } 3836 } 3837 } 3838 3839 @Override 3840 public int checkPermission(String permName, String pkgName, int userId) { 3841 if (!sUserManager.exists(userId)) { 3842 return PackageManager.PERMISSION_DENIED; 3843 } 3844 3845 synchronized (mPackages) { 3846 final PackageParser.Package p = mPackages.get(pkgName); 3847 if (p != null && p.mExtras != null) { 3848 final PackageSetting ps = (PackageSetting) p.mExtras; 3849 final PermissionsState permissionsState = ps.getPermissionsState(); 3850 if (permissionsState.hasPermission(permName, userId)) { 3851 return PackageManager.PERMISSION_GRANTED; 3852 } 3853 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3854 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3855 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3856 return PackageManager.PERMISSION_GRANTED; 3857 } 3858 } 3859 } 3860 3861 return PackageManager.PERMISSION_DENIED; 3862 } 3863 3864 @Override 3865 public int checkUidPermission(String permName, int uid) { 3866 final int userId = UserHandle.getUserId(uid); 3867 3868 if (!sUserManager.exists(userId)) { 3869 return PackageManager.PERMISSION_DENIED; 3870 } 3871 3872 synchronized (mPackages) { 3873 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3874 if (obj != null) { 3875 final SettingBase ps = (SettingBase) obj; 3876 final PermissionsState permissionsState = ps.getPermissionsState(); 3877 if (permissionsState.hasPermission(permName, userId)) { 3878 return PackageManager.PERMISSION_GRANTED; 3879 } 3880 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3881 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3882 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3883 return PackageManager.PERMISSION_GRANTED; 3884 } 3885 } else { 3886 ArraySet<String> perms = mSystemPermissions.get(uid); 3887 if (perms != null) { 3888 if (perms.contains(permName)) { 3889 return PackageManager.PERMISSION_GRANTED; 3890 } 3891 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3892 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3893 return PackageManager.PERMISSION_GRANTED; 3894 } 3895 } 3896 } 3897 } 3898 3899 return PackageManager.PERMISSION_DENIED; 3900 } 3901 3902 @Override 3903 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3904 if (UserHandle.getCallingUserId() != userId) { 3905 mContext.enforceCallingPermission( 3906 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3907 "isPermissionRevokedByPolicy for user " + userId); 3908 } 3909 3910 if (checkPermission(permission, packageName, userId) 3911 == PackageManager.PERMISSION_GRANTED) { 3912 return false; 3913 } 3914 3915 final long identity = Binder.clearCallingIdentity(); 3916 try { 3917 final int flags = getPermissionFlags(permission, packageName, userId); 3918 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3919 } finally { 3920 Binder.restoreCallingIdentity(identity); 3921 } 3922 } 3923 3924 @Override 3925 public String getPermissionControllerPackageName() { 3926 synchronized (mPackages) { 3927 return mRequiredInstallerPackage; 3928 } 3929 } 3930 3931 /** 3932 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3933 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3934 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3935 * @param message the message to log on security exception 3936 */ 3937 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3938 boolean checkShell, String message) { 3939 if (userId < 0) { 3940 throw new IllegalArgumentException("Invalid userId " + userId); 3941 } 3942 if (checkShell) { 3943 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3944 } 3945 if (userId == UserHandle.getUserId(callingUid)) return; 3946 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3947 if (requireFullPermission) { 3948 mContext.enforceCallingOrSelfPermission( 3949 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3950 } else { 3951 try { 3952 mContext.enforceCallingOrSelfPermission( 3953 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3954 } catch (SecurityException se) { 3955 mContext.enforceCallingOrSelfPermission( 3956 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3957 } 3958 } 3959 } 3960 } 3961 3962 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3963 if (callingUid == Process.SHELL_UID) { 3964 if (userHandle >= 0 3965 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3966 throw new SecurityException("Shell does not have permission to access user " 3967 + userHandle); 3968 } else if (userHandle < 0) { 3969 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3970 + Debug.getCallers(3)); 3971 } 3972 } 3973 } 3974 3975 private BasePermission findPermissionTreeLP(String permName) { 3976 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3977 if (permName.startsWith(bp.name) && 3978 permName.length() > bp.name.length() && 3979 permName.charAt(bp.name.length()) == '.') { 3980 return bp; 3981 } 3982 } 3983 return null; 3984 } 3985 3986 private BasePermission checkPermissionTreeLP(String permName) { 3987 if (permName != null) { 3988 BasePermission bp = findPermissionTreeLP(permName); 3989 if (bp != null) { 3990 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3991 return bp; 3992 } 3993 throw new SecurityException("Calling uid " 3994 + Binder.getCallingUid() 3995 + " is not allowed to add to permission tree " 3996 + bp.name + " owned by uid " + bp.uid); 3997 } 3998 } 3999 throw new SecurityException("No permission tree found for " + permName); 4000 } 4001 4002 static boolean compareStrings(CharSequence s1, CharSequence s2) { 4003 if (s1 == null) { 4004 return s2 == null; 4005 } 4006 if (s2 == null) { 4007 return false; 4008 } 4009 if (s1.getClass() != s2.getClass()) { 4010 return false; 4011 } 4012 return s1.equals(s2); 4013 } 4014 4015 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4016 if (pi1.icon != pi2.icon) return false; 4017 if (pi1.logo != pi2.logo) return false; 4018 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4019 if (!compareStrings(pi1.name, pi2.name)) return false; 4020 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4021 // We'll take care of setting this one. 4022 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4023 // These are not currently stored in settings. 4024 //if (!compareStrings(pi1.group, pi2.group)) return false; 4025 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4026 //if (pi1.labelRes != pi2.labelRes) return false; 4027 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4028 return true; 4029 } 4030 4031 int permissionInfoFootprint(PermissionInfo info) { 4032 int size = info.name.length(); 4033 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4034 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4035 return size; 4036 } 4037 4038 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4039 int size = 0; 4040 for (BasePermission perm : mSettings.mPermissions.values()) { 4041 if (perm.uid == tree.uid) { 4042 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4043 } 4044 } 4045 return size; 4046 } 4047 4048 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4049 // We calculate the max size of permissions defined by this uid and throw 4050 // if that plus the size of 'info' would exceed our stated maximum. 4051 if (tree.uid != Process.SYSTEM_UID) { 4052 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4053 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4054 throw new SecurityException("Permission tree size cap exceeded"); 4055 } 4056 } 4057 } 4058 4059 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4060 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4061 throw new SecurityException("Label must be specified in permission"); 4062 } 4063 BasePermission tree = checkPermissionTreeLP(info.name); 4064 BasePermission bp = mSettings.mPermissions.get(info.name); 4065 boolean added = bp == null; 4066 boolean changed = true; 4067 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4068 if (added) { 4069 enforcePermissionCapLocked(info, tree); 4070 bp = new BasePermission(info.name, tree.sourcePackage, 4071 BasePermission.TYPE_DYNAMIC); 4072 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4073 throw new SecurityException( 4074 "Not allowed to modify non-dynamic permission " 4075 + info.name); 4076 } else { 4077 if (bp.protectionLevel == fixedLevel 4078 && bp.perm.owner.equals(tree.perm.owner) 4079 && bp.uid == tree.uid 4080 && comparePermissionInfos(bp.perm.info, info)) { 4081 changed = false; 4082 } 4083 } 4084 bp.protectionLevel = fixedLevel; 4085 info = new PermissionInfo(info); 4086 info.protectionLevel = fixedLevel; 4087 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4088 bp.perm.info.packageName = tree.perm.info.packageName; 4089 bp.uid = tree.uid; 4090 if (added) { 4091 mSettings.mPermissions.put(info.name, bp); 4092 } 4093 if (changed) { 4094 if (!async) { 4095 mSettings.writeLPr(); 4096 } else { 4097 scheduleWriteSettingsLocked(); 4098 } 4099 } 4100 return added; 4101 } 4102 4103 @Override 4104 public boolean addPermission(PermissionInfo info) { 4105 synchronized (mPackages) { 4106 return addPermissionLocked(info, false); 4107 } 4108 } 4109 4110 @Override 4111 public boolean addPermissionAsync(PermissionInfo info) { 4112 synchronized (mPackages) { 4113 return addPermissionLocked(info, true); 4114 } 4115 } 4116 4117 @Override 4118 public void removePermission(String name) { 4119 synchronized (mPackages) { 4120 checkPermissionTreeLP(name); 4121 BasePermission bp = mSettings.mPermissions.get(name); 4122 if (bp != null) { 4123 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4124 throw new SecurityException( 4125 "Not allowed to modify non-dynamic permission " 4126 + name); 4127 } 4128 mSettings.mPermissions.remove(name); 4129 mSettings.writeLPr(); 4130 } 4131 } 4132 } 4133 4134 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4135 BasePermission bp) { 4136 int index = pkg.requestedPermissions.indexOf(bp.name); 4137 if (index == -1) { 4138 throw new SecurityException("Package " + pkg.packageName 4139 + " has not requested permission " + bp.name); 4140 } 4141 if (!bp.isRuntime() && !bp.isDevelopment()) { 4142 throw new SecurityException("Permission " + bp.name 4143 + " is not a changeable permission type"); 4144 } 4145 } 4146 4147 @Override 4148 public void grantRuntimePermission(String packageName, String name, final int userId) { 4149 if (!sUserManager.exists(userId)) { 4150 Log.e(TAG, "No such user:" + userId); 4151 return; 4152 } 4153 4154 mContext.enforceCallingOrSelfPermission( 4155 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4156 "grantRuntimePermission"); 4157 4158 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4159 true /* requireFullPermission */, true /* checkShell */, 4160 "grantRuntimePermission"); 4161 4162 final int uid; 4163 final SettingBase sb; 4164 4165 synchronized (mPackages) { 4166 final PackageParser.Package pkg = mPackages.get(packageName); 4167 if (pkg == null) { 4168 throw new IllegalArgumentException("Unknown package: " + packageName); 4169 } 4170 4171 final BasePermission bp = mSettings.mPermissions.get(name); 4172 if (bp == null) { 4173 throw new IllegalArgumentException("Unknown permission: " + name); 4174 } 4175 4176 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4177 4178 // If a permission review is required for legacy apps we represent 4179 // their permissions as always granted runtime ones since we need 4180 // to keep the review required permission flag per user while an 4181 // install permission's state is shared across all users. 4182 if (Build.PERMISSIONS_REVIEW_REQUIRED 4183 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4184 && bp.isRuntime()) { 4185 return; 4186 } 4187 4188 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4189 sb = (SettingBase) pkg.mExtras; 4190 if (sb == null) { 4191 throw new IllegalArgumentException("Unknown package: " + packageName); 4192 } 4193 4194 final PermissionsState permissionsState = sb.getPermissionsState(); 4195 4196 final int flags = permissionsState.getPermissionFlags(name, userId); 4197 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4198 throw new SecurityException("Cannot grant system fixed permission " 4199 + name + " for package " + packageName); 4200 } 4201 4202 if (bp.isDevelopment()) { 4203 // Development permissions must be handled specially, since they are not 4204 // normal runtime permissions. For now they apply to all users. 4205 if (permissionsState.grantInstallPermission(bp) != 4206 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4207 scheduleWriteSettingsLocked(); 4208 } 4209 return; 4210 } 4211 4212 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4213 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4214 return; 4215 } 4216 4217 final int result = permissionsState.grantRuntimePermission(bp, userId); 4218 switch (result) { 4219 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4220 return; 4221 } 4222 4223 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4224 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4225 mHandler.post(new Runnable() { 4226 @Override 4227 public void run() { 4228 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4229 } 4230 }); 4231 } 4232 break; 4233 } 4234 4235 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4236 4237 // Not critical if that is lost - app has to request again. 4238 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4239 } 4240 4241 // Only need to do this if user is initialized. Otherwise it's a new user 4242 // and there are no processes running as the user yet and there's no need 4243 // to make an expensive call to remount processes for the changed permissions. 4244 if (READ_EXTERNAL_STORAGE.equals(name) 4245 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4246 final long token = Binder.clearCallingIdentity(); 4247 try { 4248 if (sUserManager.isInitialized(userId)) { 4249 MountServiceInternal mountServiceInternal = LocalServices.getService( 4250 MountServiceInternal.class); 4251 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4252 } 4253 } finally { 4254 Binder.restoreCallingIdentity(token); 4255 } 4256 } 4257 } 4258 4259 @Override 4260 public void revokeRuntimePermission(String packageName, String name, int userId) { 4261 if (!sUserManager.exists(userId)) { 4262 Log.e(TAG, "No such user:" + userId); 4263 return; 4264 } 4265 4266 mContext.enforceCallingOrSelfPermission( 4267 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4268 "revokeRuntimePermission"); 4269 4270 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4271 true /* requireFullPermission */, true /* checkShell */, 4272 "revokeRuntimePermission"); 4273 4274 final int appId; 4275 4276 synchronized (mPackages) { 4277 final PackageParser.Package pkg = mPackages.get(packageName); 4278 if (pkg == null) { 4279 throw new IllegalArgumentException("Unknown package: " + packageName); 4280 } 4281 4282 final BasePermission bp = mSettings.mPermissions.get(name); 4283 if (bp == null) { 4284 throw new IllegalArgumentException("Unknown permission: " + name); 4285 } 4286 4287 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4288 4289 // If a permission review is required for legacy apps we represent 4290 // their permissions as always granted runtime ones since we need 4291 // to keep the review required permission flag per user while an 4292 // install permission's state is shared across all users. 4293 if (Build.PERMISSIONS_REVIEW_REQUIRED 4294 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4295 && bp.isRuntime()) { 4296 return; 4297 } 4298 4299 SettingBase sb = (SettingBase) pkg.mExtras; 4300 if (sb == null) { 4301 throw new IllegalArgumentException("Unknown package: " + packageName); 4302 } 4303 4304 final PermissionsState permissionsState = sb.getPermissionsState(); 4305 4306 final int flags = permissionsState.getPermissionFlags(name, userId); 4307 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4308 throw new SecurityException("Cannot revoke system fixed permission " 4309 + name + " for package " + packageName); 4310 } 4311 4312 if (bp.isDevelopment()) { 4313 // Development permissions must be handled specially, since they are not 4314 // normal runtime permissions. For now they apply to all users. 4315 if (permissionsState.revokeInstallPermission(bp) != 4316 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4317 scheduleWriteSettingsLocked(); 4318 } 4319 return; 4320 } 4321 4322 if (permissionsState.revokeRuntimePermission(bp, userId) == 4323 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4324 return; 4325 } 4326 4327 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4328 4329 // Critical, after this call app should never have the permission. 4330 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4331 4332 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4333 } 4334 4335 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4336 } 4337 4338 @Override 4339 public void resetRuntimePermissions() { 4340 mContext.enforceCallingOrSelfPermission( 4341 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4342 "revokeRuntimePermission"); 4343 4344 int callingUid = Binder.getCallingUid(); 4345 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4346 mContext.enforceCallingOrSelfPermission( 4347 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4348 "resetRuntimePermissions"); 4349 } 4350 4351 synchronized (mPackages) { 4352 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4353 for (int userId : UserManagerService.getInstance().getUserIds()) { 4354 final int packageCount = mPackages.size(); 4355 for (int i = 0; i < packageCount; i++) { 4356 PackageParser.Package pkg = mPackages.valueAt(i); 4357 if (!(pkg.mExtras instanceof PackageSetting)) { 4358 continue; 4359 } 4360 PackageSetting ps = (PackageSetting) pkg.mExtras; 4361 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4362 } 4363 } 4364 } 4365 } 4366 4367 @Override 4368 public int getPermissionFlags(String name, String packageName, int userId) { 4369 if (!sUserManager.exists(userId)) { 4370 return 0; 4371 } 4372 4373 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4374 4375 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4376 true /* requireFullPermission */, false /* checkShell */, 4377 "getPermissionFlags"); 4378 4379 synchronized (mPackages) { 4380 final PackageParser.Package pkg = mPackages.get(packageName); 4381 if (pkg == null) { 4382 return 0; 4383 } 4384 4385 final BasePermission bp = mSettings.mPermissions.get(name); 4386 if (bp == null) { 4387 return 0; 4388 } 4389 4390 SettingBase sb = (SettingBase) pkg.mExtras; 4391 if (sb == null) { 4392 return 0; 4393 } 4394 4395 PermissionsState permissionsState = sb.getPermissionsState(); 4396 return permissionsState.getPermissionFlags(name, userId); 4397 } 4398 } 4399 4400 @Override 4401 public void updatePermissionFlags(String name, String packageName, int flagMask, 4402 int flagValues, int userId) { 4403 if (!sUserManager.exists(userId)) { 4404 return; 4405 } 4406 4407 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4408 4409 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4410 true /* requireFullPermission */, true /* checkShell */, 4411 "updatePermissionFlags"); 4412 4413 // Only the system can change these flags and nothing else. 4414 if (getCallingUid() != Process.SYSTEM_UID) { 4415 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4416 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4417 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4418 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4419 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4420 } 4421 4422 synchronized (mPackages) { 4423 final PackageParser.Package pkg = mPackages.get(packageName); 4424 if (pkg == null) { 4425 throw new IllegalArgumentException("Unknown package: " + packageName); 4426 } 4427 4428 final BasePermission bp = mSettings.mPermissions.get(name); 4429 if (bp == null) { 4430 throw new IllegalArgumentException("Unknown permission: " + name); 4431 } 4432 4433 SettingBase sb = (SettingBase) pkg.mExtras; 4434 if (sb == null) { 4435 throw new IllegalArgumentException("Unknown package: " + packageName); 4436 } 4437 4438 PermissionsState permissionsState = sb.getPermissionsState(); 4439 4440 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4441 4442 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4443 // Install and runtime permissions are stored in different places, 4444 // so figure out what permission changed and persist the change. 4445 if (permissionsState.getInstallPermissionState(name) != null) { 4446 scheduleWriteSettingsLocked(); 4447 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4448 || hadState) { 4449 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4450 } 4451 } 4452 } 4453 } 4454 4455 /** 4456 * Update the permission flags for all packages and runtime permissions of a user in order 4457 * to allow device or profile owner to remove POLICY_FIXED. 4458 */ 4459 @Override 4460 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4461 if (!sUserManager.exists(userId)) { 4462 return; 4463 } 4464 4465 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4466 4467 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4468 true /* requireFullPermission */, true /* checkShell */, 4469 "updatePermissionFlagsForAllApps"); 4470 4471 // Only the system can change system fixed flags. 4472 if (getCallingUid() != Process.SYSTEM_UID) { 4473 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4474 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4475 } 4476 4477 synchronized (mPackages) { 4478 boolean changed = false; 4479 final int packageCount = mPackages.size(); 4480 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4481 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4482 SettingBase sb = (SettingBase) pkg.mExtras; 4483 if (sb == null) { 4484 continue; 4485 } 4486 PermissionsState permissionsState = sb.getPermissionsState(); 4487 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4488 userId, flagMask, flagValues); 4489 } 4490 if (changed) { 4491 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4492 } 4493 } 4494 } 4495 4496 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4497 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4498 != PackageManager.PERMISSION_GRANTED 4499 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4500 != PackageManager.PERMISSION_GRANTED) { 4501 throw new SecurityException(message + " requires " 4502 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4503 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4504 } 4505 } 4506 4507 @Override 4508 public boolean shouldShowRequestPermissionRationale(String permissionName, 4509 String packageName, int userId) { 4510 if (UserHandle.getCallingUserId() != userId) { 4511 mContext.enforceCallingPermission( 4512 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4513 "canShowRequestPermissionRationale for user " + userId); 4514 } 4515 4516 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4517 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4518 return false; 4519 } 4520 4521 if (checkPermission(permissionName, packageName, userId) 4522 == PackageManager.PERMISSION_GRANTED) { 4523 return false; 4524 } 4525 4526 final int flags; 4527 4528 final long identity = Binder.clearCallingIdentity(); 4529 try { 4530 flags = getPermissionFlags(permissionName, 4531 packageName, userId); 4532 } finally { 4533 Binder.restoreCallingIdentity(identity); 4534 } 4535 4536 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4537 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4538 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4539 4540 if ((flags & fixedFlags) != 0) { 4541 return false; 4542 } 4543 4544 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4545 } 4546 4547 @Override 4548 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4549 mContext.enforceCallingOrSelfPermission( 4550 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4551 "addOnPermissionsChangeListener"); 4552 4553 synchronized (mPackages) { 4554 mOnPermissionChangeListeners.addListenerLocked(listener); 4555 } 4556 } 4557 4558 @Override 4559 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4560 synchronized (mPackages) { 4561 mOnPermissionChangeListeners.removeListenerLocked(listener); 4562 } 4563 } 4564 4565 @Override 4566 public boolean isProtectedBroadcast(String actionName) { 4567 synchronized (mPackages) { 4568 if (mProtectedBroadcasts.contains(actionName)) { 4569 return true; 4570 } else if (actionName != null) { 4571 // TODO: remove these terrible hacks 4572 if (actionName.startsWith("android.net.netmon.lingerExpired") 4573 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4574 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4575 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4576 return true; 4577 } 4578 } 4579 } 4580 return false; 4581 } 4582 4583 @Override 4584 public int checkSignatures(String pkg1, String pkg2) { 4585 synchronized (mPackages) { 4586 final PackageParser.Package p1 = mPackages.get(pkg1); 4587 final PackageParser.Package p2 = mPackages.get(pkg2); 4588 if (p1 == null || p1.mExtras == null 4589 || p2 == null || p2.mExtras == null) { 4590 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4591 } 4592 return compareSignatures(p1.mSignatures, p2.mSignatures); 4593 } 4594 } 4595 4596 @Override 4597 public int checkUidSignatures(int uid1, int uid2) { 4598 // Map to base uids. 4599 uid1 = UserHandle.getAppId(uid1); 4600 uid2 = UserHandle.getAppId(uid2); 4601 // reader 4602 synchronized (mPackages) { 4603 Signature[] s1; 4604 Signature[] s2; 4605 Object obj = mSettings.getUserIdLPr(uid1); 4606 if (obj != null) { 4607 if (obj instanceof SharedUserSetting) { 4608 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4609 } else if (obj instanceof PackageSetting) { 4610 s1 = ((PackageSetting)obj).signatures.mSignatures; 4611 } else { 4612 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4613 } 4614 } else { 4615 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4616 } 4617 obj = mSettings.getUserIdLPr(uid2); 4618 if (obj != null) { 4619 if (obj instanceof SharedUserSetting) { 4620 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4621 } else if (obj instanceof PackageSetting) { 4622 s2 = ((PackageSetting)obj).signatures.mSignatures; 4623 } else { 4624 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4625 } 4626 } else { 4627 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4628 } 4629 return compareSignatures(s1, s2); 4630 } 4631 } 4632 4633 /** 4634 * This method should typically only be used when granting or revoking 4635 * permissions, since the app may immediately restart after this call. 4636 * <p> 4637 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4638 * guard your work against the app being relaunched. 4639 */ 4640 private void killUid(int appId, int userId, String reason) { 4641 final long identity = Binder.clearCallingIdentity(); 4642 try { 4643 IActivityManager am = ActivityManagerNative.getDefault(); 4644 if (am != null) { 4645 try { 4646 am.killUid(appId, userId, reason); 4647 } catch (RemoteException e) { 4648 /* ignore - same process */ 4649 } 4650 } 4651 } finally { 4652 Binder.restoreCallingIdentity(identity); 4653 } 4654 } 4655 4656 /** 4657 * Compares two sets of signatures. Returns: 4658 * <br /> 4659 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4660 * <br /> 4661 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4662 * <br /> 4663 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4664 * <br /> 4665 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4666 * <br /> 4667 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4668 */ 4669 static int compareSignatures(Signature[] s1, Signature[] s2) { 4670 if (s1 == null) { 4671 return s2 == null 4672 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4673 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4674 } 4675 4676 if (s2 == null) { 4677 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4678 } 4679 4680 if (s1.length != s2.length) { 4681 return PackageManager.SIGNATURE_NO_MATCH; 4682 } 4683 4684 // Since both signature sets are of size 1, we can compare without HashSets. 4685 if (s1.length == 1) { 4686 return s1[0].equals(s2[0]) ? 4687 PackageManager.SIGNATURE_MATCH : 4688 PackageManager.SIGNATURE_NO_MATCH; 4689 } 4690 4691 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4692 for (Signature sig : s1) { 4693 set1.add(sig); 4694 } 4695 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4696 for (Signature sig : s2) { 4697 set2.add(sig); 4698 } 4699 // Make sure s2 contains all signatures in s1. 4700 if (set1.equals(set2)) { 4701 return PackageManager.SIGNATURE_MATCH; 4702 } 4703 return PackageManager.SIGNATURE_NO_MATCH; 4704 } 4705 4706 /** 4707 * If the database version for this type of package (internal storage or 4708 * external storage) is less than the version where package signatures 4709 * were updated, return true. 4710 */ 4711 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4712 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4713 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4714 } 4715 4716 /** 4717 * Used for backward compatibility to make sure any packages with 4718 * certificate chains get upgraded to the new style. {@code existingSigs} 4719 * will be in the old format (since they were stored on disk from before the 4720 * system upgrade) and {@code scannedSigs} will be in the newer format. 4721 */ 4722 private int compareSignaturesCompat(PackageSignatures existingSigs, 4723 PackageParser.Package scannedPkg) { 4724 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4725 return PackageManager.SIGNATURE_NO_MATCH; 4726 } 4727 4728 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4729 for (Signature sig : existingSigs.mSignatures) { 4730 existingSet.add(sig); 4731 } 4732 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4733 for (Signature sig : scannedPkg.mSignatures) { 4734 try { 4735 Signature[] chainSignatures = sig.getChainSignatures(); 4736 for (Signature chainSig : chainSignatures) { 4737 scannedCompatSet.add(chainSig); 4738 } 4739 } catch (CertificateEncodingException e) { 4740 scannedCompatSet.add(sig); 4741 } 4742 } 4743 /* 4744 * Make sure the expanded scanned set contains all signatures in the 4745 * existing one. 4746 */ 4747 if (scannedCompatSet.equals(existingSet)) { 4748 // Migrate the old signatures to the new scheme. 4749 existingSigs.assignSignatures(scannedPkg.mSignatures); 4750 // The new KeySets will be re-added later in the scanning process. 4751 synchronized (mPackages) { 4752 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4753 } 4754 return PackageManager.SIGNATURE_MATCH; 4755 } 4756 return PackageManager.SIGNATURE_NO_MATCH; 4757 } 4758 4759 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4760 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4761 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4762 } 4763 4764 private int compareSignaturesRecover(PackageSignatures existingSigs, 4765 PackageParser.Package scannedPkg) { 4766 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4767 return PackageManager.SIGNATURE_NO_MATCH; 4768 } 4769 4770 String msg = null; 4771 try { 4772 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4773 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4774 + scannedPkg.packageName); 4775 return PackageManager.SIGNATURE_MATCH; 4776 } 4777 } catch (CertificateException e) { 4778 msg = e.getMessage(); 4779 } 4780 4781 logCriticalInfo(Log.INFO, 4782 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4783 return PackageManager.SIGNATURE_NO_MATCH; 4784 } 4785 4786 @Override 4787 public List<String> getAllPackages() { 4788 synchronized (mPackages) { 4789 return new ArrayList<String>(mPackages.keySet()); 4790 } 4791 } 4792 4793 @Override 4794 public String[] getPackagesForUid(int uid) { 4795 uid = UserHandle.getAppId(uid); 4796 // reader 4797 synchronized (mPackages) { 4798 Object obj = mSettings.getUserIdLPr(uid); 4799 if (obj instanceof SharedUserSetting) { 4800 final SharedUserSetting sus = (SharedUserSetting) obj; 4801 final int N = sus.packages.size(); 4802 final String[] res = new String[N]; 4803 for (int i = 0; i < N; i++) { 4804 res[i] = sus.packages.valueAt(i).name; 4805 } 4806 return res; 4807 } else if (obj instanceof PackageSetting) { 4808 final PackageSetting ps = (PackageSetting) obj; 4809 return new String[] { ps.name }; 4810 } 4811 } 4812 return null; 4813 } 4814 4815 @Override 4816 public String getNameForUid(int uid) { 4817 // reader 4818 synchronized (mPackages) { 4819 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4820 if (obj instanceof SharedUserSetting) { 4821 final SharedUserSetting sus = (SharedUserSetting) obj; 4822 return sus.name + ":" + sus.userId; 4823 } else if (obj instanceof PackageSetting) { 4824 final PackageSetting ps = (PackageSetting) obj; 4825 return ps.name; 4826 } 4827 } 4828 return null; 4829 } 4830 4831 @Override 4832 public int getUidForSharedUser(String sharedUserName) { 4833 if(sharedUserName == null) { 4834 return -1; 4835 } 4836 // reader 4837 synchronized (mPackages) { 4838 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4839 if (suid == null) { 4840 return -1; 4841 } 4842 return suid.userId; 4843 } 4844 } 4845 4846 @Override 4847 public int getFlagsForUid(int uid) { 4848 synchronized (mPackages) { 4849 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4850 if (obj instanceof SharedUserSetting) { 4851 final SharedUserSetting sus = (SharedUserSetting) obj; 4852 return sus.pkgFlags; 4853 } else if (obj instanceof PackageSetting) { 4854 final PackageSetting ps = (PackageSetting) obj; 4855 return ps.pkgFlags; 4856 } 4857 } 4858 return 0; 4859 } 4860 4861 @Override 4862 public int getPrivateFlagsForUid(int uid) { 4863 synchronized (mPackages) { 4864 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4865 if (obj instanceof SharedUserSetting) { 4866 final SharedUserSetting sus = (SharedUserSetting) obj; 4867 return sus.pkgPrivateFlags; 4868 } else if (obj instanceof PackageSetting) { 4869 final PackageSetting ps = (PackageSetting) obj; 4870 return ps.pkgPrivateFlags; 4871 } 4872 } 4873 return 0; 4874 } 4875 4876 @Override 4877 public boolean isUidPrivileged(int uid) { 4878 uid = UserHandle.getAppId(uid); 4879 // reader 4880 synchronized (mPackages) { 4881 Object obj = mSettings.getUserIdLPr(uid); 4882 if (obj instanceof SharedUserSetting) { 4883 final SharedUserSetting sus = (SharedUserSetting) obj; 4884 final Iterator<PackageSetting> it = sus.packages.iterator(); 4885 while (it.hasNext()) { 4886 if (it.next().isPrivileged()) { 4887 return true; 4888 } 4889 } 4890 } else if (obj instanceof PackageSetting) { 4891 final PackageSetting ps = (PackageSetting) obj; 4892 return ps.isPrivileged(); 4893 } 4894 } 4895 return false; 4896 } 4897 4898 @Override 4899 public String[] getAppOpPermissionPackages(String permissionName) { 4900 synchronized (mPackages) { 4901 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4902 if (pkgs == null) { 4903 return null; 4904 } 4905 return pkgs.toArray(new String[pkgs.size()]); 4906 } 4907 } 4908 4909 @Override 4910 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4911 int flags, int userId) { 4912 try { 4913 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4914 4915 if (!sUserManager.exists(userId)) return null; 4916 flags = updateFlagsForResolve(flags, userId, intent); 4917 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4918 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4919 4920 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4921 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4922 flags, userId); 4923 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4924 4925 final ResolveInfo bestChoice = 4926 chooseBestActivity(intent, resolvedType, flags, query, userId); 4927 4928 if (isEphemeralAllowed(intent, query, userId)) { 4929 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4930 final EphemeralResolveInfo ai = 4931 getEphemeralResolveInfo(intent, resolvedType, userId); 4932 if (ai != null) { 4933 if (DEBUG_EPHEMERAL) { 4934 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4935 } 4936 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4937 bestChoice.ephemeralResolveInfo = ai; 4938 } 4939 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4940 } 4941 return bestChoice; 4942 } finally { 4943 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4944 } 4945 } 4946 4947 @Override 4948 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4949 IntentFilter filter, int match, ComponentName activity) { 4950 final int userId = UserHandle.getCallingUserId(); 4951 if (DEBUG_PREFERRED) { 4952 Log.v(TAG, "setLastChosenActivity intent=" + intent 4953 + " resolvedType=" + resolvedType 4954 + " flags=" + flags 4955 + " filter=" + filter 4956 + " match=" + match 4957 + " activity=" + activity); 4958 filter.dump(new PrintStreamPrinter(System.out), " "); 4959 } 4960 intent.setComponent(null); 4961 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4962 userId); 4963 // Find any earlier preferred or last chosen entries and nuke them 4964 findPreferredActivity(intent, resolvedType, 4965 flags, query, 0, false, true, false, userId); 4966 // Add the new activity as the last chosen for this filter 4967 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4968 "Setting last chosen"); 4969 } 4970 4971 @Override 4972 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4973 final int userId = UserHandle.getCallingUserId(); 4974 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4975 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4976 userId); 4977 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4978 false, false, false, userId); 4979 } 4980 4981 4982 private boolean isEphemeralAllowed( 4983 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4984 // Short circuit and return early if possible. 4985 if (DISABLE_EPHEMERAL_APPS) { 4986 return false; 4987 } 4988 final int callingUser = UserHandle.getCallingUserId(); 4989 if (callingUser != UserHandle.USER_SYSTEM) { 4990 return false; 4991 } 4992 if (mEphemeralResolverConnection == null) { 4993 return false; 4994 } 4995 if (intent.getComponent() != null) { 4996 return false; 4997 } 4998 if (intent.getPackage() != null) { 4999 return false; 5000 } 5001 final boolean isWebUri = hasWebURI(intent); 5002 if (!isWebUri) { 5003 return false; 5004 } 5005 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5006 synchronized (mPackages) { 5007 final int count = resolvedActivites.size(); 5008 for (int n = 0; n < count; n++) { 5009 ResolveInfo info = resolvedActivites.get(n); 5010 String packageName = info.activityInfo.packageName; 5011 PackageSetting ps = mSettings.mPackages.get(packageName); 5012 if (ps != null) { 5013 // Try to get the status from User settings first 5014 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5015 int status = (int) (packedStatus >> 32); 5016 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5017 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5018 if (DEBUG_EPHEMERAL) { 5019 Slog.v(TAG, "DENY ephemeral apps;" 5020 + " pkg: " + packageName + ", status: " + status); 5021 } 5022 return false; 5023 } 5024 } 5025 } 5026 } 5027 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5028 return true; 5029 } 5030 5031 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 5032 int userId) { 5033 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 5034 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 5035 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5036 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5037 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixMask, 5038 ephemeralPrefixCount); 5039 final int[] shaPrefix = digest.getDigestPrefix(); 5040 final byte[][] digestBytes = digest.getDigestBytes(); 5041 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5042 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5043 shaPrefix, ephemeralPrefixMask); 5044 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5045 // No hash prefix match; there are no ephemeral apps for this domain. 5046 return null; 5047 } 5048 5049 // Go in reverse order so we match the narrowest scope first. 5050 for (int i = shaPrefix.length - 1; i >= 0 ; --i) { 5051 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5052 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5053 continue; 5054 } 5055 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5056 // No filters; this should never happen. 5057 if (filters.isEmpty()) { 5058 continue; 5059 } 5060 // We have a domain match; resolve the filters to see if anything matches. 5061 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5062 for (int j = filters.size() - 1; j >= 0; --j) { 5063 final EphemeralResolveIntentInfo intentInfo = 5064 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5065 ephemeralResolver.addFilter(intentInfo); 5066 } 5067 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5068 intent, resolvedType, false /*defaultOnly*/, userId); 5069 if (!matchedResolveInfoList.isEmpty()) { 5070 return matchedResolveInfoList.get(0); 5071 } 5072 } 5073 } 5074 // Hash or filter mis-match; no ephemeral apps for this domain. 5075 return null; 5076 } 5077 5078 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5079 int flags, List<ResolveInfo> query, int userId) { 5080 if (query != null) { 5081 final int N = query.size(); 5082 if (N == 1) { 5083 return query.get(0); 5084 } else if (N > 1) { 5085 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5086 // If there is more than one activity with the same priority, 5087 // then let the user decide between them. 5088 ResolveInfo r0 = query.get(0); 5089 ResolveInfo r1 = query.get(1); 5090 if (DEBUG_INTENT_MATCHING || debug) { 5091 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5092 + r1.activityInfo.name + "=" + r1.priority); 5093 } 5094 // If the first activity has a higher priority, or a different 5095 // default, then it is always desirable to pick it. 5096 if (r0.priority != r1.priority 5097 || r0.preferredOrder != r1.preferredOrder 5098 || r0.isDefault != r1.isDefault) { 5099 return query.get(0); 5100 } 5101 // If we have saved a preference for a preferred activity for 5102 // this Intent, use that. 5103 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5104 flags, query, r0.priority, true, false, debug, userId); 5105 if (ri != null) { 5106 return ri; 5107 } 5108 ri = new ResolveInfo(mResolveInfo); 5109 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5110 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5111 // If all of the options come from the same package, show the application's 5112 // label and icon instead of the generic resolver's. 5113 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5114 // and then throw away the ResolveInfo itself, meaning that the caller loses 5115 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5116 // a fallback for this case; we only set the target package's resources on 5117 // the ResolveInfo, not the ActivityInfo. 5118 final String intentPackage = intent.getPackage(); 5119 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5120 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5121 ri.resolvePackageName = intentPackage; 5122 if (userNeedsBadging(userId)) { 5123 ri.noResourceId = true; 5124 } else { 5125 ri.icon = appi.icon; 5126 } 5127 ri.iconResourceId = appi.icon; 5128 ri.labelRes = appi.labelRes; 5129 } 5130 ri.activityInfo.applicationInfo = new ApplicationInfo( 5131 ri.activityInfo.applicationInfo); 5132 if (userId != 0) { 5133 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5134 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5135 } 5136 // Make sure that the resolver is displayable in car mode 5137 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5138 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5139 return ri; 5140 } 5141 } 5142 return null; 5143 } 5144 5145 /** 5146 * Return true if the given list is not empty and all of its contents have 5147 * an activityInfo with the given package name. 5148 */ 5149 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5150 if (ArrayUtils.isEmpty(list)) { 5151 return false; 5152 } 5153 for (int i = 0, N = list.size(); i < N; i++) { 5154 final ResolveInfo ri = list.get(i); 5155 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5156 if (ai == null || !packageName.equals(ai.packageName)) { 5157 return false; 5158 } 5159 } 5160 return true; 5161 } 5162 5163 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5164 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5165 final int N = query.size(); 5166 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5167 .get(userId); 5168 // Get the list of persistent preferred activities that handle the intent 5169 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5170 List<PersistentPreferredActivity> pprefs = ppir != null 5171 ? ppir.queryIntent(intent, resolvedType, 5172 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5173 : null; 5174 if (pprefs != null && pprefs.size() > 0) { 5175 final int M = pprefs.size(); 5176 for (int i=0; i<M; i++) { 5177 final PersistentPreferredActivity ppa = pprefs.get(i); 5178 if (DEBUG_PREFERRED || debug) { 5179 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5180 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5181 + "\n component=" + ppa.mComponent); 5182 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5183 } 5184 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5185 flags | MATCH_DISABLED_COMPONENTS, userId); 5186 if (DEBUG_PREFERRED || debug) { 5187 Slog.v(TAG, "Found persistent preferred activity:"); 5188 if (ai != null) { 5189 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5190 } else { 5191 Slog.v(TAG, " null"); 5192 } 5193 } 5194 if (ai == null) { 5195 // This previously registered persistent preferred activity 5196 // component is no longer known. Ignore it and do NOT remove it. 5197 continue; 5198 } 5199 for (int j=0; j<N; j++) { 5200 final ResolveInfo ri = query.get(j); 5201 if (!ri.activityInfo.applicationInfo.packageName 5202 .equals(ai.applicationInfo.packageName)) { 5203 continue; 5204 } 5205 if (!ri.activityInfo.name.equals(ai.name)) { 5206 continue; 5207 } 5208 // Found a persistent preference that can handle the intent. 5209 if (DEBUG_PREFERRED || debug) { 5210 Slog.v(TAG, "Returning persistent preferred activity: " + 5211 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5212 } 5213 return ri; 5214 } 5215 } 5216 } 5217 return null; 5218 } 5219 5220 // TODO: handle preferred activities missing while user has amnesia 5221 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5222 List<ResolveInfo> query, int priority, boolean always, 5223 boolean removeMatches, boolean debug, int userId) { 5224 if (!sUserManager.exists(userId)) return null; 5225 flags = updateFlagsForResolve(flags, userId, intent); 5226 // writer 5227 synchronized (mPackages) { 5228 if (intent.getSelector() != null) { 5229 intent = intent.getSelector(); 5230 } 5231 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5232 5233 // Try to find a matching persistent preferred activity. 5234 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5235 debug, userId); 5236 5237 // If a persistent preferred activity matched, use it. 5238 if (pri != null) { 5239 return pri; 5240 } 5241 5242 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5243 // Get the list of preferred activities that handle the intent 5244 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5245 List<PreferredActivity> prefs = pir != null 5246 ? pir.queryIntent(intent, resolvedType, 5247 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5248 : null; 5249 if (prefs != null && prefs.size() > 0) { 5250 boolean changed = false; 5251 try { 5252 // First figure out how good the original match set is. 5253 // We will only allow preferred activities that came 5254 // from the same match quality. 5255 int match = 0; 5256 5257 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5258 5259 final int N = query.size(); 5260 for (int j=0; j<N; j++) { 5261 final ResolveInfo ri = query.get(j); 5262 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5263 + ": 0x" + Integer.toHexString(match)); 5264 if (ri.match > match) { 5265 match = ri.match; 5266 } 5267 } 5268 5269 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5270 + Integer.toHexString(match)); 5271 5272 match &= IntentFilter.MATCH_CATEGORY_MASK; 5273 final int M = prefs.size(); 5274 for (int i=0; i<M; i++) { 5275 final PreferredActivity pa = prefs.get(i); 5276 if (DEBUG_PREFERRED || debug) { 5277 Slog.v(TAG, "Checking PreferredActivity ds=" 5278 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5279 + "\n component=" + pa.mPref.mComponent); 5280 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5281 } 5282 if (pa.mPref.mMatch != match) { 5283 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5284 + Integer.toHexString(pa.mPref.mMatch)); 5285 continue; 5286 } 5287 // If it's not an "always" type preferred activity and that's what we're 5288 // looking for, skip it. 5289 if (always && !pa.mPref.mAlways) { 5290 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5291 continue; 5292 } 5293 final ActivityInfo ai = getActivityInfo( 5294 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5295 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5296 userId); 5297 if (DEBUG_PREFERRED || debug) { 5298 Slog.v(TAG, "Found preferred activity:"); 5299 if (ai != null) { 5300 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5301 } else { 5302 Slog.v(TAG, " null"); 5303 } 5304 } 5305 if (ai == null) { 5306 // This previously registered preferred activity 5307 // component is no longer known. Most likely an update 5308 // to the app was installed and in the new version this 5309 // component no longer exists. Clean it up by removing 5310 // it from the preferred activities list, and skip it. 5311 Slog.w(TAG, "Removing dangling preferred activity: " 5312 + pa.mPref.mComponent); 5313 pir.removeFilter(pa); 5314 changed = true; 5315 continue; 5316 } 5317 for (int j=0; j<N; j++) { 5318 final ResolveInfo ri = query.get(j); 5319 if (!ri.activityInfo.applicationInfo.packageName 5320 .equals(ai.applicationInfo.packageName)) { 5321 continue; 5322 } 5323 if (!ri.activityInfo.name.equals(ai.name)) { 5324 continue; 5325 } 5326 5327 if (removeMatches) { 5328 pir.removeFilter(pa); 5329 changed = true; 5330 if (DEBUG_PREFERRED) { 5331 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5332 } 5333 break; 5334 } 5335 5336 // Okay we found a previously set preferred or last chosen app. 5337 // If the result set is different from when this 5338 // was created, we need to clear it and re-ask the 5339 // user their preference, if we're looking for an "always" type entry. 5340 if (always && !pa.mPref.sameSet(query)) { 5341 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5342 + intent + " type " + resolvedType); 5343 if (DEBUG_PREFERRED) { 5344 Slog.v(TAG, "Removing preferred activity since set changed " 5345 + pa.mPref.mComponent); 5346 } 5347 pir.removeFilter(pa); 5348 // Re-add the filter as a "last chosen" entry (!always) 5349 PreferredActivity lastChosen = new PreferredActivity( 5350 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5351 pir.addFilter(lastChosen); 5352 changed = true; 5353 return null; 5354 } 5355 5356 // Yay! Either the set matched or we're looking for the last chosen 5357 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5358 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5359 return ri; 5360 } 5361 } 5362 } finally { 5363 if (changed) { 5364 if (DEBUG_PREFERRED) { 5365 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5366 } 5367 scheduleWritePackageRestrictionsLocked(userId); 5368 } 5369 } 5370 } 5371 } 5372 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5373 return null; 5374 } 5375 5376 /* 5377 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5378 */ 5379 @Override 5380 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5381 int targetUserId) { 5382 mContext.enforceCallingOrSelfPermission( 5383 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5384 List<CrossProfileIntentFilter> matches = 5385 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5386 if (matches != null) { 5387 int size = matches.size(); 5388 for (int i = 0; i < size; i++) { 5389 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5390 } 5391 } 5392 if (hasWebURI(intent)) { 5393 // cross-profile app linking works only towards the parent. 5394 final UserInfo parent = getProfileParent(sourceUserId); 5395 synchronized(mPackages) { 5396 int flags = updateFlagsForResolve(0, parent.id, intent); 5397 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5398 intent, resolvedType, flags, sourceUserId, parent.id); 5399 return xpDomainInfo != null; 5400 } 5401 } 5402 return false; 5403 } 5404 5405 private UserInfo getProfileParent(int userId) { 5406 final long identity = Binder.clearCallingIdentity(); 5407 try { 5408 return sUserManager.getProfileParent(userId); 5409 } finally { 5410 Binder.restoreCallingIdentity(identity); 5411 } 5412 } 5413 5414 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5415 String resolvedType, int userId) { 5416 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5417 if (resolver != null) { 5418 return resolver.queryIntent(intent, resolvedType, false, userId); 5419 } 5420 return null; 5421 } 5422 5423 @Override 5424 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5425 String resolvedType, int flags, int userId) { 5426 try { 5427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5428 5429 return new ParceledListSlice<>( 5430 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5431 } finally { 5432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5433 } 5434 } 5435 5436 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5437 String resolvedType, int flags, int userId) { 5438 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5439 flags = updateFlagsForResolve(flags, userId, intent); 5440 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5441 false /* requireFullPermission */, false /* checkShell */, 5442 "query intent activities"); 5443 ComponentName comp = intent.getComponent(); 5444 if (comp == null) { 5445 if (intent.getSelector() != null) { 5446 intent = intent.getSelector(); 5447 comp = intent.getComponent(); 5448 } 5449 } 5450 5451 if (comp != null) { 5452 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5453 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5454 if (ai != null) { 5455 final ResolveInfo ri = new ResolveInfo(); 5456 ri.activityInfo = ai; 5457 list.add(ri); 5458 } 5459 return list; 5460 } 5461 5462 // reader 5463 synchronized (mPackages) { 5464 final String pkgName = intent.getPackage(); 5465 if (pkgName == null) { 5466 List<CrossProfileIntentFilter> matchingFilters = 5467 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5468 // Check for results that need to skip the current profile. 5469 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5470 resolvedType, flags, userId); 5471 if (xpResolveInfo != null) { 5472 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5473 result.add(xpResolveInfo); 5474 return filterIfNotSystemUser(result, userId); 5475 } 5476 5477 // Check for results in the current profile. 5478 List<ResolveInfo> result = mActivities.queryIntent( 5479 intent, resolvedType, flags, userId); 5480 result = filterIfNotSystemUser(result, userId); 5481 5482 // Check for cross profile results. 5483 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5484 xpResolveInfo = queryCrossProfileIntents( 5485 matchingFilters, intent, resolvedType, flags, userId, 5486 hasNonNegativePriorityResult); 5487 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5488 boolean isVisibleToUser = filterIfNotSystemUser( 5489 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5490 if (isVisibleToUser) { 5491 result.add(xpResolveInfo); 5492 Collections.sort(result, mResolvePrioritySorter); 5493 } 5494 } 5495 if (hasWebURI(intent)) { 5496 CrossProfileDomainInfo xpDomainInfo = null; 5497 final UserInfo parent = getProfileParent(userId); 5498 if (parent != null) { 5499 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5500 flags, userId, parent.id); 5501 } 5502 if (xpDomainInfo != null) { 5503 if (xpResolveInfo != null) { 5504 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5505 // in the result. 5506 result.remove(xpResolveInfo); 5507 } 5508 if (result.size() == 0) { 5509 result.add(xpDomainInfo.resolveInfo); 5510 return result; 5511 } 5512 } else if (result.size() <= 1) { 5513 return result; 5514 } 5515 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5516 xpDomainInfo, userId); 5517 Collections.sort(result, mResolvePrioritySorter); 5518 } 5519 return result; 5520 } 5521 final PackageParser.Package pkg = mPackages.get(pkgName); 5522 if (pkg != null) { 5523 return filterIfNotSystemUser( 5524 mActivities.queryIntentForPackage( 5525 intent, resolvedType, flags, pkg.activities, userId), 5526 userId); 5527 } 5528 return new ArrayList<ResolveInfo>(); 5529 } 5530 } 5531 5532 private static class CrossProfileDomainInfo { 5533 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5534 ResolveInfo resolveInfo; 5535 /* Best domain verification status of the activities found in the other profile */ 5536 int bestDomainVerificationStatus; 5537 } 5538 5539 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5540 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5541 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5542 sourceUserId)) { 5543 return null; 5544 } 5545 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5546 resolvedType, flags, parentUserId); 5547 5548 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5549 return null; 5550 } 5551 CrossProfileDomainInfo result = null; 5552 int size = resultTargetUser.size(); 5553 for (int i = 0; i < size; i++) { 5554 ResolveInfo riTargetUser = resultTargetUser.get(i); 5555 // Intent filter verification is only for filters that specify a host. So don't return 5556 // those that handle all web uris. 5557 if (riTargetUser.handleAllWebDataURI) { 5558 continue; 5559 } 5560 String packageName = riTargetUser.activityInfo.packageName; 5561 PackageSetting ps = mSettings.mPackages.get(packageName); 5562 if (ps == null) { 5563 continue; 5564 } 5565 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5566 int status = (int)(verificationState >> 32); 5567 if (result == null) { 5568 result = new CrossProfileDomainInfo(); 5569 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5570 sourceUserId, parentUserId); 5571 result.bestDomainVerificationStatus = status; 5572 } else { 5573 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5574 result.bestDomainVerificationStatus); 5575 } 5576 } 5577 // Don't consider matches with status NEVER across profiles. 5578 if (result != null && result.bestDomainVerificationStatus 5579 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5580 return null; 5581 } 5582 return result; 5583 } 5584 5585 /** 5586 * Verification statuses are ordered from the worse to the best, except for 5587 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5588 */ 5589 private int bestDomainVerificationStatus(int status1, int status2) { 5590 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5591 return status2; 5592 } 5593 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5594 return status1; 5595 } 5596 return (int) MathUtils.max(status1, status2); 5597 } 5598 5599 private boolean isUserEnabled(int userId) { 5600 long callingId = Binder.clearCallingIdentity(); 5601 try { 5602 UserInfo userInfo = sUserManager.getUserInfo(userId); 5603 return userInfo != null && userInfo.isEnabled(); 5604 } finally { 5605 Binder.restoreCallingIdentity(callingId); 5606 } 5607 } 5608 5609 /** 5610 * Filter out activities with systemUserOnly flag set, when current user is not System. 5611 * 5612 * @return filtered list 5613 */ 5614 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5615 if (userId == UserHandle.USER_SYSTEM) { 5616 return resolveInfos; 5617 } 5618 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5619 ResolveInfo info = resolveInfos.get(i); 5620 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5621 resolveInfos.remove(i); 5622 } 5623 } 5624 return resolveInfos; 5625 } 5626 5627 /** 5628 * @param resolveInfos list of resolve infos in descending priority order 5629 * @return if the list contains a resolve info with non-negative priority 5630 */ 5631 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5632 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5633 } 5634 5635 private static boolean hasWebURI(Intent intent) { 5636 if (intent.getData() == null) { 5637 return false; 5638 } 5639 final String scheme = intent.getScheme(); 5640 if (TextUtils.isEmpty(scheme)) { 5641 return false; 5642 } 5643 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5644 } 5645 5646 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5647 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5648 int userId) { 5649 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5650 5651 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5652 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5653 candidates.size()); 5654 } 5655 5656 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5657 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5658 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5659 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5660 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5661 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5662 5663 synchronized (mPackages) { 5664 final int count = candidates.size(); 5665 // First, try to use linked apps. Partition the candidates into four lists: 5666 // one for the final results, one for the "do not use ever", one for "undefined status" 5667 // and finally one for "browser app type". 5668 for (int n=0; n<count; n++) { 5669 ResolveInfo info = candidates.get(n); 5670 String packageName = info.activityInfo.packageName; 5671 PackageSetting ps = mSettings.mPackages.get(packageName); 5672 if (ps != null) { 5673 // Add to the special match all list (Browser use case) 5674 if (info.handleAllWebDataURI) { 5675 matchAllList.add(info); 5676 continue; 5677 } 5678 // Try to get the status from User settings first 5679 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5680 int status = (int)(packedStatus >> 32); 5681 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5682 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5683 if (DEBUG_DOMAIN_VERIFICATION) { 5684 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5685 + " : linkgen=" + linkGeneration); 5686 } 5687 // Use link-enabled generation as preferredOrder, i.e. 5688 // prefer newly-enabled over earlier-enabled. 5689 info.preferredOrder = linkGeneration; 5690 alwaysList.add(info); 5691 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5692 if (DEBUG_DOMAIN_VERIFICATION) { 5693 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5694 } 5695 neverList.add(info); 5696 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5697 if (DEBUG_DOMAIN_VERIFICATION) { 5698 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5699 } 5700 alwaysAskList.add(info); 5701 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5702 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5703 if (DEBUG_DOMAIN_VERIFICATION) { 5704 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5705 } 5706 undefinedList.add(info); 5707 } 5708 } 5709 } 5710 5711 // We'll want to include browser possibilities in a few cases 5712 boolean includeBrowser = false; 5713 5714 // First try to add the "always" resolution(s) for the current user, if any 5715 if (alwaysList.size() > 0) { 5716 result.addAll(alwaysList); 5717 } else { 5718 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5719 result.addAll(undefinedList); 5720 // Maybe add one for the other profile. 5721 if (xpDomainInfo != null && ( 5722 xpDomainInfo.bestDomainVerificationStatus 5723 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5724 result.add(xpDomainInfo.resolveInfo); 5725 } 5726 includeBrowser = true; 5727 } 5728 5729 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5730 // If there were 'always' entries their preferred order has been set, so we also 5731 // back that off to make the alternatives equivalent 5732 if (alwaysAskList.size() > 0) { 5733 for (ResolveInfo i : result) { 5734 i.preferredOrder = 0; 5735 } 5736 result.addAll(alwaysAskList); 5737 includeBrowser = true; 5738 } 5739 5740 if (includeBrowser) { 5741 // Also add browsers (all of them or only the default one) 5742 if (DEBUG_DOMAIN_VERIFICATION) { 5743 Slog.v(TAG, " ...including browsers in candidate set"); 5744 } 5745 if ((matchFlags & MATCH_ALL) != 0) { 5746 result.addAll(matchAllList); 5747 } else { 5748 // Browser/generic handling case. If there's a default browser, go straight 5749 // to that (but only if there is no other higher-priority match). 5750 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5751 int maxMatchPrio = 0; 5752 ResolveInfo defaultBrowserMatch = null; 5753 final int numCandidates = matchAllList.size(); 5754 for (int n = 0; n < numCandidates; n++) { 5755 ResolveInfo info = matchAllList.get(n); 5756 // track the highest overall match priority... 5757 if (info.priority > maxMatchPrio) { 5758 maxMatchPrio = info.priority; 5759 } 5760 // ...and the highest-priority default browser match 5761 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5762 if (defaultBrowserMatch == null 5763 || (defaultBrowserMatch.priority < info.priority)) { 5764 if (debug) { 5765 Slog.v(TAG, "Considering default browser match " + info); 5766 } 5767 defaultBrowserMatch = info; 5768 } 5769 } 5770 } 5771 if (defaultBrowserMatch != null 5772 && defaultBrowserMatch.priority >= maxMatchPrio 5773 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5774 { 5775 if (debug) { 5776 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5777 } 5778 result.add(defaultBrowserMatch); 5779 } else { 5780 result.addAll(matchAllList); 5781 } 5782 } 5783 5784 // If there is nothing selected, add all candidates and remove the ones that the user 5785 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5786 if (result.size() == 0) { 5787 result.addAll(candidates); 5788 result.removeAll(neverList); 5789 } 5790 } 5791 } 5792 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5793 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5794 result.size()); 5795 for (ResolveInfo info : result) { 5796 Slog.v(TAG, " + " + info.activityInfo); 5797 } 5798 } 5799 return result; 5800 } 5801 5802 // Returns a packed value as a long: 5803 // 5804 // high 'int'-sized word: link status: undefined/ask/never/always. 5805 // low 'int'-sized word: relative priority among 'always' results. 5806 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5807 long result = ps.getDomainVerificationStatusForUser(userId); 5808 // if none available, get the master status 5809 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5810 if (ps.getIntentFilterVerificationInfo() != null) { 5811 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5812 } 5813 } 5814 return result; 5815 } 5816 5817 private ResolveInfo querySkipCurrentProfileIntents( 5818 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5819 int flags, int sourceUserId) { 5820 if (matchingFilters != null) { 5821 int size = matchingFilters.size(); 5822 for (int i = 0; i < size; i ++) { 5823 CrossProfileIntentFilter filter = matchingFilters.get(i); 5824 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5825 // Checking if there are activities in the target user that can handle the 5826 // intent. 5827 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5828 resolvedType, flags, sourceUserId); 5829 if (resolveInfo != null) { 5830 return resolveInfo; 5831 } 5832 } 5833 } 5834 } 5835 return null; 5836 } 5837 5838 // Return matching ResolveInfo in target user if any. 5839 private ResolveInfo queryCrossProfileIntents( 5840 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5841 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5842 if (matchingFilters != null) { 5843 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5844 // match the same intent. For performance reasons, it is better not to 5845 // run queryIntent twice for the same userId 5846 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5847 int size = matchingFilters.size(); 5848 for (int i = 0; i < size; i++) { 5849 CrossProfileIntentFilter filter = matchingFilters.get(i); 5850 int targetUserId = filter.getTargetUserId(); 5851 boolean skipCurrentProfile = 5852 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5853 boolean skipCurrentProfileIfNoMatchFound = 5854 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5855 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5856 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5857 // Checking if there are activities in the target user that can handle the 5858 // intent. 5859 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5860 resolvedType, flags, sourceUserId); 5861 if (resolveInfo != null) return resolveInfo; 5862 alreadyTriedUserIds.put(targetUserId, true); 5863 } 5864 } 5865 } 5866 return null; 5867 } 5868 5869 /** 5870 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5871 * will forward the intent to the filter's target user. 5872 * Otherwise, returns null. 5873 */ 5874 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5875 String resolvedType, int flags, int sourceUserId) { 5876 int targetUserId = filter.getTargetUserId(); 5877 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5878 resolvedType, flags, targetUserId); 5879 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5880 // If all the matches in the target profile are suspended, return null. 5881 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5882 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5883 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5884 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5885 targetUserId); 5886 } 5887 } 5888 } 5889 return null; 5890 } 5891 5892 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5893 int sourceUserId, int targetUserId) { 5894 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5895 long ident = Binder.clearCallingIdentity(); 5896 boolean targetIsProfile; 5897 try { 5898 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5899 } finally { 5900 Binder.restoreCallingIdentity(ident); 5901 } 5902 String className; 5903 if (targetIsProfile) { 5904 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5905 } else { 5906 className = FORWARD_INTENT_TO_PARENT; 5907 } 5908 ComponentName forwardingActivityComponentName = new ComponentName( 5909 mAndroidApplication.packageName, className); 5910 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5911 sourceUserId); 5912 if (!targetIsProfile) { 5913 forwardingActivityInfo.showUserIcon = targetUserId; 5914 forwardingResolveInfo.noResourceId = true; 5915 } 5916 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5917 forwardingResolveInfo.priority = 0; 5918 forwardingResolveInfo.preferredOrder = 0; 5919 forwardingResolveInfo.match = 0; 5920 forwardingResolveInfo.isDefault = true; 5921 forwardingResolveInfo.filter = filter; 5922 forwardingResolveInfo.targetUserId = targetUserId; 5923 return forwardingResolveInfo; 5924 } 5925 5926 @Override 5927 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5928 Intent[] specifics, String[] specificTypes, Intent intent, 5929 String resolvedType, int flags, int userId) { 5930 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5931 specificTypes, intent, resolvedType, flags, userId)); 5932 } 5933 5934 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5935 Intent[] specifics, String[] specificTypes, Intent intent, 5936 String resolvedType, int flags, int userId) { 5937 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5938 flags = updateFlagsForResolve(flags, userId, intent); 5939 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5940 false /* requireFullPermission */, false /* checkShell */, 5941 "query intent activity options"); 5942 final String resultsAction = intent.getAction(); 5943 5944 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5945 | PackageManager.GET_RESOLVED_FILTER, userId); 5946 5947 if (DEBUG_INTENT_MATCHING) { 5948 Log.v(TAG, "Query " + intent + ": " + results); 5949 } 5950 5951 int specificsPos = 0; 5952 int N; 5953 5954 // todo: note that the algorithm used here is O(N^2). This 5955 // isn't a problem in our current environment, but if we start running 5956 // into situations where we have more than 5 or 10 matches then this 5957 // should probably be changed to something smarter... 5958 5959 // First we go through and resolve each of the specific items 5960 // that were supplied, taking care of removing any corresponding 5961 // duplicate items in the generic resolve list. 5962 if (specifics != null) { 5963 for (int i=0; i<specifics.length; i++) { 5964 final Intent sintent = specifics[i]; 5965 if (sintent == null) { 5966 continue; 5967 } 5968 5969 if (DEBUG_INTENT_MATCHING) { 5970 Log.v(TAG, "Specific #" + i + ": " + sintent); 5971 } 5972 5973 String action = sintent.getAction(); 5974 if (resultsAction != null && resultsAction.equals(action)) { 5975 // If this action was explicitly requested, then don't 5976 // remove things that have it. 5977 action = null; 5978 } 5979 5980 ResolveInfo ri = null; 5981 ActivityInfo ai = null; 5982 5983 ComponentName comp = sintent.getComponent(); 5984 if (comp == null) { 5985 ri = resolveIntent( 5986 sintent, 5987 specificTypes != null ? specificTypes[i] : null, 5988 flags, userId); 5989 if (ri == null) { 5990 continue; 5991 } 5992 if (ri == mResolveInfo) { 5993 // ACK! Must do something better with this. 5994 } 5995 ai = ri.activityInfo; 5996 comp = new ComponentName(ai.applicationInfo.packageName, 5997 ai.name); 5998 } else { 5999 ai = getActivityInfo(comp, flags, userId); 6000 if (ai == null) { 6001 continue; 6002 } 6003 } 6004 6005 // Look for any generic query activities that are duplicates 6006 // of this specific one, and remove them from the results. 6007 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6008 N = results.size(); 6009 int j; 6010 for (j=specificsPos; j<N; j++) { 6011 ResolveInfo sri = results.get(j); 6012 if ((sri.activityInfo.name.equals(comp.getClassName()) 6013 && sri.activityInfo.applicationInfo.packageName.equals( 6014 comp.getPackageName())) 6015 || (action != null && sri.filter.matchAction(action))) { 6016 results.remove(j); 6017 if (DEBUG_INTENT_MATCHING) Log.v( 6018 TAG, "Removing duplicate item from " + j 6019 + " due to specific " + specificsPos); 6020 if (ri == null) { 6021 ri = sri; 6022 } 6023 j--; 6024 N--; 6025 } 6026 } 6027 6028 // Add this specific item to its proper place. 6029 if (ri == null) { 6030 ri = new ResolveInfo(); 6031 ri.activityInfo = ai; 6032 } 6033 results.add(specificsPos, ri); 6034 ri.specificIndex = i; 6035 specificsPos++; 6036 } 6037 } 6038 6039 // Now we go through the remaining generic results and remove any 6040 // duplicate actions that are found here. 6041 N = results.size(); 6042 for (int i=specificsPos; i<N-1; i++) { 6043 final ResolveInfo rii = results.get(i); 6044 if (rii.filter == null) { 6045 continue; 6046 } 6047 6048 // Iterate over all of the actions of this result's intent 6049 // filter... typically this should be just one. 6050 final Iterator<String> it = rii.filter.actionsIterator(); 6051 if (it == null) { 6052 continue; 6053 } 6054 while (it.hasNext()) { 6055 final String action = it.next(); 6056 if (resultsAction != null && resultsAction.equals(action)) { 6057 // If this action was explicitly requested, then don't 6058 // remove things that have it. 6059 continue; 6060 } 6061 for (int j=i+1; j<N; j++) { 6062 final ResolveInfo rij = results.get(j); 6063 if (rij.filter != null && rij.filter.hasAction(action)) { 6064 results.remove(j); 6065 if (DEBUG_INTENT_MATCHING) Log.v( 6066 TAG, "Removing duplicate item from " + j 6067 + " due to action " + action + " at " + i); 6068 j--; 6069 N--; 6070 } 6071 } 6072 } 6073 6074 // If the caller didn't request filter information, drop it now 6075 // so we don't have to marshall/unmarshall it. 6076 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6077 rii.filter = null; 6078 } 6079 } 6080 6081 // Filter out the caller activity if so requested. 6082 if (caller != null) { 6083 N = results.size(); 6084 for (int i=0; i<N; i++) { 6085 ActivityInfo ainfo = results.get(i).activityInfo; 6086 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6087 && caller.getClassName().equals(ainfo.name)) { 6088 results.remove(i); 6089 break; 6090 } 6091 } 6092 } 6093 6094 // If the caller didn't request filter information, 6095 // drop them now so we don't have to 6096 // marshall/unmarshall it. 6097 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6098 N = results.size(); 6099 for (int i=0; i<N; i++) { 6100 results.get(i).filter = null; 6101 } 6102 } 6103 6104 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6105 return results; 6106 } 6107 6108 @Override 6109 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6110 String resolvedType, int flags, int userId) { 6111 return new ParceledListSlice<>( 6112 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6113 } 6114 6115 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6116 String resolvedType, int flags, int userId) { 6117 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6118 flags = updateFlagsForResolve(flags, userId, intent); 6119 ComponentName comp = intent.getComponent(); 6120 if (comp == null) { 6121 if (intent.getSelector() != null) { 6122 intent = intent.getSelector(); 6123 comp = intent.getComponent(); 6124 } 6125 } 6126 if (comp != null) { 6127 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6128 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6129 if (ai != null) { 6130 ResolveInfo ri = new ResolveInfo(); 6131 ri.activityInfo = ai; 6132 list.add(ri); 6133 } 6134 return list; 6135 } 6136 6137 // reader 6138 synchronized (mPackages) { 6139 String pkgName = intent.getPackage(); 6140 if (pkgName == null) { 6141 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6142 } 6143 final PackageParser.Package pkg = mPackages.get(pkgName); 6144 if (pkg != null) { 6145 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6146 userId); 6147 } 6148 return Collections.emptyList(); 6149 } 6150 } 6151 6152 @Override 6153 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6154 if (!sUserManager.exists(userId)) return null; 6155 flags = updateFlagsForResolve(flags, userId, intent); 6156 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6157 if (query != null) { 6158 if (query.size() >= 1) { 6159 // If there is more than one service with the same priority, 6160 // just arbitrarily pick the first one. 6161 return query.get(0); 6162 } 6163 } 6164 return null; 6165 } 6166 6167 @Override 6168 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6169 String resolvedType, int flags, int userId) { 6170 return new ParceledListSlice<>( 6171 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6172 } 6173 6174 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6175 String resolvedType, int flags, int userId) { 6176 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6177 flags = updateFlagsForResolve(flags, userId, intent); 6178 ComponentName comp = intent.getComponent(); 6179 if (comp == null) { 6180 if (intent.getSelector() != null) { 6181 intent = intent.getSelector(); 6182 comp = intent.getComponent(); 6183 } 6184 } 6185 if (comp != null) { 6186 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6187 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6188 if (si != null) { 6189 final ResolveInfo ri = new ResolveInfo(); 6190 ri.serviceInfo = si; 6191 list.add(ri); 6192 } 6193 return list; 6194 } 6195 6196 // reader 6197 synchronized (mPackages) { 6198 String pkgName = intent.getPackage(); 6199 if (pkgName == null) { 6200 return mServices.queryIntent(intent, resolvedType, flags, userId); 6201 } 6202 final PackageParser.Package pkg = mPackages.get(pkgName); 6203 if (pkg != null) { 6204 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6205 userId); 6206 } 6207 return Collections.emptyList(); 6208 } 6209 } 6210 6211 @Override 6212 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6213 String resolvedType, int flags, int userId) { 6214 return new ParceledListSlice<>( 6215 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6216 } 6217 6218 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6219 Intent intent, String resolvedType, int flags, int userId) { 6220 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6221 flags = updateFlagsForResolve(flags, userId, intent); 6222 ComponentName comp = intent.getComponent(); 6223 if (comp == null) { 6224 if (intent.getSelector() != null) { 6225 intent = intent.getSelector(); 6226 comp = intent.getComponent(); 6227 } 6228 } 6229 if (comp != null) { 6230 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6231 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6232 if (pi != null) { 6233 final ResolveInfo ri = new ResolveInfo(); 6234 ri.providerInfo = pi; 6235 list.add(ri); 6236 } 6237 return list; 6238 } 6239 6240 // reader 6241 synchronized (mPackages) { 6242 String pkgName = intent.getPackage(); 6243 if (pkgName == null) { 6244 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6245 } 6246 final PackageParser.Package pkg = mPackages.get(pkgName); 6247 if (pkg != null) { 6248 return mProviders.queryIntentForPackage( 6249 intent, resolvedType, flags, pkg.providers, userId); 6250 } 6251 return Collections.emptyList(); 6252 } 6253 } 6254 6255 @Override 6256 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6257 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6258 flags = updateFlagsForPackage(flags, userId, null); 6259 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6261 true /* requireFullPermission */, false /* checkShell */, 6262 "get installed packages"); 6263 6264 // writer 6265 synchronized (mPackages) { 6266 ArrayList<PackageInfo> list; 6267 if (listUninstalled) { 6268 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6269 for (PackageSetting ps : mSettings.mPackages.values()) { 6270 final PackageInfo pi; 6271 if (ps.pkg != null) { 6272 pi = generatePackageInfo(ps, flags, userId); 6273 } else { 6274 pi = generatePackageInfo(ps, flags, userId); 6275 } 6276 if (pi != null) { 6277 list.add(pi); 6278 } 6279 } 6280 } else { 6281 list = new ArrayList<PackageInfo>(mPackages.size()); 6282 for (PackageParser.Package p : mPackages.values()) { 6283 final PackageInfo pi = 6284 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6285 if (pi != null) { 6286 list.add(pi); 6287 } 6288 } 6289 } 6290 6291 return new ParceledListSlice<PackageInfo>(list); 6292 } 6293 } 6294 6295 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6296 String[] permissions, boolean[] tmp, int flags, int userId) { 6297 int numMatch = 0; 6298 final PermissionsState permissionsState = ps.getPermissionsState(); 6299 for (int i=0; i<permissions.length; i++) { 6300 final String permission = permissions[i]; 6301 if (permissionsState.hasPermission(permission, userId)) { 6302 tmp[i] = true; 6303 numMatch++; 6304 } else { 6305 tmp[i] = false; 6306 } 6307 } 6308 if (numMatch == 0) { 6309 return; 6310 } 6311 final PackageInfo pi; 6312 if (ps.pkg != null) { 6313 pi = generatePackageInfo(ps, flags, userId); 6314 } else { 6315 pi = generatePackageInfo(ps, flags, userId); 6316 } 6317 // The above might return null in cases of uninstalled apps or install-state 6318 // skew across users/profiles. 6319 if (pi != null) { 6320 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6321 if (numMatch == permissions.length) { 6322 pi.requestedPermissions = permissions; 6323 } else { 6324 pi.requestedPermissions = new String[numMatch]; 6325 numMatch = 0; 6326 for (int i=0; i<permissions.length; i++) { 6327 if (tmp[i]) { 6328 pi.requestedPermissions[numMatch] = permissions[i]; 6329 numMatch++; 6330 } 6331 } 6332 } 6333 } 6334 list.add(pi); 6335 } 6336 } 6337 6338 @Override 6339 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6340 String[] permissions, int flags, int userId) { 6341 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6342 flags = updateFlagsForPackage(flags, userId, permissions); 6343 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6344 6345 // writer 6346 synchronized (mPackages) { 6347 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6348 boolean[] tmpBools = new boolean[permissions.length]; 6349 if (listUninstalled) { 6350 for (PackageSetting ps : mSettings.mPackages.values()) { 6351 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6352 } 6353 } else { 6354 for (PackageParser.Package pkg : mPackages.values()) { 6355 PackageSetting ps = (PackageSetting)pkg.mExtras; 6356 if (ps != null) { 6357 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6358 userId); 6359 } 6360 } 6361 } 6362 6363 return new ParceledListSlice<PackageInfo>(list); 6364 } 6365 } 6366 6367 @Override 6368 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6369 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6370 flags = updateFlagsForApplication(flags, userId, null); 6371 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6372 6373 // writer 6374 synchronized (mPackages) { 6375 ArrayList<ApplicationInfo> list; 6376 if (listUninstalled) { 6377 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6378 for (PackageSetting ps : mSettings.mPackages.values()) { 6379 ApplicationInfo ai; 6380 if (ps.pkg != null) { 6381 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6382 ps.readUserState(userId), userId); 6383 } else { 6384 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6385 } 6386 if (ai != null) { 6387 list.add(ai); 6388 } 6389 } 6390 } else { 6391 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6392 for (PackageParser.Package p : mPackages.values()) { 6393 if (p.mExtras != null) { 6394 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6395 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6396 if (ai != null) { 6397 list.add(ai); 6398 } 6399 } 6400 } 6401 } 6402 6403 return new ParceledListSlice<ApplicationInfo>(list); 6404 } 6405 } 6406 6407 @Override 6408 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6409 if (DISABLE_EPHEMERAL_APPS) { 6410 return null; 6411 } 6412 6413 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6414 "getEphemeralApplications"); 6415 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6416 true /* requireFullPermission */, false /* checkShell */, 6417 "getEphemeralApplications"); 6418 synchronized (mPackages) { 6419 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6420 .getEphemeralApplicationsLPw(userId); 6421 if (ephemeralApps != null) { 6422 return new ParceledListSlice<>(ephemeralApps); 6423 } 6424 } 6425 return null; 6426 } 6427 6428 @Override 6429 public boolean isEphemeralApplication(String packageName, int userId) { 6430 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6431 true /* requireFullPermission */, false /* checkShell */, 6432 "isEphemeral"); 6433 if (DISABLE_EPHEMERAL_APPS) { 6434 return false; 6435 } 6436 6437 if (!isCallerSameApp(packageName)) { 6438 return false; 6439 } 6440 synchronized (mPackages) { 6441 PackageParser.Package pkg = mPackages.get(packageName); 6442 if (pkg != null) { 6443 return pkg.applicationInfo.isEphemeralApp(); 6444 } 6445 } 6446 return false; 6447 } 6448 6449 @Override 6450 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6451 if (DISABLE_EPHEMERAL_APPS) { 6452 return null; 6453 } 6454 6455 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6456 true /* requireFullPermission */, false /* checkShell */, 6457 "getCookie"); 6458 if (!isCallerSameApp(packageName)) { 6459 return null; 6460 } 6461 synchronized (mPackages) { 6462 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6463 packageName, userId); 6464 } 6465 } 6466 6467 @Override 6468 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6469 if (DISABLE_EPHEMERAL_APPS) { 6470 return true; 6471 } 6472 6473 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6474 true /* requireFullPermission */, true /* checkShell */, 6475 "setCookie"); 6476 if (!isCallerSameApp(packageName)) { 6477 return false; 6478 } 6479 synchronized (mPackages) { 6480 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6481 packageName, cookie, userId); 6482 } 6483 } 6484 6485 @Override 6486 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6487 if (DISABLE_EPHEMERAL_APPS) { 6488 return null; 6489 } 6490 6491 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6492 "getEphemeralApplicationIcon"); 6493 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6494 true /* requireFullPermission */, false /* checkShell */, 6495 "getEphemeralApplicationIcon"); 6496 synchronized (mPackages) { 6497 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6498 packageName, userId); 6499 } 6500 } 6501 6502 private boolean isCallerSameApp(String packageName) { 6503 PackageParser.Package pkg = mPackages.get(packageName); 6504 return pkg != null 6505 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6506 } 6507 6508 @Override 6509 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6510 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6511 } 6512 6513 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6514 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6515 6516 // reader 6517 synchronized (mPackages) { 6518 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6519 final int userId = UserHandle.getCallingUserId(); 6520 while (i.hasNext()) { 6521 final PackageParser.Package p = i.next(); 6522 if (p.applicationInfo == null) continue; 6523 6524 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6525 && !p.applicationInfo.isDirectBootAware(); 6526 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6527 && p.applicationInfo.isDirectBootAware(); 6528 6529 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6530 && (!mSafeMode || isSystemApp(p)) 6531 && (matchesUnaware || matchesAware)) { 6532 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6533 if (ps != null) { 6534 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6535 ps.readUserState(userId), userId); 6536 if (ai != null) { 6537 finalList.add(ai); 6538 } 6539 } 6540 } 6541 } 6542 } 6543 6544 return finalList; 6545 } 6546 6547 @Override 6548 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6549 if (!sUserManager.exists(userId)) return null; 6550 flags = updateFlagsForComponent(flags, userId, name); 6551 // reader 6552 synchronized (mPackages) { 6553 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6554 PackageSetting ps = provider != null 6555 ? mSettings.mPackages.get(provider.owner.packageName) 6556 : null; 6557 return ps != null 6558 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6559 ? PackageParser.generateProviderInfo(provider, flags, 6560 ps.readUserState(userId), userId) 6561 : null; 6562 } 6563 } 6564 6565 /** 6566 * @deprecated 6567 */ 6568 @Deprecated 6569 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6570 // reader 6571 synchronized (mPackages) { 6572 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6573 .entrySet().iterator(); 6574 final int userId = UserHandle.getCallingUserId(); 6575 while (i.hasNext()) { 6576 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6577 PackageParser.Provider p = entry.getValue(); 6578 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6579 6580 if (ps != null && p.syncable 6581 && (!mSafeMode || (p.info.applicationInfo.flags 6582 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6583 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6584 ps.readUserState(userId), userId); 6585 if (info != null) { 6586 outNames.add(entry.getKey()); 6587 outInfo.add(info); 6588 } 6589 } 6590 } 6591 } 6592 } 6593 6594 @Override 6595 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6596 int uid, int flags) { 6597 final int userId = processName != null ? UserHandle.getUserId(uid) 6598 : UserHandle.getCallingUserId(); 6599 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6600 flags = updateFlagsForComponent(flags, userId, processName); 6601 6602 ArrayList<ProviderInfo> finalList = null; 6603 // reader 6604 synchronized (mPackages) { 6605 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6606 while (i.hasNext()) { 6607 final PackageParser.Provider p = i.next(); 6608 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6609 if (ps != null && p.info.authority != null 6610 && (processName == null 6611 || (p.info.processName.equals(processName) 6612 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6613 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6614 if (finalList == null) { 6615 finalList = new ArrayList<ProviderInfo>(3); 6616 } 6617 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6618 ps.readUserState(userId), userId); 6619 if (info != null) { 6620 finalList.add(info); 6621 } 6622 } 6623 } 6624 } 6625 6626 if (finalList != null) { 6627 Collections.sort(finalList, mProviderInitOrderSorter); 6628 return new ParceledListSlice<ProviderInfo>(finalList); 6629 } 6630 6631 return ParceledListSlice.emptyList(); 6632 } 6633 6634 @Override 6635 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6636 // reader 6637 synchronized (mPackages) { 6638 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6639 return PackageParser.generateInstrumentationInfo(i, flags); 6640 } 6641 } 6642 6643 @Override 6644 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6645 String targetPackage, int flags) { 6646 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6647 } 6648 6649 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6650 int flags) { 6651 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6652 6653 // reader 6654 synchronized (mPackages) { 6655 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6656 while (i.hasNext()) { 6657 final PackageParser.Instrumentation p = i.next(); 6658 if (targetPackage == null 6659 || targetPackage.equals(p.info.targetPackage)) { 6660 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6661 flags); 6662 if (ii != null) { 6663 finalList.add(ii); 6664 } 6665 } 6666 } 6667 } 6668 6669 return finalList; 6670 } 6671 6672 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6673 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6674 if (overlays == null) { 6675 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6676 return; 6677 } 6678 for (PackageParser.Package opkg : overlays.values()) { 6679 // Not much to do if idmap fails: we already logged the error 6680 // and we certainly don't want to abort installation of pkg simply 6681 // because an overlay didn't fit properly. For these reasons, 6682 // ignore the return value of createIdmapForPackagePairLI. 6683 createIdmapForPackagePairLI(pkg, opkg); 6684 } 6685 } 6686 6687 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6688 PackageParser.Package opkg) { 6689 if (!opkg.mTrustedOverlay) { 6690 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6691 opkg.baseCodePath + ": overlay not trusted"); 6692 return false; 6693 } 6694 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6695 if (overlaySet == null) { 6696 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6697 opkg.baseCodePath + " but target package has no known overlays"); 6698 return false; 6699 } 6700 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6701 // TODO: generate idmap for split APKs 6702 try { 6703 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6704 } catch (InstallerException e) { 6705 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6706 + opkg.baseCodePath); 6707 return false; 6708 } 6709 PackageParser.Package[] overlayArray = 6710 overlaySet.values().toArray(new PackageParser.Package[0]); 6711 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6712 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6713 return p1.mOverlayPriority - p2.mOverlayPriority; 6714 } 6715 }; 6716 Arrays.sort(overlayArray, cmp); 6717 6718 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6719 int i = 0; 6720 for (PackageParser.Package p : overlayArray) { 6721 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6722 } 6723 return true; 6724 } 6725 6726 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6727 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6728 try { 6729 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6730 } finally { 6731 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6732 } 6733 } 6734 6735 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6736 final File[] files = dir.listFiles(); 6737 if (ArrayUtils.isEmpty(files)) { 6738 Log.d(TAG, "No files in app dir " + dir); 6739 return; 6740 } 6741 6742 if (DEBUG_PACKAGE_SCANNING) { 6743 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6744 + " flags=0x" + Integer.toHexString(parseFlags)); 6745 } 6746 6747 for (File file : files) { 6748 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6749 && !PackageInstallerService.isStageName(file.getName()); 6750 if (!isPackage) { 6751 // Ignore entries which are not packages 6752 continue; 6753 } 6754 try { 6755 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6756 scanFlags, currentTime, null); 6757 } catch (PackageManagerException e) { 6758 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6759 6760 // Delete invalid userdata apps 6761 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6762 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6763 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6764 removeCodePathLI(file); 6765 } 6766 } 6767 } 6768 } 6769 6770 private static File getSettingsProblemFile() { 6771 File dataDir = Environment.getDataDirectory(); 6772 File systemDir = new File(dataDir, "system"); 6773 File fname = new File(systemDir, "uiderrors.txt"); 6774 return fname; 6775 } 6776 6777 static void reportSettingsProblem(int priority, String msg) { 6778 logCriticalInfo(priority, msg); 6779 } 6780 6781 static void logCriticalInfo(int priority, String msg) { 6782 Slog.println(priority, TAG, msg); 6783 EventLogTags.writePmCriticalInfo(msg); 6784 try { 6785 File fname = getSettingsProblemFile(); 6786 FileOutputStream out = new FileOutputStream(fname, true); 6787 PrintWriter pw = new FastPrintWriter(out); 6788 SimpleDateFormat formatter = new SimpleDateFormat(); 6789 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6790 pw.println(dateString + ": " + msg); 6791 pw.close(); 6792 FileUtils.setPermissions( 6793 fname.toString(), 6794 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6795 -1, -1); 6796 } catch (java.io.IOException e) { 6797 } 6798 } 6799 6800 private long getLastModifiedTime(PackageParser.Package pkg, File srcFile) { 6801 if (srcFile.isDirectory()) { 6802 final File baseFile = new File(pkg.baseCodePath); 6803 long maxModifiedTime = baseFile.lastModified(); 6804 if (pkg.splitCodePaths != null) { 6805 for (int i = pkg.splitCodePaths.length - 1; i >=0; --i) { 6806 final File splitFile = new File(pkg.splitCodePaths[i]); 6807 maxModifiedTime = Math.max(maxModifiedTime, splitFile.lastModified()); 6808 } 6809 } 6810 return maxModifiedTime; 6811 } 6812 return srcFile.lastModified(); 6813 } 6814 6815 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6816 final int policyFlags) throws PackageManagerException { 6817 if (ps != null 6818 && ps.codePath.equals(srcFile) 6819 && ps.timeStamp == getLastModifiedTime(pkg, srcFile) 6820 && !isCompatSignatureUpdateNeeded(pkg) 6821 && !isRecoverSignatureUpdateNeeded(pkg)) { 6822 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6823 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6824 ArraySet<PublicKey> signingKs; 6825 synchronized (mPackages) { 6826 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6827 } 6828 if (ps.signatures.mSignatures != null 6829 && ps.signatures.mSignatures.length != 0 6830 && signingKs != null) { 6831 // Optimization: reuse the existing cached certificates 6832 // if the package appears to be unchanged. 6833 pkg.mSignatures = ps.signatures.mSignatures; 6834 pkg.mSigningKeys = signingKs; 6835 return; 6836 } 6837 6838 Slog.w(TAG, "PackageSetting for " + ps.name 6839 + " is missing signatures. Collecting certs again to recover them."); 6840 } else { 6841 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6842 } 6843 6844 try { 6845 PackageParser.collectCertificates(pkg, policyFlags); 6846 } catch (PackageParserException e) { 6847 throw PackageManagerException.from(e); 6848 } 6849 } 6850 6851 /** 6852 * Traces a package scan. 6853 * @see #scanPackageLI(File, int, int, long, UserHandle) 6854 */ 6855 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6856 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6857 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6858 try { 6859 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6860 } finally { 6861 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6862 } 6863 } 6864 6865 /** 6866 * Scans a package and returns the newly parsed package. 6867 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6868 */ 6869 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6870 long currentTime, UserHandle user) throws PackageManagerException { 6871 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6872 PackageParser pp = new PackageParser(); 6873 pp.setSeparateProcesses(mSeparateProcesses); 6874 pp.setOnlyCoreApps(mOnlyCore); 6875 pp.setDisplayMetrics(mMetrics); 6876 6877 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6878 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6879 } 6880 6881 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6882 final PackageParser.Package pkg; 6883 try { 6884 pkg = pp.parsePackage(scanFile, parseFlags); 6885 } catch (PackageParserException e) { 6886 throw PackageManagerException.from(e); 6887 } finally { 6888 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6889 } 6890 6891 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6892 } 6893 6894 /** 6895 * Scans a package and returns the newly parsed package. 6896 * @throws PackageManagerException on a parse error. 6897 */ 6898 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6899 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6900 throws PackageManagerException { 6901 // If the package has children and this is the first dive in the function 6902 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6903 // packages (parent and children) would be successfully scanned before the 6904 // actual scan since scanning mutates internal state and we want to atomically 6905 // install the package and its children. 6906 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6907 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6908 scanFlags |= SCAN_CHECK_ONLY; 6909 } 6910 } else { 6911 scanFlags &= ~SCAN_CHECK_ONLY; 6912 } 6913 6914 // Scan the parent 6915 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6916 scanFlags, currentTime, user); 6917 6918 // Scan the children 6919 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6920 for (int i = 0; i < childCount; i++) { 6921 PackageParser.Package childPackage = pkg.childPackages.get(i); 6922 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6923 currentTime, user); 6924 } 6925 6926 6927 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6928 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6929 } 6930 6931 return scannedPkg; 6932 } 6933 6934 /** 6935 * Scans a package and returns the newly parsed package. 6936 * @throws PackageManagerException on a parse error. 6937 */ 6938 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6939 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6940 throws PackageManagerException { 6941 PackageSetting ps = null; 6942 PackageSetting updatedPkg; 6943 // reader 6944 synchronized (mPackages) { 6945 // Look to see if we already know about this package. 6946 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6947 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6948 // This package has been renamed to its original name. Let's 6949 // use that. 6950 ps = mSettings.peekPackageLPr(oldName); 6951 } 6952 // If there was no original package, see one for the real package name. 6953 if (ps == null) { 6954 ps = mSettings.peekPackageLPr(pkg.packageName); 6955 } 6956 // Check to see if this package could be hiding/updating a system 6957 // package. Must look for it either under the original or real 6958 // package name depending on our state. 6959 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6960 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6961 6962 // If this is a package we don't know about on the system partition, we 6963 // may need to remove disabled child packages on the system partition 6964 // or may need to not add child packages if the parent apk is updated 6965 // on the data partition and no longer defines this child package. 6966 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6967 // If this is a parent package for an updated system app and this system 6968 // app got an OTA update which no longer defines some of the child packages 6969 // we have to prune them from the disabled system packages. 6970 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6971 if (disabledPs != null) { 6972 final int scannedChildCount = (pkg.childPackages != null) 6973 ? pkg.childPackages.size() : 0; 6974 final int disabledChildCount = disabledPs.childPackageNames != null 6975 ? disabledPs.childPackageNames.size() : 0; 6976 for (int i = 0; i < disabledChildCount; i++) { 6977 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6978 boolean disabledPackageAvailable = false; 6979 for (int j = 0; j < scannedChildCount; j++) { 6980 PackageParser.Package childPkg = pkg.childPackages.get(j); 6981 if (childPkg.packageName.equals(disabledChildPackageName)) { 6982 disabledPackageAvailable = true; 6983 break; 6984 } 6985 } 6986 if (!disabledPackageAvailable) { 6987 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6988 } 6989 } 6990 } 6991 } 6992 } 6993 6994 boolean updatedPkgBetter = false; 6995 // First check if this is a system package that may involve an update 6996 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6997 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6998 // it needs to drop FLAG_PRIVILEGED. 6999 if (locationIsPrivileged(scanFile)) { 7000 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7001 } else { 7002 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7003 } 7004 7005 if (ps != null && !ps.codePath.equals(scanFile)) { 7006 // The path has changed from what was last scanned... check the 7007 // version of the new path against what we have stored to determine 7008 // what to do. 7009 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 7010 if (pkg.mVersionCode <= ps.versionCode) { 7011 // The system package has been updated and the code path does not match 7012 // Ignore entry. Skip it. 7013 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 7014 + " ignored: updated version " + ps.versionCode 7015 + " better than this " + pkg.mVersionCode); 7016 if (!updatedPkg.codePath.equals(scanFile)) { 7017 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 7018 + ps.name + " changing from " + updatedPkg.codePathString 7019 + " to " + scanFile); 7020 updatedPkg.codePath = scanFile; 7021 updatedPkg.codePathString = scanFile.toString(); 7022 updatedPkg.resourcePath = scanFile; 7023 updatedPkg.resourcePathString = scanFile.toString(); 7024 } 7025 updatedPkg.pkg = pkg; 7026 updatedPkg.versionCode = pkg.mVersionCode; 7027 7028 // Update the disabled system child packages to point to the package too. 7029 final int childCount = updatedPkg.childPackageNames != null 7030 ? updatedPkg.childPackageNames.size() : 0; 7031 for (int i = 0; i < childCount; i++) { 7032 String childPackageName = updatedPkg.childPackageNames.get(i); 7033 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7034 childPackageName); 7035 if (updatedChildPkg != null) { 7036 updatedChildPkg.pkg = pkg; 7037 updatedChildPkg.versionCode = pkg.mVersionCode; 7038 } 7039 } 7040 7041 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7042 + scanFile + " ignored: updated version " + ps.versionCode 7043 + " better than this " + pkg.mVersionCode); 7044 } else { 7045 // The current app on the system partition is better than 7046 // what we have updated to on the data partition; switch 7047 // back to the system partition version. 7048 // At this point, its safely assumed that package installation for 7049 // apps in system partition will go through. If not there won't be a working 7050 // version of the app 7051 // writer 7052 synchronized (mPackages) { 7053 // Just remove the loaded entries from package lists. 7054 mPackages.remove(ps.name); 7055 } 7056 7057 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7058 + " reverting from " + ps.codePathString 7059 + ": new version " + pkg.mVersionCode 7060 + " better than installed " + ps.versionCode); 7061 7062 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7063 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7064 synchronized (mInstallLock) { 7065 args.cleanUpResourcesLI(); 7066 } 7067 synchronized (mPackages) { 7068 mSettings.enableSystemPackageLPw(ps.name); 7069 } 7070 updatedPkgBetter = true; 7071 } 7072 } 7073 } 7074 7075 if (updatedPkg != null) { 7076 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7077 // initially 7078 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7079 7080 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7081 // flag set initially 7082 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7083 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7084 } 7085 } 7086 7087 // Verify certificates against what was last scanned 7088 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7089 7090 /* 7091 * A new system app appeared, but we already had a non-system one of the 7092 * same name installed earlier. 7093 */ 7094 boolean shouldHideSystemApp = false; 7095 if (updatedPkg == null && ps != null 7096 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7097 /* 7098 * Check to make sure the signatures match first. If they don't, 7099 * wipe the installed application and its data. 7100 */ 7101 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7102 != PackageManager.SIGNATURE_MATCH) { 7103 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7104 + " signatures don't match existing userdata copy; removing"); 7105 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7106 "scanPackageInternalLI")) { 7107 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7108 } 7109 ps = null; 7110 } else { 7111 /* 7112 * If the newly-added system app is an older version than the 7113 * already installed version, hide it. It will be scanned later 7114 * and re-added like an update. 7115 */ 7116 if (pkg.mVersionCode <= ps.versionCode) { 7117 shouldHideSystemApp = true; 7118 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7119 + " but new version " + pkg.mVersionCode + " better than installed " 7120 + ps.versionCode + "; hiding system"); 7121 } else { 7122 /* 7123 * The newly found system app is a newer version that the 7124 * one previously installed. Simply remove the 7125 * already-installed application and replace it with our own 7126 * while keeping the application data. 7127 */ 7128 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7129 + " reverting from " + ps.codePathString + ": new version " 7130 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7131 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7132 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7133 synchronized (mInstallLock) { 7134 args.cleanUpResourcesLI(); 7135 } 7136 } 7137 } 7138 } 7139 7140 // The apk is forward locked (not public) if its code and resources 7141 // are kept in different files. (except for app in either system or 7142 // vendor path). 7143 // TODO grab this value from PackageSettings 7144 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7145 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7146 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7147 } 7148 } 7149 7150 // TODO: extend to support forward-locked splits 7151 String resourcePath = null; 7152 String baseResourcePath = null; 7153 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7154 if (ps != null && ps.resourcePathString != null) { 7155 resourcePath = ps.resourcePathString; 7156 baseResourcePath = ps.resourcePathString; 7157 } else { 7158 // Should not happen at all. Just log an error. 7159 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7160 } 7161 } else { 7162 resourcePath = pkg.codePath; 7163 baseResourcePath = pkg.baseCodePath; 7164 } 7165 7166 // Set application objects path explicitly. 7167 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7168 pkg.setApplicationInfoCodePath(pkg.codePath); 7169 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7170 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7171 pkg.setApplicationInfoResourcePath(resourcePath); 7172 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7173 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7174 7175 // Note that we invoke the following method only if we are about to unpack an application 7176 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7177 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7178 7179 /* 7180 * If the system app should be overridden by a previously installed 7181 * data, hide the system app now and let the /data/app scan pick it up 7182 * again. 7183 */ 7184 if (shouldHideSystemApp) { 7185 synchronized (mPackages) { 7186 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7187 } 7188 } 7189 7190 return scannedPkg; 7191 } 7192 7193 private static String fixProcessName(String defProcessName, 7194 String processName, int uid) { 7195 if (processName == null) { 7196 return defProcessName; 7197 } 7198 return processName; 7199 } 7200 7201 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7202 throws PackageManagerException { 7203 if (pkgSetting.signatures.mSignatures != null) { 7204 // Already existing package. Make sure signatures match 7205 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7206 == PackageManager.SIGNATURE_MATCH; 7207 if (!match) { 7208 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7209 == PackageManager.SIGNATURE_MATCH; 7210 } 7211 if (!match) { 7212 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7213 == PackageManager.SIGNATURE_MATCH; 7214 } 7215 if (!match) { 7216 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7217 + pkg.packageName + " signatures do not match the " 7218 + "previously installed version; ignoring!"); 7219 } 7220 } 7221 7222 // Check for shared user signatures 7223 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7224 // Already existing package. Make sure signatures match 7225 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7226 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7227 if (!match) { 7228 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7229 == PackageManager.SIGNATURE_MATCH; 7230 } 7231 if (!match) { 7232 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7233 == PackageManager.SIGNATURE_MATCH; 7234 } 7235 if (!match) { 7236 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7237 "Package " + pkg.packageName 7238 + " has no signatures that match those in shared user " 7239 + pkgSetting.sharedUser.name + "; ignoring!"); 7240 } 7241 } 7242 } 7243 7244 /** 7245 * Enforces that only the system UID or root's UID can call a method exposed 7246 * via Binder. 7247 * 7248 * @param message used as message if SecurityException is thrown 7249 * @throws SecurityException if the caller is not system or root 7250 */ 7251 private static final void enforceSystemOrRoot(String message) { 7252 final int uid = Binder.getCallingUid(); 7253 if (uid != Process.SYSTEM_UID && uid != 0) { 7254 throw new SecurityException(message); 7255 } 7256 } 7257 7258 @Override 7259 public void performFstrimIfNeeded() { 7260 enforceSystemOrRoot("Only the system can request fstrim"); 7261 7262 // Before everything else, see whether we need to fstrim. 7263 try { 7264 IMountService ms = PackageHelper.getMountService(); 7265 if (ms != null) { 7266 final boolean isUpgrade = isUpgrade(); 7267 boolean doTrim = isUpgrade; 7268 if (doTrim) { 7269 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7270 } else { 7271 final long interval = android.provider.Settings.Global.getLong( 7272 mContext.getContentResolver(), 7273 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7274 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7275 if (interval > 0) { 7276 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7277 if (timeSinceLast > interval) { 7278 doTrim = true; 7279 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7280 + "; running immediately"); 7281 } 7282 } 7283 } 7284 if (doTrim) { 7285 if (!isFirstBoot()) { 7286 try { 7287 ActivityManagerNative.getDefault().showBootMessage( 7288 mContext.getResources().getString( 7289 R.string.android_upgrading_fstrim), true); 7290 } catch (RemoteException e) { 7291 } 7292 } 7293 ms.runMaintenance(); 7294 } 7295 } else { 7296 Slog.e(TAG, "Mount service unavailable!"); 7297 } 7298 } catch (RemoteException e) { 7299 // Can't happen; MountService is local 7300 } 7301 } 7302 7303 @Override 7304 public void updatePackagesIfNeeded() { 7305 enforceSystemOrRoot("Only the system can request package update"); 7306 7307 // We need to re-extract after an OTA. 7308 boolean causeUpgrade = isUpgrade(); 7309 7310 // First boot or factory reset. 7311 // Note: we also handle devices that are upgrading to N right now as if it is their 7312 // first boot, as they do not have profile data. 7313 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7314 7315 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7316 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7317 7318 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7319 return; 7320 } 7321 7322 List<PackageParser.Package> pkgs; 7323 synchronized (mPackages) { 7324 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7325 } 7326 7327 final long startTime = System.nanoTime(); 7328 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7329 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7330 7331 final int elapsedTimeSeconds = 7332 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7333 7334 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7335 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7336 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7337 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7338 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7339 } 7340 7341 /** 7342 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7343 * containing statistics about the invocation. The array consists of three elements, 7344 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7345 * and {@code numberOfPackagesFailed}. 7346 */ 7347 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7348 String compilerFilter) { 7349 7350 int numberOfPackagesVisited = 0; 7351 int numberOfPackagesOptimized = 0; 7352 int numberOfPackagesSkipped = 0; 7353 int numberOfPackagesFailed = 0; 7354 final int numberOfPackagesToDexopt = pkgs.size(); 7355 7356 for (PackageParser.Package pkg : pkgs) { 7357 numberOfPackagesVisited++; 7358 7359 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7360 if (DEBUG_DEXOPT) { 7361 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7362 } 7363 numberOfPackagesSkipped++; 7364 continue; 7365 } 7366 7367 if (DEBUG_DEXOPT) { 7368 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7369 numberOfPackagesToDexopt + ": " + pkg.packageName); 7370 } 7371 7372 if (showDialog) { 7373 try { 7374 ActivityManagerNative.getDefault().showBootMessage( 7375 mContext.getResources().getString(R.string.android_upgrading_apk, 7376 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7377 } catch (RemoteException e) { 7378 } 7379 } 7380 7381 // checkProfiles is false to avoid merging profiles during boot which 7382 // might interfere with background compilation (b/28612421). 7383 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7384 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7385 // trade-off worth doing to save boot time work. 7386 int dexOptStatus = performDexOptTraced(pkg.packageName, 7387 false /* checkProfiles */, 7388 compilerFilter, 7389 false /* force */); 7390 switch (dexOptStatus) { 7391 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7392 numberOfPackagesOptimized++; 7393 break; 7394 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7395 numberOfPackagesSkipped++; 7396 break; 7397 case PackageDexOptimizer.DEX_OPT_FAILED: 7398 numberOfPackagesFailed++; 7399 break; 7400 default: 7401 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7402 break; 7403 } 7404 } 7405 7406 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7407 numberOfPackagesFailed }; 7408 } 7409 7410 @Override 7411 public void notifyPackageUse(String packageName, int reason) { 7412 synchronized (mPackages) { 7413 PackageParser.Package p = mPackages.get(packageName); 7414 if (p == null) { 7415 return; 7416 } 7417 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7418 } 7419 } 7420 7421 // TODO: this is not used nor needed. Delete it. 7422 @Override 7423 public boolean performDexOptIfNeeded(String packageName) { 7424 int dexOptStatus = performDexOptTraced(packageName, 7425 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7426 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7427 } 7428 7429 @Override 7430 public boolean performDexOpt(String packageName, 7431 boolean checkProfiles, int compileReason, boolean force) { 7432 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7433 getCompilerFilterForReason(compileReason), force); 7434 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7435 } 7436 7437 @Override 7438 public boolean performDexOptMode(String packageName, 7439 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7440 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7441 targetCompilerFilter, force); 7442 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7443 } 7444 7445 private int performDexOptTraced(String packageName, 7446 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7447 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7448 try { 7449 return performDexOptInternal(packageName, checkProfiles, 7450 targetCompilerFilter, force); 7451 } finally { 7452 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7453 } 7454 } 7455 7456 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7457 // if the package can now be considered up to date for the given filter. 7458 private int performDexOptInternal(String packageName, 7459 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7460 PackageParser.Package p; 7461 synchronized (mPackages) { 7462 p = mPackages.get(packageName); 7463 if (p == null) { 7464 // Package could not be found. Report failure. 7465 return PackageDexOptimizer.DEX_OPT_FAILED; 7466 } 7467 mPackageUsage.write(false); 7468 } 7469 long callingId = Binder.clearCallingIdentity(); 7470 try { 7471 synchronized (mInstallLock) { 7472 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7473 targetCompilerFilter, force); 7474 } 7475 } finally { 7476 Binder.restoreCallingIdentity(callingId); 7477 } 7478 } 7479 7480 public ArraySet<String> getOptimizablePackages() { 7481 ArraySet<String> pkgs = new ArraySet<String>(); 7482 synchronized (mPackages) { 7483 for (PackageParser.Package p : mPackages.values()) { 7484 if (PackageDexOptimizer.canOptimizePackage(p)) { 7485 pkgs.add(p.packageName); 7486 } 7487 } 7488 } 7489 return pkgs; 7490 } 7491 7492 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7493 boolean checkProfiles, String targetCompilerFilter, 7494 boolean force) { 7495 // Select the dex optimizer based on the force parameter. 7496 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7497 // allocate an object here. 7498 PackageDexOptimizer pdo = force 7499 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7500 : mPackageDexOptimizer; 7501 7502 // Optimize all dependencies first. Note: we ignore the return value and march on 7503 // on errors. 7504 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7505 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7506 if (!deps.isEmpty()) { 7507 for (PackageParser.Package depPackage : deps) { 7508 // TODO: Analyze and investigate if we (should) profile libraries. 7509 // Currently this will do a full compilation of the library by default. 7510 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7511 false /* checkProfiles */, 7512 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7513 } 7514 } 7515 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7516 targetCompilerFilter); 7517 } 7518 7519 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7520 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7521 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7522 Set<String> collectedNames = new HashSet<>(); 7523 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7524 7525 retValue.remove(p); 7526 7527 return retValue; 7528 } else { 7529 return Collections.emptyList(); 7530 } 7531 } 7532 7533 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7534 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7535 if (!collectedNames.contains(p.packageName)) { 7536 collectedNames.add(p.packageName); 7537 collected.add(p); 7538 7539 if (p.usesLibraries != null) { 7540 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7541 } 7542 if (p.usesOptionalLibraries != null) { 7543 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7544 collectedNames); 7545 } 7546 } 7547 } 7548 7549 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7550 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7551 for (String libName : libs) { 7552 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7553 if (libPkg != null) { 7554 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7555 } 7556 } 7557 } 7558 7559 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7560 synchronized (mPackages) { 7561 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7562 if (lib != null && lib.apk != null) { 7563 return mPackages.get(lib.apk); 7564 } 7565 } 7566 return null; 7567 } 7568 7569 public void shutdown() { 7570 mPackageUsage.write(true); 7571 } 7572 7573 @Override 7574 public void dumpProfiles(String packageName) { 7575 PackageParser.Package pkg; 7576 synchronized (mPackages) { 7577 pkg = mPackages.get(packageName); 7578 if (pkg == null) { 7579 throw new IllegalArgumentException("Unknown package: " + packageName); 7580 } 7581 } 7582 /* Only the shell, root, or the app user should be able to dump profiles. */ 7583 int callingUid = Binder.getCallingUid(); 7584 if (callingUid != Process.SHELL_UID && 7585 callingUid != Process.ROOT_UID && 7586 callingUid != pkg.applicationInfo.uid) { 7587 throw new SecurityException("dumpProfiles"); 7588 } 7589 7590 synchronized (mInstallLock) { 7591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7592 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7593 try { 7594 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7595 String gid = Integer.toString(sharedGid); 7596 String codePaths = TextUtils.join(";", allCodePaths); 7597 mInstaller.dumpProfiles(gid, packageName, codePaths); 7598 } catch (InstallerException e) { 7599 Slog.w(TAG, "Failed to dump profiles", e); 7600 } 7601 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7602 } 7603 } 7604 7605 @Override 7606 public void forceDexOpt(String packageName) { 7607 enforceSystemOrRoot("forceDexOpt"); 7608 7609 PackageParser.Package pkg; 7610 synchronized (mPackages) { 7611 pkg = mPackages.get(packageName); 7612 if (pkg == null) { 7613 throw new IllegalArgumentException("Unknown package: " + packageName); 7614 } 7615 } 7616 7617 synchronized (mInstallLock) { 7618 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7619 7620 // Whoever is calling forceDexOpt wants a fully compiled package. 7621 // Don't use profiles since that may cause compilation to be skipped. 7622 final int res = performDexOptInternalWithDependenciesLI(pkg, 7623 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7624 true /* force */); 7625 7626 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7627 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7628 throw new IllegalStateException("Failed to dexopt: " + res); 7629 } 7630 } 7631 } 7632 7633 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7634 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7635 Slog.w(TAG, "Unable to update from " + oldPkg.name 7636 + " to " + newPkg.packageName 7637 + ": old package not in system partition"); 7638 return false; 7639 } else if (mPackages.get(oldPkg.name) != null) { 7640 Slog.w(TAG, "Unable to update from " + oldPkg.name 7641 + " to " + newPkg.packageName 7642 + ": old package still exists"); 7643 return false; 7644 } 7645 return true; 7646 } 7647 7648 void removeCodePathLI(File codePath) { 7649 if (codePath.isDirectory()) { 7650 try { 7651 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7652 } catch (InstallerException e) { 7653 Slog.w(TAG, "Failed to remove code path", e); 7654 } 7655 } else { 7656 codePath.delete(); 7657 } 7658 } 7659 7660 private int[] resolveUserIds(int userId) { 7661 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7662 } 7663 7664 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7665 if (pkg == null) { 7666 Slog.wtf(TAG, "Package was null!", new Throwable()); 7667 return; 7668 } 7669 clearAppDataLeafLIF(pkg, userId, flags); 7670 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7671 for (int i = 0; i < childCount; i++) { 7672 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7673 } 7674 } 7675 7676 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7677 final PackageSetting ps; 7678 synchronized (mPackages) { 7679 ps = mSettings.mPackages.get(pkg.packageName); 7680 } 7681 for (int realUserId : resolveUserIds(userId)) { 7682 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7683 try { 7684 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7685 ceDataInode); 7686 } catch (InstallerException e) { 7687 Slog.w(TAG, String.valueOf(e)); 7688 } 7689 } 7690 } 7691 7692 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7693 if (pkg == null) { 7694 Slog.wtf(TAG, "Package was null!", new Throwable()); 7695 return; 7696 } 7697 destroyAppDataLeafLIF(pkg, userId, flags); 7698 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7699 for (int i = 0; i < childCount; i++) { 7700 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7701 } 7702 } 7703 7704 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7705 final PackageSetting ps; 7706 synchronized (mPackages) { 7707 ps = mSettings.mPackages.get(pkg.packageName); 7708 } 7709 for (int realUserId : resolveUserIds(userId)) { 7710 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7711 try { 7712 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7713 ceDataInode); 7714 } catch (InstallerException e) { 7715 Slog.w(TAG, String.valueOf(e)); 7716 } 7717 } 7718 } 7719 7720 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7721 if (pkg == null) { 7722 Slog.wtf(TAG, "Package was null!", new Throwable()); 7723 return; 7724 } 7725 destroyAppProfilesLeafLIF(pkg); 7726 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7727 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7728 for (int i = 0; i < childCount; i++) { 7729 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7730 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7731 true /* removeBaseMarker */); 7732 } 7733 } 7734 7735 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7736 boolean removeBaseMarker) { 7737 if (pkg.isForwardLocked()) { 7738 return; 7739 } 7740 7741 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7742 try { 7743 path = PackageManagerServiceUtils.realpath(new File(path)); 7744 } catch (IOException e) { 7745 // TODO: Should we return early here ? 7746 Slog.w(TAG, "Failed to get canonical path", e); 7747 continue; 7748 } 7749 7750 final String useMarker = path.replace('/', '@'); 7751 for (int realUserId : resolveUserIds(userId)) { 7752 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7753 if (removeBaseMarker) { 7754 File foreignUseMark = new File(profileDir, useMarker); 7755 if (foreignUseMark.exists()) { 7756 if (!foreignUseMark.delete()) { 7757 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7758 + pkg.packageName); 7759 } 7760 } 7761 } 7762 7763 File[] markers = profileDir.listFiles(); 7764 if (markers != null) { 7765 final String searchString = "@" + pkg.packageName + "@"; 7766 // We also delete all markers that contain the package name we're 7767 // uninstalling. These are associated with secondary dex-files belonging 7768 // to the package. Reconstructing the path of these dex files is messy 7769 // in general. 7770 for (File marker : markers) { 7771 if (marker.getName().indexOf(searchString) > 0) { 7772 if (!marker.delete()) { 7773 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7774 + pkg.packageName); 7775 } 7776 } 7777 } 7778 } 7779 } 7780 } 7781 } 7782 7783 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7784 try { 7785 mInstaller.destroyAppProfiles(pkg.packageName); 7786 } catch (InstallerException e) { 7787 Slog.w(TAG, String.valueOf(e)); 7788 } 7789 } 7790 7791 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7792 if (pkg == null) { 7793 Slog.wtf(TAG, "Package was null!", new Throwable()); 7794 return; 7795 } 7796 clearAppProfilesLeafLIF(pkg); 7797 // We don't remove the base foreign use marker when clearing profiles because 7798 // we will rename it when the app is updated. Unlike the actual profile contents, 7799 // the foreign use marker is good across installs. 7800 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7801 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7802 for (int i = 0; i < childCount; i++) { 7803 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7804 } 7805 } 7806 7807 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7808 try { 7809 mInstaller.clearAppProfiles(pkg.packageName); 7810 } catch (InstallerException e) { 7811 Slog.w(TAG, String.valueOf(e)); 7812 } 7813 } 7814 7815 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7816 long lastUpdateTime) { 7817 // Set parent install/update time 7818 PackageSetting ps = (PackageSetting) pkg.mExtras; 7819 if (ps != null) { 7820 ps.firstInstallTime = firstInstallTime; 7821 ps.lastUpdateTime = lastUpdateTime; 7822 } 7823 // Set children install/update time 7824 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7825 for (int i = 0; i < childCount; i++) { 7826 PackageParser.Package childPkg = pkg.childPackages.get(i); 7827 ps = (PackageSetting) childPkg.mExtras; 7828 if (ps != null) { 7829 ps.firstInstallTime = firstInstallTime; 7830 ps.lastUpdateTime = lastUpdateTime; 7831 } 7832 } 7833 } 7834 7835 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7836 PackageParser.Package changingLib) { 7837 if (file.path != null) { 7838 usesLibraryFiles.add(file.path); 7839 return; 7840 } 7841 PackageParser.Package p = mPackages.get(file.apk); 7842 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7843 // If we are doing this while in the middle of updating a library apk, 7844 // then we need to make sure to use that new apk for determining the 7845 // dependencies here. (We haven't yet finished committing the new apk 7846 // to the package manager state.) 7847 if (p == null || p.packageName.equals(changingLib.packageName)) { 7848 p = changingLib; 7849 } 7850 } 7851 if (p != null) { 7852 usesLibraryFiles.addAll(p.getAllCodePaths()); 7853 } 7854 } 7855 7856 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7857 PackageParser.Package changingLib) throws PackageManagerException { 7858 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7859 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7860 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7861 for (int i=0; i<N; i++) { 7862 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7863 if (file == null) { 7864 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7865 "Package " + pkg.packageName + " requires unavailable shared library " 7866 + pkg.usesLibraries.get(i) + "; failing!"); 7867 } 7868 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7869 } 7870 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7871 for (int i=0; i<N; i++) { 7872 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7873 if (file == null) { 7874 Slog.w(TAG, "Package " + pkg.packageName 7875 + " desires unavailable shared library " 7876 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7877 } else { 7878 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7879 } 7880 } 7881 N = usesLibraryFiles.size(); 7882 if (N > 0) { 7883 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7884 } else { 7885 pkg.usesLibraryFiles = null; 7886 } 7887 } 7888 } 7889 7890 private static boolean hasString(List<String> list, List<String> which) { 7891 if (list == null) { 7892 return false; 7893 } 7894 for (int i=list.size()-1; i>=0; i--) { 7895 for (int j=which.size()-1; j>=0; j--) { 7896 if (which.get(j).equals(list.get(i))) { 7897 return true; 7898 } 7899 } 7900 } 7901 return false; 7902 } 7903 7904 private void updateAllSharedLibrariesLPw() { 7905 for (PackageParser.Package pkg : mPackages.values()) { 7906 try { 7907 updateSharedLibrariesLPw(pkg, null); 7908 } catch (PackageManagerException e) { 7909 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7910 } 7911 } 7912 } 7913 7914 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7915 PackageParser.Package changingPkg) { 7916 ArrayList<PackageParser.Package> res = null; 7917 for (PackageParser.Package pkg : mPackages.values()) { 7918 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7919 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7920 if (res == null) { 7921 res = new ArrayList<PackageParser.Package>(); 7922 } 7923 res.add(pkg); 7924 try { 7925 updateSharedLibrariesLPw(pkg, changingPkg); 7926 } catch (PackageManagerException e) { 7927 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7928 } 7929 } 7930 } 7931 return res; 7932 } 7933 7934 /** 7935 * Derive the value of the {@code cpuAbiOverride} based on the provided 7936 * value and an optional stored value from the package settings. 7937 */ 7938 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7939 String cpuAbiOverride = null; 7940 7941 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7942 cpuAbiOverride = null; 7943 } else if (abiOverride != null) { 7944 cpuAbiOverride = abiOverride; 7945 } else if (settings != null) { 7946 cpuAbiOverride = settings.cpuAbiOverrideString; 7947 } 7948 7949 return cpuAbiOverride; 7950 } 7951 7952 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7953 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7954 throws PackageManagerException { 7955 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7956 // If the package has children and this is the first dive in the function 7957 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7958 // whether all packages (parent and children) would be successfully scanned 7959 // before the actual scan since scanning mutates internal state and we want 7960 // to atomically install the package and its children. 7961 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7962 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7963 scanFlags |= SCAN_CHECK_ONLY; 7964 } 7965 } else { 7966 scanFlags &= ~SCAN_CHECK_ONLY; 7967 } 7968 7969 final PackageParser.Package scannedPkg; 7970 try { 7971 // Scan the parent 7972 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7973 // Scan the children 7974 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7975 for (int i = 0; i < childCount; i++) { 7976 PackageParser.Package childPkg = pkg.childPackages.get(i); 7977 scanPackageLI(childPkg, policyFlags, 7978 scanFlags, currentTime, user); 7979 } 7980 } finally { 7981 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7982 } 7983 7984 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7985 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7986 } 7987 7988 return scannedPkg; 7989 } 7990 7991 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7992 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7993 boolean success = false; 7994 try { 7995 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7996 currentTime, user); 7997 success = true; 7998 return res; 7999 } finally { 8000 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 8001 // DELETE_DATA_ON_FAILURES is only used by frozen paths 8002 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 8003 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 8004 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 8005 } 8006 } 8007 } 8008 8009 /** 8010 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 8011 */ 8012 private static boolean apkHasCode(String fileName) { 8013 StrictJarFile jarFile = null; 8014 try { 8015 jarFile = new StrictJarFile(fileName, 8016 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 8017 return jarFile.findEntry("classes.dex") != null; 8018 } catch (IOException ignore) { 8019 } finally { 8020 try { 8021 jarFile.close(); 8022 } catch (IOException ignore) {} 8023 } 8024 return false; 8025 } 8026 8027 /** 8028 * Enforces code policy for the package. This ensures that if an APK has 8029 * declared hasCode="true" in its manifest that the APK actually contains 8030 * code. 8031 * 8032 * @throws PackageManagerException If bytecode could not be found when it should exist 8033 */ 8034 private static void enforceCodePolicy(PackageParser.Package pkg) 8035 throws PackageManagerException { 8036 final boolean shouldHaveCode = 8037 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8038 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8039 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8040 "Package " + pkg.baseCodePath + " code is missing"); 8041 } 8042 8043 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8044 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8045 final boolean splitShouldHaveCode = 8046 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8047 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8048 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8049 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8050 } 8051 } 8052 } 8053 } 8054 8055 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8056 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8057 throws PackageManagerException { 8058 final File scanFile = new File(pkg.codePath); 8059 if (pkg.applicationInfo.getCodePath() == null || 8060 pkg.applicationInfo.getResourcePath() == null) { 8061 // Bail out. The resource and code paths haven't been set. 8062 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8063 "Code and resource paths haven't been set correctly"); 8064 } 8065 8066 // Apply policy 8067 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8068 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8069 if (pkg.applicationInfo.isDirectBootAware()) { 8070 // we're direct boot aware; set for all components 8071 for (PackageParser.Service s : pkg.services) { 8072 s.info.encryptionAware = s.info.directBootAware = true; 8073 } 8074 for (PackageParser.Provider p : pkg.providers) { 8075 p.info.encryptionAware = p.info.directBootAware = true; 8076 } 8077 for (PackageParser.Activity a : pkg.activities) { 8078 a.info.encryptionAware = a.info.directBootAware = true; 8079 } 8080 for (PackageParser.Activity r : pkg.receivers) { 8081 r.info.encryptionAware = r.info.directBootAware = true; 8082 } 8083 } 8084 } else { 8085 // Only allow system apps to be flagged as core apps. 8086 pkg.coreApp = false; 8087 // clear flags not applicable to regular apps 8088 pkg.applicationInfo.privateFlags &= 8089 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8090 pkg.applicationInfo.privateFlags &= 8091 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8092 } 8093 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8094 8095 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8096 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8097 } 8098 8099 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8100 enforceCodePolicy(pkg); 8101 } 8102 8103 if (mCustomResolverComponentName != null && 8104 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8105 setUpCustomResolverActivity(pkg); 8106 } 8107 8108 if (pkg.packageName.equals("android")) { 8109 synchronized (mPackages) { 8110 if (mAndroidApplication != null) { 8111 Slog.w(TAG, "*************************************************"); 8112 Slog.w(TAG, "Core android package being redefined. Skipping."); 8113 Slog.w(TAG, " file=" + scanFile); 8114 Slog.w(TAG, "*************************************************"); 8115 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8116 "Core android package being redefined. Skipping."); 8117 } 8118 8119 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8120 // Set up information for our fall-back user intent resolution activity. 8121 mPlatformPackage = pkg; 8122 pkg.mVersionCode = mSdkVersion; 8123 mAndroidApplication = pkg.applicationInfo; 8124 8125 if (!mResolverReplaced) { 8126 mResolveActivity.applicationInfo = mAndroidApplication; 8127 mResolveActivity.name = ResolverActivity.class.getName(); 8128 mResolveActivity.packageName = mAndroidApplication.packageName; 8129 mResolveActivity.processName = "system:ui"; 8130 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8131 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8132 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8133 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8134 mResolveActivity.exported = true; 8135 mResolveActivity.enabled = true; 8136 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8137 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8138 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8139 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8140 | ActivityInfo.CONFIG_ORIENTATION 8141 | ActivityInfo.CONFIG_KEYBOARD 8142 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8143 mResolveInfo.activityInfo = mResolveActivity; 8144 mResolveInfo.priority = 0; 8145 mResolveInfo.preferredOrder = 0; 8146 mResolveInfo.match = 0; 8147 mResolveComponentName = new ComponentName( 8148 mAndroidApplication.packageName, mResolveActivity.name); 8149 } 8150 } 8151 } 8152 } 8153 8154 if (DEBUG_PACKAGE_SCANNING) { 8155 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8156 Log.d(TAG, "Scanning package " + pkg.packageName); 8157 } 8158 8159 synchronized (mPackages) { 8160 if (mPackages.containsKey(pkg.packageName) 8161 || mSharedLibraries.containsKey(pkg.packageName)) { 8162 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8163 "Application package " + pkg.packageName 8164 + " already installed. Skipping duplicate."); 8165 } 8166 8167 // If we're only installing presumed-existing packages, require that the 8168 // scanned APK is both already known and at the path previously established 8169 // for it. Previously unknown packages we pick up normally, but if we have an 8170 // a priori expectation about this package's install presence, enforce it. 8171 // With a singular exception for new system packages. When an OTA contains 8172 // a new system package, we allow the codepath to change from a system location 8173 // to the user-installed location. If we don't allow this change, any newer, 8174 // user-installed version of the application will be ignored. 8175 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8176 if (mExpectingBetter.containsKey(pkg.packageName)) { 8177 logCriticalInfo(Log.WARN, 8178 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8179 } else { 8180 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8181 if (known != null) { 8182 if (DEBUG_PACKAGE_SCANNING) { 8183 Log.d(TAG, "Examining " + pkg.codePath 8184 + " and requiring known paths " + known.codePathString 8185 + " & " + known.resourcePathString); 8186 } 8187 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8188 || !pkg.applicationInfo.getResourcePath().equals( 8189 known.resourcePathString)) { 8190 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8191 "Application package " + pkg.packageName 8192 + " found at " + pkg.applicationInfo.getCodePath() 8193 + " but expected at " + known.codePathString 8194 + "; ignoring."); 8195 } 8196 } 8197 } 8198 } 8199 } 8200 8201 // Initialize package source and resource directories 8202 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8203 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8204 8205 SharedUserSetting suid = null; 8206 PackageSetting pkgSetting = null; 8207 8208 if (!isSystemApp(pkg)) { 8209 // Only system apps can use these features. 8210 pkg.mOriginalPackages = null; 8211 pkg.mRealPackage = null; 8212 pkg.mAdoptPermissions = null; 8213 } 8214 8215 // Getting the package setting may have a side-effect, so if we 8216 // are only checking if scan would succeed, stash a copy of the 8217 // old setting to restore at the end. 8218 PackageSetting nonMutatedPs = null; 8219 8220 // writer 8221 synchronized (mPackages) { 8222 if (pkg.mSharedUserId != null) { 8223 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8224 if (suid == null) { 8225 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8226 "Creating application package " + pkg.packageName 8227 + " for shared user failed"); 8228 } 8229 if (DEBUG_PACKAGE_SCANNING) { 8230 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8231 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8232 + "): packages=" + suid.packages); 8233 } 8234 } 8235 8236 // Check if we are renaming from an original package name. 8237 PackageSetting origPackage = null; 8238 String realName = null; 8239 if (pkg.mOriginalPackages != null) { 8240 // This package may need to be renamed to a previously 8241 // installed name. Let's check on that... 8242 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8243 if (pkg.mOriginalPackages.contains(renamed)) { 8244 // This package had originally been installed as the 8245 // original name, and we have already taken care of 8246 // transitioning to the new one. Just update the new 8247 // one to continue using the old name. 8248 realName = pkg.mRealPackage; 8249 if (!pkg.packageName.equals(renamed)) { 8250 // Callers into this function may have already taken 8251 // care of renaming the package; only do it here if 8252 // it is not already done. 8253 pkg.setPackageName(renamed); 8254 } 8255 8256 } else { 8257 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8258 if ((origPackage = mSettings.peekPackageLPr( 8259 pkg.mOriginalPackages.get(i))) != null) { 8260 // We do have the package already installed under its 8261 // original name... should we use it? 8262 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8263 // New package is not compatible with original. 8264 origPackage = null; 8265 continue; 8266 } else if (origPackage.sharedUser != null) { 8267 // Make sure uid is compatible between packages. 8268 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8269 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8270 + " to " + pkg.packageName + ": old uid " 8271 + origPackage.sharedUser.name 8272 + " differs from " + pkg.mSharedUserId); 8273 origPackage = null; 8274 continue; 8275 } 8276 // TODO: Add case when shared user id is added [b/28144775] 8277 } else { 8278 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8279 + pkg.packageName + " to old name " + origPackage.name); 8280 } 8281 break; 8282 } 8283 } 8284 } 8285 } 8286 8287 if (mTransferedPackages.contains(pkg.packageName)) { 8288 Slog.w(TAG, "Package " + pkg.packageName 8289 + " was transferred to another, but its .apk remains"); 8290 } 8291 8292 // See comments in nonMutatedPs declaration 8293 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8294 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8295 if (foundPs != null) { 8296 nonMutatedPs = new PackageSetting(foundPs); 8297 } 8298 } 8299 8300 // Just create the setting, don't add it yet. For already existing packages 8301 // the PkgSetting exists already and doesn't have to be created. 8302 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8303 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8304 pkg.applicationInfo.primaryCpuAbi, 8305 pkg.applicationInfo.secondaryCpuAbi, 8306 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8307 user, false); 8308 if (pkgSetting == null) { 8309 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8310 "Creating application package " + pkg.packageName + " failed"); 8311 } 8312 8313 if (pkgSetting.origPackage != null) { 8314 // If we are first transitioning from an original package, 8315 // fix up the new package's name now. We need to do this after 8316 // looking up the package under its new name, so getPackageLP 8317 // can take care of fiddling things correctly. 8318 pkg.setPackageName(origPackage.name); 8319 8320 // File a report about this. 8321 String msg = "New package " + pkgSetting.realName 8322 + " renamed to replace old package " + pkgSetting.name; 8323 reportSettingsProblem(Log.WARN, msg); 8324 8325 // Make a note of it. 8326 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8327 mTransferedPackages.add(origPackage.name); 8328 } 8329 8330 // No longer need to retain this. 8331 pkgSetting.origPackage = null; 8332 } 8333 8334 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8335 // Make a note of it. 8336 mTransferedPackages.add(pkg.packageName); 8337 } 8338 8339 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8340 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8341 } 8342 8343 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8344 // Check all shared libraries and map to their actual file path. 8345 // We only do this here for apps not on a system dir, because those 8346 // are the only ones that can fail an install due to this. We 8347 // will take care of the system apps by updating all of their 8348 // library paths after the scan is done. 8349 updateSharedLibrariesLPw(pkg, null); 8350 } 8351 8352 if (mFoundPolicyFile) { 8353 SELinuxMMAC.assignSeinfoValue(pkg); 8354 } 8355 8356 pkg.applicationInfo.uid = pkgSetting.appId; 8357 pkg.mExtras = pkgSetting; 8358 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8359 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8360 // We just determined the app is signed correctly, so bring 8361 // over the latest parsed certs. 8362 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8363 } else { 8364 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8365 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8366 "Package " + pkg.packageName + " upgrade keys do not match the " 8367 + "previously installed version"); 8368 } else { 8369 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8370 String msg = "System package " + pkg.packageName 8371 + " signature changed; retaining data."; 8372 reportSettingsProblem(Log.WARN, msg); 8373 } 8374 } 8375 } else { 8376 try { 8377 verifySignaturesLP(pkgSetting, pkg); 8378 // We just determined the app is signed correctly, so bring 8379 // over the latest parsed certs. 8380 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8381 } catch (PackageManagerException e) { 8382 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8383 throw e; 8384 } 8385 // The signature has changed, but this package is in the system 8386 // image... let's recover! 8387 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8388 // However... if this package is part of a shared user, but it 8389 // doesn't match the signature of the shared user, let's fail. 8390 // What this means is that you can't change the signatures 8391 // associated with an overall shared user, which doesn't seem all 8392 // that unreasonable. 8393 if (pkgSetting.sharedUser != null) { 8394 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8395 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8396 throw new PackageManagerException( 8397 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8398 "Signature mismatch for shared user: " 8399 + pkgSetting.sharedUser); 8400 } 8401 } 8402 // File a report about this. 8403 String msg = "System package " + pkg.packageName 8404 + " signature changed; retaining data."; 8405 reportSettingsProblem(Log.WARN, msg); 8406 } 8407 } 8408 // Verify that this new package doesn't have any content providers 8409 // that conflict with existing packages. Only do this if the 8410 // package isn't already installed, since we don't want to break 8411 // things that are installed. 8412 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8413 final int N = pkg.providers.size(); 8414 int i; 8415 for (i=0; i<N; i++) { 8416 PackageParser.Provider p = pkg.providers.get(i); 8417 if (p.info.authority != null) { 8418 String names[] = p.info.authority.split(";"); 8419 for (int j = 0; j < names.length; j++) { 8420 if (mProvidersByAuthority.containsKey(names[j])) { 8421 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8422 final String otherPackageName = 8423 ((other != null && other.getComponentName() != null) ? 8424 other.getComponentName().getPackageName() : "?"); 8425 throw new PackageManagerException( 8426 INSTALL_FAILED_CONFLICTING_PROVIDER, 8427 "Can't install because provider name " + names[j] 8428 + " (in package " + pkg.applicationInfo.packageName 8429 + ") is already used by " + otherPackageName); 8430 } 8431 } 8432 } 8433 } 8434 } 8435 8436 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8437 // This package wants to adopt ownership of permissions from 8438 // another package. 8439 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8440 final String origName = pkg.mAdoptPermissions.get(i); 8441 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8442 if (orig != null) { 8443 if (verifyPackageUpdateLPr(orig, pkg)) { 8444 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8445 + pkg.packageName); 8446 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8447 } 8448 } 8449 } 8450 } 8451 } 8452 8453 final String pkgName = pkg.packageName; 8454 8455 final long scanFileTime = getLastModifiedTime(pkg, scanFile); 8456 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8457 pkg.applicationInfo.processName = fixProcessName( 8458 pkg.applicationInfo.packageName, 8459 pkg.applicationInfo.processName, 8460 pkg.applicationInfo.uid); 8461 8462 if (pkg != mPlatformPackage) { 8463 // Get all of our default paths setup 8464 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8465 } 8466 8467 final String path = scanFile.getPath(); 8468 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8469 8470 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8471 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8472 8473 // Some system apps still use directory structure for native libraries 8474 // in which case we might end up not detecting abi solely based on apk 8475 // structure. Try to detect abi based on directory structure. 8476 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8477 pkg.applicationInfo.primaryCpuAbi == null) { 8478 setBundledAppAbisAndRoots(pkg, pkgSetting); 8479 setNativeLibraryPaths(pkg); 8480 } 8481 8482 } else { 8483 if ((scanFlags & SCAN_MOVE) != 0) { 8484 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8485 // but we already have this packages package info in the PackageSetting. We just 8486 // use that and derive the native library path based on the new codepath. 8487 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8488 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8489 } 8490 8491 // Set native library paths again. For moves, the path will be updated based on the 8492 // ABIs we've determined above. For non-moves, the path will be updated based on the 8493 // ABIs we determined during compilation, but the path will depend on the final 8494 // package path (after the rename away from the stage path). 8495 setNativeLibraryPaths(pkg); 8496 } 8497 8498 // This is a special case for the "system" package, where the ABI is 8499 // dictated by the zygote configuration (and init.rc). We should keep track 8500 // of this ABI so that we can deal with "normal" applications that run under 8501 // the same UID correctly. 8502 if (mPlatformPackage == pkg) { 8503 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8504 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8505 } 8506 8507 // If there's a mismatch between the abi-override in the package setting 8508 // and the abiOverride specified for the install. Warn about this because we 8509 // would've already compiled the app without taking the package setting into 8510 // account. 8511 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8512 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8513 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8514 " for package " + pkg.packageName); 8515 } 8516 } 8517 8518 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8519 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8520 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8521 8522 // Copy the derived override back to the parsed package, so that we can 8523 // update the package settings accordingly. 8524 pkg.cpuAbiOverride = cpuAbiOverride; 8525 8526 if (DEBUG_ABI_SELECTION) { 8527 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8528 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8529 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8530 } 8531 8532 // Push the derived path down into PackageSettings so we know what to 8533 // clean up at uninstall time. 8534 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8535 8536 if (DEBUG_ABI_SELECTION) { 8537 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8538 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8539 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8540 } 8541 8542 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8543 // We don't do this here during boot because we can do it all 8544 // at once after scanning all existing packages. 8545 // 8546 // We also do this *before* we perform dexopt on this package, so that 8547 // we can avoid redundant dexopts, and also to make sure we've got the 8548 // code and package path correct. 8549 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8550 pkg, true /* boot complete */); 8551 } 8552 8553 if (mFactoryTest && pkg.requestedPermissions.contains( 8554 android.Manifest.permission.FACTORY_TEST)) { 8555 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8556 } 8557 8558 ArrayList<PackageParser.Package> clientLibPkgs = null; 8559 8560 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8561 if (nonMutatedPs != null) { 8562 synchronized (mPackages) { 8563 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8564 } 8565 } 8566 return pkg; 8567 } 8568 8569 // Only privileged apps and updated privileged apps can add child packages. 8570 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8571 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8572 throw new PackageManagerException("Only privileged apps and updated " 8573 + "privileged apps can add child packages. Ignoring package " 8574 + pkg.packageName); 8575 } 8576 final int childCount = pkg.childPackages.size(); 8577 for (int i = 0; i < childCount; i++) { 8578 PackageParser.Package childPkg = pkg.childPackages.get(i); 8579 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8580 childPkg.packageName)) { 8581 throw new PackageManagerException("Cannot override a child package of " 8582 + "another disabled system app. Ignoring package " + pkg.packageName); 8583 } 8584 } 8585 } 8586 8587 // writer 8588 synchronized (mPackages) { 8589 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8590 // Only system apps can add new shared libraries. 8591 if (pkg.libraryNames != null) { 8592 for (int i=0; i<pkg.libraryNames.size(); i++) { 8593 String name = pkg.libraryNames.get(i); 8594 boolean allowed = false; 8595 if (pkg.isUpdatedSystemApp()) { 8596 // New library entries can only be added through the 8597 // system image. This is important to get rid of a lot 8598 // of nasty edge cases: for example if we allowed a non- 8599 // system update of the app to add a library, then uninstalling 8600 // the update would make the library go away, and assumptions 8601 // we made such as through app install filtering would now 8602 // have allowed apps on the device which aren't compatible 8603 // with it. Better to just have the restriction here, be 8604 // conservative, and create many fewer cases that can negatively 8605 // impact the user experience. 8606 final PackageSetting sysPs = mSettings 8607 .getDisabledSystemPkgLPr(pkg.packageName); 8608 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8609 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8610 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8611 allowed = true; 8612 break; 8613 } 8614 } 8615 } 8616 } else { 8617 allowed = true; 8618 } 8619 if (allowed) { 8620 if (!mSharedLibraries.containsKey(name)) { 8621 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8622 } else if (!name.equals(pkg.packageName)) { 8623 Slog.w(TAG, "Package " + pkg.packageName + " library " 8624 + name + " already exists; skipping"); 8625 } 8626 } else { 8627 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8628 + name + " that is not declared on system image; skipping"); 8629 } 8630 } 8631 if ((scanFlags & SCAN_BOOTING) == 0) { 8632 // If we are not booting, we need to update any applications 8633 // that are clients of our shared library. If we are booting, 8634 // this will all be done once the scan is complete. 8635 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8636 } 8637 } 8638 } 8639 } 8640 8641 if ((scanFlags & SCAN_BOOTING) != 0) { 8642 // No apps can run during boot scan, so they don't need to be frozen 8643 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8644 // Caller asked to not kill app, so it's probably not frozen 8645 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8646 // Caller asked us to ignore frozen check for some reason; they 8647 // probably didn't know the package name 8648 } else { 8649 // We're doing major surgery on this package, so it better be frozen 8650 // right now to keep it from launching 8651 checkPackageFrozen(pkgName); 8652 } 8653 8654 // Also need to kill any apps that are dependent on the library. 8655 if (clientLibPkgs != null) { 8656 for (int i=0; i<clientLibPkgs.size(); i++) { 8657 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8658 killApplication(clientPkg.applicationInfo.packageName, 8659 clientPkg.applicationInfo.uid, "update lib"); 8660 } 8661 } 8662 8663 // Make sure we're not adding any bogus keyset info 8664 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8665 ksms.assertScannedPackageValid(pkg); 8666 8667 // writer 8668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8669 8670 boolean createIdmapFailed = false; 8671 synchronized (mPackages) { 8672 // We don't expect installation to fail beyond this point 8673 8674 if (pkgSetting.pkg != null) { 8675 // Note that |user| might be null during the initial boot scan. If a codePath 8676 // for an app has changed during a boot scan, it's due to an app update that's 8677 // part of the system partition and marker changes must be applied to all users. 8678 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8679 (user != null) ? user : UserHandle.ALL); 8680 } 8681 8682 // Add the new setting to mSettings 8683 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8684 // Add the new setting to mPackages 8685 mPackages.put(pkg.applicationInfo.packageName, pkg); 8686 // Make sure we don't accidentally delete its data. 8687 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8688 while (iter.hasNext()) { 8689 PackageCleanItem item = iter.next(); 8690 if (pkgName.equals(item.packageName)) { 8691 iter.remove(); 8692 } 8693 } 8694 8695 // Take care of first install / last update times. 8696 if (currentTime != 0) { 8697 if (pkgSetting.firstInstallTime == 0) { 8698 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8699 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8700 pkgSetting.lastUpdateTime = currentTime; 8701 } 8702 } else if (pkgSetting.firstInstallTime == 0) { 8703 // We need *something*. Take time time stamp of the file. 8704 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8705 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8706 if (scanFileTime != pkgSetting.timeStamp) { 8707 // A package on the system image has changed; consider this 8708 // to be an update. 8709 pkgSetting.lastUpdateTime = scanFileTime; 8710 } 8711 } 8712 8713 // Add the package's KeySets to the global KeySetManagerService 8714 ksms.addScannedPackageLPw(pkg); 8715 8716 int N = pkg.providers.size(); 8717 StringBuilder r = null; 8718 int i; 8719 for (i=0; i<N; i++) { 8720 PackageParser.Provider p = pkg.providers.get(i); 8721 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8722 p.info.processName, pkg.applicationInfo.uid); 8723 mProviders.addProvider(p); 8724 p.syncable = p.info.isSyncable; 8725 if (p.info.authority != null) { 8726 String names[] = p.info.authority.split(";"); 8727 p.info.authority = null; 8728 for (int j = 0; j < names.length; j++) { 8729 if (j == 1 && p.syncable) { 8730 // We only want the first authority for a provider to possibly be 8731 // syncable, so if we already added this provider using a different 8732 // authority clear the syncable flag. We copy the provider before 8733 // changing it because the mProviders object contains a reference 8734 // to a provider that we don't want to change. 8735 // Only do this for the second authority since the resulting provider 8736 // object can be the same for all future authorities for this provider. 8737 p = new PackageParser.Provider(p); 8738 p.syncable = false; 8739 } 8740 if (!mProvidersByAuthority.containsKey(names[j])) { 8741 mProvidersByAuthority.put(names[j], p); 8742 if (p.info.authority == null) { 8743 p.info.authority = names[j]; 8744 } else { 8745 p.info.authority = p.info.authority + ";" + names[j]; 8746 } 8747 if (DEBUG_PACKAGE_SCANNING) { 8748 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8749 Log.d(TAG, "Registered content provider: " + names[j] 8750 + ", className = " + p.info.name + ", isSyncable = " 8751 + p.info.isSyncable); 8752 } 8753 } else { 8754 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8755 Slog.w(TAG, "Skipping provider name " + names[j] + 8756 " (in package " + pkg.applicationInfo.packageName + 8757 "): name already used by " 8758 + ((other != null && other.getComponentName() != null) 8759 ? other.getComponentName().getPackageName() : "?")); 8760 } 8761 } 8762 } 8763 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8764 if (r == null) { 8765 r = new StringBuilder(256); 8766 } else { 8767 r.append(' '); 8768 } 8769 r.append(p.info.name); 8770 } 8771 } 8772 if (r != null) { 8773 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8774 } 8775 8776 N = pkg.services.size(); 8777 r = null; 8778 for (i=0; i<N; i++) { 8779 PackageParser.Service s = pkg.services.get(i); 8780 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8781 s.info.processName, pkg.applicationInfo.uid); 8782 mServices.addService(s); 8783 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8784 if (r == null) { 8785 r = new StringBuilder(256); 8786 } else { 8787 r.append(' '); 8788 } 8789 r.append(s.info.name); 8790 } 8791 } 8792 if (r != null) { 8793 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8794 } 8795 8796 N = pkg.receivers.size(); 8797 r = null; 8798 for (i=0; i<N; i++) { 8799 PackageParser.Activity a = pkg.receivers.get(i); 8800 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8801 a.info.processName, pkg.applicationInfo.uid); 8802 mReceivers.addActivity(a, "receiver"); 8803 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8804 if (r == null) { 8805 r = new StringBuilder(256); 8806 } else { 8807 r.append(' '); 8808 } 8809 r.append(a.info.name); 8810 } 8811 } 8812 if (r != null) { 8813 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8814 } 8815 8816 N = pkg.activities.size(); 8817 r = null; 8818 for (i=0; i<N; i++) { 8819 PackageParser.Activity a = pkg.activities.get(i); 8820 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8821 a.info.processName, pkg.applicationInfo.uid); 8822 mActivities.addActivity(a, "activity"); 8823 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8824 if (r == null) { 8825 r = new StringBuilder(256); 8826 } else { 8827 r.append(' '); 8828 } 8829 r.append(a.info.name); 8830 } 8831 } 8832 if (r != null) { 8833 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8834 } 8835 8836 N = pkg.permissionGroups.size(); 8837 r = null; 8838 for (i=0; i<N; i++) { 8839 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8840 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8841 if (cur == null) { 8842 mPermissionGroups.put(pg.info.name, pg); 8843 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8844 if (r == null) { 8845 r = new StringBuilder(256); 8846 } else { 8847 r.append(' '); 8848 } 8849 r.append(pg.info.name); 8850 } 8851 } else { 8852 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8853 + pg.info.packageName + " ignored: original from " 8854 + cur.info.packageName); 8855 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8856 if (r == null) { 8857 r = new StringBuilder(256); 8858 } else { 8859 r.append(' '); 8860 } 8861 r.append("DUP:"); 8862 r.append(pg.info.name); 8863 } 8864 } 8865 } 8866 if (r != null) { 8867 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8868 } 8869 8870 N = pkg.permissions.size(); 8871 r = null; 8872 for (i=0; i<N; i++) { 8873 PackageParser.Permission p = pkg.permissions.get(i); 8874 8875 // Assume by default that we did not install this permission into the system. 8876 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8877 8878 // Now that permission groups have a special meaning, we ignore permission 8879 // groups for legacy apps to prevent unexpected behavior. In particular, 8880 // permissions for one app being granted to someone just becase they happen 8881 // to be in a group defined by another app (before this had no implications). 8882 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8883 p.group = mPermissionGroups.get(p.info.group); 8884 // Warn for a permission in an unknown group. 8885 if (p.info.group != null && p.group == null) { 8886 Slog.w(TAG, "Permission " + p.info.name + " from package " 8887 + p.info.packageName + " in an unknown group " + p.info.group); 8888 } 8889 } 8890 8891 ArrayMap<String, BasePermission> permissionMap = 8892 p.tree ? mSettings.mPermissionTrees 8893 : mSettings.mPermissions; 8894 BasePermission bp = permissionMap.get(p.info.name); 8895 8896 // Allow system apps to redefine non-system permissions 8897 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8898 final boolean currentOwnerIsSystem = (bp.perm != null 8899 && isSystemApp(bp.perm.owner)); 8900 if (isSystemApp(p.owner)) { 8901 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8902 // It's a built-in permission and no owner, take ownership now 8903 bp.packageSetting = pkgSetting; 8904 bp.perm = p; 8905 bp.uid = pkg.applicationInfo.uid; 8906 bp.sourcePackage = p.info.packageName; 8907 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8908 } else if (!currentOwnerIsSystem) { 8909 String msg = "New decl " + p.owner + " of permission " 8910 + p.info.name + " is system; overriding " + bp.sourcePackage; 8911 reportSettingsProblem(Log.WARN, msg); 8912 bp = null; 8913 } 8914 } 8915 } 8916 8917 if (bp == null) { 8918 bp = new BasePermission(p.info.name, p.info.packageName, 8919 BasePermission.TYPE_NORMAL); 8920 permissionMap.put(p.info.name, bp); 8921 } 8922 8923 if (bp.perm == null) { 8924 if (bp.sourcePackage == null 8925 || bp.sourcePackage.equals(p.info.packageName)) { 8926 BasePermission tree = findPermissionTreeLP(p.info.name); 8927 if (tree == null 8928 || tree.sourcePackage.equals(p.info.packageName)) { 8929 bp.packageSetting = pkgSetting; 8930 bp.perm = p; 8931 bp.uid = pkg.applicationInfo.uid; 8932 bp.sourcePackage = p.info.packageName; 8933 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8934 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8935 if (r == null) { 8936 r = new StringBuilder(256); 8937 } else { 8938 r.append(' '); 8939 } 8940 r.append(p.info.name); 8941 } 8942 } else { 8943 Slog.w(TAG, "Permission " + p.info.name + " from package " 8944 + p.info.packageName + " ignored: base tree " 8945 + tree.name + " is from package " 8946 + tree.sourcePackage); 8947 } 8948 } else { 8949 Slog.w(TAG, "Permission " + p.info.name + " from package " 8950 + p.info.packageName + " ignored: original from " 8951 + bp.sourcePackage); 8952 } 8953 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8954 if (r == null) { 8955 r = new StringBuilder(256); 8956 } else { 8957 r.append(' '); 8958 } 8959 r.append("DUP:"); 8960 r.append(p.info.name); 8961 } 8962 if (bp.perm == p) { 8963 bp.protectionLevel = p.info.protectionLevel; 8964 } 8965 } 8966 8967 if (r != null) { 8968 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8969 } 8970 8971 N = pkg.instrumentation.size(); 8972 r = null; 8973 for (i=0; i<N; i++) { 8974 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8975 a.info.packageName = pkg.applicationInfo.packageName; 8976 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8977 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8978 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8979 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8980 a.info.dataDir = pkg.applicationInfo.dataDir; 8981 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8982 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8983 8984 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8985 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8986 mInstrumentation.put(a.getComponentName(), a); 8987 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8988 if (r == null) { 8989 r = new StringBuilder(256); 8990 } else { 8991 r.append(' '); 8992 } 8993 r.append(a.info.name); 8994 } 8995 } 8996 if (r != null) { 8997 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8998 } 8999 9000 if (pkg.protectedBroadcasts != null) { 9001 N = pkg.protectedBroadcasts.size(); 9002 for (i=0; i<N; i++) { 9003 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 9004 } 9005 } 9006 9007 pkgSetting.setTimeStamp(scanFileTime); 9008 9009 // Create idmap files for pairs of (packages, overlay packages). 9010 // Note: "android", ie framework-res.apk, is handled by native layers. 9011 if (pkg.mOverlayTarget != null) { 9012 // This is an overlay package. 9013 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 9014 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 9015 mOverlays.put(pkg.mOverlayTarget, 9016 new ArrayMap<String, PackageParser.Package>()); 9017 } 9018 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 9019 map.put(pkg.packageName, pkg); 9020 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9021 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9022 createIdmapFailed = true; 9023 } 9024 } 9025 } else if (mOverlays.containsKey(pkg.packageName) && 9026 !pkg.packageName.equals("android")) { 9027 // This is a regular package, with one or more known overlay packages. 9028 createIdmapsForPackageLI(pkg); 9029 } 9030 } 9031 9032 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9033 9034 if (createIdmapFailed) { 9035 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9036 "scanPackageLI failed to createIdmap"); 9037 } 9038 return pkg; 9039 } 9040 9041 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9042 PackageParser.Package update, UserHandle user) { 9043 if (existing.applicationInfo == null || update.applicationInfo == null) { 9044 // This isn't due to an app installation. 9045 return; 9046 } 9047 9048 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9049 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9050 9051 // The codePath hasn't changed, so there's nothing for us to do. 9052 if (Objects.equals(oldCodePath, newCodePath)) { 9053 return; 9054 } 9055 9056 File canonicalNewCodePath; 9057 try { 9058 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9059 } catch (IOException e) { 9060 Slog.w(TAG, "Failed to get canonical path.", e); 9061 return; 9062 } 9063 9064 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9065 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9066 // that the last component of the path (i.e, the name) doesn't need canonicalization 9067 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9068 // but may change in the future. Hopefully this function won't exist at that point. 9069 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9070 oldCodePath.getName()); 9071 9072 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9073 // with "@". 9074 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9075 if (!oldMarkerPrefix.endsWith("@")) { 9076 oldMarkerPrefix += "@"; 9077 } 9078 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9079 if (!newMarkerPrefix.endsWith("@")) { 9080 newMarkerPrefix += "@"; 9081 } 9082 9083 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9084 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9085 for (String updatedPath : updatedPaths) { 9086 String updatedPathName = new File(updatedPath).getName(); 9087 markerSuffixes.add(updatedPathName.replace('/', '@')); 9088 } 9089 9090 for (int userId : resolveUserIds(user.getIdentifier())) { 9091 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9092 9093 for (String markerSuffix : markerSuffixes) { 9094 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9095 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9096 if (oldForeignUseMark.exists()) { 9097 try { 9098 Os.rename(oldForeignUseMark.getAbsolutePath(), 9099 newForeignUseMark.getAbsolutePath()); 9100 } catch (ErrnoException e) { 9101 Slog.w(TAG, "Failed to rename foreign use marker", e); 9102 oldForeignUseMark.delete(); 9103 } 9104 } 9105 } 9106 } 9107 } 9108 9109 /** 9110 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9111 * is derived purely on the basis of the contents of {@code scanFile} and 9112 * {@code cpuAbiOverride}. 9113 * 9114 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9115 */ 9116 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9117 String cpuAbiOverride, boolean extractLibs) 9118 throws PackageManagerException { 9119 // TODO: We can probably be smarter about this stuff. For installed apps, 9120 // we can calculate this information at install time once and for all. For 9121 // system apps, we can probably assume that this information doesn't change 9122 // after the first boot scan. As things stand, we do lots of unnecessary work. 9123 9124 // Give ourselves some initial paths; we'll come back for another 9125 // pass once we've determined ABI below. 9126 setNativeLibraryPaths(pkg); 9127 9128 // We would never need to extract libs for forward-locked and external packages, 9129 // since the container service will do it for us. We shouldn't attempt to 9130 // extract libs from system app when it was not updated. 9131 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9132 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9133 extractLibs = false; 9134 } 9135 9136 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9137 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9138 9139 NativeLibraryHelper.Handle handle = null; 9140 try { 9141 handle = NativeLibraryHelper.Handle.create(pkg); 9142 // TODO(multiArch): This can be null for apps that didn't go through the 9143 // usual installation process. We can calculate it again, like we 9144 // do during install time. 9145 // 9146 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9147 // unnecessary. 9148 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9149 9150 // Null out the abis so that they can be recalculated. 9151 pkg.applicationInfo.primaryCpuAbi = null; 9152 pkg.applicationInfo.secondaryCpuAbi = null; 9153 if (isMultiArch(pkg.applicationInfo)) { 9154 // Warn if we've set an abiOverride for multi-lib packages.. 9155 // By definition, we need to copy both 32 and 64 bit libraries for 9156 // such packages. 9157 if (pkg.cpuAbiOverride != null 9158 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9159 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9160 } 9161 9162 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9163 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9164 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9165 if (extractLibs) { 9166 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9167 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9168 useIsaSpecificSubdirs); 9169 } else { 9170 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9171 } 9172 } 9173 9174 maybeThrowExceptionForMultiArchCopy( 9175 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9176 9177 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9178 if (extractLibs) { 9179 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9180 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9181 useIsaSpecificSubdirs); 9182 } else { 9183 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9184 } 9185 } 9186 9187 maybeThrowExceptionForMultiArchCopy( 9188 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9189 9190 if (abi64 >= 0) { 9191 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9192 } 9193 9194 if (abi32 >= 0) { 9195 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9196 if (abi64 >= 0) { 9197 if (pkg.use32bitAbi) { 9198 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9199 pkg.applicationInfo.primaryCpuAbi = abi; 9200 } else { 9201 pkg.applicationInfo.secondaryCpuAbi = abi; 9202 } 9203 } else { 9204 pkg.applicationInfo.primaryCpuAbi = abi; 9205 } 9206 } 9207 9208 } else { 9209 String[] abiList = (cpuAbiOverride != null) ? 9210 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9211 9212 // Enable gross and lame hacks for apps that are built with old 9213 // SDK tools. We must scan their APKs for renderscript bitcode and 9214 // not launch them if it's present. Don't bother checking on devices 9215 // that don't have 64 bit support. 9216 boolean needsRenderScriptOverride = false; 9217 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9218 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9219 abiList = Build.SUPPORTED_32_BIT_ABIS; 9220 needsRenderScriptOverride = true; 9221 } 9222 9223 final int copyRet; 9224 if (extractLibs) { 9225 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9226 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9227 } else { 9228 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9229 } 9230 9231 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9232 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9233 "Error unpackaging native libs for app, errorCode=" + copyRet); 9234 } 9235 9236 if (copyRet >= 0) { 9237 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9238 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9239 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9240 } else if (needsRenderScriptOverride) { 9241 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9242 } 9243 } 9244 } catch (IOException ioe) { 9245 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9246 } finally { 9247 IoUtils.closeQuietly(handle); 9248 } 9249 9250 // Now that we've calculated the ABIs and determined if it's an internal app, 9251 // we will go ahead and populate the nativeLibraryPath. 9252 setNativeLibraryPaths(pkg); 9253 } 9254 9255 /** 9256 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9257 * i.e, so that all packages can be run inside a single process if required. 9258 * 9259 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9260 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9261 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9262 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9263 * updating a package that belongs to a shared user. 9264 * 9265 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9266 * adds unnecessary complexity. 9267 */ 9268 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9269 PackageParser.Package scannedPackage, boolean bootComplete) { 9270 String requiredInstructionSet = null; 9271 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9272 requiredInstructionSet = VMRuntime.getInstructionSet( 9273 scannedPackage.applicationInfo.primaryCpuAbi); 9274 } 9275 9276 PackageSetting requirer = null; 9277 for (PackageSetting ps : packagesForUser) { 9278 // If packagesForUser contains scannedPackage, we skip it. This will happen 9279 // when scannedPackage is an update of an existing package. Without this check, 9280 // we will never be able to change the ABI of any package belonging to a shared 9281 // user, even if it's compatible with other packages. 9282 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9283 if (ps.primaryCpuAbiString == null) { 9284 continue; 9285 } 9286 9287 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9288 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9289 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9290 // this but there's not much we can do. 9291 String errorMessage = "Instruction set mismatch, " 9292 + ((requirer == null) ? "[caller]" : requirer) 9293 + " requires " + requiredInstructionSet + " whereas " + ps 9294 + " requires " + instructionSet; 9295 Slog.w(TAG, errorMessage); 9296 } 9297 9298 if (requiredInstructionSet == null) { 9299 requiredInstructionSet = instructionSet; 9300 requirer = ps; 9301 } 9302 } 9303 } 9304 9305 if (requiredInstructionSet != null) { 9306 String adjustedAbi; 9307 if (requirer != null) { 9308 // requirer != null implies that either scannedPackage was null or that scannedPackage 9309 // did not require an ABI, in which case we have to adjust scannedPackage to match 9310 // the ABI of the set (which is the same as requirer's ABI) 9311 adjustedAbi = requirer.primaryCpuAbiString; 9312 if (scannedPackage != null) { 9313 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9314 } 9315 } else { 9316 // requirer == null implies that we're updating all ABIs in the set to 9317 // match scannedPackage. 9318 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9319 } 9320 9321 for (PackageSetting ps : packagesForUser) { 9322 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9323 if (ps.primaryCpuAbiString != null) { 9324 continue; 9325 } 9326 9327 ps.primaryCpuAbiString = adjustedAbi; 9328 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9329 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9330 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9331 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9332 + " (requirer=" 9333 + (requirer == null ? "null" : requirer.pkg.packageName) 9334 + ", scannedPackage=" 9335 + (scannedPackage != null ? scannedPackage.packageName : "null") 9336 + ")"); 9337 try { 9338 mInstaller.rmdex(ps.codePathString, 9339 getDexCodeInstructionSet(getPreferredInstructionSet())); 9340 } catch (InstallerException ignored) { 9341 } 9342 } 9343 } 9344 } 9345 } 9346 } 9347 9348 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9349 synchronized (mPackages) { 9350 mResolverReplaced = true; 9351 // Set up information for custom user intent resolution activity. 9352 mResolveActivity.applicationInfo = pkg.applicationInfo; 9353 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9354 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9355 mResolveActivity.processName = pkg.applicationInfo.packageName; 9356 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9357 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9358 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9359 mResolveActivity.theme = 0; 9360 mResolveActivity.exported = true; 9361 mResolveActivity.enabled = true; 9362 mResolveInfo.activityInfo = mResolveActivity; 9363 mResolveInfo.priority = 0; 9364 mResolveInfo.preferredOrder = 0; 9365 mResolveInfo.match = 0; 9366 mResolveComponentName = mCustomResolverComponentName; 9367 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9368 mResolveComponentName); 9369 } 9370 } 9371 9372 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9373 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9374 9375 // Set up information for ephemeral installer activity 9376 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9377 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9378 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9379 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9380 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9381 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9382 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9383 mEphemeralInstallerActivity.theme = 0; 9384 mEphemeralInstallerActivity.exported = true; 9385 mEphemeralInstallerActivity.enabled = true; 9386 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9387 mEphemeralInstallerInfo.priority = 0; 9388 mEphemeralInstallerInfo.preferredOrder = 0; 9389 mEphemeralInstallerInfo.match = 0; 9390 9391 if (DEBUG_EPHEMERAL) { 9392 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9393 } 9394 } 9395 9396 private static String calculateBundledApkRoot(final String codePathString) { 9397 final File codePath = new File(codePathString); 9398 final File codeRoot; 9399 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9400 codeRoot = Environment.getRootDirectory(); 9401 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9402 codeRoot = Environment.getOemDirectory(); 9403 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9404 codeRoot = Environment.getVendorDirectory(); 9405 } else { 9406 // Unrecognized code path; take its top real segment as the apk root: 9407 // e.g. /something/app/blah.apk => /something 9408 try { 9409 File f = codePath.getCanonicalFile(); 9410 File parent = f.getParentFile(); // non-null because codePath is a file 9411 File tmp; 9412 while ((tmp = parent.getParentFile()) != null) { 9413 f = parent; 9414 parent = tmp; 9415 } 9416 codeRoot = f; 9417 Slog.w(TAG, "Unrecognized code path " 9418 + codePath + " - using " + codeRoot); 9419 } catch (IOException e) { 9420 // Can't canonicalize the code path -- shenanigans? 9421 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9422 return Environment.getRootDirectory().getPath(); 9423 } 9424 } 9425 return codeRoot.getPath(); 9426 } 9427 9428 /** 9429 * Derive and set the location of native libraries for the given package, 9430 * which varies depending on where and how the package was installed. 9431 */ 9432 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9433 final ApplicationInfo info = pkg.applicationInfo; 9434 final String codePath = pkg.codePath; 9435 final File codeFile = new File(codePath); 9436 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9437 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9438 9439 info.nativeLibraryRootDir = null; 9440 info.nativeLibraryRootRequiresIsa = false; 9441 info.nativeLibraryDir = null; 9442 info.secondaryNativeLibraryDir = null; 9443 9444 if (isApkFile(codeFile)) { 9445 // Monolithic install 9446 if (bundledApp) { 9447 // If "/system/lib64/apkname" exists, assume that is the per-package 9448 // native library directory to use; otherwise use "/system/lib/apkname". 9449 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9450 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9451 getPrimaryInstructionSet(info)); 9452 9453 // This is a bundled system app so choose the path based on the ABI. 9454 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9455 // is just the default path. 9456 final String apkName = deriveCodePathName(codePath); 9457 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9458 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9459 apkName).getAbsolutePath(); 9460 9461 if (info.secondaryCpuAbi != null) { 9462 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9463 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9464 secondaryLibDir, apkName).getAbsolutePath(); 9465 } 9466 } else if (asecApp) { 9467 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9468 .getAbsolutePath(); 9469 } else { 9470 final String apkName = deriveCodePathName(codePath); 9471 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9472 .getAbsolutePath(); 9473 } 9474 9475 info.nativeLibraryRootRequiresIsa = false; 9476 info.nativeLibraryDir = info.nativeLibraryRootDir; 9477 } else { 9478 // Cluster install 9479 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9480 info.nativeLibraryRootRequiresIsa = true; 9481 9482 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9483 getPrimaryInstructionSet(info)).getAbsolutePath(); 9484 9485 if (info.secondaryCpuAbi != null) { 9486 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9487 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9488 } 9489 } 9490 } 9491 9492 /** 9493 * Calculate the abis and roots for a bundled app. These can uniquely 9494 * be determined from the contents of the system partition, i.e whether 9495 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9496 * of this information, and instead assume that the system was built 9497 * sensibly. 9498 */ 9499 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9500 PackageSetting pkgSetting) { 9501 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9502 9503 // If "/system/lib64/apkname" exists, assume that is the per-package 9504 // native library directory to use; otherwise use "/system/lib/apkname". 9505 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9506 setBundledAppAbi(pkg, apkRoot, apkName); 9507 // pkgSetting might be null during rescan following uninstall of updates 9508 // to a bundled app, so accommodate that possibility. The settings in 9509 // that case will be established later from the parsed package. 9510 // 9511 // If the settings aren't null, sync them up with what we've just derived. 9512 // note that apkRoot isn't stored in the package settings. 9513 if (pkgSetting != null) { 9514 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9515 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9516 } 9517 } 9518 9519 /** 9520 * Deduces the ABI of a bundled app and sets the relevant fields on the 9521 * parsed pkg object. 9522 * 9523 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9524 * under which system libraries are installed. 9525 * @param apkName the name of the installed package. 9526 */ 9527 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9528 final File codeFile = new File(pkg.codePath); 9529 9530 final boolean has64BitLibs; 9531 final boolean has32BitLibs; 9532 if (isApkFile(codeFile)) { 9533 // Monolithic install 9534 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9535 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9536 } else { 9537 // Cluster install 9538 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9539 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9540 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9541 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9542 has64BitLibs = (new File(rootDir, isa)).exists(); 9543 } else { 9544 has64BitLibs = false; 9545 } 9546 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9547 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9548 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9549 has32BitLibs = (new File(rootDir, isa)).exists(); 9550 } else { 9551 has32BitLibs = false; 9552 } 9553 } 9554 9555 if (has64BitLibs && !has32BitLibs) { 9556 // The package has 64 bit libs, but not 32 bit libs. Its primary 9557 // ABI should be 64 bit. We can safely assume here that the bundled 9558 // native libraries correspond to the most preferred ABI in the list. 9559 9560 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9561 pkg.applicationInfo.secondaryCpuAbi = null; 9562 } else if (has32BitLibs && !has64BitLibs) { 9563 // The package has 32 bit libs but not 64 bit libs. Its primary 9564 // ABI should be 32 bit. 9565 9566 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9567 pkg.applicationInfo.secondaryCpuAbi = null; 9568 } else if (has32BitLibs && has64BitLibs) { 9569 // The application has both 64 and 32 bit bundled libraries. We check 9570 // here that the app declares multiArch support, and warn if it doesn't. 9571 // 9572 // We will be lenient here and record both ABIs. The primary will be the 9573 // ABI that's higher on the list, i.e, a device that's configured to prefer 9574 // 64 bit apps will see a 64 bit primary ABI, 9575 9576 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9577 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9578 } 9579 9580 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9581 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9582 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9583 } else { 9584 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9585 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9586 } 9587 } else { 9588 pkg.applicationInfo.primaryCpuAbi = null; 9589 pkg.applicationInfo.secondaryCpuAbi = null; 9590 } 9591 } 9592 9593 private void killApplication(String pkgName, int appId, String reason) { 9594 killApplication(pkgName, appId, UserHandle.USER_ALL, reason); 9595 } 9596 9597 private void killApplication(String pkgName, int appId, int userId, String reason) { 9598 // Request the ActivityManager to kill the process(only for existing packages) 9599 // so that we do not end up in a confused state while the user is still using the older 9600 // version of the application while the new one gets installed. 9601 final long token = Binder.clearCallingIdentity(); 9602 try { 9603 IActivityManager am = ActivityManagerNative.getDefault(); 9604 if (am != null) { 9605 try { 9606 am.killApplication(pkgName, appId, userId, reason); 9607 } catch (RemoteException e) { 9608 } 9609 } 9610 } finally { 9611 Binder.restoreCallingIdentity(token); 9612 } 9613 } 9614 9615 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9616 // Remove the parent package setting 9617 PackageSetting ps = (PackageSetting) pkg.mExtras; 9618 if (ps != null) { 9619 removePackageLI(ps, chatty); 9620 } 9621 // Remove the child package setting 9622 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9623 for (int i = 0; i < childCount; i++) { 9624 PackageParser.Package childPkg = pkg.childPackages.get(i); 9625 ps = (PackageSetting) childPkg.mExtras; 9626 if (ps != null) { 9627 removePackageLI(ps, chatty); 9628 } 9629 } 9630 } 9631 9632 void removePackageLI(PackageSetting ps, boolean chatty) { 9633 if (DEBUG_INSTALL) { 9634 if (chatty) 9635 Log.d(TAG, "Removing package " + ps.name); 9636 } 9637 9638 // writer 9639 synchronized (mPackages) { 9640 mPackages.remove(ps.name); 9641 final PackageParser.Package pkg = ps.pkg; 9642 if (pkg != null) { 9643 cleanPackageDataStructuresLILPw(pkg, chatty); 9644 } 9645 } 9646 } 9647 9648 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9649 if (DEBUG_INSTALL) { 9650 if (chatty) 9651 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9652 } 9653 9654 // writer 9655 synchronized (mPackages) { 9656 // Remove the parent package 9657 mPackages.remove(pkg.applicationInfo.packageName); 9658 cleanPackageDataStructuresLILPw(pkg, chatty); 9659 9660 // Remove the child packages 9661 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9662 for (int i = 0; i < childCount; i++) { 9663 PackageParser.Package childPkg = pkg.childPackages.get(i); 9664 mPackages.remove(childPkg.applicationInfo.packageName); 9665 cleanPackageDataStructuresLILPw(childPkg, chatty); 9666 } 9667 } 9668 } 9669 9670 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9671 int N = pkg.providers.size(); 9672 StringBuilder r = null; 9673 int i; 9674 for (i=0; i<N; i++) { 9675 PackageParser.Provider p = pkg.providers.get(i); 9676 mProviders.removeProvider(p); 9677 if (p.info.authority == null) { 9678 9679 /* There was another ContentProvider with this authority when 9680 * this app was installed so this authority is null, 9681 * Ignore it as we don't have to unregister the provider. 9682 */ 9683 continue; 9684 } 9685 String names[] = p.info.authority.split(";"); 9686 for (int j = 0; j < names.length; j++) { 9687 if (mProvidersByAuthority.get(names[j]) == p) { 9688 mProvidersByAuthority.remove(names[j]); 9689 if (DEBUG_REMOVE) { 9690 if (chatty) 9691 Log.d(TAG, "Unregistered content provider: " + names[j] 9692 + ", className = " + p.info.name + ", isSyncable = " 9693 + p.info.isSyncable); 9694 } 9695 } 9696 } 9697 if (DEBUG_REMOVE && chatty) { 9698 if (r == null) { 9699 r = new StringBuilder(256); 9700 } else { 9701 r.append(' '); 9702 } 9703 r.append(p.info.name); 9704 } 9705 } 9706 if (r != null) { 9707 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9708 } 9709 9710 N = pkg.services.size(); 9711 r = null; 9712 for (i=0; i<N; i++) { 9713 PackageParser.Service s = pkg.services.get(i); 9714 mServices.removeService(s); 9715 if (chatty) { 9716 if (r == null) { 9717 r = new StringBuilder(256); 9718 } else { 9719 r.append(' '); 9720 } 9721 r.append(s.info.name); 9722 } 9723 } 9724 if (r != null) { 9725 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9726 } 9727 9728 N = pkg.receivers.size(); 9729 r = null; 9730 for (i=0; i<N; i++) { 9731 PackageParser.Activity a = pkg.receivers.get(i); 9732 mReceivers.removeActivity(a, "receiver"); 9733 if (DEBUG_REMOVE && chatty) { 9734 if (r == null) { 9735 r = new StringBuilder(256); 9736 } else { 9737 r.append(' '); 9738 } 9739 r.append(a.info.name); 9740 } 9741 } 9742 if (r != null) { 9743 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9744 } 9745 9746 N = pkg.activities.size(); 9747 r = null; 9748 for (i=0; i<N; i++) { 9749 PackageParser.Activity a = pkg.activities.get(i); 9750 mActivities.removeActivity(a, "activity"); 9751 if (DEBUG_REMOVE && chatty) { 9752 if (r == null) { 9753 r = new StringBuilder(256); 9754 } else { 9755 r.append(' '); 9756 } 9757 r.append(a.info.name); 9758 } 9759 } 9760 if (r != null) { 9761 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9762 } 9763 9764 N = pkg.permissions.size(); 9765 r = null; 9766 for (i=0; i<N; i++) { 9767 PackageParser.Permission p = pkg.permissions.get(i); 9768 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9769 if (bp == null) { 9770 bp = mSettings.mPermissionTrees.get(p.info.name); 9771 } 9772 if (bp != null && bp.perm == p) { 9773 bp.perm = null; 9774 if (DEBUG_REMOVE && chatty) { 9775 if (r == null) { 9776 r = new StringBuilder(256); 9777 } else { 9778 r.append(' '); 9779 } 9780 r.append(p.info.name); 9781 } 9782 } 9783 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9784 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9785 if (appOpPkgs != null) { 9786 appOpPkgs.remove(pkg.packageName); 9787 } 9788 } 9789 } 9790 if (r != null) { 9791 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9792 } 9793 9794 N = pkg.requestedPermissions.size(); 9795 r = null; 9796 for (i=0; i<N; i++) { 9797 String perm = pkg.requestedPermissions.get(i); 9798 BasePermission bp = mSettings.mPermissions.get(perm); 9799 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9800 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9801 if (appOpPkgs != null) { 9802 appOpPkgs.remove(pkg.packageName); 9803 if (appOpPkgs.isEmpty()) { 9804 mAppOpPermissionPackages.remove(perm); 9805 } 9806 } 9807 } 9808 } 9809 if (r != null) { 9810 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9811 } 9812 9813 N = pkg.instrumentation.size(); 9814 r = null; 9815 for (i=0; i<N; i++) { 9816 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9817 mInstrumentation.remove(a.getComponentName()); 9818 if (DEBUG_REMOVE && chatty) { 9819 if (r == null) { 9820 r = new StringBuilder(256); 9821 } else { 9822 r.append(' '); 9823 } 9824 r.append(a.info.name); 9825 } 9826 } 9827 if (r != null) { 9828 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9829 } 9830 9831 r = null; 9832 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9833 // Only system apps can hold shared libraries. 9834 if (pkg.libraryNames != null) { 9835 for (i=0; i<pkg.libraryNames.size(); i++) { 9836 String name = pkg.libraryNames.get(i); 9837 SharedLibraryEntry cur = mSharedLibraries.get(name); 9838 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9839 mSharedLibraries.remove(name); 9840 if (DEBUG_REMOVE && chatty) { 9841 if (r == null) { 9842 r = new StringBuilder(256); 9843 } else { 9844 r.append(' '); 9845 } 9846 r.append(name); 9847 } 9848 } 9849 } 9850 } 9851 } 9852 if (r != null) { 9853 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9854 } 9855 } 9856 9857 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9858 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9859 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9860 return true; 9861 } 9862 } 9863 return false; 9864 } 9865 9866 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9867 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9868 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9869 9870 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9871 // Update the parent permissions 9872 updatePermissionsLPw(pkg.packageName, pkg, flags); 9873 // Update the child permissions 9874 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9875 for (int i = 0; i < childCount; i++) { 9876 PackageParser.Package childPkg = pkg.childPackages.get(i); 9877 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9878 } 9879 } 9880 9881 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9882 int flags) { 9883 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9884 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9885 } 9886 9887 private void updatePermissionsLPw(String changingPkg, 9888 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9889 // Make sure there are no dangling permission trees. 9890 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9891 while (it.hasNext()) { 9892 final BasePermission bp = it.next(); 9893 if (bp.packageSetting == null) { 9894 // We may not yet have parsed the package, so just see if 9895 // we still know about its settings. 9896 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9897 } 9898 if (bp.packageSetting == null) { 9899 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9900 + " from package " + bp.sourcePackage); 9901 it.remove(); 9902 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9903 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9904 Slog.i(TAG, "Removing old permission tree: " + bp.name 9905 + " from package " + bp.sourcePackage); 9906 flags |= UPDATE_PERMISSIONS_ALL; 9907 it.remove(); 9908 } 9909 } 9910 } 9911 9912 // Make sure all dynamic permissions have been assigned to a package, 9913 // and make sure there are no dangling permissions. 9914 it = mSettings.mPermissions.values().iterator(); 9915 while (it.hasNext()) { 9916 final BasePermission bp = it.next(); 9917 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9918 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9919 + bp.name + " pkg=" + bp.sourcePackage 9920 + " info=" + bp.pendingInfo); 9921 if (bp.packageSetting == null && bp.pendingInfo != null) { 9922 final BasePermission tree = findPermissionTreeLP(bp.name); 9923 if (tree != null && tree.perm != null) { 9924 bp.packageSetting = tree.packageSetting; 9925 bp.perm = new PackageParser.Permission(tree.perm.owner, 9926 new PermissionInfo(bp.pendingInfo)); 9927 bp.perm.info.packageName = tree.perm.info.packageName; 9928 bp.perm.info.name = bp.name; 9929 bp.uid = tree.uid; 9930 } 9931 } 9932 } 9933 if (bp.packageSetting == null) { 9934 // We may not yet have parsed the package, so just see if 9935 // we still know about its settings. 9936 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9937 } 9938 if (bp.packageSetting == null) { 9939 Slog.w(TAG, "Removing dangling permission: " + bp.name 9940 + " from package " + bp.sourcePackage); 9941 it.remove(); 9942 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9943 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9944 Slog.i(TAG, "Removing old permission: " + bp.name 9945 + " from package " + bp.sourcePackage); 9946 flags |= UPDATE_PERMISSIONS_ALL; 9947 it.remove(); 9948 } 9949 } 9950 } 9951 9952 // Now update the permissions for all packages, in particular 9953 // replace the granted permissions of the system packages. 9954 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9955 for (PackageParser.Package pkg : mPackages.values()) { 9956 if (pkg != pkgInfo) { 9957 // Only replace for packages on requested volume 9958 final String volumeUuid = getVolumeUuidForPackage(pkg); 9959 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9960 && Objects.equals(replaceVolumeUuid, volumeUuid); 9961 grantPermissionsLPw(pkg, replace, changingPkg); 9962 } 9963 } 9964 } 9965 9966 if (pkgInfo != null) { 9967 // Only replace for packages on requested volume 9968 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9969 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9970 && Objects.equals(replaceVolumeUuid, volumeUuid); 9971 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9972 } 9973 } 9974 9975 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9976 String packageOfInterest) { 9977 // IMPORTANT: There are two types of permissions: install and runtime. 9978 // Install time permissions are granted when the app is installed to 9979 // all device users and users added in the future. Runtime permissions 9980 // are granted at runtime explicitly to specific users. Normal and signature 9981 // protected permissions are install time permissions. Dangerous permissions 9982 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9983 // otherwise they are runtime permissions. This function does not manage 9984 // runtime permissions except for the case an app targeting Lollipop MR1 9985 // being upgraded to target a newer SDK, in which case dangerous permissions 9986 // are transformed from install time to runtime ones. 9987 9988 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9989 if (ps == null) { 9990 return; 9991 } 9992 9993 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9994 9995 PermissionsState permissionsState = ps.getPermissionsState(); 9996 PermissionsState origPermissions = permissionsState; 9997 9998 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9999 10000 boolean runtimePermissionsRevoked = false; 10001 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 10002 10003 boolean changedInstallPermission = false; 10004 10005 if (replace) { 10006 ps.installPermissionsFixed = false; 10007 if (!ps.isSharedUser()) { 10008 origPermissions = new PermissionsState(permissionsState); 10009 permissionsState.reset(); 10010 } else { 10011 // We need to know only about runtime permission changes since the 10012 // calling code always writes the install permissions state but 10013 // the runtime ones are written only if changed. The only cases of 10014 // changed runtime permissions here are promotion of an install to 10015 // runtime and revocation of a runtime from a shared user. 10016 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 10017 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 10018 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 10019 runtimePermissionsRevoked = true; 10020 } 10021 } 10022 } 10023 10024 permissionsState.setGlobalGids(mGlobalGids); 10025 10026 final int N = pkg.requestedPermissions.size(); 10027 for (int i=0; i<N; i++) { 10028 final String name = pkg.requestedPermissions.get(i); 10029 final BasePermission bp = mSettings.mPermissions.get(name); 10030 10031 if (DEBUG_INSTALL) { 10032 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10033 } 10034 10035 if (bp == null || bp.packageSetting == null) { 10036 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10037 Slog.w(TAG, "Unknown permission " + name 10038 + " in package " + pkg.packageName); 10039 } 10040 continue; 10041 } 10042 10043 final String perm = bp.name; 10044 boolean allowedSig = false; 10045 int grant = GRANT_DENIED; 10046 10047 // Keep track of app op permissions. 10048 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10049 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10050 if (pkgs == null) { 10051 pkgs = new ArraySet<>(); 10052 mAppOpPermissionPackages.put(bp.name, pkgs); 10053 } 10054 pkgs.add(pkg.packageName); 10055 } 10056 10057 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10058 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10059 >= Build.VERSION_CODES.M; 10060 switch (level) { 10061 case PermissionInfo.PROTECTION_NORMAL: { 10062 // For all apps normal permissions are install time ones. 10063 grant = GRANT_INSTALL; 10064 } break; 10065 10066 case PermissionInfo.PROTECTION_DANGEROUS: { 10067 // If a permission review is required for legacy apps we represent 10068 // their permissions as always granted runtime ones since we need 10069 // to keep the review required permission flag per user while an 10070 // install permission's state is shared across all users. 10071 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10072 // For legacy apps dangerous permissions are install time ones. 10073 grant = GRANT_INSTALL; 10074 } else if (origPermissions.hasInstallPermission(bp.name)) { 10075 // For legacy apps that became modern, install becomes runtime. 10076 grant = GRANT_UPGRADE; 10077 } else if (mPromoteSystemApps 10078 && isSystemApp(ps) 10079 && mExistingSystemPackages.contains(ps.name)) { 10080 // For legacy system apps, install becomes runtime. 10081 // We cannot check hasInstallPermission() for system apps since those 10082 // permissions were granted implicitly and not persisted pre-M. 10083 grant = GRANT_UPGRADE; 10084 } else { 10085 // For modern apps keep runtime permissions unchanged. 10086 grant = GRANT_RUNTIME; 10087 } 10088 } break; 10089 10090 case PermissionInfo.PROTECTION_SIGNATURE: { 10091 // For all apps signature permissions are install time ones. 10092 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10093 if (allowedSig) { 10094 grant = GRANT_INSTALL; 10095 } 10096 } break; 10097 } 10098 10099 if (DEBUG_INSTALL) { 10100 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10101 } 10102 10103 if (grant != GRANT_DENIED) { 10104 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10105 // If this is an existing, non-system package, then 10106 // we can't add any new permissions to it. 10107 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10108 // Except... if this is a permission that was added 10109 // to the platform (note: need to only do this when 10110 // updating the platform). 10111 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10112 grant = GRANT_DENIED; 10113 } 10114 } 10115 } 10116 10117 switch (grant) { 10118 case GRANT_INSTALL: { 10119 // Revoke this as runtime permission to handle the case of 10120 // a runtime permission being downgraded to an install one. 10121 // Also in permission review mode we keep dangerous permissions 10122 // for legacy apps 10123 for (int userId : UserManagerService.getInstance().getUserIds()) { 10124 if (origPermissions.getRuntimePermissionState( 10125 bp.name, userId) != null) { 10126 // Revoke the runtime permission and clear the flags. 10127 origPermissions.revokeRuntimePermission(bp, userId); 10128 origPermissions.updatePermissionFlags(bp, userId, 10129 PackageManager.MASK_PERMISSION_FLAGS, 0); 10130 // If we revoked a permission permission, we have to write. 10131 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10132 changedRuntimePermissionUserIds, userId); 10133 } 10134 } 10135 // Grant an install permission. 10136 if (permissionsState.grantInstallPermission(bp) != 10137 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10138 changedInstallPermission = true; 10139 } 10140 } break; 10141 10142 case GRANT_RUNTIME: { 10143 // Grant previously granted runtime permissions. 10144 for (int userId : UserManagerService.getInstance().getUserIds()) { 10145 PermissionState permissionState = origPermissions 10146 .getRuntimePermissionState(bp.name, userId); 10147 int flags = permissionState != null 10148 ? permissionState.getFlags() : 0; 10149 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10150 if (permissionsState.grantRuntimePermission(bp, userId) == 10151 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10152 // If we cannot put the permission as it was, we have to write. 10153 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10154 changedRuntimePermissionUserIds, userId); 10155 } 10156 // If the app supports runtime permissions no need for a review. 10157 if (Build.PERMISSIONS_REVIEW_REQUIRED 10158 && appSupportsRuntimePermissions 10159 && (flags & PackageManager 10160 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10161 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10162 // Since we changed the flags, we have to write. 10163 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10164 changedRuntimePermissionUserIds, userId); 10165 } 10166 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10167 && !appSupportsRuntimePermissions) { 10168 // For legacy apps that need a permission review, every new 10169 // runtime permission is granted but it is pending a review. 10170 // We also need to review only platform defined runtime 10171 // permissions as these are the only ones the platform knows 10172 // how to disable the API to simulate revocation as legacy 10173 // apps don't expect to run with revoked permissions. 10174 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10175 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10176 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10177 // We changed the flags, hence have to write. 10178 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10179 changedRuntimePermissionUserIds, userId); 10180 } 10181 } 10182 if (permissionsState.grantRuntimePermission(bp, userId) 10183 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10184 // We changed the permission, hence have to write. 10185 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10186 changedRuntimePermissionUserIds, userId); 10187 } 10188 } 10189 // Propagate the permission flags. 10190 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10191 } 10192 } break; 10193 10194 case GRANT_UPGRADE: { 10195 // Grant runtime permissions for a previously held install permission. 10196 PermissionState permissionState = origPermissions 10197 .getInstallPermissionState(bp.name); 10198 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10199 10200 if (origPermissions.revokeInstallPermission(bp) 10201 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10202 // We will be transferring the permission flags, so clear them. 10203 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10204 PackageManager.MASK_PERMISSION_FLAGS, 0); 10205 changedInstallPermission = true; 10206 } 10207 10208 // If the permission is not to be promoted to runtime we ignore it and 10209 // also its other flags as they are not applicable to install permissions. 10210 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10211 for (int userId : currentUserIds) { 10212 if (permissionsState.grantRuntimePermission(bp, userId) != 10213 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10214 // Transfer the permission flags. 10215 permissionsState.updatePermissionFlags(bp, userId, 10216 flags, flags); 10217 // If we granted the permission, we have to write. 10218 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10219 changedRuntimePermissionUserIds, userId); 10220 } 10221 } 10222 } 10223 } break; 10224 10225 default: { 10226 if (packageOfInterest == null 10227 || packageOfInterest.equals(pkg.packageName)) { 10228 Slog.w(TAG, "Not granting permission " + perm 10229 + " to package " + pkg.packageName 10230 + " because it was previously installed without"); 10231 } 10232 } break; 10233 } 10234 } else { 10235 if (permissionsState.revokeInstallPermission(bp) != 10236 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10237 // Also drop the permission flags. 10238 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10239 PackageManager.MASK_PERMISSION_FLAGS, 0); 10240 changedInstallPermission = true; 10241 Slog.i(TAG, "Un-granting permission " + perm 10242 + " from package " + pkg.packageName 10243 + " (protectionLevel=" + bp.protectionLevel 10244 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10245 + ")"); 10246 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10247 // Don't print warning for app op permissions, since it is fine for them 10248 // not to be granted, there is a UI for the user to decide. 10249 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10250 Slog.w(TAG, "Not granting permission " + perm 10251 + " to package " + pkg.packageName 10252 + " (protectionLevel=" + bp.protectionLevel 10253 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10254 + ")"); 10255 } 10256 } 10257 } 10258 } 10259 10260 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10261 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10262 // This is the first that we have heard about this package, so the 10263 // permissions we have now selected are fixed until explicitly 10264 // changed. 10265 ps.installPermissionsFixed = true; 10266 } 10267 10268 // Persist the runtime permissions state for users with changes. If permissions 10269 // were revoked because no app in the shared user declares them we have to 10270 // write synchronously to avoid losing runtime permissions state. 10271 for (int userId : changedRuntimePermissionUserIds) { 10272 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10273 } 10274 10275 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10276 } 10277 10278 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10279 boolean allowed = false; 10280 final int NP = PackageParser.NEW_PERMISSIONS.length; 10281 for (int ip=0; ip<NP; ip++) { 10282 final PackageParser.NewPermissionInfo npi 10283 = PackageParser.NEW_PERMISSIONS[ip]; 10284 if (npi.name.equals(perm) 10285 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10286 allowed = true; 10287 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10288 + pkg.packageName); 10289 break; 10290 } 10291 } 10292 return allowed; 10293 } 10294 10295 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10296 BasePermission bp, PermissionsState origPermissions) { 10297 boolean allowed; 10298 allowed = (compareSignatures( 10299 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10300 == PackageManager.SIGNATURE_MATCH) 10301 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10302 == PackageManager.SIGNATURE_MATCH); 10303 if (!allowed && (bp.protectionLevel 10304 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10305 if (isSystemApp(pkg)) { 10306 // For updated system applications, a system permission 10307 // is granted only if it had been defined by the original application. 10308 if (pkg.isUpdatedSystemApp()) { 10309 final PackageSetting sysPs = mSettings 10310 .getDisabledSystemPkgLPr(pkg.packageName); 10311 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10312 // If the original was granted this permission, we take 10313 // that grant decision as read and propagate it to the 10314 // update. 10315 if (sysPs.isPrivileged()) { 10316 allowed = true; 10317 } 10318 } else { 10319 // The system apk may have been updated with an older 10320 // version of the one on the data partition, but which 10321 // granted a new system permission that it didn't have 10322 // before. In this case we do want to allow the app to 10323 // now get the new permission if the ancestral apk is 10324 // privileged to get it. 10325 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10326 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10327 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10328 allowed = true; 10329 break; 10330 } 10331 } 10332 } 10333 // Also if a privileged parent package on the system image or any of 10334 // its children requested a privileged permission, the updated child 10335 // packages can also get the permission. 10336 if (pkg.parentPackage != null) { 10337 final PackageSetting disabledSysParentPs = mSettings 10338 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10339 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10340 && disabledSysParentPs.isPrivileged()) { 10341 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10342 allowed = true; 10343 } else if (disabledSysParentPs.pkg.childPackages != null) { 10344 final int count = disabledSysParentPs.pkg.childPackages.size(); 10345 for (int i = 0; i < count; i++) { 10346 PackageParser.Package disabledSysChildPkg = 10347 disabledSysParentPs.pkg.childPackages.get(i); 10348 if (isPackageRequestingPermission(disabledSysChildPkg, 10349 perm)) { 10350 allowed = true; 10351 break; 10352 } 10353 } 10354 } 10355 } 10356 } 10357 } 10358 } else { 10359 allowed = isPrivilegedApp(pkg); 10360 } 10361 } 10362 } 10363 if (!allowed) { 10364 if (!allowed && (bp.protectionLevel 10365 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10366 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10367 // If this was a previously normal/dangerous permission that got moved 10368 // to a system permission as part of the runtime permission redesign, then 10369 // we still want to blindly grant it to old apps. 10370 allowed = true; 10371 } 10372 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10373 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10374 // If this permission is to be granted to the system installer and 10375 // this app is an installer, then it gets the permission. 10376 allowed = true; 10377 } 10378 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10379 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10380 // If this permission is to be granted to the system verifier and 10381 // this app is a verifier, then it gets the permission. 10382 allowed = true; 10383 } 10384 if (!allowed && (bp.protectionLevel 10385 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10386 && isSystemApp(pkg)) { 10387 // Any pre-installed system app is allowed to get this permission. 10388 allowed = true; 10389 } 10390 if (!allowed && (bp.protectionLevel 10391 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10392 // For development permissions, a development permission 10393 // is granted only if it was already granted. 10394 allowed = origPermissions.hasInstallPermission(perm); 10395 } 10396 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10397 && pkg.packageName.equals(mSetupWizardPackage)) { 10398 // If this permission is to be granted to the system setup wizard and 10399 // this app is a setup wizard, then it gets the permission. 10400 allowed = true; 10401 } 10402 } 10403 return allowed; 10404 } 10405 10406 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10407 final int permCount = pkg.requestedPermissions.size(); 10408 for (int j = 0; j < permCount; j++) { 10409 String requestedPermission = pkg.requestedPermissions.get(j); 10410 if (permission.equals(requestedPermission)) { 10411 return true; 10412 } 10413 } 10414 return false; 10415 } 10416 10417 final class ActivityIntentResolver 10418 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10419 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10420 boolean defaultOnly, int userId) { 10421 if (!sUserManager.exists(userId)) return null; 10422 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10423 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10424 } 10425 10426 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10427 int userId) { 10428 if (!sUserManager.exists(userId)) return null; 10429 mFlags = flags; 10430 return super.queryIntent(intent, resolvedType, 10431 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10432 } 10433 10434 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10435 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10436 if (!sUserManager.exists(userId)) return null; 10437 if (packageActivities == null) { 10438 return null; 10439 } 10440 mFlags = flags; 10441 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10442 final int N = packageActivities.size(); 10443 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10444 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10445 10446 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10447 for (int i = 0; i < N; ++i) { 10448 intentFilters = packageActivities.get(i).intents; 10449 if (intentFilters != null && intentFilters.size() > 0) { 10450 PackageParser.ActivityIntentInfo[] array = 10451 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10452 intentFilters.toArray(array); 10453 listCut.add(array); 10454 } 10455 } 10456 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10457 } 10458 10459 /** 10460 * Finds a privileged activity that matches the specified activity names. 10461 */ 10462 private PackageParser.Activity findMatchingActivity( 10463 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10464 for (PackageParser.Activity sysActivity : activityList) { 10465 if (sysActivity.info.name.equals(activityInfo.name)) { 10466 return sysActivity; 10467 } 10468 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10469 return sysActivity; 10470 } 10471 if (sysActivity.info.targetActivity != null) { 10472 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10473 return sysActivity; 10474 } 10475 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10476 return sysActivity; 10477 } 10478 } 10479 } 10480 return null; 10481 } 10482 10483 public class IterGenerator<E> { 10484 public Iterator<E> generate(ActivityIntentInfo info) { 10485 return null; 10486 } 10487 } 10488 10489 public class ActionIterGenerator extends IterGenerator<String> { 10490 @Override 10491 public Iterator<String> generate(ActivityIntentInfo info) { 10492 return info.actionsIterator(); 10493 } 10494 } 10495 10496 public class CategoriesIterGenerator extends IterGenerator<String> { 10497 @Override 10498 public Iterator<String> generate(ActivityIntentInfo info) { 10499 return info.categoriesIterator(); 10500 } 10501 } 10502 10503 public class SchemesIterGenerator extends IterGenerator<String> { 10504 @Override 10505 public Iterator<String> generate(ActivityIntentInfo info) { 10506 return info.schemesIterator(); 10507 } 10508 } 10509 10510 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10511 @Override 10512 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10513 return info.authoritiesIterator(); 10514 } 10515 } 10516 10517 /** 10518 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10519 * MODIFIED. Do not pass in a list that should not be changed. 10520 */ 10521 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10522 IterGenerator<T> generator, Iterator<T> searchIterator) { 10523 // loop through the set of actions; every one must be found in the intent filter 10524 while (searchIterator.hasNext()) { 10525 // we must have at least one filter in the list to consider a match 10526 if (intentList.size() == 0) { 10527 break; 10528 } 10529 10530 final T searchAction = searchIterator.next(); 10531 10532 // loop through the set of intent filters 10533 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10534 while (intentIter.hasNext()) { 10535 final ActivityIntentInfo intentInfo = intentIter.next(); 10536 boolean selectionFound = false; 10537 10538 // loop through the intent filter's selection criteria; at least one 10539 // of them must match the searched criteria 10540 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10541 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10542 final T intentSelection = intentSelectionIter.next(); 10543 if (intentSelection != null && intentSelection.equals(searchAction)) { 10544 selectionFound = true; 10545 break; 10546 } 10547 } 10548 10549 // the selection criteria wasn't found in this filter's set; this filter 10550 // is not a potential match 10551 if (!selectionFound) { 10552 intentIter.remove(); 10553 } 10554 } 10555 } 10556 } 10557 10558 private boolean isProtectedAction(ActivityIntentInfo filter) { 10559 final Iterator<String> actionsIter = filter.actionsIterator(); 10560 while (actionsIter != null && actionsIter.hasNext()) { 10561 final String filterAction = actionsIter.next(); 10562 if (PROTECTED_ACTIONS.contains(filterAction)) { 10563 return true; 10564 } 10565 } 10566 return false; 10567 } 10568 10569 /** 10570 * Adjusts the priority of the given intent filter according to policy. 10571 * <p> 10572 * <ul> 10573 * <li>The priority for non privileged applications is capped to '0'</li> 10574 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10575 * <li>The priority for unbundled updates to privileged applications is capped to the 10576 * priority defined on the system partition</li> 10577 * </ul> 10578 * <p> 10579 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10580 * allowed to obtain any priority on any action. 10581 */ 10582 private void adjustPriority( 10583 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10584 // nothing to do; priority is fine as-is 10585 if (intent.getPriority() <= 0) { 10586 return; 10587 } 10588 10589 final ActivityInfo activityInfo = intent.activity.info; 10590 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10591 10592 final boolean privilegedApp = 10593 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10594 if (!privilegedApp) { 10595 // non-privileged applications can never define a priority >0 10596 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10597 + " package: " + applicationInfo.packageName 10598 + " activity: " + intent.activity.className 10599 + " origPrio: " + intent.getPriority()); 10600 intent.setPriority(0); 10601 return; 10602 } 10603 10604 if (systemActivities == null) { 10605 // the system package is not disabled; we're parsing the system partition 10606 if (isProtectedAction(intent)) { 10607 if (mDeferProtectedFilters) { 10608 // We can't deal with these just yet. No component should ever obtain a 10609 // >0 priority for a protected actions, with ONE exception -- the setup 10610 // wizard. The setup wizard, however, cannot be known until we're able to 10611 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10612 // until all intent filters have been processed. Chicken, meet egg. 10613 // Let the filter temporarily have a high priority and rectify the 10614 // priorities after all system packages have been scanned. 10615 mProtectedFilters.add(intent); 10616 if (DEBUG_FILTERS) { 10617 Slog.i(TAG, "Protected action; save for later;" 10618 + " package: " + applicationInfo.packageName 10619 + " activity: " + intent.activity.className 10620 + " origPrio: " + intent.getPriority()); 10621 } 10622 return; 10623 } else { 10624 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10625 Slog.i(TAG, "No setup wizard;" 10626 + " All protected intents capped to priority 0"); 10627 } 10628 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10629 if (DEBUG_FILTERS) { 10630 Slog.i(TAG, "Found setup wizard;" 10631 + " allow priority " + intent.getPriority() + ";" 10632 + " package: " + intent.activity.info.packageName 10633 + " activity: " + intent.activity.className 10634 + " priority: " + intent.getPriority()); 10635 } 10636 // setup wizard gets whatever it wants 10637 return; 10638 } 10639 Slog.w(TAG, "Protected action; cap priority to 0;" 10640 + " package: " + intent.activity.info.packageName 10641 + " activity: " + intent.activity.className 10642 + " origPrio: " + intent.getPriority()); 10643 intent.setPriority(0); 10644 return; 10645 } 10646 } 10647 // privileged apps on the system image get whatever priority they request 10648 return; 10649 } 10650 10651 // privileged app unbundled update ... try to find the same activity 10652 final PackageParser.Activity foundActivity = 10653 findMatchingActivity(systemActivities, activityInfo); 10654 if (foundActivity == null) { 10655 // this is a new activity; it cannot obtain >0 priority 10656 if (DEBUG_FILTERS) { 10657 Slog.i(TAG, "New activity; cap priority to 0;" 10658 + " package: " + applicationInfo.packageName 10659 + " activity: " + intent.activity.className 10660 + " origPrio: " + intent.getPriority()); 10661 } 10662 intent.setPriority(0); 10663 return; 10664 } 10665 10666 // found activity, now check for filter equivalence 10667 10668 // a shallow copy is enough; we modify the list, not its contents 10669 final List<ActivityIntentInfo> intentListCopy = 10670 new ArrayList<>(foundActivity.intents); 10671 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10672 10673 // find matching action subsets 10674 final Iterator<String> actionsIterator = intent.actionsIterator(); 10675 if (actionsIterator != null) { 10676 getIntentListSubset( 10677 intentListCopy, new ActionIterGenerator(), actionsIterator); 10678 if (intentListCopy.size() == 0) { 10679 // no more intents to match; we're not equivalent 10680 if (DEBUG_FILTERS) { 10681 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10682 + " package: " + applicationInfo.packageName 10683 + " activity: " + intent.activity.className 10684 + " origPrio: " + intent.getPriority()); 10685 } 10686 intent.setPriority(0); 10687 return; 10688 } 10689 } 10690 10691 // find matching category subsets 10692 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10693 if (categoriesIterator != null) { 10694 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10695 categoriesIterator); 10696 if (intentListCopy.size() == 0) { 10697 // no more intents to match; we're not equivalent 10698 if (DEBUG_FILTERS) { 10699 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10700 + " package: " + applicationInfo.packageName 10701 + " activity: " + intent.activity.className 10702 + " origPrio: " + intent.getPriority()); 10703 } 10704 intent.setPriority(0); 10705 return; 10706 } 10707 } 10708 10709 // find matching schemes subsets 10710 final Iterator<String> schemesIterator = intent.schemesIterator(); 10711 if (schemesIterator != null) { 10712 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10713 schemesIterator); 10714 if (intentListCopy.size() == 0) { 10715 // no more intents to match; we're not equivalent 10716 if (DEBUG_FILTERS) { 10717 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10718 + " package: " + applicationInfo.packageName 10719 + " activity: " + intent.activity.className 10720 + " origPrio: " + intent.getPriority()); 10721 } 10722 intent.setPriority(0); 10723 return; 10724 } 10725 } 10726 10727 // find matching authorities subsets 10728 final Iterator<IntentFilter.AuthorityEntry> 10729 authoritiesIterator = intent.authoritiesIterator(); 10730 if (authoritiesIterator != null) { 10731 getIntentListSubset(intentListCopy, 10732 new AuthoritiesIterGenerator(), 10733 authoritiesIterator); 10734 if (intentListCopy.size() == 0) { 10735 // no more intents to match; we're not equivalent 10736 if (DEBUG_FILTERS) { 10737 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10738 + " package: " + applicationInfo.packageName 10739 + " activity: " + intent.activity.className 10740 + " origPrio: " + intent.getPriority()); 10741 } 10742 intent.setPriority(0); 10743 return; 10744 } 10745 } 10746 10747 // we found matching filter(s); app gets the max priority of all intents 10748 int cappedPriority = 0; 10749 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10750 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10751 } 10752 if (intent.getPriority() > cappedPriority) { 10753 if (DEBUG_FILTERS) { 10754 Slog.i(TAG, "Found matching filter(s);" 10755 + " cap priority to " + cappedPriority + ";" 10756 + " package: " + applicationInfo.packageName 10757 + " activity: " + intent.activity.className 10758 + " origPrio: " + intent.getPriority()); 10759 } 10760 intent.setPriority(cappedPriority); 10761 return; 10762 } 10763 // all this for nothing; the requested priority was <= what was on the system 10764 } 10765 10766 public final void addActivity(PackageParser.Activity a, String type) { 10767 mActivities.put(a.getComponentName(), a); 10768 if (DEBUG_SHOW_INFO) 10769 Log.v( 10770 TAG, " " + type + " " + 10771 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10772 if (DEBUG_SHOW_INFO) 10773 Log.v(TAG, " Class=" + a.info.name); 10774 final int NI = a.intents.size(); 10775 for (int j=0; j<NI; j++) { 10776 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10777 if ("activity".equals(type)) { 10778 final PackageSetting ps = 10779 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10780 final List<PackageParser.Activity> systemActivities = 10781 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10782 adjustPriority(systemActivities, intent); 10783 } 10784 if (DEBUG_SHOW_INFO) { 10785 Log.v(TAG, " IntentFilter:"); 10786 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10787 } 10788 if (!intent.debugCheck()) { 10789 Log.w(TAG, "==> For Activity " + a.info.name); 10790 } 10791 addFilter(intent); 10792 } 10793 } 10794 10795 public final void removeActivity(PackageParser.Activity a, String type) { 10796 mActivities.remove(a.getComponentName()); 10797 if (DEBUG_SHOW_INFO) { 10798 Log.v(TAG, " " + type + " " 10799 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10800 : a.info.name) + ":"); 10801 Log.v(TAG, " Class=" + a.info.name); 10802 } 10803 final int NI = a.intents.size(); 10804 for (int j=0; j<NI; j++) { 10805 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10806 if (DEBUG_SHOW_INFO) { 10807 Log.v(TAG, " IntentFilter:"); 10808 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10809 } 10810 removeFilter(intent); 10811 } 10812 } 10813 10814 @Override 10815 protected boolean allowFilterResult( 10816 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10817 ActivityInfo filterAi = filter.activity.info; 10818 for (int i=dest.size()-1; i>=0; i--) { 10819 ActivityInfo destAi = dest.get(i).activityInfo; 10820 if (destAi.name == filterAi.name 10821 && destAi.packageName == filterAi.packageName) { 10822 return false; 10823 } 10824 } 10825 return true; 10826 } 10827 10828 @Override 10829 protected ActivityIntentInfo[] newArray(int size) { 10830 return new ActivityIntentInfo[size]; 10831 } 10832 10833 @Override 10834 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10835 if (!sUserManager.exists(userId)) return true; 10836 PackageParser.Package p = filter.activity.owner; 10837 if (p != null) { 10838 PackageSetting ps = (PackageSetting)p.mExtras; 10839 if (ps != null) { 10840 // System apps are never considered stopped for purposes of 10841 // filtering, because there may be no way for the user to 10842 // actually re-launch them. 10843 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10844 && ps.getStopped(userId); 10845 } 10846 } 10847 return false; 10848 } 10849 10850 @Override 10851 protected boolean isPackageForFilter(String packageName, 10852 PackageParser.ActivityIntentInfo info) { 10853 return packageName.equals(info.activity.owner.packageName); 10854 } 10855 10856 @Override 10857 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10858 int match, int userId) { 10859 if (!sUserManager.exists(userId)) return null; 10860 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10861 return null; 10862 } 10863 final PackageParser.Activity activity = info.activity; 10864 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10865 if (ps == null) { 10866 return null; 10867 } 10868 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10869 ps.readUserState(userId), userId); 10870 if (ai == null) { 10871 return null; 10872 } 10873 final ResolveInfo res = new ResolveInfo(); 10874 res.activityInfo = ai; 10875 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10876 res.filter = info; 10877 } 10878 if (info != null) { 10879 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10880 } 10881 res.priority = info.getPriority(); 10882 res.preferredOrder = activity.owner.mPreferredOrder; 10883 //System.out.println("Result: " + res.activityInfo.className + 10884 // " = " + res.priority); 10885 res.match = match; 10886 res.isDefault = info.hasDefault; 10887 res.labelRes = info.labelRes; 10888 res.nonLocalizedLabel = info.nonLocalizedLabel; 10889 if (userNeedsBadging(userId)) { 10890 res.noResourceId = true; 10891 } else { 10892 res.icon = info.icon; 10893 } 10894 res.iconResourceId = info.icon; 10895 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10896 return res; 10897 } 10898 10899 @Override 10900 protected void sortResults(List<ResolveInfo> results) { 10901 Collections.sort(results, mResolvePrioritySorter); 10902 } 10903 10904 @Override 10905 protected void dumpFilter(PrintWriter out, String prefix, 10906 PackageParser.ActivityIntentInfo filter) { 10907 out.print(prefix); out.print( 10908 Integer.toHexString(System.identityHashCode(filter.activity))); 10909 out.print(' '); 10910 filter.activity.printComponentShortName(out); 10911 out.print(" filter "); 10912 out.println(Integer.toHexString(System.identityHashCode(filter))); 10913 } 10914 10915 @Override 10916 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10917 return filter.activity; 10918 } 10919 10920 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10921 PackageParser.Activity activity = (PackageParser.Activity)label; 10922 out.print(prefix); out.print( 10923 Integer.toHexString(System.identityHashCode(activity))); 10924 out.print(' '); 10925 activity.printComponentShortName(out); 10926 if (count > 1) { 10927 out.print(" ("); out.print(count); out.print(" filters)"); 10928 } 10929 out.println(); 10930 } 10931 10932 // Keys are String (activity class name), values are Activity. 10933 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10934 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10935 private int mFlags; 10936 } 10937 10938 private final class ServiceIntentResolver 10939 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10940 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10941 boolean defaultOnly, int userId) { 10942 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10943 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10944 } 10945 10946 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10947 int userId) { 10948 if (!sUserManager.exists(userId)) return null; 10949 mFlags = flags; 10950 return super.queryIntent(intent, resolvedType, 10951 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10952 } 10953 10954 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10955 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10956 if (!sUserManager.exists(userId)) return null; 10957 if (packageServices == null) { 10958 return null; 10959 } 10960 mFlags = flags; 10961 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10962 final int N = packageServices.size(); 10963 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10964 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10965 10966 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10967 for (int i = 0; i < N; ++i) { 10968 intentFilters = packageServices.get(i).intents; 10969 if (intentFilters != null && intentFilters.size() > 0) { 10970 PackageParser.ServiceIntentInfo[] array = 10971 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10972 intentFilters.toArray(array); 10973 listCut.add(array); 10974 } 10975 } 10976 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10977 } 10978 10979 public final void addService(PackageParser.Service s) { 10980 mServices.put(s.getComponentName(), s); 10981 if (DEBUG_SHOW_INFO) { 10982 Log.v(TAG, " " 10983 + (s.info.nonLocalizedLabel != null 10984 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10985 Log.v(TAG, " Class=" + s.info.name); 10986 } 10987 final int NI = s.intents.size(); 10988 int j; 10989 for (j=0; j<NI; j++) { 10990 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10991 if (DEBUG_SHOW_INFO) { 10992 Log.v(TAG, " IntentFilter:"); 10993 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10994 } 10995 if (!intent.debugCheck()) { 10996 Log.w(TAG, "==> For Service " + s.info.name); 10997 } 10998 addFilter(intent); 10999 } 11000 } 11001 11002 public final void removeService(PackageParser.Service s) { 11003 mServices.remove(s.getComponentName()); 11004 if (DEBUG_SHOW_INFO) { 11005 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 11006 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 11007 Log.v(TAG, " Class=" + s.info.name); 11008 } 11009 final int NI = s.intents.size(); 11010 int j; 11011 for (j=0; j<NI; j++) { 11012 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 11013 if (DEBUG_SHOW_INFO) { 11014 Log.v(TAG, " IntentFilter:"); 11015 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11016 } 11017 removeFilter(intent); 11018 } 11019 } 11020 11021 @Override 11022 protected boolean allowFilterResult( 11023 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11024 ServiceInfo filterSi = filter.service.info; 11025 for (int i=dest.size()-1; i>=0; i--) { 11026 ServiceInfo destAi = dest.get(i).serviceInfo; 11027 if (destAi.name == filterSi.name 11028 && destAi.packageName == filterSi.packageName) { 11029 return false; 11030 } 11031 } 11032 return true; 11033 } 11034 11035 @Override 11036 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11037 return new PackageParser.ServiceIntentInfo[size]; 11038 } 11039 11040 @Override 11041 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11042 if (!sUserManager.exists(userId)) return true; 11043 PackageParser.Package p = filter.service.owner; 11044 if (p != null) { 11045 PackageSetting ps = (PackageSetting)p.mExtras; 11046 if (ps != null) { 11047 // System apps are never considered stopped for purposes of 11048 // filtering, because there may be no way for the user to 11049 // actually re-launch them. 11050 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11051 && ps.getStopped(userId); 11052 } 11053 } 11054 return false; 11055 } 11056 11057 @Override 11058 protected boolean isPackageForFilter(String packageName, 11059 PackageParser.ServiceIntentInfo info) { 11060 return packageName.equals(info.service.owner.packageName); 11061 } 11062 11063 @Override 11064 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11065 int match, int userId) { 11066 if (!sUserManager.exists(userId)) return null; 11067 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11068 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11069 return null; 11070 } 11071 final PackageParser.Service service = info.service; 11072 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11073 if (ps == null) { 11074 return null; 11075 } 11076 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11077 ps.readUserState(userId), userId); 11078 if (si == null) { 11079 return null; 11080 } 11081 final ResolveInfo res = new ResolveInfo(); 11082 res.serviceInfo = si; 11083 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11084 res.filter = filter; 11085 } 11086 res.priority = info.getPriority(); 11087 res.preferredOrder = service.owner.mPreferredOrder; 11088 res.match = match; 11089 res.isDefault = info.hasDefault; 11090 res.labelRes = info.labelRes; 11091 res.nonLocalizedLabel = info.nonLocalizedLabel; 11092 res.icon = info.icon; 11093 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11094 return res; 11095 } 11096 11097 @Override 11098 protected void sortResults(List<ResolveInfo> results) { 11099 Collections.sort(results, mResolvePrioritySorter); 11100 } 11101 11102 @Override 11103 protected void dumpFilter(PrintWriter out, String prefix, 11104 PackageParser.ServiceIntentInfo filter) { 11105 out.print(prefix); out.print( 11106 Integer.toHexString(System.identityHashCode(filter.service))); 11107 out.print(' '); 11108 filter.service.printComponentShortName(out); 11109 out.print(" filter "); 11110 out.println(Integer.toHexString(System.identityHashCode(filter))); 11111 } 11112 11113 @Override 11114 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11115 return filter.service; 11116 } 11117 11118 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11119 PackageParser.Service service = (PackageParser.Service)label; 11120 out.print(prefix); out.print( 11121 Integer.toHexString(System.identityHashCode(service))); 11122 out.print(' '); 11123 service.printComponentShortName(out); 11124 if (count > 1) { 11125 out.print(" ("); out.print(count); out.print(" filters)"); 11126 } 11127 out.println(); 11128 } 11129 11130// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11131// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11132// final List<ResolveInfo> retList = Lists.newArrayList(); 11133// while (i.hasNext()) { 11134// final ResolveInfo resolveInfo = (ResolveInfo) i; 11135// if (isEnabledLP(resolveInfo.serviceInfo)) { 11136// retList.add(resolveInfo); 11137// } 11138// } 11139// return retList; 11140// } 11141 11142 // Keys are String (activity class name), values are Activity. 11143 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11144 = new ArrayMap<ComponentName, PackageParser.Service>(); 11145 private int mFlags; 11146 }; 11147 11148 private final class ProviderIntentResolver 11149 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11150 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11151 boolean defaultOnly, int userId) { 11152 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11153 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11154 } 11155 11156 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11157 int userId) { 11158 if (!sUserManager.exists(userId)) 11159 return null; 11160 mFlags = flags; 11161 return super.queryIntent(intent, resolvedType, 11162 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11163 } 11164 11165 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11166 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11167 if (!sUserManager.exists(userId)) 11168 return null; 11169 if (packageProviders == null) { 11170 return null; 11171 } 11172 mFlags = flags; 11173 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11174 final int N = packageProviders.size(); 11175 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11176 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11177 11178 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11179 for (int i = 0; i < N; ++i) { 11180 intentFilters = packageProviders.get(i).intents; 11181 if (intentFilters != null && intentFilters.size() > 0) { 11182 PackageParser.ProviderIntentInfo[] array = 11183 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11184 intentFilters.toArray(array); 11185 listCut.add(array); 11186 } 11187 } 11188 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11189 } 11190 11191 public final void addProvider(PackageParser.Provider p) { 11192 if (mProviders.containsKey(p.getComponentName())) { 11193 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11194 return; 11195 } 11196 11197 mProviders.put(p.getComponentName(), p); 11198 if (DEBUG_SHOW_INFO) { 11199 Log.v(TAG, " " 11200 + (p.info.nonLocalizedLabel != null 11201 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11202 Log.v(TAG, " Class=" + p.info.name); 11203 } 11204 final int NI = p.intents.size(); 11205 int j; 11206 for (j = 0; j < NI; j++) { 11207 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11208 if (DEBUG_SHOW_INFO) { 11209 Log.v(TAG, " IntentFilter:"); 11210 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11211 } 11212 if (!intent.debugCheck()) { 11213 Log.w(TAG, "==> For Provider " + p.info.name); 11214 } 11215 addFilter(intent); 11216 } 11217 } 11218 11219 public final void removeProvider(PackageParser.Provider p) { 11220 mProviders.remove(p.getComponentName()); 11221 if (DEBUG_SHOW_INFO) { 11222 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11223 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11224 Log.v(TAG, " Class=" + p.info.name); 11225 } 11226 final int NI = p.intents.size(); 11227 int j; 11228 for (j = 0; j < NI; j++) { 11229 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11230 if (DEBUG_SHOW_INFO) { 11231 Log.v(TAG, " IntentFilter:"); 11232 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11233 } 11234 removeFilter(intent); 11235 } 11236 } 11237 11238 @Override 11239 protected boolean allowFilterResult( 11240 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11241 ProviderInfo filterPi = filter.provider.info; 11242 for (int i = dest.size() - 1; i >= 0; i--) { 11243 ProviderInfo destPi = dest.get(i).providerInfo; 11244 if (destPi.name == filterPi.name 11245 && destPi.packageName == filterPi.packageName) { 11246 return false; 11247 } 11248 } 11249 return true; 11250 } 11251 11252 @Override 11253 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11254 return new PackageParser.ProviderIntentInfo[size]; 11255 } 11256 11257 @Override 11258 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11259 if (!sUserManager.exists(userId)) 11260 return true; 11261 PackageParser.Package p = filter.provider.owner; 11262 if (p != null) { 11263 PackageSetting ps = (PackageSetting) p.mExtras; 11264 if (ps != null) { 11265 // System apps are never considered stopped for purposes of 11266 // filtering, because there may be no way for the user to 11267 // actually re-launch them. 11268 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11269 && ps.getStopped(userId); 11270 } 11271 } 11272 return false; 11273 } 11274 11275 @Override 11276 protected boolean isPackageForFilter(String packageName, 11277 PackageParser.ProviderIntentInfo info) { 11278 return packageName.equals(info.provider.owner.packageName); 11279 } 11280 11281 @Override 11282 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11283 int match, int userId) { 11284 if (!sUserManager.exists(userId)) 11285 return null; 11286 final PackageParser.ProviderIntentInfo info = filter; 11287 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11288 return null; 11289 } 11290 final PackageParser.Provider provider = info.provider; 11291 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11292 if (ps == null) { 11293 return null; 11294 } 11295 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11296 ps.readUserState(userId), userId); 11297 if (pi == null) { 11298 return null; 11299 } 11300 final ResolveInfo res = new ResolveInfo(); 11301 res.providerInfo = pi; 11302 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11303 res.filter = filter; 11304 } 11305 res.priority = info.getPriority(); 11306 res.preferredOrder = provider.owner.mPreferredOrder; 11307 res.match = match; 11308 res.isDefault = info.hasDefault; 11309 res.labelRes = info.labelRes; 11310 res.nonLocalizedLabel = info.nonLocalizedLabel; 11311 res.icon = info.icon; 11312 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11313 return res; 11314 } 11315 11316 @Override 11317 protected void sortResults(List<ResolveInfo> results) { 11318 Collections.sort(results, mResolvePrioritySorter); 11319 } 11320 11321 @Override 11322 protected void dumpFilter(PrintWriter out, String prefix, 11323 PackageParser.ProviderIntentInfo filter) { 11324 out.print(prefix); 11325 out.print( 11326 Integer.toHexString(System.identityHashCode(filter.provider))); 11327 out.print(' '); 11328 filter.provider.printComponentShortName(out); 11329 out.print(" filter "); 11330 out.println(Integer.toHexString(System.identityHashCode(filter))); 11331 } 11332 11333 @Override 11334 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11335 return filter.provider; 11336 } 11337 11338 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11339 PackageParser.Provider provider = (PackageParser.Provider)label; 11340 out.print(prefix); out.print( 11341 Integer.toHexString(System.identityHashCode(provider))); 11342 out.print(' '); 11343 provider.printComponentShortName(out); 11344 if (count > 1) { 11345 out.print(" ("); out.print(count); out.print(" filters)"); 11346 } 11347 out.println(); 11348 } 11349 11350 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11351 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11352 private int mFlags; 11353 } 11354 11355 private static final class EphemeralIntentResolver 11356 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11357 @Override 11358 protected EphemeralResolveIntentInfo[] newArray(int size) { 11359 return new EphemeralResolveIntentInfo[size]; 11360 } 11361 11362 @Override 11363 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11364 return true; 11365 } 11366 11367 @Override 11368 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11369 int userId) { 11370 if (!sUserManager.exists(userId)) { 11371 return null; 11372 } 11373 return info.getEphemeralResolveInfo(); 11374 } 11375 } 11376 11377 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11378 new Comparator<ResolveInfo>() { 11379 public int compare(ResolveInfo r1, ResolveInfo r2) { 11380 int v1 = r1.priority; 11381 int v2 = r2.priority; 11382 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11383 if (v1 != v2) { 11384 return (v1 > v2) ? -1 : 1; 11385 } 11386 v1 = r1.preferredOrder; 11387 v2 = r2.preferredOrder; 11388 if (v1 != v2) { 11389 return (v1 > v2) ? -1 : 1; 11390 } 11391 if (r1.isDefault != r2.isDefault) { 11392 return r1.isDefault ? -1 : 1; 11393 } 11394 v1 = r1.match; 11395 v2 = r2.match; 11396 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11397 if (v1 != v2) { 11398 return (v1 > v2) ? -1 : 1; 11399 } 11400 if (r1.system != r2.system) { 11401 return r1.system ? -1 : 1; 11402 } 11403 if (r1.activityInfo != null) { 11404 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11405 } 11406 if (r1.serviceInfo != null) { 11407 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11408 } 11409 if (r1.providerInfo != null) { 11410 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11411 } 11412 return 0; 11413 } 11414 }; 11415 11416 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11417 new Comparator<ProviderInfo>() { 11418 public int compare(ProviderInfo p1, ProviderInfo p2) { 11419 final int v1 = p1.initOrder; 11420 final int v2 = p2.initOrder; 11421 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11422 } 11423 }; 11424 11425 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11426 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11427 final int[] userIds) { 11428 mHandler.post(new Runnable() { 11429 @Override 11430 public void run() { 11431 try { 11432 final IActivityManager am = ActivityManagerNative.getDefault(); 11433 if (am == null) return; 11434 final int[] resolvedUserIds; 11435 if (userIds == null) { 11436 resolvedUserIds = am.getRunningUserIds(); 11437 } else { 11438 resolvedUserIds = userIds; 11439 } 11440 for (int id : resolvedUserIds) { 11441 final Intent intent = new Intent(action, 11442 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11443 if (extras != null) { 11444 intent.putExtras(extras); 11445 } 11446 if (targetPkg != null) { 11447 intent.setPackage(targetPkg); 11448 } 11449 // Modify the UID when posting to other users 11450 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11451 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11452 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11453 intent.putExtra(Intent.EXTRA_UID, uid); 11454 } 11455 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11456 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11457 if (DEBUG_BROADCASTS) { 11458 RuntimeException here = new RuntimeException("here"); 11459 here.fillInStackTrace(); 11460 Slog.d(TAG, "Sending to user " + id + ": " 11461 + intent.toShortString(false, true, false, false) 11462 + " " + intent.getExtras(), here); 11463 } 11464 am.broadcastIntent(null, intent, null, finishedReceiver, 11465 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11466 null, finishedReceiver != null, false, id); 11467 } 11468 } catch (RemoteException ex) { 11469 } 11470 } 11471 }); 11472 } 11473 11474 /** 11475 * Check if the external storage media is available. This is true if there 11476 * is a mounted external storage medium or if the external storage is 11477 * emulated. 11478 */ 11479 private boolean isExternalMediaAvailable() { 11480 return mMediaMounted || Environment.isExternalStorageEmulated(); 11481 } 11482 11483 @Override 11484 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11485 // writer 11486 synchronized (mPackages) { 11487 if (!isExternalMediaAvailable()) { 11488 // If the external storage is no longer mounted at this point, 11489 // the caller may not have been able to delete all of this 11490 // packages files and can not delete any more. Bail. 11491 return null; 11492 } 11493 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11494 if (lastPackage != null) { 11495 pkgs.remove(lastPackage); 11496 } 11497 if (pkgs.size() > 0) { 11498 return pkgs.get(0); 11499 } 11500 } 11501 return null; 11502 } 11503 11504 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11505 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11506 userId, andCode ? 1 : 0, packageName); 11507 if (mSystemReady) { 11508 msg.sendToTarget(); 11509 } else { 11510 if (mPostSystemReadyMessages == null) { 11511 mPostSystemReadyMessages = new ArrayList<>(); 11512 } 11513 mPostSystemReadyMessages.add(msg); 11514 } 11515 } 11516 11517 void startCleaningPackages() { 11518 // reader 11519 if (!isExternalMediaAvailable()) { 11520 return; 11521 } 11522 synchronized (mPackages) { 11523 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11524 return; 11525 } 11526 } 11527 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11528 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11529 IActivityManager am = ActivityManagerNative.getDefault(); 11530 if (am != null) { 11531 try { 11532 am.startService(null, intent, null, mContext.getOpPackageName(), 11533 UserHandle.USER_SYSTEM); 11534 } catch (RemoteException e) { 11535 } 11536 } 11537 } 11538 11539 @Override 11540 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11541 int installFlags, String installerPackageName, int userId) { 11542 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11543 11544 final int callingUid = Binder.getCallingUid(); 11545 enforceCrossUserPermission(callingUid, userId, 11546 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11547 11548 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11549 try { 11550 if (observer != null) { 11551 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11552 } 11553 } catch (RemoteException re) { 11554 } 11555 return; 11556 } 11557 11558 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11559 installFlags |= PackageManager.INSTALL_FROM_ADB; 11560 11561 } else { 11562 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11563 // about installerPackageName. 11564 11565 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11566 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11567 } 11568 11569 UserHandle user; 11570 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11571 user = UserHandle.ALL; 11572 } else { 11573 user = new UserHandle(userId); 11574 } 11575 11576 // Only system components can circumvent runtime permissions when installing. 11577 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11578 && mContext.checkCallingOrSelfPermission(Manifest.permission 11579 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11580 throw new SecurityException("You need the " 11581 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11582 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11583 } 11584 11585 final File originFile = new File(originPath); 11586 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11587 11588 final Message msg = mHandler.obtainMessage(INIT_COPY); 11589 final VerificationInfo verificationInfo = new VerificationInfo( 11590 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11591 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11592 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11593 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11594 null /*certificates*/); 11595 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11596 msg.obj = params; 11597 11598 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11599 System.identityHashCode(msg.obj)); 11600 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11601 System.identityHashCode(msg.obj)); 11602 11603 mHandler.sendMessage(msg); 11604 } 11605 11606 void installStage(String packageName, File stagedDir, String stagedCid, 11607 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11608 String installerPackageName, int installerUid, UserHandle user, 11609 Certificate[][] certificates) { 11610 if (DEBUG_EPHEMERAL) { 11611 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11612 Slog.d(TAG, "Ephemeral install of " + packageName); 11613 } 11614 } 11615 final VerificationInfo verificationInfo = new VerificationInfo( 11616 sessionParams.originatingUri, sessionParams.referrerUri, 11617 sessionParams.originatingUid, installerUid); 11618 11619 final OriginInfo origin; 11620 if (stagedDir != null) { 11621 origin = OriginInfo.fromStagedFile(stagedDir); 11622 } else { 11623 origin = OriginInfo.fromStagedContainer(stagedCid); 11624 } 11625 11626 final Message msg = mHandler.obtainMessage(INIT_COPY); 11627 final InstallParams params = new InstallParams(origin, null, observer, 11628 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11629 verificationInfo, user, sessionParams.abiOverride, 11630 sessionParams.grantedRuntimePermissions, certificates); 11631 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11632 msg.obj = params; 11633 11634 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11635 System.identityHashCode(msg.obj)); 11636 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11637 System.identityHashCode(msg.obj)); 11638 11639 mHandler.sendMessage(msg); 11640 } 11641 11642 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11643 int userId) { 11644 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11645 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11646 } 11647 11648 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11649 int appId, int userId) { 11650 Bundle extras = new Bundle(1); 11651 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11652 11653 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11654 packageName, extras, 0, null, null, new int[] {userId}); 11655 try { 11656 IActivityManager am = ActivityManagerNative.getDefault(); 11657 if (isSystem && am.isUserRunning(userId, 0)) { 11658 // The just-installed/enabled app is bundled on the system, so presumed 11659 // to be able to run automatically without needing an explicit launch. 11660 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11661 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11662 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11663 .setPackage(packageName); 11664 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11665 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11666 } 11667 } catch (RemoteException e) { 11668 // shouldn't happen 11669 Slog.w(TAG, "Unable to bootstrap installed package", e); 11670 } 11671 } 11672 11673 @Override 11674 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11675 int userId) { 11676 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11677 PackageSetting pkgSetting; 11678 final int uid = Binder.getCallingUid(); 11679 enforceCrossUserPermission(uid, userId, 11680 true /* requireFullPermission */, true /* checkShell */, 11681 "setApplicationHiddenSetting for user " + userId); 11682 11683 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11684 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11685 return false; 11686 } 11687 11688 long callingId = Binder.clearCallingIdentity(); 11689 try { 11690 boolean sendAdded = false; 11691 boolean sendRemoved = false; 11692 // writer 11693 synchronized (mPackages) { 11694 pkgSetting = mSettings.mPackages.get(packageName); 11695 if (pkgSetting == null) { 11696 return false; 11697 } 11698 // Only allow protected packages to hide themselves. 11699 if (hidden && !UserHandle.isSameApp(uid, pkgSetting.appId) 11700 && mProtectedPackages.isPackageStateProtected(userId, packageName)) { 11701 Slog.w(TAG, "Not hiding protected package: " + packageName); 11702 return false; 11703 } 11704 if (pkgSetting.getHidden(userId) != hidden) { 11705 pkgSetting.setHidden(hidden, userId); 11706 mSettings.writePackageRestrictionsLPr(userId); 11707 if (hidden) { 11708 sendRemoved = true; 11709 } else { 11710 sendAdded = true; 11711 } 11712 } 11713 } 11714 if (sendAdded) { 11715 sendPackageAddedForUser(packageName, pkgSetting, userId); 11716 return true; 11717 } 11718 if (sendRemoved) { 11719 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11720 "hiding pkg"); 11721 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11722 return true; 11723 } 11724 } finally { 11725 Binder.restoreCallingIdentity(callingId); 11726 } 11727 return false; 11728 } 11729 11730 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11731 int userId) { 11732 final PackageRemovedInfo info = new PackageRemovedInfo(); 11733 info.removedPackage = packageName; 11734 info.removedUsers = new int[] {userId}; 11735 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11736 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11737 } 11738 11739 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11740 if (pkgList.length > 0) { 11741 Bundle extras = new Bundle(1); 11742 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11743 11744 sendPackageBroadcast( 11745 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11746 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11747 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11748 new int[] {userId}); 11749 } 11750 } 11751 11752 /** 11753 * Returns true if application is not found or there was an error. Otherwise it returns 11754 * the hidden state of the package for the given user. 11755 */ 11756 @Override 11757 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11758 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11759 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11760 true /* requireFullPermission */, false /* checkShell */, 11761 "getApplicationHidden for user " + userId); 11762 PackageSetting pkgSetting; 11763 long callingId = Binder.clearCallingIdentity(); 11764 try { 11765 // writer 11766 synchronized (mPackages) { 11767 pkgSetting = mSettings.mPackages.get(packageName); 11768 if (pkgSetting == null) { 11769 return true; 11770 } 11771 return pkgSetting.getHidden(userId); 11772 } 11773 } finally { 11774 Binder.restoreCallingIdentity(callingId); 11775 } 11776 } 11777 11778 /** 11779 * @hide 11780 */ 11781 @Override 11782 public int installExistingPackageAsUser(String packageName, int userId) { 11783 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11784 null); 11785 PackageSetting pkgSetting; 11786 final int uid = Binder.getCallingUid(); 11787 enforceCrossUserPermission(uid, userId, 11788 true /* requireFullPermission */, true /* checkShell */, 11789 "installExistingPackage for user " + userId); 11790 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11791 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11792 } 11793 11794 long callingId = Binder.clearCallingIdentity(); 11795 try { 11796 boolean installed = false; 11797 11798 // writer 11799 synchronized (mPackages) { 11800 pkgSetting = mSettings.mPackages.get(packageName); 11801 if (pkgSetting == null) { 11802 return PackageManager.INSTALL_FAILED_INVALID_URI; 11803 } 11804 if (!pkgSetting.getInstalled(userId)) { 11805 pkgSetting.setInstalled(true, userId); 11806 pkgSetting.setHidden(false, userId); 11807 mSettings.writePackageRestrictionsLPr(userId); 11808 installed = true; 11809 } 11810 } 11811 11812 if (installed) { 11813 if (pkgSetting.pkg != null) { 11814 synchronized (mInstallLock) { 11815 // We don't need to freeze for a brand new install 11816 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11817 } 11818 } 11819 sendPackageAddedForUser(packageName, pkgSetting, userId); 11820 } 11821 } finally { 11822 Binder.restoreCallingIdentity(callingId); 11823 } 11824 11825 return PackageManager.INSTALL_SUCCEEDED; 11826 } 11827 11828 boolean isUserRestricted(int userId, String restrictionKey) { 11829 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11830 if (restrictions.getBoolean(restrictionKey, false)) { 11831 Log.w(TAG, "User is restricted: " + restrictionKey); 11832 return true; 11833 } 11834 return false; 11835 } 11836 11837 @Override 11838 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11839 int userId) { 11840 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11841 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11842 true /* requireFullPermission */, true /* checkShell */, 11843 "setPackagesSuspended for user " + userId); 11844 11845 if (ArrayUtils.isEmpty(packageNames)) { 11846 return packageNames; 11847 } 11848 11849 // List of package names for whom the suspended state has changed. 11850 List<String> changedPackages = new ArrayList<>(packageNames.length); 11851 // List of package names for whom the suspended state is not set as requested in this 11852 // method. 11853 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11854 long callingId = Binder.clearCallingIdentity(); 11855 try { 11856 for (int i = 0; i < packageNames.length; i++) { 11857 String packageName = packageNames[i]; 11858 boolean changed = false; 11859 final int appId; 11860 synchronized (mPackages) { 11861 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11862 if (pkgSetting == null) { 11863 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11864 + "\". Skipping suspending/un-suspending."); 11865 unactionedPackages.add(packageName); 11866 continue; 11867 } 11868 appId = pkgSetting.appId; 11869 if (pkgSetting.getSuspended(userId) != suspended) { 11870 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11871 unactionedPackages.add(packageName); 11872 continue; 11873 } 11874 pkgSetting.setSuspended(suspended, userId); 11875 mSettings.writePackageRestrictionsLPr(userId); 11876 changed = true; 11877 changedPackages.add(packageName); 11878 } 11879 } 11880 11881 if (changed && suspended) { 11882 killApplication(packageName, UserHandle.getUid(userId, appId), 11883 "suspending package"); 11884 } 11885 } 11886 } finally { 11887 Binder.restoreCallingIdentity(callingId); 11888 } 11889 11890 if (!changedPackages.isEmpty()) { 11891 sendPackagesSuspendedForUser(changedPackages.toArray( 11892 new String[changedPackages.size()]), userId, suspended); 11893 } 11894 11895 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11896 } 11897 11898 @Override 11899 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11900 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11901 true /* requireFullPermission */, false /* checkShell */, 11902 "isPackageSuspendedForUser for user " + userId); 11903 synchronized (mPackages) { 11904 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11905 if (pkgSetting == null) { 11906 throw new IllegalArgumentException("Unknown target package: " + packageName); 11907 } 11908 return pkgSetting.getSuspended(userId); 11909 } 11910 } 11911 11912 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11913 if (isPackageDeviceAdmin(packageName, userId)) { 11914 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11915 + "\": has an active device admin"); 11916 return false; 11917 } 11918 11919 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11920 if (packageName.equals(activeLauncherPackageName)) { 11921 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11922 + "\": contains the active launcher"); 11923 return false; 11924 } 11925 11926 if (packageName.equals(mRequiredInstallerPackage)) { 11927 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11928 + "\": required for package installation"); 11929 return false; 11930 } 11931 11932 if (packageName.equals(mRequiredVerifierPackage)) { 11933 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11934 + "\": required for package verification"); 11935 return false; 11936 } 11937 11938 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11939 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11940 + "\": is the default dialer"); 11941 return false; 11942 } 11943 11944 return true; 11945 } 11946 11947 private String getActiveLauncherPackageName(int userId) { 11948 Intent intent = new Intent(Intent.ACTION_MAIN); 11949 intent.addCategory(Intent.CATEGORY_HOME); 11950 ResolveInfo resolveInfo = resolveIntent( 11951 intent, 11952 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11953 PackageManager.MATCH_DEFAULT_ONLY, 11954 userId); 11955 11956 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11957 } 11958 11959 private String getDefaultDialerPackageName(int userId) { 11960 synchronized (mPackages) { 11961 return mSettings.getDefaultDialerPackageNameLPw(userId); 11962 } 11963 } 11964 11965 @Override 11966 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11967 mContext.enforceCallingOrSelfPermission( 11968 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11969 "Only package verification agents can verify applications"); 11970 11971 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11972 final PackageVerificationResponse response = new PackageVerificationResponse( 11973 verificationCode, Binder.getCallingUid()); 11974 msg.arg1 = id; 11975 msg.obj = response; 11976 mHandler.sendMessage(msg); 11977 } 11978 11979 @Override 11980 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11981 long millisecondsToDelay) { 11982 mContext.enforceCallingOrSelfPermission( 11983 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11984 "Only package verification agents can extend verification timeouts"); 11985 11986 final PackageVerificationState state = mPendingVerification.get(id); 11987 final PackageVerificationResponse response = new PackageVerificationResponse( 11988 verificationCodeAtTimeout, Binder.getCallingUid()); 11989 11990 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11991 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11992 } 11993 if (millisecondsToDelay < 0) { 11994 millisecondsToDelay = 0; 11995 } 11996 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11997 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11998 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11999 } 12000 12001 if ((state != null) && !state.timeoutExtended()) { 12002 state.extendTimeout(); 12003 12004 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 12005 msg.arg1 = id; 12006 msg.obj = response; 12007 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 12008 } 12009 } 12010 12011 private void broadcastPackageVerified(int verificationId, Uri packageUri, 12012 int verificationCode, UserHandle user) { 12013 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 12014 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 12015 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12016 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12017 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 12018 12019 mContext.sendBroadcastAsUser(intent, user, 12020 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 12021 } 12022 12023 private ComponentName matchComponentForVerifier(String packageName, 12024 List<ResolveInfo> receivers) { 12025 ActivityInfo targetReceiver = null; 12026 12027 final int NR = receivers.size(); 12028 for (int i = 0; i < NR; i++) { 12029 final ResolveInfo info = receivers.get(i); 12030 if (info.activityInfo == null) { 12031 continue; 12032 } 12033 12034 if (packageName.equals(info.activityInfo.packageName)) { 12035 targetReceiver = info.activityInfo; 12036 break; 12037 } 12038 } 12039 12040 if (targetReceiver == null) { 12041 return null; 12042 } 12043 12044 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12045 } 12046 12047 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12048 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12049 if (pkgInfo.verifiers.length == 0) { 12050 return null; 12051 } 12052 12053 final int N = pkgInfo.verifiers.length; 12054 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12055 for (int i = 0; i < N; i++) { 12056 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12057 12058 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12059 receivers); 12060 if (comp == null) { 12061 continue; 12062 } 12063 12064 final int verifierUid = getUidForVerifier(verifierInfo); 12065 if (verifierUid == -1) { 12066 continue; 12067 } 12068 12069 if (DEBUG_VERIFY) { 12070 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12071 + " with the correct signature"); 12072 } 12073 sufficientVerifiers.add(comp); 12074 verificationState.addSufficientVerifier(verifierUid); 12075 } 12076 12077 return sufficientVerifiers; 12078 } 12079 12080 private int getUidForVerifier(VerifierInfo verifierInfo) { 12081 synchronized (mPackages) { 12082 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12083 if (pkg == null) { 12084 return -1; 12085 } else if (pkg.mSignatures.length != 1) { 12086 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12087 + " has more than one signature; ignoring"); 12088 return -1; 12089 } 12090 12091 /* 12092 * If the public key of the package's signature does not match 12093 * our expected public key, then this is a different package and 12094 * we should skip. 12095 */ 12096 12097 final byte[] expectedPublicKey; 12098 try { 12099 final Signature verifierSig = pkg.mSignatures[0]; 12100 final PublicKey publicKey = verifierSig.getPublicKey(); 12101 expectedPublicKey = publicKey.getEncoded(); 12102 } catch (CertificateException e) { 12103 return -1; 12104 } 12105 12106 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12107 12108 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12109 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12110 + " does not have the expected public key; ignoring"); 12111 return -1; 12112 } 12113 12114 return pkg.applicationInfo.uid; 12115 } 12116 } 12117 12118 @Override 12119 public void finishPackageInstall(int token, boolean didLaunch) { 12120 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12121 12122 if (DEBUG_INSTALL) { 12123 Slog.v(TAG, "BM finishing package install for " + token); 12124 } 12125 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12126 12127 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12128 mHandler.sendMessage(msg); 12129 } 12130 12131 /** 12132 * Get the verification agent timeout. 12133 * 12134 * @return verification timeout in milliseconds 12135 */ 12136 private long getVerificationTimeout() { 12137 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12138 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12139 DEFAULT_VERIFICATION_TIMEOUT); 12140 } 12141 12142 /** 12143 * Get the default verification agent response code. 12144 * 12145 * @return default verification response code 12146 */ 12147 private int getDefaultVerificationResponse() { 12148 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12149 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12150 DEFAULT_VERIFICATION_RESPONSE); 12151 } 12152 12153 /** 12154 * Check whether or not package verification has been enabled. 12155 * 12156 * @return true if verification should be performed 12157 */ 12158 private boolean isVerificationEnabled(int userId, int installFlags) { 12159 if (!DEFAULT_VERIFY_ENABLE) { 12160 return false; 12161 } 12162 // Ephemeral apps don't get the full verification treatment 12163 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12164 if (DEBUG_EPHEMERAL) { 12165 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12166 } 12167 return false; 12168 } 12169 12170 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12171 12172 // Check if installing from ADB 12173 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12174 // Do not run verification in a test harness environment 12175 if (ActivityManager.isRunningInTestHarness()) { 12176 return false; 12177 } 12178 if (ensureVerifyAppsEnabled) { 12179 return true; 12180 } 12181 // Check if the developer does not want package verification for ADB installs 12182 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12183 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12184 return false; 12185 } 12186 } 12187 12188 if (ensureVerifyAppsEnabled) { 12189 return true; 12190 } 12191 12192 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12193 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12194 } 12195 12196 @Override 12197 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12198 throws RemoteException { 12199 mContext.enforceCallingOrSelfPermission( 12200 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12201 "Only intentfilter verification agents can verify applications"); 12202 12203 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12204 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12205 Binder.getCallingUid(), verificationCode, failedDomains); 12206 msg.arg1 = id; 12207 msg.obj = response; 12208 mHandler.sendMessage(msg); 12209 } 12210 12211 @Override 12212 public int getIntentVerificationStatus(String packageName, int userId) { 12213 synchronized (mPackages) { 12214 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12215 } 12216 } 12217 12218 @Override 12219 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12220 mContext.enforceCallingOrSelfPermission( 12221 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12222 12223 boolean result = false; 12224 synchronized (mPackages) { 12225 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12226 } 12227 if (result) { 12228 scheduleWritePackageRestrictionsLocked(userId); 12229 } 12230 return result; 12231 } 12232 12233 @Override 12234 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12235 String packageName) { 12236 synchronized (mPackages) { 12237 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12238 } 12239 } 12240 12241 @Override 12242 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12243 if (TextUtils.isEmpty(packageName)) { 12244 return ParceledListSlice.emptyList(); 12245 } 12246 synchronized (mPackages) { 12247 PackageParser.Package pkg = mPackages.get(packageName); 12248 if (pkg == null || pkg.activities == null) { 12249 return ParceledListSlice.emptyList(); 12250 } 12251 final int count = pkg.activities.size(); 12252 ArrayList<IntentFilter> result = new ArrayList<>(); 12253 for (int n=0; n<count; n++) { 12254 PackageParser.Activity activity = pkg.activities.get(n); 12255 if (activity.intents != null && activity.intents.size() > 0) { 12256 result.addAll(activity.intents); 12257 } 12258 } 12259 return new ParceledListSlice<>(result); 12260 } 12261 } 12262 12263 @Override 12264 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12265 mContext.enforceCallingOrSelfPermission( 12266 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12267 12268 synchronized (mPackages) { 12269 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12270 if (packageName != null) { 12271 result |= updateIntentVerificationStatus(packageName, 12272 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12273 userId); 12274 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12275 packageName, userId); 12276 } 12277 return result; 12278 } 12279 } 12280 12281 @Override 12282 public String getDefaultBrowserPackageName(int userId) { 12283 synchronized (mPackages) { 12284 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12285 } 12286 } 12287 12288 /** 12289 * Get the "allow unknown sources" setting. 12290 * 12291 * @return the current "allow unknown sources" setting 12292 */ 12293 private int getUnknownSourcesSettings() { 12294 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12295 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12296 -1); 12297 } 12298 12299 @Override 12300 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12301 final int uid = Binder.getCallingUid(); 12302 // writer 12303 synchronized (mPackages) { 12304 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12305 if (targetPackageSetting == null) { 12306 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12307 } 12308 12309 PackageSetting installerPackageSetting; 12310 if (installerPackageName != null) { 12311 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12312 if (installerPackageSetting == null) { 12313 throw new IllegalArgumentException("Unknown installer package: " 12314 + installerPackageName); 12315 } 12316 } else { 12317 installerPackageSetting = null; 12318 } 12319 12320 Signature[] callerSignature; 12321 Object obj = mSettings.getUserIdLPr(uid); 12322 if (obj != null) { 12323 if (obj instanceof SharedUserSetting) { 12324 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12325 } else if (obj instanceof PackageSetting) { 12326 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12327 } else { 12328 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12329 } 12330 } else { 12331 throw new SecurityException("Unknown calling UID: " + uid); 12332 } 12333 12334 // Verify: can't set installerPackageName to a package that is 12335 // not signed with the same cert as the caller. 12336 if (installerPackageSetting != null) { 12337 if (compareSignatures(callerSignature, 12338 installerPackageSetting.signatures.mSignatures) 12339 != PackageManager.SIGNATURE_MATCH) { 12340 throw new SecurityException( 12341 "Caller does not have same cert as new installer package " 12342 + installerPackageName); 12343 } 12344 } 12345 12346 // Verify: if target already has an installer package, it must 12347 // be signed with the same cert as the caller. 12348 if (targetPackageSetting.installerPackageName != null) { 12349 PackageSetting setting = mSettings.mPackages.get( 12350 targetPackageSetting.installerPackageName); 12351 // If the currently set package isn't valid, then it's always 12352 // okay to change it. 12353 if (setting != null) { 12354 if (compareSignatures(callerSignature, 12355 setting.signatures.mSignatures) 12356 != PackageManager.SIGNATURE_MATCH) { 12357 throw new SecurityException( 12358 "Caller does not have same cert as old installer package " 12359 + targetPackageSetting.installerPackageName); 12360 } 12361 } 12362 } 12363 12364 // Okay! 12365 targetPackageSetting.installerPackageName = installerPackageName; 12366 if (installerPackageName != null) { 12367 mSettings.mInstallerPackages.add(installerPackageName); 12368 } 12369 scheduleWriteSettingsLocked(); 12370 } 12371 } 12372 12373 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12374 // Queue up an async operation since the package installation may take a little while. 12375 mHandler.post(new Runnable() { 12376 public void run() { 12377 mHandler.removeCallbacks(this); 12378 // Result object to be returned 12379 PackageInstalledInfo res = new PackageInstalledInfo(); 12380 res.setReturnCode(currentStatus); 12381 res.uid = -1; 12382 res.pkg = null; 12383 res.removedInfo = null; 12384 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12385 args.doPreInstall(res.returnCode); 12386 synchronized (mInstallLock) { 12387 installPackageTracedLI(args, res); 12388 } 12389 args.doPostInstall(res.returnCode, res.uid); 12390 } 12391 12392 // A restore should be performed at this point if (a) the install 12393 // succeeded, (b) the operation is not an update, and (c) the new 12394 // package has not opted out of backup participation. 12395 final boolean update = res.removedInfo != null 12396 && res.removedInfo.removedPackage != null; 12397 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12398 boolean doRestore = !update 12399 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12400 12401 // Set up the post-install work request bookkeeping. This will be used 12402 // and cleaned up by the post-install event handling regardless of whether 12403 // there's a restore pass performed. Token values are >= 1. 12404 int token; 12405 if (mNextInstallToken < 0) mNextInstallToken = 1; 12406 token = mNextInstallToken++; 12407 12408 PostInstallData data = new PostInstallData(args, res); 12409 mRunningInstalls.put(token, data); 12410 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12411 12412 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12413 // Pass responsibility to the Backup Manager. It will perform a 12414 // restore if appropriate, then pass responsibility back to the 12415 // Package Manager to run the post-install observer callbacks 12416 // and broadcasts. 12417 IBackupManager bm = IBackupManager.Stub.asInterface( 12418 ServiceManager.getService(Context.BACKUP_SERVICE)); 12419 if (bm != null) { 12420 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12421 + " to BM for possible restore"); 12422 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12423 try { 12424 // TODO: http://b/22388012 12425 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12426 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12427 } else { 12428 doRestore = false; 12429 } 12430 } catch (RemoteException e) { 12431 // can't happen; the backup manager is local 12432 } catch (Exception e) { 12433 Slog.e(TAG, "Exception trying to enqueue restore", e); 12434 doRestore = false; 12435 } 12436 } else { 12437 Slog.e(TAG, "Backup Manager not found!"); 12438 doRestore = false; 12439 } 12440 } 12441 12442 if (!doRestore) { 12443 // No restore possible, or the Backup Manager was mysteriously not 12444 // available -- just fire the post-install work request directly. 12445 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12446 12447 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12448 12449 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12450 mHandler.sendMessage(msg); 12451 } 12452 } 12453 }); 12454 } 12455 12456 /** 12457 * Callback from PackageSettings whenever an app is first transitioned out of the 12458 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12459 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12460 * here whether the app is the target of an ongoing install, and only send the 12461 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12462 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12463 * handling. 12464 */ 12465 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12466 // Serialize this with the rest of the install-process message chain. In the 12467 // restore-at-install case, this Runnable will necessarily run before the 12468 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12469 // are coherent. In the non-restore case, the app has already completed install 12470 // and been launched through some other means, so it is not in a problematic 12471 // state for observers to see the FIRST_LAUNCH signal. 12472 mHandler.post(new Runnable() { 12473 @Override 12474 public void run() { 12475 for (int i = 0; i < mRunningInstalls.size(); i++) { 12476 final PostInstallData data = mRunningInstalls.valueAt(i); 12477 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12478 // right package; but is it for the right user? 12479 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12480 if (userId == data.res.newUsers[uIndex]) { 12481 if (DEBUG_BACKUP) { 12482 Slog.i(TAG, "Package " + pkgName 12483 + " being restored so deferring FIRST_LAUNCH"); 12484 } 12485 return; 12486 } 12487 } 12488 } 12489 } 12490 // didn't find it, so not being restored 12491 if (DEBUG_BACKUP) { 12492 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12493 } 12494 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12495 } 12496 }); 12497 } 12498 12499 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12500 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12501 installerPkg, null, userIds); 12502 } 12503 12504 private abstract class HandlerParams { 12505 private static final int MAX_RETRIES = 4; 12506 12507 /** 12508 * Number of times startCopy() has been attempted and had a non-fatal 12509 * error. 12510 */ 12511 private int mRetries = 0; 12512 12513 /** User handle for the user requesting the information or installation. */ 12514 private final UserHandle mUser; 12515 String traceMethod; 12516 int traceCookie; 12517 12518 HandlerParams(UserHandle user) { 12519 mUser = user; 12520 } 12521 12522 UserHandle getUser() { 12523 return mUser; 12524 } 12525 12526 HandlerParams setTraceMethod(String traceMethod) { 12527 this.traceMethod = traceMethod; 12528 return this; 12529 } 12530 12531 HandlerParams setTraceCookie(int traceCookie) { 12532 this.traceCookie = traceCookie; 12533 return this; 12534 } 12535 12536 final boolean startCopy() { 12537 boolean res; 12538 try { 12539 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12540 12541 if (++mRetries > MAX_RETRIES) { 12542 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12543 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12544 handleServiceError(); 12545 return false; 12546 } else { 12547 handleStartCopy(); 12548 res = true; 12549 } 12550 } catch (RemoteException e) { 12551 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12552 mHandler.sendEmptyMessage(MCS_RECONNECT); 12553 res = false; 12554 } 12555 handleReturnCode(); 12556 return res; 12557 } 12558 12559 final void serviceError() { 12560 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12561 handleServiceError(); 12562 handleReturnCode(); 12563 } 12564 12565 abstract void handleStartCopy() throws RemoteException; 12566 abstract void handleServiceError(); 12567 abstract void handleReturnCode(); 12568 } 12569 12570 class MeasureParams extends HandlerParams { 12571 private final PackageStats mStats; 12572 private boolean mSuccess; 12573 12574 private final IPackageStatsObserver mObserver; 12575 12576 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12577 super(new UserHandle(stats.userHandle)); 12578 mObserver = observer; 12579 mStats = stats; 12580 } 12581 12582 @Override 12583 public String toString() { 12584 return "MeasureParams{" 12585 + Integer.toHexString(System.identityHashCode(this)) 12586 + " " + mStats.packageName + "}"; 12587 } 12588 12589 @Override 12590 void handleStartCopy() throws RemoteException { 12591 synchronized (mInstallLock) { 12592 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12593 } 12594 12595 if (mSuccess) { 12596 boolean mounted = false; 12597 try { 12598 final String status = Environment.getExternalStorageState(); 12599 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12600 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12601 } catch (Exception e) { 12602 } 12603 12604 if (mounted) { 12605 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12606 12607 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12608 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12609 12610 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12611 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12612 12613 // Always subtract cache size, since it's a subdirectory 12614 mStats.externalDataSize -= mStats.externalCacheSize; 12615 12616 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12617 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12618 12619 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12620 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12621 } 12622 } 12623 } 12624 12625 @Override 12626 void handleReturnCode() { 12627 if (mObserver != null) { 12628 try { 12629 mObserver.onGetStatsCompleted(mStats, mSuccess); 12630 } catch (RemoteException e) { 12631 Slog.i(TAG, "Observer no longer exists."); 12632 } 12633 } 12634 } 12635 12636 @Override 12637 void handleServiceError() { 12638 Slog.e(TAG, "Could not measure application " + mStats.packageName 12639 + " external storage"); 12640 } 12641 } 12642 12643 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12644 throws RemoteException { 12645 long result = 0; 12646 for (File path : paths) { 12647 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12648 } 12649 return result; 12650 } 12651 12652 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12653 for (File path : paths) { 12654 try { 12655 mcs.clearDirectory(path.getAbsolutePath()); 12656 } catch (RemoteException e) { 12657 } 12658 } 12659 } 12660 12661 static class OriginInfo { 12662 /** 12663 * Location where install is coming from, before it has been 12664 * copied/renamed into place. This could be a single monolithic APK 12665 * file, or a cluster directory. This location may be untrusted. 12666 */ 12667 final File file; 12668 final String cid; 12669 12670 /** 12671 * Flag indicating that {@link #file} or {@link #cid} has already been 12672 * staged, meaning downstream users don't need to defensively copy the 12673 * contents. 12674 */ 12675 final boolean staged; 12676 12677 /** 12678 * Flag indicating that {@link #file} or {@link #cid} is an already 12679 * installed app that is being moved. 12680 */ 12681 final boolean existing; 12682 12683 final String resolvedPath; 12684 final File resolvedFile; 12685 12686 static OriginInfo fromNothing() { 12687 return new OriginInfo(null, null, false, false); 12688 } 12689 12690 static OriginInfo fromUntrustedFile(File file) { 12691 return new OriginInfo(file, null, false, false); 12692 } 12693 12694 static OriginInfo fromExistingFile(File file) { 12695 return new OriginInfo(file, null, false, true); 12696 } 12697 12698 static OriginInfo fromStagedFile(File file) { 12699 return new OriginInfo(file, null, true, false); 12700 } 12701 12702 static OriginInfo fromStagedContainer(String cid) { 12703 return new OriginInfo(null, cid, true, false); 12704 } 12705 12706 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12707 this.file = file; 12708 this.cid = cid; 12709 this.staged = staged; 12710 this.existing = existing; 12711 12712 if (cid != null) { 12713 resolvedPath = PackageHelper.getSdDir(cid); 12714 resolvedFile = new File(resolvedPath); 12715 } else if (file != null) { 12716 resolvedPath = file.getAbsolutePath(); 12717 resolvedFile = file; 12718 } else { 12719 resolvedPath = null; 12720 resolvedFile = null; 12721 } 12722 } 12723 } 12724 12725 static class MoveInfo { 12726 final int moveId; 12727 final String fromUuid; 12728 final String toUuid; 12729 final String packageName; 12730 final String dataAppName; 12731 final int appId; 12732 final String seinfo; 12733 final int targetSdkVersion; 12734 12735 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12736 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12737 this.moveId = moveId; 12738 this.fromUuid = fromUuid; 12739 this.toUuid = toUuid; 12740 this.packageName = packageName; 12741 this.dataAppName = dataAppName; 12742 this.appId = appId; 12743 this.seinfo = seinfo; 12744 this.targetSdkVersion = targetSdkVersion; 12745 } 12746 } 12747 12748 static class VerificationInfo { 12749 /** A constant used to indicate that a uid value is not present. */ 12750 public static final int NO_UID = -1; 12751 12752 /** URI referencing where the package was downloaded from. */ 12753 final Uri originatingUri; 12754 12755 /** HTTP referrer URI associated with the originatingURI. */ 12756 final Uri referrer; 12757 12758 /** UID of the application that the install request originated from. */ 12759 final int originatingUid; 12760 12761 /** UID of application requesting the install */ 12762 final int installerUid; 12763 12764 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12765 this.originatingUri = originatingUri; 12766 this.referrer = referrer; 12767 this.originatingUid = originatingUid; 12768 this.installerUid = installerUid; 12769 } 12770 } 12771 12772 class InstallParams extends HandlerParams { 12773 final OriginInfo origin; 12774 final MoveInfo move; 12775 final IPackageInstallObserver2 observer; 12776 int installFlags; 12777 final String installerPackageName; 12778 final String volumeUuid; 12779 private InstallArgs mArgs; 12780 private int mRet; 12781 final String packageAbiOverride; 12782 final String[] grantedRuntimePermissions; 12783 final VerificationInfo verificationInfo; 12784 final Certificate[][] certificates; 12785 12786 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12787 int installFlags, String installerPackageName, String volumeUuid, 12788 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12789 String[] grantedPermissions, Certificate[][] certificates) { 12790 super(user); 12791 this.origin = origin; 12792 this.move = move; 12793 this.observer = observer; 12794 this.installFlags = installFlags; 12795 this.installerPackageName = installerPackageName; 12796 this.volumeUuid = volumeUuid; 12797 this.verificationInfo = verificationInfo; 12798 this.packageAbiOverride = packageAbiOverride; 12799 this.grantedRuntimePermissions = grantedPermissions; 12800 this.certificates = certificates; 12801 } 12802 12803 @Override 12804 public String toString() { 12805 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12806 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12807 } 12808 12809 private int installLocationPolicy(PackageInfoLite pkgLite) { 12810 String packageName = pkgLite.packageName; 12811 int installLocation = pkgLite.installLocation; 12812 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12813 // reader 12814 synchronized (mPackages) { 12815 // Currently installed package which the new package is attempting to replace or 12816 // null if no such package is installed. 12817 PackageParser.Package installedPkg = mPackages.get(packageName); 12818 // Package which currently owns the data which the new package will own if installed. 12819 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12820 // will be null whereas dataOwnerPkg will contain information about the package 12821 // which was uninstalled while keeping its data. 12822 PackageParser.Package dataOwnerPkg = installedPkg; 12823 if (dataOwnerPkg == null) { 12824 PackageSetting ps = mSettings.mPackages.get(packageName); 12825 if (ps != null) { 12826 dataOwnerPkg = ps.pkg; 12827 } 12828 } 12829 12830 if (dataOwnerPkg != null) { 12831 // If installed, the package will get access to data left on the device by its 12832 // predecessor. As a security measure, this is permited only if this is not a 12833 // version downgrade or if the predecessor package is marked as debuggable and 12834 // a downgrade is explicitly requested. 12835 // 12836 // On debuggable platform builds, downgrades are permitted even for 12837 // non-debuggable packages to make testing easier. Debuggable platform builds do 12838 // not offer security guarantees and thus it's OK to disable some security 12839 // mechanisms to make debugging/testing easier on those builds. However, even on 12840 // debuggable builds downgrades of packages are permitted only if requested via 12841 // installFlags. This is because we aim to keep the behavior of debuggable 12842 // platform builds as close as possible to the behavior of non-debuggable 12843 // platform builds. 12844 final boolean downgradeRequested = 12845 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12846 final boolean packageDebuggable = 12847 (dataOwnerPkg.applicationInfo.flags 12848 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12849 final boolean downgradePermitted = 12850 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12851 if (!downgradePermitted) { 12852 try { 12853 checkDowngrade(dataOwnerPkg, pkgLite); 12854 } catch (PackageManagerException e) { 12855 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12856 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12857 } 12858 } 12859 } 12860 12861 if (installedPkg != null) { 12862 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12863 // Check for updated system application. 12864 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12865 if (onSd) { 12866 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12867 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12868 } 12869 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12870 } else { 12871 if (onSd) { 12872 // Install flag overrides everything. 12873 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12874 } 12875 // If current upgrade specifies particular preference 12876 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12877 // Application explicitly specified internal. 12878 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12879 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12880 // App explictly prefers external. Let policy decide 12881 } else { 12882 // Prefer previous location 12883 if (isExternal(installedPkg)) { 12884 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12885 } 12886 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12887 } 12888 } 12889 } else { 12890 // Invalid install. Return error code 12891 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12892 } 12893 } 12894 } 12895 // All the special cases have been taken care of. 12896 // Return result based on recommended install location. 12897 if (onSd) { 12898 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12899 } 12900 return pkgLite.recommendedInstallLocation; 12901 } 12902 12903 /* 12904 * Invoke remote method to get package information and install 12905 * location values. Override install location based on default 12906 * policy if needed and then create install arguments based 12907 * on the install location. 12908 */ 12909 public void handleStartCopy() throws RemoteException { 12910 int ret = PackageManager.INSTALL_SUCCEEDED; 12911 12912 // If we're already staged, we've firmly committed to an install location 12913 if (origin.staged) { 12914 if (origin.file != null) { 12915 installFlags |= PackageManager.INSTALL_INTERNAL; 12916 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12917 } else if (origin.cid != null) { 12918 installFlags |= PackageManager.INSTALL_EXTERNAL; 12919 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12920 } else { 12921 throw new IllegalStateException("Invalid stage location"); 12922 } 12923 } 12924 12925 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12926 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12927 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12928 PackageInfoLite pkgLite = null; 12929 12930 if (onInt && onSd) { 12931 // Check if both bits are set. 12932 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12933 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12934 } else if (onSd && ephemeral) { 12935 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12936 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12937 } else { 12938 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12939 packageAbiOverride); 12940 12941 if (DEBUG_EPHEMERAL && ephemeral) { 12942 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12943 } 12944 12945 /* 12946 * If we have too little free space, try to free cache 12947 * before giving up. 12948 */ 12949 if (!origin.staged && pkgLite.recommendedInstallLocation 12950 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12951 // TODO: focus freeing disk space on the target device 12952 final StorageManager storage = StorageManager.from(mContext); 12953 final long lowThreshold = storage.getStorageLowBytes( 12954 Environment.getDataDirectory()); 12955 12956 final long sizeBytes = mContainerService.calculateInstalledSize( 12957 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12958 12959 try { 12960 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12961 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12962 installFlags, packageAbiOverride); 12963 } catch (InstallerException e) { 12964 Slog.w(TAG, "Failed to free cache", e); 12965 } 12966 12967 /* 12968 * The cache free must have deleted the file we 12969 * downloaded to install. 12970 * 12971 * TODO: fix the "freeCache" call to not delete 12972 * the file we care about. 12973 */ 12974 if (pkgLite.recommendedInstallLocation 12975 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12976 pkgLite.recommendedInstallLocation 12977 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12978 } 12979 } 12980 } 12981 12982 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12983 int loc = pkgLite.recommendedInstallLocation; 12984 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12985 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12986 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12987 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12988 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12989 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12990 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12991 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12992 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12993 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12994 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12995 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12996 } else { 12997 // Override with defaults if needed. 12998 loc = installLocationPolicy(pkgLite); 12999 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 13000 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 13001 } else if (!onSd && !onInt) { 13002 // Override install location with flags 13003 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 13004 // Set the flag to install on external media. 13005 installFlags |= PackageManager.INSTALL_EXTERNAL; 13006 installFlags &= ~PackageManager.INSTALL_INTERNAL; 13007 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 13008 if (DEBUG_EPHEMERAL) { 13009 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 13010 } 13011 installFlags |= PackageManager.INSTALL_EPHEMERAL; 13012 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 13013 |PackageManager.INSTALL_INTERNAL); 13014 } else { 13015 // Make sure the flag for installing on external 13016 // media is unset 13017 installFlags |= PackageManager.INSTALL_INTERNAL; 13018 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 13019 } 13020 } 13021 } 13022 } 13023 13024 final InstallArgs args = createInstallArgs(this); 13025 mArgs = args; 13026 13027 if (ret == PackageManager.INSTALL_SUCCEEDED) { 13028 // TODO: http://b/22976637 13029 // Apps installed for "all" users use the device owner to verify the app 13030 UserHandle verifierUser = getUser(); 13031 if (verifierUser == UserHandle.ALL) { 13032 verifierUser = UserHandle.SYSTEM; 13033 } 13034 13035 /* 13036 * Determine if we have any installed package verifiers. If we 13037 * do, then we'll defer to them to verify the packages. 13038 */ 13039 final int requiredUid = mRequiredVerifierPackage == null ? -1 13040 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13041 verifierUser.getIdentifier()); 13042 if (!origin.existing && requiredUid != -1 13043 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13044 final Intent verification = new Intent( 13045 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13046 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13047 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13048 PACKAGE_MIME_TYPE); 13049 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13050 13051 // Query all live verifiers based on current user state 13052 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13053 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13054 13055 if (DEBUG_VERIFY) { 13056 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13057 + verification.toString() + " with " + pkgLite.verifiers.length 13058 + " optional verifiers"); 13059 } 13060 13061 final int verificationId = mPendingVerificationToken++; 13062 13063 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13064 13065 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13066 installerPackageName); 13067 13068 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13069 installFlags); 13070 13071 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13072 pkgLite.packageName); 13073 13074 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13075 pkgLite.versionCode); 13076 13077 if (verificationInfo != null) { 13078 if (verificationInfo.originatingUri != null) { 13079 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13080 verificationInfo.originatingUri); 13081 } 13082 if (verificationInfo.referrer != null) { 13083 verification.putExtra(Intent.EXTRA_REFERRER, 13084 verificationInfo.referrer); 13085 } 13086 if (verificationInfo.originatingUid >= 0) { 13087 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13088 verificationInfo.originatingUid); 13089 } 13090 if (verificationInfo.installerUid >= 0) { 13091 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13092 verificationInfo.installerUid); 13093 } 13094 } 13095 13096 final PackageVerificationState verificationState = new PackageVerificationState( 13097 requiredUid, args); 13098 13099 mPendingVerification.append(verificationId, verificationState); 13100 13101 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13102 receivers, verificationState); 13103 13104 /* 13105 * If any sufficient verifiers were listed in the package 13106 * manifest, attempt to ask them. 13107 */ 13108 if (sufficientVerifiers != null) { 13109 final int N = sufficientVerifiers.size(); 13110 if (N == 0) { 13111 Slog.i(TAG, "Additional verifiers required, but none installed."); 13112 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13113 } else { 13114 for (int i = 0; i < N; i++) { 13115 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13116 13117 final Intent sufficientIntent = new Intent(verification); 13118 sufficientIntent.setComponent(verifierComponent); 13119 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13120 } 13121 } 13122 } 13123 13124 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13125 mRequiredVerifierPackage, receivers); 13126 if (ret == PackageManager.INSTALL_SUCCEEDED 13127 && mRequiredVerifierPackage != null) { 13128 Trace.asyncTraceBegin( 13129 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13130 /* 13131 * Send the intent to the required verification agent, 13132 * but only start the verification timeout after the 13133 * target BroadcastReceivers have run. 13134 */ 13135 verification.setComponent(requiredVerifierComponent); 13136 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13137 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13138 new BroadcastReceiver() { 13139 @Override 13140 public void onReceive(Context context, Intent intent) { 13141 final Message msg = mHandler 13142 .obtainMessage(CHECK_PENDING_VERIFICATION); 13143 msg.arg1 = verificationId; 13144 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13145 } 13146 }, null, 0, null, null); 13147 13148 /* 13149 * We don't want the copy to proceed until verification 13150 * succeeds, so null out this field. 13151 */ 13152 mArgs = null; 13153 } 13154 } else { 13155 /* 13156 * No package verification is enabled, so immediately start 13157 * the remote call to initiate copy using temporary file. 13158 */ 13159 ret = args.copyApk(mContainerService, true); 13160 } 13161 } 13162 13163 mRet = ret; 13164 } 13165 13166 @Override 13167 void handleReturnCode() { 13168 // If mArgs is null, then MCS couldn't be reached. When it 13169 // reconnects, it will try again to install. At that point, this 13170 // will succeed. 13171 if (mArgs != null) { 13172 processPendingInstall(mArgs, mRet); 13173 } 13174 } 13175 13176 @Override 13177 void handleServiceError() { 13178 mArgs = createInstallArgs(this); 13179 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13180 } 13181 13182 public boolean isForwardLocked() { 13183 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13184 } 13185 } 13186 13187 /** 13188 * Used during creation of InstallArgs 13189 * 13190 * @param installFlags package installation flags 13191 * @return true if should be installed on external storage 13192 */ 13193 private static boolean installOnExternalAsec(int installFlags) { 13194 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13195 return false; 13196 } 13197 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13198 return true; 13199 } 13200 return false; 13201 } 13202 13203 /** 13204 * Used during creation of InstallArgs 13205 * 13206 * @param installFlags package installation flags 13207 * @return true if should be installed as forward locked 13208 */ 13209 private static boolean installForwardLocked(int installFlags) { 13210 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13211 } 13212 13213 private InstallArgs createInstallArgs(InstallParams params) { 13214 if (params.move != null) { 13215 return new MoveInstallArgs(params); 13216 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13217 return new AsecInstallArgs(params); 13218 } else { 13219 return new FileInstallArgs(params); 13220 } 13221 } 13222 13223 /** 13224 * Create args that describe an existing installed package. Typically used 13225 * when cleaning up old installs, or used as a move source. 13226 */ 13227 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13228 String resourcePath, String[] instructionSets) { 13229 final boolean isInAsec; 13230 if (installOnExternalAsec(installFlags)) { 13231 /* Apps on SD card are always in ASEC containers. */ 13232 isInAsec = true; 13233 } else if (installForwardLocked(installFlags) 13234 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13235 /* 13236 * Forward-locked apps are only in ASEC containers if they're the 13237 * new style 13238 */ 13239 isInAsec = true; 13240 } else { 13241 isInAsec = false; 13242 } 13243 13244 if (isInAsec) { 13245 return new AsecInstallArgs(codePath, instructionSets, 13246 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13247 } else { 13248 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13249 } 13250 } 13251 13252 static abstract class InstallArgs { 13253 /** @see InstallParams#origin */ 13254 final OriginInfo origin; 13255 /** @see InstallParams#move */ 13256 final MoveInfo move; 13257 13258 final IPackageInstallObserver2 observer; 13259 // Always refers to PackageManager flags only 13260 final int installFlags; 13261 final String installerPackageName; 13262 final String volumeUuid; 13263 final UserHandle user; 13264 final String abiOverride; 13265 final String[] installGrantPermissions; 13266 /** If non-null, drop an async trace when the install completes */ 13267 final String traceMethod; 13268 final int traceCookie; 13269 final Certificate[][] certificates; 13270 13271 // The list of instruction sets supported by this app. This is currently 13272 // only used during the rmdex() phase to clean up resources. We can get rid of this 13273 // if we move dex files under the common app path. 13274 /* nullable */ String[] instructionSets; 13275 13276 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13277 int installFlags, String installerPackageName, String volumeUuid, 13278 UserHandle user, String[] instructionSets, 13279 String abiOverride, String[] installGrantPermissions, 13280 String traceMethod, int traceCookie, Certificate[][] certificates) { 13281 this.origin = origin; 13282 this.move = move; 13283 this.installFlags = installFlags; 13284 this.observer = observer; 13285 this.installerPackageName = installerPackageName; 13286 this.volumeUuid = volumeUuid; 13287 this.user = user; 13288 this.instructionSets = instructionSets; 13289 this.abiOverride = abiOverride; 13290 this.installGrantPermissions = installGrantPermissions; 13291 this.traceMethod = traceMethod; 13292 this.traceCookie = traceCookie; 13293 this.certificates = certificates; 13294 } 13295 13296 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13297 abstract int doPreInstall(int status); 13298 13299 /** 13300 * Rename package into final resting place. All paths on the given 13301 * scanned package should be updated to reflect the rename. 13302 */ 13303 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13304 abstract int doPostInstall(int status, int uid); 13305 13306 /** @see PackageSettingBase#codePathString */ 13307 abstract String getCodePath(); 13308 /** @see PackageSettingBase#resourcePathString */ 13309 abstract String getResourcePath(); 13310 13311 // Need installer lock especially for dex file removal. 13312 abstract void cleanUpResourcesLI(); 13313 abstract boolean doPostDeleteLI(boolean delete); 13314 13315 /** 13316 * Called before the source arguments are copied. This is used mostly 13317 * for MoveParams when it needs to read the source file to put it in the 13318 * destination. 13319 */ 13320 int doPreCopy() { 13321 return PackageManager.INSTALL_SUCCEEDED; 13322 } 13323 13324 /** 13325 * Called after the source arguments are copied. This is used mostly for 13326 * MoveParams when it needs to read the source file to put it in the 13327 * destination. 13328 */ 13329 int doPostCopy(int uid) { 13330 return PackageManager.INSTALL_SUCCEEDED; 13331 } 13332 13333 protected boolean isFwdLocked() { 13334 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13335 } 13336 13337 protected boolean isExternalAsec() { 13338 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13339 } 13340 13341 protected boolean isEphemeral() { 13342 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13343 } 13344 13345 UserHandle getUser() { 13346 return user; 13347 } 13348 } 13349 13350 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13351 if (!allCodePaths.isEmpty()) { 13352 if (instructionSets == null) { 13353 throw new IllegalStateException("instructionSet == null"); 13354 } 13355 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13356 for (String codePath : allCodePaths) { 13357 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13358 try { 13359 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13360 } catch (InstallerException ignored) { 13361 } 13362 } 13363 } 13364 } 13365 } 13366 13367 /** 13368 * Logic to handle installation of non-ASEC applications, including copying 13369 * and renaming logic. 13370 */ 13371 class FileInstallArgs extends InstallArgs { 13372 private File codeFile; 13373 private File resourceFile; 13374 13375 // Example topology: 13376 // /data/app/com.example/base.apk 13377 // /data/app/com.example/split_foo.apk 13378 // /data/app/com.example/lib/arm/libfoo.so 13379 // /data/app/com.example/lib/arm64/libfoo.so 13380 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13381 13382 /** New install */ 13383 FileInstallArgs(InstallParams params) { 13384 super(params.origin, params.move, params.observer, params.installFlags, 13385 params.installerPackageName, params.volumeUuid, 13386 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13387 params.grantedRuntimePermissions, 13388 params.traceMethod, params.traceCookie, params.certificates); 13389 if (isFwdLocked()) { 13390 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13391 } 13392 } 13393 13394 /** Existing install */ 13395 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13396 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13397 null, null, null, 0, null /*certificates*/); 13398 this.codeFile = (codePath != null) ? new File(codePath) : null; 13399 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13400 } 13401 13402 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13403 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13404 try { 13405 return doCopyApk(imcs, temp); 13406 } finally { 13407 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13408 } 13409 } 13410 13411 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13412 if (origin.staged) { 13413 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13414 codeFile = origin.file; 13415 resourceFile = origin.file; 13416 return PackageManager.INSTALL_SUCCEEDED; 13417 } 13418 13419 try { 13420 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13421 final File tempDir = 13422 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13423 codeFile = tempDir; 13424 resourceFile = tempDir; 13425 } catch (IOException e) { 13426 Slog.w(TAG, "Failed to create copy file: " + e); 13427 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13428 } 13429 13430 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13431 @Override 13432 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13433 if (!FileUtils.isValidExtFilename(name)) { 13434 throw new IllegalArgumentException("Invalid filename: " + name); 13435 } 13436 try { 13437 final File file = new File(codeFile, name); 13438 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13439 O_RDWR | O_CREAT, 0644); 13440 Os.chmod(file.getAbsolutePath(), 0644); 13441 return new ParcelFileDescriptor(fd); 13442 } catch (ErrnoException e) { 13443 throw new RemoteException("Failed to open: " + e.getMessage()); 13444 } 13445 } 13446 }; 13447 13448 int ret = PackageManager.INSTALL_SUCCEEDED; 13449 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13450 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13451 Slog.e(TAG, "Failed to copy package"); 13452 return ret; 13453 } 13454 13455 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13456 NativeLibraryHelper.Handle handle = null; 13457 try { 13458 handle = NativeLibraryHelper.Handle.create(codeFile); 13459 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13460 abiOverride); 13461 } catch (IOException e) { 13462 Slog.e(TAG, "Copying native libraries failed", e); 13463 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13464 } finally { 13465 IoUtils.closeQuietly(handle); 13466 } 13467 13468 return ret; 13469 } 13470 13471 int doPreInstall(int status) { 13472 if (status != PackageManager.INSTALL_SUCCEEDED) { 13473 cleanUp(); 13474 } 13475 return status; 13476 } 13477 13478 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13479 if (status != PackageManager.INSTALL_SUCCEEDED) { 13480 cleanUp(); 13481 return false; 13482 } 13483 13484 final File targetDir = codeFile.getParentFile(); 13485 final File beforeCodeFile = codeFile; 13486 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13487 13488 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13489 try { 13490 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13491 } catch (ErrnoException e) { 13492 Slog.w(TAG, "Failed to rename", e); 13493 return false; 13494 } 13495 13496 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13497 Slog.w(TAG, "Failed to restorecon"); 13498 return false; 13499 } 13500 13501 // Reflect the rename internally 13502 codeFile = afterCodeFile; 13503 resourceFile = afterCodeFile; 13504 13505 // Reflect the rename in scanned details 13506 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13507 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13508 afterCodeFile, pkg.baseCodePath)); 13509 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13510 afterCodeFile, pkg.splitCodePaths)); 13511 13512 // Reflect the rename in app info 13513 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13514 pkg.setApplicationInfoCodePath(pkg.codePath); 13515 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13516 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13517 pkg.setApplicationInfoResourcePath(pkg.codePath); 13518 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13519 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13520 13521 return true; 13522 } 13523 13524 int doPostInstall(int status, int uid) { 13525 if (status != PackageManager.INSTALL_SUCCEEDED) { 13526 cleanUp(); 13527 } 13528 return status; 13529 } 13530 13531 @Override 13532 String getCodePath() { 13533 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13534 } 13535 13536 @Override 13537 String getResourcePath() { 13538 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13539 } 13540 13541 private boolean cleanUp() { 13542 if (codeFile == null || !codeFile.exists()) { 13543 return false; 13544 } 13545 13546 removeCodePathLI(codeFile); 13547 13548 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13549 resourceFile.delete(); 13550 } 13551 13552 return true; 13553 } 13554 13555 void cleanUpResourcesLI() { 13556 // Try enumerating all code paths before deleting 13557 List<String> allCodePaths = Collections.EMPTY_LIST; 13558 if (codeFile != null && codeFile.exists()) { 13559 try { 13560 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13561 allCodePaths = pkg.getAllCodePaths(); 13562 } catch (PackageParserException e) { 13563 // Ignored; we tried our best 13564 } 13565 } 13566 13567 cleanUp(); 13568 removeDexFiles(allCodePaths, instructionSets); 13569 } 13570 13571 boolean doPostDeleteLI(boolean delete) { 13572 // XXX err, shouldn't we respect the delete flag? 13573 cleanUpResourcesLI(); 13574 return true; 13575 } 13576 } 13577 13578 private boolean isAsecExternal(String cid) { 13579 final String asecPath = PackageHelper.getSdFilesystem(cid); 13580 return !asecPath.startsWith(mAsecInternalPath); 13581 } 13582 13583 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13584 PackageManagerException { 13585 if (copyRet < 0) { 13586 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13587 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13588 throw new PackageManagerException(copyRet, message); 13589 } 13590 } 13591 } 13592 13593 /** 13594 * Extract the MountService "container ID" from the full code path of an 13595 * .apk. 13596 */ 13597 static String cidFromCodePath(String fullCodePath) { 13598 int eidx = fullCodePath.lastIndexOf("/"); 13599 String subStr1 = fullCodePath.substring(0, eidx); 13600 int sidx = subStr1.lastIndexOf("/"); 13601 return subStr1.substring(sidx+1, eidx); 13602 } 13603 13604 /** 13605 * Logic to handle installation of ASEC applications, including copying and 13606 * renaming logic. 13607 */ 13608 class AsecInstallArgs extends InstallArgs { 13609 static final String RES_FILE_NAME = "pkg.apk"; 13610 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13611 13612 String cid; 13613 String packagePath; 13614 String resourcePath; 13615 13616 /** New install */ 13617 AsecInstallArgs(InstallParams params) { 13618 super(params.origin, params.move, params.observer, params.installFlags, 13619 params.installerPackageName, params.volumeUuid, 13620 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13621 params.grantedRuntimePermissions, 13622 params.traceMethod, params.traceCookie, params.certificates); 13623 } 13624 13625 /** Existing install */ 13626 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13627 boolean isExternal, boolean isForwardLocked) { 13628 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13629 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13630 instructionSets, null, null, null, 0, null /*certificates*/); 13631 // Hackily pretend we're still looking at a full code path 13632 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13633 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13634 } 13635 13636 // Extract cid from fullCodePath 13637 int eidx = fullCodePath.lastIndexOf("/"); 13638 String subStr1 = fullCodePath.substring(0, eidx); 13639 int sidx = subStr1.lastIndexOf("/"); 13640 cid = subStr1.substring(sidx+1, eidx); 13641 setMountPath(subStr1); 13642 } 13643 13644 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13645 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13646 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13647 instructionSets, null, null, null, 0, null /*certificates*/); 13648 this.cid = cid; 13649 setMountPath(PackageHelper.getSdDir(cid)); 13650 } 13651 13652 void createCopyFile() { 13653 cid = mInstallerService.allocateExternalStageCidLegacy(); 13654 } 13655 13656 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13657 if (origin.staged && origin.cid != null) { 13658 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13659 cid = origin.cid; 13660 setMountPath(PackageHelper.getSdDir(cid)); 13661 return PackageManager.INSTALL_SUCCEEDED; 13662 } 13663 13664 if (temp) { 13665 createCopyFile(); 13666 } else { 13667 /* 13668 * Pre-emptively destroy the container since it's destroyed if 13669 * copying fails due to it existing anyway. 13670 */ 13671 PackageHelper.destroySdDir(cid); 13672 } 13673 13674 final String newMountPath = imcs.copyPackageToContainer( 13675 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13676 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13677 13678 if (newMountPath != null) { 13679 setMountPath(newMountPath); 13680 return PackageManager.INSTALL_SUCCEEDED; 13681 } else { 13682 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13683 } 13684 } 13685 13686 @Override 13687 String getCodePath() { 13688 return packagePath; 13689 } 13690 13691 @Override 13692 String getResourcePath() { 13693 return resourcePath; 13694 } 13695 13696 int doPreInstall(int status) { 13697 if (status != PackageManager.INSTALL_SUCCEEDED) { 13698 // Destroy container 13699 PackageHelper.destroySdDir(cid); 13700 } else { 13701 boolean mounted = PackageHelper.isContainerMounted(cid); 13702 if (!mounted) { 13703 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13704 Process.SYSTEM_UID); 13705 if (newMountPath != null) { 13706 setMountPath(newMountPath); 13707 } else { 13708 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13709 } 13710 } 13711 } 13712 return status; 13713 } 13714 13715 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13716 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13717 String newMountPath = null; 13718 if (PackageHelper.isContainerMounted(cid)) { 13719 // Unmount the container 13720 if (!PackageHelper.unMountSdDir(cid)) { 13721 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13722 return false; 13723 } 13724 } 13725 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13726 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13727 " which might be stale. Will try to clean up."); 13728 // Clean up the stale container and proceed to recreate. 13729 if (!PackageHelper.destroySdDir(newCacheId)) { 13730 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13731 return false; 13732 } 13733 // Successfully cleaned up stale container. Try to rename again. 13734 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13735 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13736 + " inspite of cleaning it up."); 13737 return false; 13738 } 13739 } 13740 if (!PackageHelper.isContainerMounted(newCacheId)) { 13741 Slog.w(TAG, "Mounting container " + newCacheId); 13742 newMountPath = PackageHelper.mountSdDir(newCacheId, 13743 getEncryptKey(), Process.SYSTEM_UID); 13744 } else { 13745 newMountPath = PackageHelper.getSdDir(newCacheId); 13746 } 13747 if (newMountPath == null) { 13748 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13749 return false; 13750 } 13751 Log.i(TAG, "Succesfully renamed " + cid + 13752 " to " + newCacheId + 13753 " at new path: " + newMountPath); 13754 cid = newCacheId; 13755 13756 final File beforeCodeFile = new File(packagePath); 13757 setMountPath(newMountPath); 13758 final File afterCodeFile = new File(packagePath); 13759 13760 // Reflect the rename in scanned details 13761 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13762 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13763 afterCodeFile, pkg.baseCodePath)); 13764 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13765 afterCodeFile, pkg.splitCodePaths)); 13766 13767 // Reflect the rename in app info 13768 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13769 pkg.setApplicationInfoCodePath(pkg.codePath); 13770 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13771 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13772 pkg.setApplicationInfoResourcePath(pkg.codePath); 13773 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13774 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13775 13776 return true; 13777 } 13778 13779 private void setMountPath(String mountPath) { 13780 final File mountFile = new File(mountPath); 13781 13782 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13783 if (monolithicFile.exists()) { 13784 packagePath = monolithicFile.getAbsolutePath(); 13785 if (isFwdLocked()) { 13786 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13787 } else { 13788 resourcePath = packagePath; 13789 } 13790 } else { 13791 packagePath = mountFile.getAbsolutePath(); 13792 resourcePath = packagePath; 13793 } 13794 } 13795 13796 int doPostInstall(int status, int uid) { 13797 if (status != PackageManager.INSTALL_SUCCEEDED) { 13798 cleanUp(); 13799 } else { 13800 final int groupOwner; 13801 final String protectedFile; 13802 if (isFwdLocked()) { 13803 groupOwner = UserHandle.getSharedAppGid(uid); 13804 protectedFile = RES_FILE_NAME; 13805 } else { 13806 groupOwner = -1; 13807 protectedFile = null; 13808 } 13809 13810 if (uid < Process.FIRST_APPLICATION_UID 13811 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13812 Slog.e(TAG, "Failed to finalize " + cid); 13813 PackageHelper.destroySdDir(cid); 13814 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13815 } 13816 13817 boolean mounted = PackageHelper.isContainerMounted(cid); 13818 if (!mounted) { 13819 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13820 } 13821 } 13822 return status; 13823 } 13824 13825 private void cleanUp() { 13826 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13827 13828 // Destroy secure container 13829 PackageHelper.destroySdDir(cid); 13830 } 13831 13832 private List<String> getAllCodePaths() { 13833 final File codeFile = new File(getCodePath()); 13834 if (codeFile != null && codeFile.exists()) { 13835 try { 13836 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13837 return pkg.getAllCodePaths(); 13838 } catch (PackageParserException e) { 13839 // Ignored; we tried our best 13840 } 13841 } 13842 return Collections.EMPTY_LIST; 13843 } 13844 13845 void cleanUpResourcesLI() { 13846 // Enumerate all code paths before deleting 13847 cleanUpResourcesLI(getAllCodePaths()); 13848 } 13849 13850 private void cleanUpResourcesLI(List<String> allCodePaths) { 13851 cleanUp(); 13852 removeDexFiles(allCodePaths, instructionSets); 13853 } 13854 13855 String getPackageName() { 13856 return getAsecPackageName(cid); 13857 } 13858 13859 boolean doPostDeleteLI(boolean delete) { 13860 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13861 final List<String> allCodePaths = getAllCodePaths(); 13862 boolean mounted = PackageHelper.isContainerMounted(cid); 13863 if (mounted) { 13864 // Unmount first 13865 if (PackageHelper.unMountSdDir(cid)) { 13866 mounted = false; 13867 } 13868 } 13869 if (!mounted && delete) { 13870 cleanUpResourcesLI(allCodePaths); 13871 } 13872 return !mounted; 13873 } 13874 13875 @Override 13876 int doPreCopy() { 13877 if (isFwdLocked()) { 13878 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13879 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13880 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13881 } 13882 } 13883 13884 return PackageManager.INSTALL_SUCCEEDED; 13885 } 13886 13887 @Override 13888 int doPostCopy(int uid) { 13889 if (isFwdLocked()) { 13890 if (uid < Process.FIRST_APPLICATION_UID 13891 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13892 RES_FILE_NAME)) { 13893 Slog.e(TAG, "Failed to finalize " + cid); 13894 PackageHelper.destroySdDir(cid); 13895 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13896 } 13897 } 13898 13899 return PackageManager.INSTALL_SUCCEEDED; 13900 } 13901 } 13902 13903 /** 13904 * Logic to handle movement of existing installed applications. 13905 */ 13906 class MoveInstallArgs extends InstallArgs { 13907 private File codeFile; 13908 private File resourceFile; 13909 13910 /** New install */ 13911 MoveInstallArgs(InstallParams params) { 13912 super(params.origin, params.move, params.observer, params.installFlags, 13913 params.installerPackageName, params.volumeUuid, 13914 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13915 params.grantedRuntimePermissions, 13916 params.traceMethod, params.traceCookie, params.certificates); 13917 } 13918 13919 int copyApk(IMediaContainerService imcs, boolean temp) { 13920 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13921 + move.fromUuid + " to " + move.toUuid); 13922 synchronized (mInstaller) { 13923 try { 13924 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13925 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13926 } catch (InstallerException e) { 13927 Slog.w(TAG, "Failed to move app", e); 13928 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13929 } 13930 } 13931 13932 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13933 resourceFile = codeFile; 13934 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13935 13936 return PackageManager.INSTALL_SUCCEEDED; 13937 } 13938 13939 int doPreInstall(int status) { 13940 if (status != PackageManager.INSTALL_SUCCEEDED) { 13941 cleanUp(move.toUuid); 13942 } 13943 return status; 13944 } 13945 13946 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13947 if (status != PackageManager.INSTALL_SUCCEEDED) { 13948 cleanUp(move.toUuid); 13949 return false; 13950 } 13951 13952 // Reflect the move in app info 13953 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13954 pkg.setApplicationInfoCodePath(pkg.codePath); 13955 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13956 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13957 pkg.setApplicationInfoResourcePath(pkg.codePath); 13958 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13959 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13960 13961 return true; 13962 } 13963 13964 int doPostInstall(int status, int uid) { 13965 if (status == PackageManager.INSTALL_SUCCEEDED) { 13966 cleanUp(move.fromUuid); 13967 } else { 13968 cleanUp(move.toUuid); 13969 } 13970 return status; 13971 } 13972 13973 @Override 13974 String getCodePath() { 13975 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13976 } 13977 13978 @Override 13979 String getResourcePath() { 13980 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13981 } 13982 13983 private boolean cleanUp(String volumeUuid) { 13984 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13985 move.dataAppName); 13986 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13987 final int[] userIds = sUserManager.getUserIds(); 13988 synchronized (mInstallLock) { 13989 // Clean up both app data and code 13990 // All package moves are frozen until finished 13991 for (int userId : userIds) { 13992 try { 13993 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13994 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13995 } catch (InstallerException e) { 13996 Slog.w(TAG, String.valueOf(e)); 13997 } 13998 } 13999 removeCodePathLI(codeFile); 14000 } 14001 return true; 14002 } 14003 14004 void cleanUpResourcesLI() { 14005 throw new UnsupportedOperationException(); 14006 } 14007 14008 boolean doPostDeleteLI(boolean delete) { 14009 throw new UnsupportedOperationException(); 14010 } 14011 } 14012 14013 static String getAsecPackageName(String packageCid) { 14014 int idx = packageCid.lastIndexOf("-"); 14015 if (idx == -1) { 14016 return packageCid; 14017 } 14018 return packageCid.substring(0, idx); 14019 } 14020 14021 // Utility method used to create code paths based on package name and available index. 14022 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 14023 String idxStr = ""; 14024 int idx = 1; 14025 // Fall back to default value of idx=1 if prefix is not 14026 // part of oldCodePath 14027 if (oldCodePath != null) { 14028 String subStr = oldCodePath; 14029 // Drop the suffix right away 14030 if (suffix != null && subStr.endsWith(suffix)) { 14031 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14032 } 14033 // If oldCodePath already contains prefix find out the 14034 // ending index to either increment or decrement. 14035 int sidx = subStr.lastIndexOf(prefix); 14036 if (sidx != -1) { 14037 subStr = subStr.substring(sidx + prefix.length()); 14038 if (subStr != null) { 14039 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14040 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14041 } 14042 try { 14043 idx = Integer.parseInt(subStr); 14044 if (idx <= 1) { 14045 idx++; 14046 } else { 14047 idx--; 14048 } 14049 } catch(NumberFormatException e) { 14050 } 14051 } 14052 } 14053 } 14054 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14055 return prefix + idxStr; 14056 } 14057 14058 private File getNextCodePath(File targetDir, String packageName) { 14059 int suffix = 1; 14060 File result; 14061 do { 14062 result = new File(targetDir, packageName + "-" + suffix); 14063 suffix++; 14064 } while (result.exists()); 14065 return result; 14066 } 14067 14068 // Utility method that returns the relative package path with respect 14069 // to the installation directory. Like say for /data/data/com.test-1.apk 14070 // string com.test-1 is returned. 14071 static String deriveCodePathName(String codePath) { 14072 if (codePath == null) { 14073 return null; 14074 } 14075 final File codeFile = new File(codePath); 14076 final String name = codeFile.getName(); 14077 if (codeFile.isDirectory()) { 14078 return name; 14079 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14080 final int lastDot = name.lastIndexOf('.'); 14081 return name.substring(0, lastDot); 14082 } else { 14083 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14084 return null; 14085 } 14086 } 14087 14088 static class PackageInstalledInfo { 14089 String name; 14090 int uid; 14091 // The set of users that originally had this package installed. 14092 int[] origUsers; 14093 // The set of users that now have this package installed. 14094 int[] newUsers; 14095 PackageParser.Package pkg; 14096 int returnCode; 14097 String returnMsg; 14098 PackageRemovedInfo removedInfo; 14099 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14100 14101 public void setError(int code, String msg) { 14102 setReturnCode(code); 14103 setReturnMessage(msg); 14104 Slog.w(TAG, msg); 14105 } 14106 14107 public void setError(String msg, PackageParserException e) { 14108 setReturnCode(e.error); 14109 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14110 Slog.w(TAG, msg, e); 14111 } 14112 14113 public void setError(String msg, PackageManagerException e) { 14114 returnCode = e.error; 14115 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14116 Slog.w(TAG, msg, e); 14117 } 14118 14119 public void setReturnCode(int returnCode) { 14120 this.returnCode = returnCode; 14121 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14122 for (int i = 0; i < childCount; i++) { 14123 addedChildPackages.valueAt(i).returnCode = returnCode; 14124 } 14125 } 14126 14127 private void setReturnMessage(String returnMsg) { 14128 this.returnMsg = returnMsg; 14129 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14130 for (int i = 0; i < childCount; i++) { 14131 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14132 } 14133 } 14134 14135 // In some error cases we want to convey more info back to the observer 14136 String origPackage; 14137 String origPermission; 14138 } 14139 14140 /* 14141 * Install a non-existing package. 14142 */ 14143 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14144 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14145 PackageInstalledInfo res) { 14146 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14147 14148 // Remember this for later, in case we need to rollback this install 14149 String pkgName = pkg.packageName; 14150 14151 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14152 14153 synchronized(mPackages) { 14154 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14155 // A package with the same name is already installed, though 14156 // it has been renamed to an older name. The package we 14157 // are trying to install should be installed as an update to 14158 // the existing one, but that has not been requested, so bail. 14159 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14160 + " without first uninstalling package running as " 14161 + mSettings.mRenamedPackages.get(pkgName)); 14162 return; 14163 } 14164 if (mPackages.containsKey(pkgName)) { 14165 // Don't allow installation over an existing package with the same name. 14166 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14167 + " without first uninstalling."); 14168 return; 14169 } 14170 } 14171 14172 try { 14173 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14174 System.currentTimeMillis(), user); 14175 14176 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14177 14178 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14179 prepareAppDataAfterInstallLIF(newPackage); 14180 14181 } else { 14182 // Remove package from internal structures, but keep around any 14183 // data that might have already existed 14184 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14185 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14186 } 14187 } catch (PackageManagerException e) { 14188 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14189 } 14190 14191 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14192 } 14193 14194 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14195 // Can't rotate keys during boot or if sharedUser. 14196 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14197 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14198 return false; 14199 } 14200 // app is using upgradeKeySets; make sure all are valid 14201 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14202 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14203 for (int i = 0; i < upgradeKeySets.length; i++) { 14204 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14205 Slog.wtf(TAG, "Package " 14206 + (oldPs.name != null ? oldPs.name : "<null>") 14207 + " contains upgrade-key-set reference to unknown key-set: " 14208 + upgradeKeySets[i] 14209 + " reverting to signatures check."); 14210 return false; 14211 } 14212 } 14213 return true; 14214 } 14215 14216 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14217 // Upgrade keysets are being used. Determine if new package has a superset of the 14218 // required keys. 14219 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14220 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14221 for (int i = 0; i < upgradeKeySets.length; i++) { 14222 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14223 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14224 return true; 14225 } 14226 } 14227 return false; 14228 } 14229 14230 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14231 try (DigestInputStream digestStream = 14232 new DigestInputStream(new FileInputStream(file), digest)) { 14233 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14234 } 14235 } 14236 14237 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14238 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14239 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14240 14241 final PackageParser.Package oldPackage; 14242 final String pkgName = pkg.packageName; 14243 final int[] allUsers; 14244 final int[] installedUsers; 14245 14246 synchronized(mPackages) { 14247 oldPackage = mPackages.get(pkgName); 14248 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14249 14250 // don't allow upgrade to target a release SDK from a pre-release SDK 14251 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14252 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14253 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14254 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14255 if (oldTargetsPreRelease 14256 && !newTargetsPreRelease 14257 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14258 Slog.w(TAG, "Can't install package targeting released sdk"); 14259 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14260 return; 14261 } 14262 14263 // don't allow an upgrade from full to ephemeral 14264 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14265 if (isEphemeral && !oldIsEphemeral) { 14266 // can't downgrade from full to ephemeral 14267 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14268 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14269 return; 14270 } 14271 14272 // verify signatures are valid 14273 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14274 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14275 if (!checkUpgradeKeySetLP(ps, pkg)) { 14276 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14277 "New package not signed by keys specified by upgrade-keysets: " 14278 + pkgName); 14279 return; 14280 } 14281 } else { 14282 // default to original signature matching 14283 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14284 != PackageManager.SIGNATURE_MATCH) { 14285 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14286 "New package has a different signature: " + pkgName); 14287 return; 14288 } 14289 } 14290 14291 // don't allow a system upgrade unless the upgrade hash matches 14292 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14293 byte[] digestBytes = null; 14294 try { 14295 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14296 updateDigest(digest, new File(pkg.baseCodePath)); 14297 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14298 for (String path : pkg.splitCodePaths) { 14299 updateDigest(digest, new File(path)); 14300 } 14301 } 14302 digestBytes = digest.digest(); 14303 } catch (NoSuchAlgorithmException | IOException e) { 14304 res.setError(INSTALL_FAILED_INVALID_APK, 14305 "Could not compute hash: " + pkgName); 14306 return; 14307 } 14308 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14309 res.setError(INSTALL_FAILED_INVALID_APK, 14310 "New package fails restrict-update check: " + pkgName); 14311 return; 14312 } 14313 // retain upgrade restriction 14314 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14315 } 14316 14317 // Check for shared user id changes 14318 String invalidPackageName = 14319 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14320 if (invalidPackageName != null) { 14321 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14322 "Package " + invalidPackageName + " tried to change user " 14323 + oldPackage.mSharedUserId); 14324 return; 14325 } 14326 14327 // In case of rollback, remember per-user/profile install state 14328 allUsers = sUserManager.getUserIds(); 14329 installedUsers = ps.queryInstalledUsers(allUsers, true); 14330 } 14331 14332 // Update what is removed 14333 res.removedInfo = new PackageRemovedInfo(); 14334 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14335 res.removedInfo.removedPackage = oldPackage.packageName; 14336 res.removedInfo.isUpdate = true; 14337 res.removedInfo.origUsers = installedUsers; 14338 final int childCount = (oldPackage.childPackages != null) 14339 ? oldPackage.childPackages.size() : 0; 14340 for (int i = 0; i < childCount; i++) { 14341 boolean childPackageUpdated = false; 14342 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14343 if (res.addedChildPackages != null) { 14344 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14345 if (childRes != null) { 14346 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14347 childRes.removedInfo.removedPackage = childPkg.packageName; 14348 childRes.removedInfo.isUpdate = true; 14349 childPackageUpdated = true; 14350 } 14351 } 14352 if (!childPackageUpdated) { 14353 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14354 childRemovedRes.removedPackage = childPkg.packageName; 14355 childRemovedRes.isUpdate = false; 14356 childRemovedRes.dataRemoved = true; 14357 synchronized (mPackages) { 14358 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14359 if (childPs != null) { 14360 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14361 } 14362 } 14363 if (res.removedInfo.removedChildPackages == null) { 14364 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14365 } 14366 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14367 } 14368 } 14369 14370 boolean sysPkg = (isSystemApp(oldPackage)); 14371 if (sysPkg) { 14372 // Set the system/privileged flags as needed 14373 final boolean privileged = 14374 (oldPackage.applicationInfo.privateFlags 14375 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14376 final int systemPolicyFlags = policyFlags 14377 | PackageParser.PARSE_IS_SYSTEM 14378 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14379 14380 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14381 user, allUsers, installerPackageName, res); 14382 } else { 14383 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14384 user, allUsers, installerPackageName, res); 14385 } 14386 } 14387 14388 public List<String> getPreviousCodePaths(String packageName) { 14389 final PackageSetting ps = mSettings.mPackages.get(packageName); 14390 final List<String> result = new ArrayList<String>(); 14391 if (ps != null && ps.oldCodePaths != null) { 14392 result.addAll(ps.oldCodePaths); 14393 } 14394 return result; 14395 } 14396 14397 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14398 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14399 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14400 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14401 + deletedPackage); 14402 14403 String pkgName = deletedPackage.packageName; 14404 boolean deletedPkg = true; 14405 boolean addedPkg = false; 14406 boolean updatedSettings = false; 14407 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14408 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14409 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14410 14411 final long origUpdateTime = (pkg.mExtras != null) 14412 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14413 14414 // First delete the existing package while retaining the data directory 14415 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14416 res.removedInfo, true, pkg)) { 14417 // If the existing package wasn't successfully deleted 14418 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14419 deletedPkg = false; 14420 } else { 14421 // Successfully deleted the old package; proceed with replace. 14422 14423 // If deleted package lived in a container, give users a chance to 14424 // relinquish resources before killing. 14425 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14426 if (DEBUG_INSTALL) { 14427 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14428 } 14429 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14430 final ArrayList<String> pkgList = new ArrayList<String>(1); 14431 pkgList.add(deletedPackage.applicationInfo.packageName); 14432 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14433 } 14434 14435 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14436 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14437 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14438 14439 try { 14440 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14441 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14442 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14443 14444 // Update the in-memory copy of the previous code paths. 14445 PackageSetting ps = mSettings.mPackages.get(pkgName); 14446 if (!killApp) { 14447 if (ps.oldCodePaths == null) { 14448 ps.oldCodePaths = new ArraySet<>(); 14449 } 14450 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14451 if (deletedPackage.splitCodePaths != null) { 14452 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14453 } 14454 } else { 14455 ps.oldCodePaths = null; 14456 } 14457 if (ps.childPackageNames != null) { 14458 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14459 final String childPkgName = ps.childPackageNames.get(i); 14460 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14461 childPs.oldCodePaths = ps.oldCodePaths; 14462 } 14463 } 14464 prepareAppDataAfterInstallLIF(newPackage); 14465 addedPkg = true; 14466 } catch (PackageManagerException e) { 14467 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14468 } 14469 } 14470 14471 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14472 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14473 14474 // Revert all internal state mutations and added folders for the failed install 14475 if (addedPkg) { 14476 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14477 res.removedInfo, true, null); 14478 } 14479 14480 // Restore the old package 14481 if (deletedPkg) { 14482 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14483 File restoreFile = new File(deletedPackage.codePath); 14484 // Parse old package 14485 boolean oldExternal = isExternal(deletedPackage); 14486 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14487 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14488 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14489 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14490 try { 14491 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14492 null); 14493 } catch (PackageManagerException e) { 14494 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14495 + e.getMessage()); 14496 return; 14497 } 14498 14499 synchronized (mPackages) { 14500 // Ensure the installer package name up to date 14501 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14502 14503 // Update permissions for restored package 14504 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14505 14506 mSettings.writeLPr(); 14507 } 14508 14509 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14510 } 14511 } else { 14512 synchronized (mPackages) { 14513 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14514 if (ps != null) { 14515 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14516 if (res.removedInfo.removedChildPackages != null) { 14517 final int childCount = res.removedInfo.removedChildPackages.size(); 14518 // Iterate in reverse as we may modify the collection 14519 for (int i = childCount - 1; i >= 0; i--) { 14520 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14521 if (res.addedChildPackages.containsKey(childPackageName)) { 14522 res.removedInfo.removedChildPackages.removeAt(i); 14523 } else { 14524 PackageRemovedInfo childInfo = res.removedInfo 14525 .removedChildPackages.valueAt(i); 14526 childInfo.removedForAllUsers = mPackages.get( 14527 childInfo.removedPackage) == null; 14528 } 14529 } 14530 } 14531 } 14532 } 14533 } 14534 } 14535 14536 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14537 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14538 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14539 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14540 + ", old=" + deletedPackage); 14541 14542 final boolean disabledSystem; 14543 14544 // Remove existing system package 14545 removePackageLI(deletedPackage, true); 14546 14547 synchronized (mPackages) { 14548 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14549 } 14550 if (!disabledSystem) { 14551 // We didn't need to disable the .apk as a current system package, 14552 // which means we are replacing another update that is already 14553 // installed. We need to make sure to delete the older one's .apk. 14554 res.removedInfo.args = createInstallArgsForExisting(0, 14555 deletedPackage.applicationInfo.getCodePath(), 14556 deletedPackage.applicationInfo.getResourcePath(), 14557 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14558 } else { 14559 res.removedInfo.args = null; 14560 } 14561 14562 // Successfully disabled the old package. Now proceed with re-installation 14563 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14564 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14565 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14566 14567 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14568 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14569 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14570 14571 PackageParser.Package newPackage = null; 14572 try { 14573 // Add the package to the internal data structures 14574 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14575 14576 // Set the update and install times 14577 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14578 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14579 System.currentTimeMillis()); 14580 14581 // Update the package dynamic state if succeeded 14582 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14583 // Now that the install succeeded make sure we remove data 14584 // directories for any child package the update removed. 14585 final int deletedChildCount = (deletedPackage.childPackages != null) 14586 ? deletedPackage.childPackages.size() : 0; 14587 final int newChildCount = (newPackage.childPackages != null) 14588 ? newPackage.childPackages.size() : 0; 14589 for (int i = 0; i < deletedChildCount; i++) { 14590 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14591 boolean childPackageDeleted = true; 14592 for (int j = 0; j < newChildCount; j++) { 14593 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14594 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14595 childPackageDeleted = false; 14596 break; 14597 } 14598 } 14599 if (childPackageDeleted) { 14600 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14601 deletedChildPkg.packageName); 14602 if (ps != null && res.removedInfo.removedChildPackages != null) { 14603 PackageRemovedInfo removedChildRes = res.removedInfo 14604 .removedChildPackages.get(deletedChildPkg.packageName); 14605 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14606 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14607 } 14608 } 14609 } 14610 14611 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14612 prepareAppDataAfterInstallLIF(newPackage); 14613 } 14614 } catch (PackageManagerException e) { 14615 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14616 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14617 } 14618 14619 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14620 // Re installation failed. Restore old information 14621 // Remove new pkg information 14622 if (newPackage != null) { 14623 removeInstalledPackageLI(newPackage, true); 14624 } 14625 // Add back the old system package 14626 try { 14627 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14628 } catch (PackageManagerException e) { 14629 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14630 } 14631 14632 synchronized (mPackages) { 14633 if (disabledSystem) { 14634 enableSystemPackageLPw(deletedPackage); 14635 } 14636 14637 // Ensure the installer package name up to date 14638 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14639 14640 // Update permissions for restored package 14641 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14642 14643 mSettings.writeLPr(); 14644 } 14645 14646 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14647 + " after failed upgrade"); 14648 } 14649 } 14650 14651 /** 14652 * Checks whether the parent or any of the child packages have a change shared 14653 * user. For a package to be a valid update the shred users of the parent and 14654 * the children should match. We may later support changing child shared users. 14655 * @param oldPkg The updated package. 14656 * @param newPkg The update package. 14657 * @return The shared user that change between the versions. 14658 */ 14659 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14660 PackageParser.Package newPkg) { 14661 // Check parent shared user 14662 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14663 return newPkg.packageName; 14664 } 14665 // Check child shared users 14666 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14667 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14668 for (int i = 0; i < newChildCount; i++) { 14669 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14670 // If this child was present, did it have the same shared user? 14671 for (int j = 0; j < oldChildCount; j++) { 14672 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14673 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14674 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14675 return newChildPkg.packageName; 14676 } 14677 } 14678 } 14679 return null; 14680 } 14681 14682 private void removeNativeBinariesLI(PackageSetting ps) { 14683 // Remove the lib path for the parent package 14684 if (ps != null) { 14685 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14686 // Remove the lib path for the child packages 14687 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14688 for (int i = 0; i < childCount; i++) { 14689 PackageSetting childPs = null; 14690 synchronized (mPackages) { 14691 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14692 } 14693 if (childPs != null) { 14694 NativeLibraryHelper.removeNativeBinariesLI(childPs 14695 .legacyNativeLibraryPathString); 14696 } 14697 } 14698 } 14699 } 14700 14701 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14702 // Enable the parent package 14703 mSettings.enableSystemPackageLPw(pkg.packageName); 14704 // Enable the child packages 14705 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14706 for (int i = 0; i < childCount; i++) { 14707 PackageParser.Package childPkg = pkg.childPackages.get(i); 14708 mSettings.enableSystemPackageLPw(childPkg.packageName); 14709 } 14710 } 14711 14712 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14713 PackageParser.Package newPkg) { 14714 // Disable the parent package (parent always replaced) 14715 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14716 // Disable the child packages 14717 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14718 for (int i = 0; i < childCount; i++) { 14719 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14720 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14721 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14722 } 14723 return disabled; 14724 } 14725 14726 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14727 String installerPackageName) { 14728 // Enable the parent package 14729 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14730 // Enable the child packages 14731 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14732 for (int i = 0; i < childCount; i++) { 14733 PackageParser.Package childPkg = pkg.childPackages.get(i); 14734 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14735 } 14736 } 14737 14738 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14739 // Collect all used permissions in the UID 14740 ArraySet<String> usedPermissions = new ArraySet<>(); 14741 final int packageCount = su.packages.size(); 14742 for (int i = 0; i < packageCount; i++) { 14743 PackageSetting ps = su.packages.valueAt(i); 14744 if (ps.pkg == null) { 14745 continue; 14746 } 14747 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14748 for (int j = 0; j < requestedPermCount; j++) { 14749 String permission = ps.pkg.requestedPermissions.get(j); 14750 BasePermission bp = mSettings.mPermissions.get(permission); 14751 if (bp != null) { 14752 usedPermissions.add(permission); 14753 } 14754 } 14755 } 14756 14757 PermissionsState permissionsState = su.getPermissionsState(); 14758 // Prune install permissions 14759 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14760 final int installPermCount = installPermStates.size(); 14761 for (int i = installPermCount - 1; i >= 0; i--) { 14762 PermissionState permissionState = installPermStates.get(i); 14763 if (!usedPermissions.contains(permissionState.getName())) { 14764 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14765 if (bp != null) { 14766 permissionsState.revokeInstallPermission(bp); 14767 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14768 PackageManager.MASK_PERMISSION_FLAGS, 0); 14769 } 14770 } 14771 } 14772 14773 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14774 14775 // Prune runtime permissions 14776 for (int userId : allUserIds) { 14777 List<PermissionState> runtimePermStates = permissionsState 14778 .getRuntimePermissionStates(userId); 14779 final int runtimePermCount = runtimePermStates.size(); 14780 for (int i = runtimePermCount - 1; i >= 0; i--) { 14781 PermissionState permissionState = runtimePermStates.get(i); 14782 if (!usedPermissions.contains(permissionState.getName())) { 14783 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14784 if (bp != null) { 14785 permissionsState.revokeRuntimePermission(bp, userId); 14786 permissionsState.updatePermissionFlags(bp, userId, 14787 PackageManager.MASK_PERMISSION_FLAGS, 0); 14788 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14789 runtimePermissionChangedUserIds, userId); 14790 } 14791 } 14792 } 14793 } 14794 14795 return runtimePermissionChangedUserIds; 14796 } 14797 14798 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14799 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14800 // Update the parent package setting 14801 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14802 res, user); 14803 // Update the child packages setting 14804 final int childCount = (newPackage.childPackages != null) 14805 ? newPackage.childPackages.size() : 0; 14806 for (int i = 0; i < childCount; i++) { 14807 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14808 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14809 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14810 childRes.origUsers, childRes, user); 14811 } 14812 } 14813 14814 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14815 String installerPackageName, int[] allUsers, int[] installedForUsers, 14816 PackageInstalledInfo res, UserHandle user) { 14817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14818 14819 String pkgName = newPackage.packageName; 14820 synchronized (mPackages) { 14821 //write settings. the installStatus will be incomplete at this stage. 14822 //note that the new package setting would have already been 14823 //added to mPackages. It hasn't been persisted yet. 14824 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14825 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14826 mSettings.writeLPr(); 14827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14828 } 14829 14830 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14831 synchronized (mPackages) { 14832 updatePermissionsLPw(newPackage.packageName, newPackage, 14833 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14834 ? UPDATE_PERMISSIONS_ALL : 0)); 14835 // For system-bundled packages, we assume that installing an upgraded version 14836 // of the package implies that the user actually wants to run that new code, 14837 // so we enable the package. 14838 PackageSetting ps = mSettings.mPackages.get(pkgName); 14839 final int userId = user.getIdentifier(); 14840 if (ps != null) { 14841 if (isSystemApp(newPackage)) { 14842 if (DEBUG_INSTALL) { 14843 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14844 } 14845 // Enable system package for requested users 14846 if (res.origUsers != null) { 14847 for (int origUserId : res.origUsers) { 14848 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14849 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14850 origUserId, installerPackageName); 14851 } 14852 } 14853 } 14854 // Also convey the prior install/uninstall state 14855 if (allUsers != null && installedForUsers != null) { 14856 for (int currentUserId : allUsers) { 14857 final boolean installed = ArrayUtils.contains( 14858 installedForUsers, currentUserId); 14859 if (DEBUG_INSTALL) { 14860 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14861 } 14862 ps.setInstalled(installed, currentUserId); 14863 } 14864 // these install state changes will be persisted in the 14865 // upcoming call to mSettings.writeLPr(). 14866 } 14867 } 14868 // It's implied that when a user requests installation, they want the app to be 14869 // installed and enabled. 14870 if (userId != UserHandle.USER_ALL) { 14871 ps.setInstalled(true, userId); 14872 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14873 } 14874 } 14875 res.name = pkgName; 14876 res.uid = newPackage.applicationInfo.uid; 14877 res.pkg = newPackage; 14878 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14879 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14880 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14881 //to update install status 14882 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14883 mSettings.writeLPr(); 14884 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14885 } 14886 14887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14888 } 14889 14890 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14891 try { 14892 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14893 installPackageLI(args, res); 14894 } finally { 14895 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14896 } 14897 } 14898 14899 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14900 final int installFlags = args.installFlags; 14901 final String installerPackageName = args.installerPackageName; 14902 final String volumeUuid = args.volumeUuid; 14903 final File tmpPackageFile = new File(args.getCodePath()); 14904 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14905 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14906 || (args.volumeUuid != null)); 14907 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14908 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14909 boolean replace = false; 14910 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14911 if (args.move != null) { 14912 // moving a complete application; perform an initial scan on the new install location 14913 scanFlags |= SCAN_INITIAL; 14914 } 14915 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14916 scanFlags |= SCAN_DONT_KILL_APP; 14917 } 14918 14919 // Result object to be returned 14920 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14921 14922 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14923 14924 // Sanity check 14925 if (ephemeral && (forwardLocked || onExternal)) { 14926 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14927 + " external=" + onExternal); 14928 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14929 return; 14930 } 14931 14932 // Retrieve PackageSettings and parse package 14933 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14934 | PackageParser.PARSE_ENFORCE_CODE 14935 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14936 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14937 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14938 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14939 PackageParser pp = new PackageParser(); 14940 pp.setSeparateProcesses(mSeparateProcesses); 14941 pp.setDisplayMetrics(mMetrics); 14942 14943 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14944 final PackageParser.Package pkg; 14945 try { 14946 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14947 } catch (PackageParserException e) { 14948 res.setError("Failed parse during installPackageLI", e); 14949 return; 14950 } finally { 14951 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14952 } 14953 14954 // If we are installing a clustered package add results for the children 14955 if (pkg.childPackages != null) { 14956 synchronized (mPackages) { 14957 final int childCount = pkg.childPackages.size(); 14958 for (int i = 0; i < childCount; i++) { 14959 PackageParser.Package childPkg = pkg.childPackages.get(i); 14960 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14961 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14962 childRes.pkg = childPkg; 14963 childRes.name = childPkg.packageName; 14964 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14965 if (childPs != null) { 14966 childRes.origUsers = childPs.queryInstalledUsers( 14967 sUserManager.getUserIds(), true); 14968 } 14969 if ((mPackages.containsKey(childPkg.packageName))) { 14970 childRes.removedInfo = new PackageRemovedInfo(); 14971 childRes.removedInfo.removedPackage = childPkg.packageName; 14972 } 14973 if (res.addedChildPackages == null) { 14974 res.addedChildPackages = new ArrayMap<>(); 14975 } 14976 res.addedChildPackages.put(childPkg.packageName, childRes); 14977 } 14978 } 14979 } 14980 14981 // If package doesn't declare API override, mark that we have an install 14982 // time CPU ABI override. 14983 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14984 pkg.cpuAbiOverride = args.abiOverride; 14985 } 14986 14987 String pkgName = res.name = pkg.packageName; 14988 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14989 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14990 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14991 return; 14992 } 14993 } 14994 14995 try { 14996 // either use what we've been given or parse directly from the APK 14997 if (args.certificates != null) { 14998 try { 14999 PackageParser.populateCertificates(pkg, args.certificates); 15000 } catch (PackageParserException e) { 15001 // there was something wrong with the certificates we were given; 15002 // try to pull them from the APK 15003 PackageParser.collectCertificates(pkg, parseFlags); 15004 } 15005 } else { 15006 PackageParser.collectCertificates(pkg, parseFlags); 15007 } 15008 } catch (PackageParserException e) { 15009 res.setError("Failed collect during installPackageLI", e); 15010 return; 15011 } 15012 15013 // Get rid of all references to package scan path via parser. 15014 pp = null; 15015 String oldCodePath = null; 15016 boolean systemApp = false; 15017 synchronized (mPackages) { 15018 // Check if installing already existing package 15019 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 15020 String oldName = mSettings.mRenamedPackages.get(pkgName); 15021 if (pkg.mOriginalPackages != null 15022 && pkg.mOriginalPackages.contains(oldName) 15023 && mPackages.containsKey(oldName)) { 15024 // This package is derived from an original package, 15025 // and this device has been updating from that original 15026 // name. We must continue using the original name, so 15027 // rename the new package here. 15028 pkg.setPackageName(oldName); 15029 pkgName = pkg.packageName; 15030 replace = true; 15031 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15032 + oldName + " pkgName=" + pkgName); 15033 } else if (mPackages.containsKey(pkgName)) { 15034 // This package, under its official name, already exists 15035 // on the device; we should replace it. 15036 replace = true; 15037 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15038 } 15039 15040 // Child packages are installed through the parent package 15041 if (pkg.parentPackage != null) { 15042 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15043 "Package " + pkg.packageName + " is child of package " 15044 + pkg.parentPackage.parentPackage + ". Child packages " 15045 + "can be updated only through the parent package."); 15046 return; 15047 } 15048 15049 if (replace) { 15050 // Prevent apps opting out from runtime permissions 15051 PackageParser.Package oldPackage = mPackages.get(pkgName); 15052 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15053 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15054 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15055 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15056 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15057 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15058 + " doesn't support runtime permissions but the old" 15059 + " target SDK " + oldTargetSdk + " does."); 15060 return; 15061 } 15062 15063 // Prevent installing of child packages 15064 if (oldPackage.parentPackage != null) { 15065 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15066 "Package " + pkg.packageName + " is child of package " 15067 + oldPackage.parentPackage + ". Child packages " 15068 + "can be updated only through the parent package."); 15069 return; 15070 } 15071 } 15072 } 15073 15074 PackageSetting ps = mSettings.mPackages.get(pkgName); 15075 if (ps != null) { 15076 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15077 15078 // Quick sanity check that we're signed correctly if updating; 15079 // we'll check this again later when scanning, but we want to 15080 // bail early here before tripping over redefined permissions. 15081 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15082 if (!checkUpgradeKeySetLP(ps, pkg)) { 15083 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15084 + pkg.packageName + " upgrade keys do not match the " 15085 + "previously installed version"); 15086 return; 15087 } 15088 } else { 15089 try { 15090 verifySignaturesLP(ps, pkg); 15091 } catch (PackageManagerException e) { 15092 res.setError(e.error, e.getMessage()); 15093 return; 15094 } 15095 } 15096 15097 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15098 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15099 systemApp = (ps.pkg.applicationInfo.flags & 15100 ApplicationInfo.FLAG_SYSTEM) != 0; 15101 } 15102 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15103 } 15104 15105 // Check whether the newly-scanned package wants to define an already-defined perm 15106 int N = pkg.permissions.size(); 15107 for (int i = N-1; i >= 0; i--) { 15108 PackageParser.Permission perm = pkg.permissions.get(i); 15109 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15110 if (bp != null) { 15111 // If the defining package is signed with our cert, it's okay. This 15112 // also includes the "updating the same package" case, of course. 15113 // "updating same package" could also involve key-rotation. 15114 final boolean sigsOk; 15115 if (bp.sourcePackage.equals(pkg.packageName) 15116 && (bp.packageSetting instanceof PackageSetting) 15117 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15118 scanFlags))) { 15119 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15120 } else { 15121 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15122 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15123 } 15124 if (!sigsOk) { 15125 // If the owning package is the system itself, we log but allow 15126 // install to proceed; we fail the install on all other permission 15127 // redefinitions. 15128 if (!bp.sourcePackage.equals("android")) { 15129 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15130 + pkg.packageName + " attempting to redeclare permission " 15131 + perm.info.name + " already owned by " + bp.sourcePackage); 15132 res.origPermission = perm.info.name; 15133 res.origPackage = bp.sourcePackage; 15134 return; 15135 } else { 15136 Slog.w(TAG, "Package " + pkg.packageName 15137 + " attempting to redeclare system permission " 15138 + perm.info.name + "; ignoring new declaration"); 15139 pkg.permissions.remove(i); 15140 } 15141 } 15142 } 15143 } 15144 } 15145 15146 if (systemApp) { 15147 if (onExternal) { 15148 // Abort update; system app can't be replaced with app on sdcard 15149 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15150 "Cannot install updates to system apps on sdcard"); 15151 return; 15152 } else if (ephemeral) { 15153 // Abort update; system app can't be replaced with an ephemeral app 15154 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15155 "Cannot update a system app with an ephemeral app"); 15156 return; 15157 } 15158 } 15159 15160 if (args.move != null) { 15161 // We did an in-place move, so dex is ready to roll 15162 scanFlags |= SCAN_NO_DEX; 15163 scanFlags |= SCAN_MOVE; 15164 15165 synchronized (mPackages) { 15166 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15167 if (ps == null) { 15168 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15169 "Missing settings for moved package " + pkgName); 15170 } 15171 15172 // We moved the entire application as-is, so bring over the 15173 // previously derived ABI information. 15174 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15175 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15176 } 15177 15178 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15179 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15180 scanFlags |= SCAN_NO_DEX; 15181 15182 try { 15183 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15184 args.abiOverride : pkg.cpuAbiOverride); 15185 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15186 true /* extract libs */); 15187 } catch (PackageManagerException pme) { 15188 Slog.e(TAG, "Error deriving application ABI", pme); 15189 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15190 return; 15191 } 15192 15193 // Shared libraries for the package need to be updated. 15194 synchronized (mPackages) { 15195 try { 15196 updateSharedLibrariesLPw(pkg, null); 15197 } catch (PackageManagerException e) { 15198 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15199 } 15200 } 15201 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15202 // Do not run PackageDexOptimizer through the local performDexOpt 15203 // method because `pkg` may not be in `mPackages` yet. 15204 // 15205 // Also, don't fail application installs if the dexopt step fails. 15206 mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15207 null /* instructionSets */, false /* checkProfiles */, 15208 getCompilerFilterForReason(REASON_INSTALL)); 15209 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15210 15211 // Notify BackgroundDexOptService that the package has been changed. 15212 // If this is an update of a package which used to fail to compile, 15213 // BDOS will remove it from its blacklist. 15214 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15215 } 15216 15217 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15218 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15219 return; 15220 } 15221 15222 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15223 15224 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15225 "installPackageLI")) { 15226 if (replace) { 15227 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15228 installerPackageName, res); 15229 } else { 15230 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15231 args.user, installerPackageName, volumeUuid, res); 15232 } 15233 } 15234 synchronized (mPackages) { 15235 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15236 if (ps != null) { 15237 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15238 } 15239 15240 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15241 for (int i = 0; i < childCount; i++) { 15242 PackageParser.Package childPkg = pkg.childPackages.get(i); 15243 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15244 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15245 if (childPs != null) { 15246 childRes.newUsers = childPs.queryInstalledUsers( 15247 sUserManager.getUserIds(), true); 15248 } 15249 } 15250 } 15251 } 15252 15253 private void startIntentFilterVerifications(int userId, boolean replacing, 15254 PackageParser.Package pkg) { 15255 if (mIntentFilterVerifierComponent == null) { 15256 Slog.w(TAG, "No IntentFilter verification will not be done as " 15257 + "there is no IntentFilterVerifier available!"); 15258 return; 15259 } 15260 15261 final int verifierUid = getPackageUid( 15262 mIntentFilterVerifierComponent.getPackageName(), 15263 MATCH_DEBUG_TRIAGED_MISSING, 15264 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15265 15266 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15267 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15268 mHandler.sendMessage(msg); 15269 15270 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15271 for (int i = 0; i < childCount; i++) { 15272 PackageParser.Package childPkg = pkg.childPackages.get(i); 15273 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15274 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15275 mHandler.sendMessage(msg); 15276 } 15277 } 15278 15279 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15280 PackageParser.Package pkg) { 15281 int size = pkg.activities.size(); 15282 if (size == 0) { 15283 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15284 "No activity, so no need to verify any IntentFilter!"); 15285 return; 15286 } 15287 15288 final boolean hasDomainURLs = hasDomainURLs(pkg); 15289 if (!hasDomainURLs) { 15290 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15291 "No domain URLs, so no need to verify any IntentFilter!"); 15292 return; 15293 } 15294 15295 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15296 + " if any IntentFilter from the " + size 15297 + " Activities needs verification ..."); 15298 15299 int count = 0; 15300 final String packageName = pkg.packageName; 15301 15302 synchronized (mPackages) { 15303 // If this is a new install and we see that we've already run verification for this 15304 // package, we have nothing to do: it means the state was restored from backup. 15305 if (!replacing) { 15306 IntentFilterVerificationInfo ivi = 15307 mSettings.getIntentFilterVerificationLPr(packageName); 15308 if (ivi != null) { 15309 if (DEBUG_DOMAIN_VERIFICATION) { 15310 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15311 + ivi.getStatusString()); 15312 } 15313 return; 15314 } 15315 } 15316 15317 // If any filters need to be verified, then all need to be. 15318 boolean needToVerify = false; 15319 for (PackageParser.Activity a : pkg.activities) { 15320 for (ActivityIntentInfo filter : a.intents) { 15321 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15322 if (DEBUG_DOMAIN_VERIFICATION) { 15323 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15324 } 15325 needToVerify = true; 15326 break; 15327 } 15328 } 15329 } 15330 15331 if (needToVerify) { 15332 final int verificationId = mIntentFilterVerificationToken++; 15333 for (PackageParser.Activity a : pkg.activities) { 15334 for (ActivityIntentInfo filter : a.intents) { 15335 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15336 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15337 "Verification needed for IntentFilter:" + filter.toString()); 15338 mIntentFilterVerifier.addOneIntentFilterVerification( 15339 verifierUid, userId, verificationId, filter, packageName); 15340 count++; 15341 } 15342 } 15343 } 15344 } 15345 } 15346 15347 if (count > 0) { 15348 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15349 + " IntentFilter verification" + (count > 1 ? "s" : "") 15350 + " for userId:" + userId); 15351 mIntentFilterVerifier.startVerifications(userId); 15352 } else { 15353 if (DEBUG_DOMAIN_VERIFICATION) { 15354 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15355 } 15356 } 15357 } 15358 15359 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15360 final ComponentName cn = filter.activity.getComponentName(); 15361 final String packageName = cn.getPackageName(); 15362 15363 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15364 packageName); 15365 if (ivi == null) { 15366 return true; 15367 } 15368 int status = ivi.getStatus(); 15369 switch (status) { 15370 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15371 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15372 return true; 15373 15374 default: 15375 // Nothing to do 15376 return false; 15377 } 15378 } 15379 15380 private static boolean isMultiArch(ApplicationInfo info) { 15381 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15382 } 15383 15384 private static boolean isExternal(PackageParser.Package pkg) { 15385 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15386 } 15387 15388 private static boolean isExternal(PackageSetting ps) { 15389 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15390 } 15391 15392 private static boolean isEphemeral(PackageParser.Package pkg) { 15393 return pkg.applicationInfo.isEphemeralApp(); 15394 } 15395 15396 private static boolean isEphemeral(PackageSetting ps) { 15397 return ps.pkg != null && isEphemeral(ps.pkg); 15398 } 15399 15400 private static boolean isSystemApp(PackageParser.Package pkg) { 15401 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15402 } 15403 15404 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15405 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15406 } 15407 15408 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15409 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15410 } 15411 15412 private static boolean isSystemApp(PackageSetting ps) { 15413 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15414 } 15415 15416 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15417 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15418 } 15419 15420 private int packageFlagsToInstallFlags(PackageSetting ps) { 15421 int installFlags = 0; 15422 if (isEphemeral(ps)) { 15423 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15424 } 15425 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15426 // This existing package was an external ASEC install when we have 15427 // the external flag without a UUID 15428 installFlags |= PackageManager.INSTALL_EXTERNAL; 15429 } 15430 if (ps.isForwardLocked()) { 15431 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15432 } 15433 return installFlags; 15434 } 15435 15436 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15437 if (isExternal(pkg)) { 15438 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15439 return StorageManager.UUID_PRIMARY_PHYSICAL; 15440 } else { 15441 return pkg.volumeUuid; 15442 } 15443 } else { 15444 return StorageManager.UUID_PRIVATE_INTERNAL; 15445 } 15446 } 15447 15448 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15449 if (isExternal(pkg)) { 15450 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15451 return mSettings.getExternalVersion(); 15452 } else { 15453 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15454 } 15455 } else { 15456 return mSettings.getInternalVersion(); 15457 } 15458 } 15459 15460 private void deleteTempPackageFiles() { 15461 final FilenameFilter filter = new FilenameFilter() { 15462 public boolean accept(File dir, String name) { 15463 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15464 } 15465 }; 15466 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15467 file.delete(); 15468 } 15469 } 15470 15471 @Override 15472 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15473 int flags) { 15474 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15475 flags); 15476 } 15477 15478 @Override 15479 public void deletePackage(final String packageName, 15480 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15481 mContext.enforceCallingOrSelfPermission( 15482 android.Manifest.permission.DELETE_PACKAGES, null); 15483 Preconditions.checkNotNull(packageName); 15484 Preconditions.checkNotNull(observer); 15485 final int uid = Binder.getCallingUid(); 15486 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15487 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15488 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15489 mContext.enforceCallingOrSelfPermission( 15490 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15491 "deletePackage for user " + userId); 15492 } 15493 15494 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15495 try { 15496 observer.onPackageDeleted(packageName, 15497 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15498 } catch (RemoteException re) { 15499 } 15500 return; 15501 } 15502 15503 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15504 try { 15505 observer.onPackageDeleted(packageName, 15506 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15507 } catch (RemoteException re) { 15508 } 15509 return; 15510 } 15511 15512 if (DEBUG_REMOVE) { 15513 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15514 + " deleteAllUsers: " + deleteAllUsers ); 15515 } 15516 // Queue up an async operation since the package deletion may take a little while. 15517 mHandler.post(new Runnable() { 15518 public void run() { 15519 mHandler.removeCallbacks(this); 15520 int returnCode; 15521 if (!deleteAllUsers) { 15522 returnCode = deletePackageX(packageName, userId, deleteFlags); 15523 } else { 15524 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15525 // If nobody is blocking uninstall, proceed with delete for all users 15526 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15527 returnCode = deletePackageX(packageName, userId, deleteFlags); 15528 } else { 15529 // Otherwise uninstall individually for users with blockUninstalls=false 15530 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15531 for (int userId : users) { 15532 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15533 returnCode = deletePackageX(packageName, userId, userFlags); 15534 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15535 Slog.w(TAG, "Package delete failed for user " + userId 15536 + ", returnCode " + returnCode); 15537 } 15538 } 15539 } 15540 // The app has only been marked uninstalled for certain users. 15541 // We still need to report that delete was blocked 15542 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15543 } 15544 } 15545 try { 15546 observer.onPackageDeleted(packageName, returnCode, null); 15547 } catch (RemoteException e) { 15548 Log.i(TAG, "Observer no longer exists."); 15549 } //end catch 15550 } //end run 15551 }); 15552 } 15553 15554 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15555 int[] result = EMPTY_INT_ARRAY; 15556 for (int userId : userIds) { 15557 if (getBlockUninstallForUser(packageName, userId)) { 15558 result = ArrayUtils.appendInt(result, userId); 15559 } 15560 } 15561 return result; 15562 } 15563 15564 @Override 15565 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15566 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15567 } 15568 15569 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15570 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15571 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15572 try { 15573 if (dpm != null) { 15574 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15575 /* callingUserOnly =*/ false); 15576 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15577 : deviceOwnerComponentName.getPackageName(); 15578 // Does the package contains the device owner? 15579 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15580 // this check is probably not needed, since DO should be registered as a device 15581 // admin on some user too. (Original bug for this: b/17657954) 15582 if (packageName.equals(deviceOwnerPackageName)) { 15583 return true; 15584 } 15585 // Does it contain a device admin for any user? 15586 int[] users; 15587 if (userId == UserHandle.USER_ALL) { 15588 users = sUserManager.getUserIds(); 15589 } else { 15590 users = new int[]{userId}; 15591 } 15592 for (int i = 0; i < users.length; ++i) { 15593 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15594 return true; 15595 } 15596 } 15597 } 15598 } catch (RemoteException e) { 15599 } 15600 return false; 15601 } 15602 15603 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15604 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15605 } 15606 15607 /** 15608 * This method is an internal method that could be get invoked either 15609 * to delete an installed package or to clean up a failed installation. 15610 * After deleting an installed package, a broadcast is sent to notify any 15611 * listeners that the package has been removed. For cleaning up a failed 15612 * installation, the broadcast is not necessary since the package's 15613 * installation wouldn't have sent the initial broadcast either 15614 * The key steps in deleting a package are 15615 * deleting the package information in internal structures like mPackages, 15616 * deleting the packages base directories through installd 15617 * updating mSettings to reflect current status 15618 * persisting settings for later use 15619 * sending a broadcast if necessary 15620 */ 15621 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15622 final PackageRemovedInfo info = new PackageRemovedInfo(); 15623 final boolean res; 15624 15625 final int removeUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15626 ? UserHandle.USER_ALL : userId; 15627 15628 if (isPackageDeviceAdmin(packageName, removeUser)) { 15629 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15630 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15631 } 15632 15633 PackageSetting uninstalledPs = null; 15634 15635 // for the uninstall-updates case and restricted profiles, remember the per- 15636 // user handle installed state 15637 int[] allUsers; 15638 synchronized (mPackages) { 15639 uninstalledPs = mSettings.mPackages.get(packageName); 15640 if (uninstalledPs == null) { 15641 Slog.w(TAG, "Not removing non-existent package " + packageName); 15642 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15643 } 15644 allUsers = sUserManager.getUserIds(); 15645 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15646 } 15647 15648 final int freezeUser; 15649 if (isUpdatedSystemApp(uninstalledPs) 15650 && ((deleteFlags & PackageManager.DELETE_SYSTEM_APP) == 0)) { 15651 // We're downgrading a system app, which will apply to all users, so 15652 // freeze them all during the downgrade 15653 freezeUser = UserHandle.USER_ALL; 15654 } else { 15655 freezeUser = removeUser; 15656 } 15657 15658 synchronized (mInstallLock) { 15659 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15660 try (PackageFreezer freezer = freezePackageForDelete(packageName, freezeUser, 15661 deleteFlags, "deletePackageX")) { 15662 res = deletePackageLIF(packageName, UserHandle.of(removeUser), true, allUsers, 15663 deleteFlags | REMOVE_CHATTY, info, true, null); 15664 } 15665 synchronized (mPackages) { 15666 if (res) { 15667 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15668 } 15669 } 15670 } 15671 15672 if (res) { 15673 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15674 info.sendPackageRemovedBroadcasts(killApp); 15675 info.sendSystemPackageUpdatedBroadcasts(); 15676 info.sendSystemPackageAppearedBroadcasts(); 15677 } 15678 // Force a gc here. 15679 Runtime.getRuntime().gc(); 15680 // Delete the resources here after sending the broadcast to let 15681 // other processes clean up before deleting resources. 15682 if (info.args != null) { 15683 synchronized (mInstallLock) { 15684 info.args.doPostDeleteLI(true); 15685 } 15686 } 15687 15688 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15689 } 15690 15691 class PackageRemovedInfo { 15692 String removedPackage; 15693 int uid = -1; 15694 int removedAppId = -1; 15695 int[] origUsers; 15696 int[] removedUsers = null; 15697 boolean isRemovedPackageSystemUpdate = false; 15698 boolean isUpdate; 15699 boolean dataRemoved; 15700 boolean removedForAllUsers; 15701 // Clean up resources deleted packages. 15702 InstallArgs args = null; 15703 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15704 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15705 15706 void sendPackageRemovedBroadcasts(boolean killApp) { 15707 sendPackageRemovedBroadcastInternal(killApp); 15708 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15709 for (int i = 0; i < childCount; i++) { 15710 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15711 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15712 } 15713 } 15714 15715 void sendSystemPackageUpdatedBroadcasts() { 15716 if (isRemovedPackageSystemUpdate) { 15717 sendSystemPackageUpdatedBroadcastsInternal(); 15718 final int childCount = (removedChildPackages != null) 15719 ? removedChildPackages.size() : 0; 15720 for (int i = 0; i < childCount; i++) { 15721 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15722 if (childInfo.isRemovedPackageSystemUpdate) { 15723 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15724 } 15725 } 15726 } 15727 } 15728 15729 void sendSystemPackageAppearedBroadcasts() { 15730 final int packageCount = (appearedChildPackages != null) 15731 ? appearedChildPackages.size() : 0; 15732 for (int i = 0; i < packageCount; i++) { 15733 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15734 for (int userId : installedInfo.newUsers) { 15735 sendPackageAddedForUser(installedInfo.name, true, 15736 UserHandle.getAppId(installedInfo.uid), userId); 15737 } 15738 } 15739 } 15740 15741 private void sendSystemPackageUpdatedBroadcastsInternal() { 15742 Bundle extras = new Bundle(2); 15743 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15744 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15745 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15746 extras, 0, null, null, null); 15747 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15748 extras, 0, null, null, null); 15749 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15750 null, 0, removedPackage, null, null); 15751 } 15752 15753 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15754 Bundle extras = new Bundle(2); 15755 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15756 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15757 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15758 if (isUpdate || isRemovedPackageSystemUpdate) { 15759 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15760 } 15761 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15762 if (removedPackage != null) { 15763 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15764 extras, 0, null, null, removedUsers); 15765 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15766 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15767 removedPackage, extras, 0, null, null, removedUsers); 15768 } 15769 } 15770 if (removedAppId >= 0) { 15771 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15772 removedUsers); 15773 } 15774 } 15775 } 15776 15777 /* 15778 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15779 * flag is not set, the data directory is removed as well. 15780 * make sure this flag is set for partially installed apps. If not its meaningless to 15781 * delete a partially installed application. 15782 */ 15783 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15784 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15785 String packageName = ps.name; 15786 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15787 // Retrieve object to delete permissions for shared user later on 15788 final PackageParser.Package deletedPkg; 15789 final PackageSetting deletedPs; 15790 // reader 15791 synchronized (mPackages) { 15792 deletedPkg = mPackages.get(packageName); 15793 deletedPs = mSettings.mPackages.get(packageName); 15794 if (outInfo != null) { 15795 outInfo.removedPackage = packageName; 15796 outInfo.removedUsers = deletedPs != null 15797 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15798 : null; 15799 } 15800 } 15801 15802 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15803 15804 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15805 final PackageParser.Package resolvedPkg; 15806 if (deletedPkg != null) { 15807 resolvedPkg = deletedPkg; 15808 } else { 15809 // We don't have a parsed package when it lives on an ejected 15810 // adopted storage device, so fake something together 15811 resolvedPkg = new PackageParser.Package(ps.name); 15812 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15813 } 15814 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15815 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15816 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15817 if (outInfo != null) { 15818 outInfo.dataRemoved = true; 15819 } 15820 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15821 } 15822 15823 // writer 15824 synchronized (mPackages) { 15825 if (deletedPs != null) { 15826 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15827 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15828 clearDefaultBrowserIfNeeded(packageName); 15829 if (outInfo != null) { 15830 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15831 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15832 } 15833 updatePermissionsLPw(deletedPs.name, null, 0); 15834 if (deletedPs.sharedUser != null) { 15835 // Remove permissions associated with package. Since runtime 15836 // permissions are per user we have to kill the removed package 15837 // or packages running under the shared user of the removed 15838 // package if revoking the permissions requested only by the removed 15839 // package is successful and this causes a change in gids. 15840 for (int userId : UserManagerService.getInstance().getUserIds()) { 15841 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15842 userId); 15843 if (userIdToKill == UserHandle.USER_ALL 15844 || userIdToKill >= UserHandle.USER_SYSTEM) { 15845 // If gids changed for this user, kill all affected packages. 15846 mHandler.post(new Runnable() { 15847 @Override 15848 public void run() { 15849 // This has to happen with no lock held. 15850 killApplication(deletedPs.name, deletedPs.appId, 15851 KILL_APP_REASON_GIDS_CHANGED); 15852 } 15853 }); 15854 break; 15855 } 15856 } 15857 } 15858 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15859 } 15860 // make sure to preserve per-user disabled state if this removal was just 15861 // a downgrade of a system app to the factory package 15862 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15863 if (DEBUG_REMOVE) { 15864 Slog.d(TAG, "Propagating install state across downgrade"); 15865 } 15866 for (int userId : allUserHandles) { 15867 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15868 if (DEBUG_REMOVE) { 15869 Slog.d(TAG, " user " + userId + " => " + installed); 15870 } 15871 ps.setInstalled(installed, userId); 15872 } 15873 } 15874 } 15875 // can downgrade to reader 15876 if (writeSettings) { 15877 // Save settings now 15878 mSettings.writeLPr(); 15879 } 15880 } 15881 if (outInfo != null) { 15882 // A user ID was deleted here. Go through all users and remove it 15883 // from KeyStore. 15884 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15885 } 15886 } 15887 15888 static boolean locationIsPrivileged(File path) { 15889 try { 15890 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15891 .getCanonicalPath(); 15892 return path.getCanonicalPath().startsWith(privilegedAppDir); 15893 } catch (IOException e) { 15894 Slog.e(TAG, "Unable to access code path " + path); 15895 } 15896 return false; 15897 } 15898 15899 /* 15900 * Tries to delete system package. 15901 */ 15902 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15903 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15904 boolean writeSettings) { 15905 if (deletedPs.parentPackageName != null) { 15906 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15907 return false; 15908 } 15909 15910 final boolean applyUserRestrictions 15911 = (allUserHandles != null) && (outInfo.origUsers != null); 15912 final PackageSetting disabledPs; 15913 // Confirm if the system package has been updated 15914 // An updated system app can be deleted. This will also have to restore 15915 // the system pkg from system partition 15916 // reader 15917 synchronized (mPackages) { 15918 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15919 } 15920 15921 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15922 + " disabledPs=" + disabledPs); 15923 15924 if (disabledPs == null) { 15925 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15926 return false; 15927 } else if (DEBUG_REMOVE) { 15928 Slog.d(TAG, "Deleting system pkg from data partition"); 15929 } 15930 15931 if (DEBUG_REMOVE) { 15932 if (applyUserRestrictions) { 15933 Slog.d(TAG, "Remembering install states:"); 15934 for (int userId : allUserHandles) { 15935 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15936 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15937 } 15938 } 15939 } 15940 15941 // Delete the updated package 15942 outInfo.isRemovedPackageSystemUpdate = true; 15943 if (outInfo.removedChildPackages != null) { 15944 final int childCount = (deletedPs.childPackageNames != null) 15945 ? deletedPs.childPackageNames.size() : 0; 15946 for (int i = 0; i < childCount; i++) { 15947 String childPackageName = deletedPs.childPackageNames.get(i); 15948 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15949 .contains(childPackageName)) { 15950 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15951 childPackageName); 15952 if (childInfo != null) { 15953 childInfo.isRemovedPackageSystemUpdate = true; 15954 } 15955 } 15956 } 15957 } 15958 15959 if (disabledPs.versionCode < deletedPs.versionCode) { 15960 // Delete data for downgrades 15961 flags &= ~PackageManager.DELETE_KEEP_DATA; 15962 } else { 15963 // Preserve data by setting flag 15964 flags |= PackageManager.DELETE_KEEP_DATA; 15965 } 15966 15967 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15968 outInfo, writeSettings, disabledPs.pkg); 15969 if (!ret) { 15970 return false; 15971 } 15972 15973 // writer 15974 synchronized (mPackages) { 15975 // Reinstate the old system package 15976 enableSystemPackageLPw(disabledPs.pkg); 15977 // Remove any native libraries from the upgraded package. 15978 removeNativeBinariesLI(deletedPs); 15979 } 15980 15981 // Install the system package 15982 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15983 int parseFlags = mDefParseFlags 15984 | PackageParser.PARSE_MUST_BE_APK 15985 | PackageParser.PARSE_IS_SYSTEM 15986 | PackageParser.PARSE_IS_SYSTEM_DIR; 15987 if (locationIsPrivileged(disabledPs.codePath)) { 15988 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15989 } 15990 15991 final PackageParser.Package newPkg; 15992 try { 15993 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15994 } catch (PackageManagerException e) { 15995 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15996 + e.getMessage()); 15997 return false; 15998 } 15999 16000 prepareAppDataAfterInstallLIF(newPkg); 16001 16002 // writer 16003 synchronized (mPackages) { 16004 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 16005 16006 // Propagate the permissions state as we do not want to drop on the floor 16007 // runtime permissions. The update permissions method below will take 16008 // care of removing obsolete permissions and grant install permissions. 16009 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 16010 updatePermissionsLPw(newPkg.packageName, newPkg, 16011 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 16012 16013 if (applyUserRestrictions) { 16014 if (DEBUG_REMOVE) { 16015 Slog.d(TAG, "Propagating install state across reinstall"); 16016 } 16017 for (int userId : allUserHandles) { 16018 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 16019 if (DEBUG_REMOVE) { 16020 Slog.d(TAG, " user " + userId + " => " + installed); 16021 } 16022 ps.setInstalled(installed, userId); 16023 16024 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16025 } 16026 // Regardless of writeSettings we need to ensure that this restriction 16027 // state propagation is persisted 16028 mSettings.writeAllUsersPackageRestrictionsLPr(); 16029 } 16030 // can downgrade to reader here 16031 if (writeSettings) { 16032 mSettings.writeLPr(); 16033 } 16034 } 16035 return true; 16036 } 16037 16038 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16039 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16040 PackageRemovedInfo outInfo, boolean writeSettings, 16041 PackageParser.Package replacingPackage) { 16042 synchronized (mPackages) { 16043 if (outInfo != null) { 16044 outInfo.uid = ps.appId; 16045 } 16046 16047 if (outInfo != null && outInfo.removedChildPackages != null) { 16048 final int childCount = (ps.childPackageNames != null) 16049 ? ps.childPackageNames.size() : 0; 16050 for (int i = 0; i < childCount; i++) { 16051 String childPackageName = ps.childPackageNames.get(i); 16052 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16053 if (childPs == null) { 16054 return false; 16055 } 16056 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16057 childPackageName); 16058 if (childInfo != null) { 16059 childInfo.uid = childPs.appId; 16060 } 16061 } 16062 } 16063 } 16064 16065 // Delete package data from internal structures and also remove data if flag is set 16066 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16067 16068 // Delete the child packages data 16069 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16070 for (int i = 0; i < childCount; i++) { 16071 PackageSetting childPs; 16072 synchronized (mPackages) { 16073 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16074 } 16075 if (childPs != null) { 16076 PackageRemovedInfo childOutInfo = (outInfo != null 16077 && outInfo.removedChildPackages != null) 16078 ? outInfo.removedChildPackages.get(childPs.name) : null; 16079 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16080 && (replacingPackage != null 16081 && !replacingPackage.hasChildPackage(childPs.name)) 16082 ? flags & ~DELETE_KEEP_DATA : flags; 16083 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16084 deleteFlags, writeSettings); 16085 } 16086 } 16087 16088 // Delete application code and resources only for parent packages 16089 if (ps.parentPackageName == null) { 16090 if (deleteCodeAndResources && (outInfo != null)) { 16091 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16092 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16093 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16094 } 16095 } 16096 16097 return true; 16098 } 16099 16100 @Override 16101 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16102 int userId) { 16103 mContext.enforceCallingOrSelfPermission( 16104 android.Manifest.permission.DELETE_PACKAGES, null); 16105 synchronized (mPackages) { 16106 PackageSetting ps = mSettings.mPackages.get(packageName); 16107 if (ps == null) { 16108 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16109 return false; 16110 } 16111 if (!ps.getInstalled(userId)) { 16112 // Can't block uninstall for an app that is not installed or enabled. 16113 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16114 return false; 16115 } 16116 ps.setBlockUninstall(blockUninstall, userId); 16117 mSettings.writePackageRestrictionsLPr(userId); 16118 } 16119 return true; 16120 } 16121 16122 @Override 16123 public boolean getBlockUninstallForUser(String packageName, int userId) { 16124 synchronized (mPackages) { 16125 PackageSetting ps = mSettings.mPackages.get(packageName); 16126 if (ps == null) { 16127 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16128 return false; 16129 } 16130 return ps.getBlockUninstall(userId); 16131 } 16132 } 16133 16134 @Override 16135 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16136 int callingUid = Binder.getCallingUid(); 16137 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16138 throw new SecurityException( 16139 "setRequiredForSystemUser can only be run by the system or root"); 16140 } 16141 synchronized (mPackages) { 16142 PackageSetting ps = mSettings.mPackages.get(packageName); 16143 if (ps == null) { 16144 Log.w(TAG, "Package doesn't exist: " + packageName); 16145 return false; 16146 } 16147 if (systemUserApp) { 16148 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16149 } else { 16150 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16151 } 16152 mSettings.writeLPr(); 16153 } 16154 return true; 16155 } 16156 16157 /* 16158 * This method handles package deletion in general 16159 */ 16160 private boolean deletePackageLIF(String packageName, UserHandle user, 16161 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16162 PackageRemovedInfo outInfo, boolean writeSettings, 16163 PackageParser.Package replacingPackage) { 16164 if (packageName == null) { 16165 Slog.w(TAG, "Attempt to delete null packageName."); 16166 return false; 16167 } 16168 16169 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16170 16171 PackageSetting ps; 16172 16173 synchronized (mPackages) { 16174 ps = mSettings.mPackages.get(packageName); 16175 if (ps == null) { 16176 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16177 return false; 16178 } 16179 16180 if (ps.parentPackageName != null && (!isSystemApp(ps) 16181 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16182 if (DEBUG_REMOVE) { 16183 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16184 + ((user == null) ? UserHandle.USER_ALL : user)); 16185 } 16186 final int removedUserId = (user != null) ? user.getIdentifier() 16187 : UserHandle.USER_ALL; 16188 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16189 return false; 16190 } 16191 markPackageUninstalledForUserLPw(ps, user); 16192 scheduleWritePackageRestrictionsLocked(user); 16193 return true; 16194 } 16195 } 16196 16197 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16198 && user.getIdentifier() != UserHandle.USER_ALL)) { 16199 // The caller is asking that the package only be deleted for a single 16200 // user. To do this, we just mark its uninstalled state and delete 16201 // its data. If this is a system app, we only allow this to happen if 16202 // they have set the special DELETE_SYSTEM_APP which requests different 16203 // semantics than normal for uninstalling system apps. 16204 markPackageUninstalledForUserLPw(ps, user); 16205 16206 if (!isSystemApp(ps)) { 16207 // Do not uninstall the APK if an app should be cached 16208 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16209 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16210 // Other user still have this package installed, so all 16211 // we need to do is clear this user's data and save that 16212 // it is uninstalled. 16213 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16214 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16215 return false; 16216 } 16217 scheduleWritePackageRestrictionsLocked(user); 16218 return true; 16219 } else { 16220 // We need to set it back to 'installed' so the uninstall 16221 // broadcasts will be sent correctly. 16222 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16223 ps.setInstalled(true, user.getIdentifier()); 16224 } 16225 } else { 16226 // This is a system app, so we assume that the 16227 // other users still have this package installed, so all 16228 // we need to do is clear this user's data and save that 16229 // it is uninstalled. 16230 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16231 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16232 return false; 16233 } 16234 scheduleWritePackageRestrictionsLocked(user); 16235 return true; 16236 } 16237 } 16238 16239 // If we are deleting a composite package for all users, keep track 16240 // of result for each child. 16241 if (ps.childPackageNames != null && outInfo != null) { 16242 synchronized (mPackages) { 16243 final int childCount = ps.childPackageNames.size(); 16244 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16245 for (int i = 0; i < childCount; i++) { 16246 String childPackageName = ps.childPackageNames.get(i); 16247 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16248 childInfo.removedPackage = childPackageName; 16249 outInfo.removedChildPackages.put(childPackageName, childInfo); 16250 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16251 if (childPs != null) { 16252 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16253 } 16254 } 16255 } 16256 } 16257 16258 boolean ret = false; 16259 if (isSystemApp(ps)) { 16260 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16261 // When an updated system application is deleted we delete the existing resources 16262 // as well and fall back to existing code in system partition 16263 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16264 } else { 16265 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16266 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16267 outInfo, writeSettings, replacingPackage); 16268 } 16269 16270 // Take a note whether we deleted the package for all users 16271 if (outInfo != null) { 16272 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16273 if (outInfo.removedChildPackages != null) { 16274 synchronized (mPackages) { 16275 final int childCount = outInfo.removedChildPackages.size(); 16276 for (int i = 0; i < childCount; i++) { 16277 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16278 if (childInfo != null) { 16279 childInfo.removedForAllUsers = mPackages.get( 16280 childInfo.removedPackage) == null; 16281 } 16282 } 16283 } 16284 } 16285 // If we uninstalled an update to a system app there may be some 16286 // child packages that appeared as they are declared in the system 16287 // app but were not declared in the update. 16288 if (isSystemApp(ps)) { 16289 synchronized (mPackages) { 16290 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16291 final int childCount = (updatedPs.childPackageNames != null) 16292 ? updatedPs.childPackageNames.size() : 0; 16293 for (int i = 0; i < childCount; i++) { 16294 String childPackageName = updatedPs.childPackageNames.get(i); 16295 if (outInfo.removedChildPackages == null 16296 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16297 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16298 if (childPs == null) { 16299 continue; 16300 } 16301 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16302 installRes.name = childPackageName; 16303 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16304 installRes.pkg = mPackages.get(childPackageName); 16305 installRes.uid = childPs.pkg.applicationInfo.uid; 16306 if (outInfo.appearedChildPackages == null) { 16307 outInfo.appearedChildPackages = new ArrayMap<>(); 16308 } 16309 outInfo.appearedChildPackages.put(childPackageName, installRes); 16310 } 16311 } 16312 } 16313 } 16314 } 16315 16316 return ret; 16317 } 16318 16319 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16320 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16321 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16322 for (int nextUserId : userIds) { 16323 if (DEBUG_REMOVE) { 16324 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16325 } 16326 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16327 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16328 false /*hidden*/, false /*suspended*/, null, null, null, 16329 false /*blockUninstall*/, 16330 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16331 } 16332 } 16333 16334 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16335 PackageRemovedInfo outInfo) { 16336 final PackageParser.Package pkg; 16337 synchronized (mPackages) { 16338 pkg = mPackages.get(ps.name); 16339 } 16340 16341 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16342 : new int[] {userId}; 16343 for (int nextUserId : userIds) { 16344 if (DEBUG_REMOVE) { 16345 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16346 + nextUserId); 16347 } 16348 16349 destroyAppDataLIF(pkg, userId, 16350 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16351 destroyAppProfilesLIF(pkg, userId); 16352 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16353 schedulePackageCleaning(ps.name, nextUserId, false); 16354 synchronized (mPackages) { 16355 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16356 scheduleWritePackageRestrictionsLocked(nextUserId); 16357 } 16358 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16359 } 16360 } 16361 16362 if (outInfo != null) { 16363 outInfo.removedPackage = ps.name; 16364 outInfo.removedAppId = ps.appId; 16365 outInfo.removedUsers = userIds; 16366 } 16367 16368 return true; 16369 } 16370 16371 private final class ClearStorageConnection implements ServiceConnection { 16372 IMediaContainerService mContainerService; 16373 16374 @Override 16375 public void onServiceConnected(ComponentName name, IBinder service) { 16376 synchronized (this) { 16377 mContainerService = IMediaContainerService.Stub.asInterface(service); 16378 notifyAll(); 16379 } 16380 } 16381 16382 @Override 16383 public void onServiceDisconnected(ComponentName name) { 16384 } 16385 } 16386 16387 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16388 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16389 16390 final boolean mounted; 16391 if (Environment.isExternalStorageEmulated()) { 16392 mounted = true; 16393 } else { 16394 final String status = Environment.getExternalStorageState(); 16395 16396 mounted = status.equals(Environment.MEDIA_MOUNTED) 16397 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16398 } 16399 16400 if (!mounted) { 16401 return; 16402 } 16403 16404 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16405 int[] users; 16406 if (userId == UserHandle.USER_ALL) { 16407 users = sUserManager.getUserIds(); 16408 } else { 16409 users = new int[] { userId }; 16410 } 16411 final ClearStorageConnection conn = new ClearStorageConnection(); 16412 if (mContext.bindServiceAsUser( 16413 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16414 try { 16415 for (int curUser : users) { 16416 long timeout = SystemClock.uptimeMillis() + 5000; 16417 synchronized (conn) { 16418 long now; 16419 while (conn.mContainerService == null && 16420 (now = SystemClock.uptimeMillis()) < timeout) { 16421 try { 16422 conn.wait(timeout - now); 16423 } catch (InterruptedException e) { 16424 } 16425 } 16426 } 16427 if (conn.mContainerService == null) { 16428 return; 16429 } 16430 16431 final UserEnvironment userEnv = new UserEnvironment(curUser); 16432 clearDirectory(conn.mContainerService, 16433 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16434 if (allData) { 16435 clearDirectory(conn.mContainerService, 16436 userEnv.buildExternalStorageAppDataDirs(packageName)); 16437 clearDirectory(conn.mContainerService, 16438 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16439 } 16440 } 16441 } finally { 16442 mContext.unbindService(conn); 16443 } 16444 } 16445 } 16446 16447 @Override 16448 public void clearApplicationProfileData(String packageName) { 16449 enforceSystemOrRoot("Only the system can clear all profile data"); 16450 16451 final PackageParser.Package pkg; 16452 synchronized (mPackages) { 16453 pkg = mPackages.get(packageName); 16454 } 16455 16456 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16457 synchronized (mInstallLock) { 16458 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16459 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16460 true /* removeBaseMarker */); 16461 } 16462 } 16463 } 16464 16465 @Override 16466 public void clearApplicationUserData(final String packageName, 16467 final IPackageDataObserver observer, final int userId) { 16468 mContext.enforceCallingOrSelfPermission( 16469 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16470 16471 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16472 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16473 16474 if (mProtectedPackages.isPackageDataProtected(userId, packageName)) { 16475 throw new SecurityException("Cannot clear data for a protected package: " 16476 + packageName); 16477 } 16478 // Queue up an async operation since the package deletion may take a little while. 16479 mHandler.post(new Runnable() { 16480 public void run() { 16481 mHandler.removeCallbacks(this); 16482 final boolean succeeded; 16483 try (PackageFreezer freezer = freezePackage(packageName, 16484 "clearApplicationUserData")) { 16485 synchronized (mInstallLock) { 16486 succeeded = clearApplicationUserDataLIF(packageName, userId); 16487 } 16488 clearExternalStorageDataSync(packageName, userId, true); 16489 } 16490 if (succeeded) { 16491 // invoke DeviceStorageMonitor's update method to clear any notifications 16492 DeviceStorageMonitorInternal dsm = LocalServices 16493 .getService(DeviceStorageMonitorInternal.class); 16494 if (dsm != null) { 16495 dsm.checkMemory(); 16496 } 16497 } 16498 if(observer != null) { 16499 try { 16500 observer.onRemoveCompleted(packageName, succeeded); 16501 } catch (RemoteException e) { 16502 Log.i(TAG, "Observer no longer exists."); 16503 } 16504 } //end if observer 16505 } //end run 16506 }); 16507 } 16508 16509 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16510 if (packageName == null) { 16511 Slog.w(TAG, "Attempt to delete null packageName."); 16512 return false; 16513 } 16514 16515 // Try finding details about the requested package 16516 PackageParser.Package pkg; 16517 synchronized (mPackages) { 16518 pkg = mPackages.get(packageName); 16519 if (pkg == null) { 16520 final PackageSetting ps = mSettings.mPackages.get(packageName); 16521 if (ps != null) { 16522 pkg = ps.pkg; 16523 } 16524 } 16525 16526 if (pkg == null) { 16527 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16528 return false; 16529 } 16530 16531 PackageSetting ps = (PackageSetting) pkg.mExtras; 16532 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16533 } 16534 16535 clearAppDataLIF(pkg, userId, 16536 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16537 16538 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16539 removeKeystoreDataIfNeeded(userId, appId); 16540 16541 UserManagerInternal umInternal = getUserManagerInternal(); 16542 final int flags; 16543 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16544 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16545 } else if (umInternal.isUserRunning(userId)) { 16546 flags = StorageManager.FLAG_STORAGE_DE; 16547 } else { 16548 flags = 0; 16549 } 16550 prepareAppDataContentsLIF(pkg, userId, flags); 16551 16552 return true; 16553 } 16554 16555 /** 16556 * Reverts user permission state changes (permissions and flags) in 16557 * all packages for a given user. 16558 * 16559 * @param userId The device user for which to do a reset. 16560 */ 16561 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16562 final int packageCount = mPackages.size(); 16563 for (int i = 0; i < packageCount; i++) { 16564 PackageParser.Package pkg = mPackages.valueAt(i); 16565 PackageSetting ps = (PackageSetting) pkg.mExtras; 16566 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16567 } 16568 } 16569 16570 private void resetNetworkPolicies(int userId) { 16571 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16572 } 16573 16574 /** 16575 * Reverts user permission state changes (permissions and flags). 16576 * 16577 * @param ps The package for which to reset. 16578 * @param userId The device user for which to do a reset. 16579 */ 16580 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16581 final PackageSetting ps, final int userId) { 16582 if (ps.pkg == null) { 16583 return; 16584 } 16585 16586 // These are flags that can change base on user actions. 16587 final int userSettableMask = FLAG_PERMISSION_USER_SET 16588 | FLAG_PERMISSION_USER_FIXED 16589 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16590 | FLAG_PERMISSION_REVIEW_REQUIRED; 16591 16592 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16593 | FLAG_PERMISSION_POLICY_FIXED; 16594 16595 boolean writeInstallPermissions = false; 16596 boolean writeRuntimePermissions = false; 16597 16598 final int permissionCount = ps.pkg.requestedPermissions.size(); 16599 for (int i = 0; i < permissionCount; i++) { 16600 String permission = ps.pkg.requestedPermissions.get(i); 16601 16602 BasePermission bp = mSettings.mPermissions.get(permission); 16603 if (bp == null) { 16604 continue; 16605 } 16606 16607 // If shared user we just reset the state to which only this app contributed. 16608 if (ps.sharedUser != null) { 16609 boolean used = false; 16610 final int packageCount = ps.sharedUser.packages.size(); 16611 for (int j = 0; j < packageCount; j++) { 16612 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16613 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16614 && pkg.pkg.requestedPermissions.contains(permission)) { 16615 used = true; 16616 break; 16617 } 16618 } 16619 if (used) { 16620 continue; 16621 } 16622 } 16623 16624 PermissionsState permissionsState = ps.getPermissionsState(); 16625 16626 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16627 16628 // Always clear the user settable flags. 16629 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16630 bp.name) != null; 16631 // If permission review is enabled and this is a legacy app, mark the 16632 // permission as requiring a review as this is the initial state. 16633 int flags = 0; 16634 if (Build.PERMISSIONS_REVIEW_REQUIRED 16635 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16636 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16637 } 16638 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16639 if (hasInstallState) { 16640 writeInstallPermissions = true; 16641 } else { 16642 writeRuntimePermissions = true; 16643 } 16644 } 16645 16646 // Below is only runtime permission handling. 16647 if (!bp.isRuntime()) { 16648 continue; 16649 } 16650 16651 // Never clobber system or policy. 16652 if ((oldFlags & policyOrSystemFlags) != 0) { 16653 continue; 16654 } 16655 16656 // If this permission was granted by default, make sure it is. 16657 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16658 if (permissionsState.grantRuntimePermission(bp, userId) 16659 != PERMISSION_OPERATION_FAILURE) { 16660 writeRuntimePermissions = true; 16661 } 16662 // If permission review is enabled the permissions for a legacy apps 16663 // are represented as constantly granted runtime ones, so don't revoke. 16664 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16665 // Otherwise, reset the permission. 16666 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16667 switch (revokeResult) { 16668 case PERMISSION_OPERATION_SUCCESS: 16669 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16670 writeRuntimePermissions = true; 16671 final int appId = ps.appId; 16672 mHandler.post(new Runnable() { 16673 @Override 16674 public void run() { 16675 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16676 } 16677 }); 16678 } break; 16679 } 16680 } 16681 } 16682 16683 // Synchronously write as we are taking permissions away. 16684 if (writeRuntimePermissions) { 16685 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16686 } 16687 16688 // Synchronously write as we are taking permissions away. 16689 if (writeInstallPermissions) { 16690 mSettings.writeLPr(); 16691 } 16692 } 16693 16694 /** 16695 * Remove entries from the keystore daemon. Will only remove it if the 16696 * {@code appId} is valid. 16697 */ 16698 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16699 if (appId < 0) { 16700 return; 16701 } 16702 16703 final KeyStore keyStore = KeyStore.getInstance(); 16704 if (keyStore != null) { 16705 if (userId == UserHandle.USER_ALL) { 16706 for (final int individual : sUserManager.getUserIds()) { 16707 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16708 } 16709 } else { 16710 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16711 } 16712 } else { 16713 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16714 } 16715 } 16716 16717 @Override 16718 public void deleteApplicationCacheFiles(final String packageName, 16719 final IPackageDataObserver observer) { 16720 final int userId = UserHandle.getCallingUserId(); 16721 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16722 } 16723 16724 @Override 16725 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16726 final IPackageDataObserver observer) { 16727 mContext.enforceCallingOrSelfPermission( 16728 android.Manifest.permission.DELETE_CACHE_FILES, null); 16729 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16730 /* requireFullPermission= */ true, /* checkShell= */ false, 16731 "delete application cache files"); 16732 16733 final PackageParser.Package pkg; 16734 synchronized (mPackages) { 16735 pkg = mPackages.get(packageName); 16736 } 16737 16738 // Queue up an async operation since the package deletion may take a little while. 16739 mHandler.post(new Runnable() { 16740 public void run() { 16741 synchronized (mInstallLock) { 16742 final int flags = StorageManager.FLAG_STORAGE_DE 16743 | StorageManager.FLAG_STORAGE_CE; 16744 // We're only clearing cache files, so we don't care if the 16745 // app is unfrozen and still able to run 16746 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16747 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16748 } 16749 clearExternalStorageDataSync(packageName, userId, false); 16750 if (observer != null) { 16751 try { 16752 observer.onRemoveCompleted(packageName, true); 16753 } catch (RemoteException e) { 16754 Log.i(TAG, "Observer no longer exists."); 16755 } 16756 } 16757 } 16758 }); 16759 } 16760 16761 @Override 16762 public void getPackageSizeInfo(final String packageName, int userHandle, 16763 final IPackageStatsObserver observer) { 16764 mContext.enforceCallingOrSelfPermission( 16765 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16766 if (packageName == null) { 16767 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16768 } 16769 16770 PackageStats stats = new PackageStats(packageName, userHandle); 16771 16772 /* 16773 * Queue up an async operation since the package measurement may take a 16774 * little while. 16775 */ 16776 Message msg = mHandler.obtainMessage(INIT_COPY); 16777 msg.obj = new MeasureParams(stats, observer); 16778 mHandler.sendMessage(msg); 16779 } 16780 16781 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16782 final PackageSetting ps; 16783 synchronized (mPackages) { 16784 ps = mSettings.mPackages.get(packageName); 16785 if (ps == null) { 16786 Slog.w(TAG, "Failed to find settings for " + packageName); 16787 return false; 16788 } 16789 } 16790 try { 16791 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16792 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16793 ps.getCeDataInode(userId), ps.codePathString, stats); 16794 } catch (InstallerException e) { 16795 Slog.w(TAG, String.valueOf(e)); 16796 return false; 16797 } 16798 16799 // For now, ignore code size of packages on system partition 16800 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16801 stats.codeSize = 0; 16802 } 16803 16804 return true; 16805 } 16806 16807 private int getUidTargetSdkVersionLockedLPr(int uid) { 16808 Object obj = mSettings.getUserIdLPr(uid); 16809 if (obj instanceof SharedUserSetting) { 16810 final SharedUserSetting sus = (SharedUserSetting) obj; 16811 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16812 final Iterator<PackageSetting> it = sus.packages.iterator(); 16813 while (it.hasNext()) { 16814 final PackageSetting ps = it.next(); 16815 if (ps.pkg != null) { 16816 int v = ps.pkg.applicationInfo.targetSdkVersion; 16817 if (v < vers) vers = v; 16818 } 16819 } 16820 return vers; 16821 } else if (obj instanceof PackageSetting) { 16822 final PackageSetting ps = (PackageSetting) obj; 16823 if (ps.pkg != null) { 16824 return ps.pkg.applicationInfo.targetSdkVersion; 16825 } 16826 } 16827 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16828 } 16829 16830 @Override 16831 public void addPreferredActivity(IntentFilter filter, int match, 16832 ComponentName[] set, ComponentName activity, int userId) { 16833 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16834 "Adding preferred"); 16835 } 16836 16837 private void addPreferredActivityInternal(IntentFilter filter, int match, 16838 ComponentName[] set, ComponentName activity, boolean always, int userId, 16839 String opname) { 16840 // writer 16841 int callingUid = Binder.getCallingUid(); 16842 enforceCrossUserPermission(callingUid, userId, 16843 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16844 if (filter.countActions() == 0) { 16845 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16846 return; 16847 } 16848 synchronized (mPackages) { 16849 if (mContext.checkCallingOrSelfPermission( 16850 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16851 != PackageManager.PERMISSION_GRANTED) { 16852 if (getUidTargetSdkVersionLockedLPr(callingUid) 16853 < Build.VERSION_CODES.FROYO) { 16854 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16855 + callingUid); 16856 return; 16857 } 16858 mContext.enforceCallingOrSelfPermission( 16859 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16860 } 16861 16862 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16863 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16864 + userId + ":"); 16865 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16866 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16867 scheduleWritePackageRestrictionsLocked(userId); 16868 } 16869 } 16870 16871 @Override 16872 public void replacePreferredActivity(IntentFilter filter, int match, 16873 ComponentName[] set, ComponentName activity, int userId) { 16874 if (filter.countActions() != 1) { 16875 throw new IllegalArgumentException( 16876 "replacePreferredActivity expects filter to have only 1 action."); 16877 } 16878 if (filter.countDataAuthorities() != 0 16879 || filter.countDataPaths() != 0 16880 || filter.countDataSchemes() > 1 16881 || filter.countDataTypes() != 0) { 16882 throw new IllegalArgumentException( 16883 "replacePreferredActivity expects filter to have no data authorities, " + 16884 "paths, or types; and at most one scheme."); 16885 } 16886 16887 final int callingUid = Binder.getCallingUid(); 16888 enforceCrossUserPermission(callingUid, userId, 16889 true /* requireFullPermission */, false /* checkShell */, 16890 "replace preferred activity"); 16891 synchronized (mPackages) { 16892 if (mContext.checkCallingOrSelfPermission( 16893 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16894 != PackageManager.PERMISSION_GRANTED) { 16895 if (getUidTargetSdkVersionLockedLPr(callingUid) 16896 < Build.VERSION_CODES.FROYO) { 16897 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16898 + Binder.getCallingUid()); 16899 return; 16900 } 16901 mContext.enforceCallingOrSelfPermission( 16902 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16903 } 16904 16905 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16906 if (pir != null) { 16907 // Get all of the existing entries that exactly match this filter. 16908 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16909 if (existing != null && existing.size() == 1) { 16910 PreferredActivity cur = existing.get(0); 16911 if (DEBUG_PREFERRED) { 16912 Slog.i(TAG, "Checking replace of preferred:"); 16913 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16914 if (!cur.mPref.mAlways) { 16915 Slog.i(TAG, " -- CUR; not mAlways!"); 16916 } else { 16917 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16918 Slog.i(TAG, " -- CUR: mSet=" 16919 + Arrays.toString(cur.mPref.mSetComponents)); 16920 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16921 Slog.i(TAG, " -- NEW: mMatch=" 16922 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16923 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16924 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16925 } 16926 } 16927 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16928 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16929 && cur.mPref.sameSet(set)) { 16930 // Setting the preferred activity to what it happens to be already 16931 if (DEBUG_PREFERRED) { 16932 Slog.i(TAG, "Replacing with same preferred activity " 16933 + cur.mPref.mShortComponent + " for user " 16934 + userId + ":"); 16935 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16936 } 16937 return; 16938 } 16939 } 16940 16941 if (existing != null) { 16942 if (DEBUG_PREFERRED) { 16943 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16944 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16945 } 16946 for (int i = 0; i < existing.size(); i++) { 16947 PreferredActivity pa = existing.get(i); 16948 if (DEBUG_PREFERRED) { 16949 Slog.i(TAG, "Removing existing preferred activity " 16950 + pa.mPref.mComponent + ":"); 16951 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16952 } 16953 pir.removeFilter(pa); 16954 } 16955 } 16956 } 16957 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16958 "Replacing preferred"); 16959 } 16960 } 16961 16962 @Override 16963 public void clearPackagePreferredActivities(String packageName) { 16964 final int uid = Binder.getCallingUid(); 16965 // writer 16966 synchronized (mPackages) { 16967 PackageParser.Package pkg = mPackages.get(packageName); 16968 if (pkg == null || pkg.applicationInfo.uid != uid) { 16969 if (mContext.checkCallingOrSelfPermission( 16970 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16971 != PackageManager.PERMISSION_GRANTED) { 16972 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16973 < Build.VERSION_CODES.FROYO) { 16974 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16975 + Binder.getCallingUid()); 16976 return; 16977 } 16978 mContext.enforceCallingOrSelfPermission( 16979 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16980 } 16981 } 16982 16983 int user = UserHandle.getCallingUserId(); 16984 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16985 scheduleWritePackageRestrictionsLocked(user); 16986 } 16987 } 16988 } 16989 16990 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16991 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16992 ArrayList<PreferredActivity> removed = null; 16993 boolean changed = false; 16994 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16995 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16996 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16997 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16998 continue; 16999 } 17000 Iterator<PreferredActivity> it = pir.filterIterator(); 17001 while (it.hasNext()) { 17002 PreferredActivity pa = it.next(); 17003 // Mark entry for removal only if it matches the package name 17004 // and the entry is of type "always". 17005 if (packageName == null || 17006 (pa.mPref.mComponent.getPackageName().equals(packageName) 17007 && pa.mPref.mAlways)) { 17008 if (removed == null) { 17009 removed = new ArrayList<PreferredActivity>(); 17010 } 17011 removed.add(pa); 17012 } 17013 } 17014 if (removed != null) { 17015 for (int j=0; j<removed.size(); j++) { 17016 PreferredActivity pa = removed.get(j); 17017 pir.removeFilter(pa); 17018 } 17019 changed = true; 17020 } 17021 } 17022 return changed; 17023 } 17024 17025 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17026 private void clearIntentFilterVerificationsLPw(int userId) { 17027 final int packageCount = mPackages.size(); 17028 for (int i = 0; i < packageCount; i++) { 17029 PackageParser.Package pkg = mPackages.valueAt(i); 17030 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 17031 } 17032 } 17033 17034 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 17035 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 17036 if (userId == UserHandle.USER_ALL) { 17037 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17038 sUserManager.getUserIds())) { 17039 for (int oneUserId : sUserManager.getUserIds()) { 17040 scheduleWritePackageRestrictionsLocked(oneUserId); 17041 } 17042 } 17043 } else { 17044 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17045 scheduleWritePackageRestrictionsLocked(userId); 17046 } 17047 } 17048 } 17049 17050 void clearDefaultBrowserIfNeeded(String packageName) { 17051 for (int oneUserId : sUserManager.getUserIds()) { 17052 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17053 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17054 if (packageName.equals(defaultBrowserPackageName)) { 17055 setDefaultBrowserPackageName(null, oneUserId); 17056 } 17057 } 17058 } 17059 17060 @Override 17061 public void resetApplicationPreferences(int userId) { 17062 mContext.enforceCallingOrSelfPermission( 17063 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17064 final long identity = Binder.clearCallingIdentity(); 17065 // writer 17066 try { 17067 synchronized (mPackages) { 17068 clearPackagePreferredActivitiesLPw(null, userId); 17069 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17070 // TODO: We have to reset the default SMS and Phone. This requires 17071 // significant refactoring to keep all default apps in the package 17072 // manager (cleaner but more work) or have the services provide 17073 // callbacks to the package manager to request a default app reset. 17074 applyFactoryDefaultBrowserLPw(userId); 17075 clearIntentFilterVerificationsLPw(userId); 17076 primeDomainVerificationsLPw(userId); 17077 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17078 scheduleWritePackageRestrictionsLocked(userId); 17079 } 17080 resetNetworkPolicies(userId); 17081 } finally { 17082 Binder.restoreCallingIdentity(identity); 17083 } 17084 } 17085 17086 @Override 17087 public int getPreferredActivities(List<IntentFilter> outFilters, 17088 List<ComponentName> outActivities, String packageName) { 17089 17090 int num = 0; 17091 final int userId = UserHandle.getCallingUserId(); 17092 // reader 17093 synchronized (mPackages) { 17094 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17095 if (pir != null) { 17096 final Iterator<PreferredActivity> it = pir.filterIterator(); 17097 while (it.hasNext()) { 17098 final PreferredActivity pa = it.next(); 17099 if (packageName == null 17100 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17101 && pa.mPref.mAlways)) { 17102 if (outFilters != null) { 17103 outFilters.add(new IntentFilter(pa)); 17104 } 17105 if (outActivities != null) { 17106 outActivities.add(pa.mPref.mComponent); 17107 } 17108 } 17109 } 17110 } 17111 } 17112 17113 return num; 17114 } 17115 17116 @Override 17117 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17118 int userId) { 17119 int callingUid = Binder.getCallingUid(); 17120 if (callingUid != Process.SYSTEM_UID) { 17121 throw new SecurityException( 17122 "addPersistentPreferredActivity can only be run by the system"); 17123 } 17124 if (filter.countActions() == 0) { 17125 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17126 return; 17127 } 17128 synchronized (mPackages) { 17129 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17130 ":"); 17131 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17132 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17133 new PersistentPreferredActivity(filter, activity)); 17134 scheduleWritePackageRestrictionsLocked(userId); 17135 } 17136 } 17137 17138 @Override 17139 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17140 int callingUid = Binder.getCallingUid(); 17141 if (callingUid != Process.SYSTEM_UID) { 17142 throw new SecurityException( 17143 "clearPackagePersistentPreferredActivities can only be run by the system"); 17144 } 17145 ArrayList<PersistentPreferredActivity> removed = null; 17146 boolean changed = false; 17147 synchronized (mPackages) { 17148 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17149 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17150 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17151 .valueAt(i); 17152 if (userId != thisUserId) { 17153 continue; 17154 } 17155 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17156 while (it.hasNext()) { 17157 PersistentPreferredActivity ppa = it.next(); 17158 // Mark entry for removal only if it matches the package name. 17159 if (ppa.mComponent.getPackageName().equals(packageName)) { 17160 if (removed == null) { 17161 removed = new ArrayList<PersistentPreferredActivity>(); 17162 } 17163 removed.add(ppa); 17164 } 17165 } 17166 if (removed != null) { 17167 for (int j=0; j<removed.size(); j++) { 17168 PersistentPreferredActivity ppa = removed.get(j); 17169 ppir.removeFilter(ppa); 17170 } 17171 changed = true; 17172 } 17173 } 17174 17175 if (changed) { 17176 scheduleWritePackageRestrictionsLocked(userId); 17177 } 17178 } 17179 } 17180 17181 /** 17182 * Common machinery for picking apart a restored XML blob and passing 17183 * it to a caller-supplied functor to be applied to the running system. 17184 */ 17185 private void restoreFromXml(XmlPullParser parser, int userId, 17186 String expectedStartTag, BlobXmlRestorer functor) 17187 throws IOException, XmlPullParserException { 17188 int type; 17189 while ((type = parser.next()) != XmlPullParser.START_TAG 17190 && type != XmlPullParser.END_DOCUMENT) { 17191 } 17192 if (type != XmlPullParser.START_TAG) { 17193 // oops didn't find a start tag?! 17194 if (DEBUG_BACKUP) { 17195 Slog.e(TAG, "Didn't find start tag during restore"); 17196 } 17197 return; 17198 } 17199Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17200 // this is supposed to be TAG_PREFERRED_BACKUP 17201 if (!expectedStartTag.equals(parser.getName())) { 17202 if (DEBUG_BACKUP) { 17203 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17204 } 17205 return; 17206 } 17207 17208 // skip interfering stuff, then we're aligned with the backing implementation 17209 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17210Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17211 functor.apply(parser, userId); 17212 } 17213 17214 private interface BlobXmlRestorer { 17215 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17216 } 17217 17218 /** 17219 * Non-Binder method, support for the backup/restore mechanism: write the 17220 * full set of preferred activities in its canonical XML format. Returns the 17221 * XML output as a byte array, or null if there is none. 17222 */ 17223 @Override 17224 public byte[] getPreferredActivityBackup(int userId) { 17225 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17226 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17227 } 17228 17229 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17230 try { 17231 final XmlSerializer serializer = new FastXmlSerializer(); 17232 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17233 serializer.startDocument(null, true); 17234 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17235 17236 synchronized (mPackages) { 17237 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17238 } 17239 17240 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17241 serializer.endDocument(); 17242 serializer.flush(); 17243 } catch (Exception e) { 17244 if (DEBUG_BACKUP) { 17245 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17246 } 17247 return null; 17248 } 17249 17250 return dataStream.toByteArray(); 17251 } 17252 17253 @Override 17254 public void restorePreferredActivities(byte[] backup, int userId) { 17255 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17256 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17257 } 17258 17259 try { 17260 final XmlPullParser parser = Xml.newPullParser(); 17261 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17262 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17263 new BlobXmlRestorer() { 17264 @Override 17265 public void apply(XmlPullParser parser, int userId) 17266 throws XmlPullParserException, IOException { 17267 synchronized (mPackages) { 17268 mSettings.readPreferredActivitiesLPw(parser, userId); 17269 } 17270 } 17271 } ); 17272 } catch (Exception e) { 17273 if (DEBUG_BACKUP) { 17274 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17275 } 17276 } 17277 } 17278 17279 /** 17280 * Non-Binder method, support for the backup/restore mechanism: write the 17281 * default browser (etc) settings in its canonical XML format. Returns the default 17282 * browser XML representation as a byte array, or null if there is none. 17283 */ 17284 @Override 17285 public byte[] getDefaultAppsBackup(int userId) { 17286 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17287 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17288 } 17289 17290 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17291 try { 17292 final XmlSerializer serializer = new FastXmlSerializer(); 17293 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17294 serializer.startDocument(null, true); 17295 serializer.startTag(null, TAG_DEFAULT_APPS); 17296 17297 synchronized (mPackages) { 17298 mSettings.writeDefaultAppsLPr(serializer, userId); 17299 } 17300 17301 serializer.endTag(null, TAG_DEFAULT_APPS); 17302 serializer.endDocument(); 17303 serializer.flush(); 17304 } catch (Exception e) { 17305 if (DEBUG_BACKUP) { 17306 Slog.e(TAG, "Unable to write default apps for backup", e); 17307 } 17308 return null; 17309 } 17310 17311 return dataStream.toByteArray(); 17312 } 17313 17314 @Override 17315 public void restoreDefaultApps(byte[] backup, int userId) { 17316 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17317 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17318 } 17319 17320 try { 17321 final XmlPullParser parser = Xml.newPullParser(); 17322 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17323 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17324 new BlobXmlRestorer() { 17325 @Override 17326 public void apply(XmlPullParser parser, int userId) 17327 throws XmlPullParserException, IOException { 17328 synchronized (mPackages) { 17329 mSettings.readDefaultAppsLPw(parser, userId); 17330 } 17331 } 17332 } ); 17333 } catch (Exception e) { 17334 if (DEBUG_BACKUP) { 17335 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17336 } 17337 } 17338 } 17339 17340 @Override 17341 public byte[] getIntentFilterVerificationBackup(int userId) { 17342 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17343 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17344 } 17345 17346 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17347 try { 17348 final XmlSerializer serializer = new FastXmlSerializer(); 17349 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17350 serializer.startDocument(null, true); 17351 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17352 17353 synchronized (mPackages) { 17354 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17355 } 17356 17357 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17358 serializer.endDocument(); 17359 serializer.flush(); 17360 } catch (Exception e) { 17361 if (DEBUG_BACKUP) { 17362 Slog.e(TAG, "Unable to write default apps for backup", e); 17363 } 17364 return null; 17365 } 17366 17367 return dataStream.toByteArray(); 17368 } 17369 17370 @Override 17371 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17372 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17373 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17374 } 17375 17376 try { 17377 final XmlPullParser parser = Xml.newPullParser(); 17378 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17379 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17380 new BlobXmlRestorer() { 17381 @Override 17382 public void apply(XmlPullParser parser, int userId) 17383 throws XmlPullParserException, IOException { 17384 synchronized (mPackages) { 17385 mSettings.readAllDomainVerificationsLPr(parser, userId); 17386 mSettings.writeLPr(); 17387 } 17388 } 17389 } ); 17390 } catch (Exception e) { 17391 if (DEBUG_BACKUP) { 17392 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17393 } 17394 } 17395 } 17396 17397 @Override 17398 public byte[] getPermissionGrantBackup(int userId) { 17399 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17400 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17401 } 17402 17403 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17404 try { 17405 final XmlSerializer serializer = new FastXmlSerializer(); 17406 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17407 serializer.startDocument(null, true); 17408 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17409 17410 synchronized (mPackages) { 17411 serializeRuntimePermissionGrantsLPr(serializer, userId); 17412 } 17413 17414 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17415 serializer.endDocument(); 17416 serializer.flush(); 17417 } catch (Exception e) { 17418 if (DEBUG_BACKUP) { 17419 Slog.e(TAG, "Unable to write default apps for backup", e); 17420 } 17421 return null; 17422 } 17423 17424 return dataStream.toByteArray(); 17425 } 17426 17427 @Override 17428 public void restorePermissionGrants(byte[] backup, int userId) { 17429 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17430 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17431 } 17432 17433 try { 17434 final XmlPullParser parser = Xml.newPullParser(); 17435 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17436 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17437 new BlobXmlRestorer() { 17438 @Override 17439 public void apply(XmlPullParser parser, int userId) 17440 throws XmlPullParserException, IOException { 17441 synchronized (mPackages) { 17442 processRestoredPermissionGrantsLPr(parser, userId); 17443 } 17444 } 17445 } ); 17446 } catch (Exception e) { 17447 if (DEBUG_BACKUP) { 17448 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17449 } 17450 } 17451 } 17452 17453 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17454 throws IOException { 17455 serializer.startTag(null, TAG_ALL_GRANTS); 17456 17457 final int N = mSettings.mPackages.size(); 17458 for (int i = 0; i < N; i++) { 17459 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17460 boolean pkgGrantsKnown = false; 17461 17462 PermissionsState packagePerms = ps.getPermissionsState(); 17463 17464 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17465 final int grantFlags = state.getFlags(); 17466 // only look at grants that are not system/policy fixed 17467 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17468 final boolean isGranted = state.isGranted(); 17469 // And only back up the user-twiddled state bits 17470 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17471 final String packageName = mSettings.mPackages.keyAt(i); 17472 if (!pkgGrantsKnown) { 17473 serializer.startTag(null, TAG_GRANT); 17474 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17475 pkgGrantsKnown = true; 17476 } 17477 17478 final boolean userSet = 17479 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17480 final boolean userFixed = 17481 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17482 final boolean revoke = 17483 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17484 17485 serializer.startTag(null, TAG_PERMISSION); 17486 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17487 if (isGranted) { 17488 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17489 } 17490 if (userSet) { 17491 serializer.attribute(null, ATTR_USER_SET, "true"); 17492 } 17493 if (userFixed) { 17494 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17495 } 17496 if (revoke) { 17497 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17498 } 17499 serializer.endTag(null, TAG_PERMISSION); 17500 } 17501 } 17502 } 17503 17504 if (pkgGrantsKnown) { 17505 serializer.endTag(null, TAG_GRANT); 17506 } 17507 } 17508 17509 serializer.endTag(null, TAG_ALL_GRANTS); 17510 } 17511 17512 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17513 throws XmlPullParserException, IOException { 17514 String pkgName = null; 17515 int outerDepth = parser.getDepth(); 17516 int type; 17517 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17518 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17519 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17520 continue; 17521 } 17522 17523 final String tagName = parser.getName(); 17524 if (tagName.equals(TAG_GRANT)) { 17525 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17526 if (DEBUG_BACKUP) { 17527 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17528 } 17529 } else if (tagName.equals(TAG_PERMISSION)) { 17530 17531 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17532 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17533 17534 int newFlagSet = 0; 17535 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17536 newFlagSet |= FLAG_PERMISSION_USER_SET; 17537 } 17538 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17539 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17540 } 17541 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17542 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17543 } 17544 if (DEBUG_BACKUP) { 17545 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17546 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17547 } 17548 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17549 if (ps != null) { 17550 // Already installed so we apply the grant immediately 17551 if (DEBUG_BACKUP) { 17552 Slog.v(TAG, " + already installed; applying"); 17553 } 17554 PermissionsState perms = ps.getPermissionsState(); 17555 BasePermission bp = mSettings.mPermissions.get(permName); 17556 if (bp != null) { 17557 if (isGranted) { 17558 perms.grantRuntimePermission(bp, userId); 17559 } 17560 if (newFlagSet != 0) { 17561 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17562 } 17563 } 17564 } else { 17565 // Need to wait for post-restore install to apply the grant 17566 if (DEBUG_BACKUP) { 17567 Slog.v(TAG, " - not yet installed; saving for later"); 17568 } 17569 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17570 isGranted, newFlagSet, userId); 17571 } 17572 } else { 17573 PackageManagerService.reportSettingsProblem(Log.WARN, 17574 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17575 XmlUtils.skipCurrentTag(parser); 17576 } 17577 } 17578 17579 scheduleWriteSettingsLocked(); 17580 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17581 } 17582 17583 @Override 17584 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17585 int sourceUserId, int targetUserId, int flags) { 17586 mContext.enforceCallingOrSelfPermission( 17587 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17588 int callingUid = Binder.getCallingUid(); 17589 enforceOwnerRights(ownerPackage, callingUid); 17590 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17591 if (intentFilter.countActions() == 0) { 17592 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17593 return; 17594 } 17595 synchronized (mPackages) { 17596 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17597 ownerPackage, targetUserId, flags); 17598 CrossProfileIntentResolver resolver = 17599 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17600 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17601 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17602 if (existing != null) { 17603 int size = existing.size(); 17604 for (int i = 0; i < size; i++) { 17605 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17606 return; 17607 } 17608 } 17609 } 17610 resolver.addFilter(newFilter); 17611 scheduleWritePackageRestrictionsLocked(sourceUserId); 17612 } 17613 } 17614 17615 @Override 17616 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17617 mContext.enforceCallingOrSelfPermission( 17618 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17619 int callingUid = Binder.getCallingUid(); 17620 enforceOwnerRights(ownerPackage, callingUid); 17621 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17622 synchronized (mPackages) { 17623 CrossProfileIntentResolver resolver = 17624 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17625 ArraySet<CrossProfileIntentFilter> set = 17626 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17627 for (CrossProfileIntentFilter filter : set) { 17628 if (filter.getOwnerPackage().equals(ownerPackage)) { 17629 resolver.removeFilter(filter); 17630 } 17631 } 17632 scheduleWritePackageRestrictionsLocked(sourceUserId); 17633 } 17634 } 17635 17636 // Enforcing that callingUid is owning pkg on userId 17637 private void enforceOwnerRights(String pkg, int callingUid) { 17638 // The system owns everything. 17639 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17640 return; 17641 } 17642 int callingUserId = UserHandle.getUserId(callingUid); 17643 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17644 if (pi == null) { 17645 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17646 + callingUserId); 17647 } 17648 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17649 throw new SecurityException("Calling uid " + callingUid 17650 + " does not own package " + pkg); 17651 } 17652 } 17653 17654 @Override 17655 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17656 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17657 } 17658 17659 private Intent getHomeIntent() { 17660 Intent intent = new Intent(Intent.ACTION_MAIN); 17661 intent.addCategory(Intent.CATEGORY_HOME); 17662 return intent; 17663 } 17664 17665 private IntentFilter getHomeFilter() { 17666 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17667 filter.addCategory(Intent.CATEGORY_HOME); 17668 filter.addCategory(Intent.CATEGORY_DEFAULT); 17669 return filter; 17670 } 17671 17672 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17673 int userId) { 17674 Intent intent = getHomeIntent(); 17675 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17676 PackageManager.GET_META_DATA, userId); 17677 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17678 true, false, false, userId); 17679 17680 allHomeCandidates.clear(); 17681 if (list != null) { 17682 for (ResolveInfo ri : list) { 17683 allHomeCandidates.add(ri); 17684 } 17685 } 17686 return (preferred == null || preferred.activityInfo == null) 17687 ? null 17688 : new ComponentName(preferred.activityInfo.packageName, 17689 preferred.activityInfo.name); 17690 } 17691 17692 @Override 17693 public void setHomeActivity(ComponentName comp, int userId) { 17694 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17695 getHomeActivitiesAsUser(homeActivities, userId); 17696 17697 boolean found = false; 17698 17699 final int size = homeActivities.size(); 17700 final ComponentName[] set = new ComponentName[size]; 17701 for (int i = 0; i < size; i++) { 17702 final ResolveInfo candidate = homeActivities.get(i); 17703 final ActivityInfo info = candidate.activityInfo; 17704 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17705 set[i] = activityName; 17706 if (!found && activityName.equals(comp)) { 17707 found = true; 17708 } 17709 } 17710 if (!found) { 17711 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17712 + userId); 17713 } 17714 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17715 set, comp, userId); 17716 } 17717 17718 private @Nullable String getSetupWizardPackageName() { 17719 final Intent intent = new Intent(Intent.ACTION_MAIN); 17720 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17721 17722 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17723 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17724 | MATCH_DISABLED_COMPONENTS, 17725 UserHandle.myUserId()); 17726 if (matches.size() == 1) { 17727 return matches.get(0).getComponentInfo().packageName; 17728 } else { 17729 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17730 + ": matches=" + matches); 17731 return null; 17732 } 17733 } 17734 17735 @Override 17736 public void setApplicationEnabledSetting(String appPackageName, 17737 int newState, int flags, int userId, String callingPackage) { 17738 if (!sUserManager.exists(userId)) return; 17739 if (callingPackage == null) { 17740 callingPackage = Integer.toString(Binder.getCallingUid()); 17741 } 17742 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17743 } 17744 17745 @Override 17746 public void setComponentEnabledSetting(ComponentName componentName, 17747 int newState, int flags, int userId) { 17748 if (!sUserManager.exists(userId)) return; 17749 setEnabledSetting(componentName.getPackageName(), 17750 componentName.getClassName(), newState, flags, userId, null); 17751 } 17752 17753 private void setEnabledSetting(final String packageName, String className, int newState, 17754 final int flags, int userId, String callingPackage) { 17755 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17756 || newState == COMPONENT_ENABLED_STATE_ENABLED 17757 || newState == COMPONENT_ENABLED_STATE_DISABLED 17758 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17759 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17760 throw new IllegalArgumentException("Invalid new component state: " 17761 + newState); 17762 } 17763 PackageSetting pkgSetting; 17764 final int uid = Binder.getCallingUid(); 17765 final int permission; 17766 if (uid == Process.SYSTEM_UID) { 17767 permission = PackageManager.PERMISSION_GRANTED; 17768 } else { 17769 permission = mContext.checkCallingOrSelfPermission( 17770 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17771 } 17772 enforceCrossUserPermission(uid, userId, 17773 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17774 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17775 boolean sendNow = false; 17776 boolean isApp = (className == null); 17777 String componentName = isApp ? packageName : className; 17778 int packageUid = -1; 17779 ArrayList<String> components; 17780 17781 // writer 17782 synchronized (mPackages) { 17783 pkgSetting = mSettings.mPackages.get(packageName); 17784 if (pkgSetting == null) { 17785 if (className == null) { 17786 throw new IllegalArgumentException("Unknown package: " + packageName); 17787 } 17788 throw new IllegalArgumentException( 17789 "Unknown component: " + packageName + "/" + className); 17790 } 17791 } 17792 17793 // Limit who can change which apps 17794 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17795 // Don't allow apps that don't have permission to modify other apps 17796 if (!allowedByPermission) { 17797 throw new SecurityException( 17798 "Permission Denial: attempt to change component state from pid=" 17799 + Binder.getCallingPid() 17800 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17801 } 17802 // Don't allow changing protected packages. 17803 if (mProtectedPackages.isPackageStateProtected(userId, packageName)) { 17804 throw new SecurityException("Cannot disable a protected package: " + packageName); 17805 } 17806 } 17807 17808 synchronized (mPackages) { 17809 if (uid == Process.SHELL_UID) { 17810 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17811 int oldState = pkgSetting.getEnabled(userId); 17812 if (className == null 17813 && 17814 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17815 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17816 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17817 && 17818 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17819 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17820 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17821 // ok 17822 } else { 17823 throw new SecurityException( 17824 "Shell cannot change component state for " + packageName + "/" 17825 + className + " to " + newState); 17826 } 17827 } 17828 if (className == null) { 17829 // We're dealing with an application/package level state change 17830 if (pkgSetting.getEnabled(userId) == newState) { 17831 // Nothing to do 17832 return; 17833 } 17834 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17835 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17836 // Don't care about who enables an app. 17837 callingPackage = null; 17838 } 17839 pkgSetting.setEnabled(newState, userId, callingPackage); 17840 // pkgSetting.pkg.mSetEnabled = newState; 17841 } else { 17842 // We're dealing with a component level state change 17843 // First, verify that this is a valid class name. 17844 PackageParser.Package pkg = pkgSetting.pkg; 17845 if (pkg == null || !pkg.hasComponentClassName(className)) { 17846 if (pkg != null && 17847 pkg.applicationInfo.targetSdkVersion >= 17848 Build.VERSION_CODES.JELLY_BEAN) { 17849 throw new IllegalArgumentException("Component class " + className 17850 + " does not exist in " + packageName); 17851 } else { 17852 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17853 + className + " does not exist in " + packageName); 17854 } 17855 } 17856 switch (newState) { 17857 case COMPONENT_ENABLED_STATE_ENABLED: 17858 if (!pkgSetting.enableComponentLPw(className, userId)) { 17859 return; 17860 } 17861 break; 17862 case COMPONENT_ENABLED_STATE_DISABLED: 17863 if (!pkgSetting.disableComponentLPw(className, userId)) { 17864 return; 17865 } 17866 break; 17867 case COMPONENT_ENABLED_STATE_DEFAULT: 17868 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17869 return; 17870 } 17871 break; 17872 default: 17873 Slog.e(TAG, "Invalid new component state: " + newState); 17874 return; 17875 } 17876 } 17877 scheduleWritePackageRestrictionsLocked(userId); 17878 components = mPendingBroadcasts.get(userId, packageName); 17879 final boolean newPackage = components == null; 17880 if (newPackage) { 17881 components = new ArrayList<String>(); 17882 } 17883 if (!components.contains(componentName)) { 17884 components.add(componentName); 17885 } 17886 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17887 sendNow = true; 17888 // Purge entry from pending broadcast list if another one exists already 17889 // since we are sending one right away. 17890 mPendingBroadcasts.remove(userId, packageName); 17891 } else { 17892 if (newPackage) { 17893 mPendingBroadcasts.put(userId, packageName, components); 17894 } 17895 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17896 // Schedule a message 17897 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17898 } 17899 } 17900 } 17901 17902 long callingId = Binder.clearCallingIdentity(); 17903 try { 17904 if (sendNow) { 17905 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17906 sendPackageChangedBroadcast(packageName, 17907 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17908 } 17909 } finally { 17910 Binder.restoreCallingIdentity(callingId); 17911 } 17912 } 17913 17914 @Override 17915 public void flushPackageRestrictionsAsUser(int userId) { 17916 if (!sUserManager.exists(userId)) { 17917 return; 17918 } 17919 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17920 false /* checkShell */, "flushPackageRestrictions"); 17921 synchronized (mPackages) { 17922 mSettings.writePackageRestrictionsLPr(userId); 17923 mDirtyUsers.remove(userId); 17924 if (mDirtyUsers.isEmpty()) { 17925 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17926 } 17927 } 17928 } 17929 17930 private void sendPackageChangedBroadcast(String packageName, 17931 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17932 if (DEBUG_INSTALL) 17933 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17934 + componentNames); 17935 Bundle extras = new Bundle(4); 17936 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17937 String nameList[] = new String[componentNames.size()]; 17938 componentNames.toArray(nameList); 17939 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17940 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17941 extras.putInt(Intent.EXTRA_UID, packageUid); 17942 // If this is not reporting a change of the overall package, then only send it 17943 // to registered receivers. We don't want to launch a swath of apps for every 17944 // little component state change. 17945 final int flags = !componentNames.contains(packageName) 17946 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17947 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17948 new int[] {UserHandle.getUserId(packageUid)}); 17949 } 17950 17951 @Override 17952 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17953 if (!sUserManager.exists(userId)) return; 17954 final int uid = Binder.getCallingUid(); 17955 final int permission = mContext.checkCallingOrSelfPermission( 17956 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17957 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17958 enforceCrossUserPermission(uid, userId, 17959 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17960 // writer 17961 synchronized (mPackages) { 17962 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17963 allowedByPermission, uid, userId)) { 17964 scheduleWritePackageRestrictionsLocked(userId); 17965 } 17966 } 17967 } 17968 17969 @Override 17970 public String getInstallerPackageName(String packageName) { 17971 // reader 17972 synchronized (mPackages) { 17973 return mSettings.getInstallerPackageNameLPr(packageName); 17974 } 17975 } 17976 17977 public boolean isOrphaned(String packageName) { 17978 // reader 17979 synchronized (mPackages) { 17980 return mSettings.isOrphaned(packageName); 17981 } 17982 } 17983 17984 @Override 17985 public int getApplicationEnabledSetting(String packageName, int userId) { 17986 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17987 int uid = Binder.getCallingUid(); 17988 enforceCrossUserPermission(uid, userId, 17989 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17990 // reader 17991 synchronized (mPackages) { 17992 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17993 } 17994 } 17995 17996 @Override 17997 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17998 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17999 int uid = Binder.getCallingUid(); 18000 enforceCrossUserPermission(uid, userId, 18001 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 18002 // reader 18003 synchronized (mPackages) { 18004 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 18005 } 18006 } 18007 18008 @Override 18009 public void enterSafeMode() { 18010 enforceSystemOrRoot("Only the system can request entering safe mode"); 18011 18012 if (!mSystemReady) { 18013 mSafeMode = true; 18014 } 18015 } 18016 18017 @Override 18018 public void systemReady() { 18019 mSystemReady = true; 18020 18021 // Read the compatibilty setting when the system is ready. 18022 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 18023 mContext.getContentResolver(), 18024 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 18025 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 18026 if (DEBUG_SETTINGS) { 18027 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 18028 } 18029 18030 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 18031 18032 synchronized (mPackages) { 18033 // Verify that all of the preferred activity components actually 18034 // exist. It is possible for applications to be updated and at 18035 // that point remove a previously declared activity component that 18036 // had been set as a preferred activity. We try to clean this up 18037 // the next time we encounter that preferred activity, but it is 18038 // possible for the user flow to never be able to return to that 18039 // situation so here we do a sanity check to make sure we haven't 18040 // left any junk around. 18041 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18042 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18043 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18044 removed.clear(); 18045 for (PreferredActivity pa : pir.filterSet()) { 18046 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18047 removed.add(pa); 18048 } 18049 } 18050 if (removed.size() > 0) { 18051 for (int r=0; r<removed.size(); r++) { 18052 PreferredActivity pa = removed.get(r); 18053 Slog.w(TAG, "Removing dangling preferred activity: " 18054 + pa.mPref.mComponent); 18055 pir.removeFilter(pa); 18056 } 18057 mSettings.writePackageRestrictionsLPr( 18058 mSettings.mPreferredActivities.keyAt(i)); 18059 } 18060 } 18061 18062 for (int userId : UserManagerService.getInstance().getUserIds()) { 18063 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18064 grantPermissionsUserIds = ArrayUtils.appendInt( 18065 grantPermissionsUserIds, userId); 18066 } 18067 } 18068 } 18069 sUserManager.systemReady(); 18070 18071 // If we upgraded grant all default permissions before kicking off. 18072 for (int userId : grantPermissionsUserIds) { 18073 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18074 } 18075 18076 // Kick off any messages waiting for system ready 18077 if (mPostSystemReadyMessages != null) { 18078 for (Message msg : mPostSystemReadyMessages) { 18079 msg.sendToTarget(); 18080 } 18081 mPostSystemReadyMessages = null; 18082 } 18083 18084 // Watch for external volumes that come and go over time 18085 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18086 storage.registerListener(mStorageListener); 18087 18088 mInstallerService.systemReady(); 18089 mPackageDexOptimizer.systemReady(); 18090 18091 MountServiceInternal mountServiceInternal = LocalServices.getService( 18092 MountServiceInternal.class); 18093 mountServiceInternal.addExternalStoragePolicy( 18094 new MountServiceInternal.ExternalStorageMountPolicy() { 18095 @Override 18096 public int getMountMode(int uid, String packageName) { 18097 if (Process.isIsolated(uid)) { 18098 return Zygote.MOUNT_EXTERNAL_NONE; 18099 } 18100 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18101 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18102 } 18103 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18104 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18105 } 18106 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18107 return Zygote.MOUNT_EXTERNAL_READ; 18108 } 18109 return Zygote.MOUNT_EXTERNAL_WRITE; 18110 } 18111 18112 @Override 18113 public boolean hasExternalStorage(int uid, String packageName) { 18114 return true; 18115 } 18116 }); 18117 18118 // Now that we're mostly running, clean up stale users and apps 18119 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18120 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18121 } 18122 18123 @Override 18124 public boolean isSafeMode() { 18125 return mSafeMode; 18126 } 18127 18128 @Override 18129 public boolean hasSystemUidErrors() { 18130 return mHasSystemUidErrors; 18131 } 18132 18133 static String arrayToString(int[] array) { 18134 StringBuffer buf = new StringBuffer(128); 18135 buf.append('['); 18136 if (array != null) { 18137 for (int i=0; i<array.length; i++) { 18138 if (i > 0) buf.append(", "); 18139 buf.append(array[i]); 18140 } 18141 } 18142 buf.append(']'); 18143 return buf.toString(); 18144 } 18145 18146 static class DumpState { 18147 public static final int DUMP_LIBS = 1 << 0; 18148 public static final int DUMP_FEATURES = 1 << 1; 18149 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18150 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18151 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18152 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18153 public static final int DUMP_PERMISSIONS = 1 << 6; 18154 public static final int DUMP_PACKAGES = 1 << 7; 18155 public static final int DUMP_SHARED_USERS = 1 << 8; 18156 public static final int DUMP_MESSAGES = 1 << 9; 18157 public static final int DUMP_PROVIDERS = 1 << 10; 18158 public static final int DUMP_VERIFIERS = 1 << 11; 18159 public static final int DUMP_PREFERRED = 1 << 12; 18160 public static final int DUMP_PREFERRED_XML = 1 << 13; 18161 public static final int DUMP_KEYSETS = 1 << 14; 18162 public static final int DUMP_VERSION = 1 << 15; 18163 public static final int DUMP_INSTALLS = 1 << 16; 18164 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18165 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18166 public static final int DUMP_FROZEN = 1 << 19; 18167 public static final int DUMP_DEXOPT = 1 << 20; 18168 18169 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18170 18171 private int mTypes; 18172 18173 private int mOptions; 18174 18175 private boolean mTitlePrinted; 18176 18177 private SharedUserSetting mSharedUser; 18178 18179 public boolean isDumping(int type) { 18180 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18181 return true; 18182 } 18183 18184 return (mTypes & type) != 0; 18185 } 18186 18187 public void setDump(int type) { 18188 mTypes |= type; 18189 } 18190 18191 public boolean isOptionEnabled(int option) { 18192 return (mOptions & option) != 0; 18193 } 18194 18195 public void setOptionEnabled(int option) { 18196 mOptions |= option; 18197 } 18198 18199 public boolean onTitlePrinted() { 18200 final boolean printed = mTitlePrinted; 18201 mTitlePrinted = true; 18202 return printed; 18203 } 18204 18205 public boolean getTitlePrinted() { 18206 return mTitlePrinted; 18207 } 18208 18209 public void setTitlePrinted(boolean enabled) { 18210 mTitlePrinted = enabled; 18211 } 18212 18213 public SharedUserSetting getSharedUser() { 18214 return mSharedUser; 18215 } 18216 18217 public void setSharedUser(SharedUserSetting user) { 18218 mSharedUser = user; 18219 } 18220 } 18221 18222 @Override 18223 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18224 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18225 (new PackageManagerShellCommand(this)).exec( 18226 this, in, out, err, args, resultReceiver); 18227 } 18228 18229 @Override 18230 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18231 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18232 != PackageManager.PERMISSION_GRANTED) { 18233 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18234 + Binder.getCallingPid() 18235 + ", uid=" + Binder.getCallingUid() 18236 + " without permission " 18237 + android.Manifest.permission.DUMP); 18238 return; 18239 } 18240 18241 DumpState dumpState = new DumpState(); 18242 boolean fullPreferred = false; 18243 boolean checkin = false; 18244 18245 String packageName = null; 18246 ArraySet<String> permissionNames = null; 18247 18248 int opti = 0; 18249 while (opti < args.length) { 18250 String opt = args[opti]; 18251 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18252 break; 18253 } 18254 opti++; 18255 18256 if ("-a".equals(opt)) { 18257 // Right now we only know how to print all. 18258 } else if ("-h".equals(opt)) { 18259 pw.println("Package manager dump options:"); 18260 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18261 pw.println(" --checkin: dump for a checkin"); 18262 pw.println(" -f: print details of intent filters"); 18263 pw.println(" -h: print this help"); 18264 pw.println(" cmd may be one of:"); 18265 pw.println(" l[ibraries]: list known shared libraries"); 18266 pw.println(" f[eatures]: list device features"); 18267 pw.println(" k[eysets]: print known keysets"); 18268 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18269 pw.println(" perm[issions]: dump permissions"); 18270 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18271 pw.println(" pref[erred]: print preferred package settings"); 18272 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18273 pw.println(" prov[iders]: dump content providers"); 18274 pw.println(" p[ackages]: dump installed packages"); 18275 pw.println(" s[hared-users]: dump shared user IDs"); 18276 pw.println(" m[essages]: print collected runtime messages"); 18277 pw.println(" v[erifiers]: print package verifier info"); 18278 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18279 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18280 pw.println(" version: print database version info"); 18281 pw.println(" write: write current settings now"); 18282 pw.println(" installs: details about install sessions"); 18283 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18284 pw.println(" dexopt: dump dexopt state"); 18285 pw.println(" <package.name>: info about given package"); 18286 return; 18287 } else if ("--checkin".equals(opt)) { 18288 checkin = true; 18289 } else if ("-f".equals(opt)) { 18290 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18291 } else { 18292 pw.println("Unknown argument: " + opt + "; use -h for help"); 18293 } 18294 } 18295 18296 // Is the caller requesting to dump a particular piece of data? 18297 if (opti < args.length) { 18298 String cmd = args[opti]; 18299 opti++; 18300 // Is this a package name? 18301 if ("android".equals(cmd) || cmd.contains(".")) { 18302 packageName = cmd; 18303 // When dumping a single package, we always dump all of its 18304 // filter information since the amount of data will be reasonable. 18305 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18306 } else if ("check-permission".equals(cmd)) { 18307 if (opti >= args.length) { 18308 pw.println("Error: check-permission missing permission argument"); 18309 return; 18310 } 18311 String perm = args[opti]; 18312 opti++; 18313 if (opti >= args.length) { 18314 pw.println("Error: check-permission missing package argument"); 18315 return; 18316 } 18317 String pkg = args[opti]; 18318 opti++; 18319 int user = UserHandle.getUserId(Binder.getCallingUid()); 18320 if (opti < args.length) { 18321 try { 18322 user = Integer.parseInt(args[opti]); 18323 } catch (NumberFormatException e) { 18324 pw.println("Error: check-permission user argument is not a number: " 18325 + args[opti]); 18326 return; 18327 } 18328 } 18329 pw.println(checkPermission(perm, pkg, user)); 18330 return; 18331 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18332 dumpState.setDump(DumpState.DUMP_LIBS); 18333 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18334 dumpState.setDump(DumpState.DUMP_FEATURES); 18335 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18336 if (opti >= args.length) { 18337 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18338 | DumpState.DUMP_SERVICE_RESOLVERS 18339 | DumpState.DUMP_RECEIVER_RESOLVERS 18340 | DumpState.DUMP_CONTENT_RESOLVERS); 18341 } else { 18342 while (opti < args.length) { 18343 String name = args[opti]; 18344 if ("a".equals(name) || "activity".equals(name)) { 18345 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18346 } else if ("s".equals(name) || "service".equals(name)) { 18347 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18348 } else if ("r".equals(name) || "receiver".equals(name)) { 18349 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18350 } else if ("c".equals(name) || "content".equals(name)) { 18351 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18352 } else { 18353 pw.println("Error: unknown resolver table type: " + name); 18354 return; 18355 } 18356 opti++; 18357 } 18358 } 18359 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18360 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18361 } else if ("permission".equals(cmd)) { 18362 if (opti >= args.length) { 18363 pw.println("Error: permission requires permission name"); 18364 return; 18365 } 18366 permissionNames = new ArraySet<>(); 18367 while (opti < args.length) { 18368 permissionNames.add(args[opti]); 18369 opti++; 18370 } 18371 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18372 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18373 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18374 dumpState.setDump(DumpState.DUMP_PREFERRED); 18375 } else if ("preferred-xml".equals(cmd)) { 18376 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18377 if (opti < args.length && "--full".equals(args[opti])) { 18378 fullPreferred = true; 18379 opti++; 18380 } 18381 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18382 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18383 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18384 dumpState.setDump(DumpState.DUMP_PACKAGES); 18385 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18386 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18387 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18388 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18389 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18390 dumpState.setDump(DumpState.DUMP_MESSAGES); 18391 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18392 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18393 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18394 || "intent-filter-verifiers".equals(cmd)) { 18395 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18396 } else if ("version".equals(cmd)) { 18397 dumpState.setDump(DumpState.DUMP_VERSION); 18398 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18399 dumpState.setDump(DumpState.DUMP_KEYSETS); 18400 } else if ("installs".equals(cmd)) { 18401 dumpState.setDump(DumpState.DUMP_INSTALLS); 18402 } else if ("frozen".equals(cmd)) { 18403 dumpState.setDump(DumpState.DUMP_FROZEN); 18404 } else if ("dexopt".equals(cmd)) { 18405 dumpState.setDump(DumpState.DUMP_DEXOPT); 18406 } else if ("write".equals(cmd)) { 18407 synchronized (mPackages) { 18408 mSettings.writeLPr(); 18409 pw.println("Settings written."); 18410 return; 18411 } 18412 } 18413 } 18414 18415 if (checkin) { 18416 pw.println("vers,1"); 18417 } 18418 18419 // reader 18420 synchronized (mPackages) { 18421 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18422 if (!checkin) { 18423 if (dumpState.onTitlePrinted()) 18424 pw.println(); 18425 pw.println("Database versions:"); 18426 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18427 } 18428 } 18429 18430 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18431 if (!checkin) { 18432 if (dumpState.onTitlePrinted()) 18433 pw.println(); 18434 pw.println("Verifiers:"); 18435 pw.print(" Required: "); 18436 pw.print(mRequiredVerifierPackage); 18437 pw.print(" (uid="); 18438 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18439 UserHandle.USER_SYSTEM)); 18440 pw.println(")"); 18441 } else if (mRequiredVerifierPackage != null) { 18442 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18443 pw.print(","); 18444 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18445 UserHandle.USER_SYSTEM)); 18446 } 18447 } 18448 18449 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18450 packageName == null) { 18451 if (mIntentFilterVerifierComponent != null) { 18452 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18453 if (!checkin) { 18454 if (dumpState.onTitlePrinted()) 18455 pw.println(); 18456 pw.println("Intent Filter Verifier:"); 18457 pw.print(" Using: "); 18458 pw.print(verifierPackageName); 18459 pw.print(" (uid="); 18460 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18461 UserHandle.USER_SYSTEM)); 18462 pw.println(")"); 18463 } else if (verifierPackageName != null) { 18464 pw.print("ifv,"); pw.print(verifierPackageName); 18465 pw.print(","); 18466 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18467 UserHandle.USER_SYSTEM)); 18468 } 18469 } else { 18470 pw.println(); 18471 pw.println("No Intent Filter Verifier available!"); 18472 } 18473 } 18474 18475 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18476 boolean printedHeader = false; 18477 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18478 while (it.hasNext()) { 18479 String name = it.next(); 18480 SharedLibraryEntry ent = mSharedLibraries.get(name); 18481 if (!checkin) { 18482 if (!printedHeader) { 18483 if (dumpState.onTitlePrinted()) 18484 pw.println(); 18485 pw.println("Libraries:"); 18486 printedHeader = true; 18487 } 18488 pw.print(" "); 18489 } else { 18490 pw.print("lib,"); 18491 } 18492 pw.print(name); 18493 if (!checkin) { 18494 pw.print(" -> "); 18495 } 18496 if (ent.path != null) { 18497 if (!checkin) { 18498 pw.print("(jar) "); 18499 pw.print(ent.path); 18500 } else { 18501 pw.print(",jar,"); 18502 pw.print(ent.path); 18503 } 18504 } else { 18505 if (!checkin) { 18506 pw.print("(apk) "); 18507 pw.print(ent.apk); 18508 } else { 18509 pw.print(",apk,"); 18510 pw.print(ent.apk); 18511 } 18512 } 18513 pw.println(); 18514 } 18515 } 18516 18517 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18518 if (dumpState.onTitlePrinted()) 18519 pw.println(); 18520 if (!checkin) { 18521 pw.println("Features:"); 18522 } 18523 18524 for (FeatureInfo feat : mAvailableFeatures.values()) { 18525 if (checkin) { 18526 pw.print("feat,"); 18527 pw.print(feat.name); 18528 pw.print(","); 18529 pw.println(feat.version); 18530 } else { 18531 pw.print(" "); 18532 pw.print(feat.name); 18533 if (feat.version > 0) { 18534 pw.print(" version="); 18535 pw.print(feat.version); 18536 } 18537 pw.println(); 18538 } 18539 } 18540 } 18541 18542 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18543 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18544 : "Activity Resolver Table:", " ", packageName, 18545 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18546 dumpState.setTitlePrinted(true); 18547 } 18548 } 18549 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18550 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18551 : "Receiver Resolver Table:", " ", packageName, 18552 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18553 dumpState.setTitlePrinted(true); 18554 } 18555 } 18556 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18557 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18558 : "Service Resolver Table:", " ", packageName, 18559 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18560 dumpState.setTitlePrinted(true); 18561 } 18562 } 18563 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18564 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18565 : "Provider Resolver Table:", " ", packageName, 18566 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18567 dumpState.setTitlePrinted(true); 18568 } 18569 } 18570 18571 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18572 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18573 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18574 int user = mSettings.mPreferredActivities.keyAt(i); 18575 if (pir.dump(pw, 18576 dumpState.getTitlePrinted() 18577 ? "\nPreferred Activities User " + user + ":" 18578 : "Preferred Activities User " + user + ":", " ", 18579 packageName, true, false)) { 18580 dumpState.setTitlePrinted(true); 18581 } 18582 } 18583 } 18584 18585 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18586 pw.flush(); 18587 FileOutputStream fout = new FileOutputStream(fd); 18588 BufferedOutputStream str = new BufferedOutputStream(fout); 18589 XmlSerializer serializer = new FastXmlSerializer(); 18590 try { 18591 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18592 serializer.startDocument(null, true); 18593 serializer.setFeature( 18594 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18595 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18596 serializer.endDocument(); 18597 serializer.flush(); 18598 } catch (IllegalArgumentException e) { 18599 pw.println("Failed writing: " + e); 18600 } catch (IllegalStateException e) { 18601 pw.println("Failed writing: " + e); 18602 } catch (IOException e) { 18603 pw.println("Failed writing: " + e); 18604 } 18605 } 18606 18607 if (!checkin 18608 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18609 && packageName == null) { 18610 pw.println(); 18611 int count = mSettings.mPackages.size(); 18612 if (count == 0) { 18613 pw.println("No applications!"); 18614 pw.println(); 18615 } else { 18616 final String prefix = " "; 18617 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18618 if (allPackageSettings.size() == 0) { 18619 pw.println("No domain preferred apps!"); 18620 pw.println(); 18621 } else { 18622 pw.println("App verification status:"); 18623 pw.println(); 18624 count = 0; 18625 for (PackageSetting ps : allPackageSettings) { 18626 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18627 if (ivi == null || ivi.getPackageName() == null) continue; 18628 pw.println(prefix + "Package: " + ivi.getPackageName()); 18629 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18630 pw.println(prefix + "Status: " + ivi.getStatusString()); 18631 pw.println(); 18632 count++; 18633 } 18634 if (count == 0) { 18635 pw.println(prefix + "No app verification established."); 18636 pw.println(); 18637 } 18638 for (int userId : sUserManager.getUserIds()) { 18639 pw.println("App linkages for user " + userId + ":"); 18640 pw.println(); 18641 count = 0; 18642 for (PackageSetting ps : allPackageSettings) { 18643 final long status = ps.getDomainVerificationStatusForUser(userId); 18644 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18645 continue; 18646 } 18647 pw.println(prefix + "Package: " + ps.name); 18648 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18649 String statusStr = IntentFilterVerificationInfo. 18650 getStatusStringFromValue(status); 18651 pw.println(prefix + "Status: " + statusStr); 18652 pw.println(); 18653 count++; 18654 } 18655 if (count == 0) { 18656 pw.println(prefix + "No configured app linkages."); 18657 pw.println(); 18658 } 18659 } 18660 } 18661 } 18662 } 18663 18664 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18665 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18666 if (packageName == null && permissionNames == null) { 18667 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18668 if (iperm == 0) { 18669 if (dumpState.onTitlePrinted()) 18670 pw.println(); 18671 pw.println("AppOp Permissions:"); 18672 } 18673 pw.print(" AppOp Permission "); 18674 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18675 pw.println(":"); 18676 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18677 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18678 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18679 } 18680 } 18681 } 18682 } 18683 18684 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18685 boolean printedSomething = false; 18686 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18687 if (packageName != null && !packageName.equals(p.info.packageName)) { 18688 continue; 18689 } 18690 if (!printedSomething) { 18691 if (dumpState.onTitlePrinted()) 18692 pw.println(); 18693 pw.println("Registered ContentProviders:"); 18694 printedSomething = true; 18695 } 18696 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18697 pw.print(" "); pw.println(p.toString()); 18698 } 18699 printedSomething = false; 18700 for (Map.Entry<String, PackageParser.Provider> entry : 18701 mProvidersByAuthority.entrySet()) { 18702 PackageParser.Provider p = entry.getValue(); 18703 if (packageName != null && !packageName.equals(p.info.packageName)) { 18704 continue; 18705 } 18706 if (!printedSomething) { 18707 if (dumpState.onTitlePrinted()) 18708 pw.println(); 18709 pw.println("ContentProvider Authorities:"); 18710 printedSomething = true; 18711 } 18712 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18713 pw.print(" "); pw.println(p.toString()); 18714 if (p.info != null && p.info.applicationInfo != null) { 18715 final String appInfo = p.info.applicationInfo.toString(); 18716 pw.print(" applicationInfo="); pw.println(appInfo); 18717 } 18718 } 18719 } 18720 18721 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18722 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18723 } 18724 18725 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18726 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18727 } 18728 18729 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18730 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18731 } 18732 18733 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18734 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18735 } 18736 18737 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18738 // XXX should handle packageName != null by dumping only install data that 18739 // the given package is involved with. 18740 if (dumpState.onTitlePrinted()) pw.println(); 18741 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18742 } 18743 18744 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && 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 18749 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18750 ipw.println(); 18751 ipw.println("Frozen packages:"); 18752 ipw.increaseIndent(); 18753 if (mFrozenPackages.size() == 0) { 18754 ipw.println("(none)"); 18755 } else { 18756 for (int i = 0; i < mFrozenPackages.size(); i++) { 18757 ipw.println(mFrozenPackages.valueAt(i)); 18758 } 18759 } 18760 ipw.decreaseIndent(); 18761 } 18762 18763 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18764 if (dumpState.onTitlePrinted()) pw.println(); 18765 dumpDexoptStateLPr(pw, packageName); 18766 } 18767 18768 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18769 if (dumpState.onTitlePrinted()) pw.println(); 18770 mSettings.dumpReadMessagesLPr(pw, dumpState); 18771 18772 pw.println(); 18773 pw.println("Package warning messages:"); 18774 BufferedReader in = null; 18775 String line = null; 18776 try { 18777 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18778 while ((line = in.readLine()) != null) { 18779 if (line.contains("ignored: updated version")) continue; 18780 pw.println(line); 18781 } 18782 } catch (IOException ignored) { 18783 } finally { 18784 IoUtils.closeQuietly(in); 18785 } 18786 } 18787 18788 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18789 BufferedReader in = null; 18790 String line = null; 18791 try { 18792 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18793 while ((line = in.readLine()) != null) { 18794 if (line.contains("ignored: updated version")) continue; 18795 pw.print("msg,"); 18796 pw.println(line); 18797 } 18798 } catch (IOException ignored) { 18799 } finally { 18800 IoUtils.closeQuietly(in); 18801 } 18802 } 18803 } 18804 } 18805 18806 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18807 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18808 ipw.println(); 18809 ipw.println("Dexopt state:"); 18810 ipw.increaseIndent(); 18811 Collection<PackageParser.Package> packages = null; 18812 if (packageName != null) { 18813 PackageParser.Package targetPackage = mPackages.get(packageName); 18814 if (targetPackage != null) { 18815 packages = Collections.singletonList(targetPackage); 18816 } else { 18817 ipw.println("Unable to find package: " + packageName); 18818 return; 18819 } 18820 } else { 18821 packages = mPackages.values(); 18822 } 18823 18824 for (PackageParser.Package pkg : packages) { 18825 ipw.println("[" + pkg.packageName + "]"); 18826 ipw.increaseIndent(); 18827 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18828 ipw.decreaseIndent(); 18829 } 18830 } 18831 18832 private String dumpDomainString(String packageName) { 18833 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18834 .getList(); 18835 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18836 18837 ArraySet<String> result = new ArraySet<>(); 18838 if (iviList.size() > 0) { 18839 for (IntentFilterVerificationInfo ivi : iviList) { 18840 for (String host : ivi.getDomains()) { 18841 result.add(host); 18842 } 18843 } 18844 } 18845 if (filters != null && filters.size() > 0) { 18846 for (IntentFilter filter : filters) { 18847 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18848 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18849 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18850 result.addAll(filter.getHostsList()); 18851 } 18852 } 18853 } 18854 18855 StringBuilder sb = new StringBuilder(result.size() * 16); 18856 for (String domain : result) { 18857 if (sb.length() > 0) sb.append(" "); 18858 sb.append(domain); 18859 } 18860 return sb.toString(); 18861 } 18862 18863 // ------- apps on sdcard specific code ------- 18864 static final boolean DEBUG_SD_INSTALL = false; 18865 18866 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18867 18868 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18869 18870 private boolean mMediaMounted = false; 18871 18872 static String getEncryptKey() { 18873 try { 18874 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18875 SD_ENCRYPTION_KEYSTORE_NAME); 18876 if (sdEncKey == null) { 18877 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18878 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18879 if (sdEncKey == null) { 18880 Slog.e(TAG, "Failed to create encryption keys"); 18881 return null; 18882 } 18883 } 18884 return sdEncKey; 18885 } catch (NoSuchAlgorithmException nsae) { 18886 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18887 return null; 18888 } catch (IOException ioe) { 18889 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18890 return null; 18891 } 18892 } 18893 18894 /* 18895 * Update media status on PackageManager. 18896 */ 18897 @Override 18898 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18899 int callingUid = Binder.getCallingUid(); 18900 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18901 throw new SecurityException("Media status can only be updated by the system"); 18902 } 18903 // reader; this apparently protects mMediaMounted, but should probably 18904 // be a different lock in that case. 18905 synchronized (mPackages) { 18906 Log.i(TAG, "Updating external media status from " 18907 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18908 + (mediaStatus ? "mounted" : "unmounted")); 18909 if (DEBUG_SD_INSTALL) 18910 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18911 + ", mMediaMounted=" + mMediaMounted); 18912 if (mediaStatus == mMediaMounted) { 18913 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18914 : 0, -1); 18915 mHandler.sendMessage(msg); 18916 return; 18917 } 18918 mMediaMounted = mediaStatus; 18919 } 18920 // Queue up an async operation since the package installation may take a 18921 // little while. 18922 mHandler.post(new Runnable() { 18923 public void run() { 18924 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18925 } 18926 }); 18927 } 18928 18929 /** 18930 * Called by MountService when the initial ASECs to scan are available. 18931 * Should block until all the ASEC containers are finished being scanned. 18932 */ 18933 public void scanAvailableAsecs() { 18934 updateExternalMediaStatusInner(true, false, false); 18935 } 18936 18937 /* 18938 * Collect information of applications on external media, map them against 18939 * existing containers and update information based on current mount status. 18940 * Please note that we always have to report status if reportStatus has been 18941 * set to true especially when unloading packages. 18942 */ 18943 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18944 boolean externalStorage) { 18945 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18946 int[] uidArr = EmptyArray.INT; 18947 18948 final String[] list = PackageHelper.getSecureContainerList(); 18949 if (ArrayUtils.isEmpty(list)) { 18950 Log.i(TAG, "No secure containers found"); 18951 } else { 18952 // Process list of secure containers and categorize them 18953 // as active or stale based on their package internal state. 18954 18955 // reader 18956 synchronized (mPackages) { 18957 for (String cid : list) { 18958 // Leave stages untouched for now; installer service owns them 18959 if (PackageInstallerService.isStageName(cid)) continue; 18960 18961 if (DEBUG_SD_INSTALL) 18962 Log.i(TAG, "Processing container " + cid); 18963 String pkgName = getAsecPackageName(cid); 18964 if (pkgName == null) { 18965 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18966 continue; 18967 } 18968 if (DEBUG_SD_INSTALL) 18969 Log.i(TAG, "Looking for pkg : " + pkgName); 18970 18971 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18972 if (ps == null) { 18973 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18974 continue; 18975 } 18976 18977 /* 18978 * Skip packages that are not external if we're unmounting 18979 * external storage. 18980 */ 18981 if (externalStorage && !isMounted && !isExternal(ps)) { 18982 continue; 18983 } 18984 18985 final AsecInstallArgs args = new AsecInstallArgs(cid, 18986 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18987 // The package status is changed only if the code path 18988 // matches between settings and the container id. 18989 if (ps.codePathString != null 18990 && ps.codePathString.startsWith(args.getCodePath())) { 18991 if (DEBUG_SD_INSTALL) { 18992 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18993 + " at code path: " + ps.codePathString); 18994 } 18995 18996 // We do have a valid package installed on sdcard 18997 processCids.put(args, ps.codePathString); 18998 final int uid = ps.appId; 18999 if (uid != -1) { 19000 uidArr = ArrayUtils.appendInt(uidArr, uid); 19001 } 19002 } else { 19003 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 19004 + ps.codePathString); 19005 } 19006 } 19007 } 19008 19009 Arrays.sort(uidArr); 19010 } 19011 19012 // Process packages with valid entries. 19013 if (isMounted) { 19014 if (DEBUG_SD_INSTALL) 19015 Log.i(TAG, "Loading packages"); 19016 loadMediaPackages(processCids, uidArr, externalStorage); 19017 startCleaningPackages(); 19018 mInstallerService.onSecureContainersAvailable(); 19019 } else { 19020 if (DEBUG_SD_INSTALL) 19021 Log.i(TAG, "Unloading packages"); 19022 unloadMediaPackages(processCids, uidArr, reportStatus); 19023 } 19024 } 19025 19026 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19027 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 19028 final int size = infos.size(); 19029 final String[] packageNames = new String[size]; 19030 final int[] packageUids = new int[size]; 19031 for (int i = 0; i < size; i++) { 19032 final ApplicationInfo info = infos.get(i); 19033 packageNames[i] = info.packageName; 19034 packageUids[i] = info.uid; 19035 } 19036 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19037 finishedReceiver); 19038 } 19039 19040 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19041 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19042 sendResourcesChangedBroadcast(mediaStatus, replacing, 19043 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19044 } 19045 19046 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19047 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19048 int size = pkgList.length; 19049 if (size > 0) { 19050 // Send broadcasts here 19051 Bundle extras = new Bundle(); 19052 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19053 if (uidArr != null) { 19054 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19055 } 19056 if (replacing) { 19057 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19058 } 19059 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19060 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19061 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19062 } 19063 } 19064 19065 /* 19066 * Look at potentially valid container ids from processCids If package 19067 * information doesn't match the one on record or package scanning fails, 19068 * the cid is added to list of removeCids. We currently don't delete stale 19069 * containers. 19070 */ 19071 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19072 boolean externalStorage) { 19073 ArrayList<String> pkgList = new ArrayList<String>(); 19074 Set<AsecInstallArgs> keys = processCids.keySet(); 19075 19076 for (AsecInstallArgs args : keys) { 19077 String codePath = processCids.get(args); 19078 if (DEBUG_SD_INSTALL) 19079 Log.i(TAG, "Loading container : " + args.cid); 19080 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19081 try { 19082 // Make sure there are no container errors first. 19083 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19084 Slog.e(TAG, "Failed to mount cid : " + args.cid 19085 + " when installing from sdcard"); 19086 continue; 19087 } 19088 // Check code path here. 19089 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19090 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19091 + " does not match one in settings " + codePath); 19092 continue; 19093 } 19094 // Parse package 19095 int parseFlags = mDefParseFlags; 19096 if (args.isExternalAsec()) { 19097 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19098 } 19099 if (args.isFwdLocked()) { 19100 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19101 } 19102 19103 synchronized (mInstallLock) { 19104 PackageParser.Package pkg = null; 19105 try { 19106 // Sadly we don't know the package name yet to freeze it 19107 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19108 SCAN_IGNORE_FROZEN, 0, null); 19109 } catch (PackageManagerException e) { 19110 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19111 } 19112 // Scan the package 19113 if (pkg != null) { 19114 /* 19115 * TODO why is the lock being held? doPostInstall is 19116 * called in other places without the lock. This needs 19117 * to be straightened out. 19118 */ 19119 // writer 19120 synchronized (mPackages) { 19121 retCode = PackageManager.INSTALL_SUCCEEDED; 19122 pkgList.add(pkg.packageName); 19123 // Post process args 19124 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19125 pkg.applicationInfo.uid); 19126 } 19127 } else { 19128 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19129 } 19130 } 19131 19132 } finally { 19133 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19134 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19135 } 19136 } 19137 } 19138 // writer 19139 synchronized (mPackages) { 19140 // If the platform SDK has changed since the last time we booted, 19141 // we need to re-grant app permission to catch any new ones that 19142 // appear. This is really a hack, and means that apps can in some 19143 // cases get permissions that the user didn't initially explicitly 19144 // allow... it would be nice to have some better way to handle 19145 // this situation. 19146 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19147 : mSettings.getInternalVersion(); 19148 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19149 : StorageManager.UUID_PRIVATE_INTERNAL; 19150 19151 int updateFlags = UPDATE_PERMISSIONS_ALL; 19152 if (ver.sdkVersion != mSdkVersion) { 19153 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19154 + mSdkVersion + "; regranting permissions for external"); 19155 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19156 } 19157 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19158 19159 // Yay, everything is now upgraded 19160 ver.forceCurrent(); 19161 19162 // can downgrade to reader 19163 // Persist settings 19164 mSettings.writeLPr(); 19165 } 19166 // Send a broadcast to let everyone know we are done processing 19167 if (pkgList.size() > 0) { 19168 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19169 } 19170 } 19171 19172 /* 19173 * Utility method to unload a list of specified containers 19174 */ 19175 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19176 // Just unmount all valid containers. 19177 for (AsecInstallArgs arg : cidArgs) { 19178 synchronized (mInstallLock) { 19179 arg.doPostDeleteLI(false); 19180 } 19181 } 19182 } 19183 19184 /* 19185 * Unload packages mounted on external media. This involves deleting package 19186 * data from internal structures, sending broadcasts about disabled packages, 19187 * gc'ing to free up references, unmounting all secure containers 19188 * corresponding to packages on external media, and posting a 19189 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19190 * that we always have to post this message if status has been requested no 19191 * matter what. 19192 */ 19193 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19194 final boolean reportStatus) { 19195 if (DEBUG_SD_INSTALL) 19196 Log.i(TAG, "unloading media packages"); 19197 ArrayList<String> pkgList = new ArrayList<String>(); 19198 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19199 final Set<AsecInstallArgs> keys = processCids.keySet(); 19200 for (AsecInstallArgs args : keys) { 19201 String pkgName = args.getPackageName(); 19202 if (DEBUG_SD_INSTALL) 19203 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19204 // Delete package internally 19205 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19206 synchronized (mInstallLock) { 19207 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19208 final boolean res; 19209 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19210 "unloadMediaPackages")) { 19211 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19212 null); 19213 } 19214 if (res) { 19215 pkgList.add(pkgName); 19216 } else { 19217 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19218 failedList.add(args); 19219 } 19220 } 19221 } 19222 19223 // reader 19224 synchronized (mPackages) { 19225 // We didn't update the settings after removing each package; 19226 // write them now for all packages. 19227 mSettings.writeLPr(); 19228 } 19229 19230 // We have to absolutely send UPDATED_MEDIA_STATUS only 19231 // after confirming that all the receivers processed the ordered 19232 // broadcast when packages get disabled, force a gc to clean things up. 19233 // and unload all the containers. 19234 if (pkgList.size() > 0) { 19235 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19236 new IIntentReceiver.Stub() { 19237 public void performReceive(Intent intent, int resultCode, String data, 19238 Bundle extras, boolean ordered, boolean sticky, 19239 int sendingUser) throws RemoteException { 19240 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19241 reportStatus ? 1 : 0, 1, keys); 19242 mHandler.sendMessage(msg); 19243 } 19244 }); 19245 } else { 19246 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19247 keys); 19248 mHandler.sendMessage(msg); 19249 } 19250 } 19251 19252 private void loadPrivatePackages(final VolumeInfo vol) { 19253 mHandler.post(new Runnable() { 19254 @Override 19255 public void run() { 19256 loadPrivatePackagesInner(vol); 19257 } 19258 }); 19259 } 19260 19261 private void loadPrivatePackagesInner(VolumeInfo vol) { 19262 final String volumeUuid = vol.fsUuid; 19263 if (TextUtils.isEmpty(volumeUuid)) { 19264 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19265 return; 19266 } 19267 19268 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19269 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19270 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19271 19272 final VersionInfo ver; 19273 final List<PackageSetting> packages; 19274 synchronized (mPackages) { 19275 ver = mSettings.findOrCreateVersion(volumeUuid); 19276 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19277 } 19278 19279 for (PackageSetting ps : packages) { 19280 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19281 synchronized (mInstallLock) { 19282 final PackageParser.Package pkg; 19283 try { 19284 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19285 loaded.add(pkg.applicationInfo); 19286 19287 } catch (PackageManagerException e) { 19288 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19289 } 19290 19291 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19292 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19293 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19294 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19295 } 19296 } 19297 } 19298 19299 // Reconcile app data for all started/unlocked users 19300 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19301 final UserManager um = mContext.getSystemService(UserManager.class); 19302 UserManagerInternal umInternal = getUserManagerInternal(); 19303 for (UserInfo user : um.getUsers()) { 19304 final int flags; 19305 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19306 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19307 } else if (umInternal.isUserRunning(user.id)) { 19308 flags = StorageManager.FLAG_STORAGE_DE; 19309 } else { 19310 continue; 19311 } 19312 19313 try { 19314 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19315 synchronized (mInstallLock) { 19316 reconcileAppsDataLI(volumeUuid, user.id, flags); 19317 } 19318 } catch (IllegalStateException e) { 19319 // Device was probably ejected, and we'll process that event momentarily 19320 Slog.w(TAG, "Failed to prepare storage: " + e); 19321 } 19322 } 19323 19324 synchronized (mPackages) { 19325 int updateFlags = UPDATE_PERMISSIONS_ALL; 19326 if (ver.sdkVersion != mSdkVersion) { 19327 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19328 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19329 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19330 } 19331 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19332 19333 // Yay, everything is now upgraded 19334 ver.forceCurrent(); 19335 19336 mSettings.writeLPr(); 19337 } 19338 19339 for (PackageFreezer freezer : freezers) { 19340 freezer.close(); 19341 } 19342 19343 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19344 sendResourcesChangedBroadcast(true, false, loaded, null); 19345 } 19346 19347 private void unloadPrivatePackages(final VolumeInfo vol) { 19348 mHandler.post(new Runnable() { 19349 @Override 19350 public void run() { 19351 unloadPrivatePackagesInner(vol); 19352 } 19353 }); 19354 } 19355 19356 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19357 final String volumeUuid = vol.fsUuid; 19358 if (TextUtils.isEmpty(volumeUuid)) { 19359 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19360 return; 19361 } 19362 19363 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19364 synchronized (mInstallLock) { 19365 synchronized (mPackages) { 19366 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19367 for (PackageSetting ps : packages) { 19368 if (ps.pkg == null) continue; 19369 19370 final ApplicationInfo info = ps.pkg.applicationInfo; 19371 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19372 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19373 19374 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19375 "unloadPrivatePackagesInner")) { 19376 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19377 false, null)) { 19378 unloaded.add(info); 19379 } else { 19380 Slog.w(TAG, "Failed to unload " + ps.codePath); 19381 } 19382 } 19383 19384 // Try very hard to release any references to this package 19385 // so we don't risk the system server being killed due to 19386 // open FDs 19387 AttributeCache.instance().removePackage(ps.name); 19388 } 19389 19390 mSettings.writeLPr(); 19391 } 19392 } 19393 19394 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19395 sendResourcesChangedBroadcast(false, false, unloaded, null); 19396 19397 // Try very hard to release any references to this path so we don't risk 19398 // the system server being killed due to open FDs 19399 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19400 19401 for (int i = 0; i < 3; i++) { 19402 System.gc(); 19403 System.runFinalization(); 19404 } 19405 } 19406 19407 /** 19408 * Prepare storage areas for given user on all mounted devices. 19409 */ 19410 void prepareUserData(int userId, int userSerial, int flags) { 19411 synchronized (mInstallLock) { 19412 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19413 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19414 final String volumeUuid = vol.getFsUuid(); 19415 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19416 } 19417 } 19418 } 19419 19420 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19421 boolean allowRecover) { 19422 // Prepare storage and verify that serial numbers are consistent; if 19423 // there's a mismatch we need to destroy to avoid leaking data 19424 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19425 try { 19426 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19427 19428 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19429 UserManagerService.enforceSerialNumber( 19430 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19431 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19432 UserManagerService.enforceSerialNumber( 19433 Environment.getDataSystemDeDirectory(userId), userSerial); 19434 } 19435 } 19436 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19437 UserManagerService.enforceSerialNumber( 19438 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19439 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19440 UserManagerService.enforceSerialNumber( 19441 Environment.getDataSystemCeDirectory(userId), userSerial); 19442 } 19443 } 19444 19445 synchronized (mInstallLock) { 19446 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19447 } 19448 } catch (Exception e) { 19449 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19450 + " because we failed to prepare: " + e); 19451 destroyUserDataLI(volumeUuid, userId, 19452 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19453 19454 if (allowRecover) { 19455 // Try one last time; if we fail again we're really in trouble 19456 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19457 } 19458 } 19459 } 19460 19461 /** 19462 * Destroy storage areas for given user on all mounted devices. 19463 */ 19464 void destroyUserData(int userId, int flags) { 19465 synchronized (mInstallLock) { 19466 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19467 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19468 final String volumeUuid = vol.getFsUuid(); 19469 destroyUserDataLI(volumeUuid, userId, flags); 19470 } 19471 } 19472 } 19473 19474 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19475 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19476 try { 19477 // Clean up app data, profile data, and media data 19478 mInstaller.destroyUserData(volumeUuid, userId, flags); 19479 19480 // Clean up system data 19481 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19482 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19483 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19484 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19485 } 19486 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19487 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19488 } 19489 } 19490 19491 // Data with special labels is now gone, so finish the job 19492 storage.destroyUserStorage(volumeUuid, userId, flags); 19493 19494 } catch (Exception e) { 19495 logCriticalInfo(Log.WARN, 19496 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19497 } 19498 } 19499 19500 /** 19501 * Examine all users present on given mounted volume, and destroy data 19502 * belonging to users that are no longer valid, or whose user ID has been 19503 * recycled. 19504 */ 19505 private void reconcileUsers(String volumeUuid) { 19506 final List<File> files = new ArrayList<>(); 19507 Collections.addAll(files, FileUtils 19508 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19509 Collections.addAll(files, FileUtils 19510 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19511 Collections.addAll(files, FileUtils 19512 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19513 Collections.addAll(files, FileUtils 19514 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19515 for (File file : files) { 19516 if (!file.isDirectory()) continue; 19517 19518 final int userId; 19519 final UserInfo info; 19520 try { 19521 userId = Integer.parseInt(file.getName()); 19522 info = sUserManager.getUserInfo(userId); 19523 } catch (NumberFormatException e) { 19524 Slog.w(TAG, "Invalid user directory " + file); 19525 continue; 19526 } 19527 19528 boolean destroyUser = false; 19529 if (info == null) { 19530 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19531 + " because no matching user was found"); 19532 destroyUser = true; 19533 } else if (!mOnlyCore) { 19534 try { 19535 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19536 } catch (IOException e) { 19537 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19538 + " because we failed to enforce serial number: " + e); 19539 destroyUser = true; 19540 } 19541 } 19542 19543 if (destroyUser) { 19544 synchronized (mInstallLock) { 19545 destroyUserDataLI(volumeUuid, userId, 19546 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19547 } 19548 } 19549 } 19550 } 19551 19552 private void assertPackageKnown(String volumeUuid, String packageName) 19553 throws PackageManagerException { 19554 synchronized (mPackages) { 19555 final PackageSetting ps = mSettings.mPackages.get(packageName); 19556 if (ps == null) { 19557 throw new PackageManagerException("Package " + packageName + " is unknown"); 19558 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19559 throw new PackageManagerException( 19560 "Package " + packageName + " found on unknown volume " + volumeUuid 19561 + "; expected volume " + ps.volumeUuid); 19562 } 19563 } 19564 } 19565 19566 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19567 throws PackageManagerException { 19568 synchronized (mPackages) { 19569 final PackageSetting ps = mSettings.mPackages.get(packageName); 19570 if (ps == null) { 19571 throw new PackageManagerException("Package " + packageName + " is unknown"); 19572 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19573 throw new PackageManagerException( 19574 "Package " + packageName + " found on unknown volume " + volumeUuid 19575 + "; expected volume " + ps.volumeUuid); 19576 } else if (!ps.getInstalled(userId)) { 19577 throw new PackageManagerException( 19578 "Package " + packageName + " not installed for user " + userId); 19579 } 19580 } 19581 } 19582 19583 /** 19584 * Examine all apps present on given mounted volume, and destroy apps that 19585 * aren't expected, either due to uninstallation or reinstallation on 19586 * another volume. 19587 */ 19588 private void reconcileApps(String volumeUuid) { 19589 final File[] files = FileUtils 19590 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19591 for (File file : files) { 19592 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19593 && !PackageInstallerService.isStageName(file.getName()); 19594 if (!isPackage) { 19595 // Ignore entries which are not packages 19596 continue; 19597 } 19598 19599 try { 19600 final PackageLite pkg = PackageParser.parsePackageLite(file, 19601 PackageParser.PARSE_MUST_BE_APK); 19602 assertPackageKnown(volumeUuid, pkg.packageName); 19603 19604 } catch (PackageParserException | PackageManagerException e) { 19605 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19606 synchronized (mInstallLock) { 19607 removeCodePathLI(file); 19608 } 19609 } 19610 } 19611 } 19612 19613 /** 19614 * Reconcile all app data for the given user. 19615 * <p> 19616 * Verifies that directories exist and that ownership and labeling is 19617 * correct for all installed apps on all mounted volumes. 19618 */ 19619 void reconcileAppsData(int userId, int flags) { 19620 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19621 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19622 final String volumeUuid = vol.getFsUuid(); 19623 synchronized (mInstallLock) { 19624 reconcileAppsDataLI(volumeUuid, userId, flags); 19625 } 19626 } 19627 } 19628 19629 /** 19630 * Reconcile all app data on given mounted volume. 19631 * <p> 19632 * Destroys app data that isn't expected, either due to uninstallation or 19633 * reinstallation on another volume. 19634 * <p> 19635 * Verifies that directories exist and that ownership and labeling is 19636 * correct for all installed apps. 19637 */ 19638 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19639 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19640 + Integer.toHexString(flags)); 19641 19642 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19643 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19644 19645 boolean restoreconNeeded = false; 19646 19647 // First look for stale data that doesn't belong, and check if things 19648 // have changed since we did our last restorecon 19649 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19650 if (StorageManager.isFileEncryptedNativeOrEmulated() 19651 && !StorageManager.isUserKeyUnlocked(userId)) { 19652 throw new RuntimeException( 19653 "Yikes, someone asked us to reconcile CE storage while " + userId 19654 + " was still locked; this would have caused massive data loss!"); 19655 } 19656 19657 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19658 19659 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19660 for (File file : files) { 19661 final String packageName = file.getName(); 19662 try { 19663 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19664 } catch (PackageManagerException e) { 19665 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19666 try { 19667 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19668 StorageManager.FLAG_STORAGE_CE, 0); 19669 } catch (InstallerException e2) { 19670 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19671 } 19672 } 19673 } 19674 } 19675 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19676 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19677 19678 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19679 for (File file : files) { 19680 final String packageName = file.getName(); 19681 try { 19682 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19683 } catch (PackageManagerException e) { 19684 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19685 try { 19686 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19687 StorageManager.FLAG_STORAGE_DE, 0); 19688 } catch (InstallerException e2) { 19689 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19690 } 19691 } 19692 } 19693 } 19694 19695 // Ensure that data directories are ready to roll for all packages 19696 // installed for this volume and user 19697 final List<PackageSetting> packages; 19698 synchronized (mPackages) { 19699 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19700 } 19701 int preparedCount = 0; 19702 for (PackageSetting ps : packages) { 19703 final String packageName = ps.name; 19704 if (ps.pkg == null) { 19705 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19706 // TODO: might be due to legacy ASEC apps; we should circle back 19707 // and reconcile again once they're scanned 19708 continue; 19709 } 19710 19711 if (ps.getInstalled(userId)) { 19712 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19713 19714 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19715 // We may have just shuffled around app data directories, so 19716 // prepare them one more time 19717 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19718 } 19719 19720 preparedCount++; 19721 } 19722 } 19723 19724 if (restoreconNeeded) { 19725 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19726 SELinuxMMAC.setRestoreconDone(ceDir); 19727 } 19728 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19729 SELinuxMMAC.setRestoreconDone(deDir); 19730 } 19731 } 19732 19733 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19734 + " packages; restoreconNeeded was " + restoreconNeeded); 19735 } 19736 19737 /** 19738 * Prepare app data for the given app just after it was installed or 19739 * upgraded. This method carefully only touches users that it's installed 19740 * for, and it forces a restorecon to handle any seinfo changes. 19741 * <p> 19742 * Verifies that directories exist and that ownership and labeling is 19743 * correct for all installed apps. If there is an ownership mismatch, it 19744 * will try recovering system apps by wiping data; third-party app data is 19745 * left intact. 19746 * <p> 19747 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19748 */ 19749 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19750 final PackageSetting ps; 19751 synchronized (mPackages) { 19752 ps = mSettings.mPackages.get(pkg.packageName); 19753 mSettings.writeKernelMappingLPr(ps); 19754 } 19755 19756 final UserManager um = mContext.getSystemService(UserManager.class); 19757 UserManagerInternal umInternal = getUserManagerInternal(); 19758 for (UserInfo user : um.getUsers()) { 19759 final int flags; 19760 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19761 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19762 } else if (umInternal.isUserRunning(user.id)) { 19763 flags = StorageManager.FLAG_STORAGE_DE; 19764 } else { 19765 continue; 19766 } 19767 19768 if (ps.getInstalled(user.id)) { 19769 // Whenever an app changes, force a restorecon of its data 19770 // TODO: when user data is locked, mark that we're still dirty 19771 prepareAppDataLIF(pkg, user.id, flags, true); 19772 } 19773 } 19774 } 19775 19776 /** 19777 * Prepare app data for the given app. 19778 * <p> 19779 * Verifies that directories exist and that ownership and labeling is 19780 * correct for all installed apps. If there is an ownership mismatch, this 19781 * will try recovering system apps by wiping data; third-party app data is 19782 * left intact. 19783 */ 19784 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19785 boolean restoreconNeeded) { 19786 if (pkg == null) { 19787 Slog.wtf(TAG, "Package was null!", new Throwable()); 19788 return; 19789 } 19790 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19791 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19792 for (int i = 0; i < childCount; i++) { 19793 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19794 } 19795 } 19796 19797 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19798 boolean restoreconNeeded) { 19799 if (DEBUG_APP_DATA) { 19800 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19801 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19802 } 19803 19804 final String volumeUuid = pkg.volumeUuid; 19805 final String packageName = pkg.packageName; 19806 final ApplicationInfo app = pkg.applicationInfo; 19807 final int appId = UserHandle.getAppId(app.uid); 19808 19809 Preconditions.checkNotNull(app.seinfo); 19810 19811 try { 19812 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19813 appId, app.seinfo, app.targetSdkVersion); 19814 } catch (InstallerException e) { 19815 if (app.isSystemApp()) { 19816 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19817 + ", but trying to recover: " + e); 19818 destroyAppDataLeafLIF(pkg, userId, flags); 19819 try { 19820 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19821 appId, app.seinfo, app.targetSdkVersion); 19822 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19823 } catch (InstallerException e2) { 19824 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19825 } 19826 } else { 19827 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19828 } 19829 } 19830 19831 if (restoreconNeeded) { 19832 try { 19833 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19834 app.seinfo); 19835 } catch (InstallerException e) { 19836 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19837 } 19838 } 19839 19840 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19841 try { 19842 // CE storage is unlocked right now, so read out the inode and 19843 // remember for use later when it's locked 19844 // TODO: mark this structure as dirty so we persist it! 19845 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19846 StorageManager.FLAG_STORAGE_CE); 19847 synchronized (mPackages) { 19848 final PackageSetting ps = mSettings.mPackages.get(packageName); 19849 if (ps != null) { 19850 ps.setCeDataInode(ceDataInode, userId); 19851 } 19852 } 19853 } catch (InstallerException e) { 19854 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19855 } 19856 } 19857 19858 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19859 } 19860 19861 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19862 if (pkg == null) { 19863 Slog.wtf(TAG, "Package was null!", new Throwable()); 19864 return; 19865 } 19866 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19867 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19868 for (int i = 0; i < childCount; i++) { 19869 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19870 } 19871 } 19872 19873 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19874 final String volumeUuid = pkg.volumeUuid; 19875 final String packageName = pkg.packageName; 19876 final ApplicationInfo app = pkg.applicationInfo; 19877 19878 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19879 // Create a native library symlink only if we have native libraries 19880 // and if the native libraries are 32 bit libraries. We do not provide 19881 // this symlink for 64 bit libraries. 19882 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19883 final String nativeLibPath = app.nativeLibraryDir; 19884 try { 19885 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19886 nativeLibPath, userId); 19887 } catch (InstallerException e) { 19888 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19889 } 19890 } 19891 } 19892 } 19893 19894 /** 19895 * For system apps on non-FBE devices, this method migrates any existing 19896 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19897 * requested by the app. 19898 */ 19899 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19900 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19901 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19902 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19903 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19904 try { 19905 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19906 storageTarget); 19907 } catch (InstallerException e) { 19908 logCriticalInfo(Log.WARN, 19909 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19910 } 19911 return true; 19912 } else { 19913 return false; 19914 } 19915 } 19916 19917 public PackageFreezer freezePackage(String packageName, String killReason) { 19918 return freezePackage(packageName, UserHandle.USER_ALL, killReason); 19919 } 19920 19921 public PackageFreezer freezePackage(String packageName, int userId, String killReason) { 19922 return new PackageFreezer(packageName, userId, killReason); 19923 } 19924 19925 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19926 String killReason) { 19927 return freezePackageForInstall(packageName, UserHandle.USER_ALL, installFlags, killReason); 19928 } 19929 19930 public PackageFreezer freezePackageForInstall(String packageName, int userId, int installFlags, 19931 String killReason) { 19932 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19933 return new PackageFreezer(); 19934 } else { 19935 return freezePackage(packageName, userId, killReason); 19936 } 19937 } 19938 19939 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19940 String killReason) { 19941 return freezePackageForDelete(packageName, UserHandle.USER_ALL, deleteFlags, killReason); 19942 } 19943 19944 public PackageFreezer freezePackageForDelete(String packageName, int userId, int deleteFlags, 19945 String killReason) { 19946 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19947 return new PackageFreezer(); 19948 } else { 19949 return freezePackage(packageName, userId, killReason); 19950 } 19951 } 19952 19953 /** 19954 * Class that freezes and kills the given package upon creation, and 19955 * unfreezes it upon closing. This is typically used when doing surgery on 19956 * app code/data to prevent the app from running while you're working. 19957 */ 19958 private class PackageFreezer implements AutoCloseable { 19959 private final String mPackageName; 19960 private final PackageFreezer[] mChildren; 19961 19962 private final boolean mWeFroze; 19963 19964 private final AtomicBoolean mClosed = new AtomicBoolean(); 19965 private final CloseGuard mCloseGuard = CloseGuard.get(); 19966 19967 /** 19968 * Create and return a stub freezer that doesn't actually do anything, 19969 * typically used when someone requested 19970 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19971 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19972 */ 19973 public PackageFreezer() { 19974 mPackageName = null; 19975 mChildren = null; 19976 mWeFroze = false; 19977 mCloseGuard.open("close"); 19978 } 19979 19980 public PackageFreezer(String packageName, int userId, String killReason) { 19981 synchronized (mPackages) { 19982 mPackageName = packageName; 19983 mWeFroze = mFrozenPackages.add(mPackageName); 19984 19985 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19986 if (ps != null) { 19987 killApplication(ps.name, ps.appId, userId, killReason); 19988 } 19989 19990 final PackageParser.Package p = mPackages.get(packageName); 19991 if (p != null && p.childPackages != null) { 19992 final int N = p.childPackages.size(); 19993 mChildren = new PackageFreezer[N]; 19994 for (int i = 0; i < N; i++) { 19995 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19996 userId, killReason); 19997 } 19998 } else { 19999 mChildren = null; 20000 } 20001 } 20002 mCloseGuard.open("close"); 20003 } 20004 20005 @Override 20006 protected void finalize() throws Throwable { 20007 try { 20008 mCloseGuard.warnIfOpen(); 20009 close(); 20010 } finally { 20011 super.finalize(); 20012 } 20013 } 20014 20015 @Override 20016 public void close() { 20017 mCloseGuard.close(); 20018 if (mClosed.compareAndSet(false, true)) { 20019 synchronized (mPackages) { 20020 if (mWeFroze) { 20021 mFrozenPackages.remove(mPackageName); 20022 } 20023 20024 if (mChildren != null) { 20025 for (PackageFreezer freezer : mChildren) { 20026 freezer.close(); 20027 } 20028 } 20029 } 20030 } 20031 } 20032 } 20033 20034 /** 20035 * Verify that given package is currently frozen. 20036 */ 20037 private void checkPackageFrozen(String packageName) { 20038 synchronized (mPackages) { 20039 if (!mFrozenPackages.contains(packageName)) { 20040 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 20041 } 20042 } 20043 } 20044 20045 @Override 20046 public int movePackage(final String packageName, final String volumeUuid) { 20047 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20048 20049 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 20050 final int moveId = mNextMoveId.getAndIncrement(); 20051 mHandler.post(new Runnable() { 20052 @Override 20053 public void run() { 20054 try { 20055 movePackageInternal(packageName, volumeUuid, moveId, user); 20056 } catch (PackageManagerException e) { 20057 Slog.w(TAG, "Failed to move " + packageName, e); 20058 mMoveCallbacks.notifyStatusChanged(moveId, 20059 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20060 } 20061 } 20062 }); 20063 return moveId; 20064 } 20065 20066 private void movePackageInternal(final String packageName, final String volumeUuid, 20067 final int moveId, UserHandle user) throws PackageManagerException { 20068 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20069 final PackageManager pm = mContext.getPackageManager(); 20070 20071 final boolean currentAsec; 20072 final String currentVolumeUuid; 20073 final File codeFile; 20074 final String installerPackageName; 20075 final String packageAbiOverride; 20076 final int appId; 20077 final String seinfo; 20078 final String label; 20079 final int targetSdkVersion; 20080 final PackageFreezer freezer; 20081 final int[] installedUserIds; 20082 20083 // reader 20084 synchronized (mPackages) { 20085 final PackageParser.Package pkg = mPackages.get(packageName); 20086 final PackageSetting ps = mSettings.mPackages.get(packageName); 20087 if (pkg == null || ps == null) { 20088 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20089 } 20090 20091 if (pkg.applicationInfo.isSystemApp()) { 20092 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20093 "Cannot move system application"); 20094 } 20095 20096 if (pkg.applicationInfo.isExternalAsec()) { 20097 currentAsec = true; 20098 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20099 } else if (pkg.applicationInfo.isForwardLocked()) { 20100 currentAsec = true; 20101 currentVolumeUuid = "forward_locked"; 20102 } else { 20103 currentAsec = false; 20104 currentVolumeUuid = ps.volumeUuid; 20105 20106 final File probe = new File(pkg.codePath); 20107 final File probeOat = new File(probe, "oat"); 20108 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20109 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20110 "Move only supported for modern cluster style installs"); 20111 } 20112 } 20113 20114 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20115 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20116 "Package already moved to " + volumeUuid); 20117 } 20118 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20119 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20120 "Device admin cannot be moved"); 20121 } 20122 20123 if (mFrozenPackages.contains(packageName)) { 20124 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20125 "Failed to move already frozen package"); 20126 } 20127 20128 codeFile = new File(pkg.codePath); 20129 installerPackageName = ps.installerPackageName; 20130 packageAbiOverride = ps.cpuAbiOverrideString; 20131 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20132 seinfo = pkg.applicationInfo.seinfo; 20133 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20134 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20135 freezer = freezePackage(packageName, "movePackageInternal"); 20136 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20137 } 20138 20139 final Bundle extras = new Bundle(); 20140 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20141 extras.putString(Intent.EXTRA_TITLE, label); 20142 mMoveCallbacks.notifyCreated(moveId, extras); 20143 20144 int installFlags; 20145 final boolean moveCompleteApp; 20146 final File measurePath; 20147 20148 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20149 installFlags = INSTALL_INTERNAL; 20150 moveCompleteApp = !currentAsec; 20151 measurePath = Environment.getDataAppDirectory(volumeUuid); 20152 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20153 installFlags = INSTALL_EXTERNAL; 20154 moveCompleteApp = false; 20155 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20156 } else { 20157 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20158 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20159 || !volume.isMountedWritable()) { 20160 freezer.close(); 20161 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20162 "Move location not mounted private volume"); 20163 } 20164 20165 Preconditions.checkState(!currentAsec); 20166 20167 installFlags = INSTALL_INTERNAL; 20168 moveCompleteApp = true; 20169 measurePath = Environment.getDataAppDirectory(volumeUuid); 20170 } 20171 20172 final PackageStats stats = new PackageStats(null, -1); 20173 synchronized (mInstaller) { 20174 for (int userId : installedUserIds) { 20175 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20176 freezer.close(); 20177 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20178 "Failed to measure package size"); 20179 } 20180 } 20181 } 20182 20183 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20184 + stats.dataSize); 20185 20186 final long startFreeBytes = measurePath.getFreeSpace(); 20187 final long sizeBytes; 20188 if (moveCompleteApp) { 20189 sizeBytes = stats.codeSize + stats.dataSize; 20190 } else { 20191 sizeBytes = stats.codeSize; 20192 } 20193 20194 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20195 freezer.close(); 20196 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20197 "Not enough free space to move"); 20198 } 20199 20200 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20201 20202 final CountDownLatch installedLatch = new CountDownLatch(1); 20203 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20204 @Override 20205 public void onUserActionRequired(Intent intent) throws RemoteException { 20206 throw new IllegalStateException(); 20207 } 20208 20209 @Override 20210 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20211 Bundle extras) throws RemoteException { 20212 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20213 + PackageManager.installStatusToString(returnCode, msg)); 20214 20215 installedLatch.countDown(); 20216 freezer.close(); 20217 20218 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20219 switch (status) { 20220 case PackageInstaller.STATUS_SUCCESS: 20221 mMoveCallbacks.notifyStatusChanged(moveId, 20222 PackageManager.MOVE_SUCCEEDED); 20223 break; 20224 case PackageInstaller.STATUS_FAILURE_STORAGE: 20225 mMoveCallbacks.notifyStatusChanged(moveId, 20226 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20227 break; 20228 default: 20229 mMoveCallbacks.notifyStatusChanged(moveId, 20230 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20231 break; 20232 } 20233 } 20234 }; 20235 20236 final MoveInfo move; 20237 if (moveCompleteApp) { 20238 // Kick off a thread to report progress estimates 20239 new Thread() { 20240 @Override 20241 public void run() { 20242 while (true) { 20243 try { 20244 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20245 break; 20246 } 20247 } catch (InterruptedException ignored) { 20248 } 20249 20250 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20251 final int progress = 10 + (int) MathUtils.constrain( 20252 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20253 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20254 } 20255 } 20256 }.start(); 20257 20258 final String dataAppName = codeFile.getName(); 20259 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20260 dataAppName, appId, seinfo, targetSdkVersion); 20261 } else { 20262 move = null; 20263 } 20264 20265 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20266 20267 final Message msg = mHandler.obtainMessage(INIT_COPY); 20268 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20269 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20270 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20271 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20272 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20273 msg.obj = params; 20274 20275 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20276 System.identityHashCode(msg.obj)); 20277 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20278 System.identityHashCode(msg.obj)); 20279 20280 mHandler.sendMessage(msg); 20281 } 20282 20283 @Override 20284 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20285 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20286 20287 final int realMoveId = mNextMoveId.getAndIncrement(); 20288 final Bundle extras = new Bundle(); 20289 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20290 mMoveCallbacks.notifyCreated(realMoveId, extras); 20291 20292 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20293 @Override 20294 public void onCreated(int moveId, Bundle extras) { 20295 // Ignored 20296 } 20297 20298 @Override 20299 public void onStatusChanged(int moveId, int status, long estMillis) { 20300 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20301 } 20302 }; 20303 20304 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20305 storage.setPrimaryStorageUuid(volumeUuid, callback); 20306 return realMoveId; 20307 } 20308 20309 @Override 20310 public int getMoveStatus(int moveId) { 20311 mContext.enforceCallingOrSelfPermission( 20312 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20313 return mMoveCallbacks.mLastStatus.get(moveId); 20314 } 20315 20316 @Override 20317 public void registerMoveCallback(IPackageMoveObserver callback) { 20318 mContext.enforceCallingOrSelfPermission( 20319 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20320 mMoveCallbacks.register(callback); 20321 } 20322 20323 @Override 20324 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20325 mContext.enforceCallingOrSelfPermission( 20326 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20327 mMoveCallbacks.unregister(callback); 20328 } 20329 20330 @Override 20331 public boolean setInstallLocation(int loc) { 20332 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20333 null); 20334 if (getInstallLocation() == loc) { 20335 return true; 20336 } 20337 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20338 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20339 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20340 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20341 return true; 20342 } 20343 return false; 20344 } 20345 20346 @Override 20347 public int getInstallLocation() { 20348 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20349 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20350 PackageHelper.APP_INSTALL_AUTO); 20351 } 20352 20353 /** Called by UserManagerService */ 20354 void cleanUpUser(UserManagerService userManager, int userHandle) { 20355 synchronized (mPackages) { 20356 mDirtyUsers.remove(userHandle); 20357 mUserNeedsBadging.delete(userHandle); 20358 mSettings.removeUserLPw(userHandle); 20359 mPendingBroadcasts.remove(userHandle); 20360 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20361 removeUnusedPackagesLPw(userManager, userHandle); 20362 } 20363 } 20364 20365 /** 20366 * We're removing userHandle and would like to remove any downloaded packages 20367 * that are no longer in use by any other user. 20368 * @param userHandle the user being removed 20369 */ 20370 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20371 final boolean DEBUG_CLEAN_APKS = false; 20372 int [] users = userManager.getUserIds(); 20373 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20374 while (psit.hasNext()) { 20375 PackageSetting ps = psit.next(); 20376 if (ps.pkg == null) { 20377 continue; 20378 } 20379 final String packageName = ps.pkg.packageName; 20380 // Skip over if system app 20381 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20382 continue; 20383 } 20384 if (DEBUG_CLEAN_APKS) { 20385 Slog.i(TAG, "Checking package " + packageName); 20386 } 20387 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20388 if (keep) { 20389 if (DEBUG_CLEAN_APKS) { 20390 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20391 } 20392 } else { 20393 for (int i = 0; i < users.length; i++) { 20394 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20395 keep = true; 20396 if (DEBUG_CLEAN_APKS) { 20397 Slog.i(TAG, " Keeping package " + packageName + " for user " 20398 + users[i]); 20399 } 20400 break; 20401 } 20402 } 20403 } 20404 if (!keep) { 20405 if (DEBUG_CLEAN_APKS) { 20406 Slog.i(TAG, " Removing package " + packageName); 20407 } 20408 mHandler.post(new Runnable() { 20409 public void run() { 20410 deletePackageX(packageName, userHandle, 0); 20411 } //end run 20412 }); 20413 } 20414 } 20415 } 20416 20417 /** Called by UserManagerService */ 20418 void createNewUser(int userId) { 20419 synchronized (mInstallLock) { 20420 mSettings.createNewUserLI(this, mInstaller, userId); 20421 } 20422 synchronized (mPackages) { 20423 scheduleWritePackageRestrictionsLocked(userId); 20424 scheduleWritePackageListLocked(userId); 20425 applyFactoryDefaultBrowserLPw(userId); 20426 primeDomainVerificationsLPw(userId); 20427 } 20428 } 20429 20430 void onBeforeUserStartUninitialized(final int userId) { 20431 synchronized (mPackages) { 20432 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20433 return; 20434 } 20435 } 20436 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20437 // If permission review for legacy apps is required, we represent 20438 // dagerous permissions for such apps as always granted runtime 20439 // permissions to keep per user flag state whether review is needed. 20440 // Hence, if a new user is added we have to propagate dangerous 20441 // permission grants for these legacy apps. 20442 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20443 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20444 | UPDATE_PERMISSIONS_REPLACE_ALL); 20445 } 20446 } 20447 20448 @Override 20449 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20450 mContext.enforceCallingOrSelfPermission( 20451 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20452 "Only package verification agents can read the verifier device identity"); 20453 20454 synchronized (mPackages) { 20455 return mSettings.getVerifierDeviceIdentityLPw(); 20456 } 20457 } 20458 20459 @Override 20460 public void setPermissionEnforced(String permission, boolean enforced) { 20461 // TODO: Now that we no longer change GID for storage, this should to away. 20462 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20463 "setPermissionEnforced"); 20464 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20465 synchronized (mPackages) { 20466 if (mSettings.mReadExternalStorageEnforced == null 20467 || mSettings.mReadExternalStorageEnforced != enforced) { 20468 mSettings.mReadExternalStorageEnforced = enforced; 20469 mSettings.writeLPr(); 20470 } 20471 } 20472 // kill any non-foreground processes so we restart them and 20473 // grant/revoke the GID. 20474 final IActivityManager am = ActivityManagerNative.getDefault(); 20475 if (am != null) { 20476 final long token = Binder.clearCallingIdentity(); 20477 try { 20478 am.killProcessesBelowForeground("setPermissionEnforcement"); 20479 } catch (RemoteException e) { 20480 } finally { 20481 Binder.restoreCallingIdentity(token); 20482 } 20483 } 20484 } else { 20485 throw new IllegalArgumentException("No selective enforcement for " + permission); 20486 } 20487 } 20488 20489 @Override 20490 @Deprecated 20491 public boolean isPermissionEnforced(String permission) { 20492 return true; 20493 } 20494 20495 @Override 20496 public boolean isStorageLow() { 20497 final long token = Binder.clearCallingIdentity(); 20498 try { 20499 final DeviceStorageMonitorInternal 20500 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20501 if (dsm != null) { 20502 return dsm.isMemoryLow(); 20503 } else { 20504 return false; 20505 } 20506 } finally { 20507 Binder.restoreCallingIdentity(token); 20508 } 20509 } 20510 20511 @Override 20512 public IPackageInstaller getPackageInstaller() { 20513 return mInstallerService; 20514 } 20515 20516 private boolean userNeedsBadging(int userId) { 20517 int index = mUserNeedsBadging.indexOfKey(userId); 20518 if (index < 0) { 20519 final UserInfo userInfo; 20520 final long token = Binder.clearCallingIdentity(); 20521 try { 20522 userInfo = sUserManager.getUserInfo(userId); 20523 } finally { 20524 Binder.restoreCallingIdentity(token); 20525 } 20526 final boolean b; 20527 if (userInfo != null && userInfo.isManagedProfile()) { 20528 b = true; 20529 } else { 20530 b = false; 20531 } 20532 mUserNeedsBadging.put(userId, b); 20533 return b; 20534 } 20535 return mUserNeedsBadging.valueAt(index); 20536 } 20537 20538 @Override 20539 public KeySet getKeySetByAlias(String packageName, String alias) { 20540 if (packageName == null || alias == null) { 20541 return null; 20542 } 20543 synchronized(mPackages) { 20544 final PackageParser.Package pkg = mPackages.get(packageName); 20545 if (pkg == null) { 20546 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20547 throw new IllegalArgumentException("Unknown package: " + packageName); 20548 } 20549 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20550 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20551 } 20552 } 20553 20554 @Override 20555 public KeySet getSigningKeySet(String packageName) { 20556 if (packageName == null) { 20557 return null; 20558 } 20559 synchronized(mPackages) { 20560 final PackageParser.Package pkg = mPackages.get(packageName); 20561 if (pkg == null) { 20562 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20563 throw new IllegalArgumentException("Unknown package: " + packageName); 20564 } 20565 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20566 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20567 throw new SecurityException("May not access signing KeySet of other apps."); 20568 } 20569 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20570 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20571 } 20572 } 20573 20574 @Override 20575 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20576 if (packageName == null || ks == null) { 20577 return false; 20578 } 20579 synchronized(mPackages) { 20580 final PackageParser.Package pkg = mPackages.get(packageName); 20581 if (pkg == null) { 20582 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20583 throw new IllegalArgumentException("Unknown package: " + packageName); 20584 } 20585 IBinder ksh = ks.getToken(); 20586 if (ksh instanceof KeySetHandle) { 20587 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20588 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20589 } 20590 return false; 20591 } 20592 } 20593 20594 @Override 20595 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20596 if (packageName == null || ks == null) { 20597 return false; 20598 } 20599 synchronized(mPackages) { 20600 final PackageParser.Package pkg = mPackages.get(packageName); 20601 if (pkg == null) { 20602 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20603 throw new IllegalArgumentException("Unknown package: " + packageName); 20604 } 20605 IBinder ksh = ks.getToken(); 20606 if (ksh instanceof KeySetHandle) { 20607 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20608 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20609 } 20610 return false; 20611 } 20612 } 20613 20614 private void deletePackageIfUnusedLPr(final String packageName) { 20615 PackageSetting ps = mSettings.mPackages.get(packageName); 20616 if (ps == null) { 20617 return; 20618 } 20619 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20620 // TODO Implement atomic delete if package is unused 20621 // It is currently possible that the package will be deleted even if it is installed 20622 // after this method returns. 20623 mHandler.post(new Runnable() { 20624 public void run() { 20625 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20626 } 20627 }); 20628 } 20629 } 20630 20631 /** 20632 * Check and throw if the given before/after packages would be considered a 20633 * downgrade. 20634 */ 20635 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20636 throws PackageManagerException { 20637 if (after.versionCode < before.mVersionCode) { 20638 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20639 "Update version code " + after.versionCode + " is older than current " 20640 + before.mVersionCode); 20641 } else if (after.versionCode == before.mVersionCode) { 20642 if (after.baseRevisionCode < before.baseRevisionCode) { 20643 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20644 "Update base revision code " + after.baseRevisionCode 20645 + " is older than current " + before.baseRevisionCode); 20646 } 20647 20648 if (!ArrayUtils.isEmpty(after.splitNames)) { 20649 for (int i = 0; i < after.splitNames.length; i++) { 20650 final String splitName = after.splitNames[i]; 20651 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20652 if (j != -1) { 20653 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20654 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20655 "Update split " + splitName + " revision code " 20656 + after.splitRevisionCodes[i] + " is older than current " 20657 + before.splitRevisionCodes[j]); 20658 } 20659 } 20660 } 20661 } 20662 } 20663 } 20664 20665 private static class MoveCallbacks extends Handler { 20666 private static final int MSG_CREATED = 1; 20667 private static final int MSG_STATUS_CHANGED = 2; 20668 20669 private final RemoteCallbackList<IPackageMoveObserver> 20670 mCallbacks = new RemoteCallbackList<>(); 20671 20672 private final SparseIntArray mLastStatus = new SparseIntArray(); 20673 20674 public MoveCallbacks(Looper looper) { 20675 super(looper); 20676 } 20677 20678 public void register(IPackageMoveObserver callback) { 20679 mCallbacks.register(callback); 20680 } 20681 20682 public void unregister(IPackageMoveObserver callback) { 20683 mCallbacks.unregister(callback); 20684 } 20685 20686 @Override 20687 public void handleMessage(Message msg) { 20688 final SomeArgs args = (SomeArgs) msg.obj; 20689 final int n = mCallbacks.beginBroadcast(); 20690 for (int i = 0; i < n; i++) { 20691 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20692 try { 20693 invokeCallback(callback, msg.what, args); 20694 } catch (RemoteException ignored) { 20695 } 20696 } 20697 mCallbacks.finishBroadcast(); 20698 args.recycle(); 20699 } 20700 20701 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20702 throws RemoteException { 20703 switch (what) { 20704 case MSG_CREATED: { 20705 callback.onCreated(args.argi1, (Bundle) args.arg2); 20706 break; 20707 } 20708 case MSG_STATUS_CHANGED: { 20709 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20710 break; 20711 } 20712 } 20713 } 20714 20715 private void notifyCreated(int moveId, Bundle extras) { 20716 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20717 20718 final SomeArgs args = SomeArgs.obtain(); 20719 args.argi1 = moveId; 20720 args.arg2 = extras; 20721 obtainMessage(MSG_CREATED, args).sendToTarget(); 20722 } 20723 20724 private void notifyStatusChanged(int moveId, int status) { 20725 notifyStatusChanged(moveId, status, -1); 20726 } 20727 20728 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20729 Slog.v(TAG, "Move " + moveId + " status " + status); 20730 20731 final SomeArgs args = SomeArgs.obtain(); 20732 args.argi1 = moveId; 20733 args.argi2 = status; 20734 args.arg3 = estMillis; 20735 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20736 20737 synchronized (mLastStatus) { 20738 mLastStatus.put(moveId, status); 20739 } 20740 } 20741 } 20742 20743 private final static class OnPermissionChangeListeners extends Handler { 20744 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20745 20746 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20747 new RemoteCallbackList<>(); 20748 20749 public OnPermissionChangeListeners(Looper looper) { 20750 super(looper); 20751 } 20752 20753 @Override 20754 public void handleMessage(Message msg) { 20755 switch (msg.what) { 20756 case MSG_ON_PERMISSIONS_CHANGED: { 20757 final int uid = msg.arg1; 20758 handleOnPermissionsChanged(uid); 20759 } break; 20760 } 20761 } 20762 20763 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20764 mPermissionListeners.register(listener); 20765 20766 } 20767 20768 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20769 mPermissionListeners.unregister(listener); 20770 } 20771 20772 public void onPermissionsChanged(int uid) { 20773 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20774 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20775 } 20776 } 20777 20778 private void handleOnPermissionsChanged(int uid) { 20779 final int count = mPermissionListeners.beginBroadcast(); 20780 try { 20781 for (int i = 0; i < count; i++) { 20782 IOnPermissionsChangeListener callback = mPermissionListeners 20783 .getBroadcastItem(i); 20784 try { 20785 callback.onPermissionsChanged(uid); 20786 } catch (RemoteException e) { 20787 Log.e(TAG, "Permission listener is dead", e); 20788 } 20789 } 20790 } finally { 20791 mPermissionListeners.finishBroadcast(); 20792 } 20793 } 20794 } 20795 20796 private class PackageManagerInternalImpl extends PackageManagerInternal { 20797 @Override 20798 public void setLocationPackagesProvider(PackagesProvider provider) { 20799 synchronized (mPackages) { 20800 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20801 } 20802 } 20803 20804 @Override 20805 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20806 synchronized (mPackages) { 20807 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20808 } 20809 } 20810 20811 @Override 20812 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20813 synchronized (mPackages) { 20814 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20815 } 20816 } 20817 20818 @Override 20819 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20820 synchronized (mPackages) { 20821 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20822 } 20823 } 20824 20825 @Override 20826 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20827 synchronized (mPackages) { 20828 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20829 } 20830 } 20831 20832 @Override 20833 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20834 synchronized (mPackages) { 20835 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20836 } 20837 } 20838 20839 @Override 20840 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20841 synchronized (mPackages) { 20842 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20843 packageName, userId); 20844 } 20845 } 20846 20847 @Override 20848 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20849 synchronized (mPackages) { 20850 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20851 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20852 packageName, userId); 20853 } 20854 } 20855 20856 @Override 20857 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20858 synchronized (mPackages) { 20859 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20860 packageName, userId); 20861 } 20862 } 20863 20864 @Override 20865 public void setKeepUninstalledPackages(final List<String> packageList) { 20866 Preconditions.checkNotNull(packageList); 20867 List<String> removedFromList = null; 20868 synchronized (mPackages) { 20869 if (mKeepUninstalledPackages != null) { 20870 final int packagesCount = mKeepUninstalledPackages.size(); 20871 for (int i = 0; i < packagesCount; i++) { 20872 String oldPackage = mKeepUninstalledPackages.get(i); 20873 if (packageList != null && packageList.contains(oldPackage)) { 20874 continue; 20875 } 20876 if (removedFromList == null) { 20877 removedFromList = new ArrayList<>(); 20878 } 20879 removedFromList.add(oldPackage); 20880 } 20881 } 20882 mKeepUninstalledPackages = new ArrayList<>(packageList); 20883 if (removedFromList != null) { 20884 final int removedCount = removedFromList.size(); 20885 for (int i = 0; i < removedCount; i++) { 20886 deletePackageIfUnusedLPr(removedFromList.get(i)); 20887 } 20888 } 20889 } 20890 } 20891 20892 @Override 20893 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20894 synchronized (mPackages) { 20895 // If we do not support permission review, done. 20896 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20897 return false; 20898 } 20899 20900 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20901 if (packageSetting == null) { 20902 return false; 20903 } 20904 20905 // Permission review applies only to apps not supporting the new permission model. 20906 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20907 return false; 20908 } 20909 20910 // Legacy apps have the permission and get user consent on launch. 20911 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20912 return permissionsState.isPermissionReviewRequired(userId); 20913 } 20914 } 20915 20916 @Override 20917 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20918 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20919 } 20920 20921 @Override 20922 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20923 int userId) { 20924 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20925 } 20926 20927 @Override 20928 public void setDeviceAndProfileOwnerPackages( 20929 int deviceOwnerUserId, String deviceOwnerPackage, 20930 SparseArray<String> profileOwnerPackages) { 20931 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20932 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20933 } 20934 20935 @Override 20936 public boolean isPackageDataProtected(int userId, String packageName) { 20937 return mProtectedPackages.isPackageDataProtected(userId, packageName); 20938 } 20939 } 20940 20941 @Override 20942 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20943 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20944 synchronized (mPackages) { 20945 final long identity = Binder.clearCallingIdentity(); 20946 try { 20947 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20948 packageNames, userId); 20949 } finally { 20950 Binder.restoreCallingIdentity(identity); 20951 } 20952 } 20953 } 20954 20955 private static void enforceSystemOrPhoneCaller(String tag) { 20956 int callingUid = Binder.getCallingUid(); 20957 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20958 throw new SecurityException( 20959 "Cannot call " + tag + " from UID " + callingUid); 20960 } 20961 } 20962 20963 boolean isHistoricalPackageUsageAvailable() { 20964 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20965 } 20966 20967 /** 20968 * Return a <b>copy</b> of the collection of packages known to the package manager. 20969 * @return A copy of the values of mPackages. 20970 */ 20971 Collection<PackageParser.Package> getPackages() { 20972 synchronized (mPackages) { 20973 return new ArrayList<>(mPackages.values()); 20974 } 20975 } 20976 20977 /** 20978 * Logs process start information (including base APK hash) to the security log. 20979 * @hide 20980 */ 20981 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20982 String apkFile, int pid) { 20983 if (!SecurityLog.isLoggingEnabled()) { 20984 return; 20985 } 20986 Bundle data = new Bundle(); 20987 data.putLong("startTimestamp", System.currentTimeMillis()); 20988 data.putString("processName", processName); 20989 data.putInt("uid", uid); 20990 data.putString("seinfo", seinfo); 20991 data.putString("apkFile", apkFile); 20992 data.putInt("pid", pid); 20993 Message msg = mProcessLoggingHandler.obtainMessage( 20994 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20995 msg.setData(data); 20996 mProcessLoggingHandler.sendMessage(msg); 20997 } 20998} 20999