PackageManagerService.java revision 3dafee6c1820bf0946bab04b290c5a757112d3e7
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 = 0xFFFFFFFF; 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 = new ProtectedPackages(); 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.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1223 readVersion1LP(in, sb); 1224 } else { 1225 readVersion0LP(in, sb, firstLine); 1226 } 1227 } catch (FileNotFoundException expected) { 1228 mIsHistoricalPackageUsageAvailable = false; 1229 } catch (IOException e) { 1230 Log.w(TAG, "Failed to read package usage times", e); 1231 } finally { 1232 IoUtils.closeQuietly(in); 1233 } 1234 } 1235 mLastWritten.set(SystemClock.elapsedRealtime()); 1236 } 1237 1238 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1239 throws IOException { 1240 // Initial version of the file had no version number and stored one 1241 // package-timestamp pair per line. 1242 // Note that the first line has already been read from the InputStream. 1243 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1244 String[] tokens = line.split(" "); 1245 if (tokens.length != 2) { 1246 throw new IOException("Failed to parse " + line + 1247 " as package-timestamp pair."); 1248 } 1249 1250 String packageName = tokens[0]; 1251 PackageParser.Package pkg = mPackages.get(packageName); 1252 if (pkg == null) { 1253 continue; 1254 } 1255 1256 long timestamp = parseAsLong(tokens[1]); 1257 for (int reason = 0; 1258 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1259 reason++) { 1260 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1261 } 1262 } 1263 } 1264 1265 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1266 // Version 1 of the file started with the corresponding version 1267 // number and then stored a package name and eight timestamps per line. 1268 String line; 1269 while ((line = readLine(in, sb)) != null) { 1270 String[] tokens = line.split(" "); 1271 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1272 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1273 } 1274 1275 String packageName = tokens[0]; 1276 PackageParser.Package pkg = mPackages.get(packageName); 1277 if (pkg == null) { 1278 continue; 1279 } 1280 1281 for (int reason = 0; 1282 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1283 reason++) { 1284 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1285 } 1286 } 1287 } 1288 1289 private long parseAsLong(String token) throws IOException { 1290 try { 1291 return Long.parseLong(token); 1292 } catch (NumberFormatException e) { 1293 throw new IOException("Failed to parse " + token + " as a long.", e); 1294 } 1295 } 1296 1297 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1298 return readToken(in, sb, '\n'); 1299 } 1300 1301 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1302 throws IOException { 1303 sb.setLength(0); 1304 while (true) { 1305 int ch = in.read(); 1306 if (ch == -1) { 1307 if (sb.length() == 0) { 1308 return null; 1309 } 1310 throw new IOException("Unexpected EOF"); 1311 } 1312 if (ch == endOfToken) { 1313 return sb.toString(); 1314 } 1315 sb.append((char)ch); 1316 } 1317 } 1318 1319 private AtomicFile getFile() { 1320 File dataDir = Environment.getDataDirectory(); 1321 File systemDir = new File(dataDir, "system"); 1322 File fname = new File(systemDir, "package-usage.list"); 1323 return new AtomicFile(fname); 1324 } 1325 1326 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1327 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1328 } 1329 1330 class PackageHandler extends Handler { 1331 private boolean mBound = false; 1332 final ArrayList<HandlerParams> mPendingInstalls = 1333 new ArrayList<HandlerParams>(); 1334 1335 private boolean connectToService() { 1336 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1337 " DefaultContainerService"); 1338 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1340 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1341 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1342 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1343 mBound = true; 1344 return true; 1345 } 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1347 return false; 1348 } 1349 1350 private void disconnectService() { 1351 mContainerService = null; 1352 mBound = false; 1353 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1354 mContext.unbindService(mDefContainerConn); 1355 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1356 } 1357 1358 PackageHandler(Looper looper) { 1359 super(looper); 1360 } 1361 1362 public void handleMessage(Message msg) { 1363 try { 1364 doHandleMessage(msg); 1365 } finally { 1366 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1367 } 1368 } 1369 1370 void doHandleMessage(Message msg) { 1371 switch (msg.what) { 1372 case INIT_COPY: { 1373 HandlerParams params = (HandlerParams) msg.obj; 1374 int idx = mPendingInstalls.size(); 1375 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1376 // If a bind was already initiated we dont really 1377 // need to do anything. The pending install 1378 // will be processed later on. 1379 if (!mBound) { 1380 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1381 System.identityHashCode(mHandler)); 1382 // If this is the only one pending we might 1383 // have to bind to the service again. 1384 if (!connectToService()) { 1385 Slog.e(TAG, "Failed to bind to media container service"); 1386 params.serviceError(); 1387 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1388 System.identityHashCode(mHandler)); 1389 if (params.traceMethod != null) { 1390 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1391 params.traceCookie); 1392 } 1393 return; 1394 } else { 1395 // Once we bind to the service, the first 1396 // pending request will be processed. 1397 mPendingInstalls.add(idx, params); 1398 } 1399 } else { 1400 mPendingInstalls.add(idx, params); 1401 // Already bound to the service. Just make 1402 // sure we trigger off processing the first request. 1403 if (idx == 0) { 1404 mHandler.sendEmptyMessage(MCS_BOUND); 1405 } 1406 } 1407 break; 1408 } 1409 case MCS_BOUND: { 1410 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1411 if (msg.obj != null) { 1412 mContainerService = (IMediaContainerService) msg.obj; 1413 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1414 System.identityHashCode(mHandler)); 1415 } 1416 if (mContainerService == null) { 1417 if (!mBound) { 1418 // Something seriously wrong since we are not bound and we are not 1419 // waiting for connection. Bail out. 1420 Slog.e(TAG, "Cannot bind to media container service"); 1421 for (HandlerParams params : mPendingInstalls) { 1422 // Indicate service bind error 1423 params.serviceError(); 1424 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1425 System.identityHashCode(params)); 1426 if (params.traceMethod != null) { 1427 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1428 params.traceMethod, params.traceCookie); 1429 } 1430 return; 1431 } 1432 mPendingInstalls.clear(); 1433 } else { 1434 Slog.w(TAG, "Waiting to connect to media container service"); 1435 } 1436 } else if (mPendingInstalls.size() > 0) { 1437 HandlerParams params = mPendingInstalls.get(0); 1438 if (params != null) { 1439 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1440 System.identityHashCode(params)); 1441 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1442 if (params.startCopy()) { 1443 // We are done... look for more work or to 1444 // go idle. 1445 if (DEBUG_SD_INSTALL) Log.i(TAG, 1446 "Checking for more work or unbind..."); 1447 // Delete pending install 1448 if (mPendingInstalls.size() > 0) { 1449 mPendingInstalls.remove(0); 1450 } 1451 if (mPendingInstalls.size() == 0) { 1452 if (mBound) { 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, 1454 "Posting delayed MCS_UNBIND"); 1455 removeMessages(MCS_UNBIND); 1456 Message ubmsg = obtainMessage(MCS_UNBIND); 1457 // Unbind after a little delay, to avoid 1458 // continual thrashing. 1459 sendMessageDelayed(ubmsg, 10000); 1460 } 1461 } else { 1462 // There are more pending requests in queue. 1463 // Just post MCS_BOUND message to trigger processing 1464 // of next pending install. 1465 if (DEBUG_SD_INSTALL) Log.i(TAG, 1466 "Posting MCS_BOUND for next work"); 1467 mHandler.sendEmptyMessage(MCS_BOUND); 1468 } 1469 } 1470 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1471 } 1472 } else { 1473 // Should never happen ideally. 1474 Slog.w(TAG, "Empty queue"); 1475 } 1476 break; 1477 } 1478 case MCS_RECONNECT: { 1479 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1480 if (mPendingInstalls.size() > 0) { 1481 if (mBound) { 1482 disconnectService(); 1483 } 1484 if (!connectToService()) { 1485 Slog.e(TAG, "Failed to bind to media container service"); 1486 for (HandlerParams params : mPendingInstalls) { 1487 // Indicate service bind error 1488 params.serviceError(); 1489 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1490 System.identityHashCode(params)); 1491 } 1492 mPendingInstalls.clear(); 1493 } 1494 } 1495 break; 1496 } 1497 case MCS_UNBIND: { 1498 // If there is no actual work left, then time to unbind. 1499 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1500 1501 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1502 if (mBound) { 1503 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1504 1505 disconnectService(); 1506 } 1507 } else if (mPendingInstalls.size() > 0) { 1508 // There are more pending requests in queue. 1509 // Just post MCS_BOUND message to trigger processing 1510 // of next pending install. 1511 mHandler.sendEmptyMessage(MCS_BOUND); 1512 } 1513 1514 break; 1515 } 1516 case MCS_GIVE_UP: { 1517 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1518 HandlerParams params = mPendingInstalls.remove(0); 1519 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1520 System.identityHashCode(params)); 1521 break; 1522 } 1523 case SEND_PENDING_BROADCAST: { 1524 String packages[]; 1525 ArrayList<String> components[]; 1526 int size = 0; 1527 int uids[]; 1528 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1529 synchronized (mPackages) { 1530 if (mPendingBroadcasts == null) { 1531 return; 1532 } 1533 size = mPendingBroadcasts.size(); 1534 if (size <= 0) { 1535 // Nothing to be done. Just return 1536 return; 1537 } 1538 packages = new String[size]; 1539 components = new ArrayList[size]; 1540 uids = new int[size]; 1541 int i = 0; // filling out the above arrays 1542 1543 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1544 int packageUserId = mPendingBroadcasts.userIdAt(n); 1545 Iterator<Map.Entry<String, ArrayList<String>>> it 1546 = mPendingBroadcasts.packagesForUserId(packageUserId) 1547 .entrySet().iterator(); 1548 while (it.hasNext() && i < size) { 1549 Map.Entry<String, ArrayList<String>> ent = it.next(); 1550 packages[i] = ent.getKey(); 1551 components[i] = ent.getValue(); 1552 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1553 uids[i] = (ps != null) 1554 ? UserHandle.getUid(packageUserId, ps.appId) 1555 : -1; 1556 i++; 1557 } 1558 } 1559 size = i; 1560 mPendingBroadcasts.clear(); 1561 } 1562 // Send broadcasts 1563 for (int i = 0; i < size; i++) { 1564 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1565 } 1566 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1567 break; 1568 } 1569 case START_CLEANING_PACKAGE: { 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1571 final String packageName = (String)msg.obj; 1572 final int userId = msg.arg1; 1573 final boolean andCode = msg.arg2 != 0; 1574 synchronized (mPackages) { 1575 if (userId == UserHandle.USER_ALL) { 1576 int[] users = sUserManager.getUserIds(); 1577 for (int user : users) { 1578 mSettings.addPackageToCleanLPw( 1579 new PackageCleanItem(user, packageName, andCode)); 1580 } 1581 } else { 1582 mSettings.addPackageToCleanLPw( 1583 new PackageCleanItem(userId, packageName, andCode)); 1584 } 1585 } 1586 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1587 startCleaningPackages(); 1588 } break; 1589 case POST_INSTALL: { 1590 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1591 1592 PostInstallData data = mRunningInstalls.get(msg.arg1); 1593 final boolean didRestore = (msg.arg2 != 0); 1594 mRunningInstalls.delete(msg.arg1); 1595 1596 if (data != null) { 1597 InstallArgs args = data.args; 1598 PackageInstalledInfo parentRes = data.res; 1599 1600 final boolean grantPermissions = (args.installFlags 1601 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1602 final boolean killApp = (args.installFlags 1603 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1604 final String[] grantedPermissions = args.installGrantPermissions; 1605 1606 // Handle the parent package 1607 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1608 grantedPermissions, didRestore, args.installerPackageName, 1609 args.observer); 1610 1611 // Handle the child packages 1612 final int childCount = (parentRes.addedChildPackages != null) 1613 ? parentRes.addedChildPackages.size() : 0; 1614 for (int i = 0; i < childCount; i++) { 1615 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1616 handlePackagePostInstall(childRes, grantPermissions, killApp, 1617 grantedPermissions, false, args.installerPackageName, 1618 args.observer); 1619 } 1620 1621 // Log tracing if needed 1622 if (args.traceMethod != null) { 1623 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1624 args.traceCookie); 1625 } 1626 } else { 1627 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1628 } 1629 1630 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1631 } break; 1632 case UPDATED_MEDIA_STATUS: { 1633 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1634 boolean reportStatus = msg.arg1 == 1; 1635 boolean doGc = msg.arg2 == 1; 1636 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1637 if (doGc) { 1638 // Force a gc to clear up stale containers. 1639 Runtime.getRuntime().gc(); 1640 } 1641 if (msg.obj != null) { 1642 @SuppressWarnings("unchecked") 1643 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1644 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1645 // Unload containers 1646 unloadAllContainers(args); 1647 } 1648 if (reportStatus) { 1649 try { 1650 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1651 PackageHelper.getMountService().finishMediaUpdate(); 1652 } catch (RemoteException e) { 1653 Log.e(TAG, "MountService not running?"); 1654 } 1655 } 1656 } break; 1657 case WRITE_SETTINGS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_SETTINGS); 1661 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1662 mSettings.writeLPr(); 1663 mDirtyUsers.clear(); 1664 } 1665 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1666 } break; 1667 case WRITE_PACKAGE_RESTRICTIONS: { 1668 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1669 synchronized (mPackages) { 1670 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1671 for (int userId : mDirtyUsers) { 1672 mSettings.writePackageRestrictionsLPr(userId); 1673 } 1674 mDirtyUsers.clear(); 1675 } 1676 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1677 } break; 1678 case WRITE_PACKAGE_LIST: { 1679 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1680 synchronized (mPackages) { 1681 removeMessages(WRITE_PACKAGE_LIST); 1682 mSettings.writePackageListLPr(msg.arg1); 1683 } 1684 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1685 } break; 1686 case CHECK_PENDING_VERIFICATION: { 1687 final int verificationId = msg.arg1; 1688 final PackageVerificationState state = mPendingVerification.get(verificationId); 1689 1690 if ((state != null) && !state.timeoutExtended()) { 1691 final InstallArgs args = state.getInstallArgs(); 1692 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1693 1694 Slog.i(TAG, "Verification timed out for " + originUri); 1695 mPendingVerification.remove(verificationId); 1696 1697 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1698 1699 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1700 Slog.i(TAG, "Continuing with installation of " + originUri); 1701 state.setVerifierResponse(Binder.getCallingUid(), 1702 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1703 broadcastPackageVerified(verificationId, originUri, 1704 PackageManager.VERIFICATION_ALLOW, 1705 state.getInstallArgs().getUser()); 1706 try { 1707 ret = args.copyApk(mContainerService, true); 1708 } catch (RemoteException e) { 1709 Slog.e(TAG, "Could not contact the ContainerService"); 1710 } 1711 } else { 1712 broadcastPackageVerified(verificationId, originUri, 1713 PackageManager.VERIFICATION_REJECT, 1714 state.getInstallArgs().getUser()); 1715 } 1716 1717 Trace.asyncTraceEnd( 1718 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1719 1720 processPendingInstall(args, ret); 1721 mHandler.sendEmptyMessage(MCS_UNBIND); 1722 } 1723 break; 1724 } 1725 case PACKAGE_VERIFIED: { 1726 final int verificationId = msg.arg1; 1727 1728 final PackageVerificationState state = mPendingVerification.get(verificationId); 1729 if (state == null) { 1730 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1731 break; 1732 } 1733 1734 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1735 1736 state.setVerifierResponse(response.callerUid, response.code); 1737 1738 if (state.isVerificationComplete()) { 1739 mPendingVerification.remove(verificationId); 1740 1741 final InstallArgs args = state.getInstallArgs(); 1742 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1743 1744 int ret; 1745 if (state.isInstallAllowed()) { 1746 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1747 broadcastPackageVerified(verificationId, originUri, 1748 response.code, state.getInstallArgs().getUser()); 1749 try { 1750 ret = args.copyApk(mContainerService, true); 1751 } catch (RemoteException e) { 1752 Slog.e(TAG, "Could not contact the ContainerService"); 1753 } 1754 } else { 1755 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1756 } 1757 1758 Trace.asyncTraceEnd( 1759 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1760 1761 processPendingInstall(args, ret); 1762 mHandler.sendEmptyMessage(MCS_UNBIND); 1763 } 1764 1765 break; 1766 } 1767 case START_INTENT_FILTER_VERIFICATIONS: { 1768 IFVerificationParams params = (IFVerificationParams) msg.obj; 1769 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1770 params.replacing, params.pkg); 1771 break; 1772 } 1773 case INTENT_FILTER_VERIFIED: { 1774 final int verificationId = msg.arg1; 1775 1776 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1777 verificationId); 1778 if (state == null) { 1779 Slog.w(TAG, "Invalid IntentFilter verification token " 1780 + verificationId + " received"); 1781 break; 1782 } 1783 1784 final int userId = state.getUserId(); 1785 1786 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1787 "Processing IntentFilter verification with token:" 1788 + verificationId + " and userId:" + userId); 1789 1790 final IntentFilterVerificationResponse response = 1791 (IntentFilterVerificationResponse) msg.obj; 1792 1793 state.setVerifierResponse(response.callerUid, response.code); 1794 1795 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1796 "IntentFilter verification with token:" + verificationId 1797 + " and userId:" + userId 1798 + " is settings verifier response with response code:" 1799 + response.code); 1800 1801 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1802 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1803 + response.getFailedDomainsString()); 1804 } 1805 1806 if (state.isVerificationComplete()) { 1807 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1808 } else { 1809 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1810 "IntentFilter verification with token:" + verificationId 1811 + " was not said to be complete"); 1812 } 1813 1814 break; 1815 } 1816 } 1817 } 1818 } 1819 1820 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1821 boolean killApp, String[] grantedPermissions, 1822 boolean launchedForRestore, String installerPackage, 1823 IPackageInstallObserver2 installObserver) { 1824 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1825 // Send the removed broadcasts 1826 if (res.removedInfo != null) { 1827 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1828 } 1829 1830 // Now that we successfully installed the package, grant runtime 1831 // permissions if requested before broadcasting the install. 1832 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1833 >= Build.VERSION_CODES.M) { 1834 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1835 } 1836 1837 final boolean update = res.removedInfo != null 1838 && res.removedInfo.removedPackage != null; 1839 1840 // If this is the first time we have child packages for a disabled privileged 1841 // app that had no children, we grant requested runtime permissions to the new 1842 // children if the parent on the system image had them already granted. 1843 if (res.pkg.parentPackage != null) { 1844 synchronized (mPackages) { 1845 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1846 } 1847 } 1848 1849 synchronized (mPackages) { 1850 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1851 } 1852 1853 final String packageName = res.pkg.applicationInfo.packageName; 1854 Bundle extras = new Bundle(1); 1855 extras.putInt(Intent.EXTRA_UID, res.uid); 1856 1857 // Determine the set of users who are adding this package for 1858 // the first time vs. those who are seeing an update. 1859 int[] firstUsers = EMPTY_INT_ARRAY; 1860 int[] updateUsers = EMPTY_INT_ARRAY; 1861 if (res.origUsers == null || res.origUsers.length == 0) { 1862 firstUsers = res.newUsers; 1863 } else { 1864 for (int newUser : res.newUsers) { 1865 boolean isNew = true; 1866 for (int origUser : res.origUsers) { 1867 if (origUser == newUser) { 1868 isNew = false; 1869 break; 1870 } 1871 } 1872 if (isNew) { 1873 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1874 } else { 1875 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1876 } 1877 } 1878 } 1879 1880 // Send installed broadcasts if the install/update is not ephemeral 1881 if (!isEphemeral(res.pkg)) { 1882 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1883 1884 // Send added for users that see the package for the first time 1885 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1886 extras, 0 /*flags*/, null /*targetPackage*/, 1887 null /*finishedReceiver*/, firstUsers); 1888 1889 // Send added for users that don't see the package for the first time 1890 if (update) { 1891 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1892 } 1893 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1894 extras, 0 /*flags*/, null /*targetPackage*/, 1895 null /*finishedReceiver*/, updateUsers); 1896 1897 // Send replaced for users that don't see the package for the first time 1898 if (update) { 1899 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1900 packageName, extras, 0 /*flags*/, 1901 null /*targetPackage*/, null /*finishedReceiver*/, 1902 updateUsers); 1903 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1904 null /*package*/, null /*extras*/, 0 /*flags*/, 1905 packageName /*targetPackage*/, 1906 null /*finishedReceiver*/, updateUsers); 1907 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1908 // First-install and we did a restore, so we're responsible for the 1909 // first-launch broadcast. 1910 if (DEBUG_BACKUP) { 1911 Slog.i(TAG, "Post-restore of " + packageName 1912 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1913 } 1914 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1915 } 1916 1917 // Send broadcast package appeared if forward locked/external for all users 1918 // treat asec-hosted packages like removable media on upgrade 1919 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1920 if (DEBUG_INSTALL) { 1921 Slog.i(TAG, "upgrading pkg " + res.pkg 1922 + " is ASEC-hosted -> AVAILABLE"); 1923 } 1924 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1925 ArrayList<String> pkgList = new ArrayList<>(1); 1926 pkgList.add(packageName); 1927 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1928 } 1929 } 1930 1931 // Work that needs to happen on first install within each user 1932 if (firstUsers != null && firstUsers.length > 0) { 1933 synchronized (mPackages) { 1934 for (int userId : firstUsers) { 1935 // If this app is a browser and it's newly-installed for some 1936 // users, clear any default-browser state in those users. The 1937 // app's nature doesn't depend on the user, so we can just check 1938 // its browser nature in any user and generalize. 1939 if (packageIsBrowser(packageName, userId)) { 1940 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1941 } 1942 1943 // We may also need to apply pending (restored) runtime 1944 // permission grants within these users. 1945 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1946 } 1947 } 1948 } 1949 1950 // Log current value of "unknown sources" setting 1951 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1952 getUnknownSourcesSettings()); 1953 1954 // Force a gc to clear up things 1955 Runtime.getRuntime().gc(); 1956 1957 // Remove the replaced package's older resources safely now 1958 // We delete after a gc for applications on sdcard. 1959 if (res.removedInfo != null && res.removedInfo.args != null) { 1960 synchronized (mInstallLock) { 1961 res.removedInfo.args.doPostDeleteLI(true); 1962 } 1963 } 1964 } 1965 1966 // If someone is watching installs - notify them 1967 if (installObserver != null) { 1968 try { 1969 Bundle extras = extrasForInstallResult(res); 1970 installObserver.onPackageInstalled(res.name, res.returnCode, 1971 res.returnMsg, extras); 1972 } catch (RemoteException e) { 1973 Slog.i(TAG, "Observer no longer exists."); 1974 } 1975 } 1976 } 1977 1978 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1979 PackageParser.Package pkg) { 1980 if (pkg.parentPackage == null) { 1981 return; 1982 } 1983 if (pkg.requestedPermissions == null) { 1984 return; 1985 } 1986 final PackageSetting disabledSysParentPs = mSettings 1987 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1988 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1989 || !disabledSysParentPs.isPrivileged() 1990 || (disabledSysParentPs.childPackageNames != null 1991 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1992 return; 1993 } 1994 final int[] allUserIds = sUserManager.getUserIds(); 1995 final int permCount = pkg.requestedPermissions.size(); 1996 for (int i = 0; i < permCount; i++) { 1997 String permission = pkg.requestedPermissions.get(i); 1998 BasePermission bp = mSettings.mPermissions.get(permission); 1999 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 2000 continue; 2001 } 2002 for (int userId : allUserIds) { 2003 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 2004 permission, userId)) { 2005 grantRuntimePermission(pkg.packageName, permission, userId); 2006 } 2007 } 2008 } 2009 } 2010 2011 private StorageEventListener mStorageListener = new StorageEventListener() { 2012 @Override 2013 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2014 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2015 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2016 final String volumeUuid = vol.getFsUuid(); 2017 2018 // Clean up any users or apps that were removed or recreated 2019 // while this volume was missing 2020 reconcileUsers(volumeUuid); 2021 reconcileApps(volumeUuid); 2022 2023 // Clean up any install sessions that expired or were 2024 // cancelled while this volume was missing 2025 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2026 2027 loadPrivatePackages(vol); 2028 2029 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2030 unloadPrivatePackages(vol); 2031 } 2032 } 2033 2034 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2035 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2036 updateExternalMediaStatus(true, false); 2037 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2038 updateExternalMediaStatus(false, false); 2039 } 2040 } 2041 } 2042 2043 @Override 2044 public void onVolumeForgotten(String fsUuid) { 2045 if (TextUtils.isEmpty(fsUuid)) { 2046 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2047 return; 2048 } 2049 2050 // Remove any apps installed on the forgotten volume 2051 synchronized (mPackages) { 2052 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2053 for (PackageSetting ps : packages) { 2054 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2055 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2056 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2057 } 2058 2059 mSettings.onVolumeForgotten(fsUuid); 2060 mSettings.writeLPr(); 2061 } 2062 } 2063 }; 2064 2065 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2066 String[] grantedPermissions) { 2067 for (int userId : userIds) { 2068 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2069 } 2070 2071 // We could have touched GID membership, so flush out packages.list 2072 synchronized (mPackages) { 2073 mSettings.writePackageListLPr(); 2074 } 2075 } 2076 2077 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2078 String[] grantedPermissions) { 2079 SettingBase sb = (SettingBase) pkg.mExtras; 2080 if (sb == null) { 2081 return; 2082 } 2083 2084 PermissionsState permissionsState = sb.getPermissionsState(); 2085 2086 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2087 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2088 2089 for (String permission : pkg.requestedPermissions) { 2090 final BasePermission bp; 2091 synchronized (mPackages) { 2092 bp = mSettings.mPermissions.get(permission); 2093 } 2094 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2095 && (grantedPermissions == null 2096 || ArrayUtils.contains(grantedPermissions, permission))) { 2097 final int flags = permissionsState.getPermissionFlags(permission, userId); 2098 // Installer cannot change immutable permissions. 2099 if ((flags & immutableFlags) == 0) { 2100 grantRuntimePermission(pkg.packageName, permission, userId); 2101 } 2102 } 2103 } 2104 } 2105 2106 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2107 Bundle extras = null; 2108 switch (res.returnCode) { 2109 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2110 extras = new Bundle(); 2111 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2112 res.origPermission); 2113 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2114 res.origPackage); 2115 break; 2116 } 2117 case PackageManager.INSTALL_SUCCEEDED: { 2118 extras = new Bundle(); 2119 extras.putBoolean(Intent.EXTRA_REPLACING, 2120 res.removedInfo != null && res.removedInfo.removedPackage != null); 2121 break; 2122 } 2123 } 2124 return extras; 2125 } 2126 2127 void scheduleWriteSettingsLocked() { 2128 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2129 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2130 } 2131 } 2132 2133 void scheduleWritePackageListLocked(int userId) { 2134 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2135 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2136 msg.arg1 = userId; 2137 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2138 } 2139 } 2140 2141 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2142 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2143 scheduleWritePackageRestrictionsLocked(userId); 2144 } 2145 2146 void scheduleWritePackageRestrictionsLocked(int userId) { 2147 final int[] userIds = (userId == UserHandle.USER_ALL) 2148 ? sUserManager.getUserIds() : new int[]{userId}; 2149 for (int nextUserId : userIds) { 2150 if (!sUserManager.exists(nextUserId)) return; 2151 mDirtyUsers.add(nextUserId); 2152 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2153 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2154 } 2155 } 2156 } 2157 2158 public static PackageManagerService main(Context context, Installer installer, 2159 boolean factoryTest, boolean onlyCore) { 2160 // Self-check for initial settings. 2161 PackageManagerServiceCompilerMapping.checkProperties(); 2162 2163 PackageManagerService m = new PackageManagerService(context, installer, 2164 factoryTest, onlyCore); 2165 m.enableSystemUserPackages(); 2166 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2167 // disabled after already being started. 2168 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2169 UserHandle.USER_SYSTEM); 2170 ServiceManager.addService("package", m); 2171 return m; 2172 } 2173 2174 private void enableSystemUserPackages() { 2175 if (!UserManager.isSplitSystemUser()) { 2176 return; 2177 } 2178 // For system user, enable apps based on the following conditions: 2179 // - app is whitelisted or belong to one of these groups: 2180 // -- system app which has no launcher icons 2181 // -- system app which has INTERACT_ACROSS_USERS permission 2182 // -- system IME app 2183 // - app is not in the blacklist 2184 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2185 Set<String> enableApps = new ArraySet<>(); 2186 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2187 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2188 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2189 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2190 enableApps.addAll(wlApps); 2191 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2192 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2193 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2194 enableApps.removeAll(blApps); 2195 Log.i(TAG, "Applications installed for system user: " + enableApps); 2196 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2197 UserHandle.SYSTEM); 2198 final int allAppsSize = allAps.size(); 2199 synchronized (mPackages) { 2200 for (int i = 0; i < allAppsSize; i++) { 2201 String pName = allAps.get(i); 2202 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2203 // Should not happen, but we shouldn't be failing if it does 2204 if (pkgSetting == null) { 2205 continue; 2206 } 2207 boolean install = enableApps.contains(pName); 2208 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2209 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2210 + " for system user"); 2211 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2212 } 2213 } 2214 } 2215 } 2216 2217 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2218 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2219 Context.DISPLAY_SERVICE); 2220 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2221 } 2222 2223 /** 2224 * Requests that files preopted on a secondary system partition be copied to the data partition 2225 * if possible. Note that the actual copying of the files is accomplished by init for security 2226 * reasons. This simply requests that the copy takes place and awaits confirmation of its 2227 * completion. See platform/system/extras/cppreopt/ for the implementation of the actual copy. 2228 */ 2229 private static void requestCopyPreoptedFiles() { 2230 final int WAIT_TIME_MS = 100; 2231 final String CP_PREOPT_PROPERTY = "sys.cppreopt"; 2232 if (SystemProperties.getInt("ro.cp_system_other_odex", 0) == 1) { 2233 SystemProperties.set(CP_PREOPT_PROPERTY, "requested"); 2234 // We will wait for up to 100 seconds. 2235 final long timeEnd = SystemClock.uptimeMillis() + 100 * 1000; 2236 while (!SystemProperties.get(CP_PREOPT_PROPERTY).equals("finished")) { 2237 try { 2238 Thread.sleep(WAIT_TIME_MS); 2239 } catch (InterruptedException e) { 2240 // Do nothing 2241 } 2242 if (SystemClock.uptimeMillis() > timeEnd) { 2243 SystemProperties.set(CP_PREOPT_PROPERTY, "timed-out"); 2244 Slog.wtf(TAG, "cppreopt did not finish!"); 2245 break; 2246 } 2247 } 2248 } 2249 } 2250 2251 public PackageManagerService(Context context, Installer installer, 2252 boolean factoryTest, boolean onlyCore) { 2253 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2254 SystemClock.uptimeMillis()); 2255 2256 if (mSdkVersion <= 0) { 2257 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2258 } 2259 2260 mContext = context; 2261 mFactoryTest = factoryTest; 2262 mOnlyCore = onlyCore; 2263 mMetrics = new DisplayMetrics(); 2264 mSettings = new Settings(mPackages); 2265 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2266 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2267 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2268 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2269 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2270 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2271 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2272 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2273 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2274 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2275 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2276 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2277 2278 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2279 if (separateProcesses != null && separateProcesses.length() > 0) { 2280 if ("*".equals(separateProcesses)) { 2281 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2282 mSeparateProcesses = null; 2283 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2284 } else { 2285 mDefParseFlags = 0; 2286 mSeparateProcesses = separateProcesses.split(","); 2287 Slog.w(TAG, "Running with debug.separate_processes: " 2288 + separateProcesses); 2289 } 2290 } else { 2291 mDefParseFlags = 0; 2292 mSeparateProcesses = null; 2293 } 2294 2295 mInstaller = installer; 2296 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2297 "*dexopt*"); 2298 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2299 2300 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2301 FgThread.get().getLooper()); 2302 2303 getDefaultDisplayMetrics(context, mMetrics); 2304 2305 SystemConfig systemConfig = SystemConfig.getInstance(); 2306 mGlobalGids = systemConfig.getGlobalGids(); 2307 mSystemPermissions = systemConfig.getSystemPermissions(); 2308 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2309 2310 synchronized (mInstallLock) { 2311 // writer 2312 synchronized (mPackages) { 2313 mHandlerThread = new ServiceThread(TAG, 2314 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2315 mHandlerThread.start(); 2316 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2317 mProcessLoggingHandler = new ProcessLoggingHandler(); 2318 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2319 2320 File dataDir = Environment.getDataDirectory(); 2321 mAppInstallDir = new File(dataDir, "app"); 2322 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2323 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2324 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2325 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2326 2327 sUserManager = new UserManagerService(context, this, mPackages); 2328 2329 // Propagate permission configuration in to package manager. 2330 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2331 = systemConfig.getPermissions(); 2332 for (int i=0; i<permConfig.size(); i++) { 2333 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2334 BasePermission bp = mSettings.mPermissions.get(perm.name); 2335 if (bp == null) { 2336 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2337 mSettings.mPermissions.put(perm.name, bp); 2338 } 2339 if (perm.gids != null) { 2340 bp.setGids(perm.gids, perm.perUser); 2341 } 2342 } 2343 2344 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2345 for (int i=0; i<libConfig.size(); i++) { 2346 mSharedLibraries.put(libConfig.keyAt(i), 2347 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2348 } 2349 2350 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2351 2352 mFirstBoot = !mSettings.readLPw(sUserManager.getUsers(false)); 2353 2354 if (mFirstBoot) { 2355 requestCopyPreoptedFiles(); 2356 } 2357 2358 String customResolverActivity = Resources.getSystem().getString( 2359 R.string.config_customResolverActivity); 2360 if (TextUtils.isEmpty(customResolverActivity)) { 2361 customResolverActivity = null; 2362 } else { 2363 mCustomResolverComponentName = ComponentName.unflattenFromString( 2364 customResolverActivity); 2365 } 2366 2367 long startTime = SystemClock.uptimeMillis(); 2368 2369 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2370 startTime); 2371 2372 // Set flag to monitor and not change apk file paths when 2373 // scanning install directories. 2374 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2375 2376 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2377 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2378 2379 if (bootClassPath == null) { 2380 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2381 } 2382 2383 if (systemServerClassPath == null) { 2384 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2385 } 2386 2387 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2388 final String[] dexCodeInstructionSets = 2389 getDexCodeInstructionSets( 2390 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2391 2392 /** 2393 * Ensure all external libraries have had dexopt run on them. 2394 */ 2395 if (mSharedLibraries.size() > 0) { 2396 // NOTE: For now, we're compiling these system "shared libraries" 2397 // (and framework jars) into all available architectures. It's possible 2398 // to compile them only when we come across an app that uses them (there's 2399 // already logic for that in scanPackageLI) but that adds some complexity. 2400 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2401 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2402 final String lib = libEntry.path; 2403 if (lib == null) { 2404 continue; 2405 } 2406 2407 try { 2408 // Shared libraries do not have profiles so we perform a full 2409 // AOT compilation (if needed). 2410 int dexoptNeeded = DexFile.getDexOptNeeded( 2411 lib, dexCodeInstructionSet, 2412 getCompilerFilterForReason(REASON_SHARED_APK), 2413 false /* newProfile */); 2414 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2415 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2416 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2417 getCompilerFilterForReason(REASON_SHARED_APK), 2418 StorageManager.UUID_PRIVATE_INTERNAL, 2419 SKIP_SHARED_LIBRARY_CHECK); 2420 } 2421 } catch (FileNotFoundException e) { 2422 Slog.w(TAG, "Library not found: " + lib); 2423 } catch (IOException | InstallerException e) { 2424 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2425 + e.getMessage()); 2426 } 2427 } 2428 } 2429 } 2430 2431 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2432 2433 final VersionInfo ver = mSettings.getInternalVersion(); 2434 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2435 2436 // when upgrading from pre-M, promote system app permissions from install to runtime 2437 mPromoteSystemApps = 2438 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2439 2440 // When upgrading from pre-N, we need to handle package extraction like first boot, 2441 // as there is no profiling data available. 2442 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2443 2444 // save off the names of pre-existing system packages prior to scanning; we don't 2445 // want to automatically grant runtime permissions for new system apps 2446 if (mPromoteSystemApps) { 2447 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2448 while (pkgSettingIter.hasNext()) { 2449 PackageSetting ps = pkgSettingIter.next(); 2450 if (isSystemApp(ps)) { 2451 mExistingSystemPackages.add(ps.name); 2452 } 2453 } 2454 } 2455 2456 // Collect vendor overlay packages. 2457 // (Do this before scanning any apps.) 2458 // For security and version matching reason, only consider 2459 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2460 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2461 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2462 | PackageParser.PARSE_IS_SYSTEM 2463 | PackageParser.PARSE_IS_SYSTEM_DIR 2464 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2465 2466 // Find base frameworks (resource packages without code). 2467 scanDirTracedLI(frameworkDir, mDefParseFlags 2468 | PackageParser.PARSE_IS_SYSTEM 2469 | PackageParser.PARSE_IS_SYSTEM_DIR 2470 | PackageParser.PARSE_IS_PRIVILEGED, 2471 scanFlags | SCAN_NO_DEX, 0); 2472 2473 // Collected privileged system packages. 2474 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2475 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2476 | PackageParser.PARSE_IS_SYSTEM 2477 | PackageParser.PARSE_IS_SYSTEM_DIR 2478 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2479 2480 // Collect ordinary system packages. 2481 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2482 scanDirTracedLI(systemAppDir, mDefParseFlags 2483 | PackageParser.PARSE_IS_SYSTEM 2484 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2485 2486 // Collect all vendor packages. 2487 File vendorAppDir = new File("/vendor/app"); 2488 try { 2489 vendorAppDir = vendorAppDir.getCanonicalFile(); 2490 } catch (IOException e) { 2491 // failed to look up canonical path, continue with original one 2492 } 2493 scanDirTracedLI(vendorAppDir, mDefParseFlags 2494 | PackageParser.PARSE_IS_SYSTEM 2495 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2496 2497 // Collect all OEM packages. 2498 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2499 scanDirTracedLI(oemAppDir, mDefParseFlags 2500 | PackageParser.PARSE_IS_SYSTEM 2501 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2502 2503 // Prune any system packages that no longer exist. 2504 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2505 if (!mOnlyCore) { 2506 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2507 while (psit.hasNext()) { 2508 PackageSetting ps = psit.next(); 2509 2510 /* 2511 * If this is not a system app, it can't be a 2512 * disable system app. 2513 */ 2514 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2515 continue; 2516 } 2517 2518 /* 2519 * If the package is scanned, it's not erased. 2520 */ 2521 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2522 if (scannedPkg != null) { 2523 /* 2524 * If the system app is both scanned and in the 2525 * disabled packages list, then it must have been 2526 * added via OTA. Remove it from the currently 2527 * scanned package so the previously user-installed 2528 * application can be scanned. 2529 */ 2530 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2531 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2532 + ps.name + "; removing system app. Last known codePath=" 2533 + ps.codePathString + ", installStatus=" + ps.installStatus 2534 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2535 + scannedPkg.mVersionCode); 2536 removePackageLI(scannedPkg, true); 2537 mExpectingBetter.put(ps.name, ps.codePath); 2538 } 2539 2540 continue; 2541 } 2542 2543 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2544 psit.remove(); 2545 logCriticalInfo(Log.WARN, "System package " + ps.name 2546 + " no longer exists; it's data will be wiped"); 2547 // Actual deletion of code and data will be handled by later 2548 // reconciliation step 2549 } else { 2550 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2551 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2552 possiblyDeletedUpdatedSystemApps.add(ps.name); 2553 } 2554 } 2555 } 2556 } 2557 2558 //look for any incomplete package installations 2559 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2560 for (int i = 0; i < deletePkgsList.size(); i++) { 2561 // Actual deletion of code and data will be handled by later 2562 // reconciliation step 2563 final String packageName = deletePkgsList.get(i).name; 2564 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2565 synchronized (mPackages) { 2566 mSettings.removePackageLPw(packageName); 2567 } 2568 } 2569 2570 //delete tmp files 2571 deleteTempPackageFiles(); 2572 2573 // Remove any shared userIDs that have no associated packages 2574 mSettings.pruneSharedUsersLPw(); 2575 2576 if (!mOnlyCore) { 2577 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2578 SystemClock.uptimeMillis()); 2579 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2580 2581 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2582 | PackageParser.PARSE_FORWARD_LOCK, 2583 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2584 2585 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2586 | PackageParser.PARSE_IS_EPHEMERAL, 2587 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2588 2589 /** 2590 * Remove disable package settings for any updated system 2591 * apps that were removed via an OTA. If they're not a 2592 * previously-updated app, remove them completely. 2593 * Otherwise, just revoke their system-level permissions. 2594 */ 2595 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2596 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2597 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2598 2599 String msg; 2600 if (deletedPkg == null) { 2601 msg = "Updated system package " + deletedAppName 2602 + " no longer exists; it's data will be wiped"; 2603 // Actual deletion of code and data will be handled by later 2604 // reconciliation step 2605 } else { 2606 msg = "Updated system app + " + deletedAppName 2607 + " no longer present; removing system privileges for " 2608 + deletedAppName; 2609 2610 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2611 2612 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2613 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2614 } 2615 logCriticalInfo(Log.WARN, msg); 2616 } 2617 2618 /** 2619 * Make sure all system apps that we expected to appear on 2620 * the userdata partition actually showed up. If they never 2621 * appeared, crawl back and revive the system version. 2622 */ 2623 for (int i = 0; i < mExpectingBetter.size(); i++) { 2624 final String packageName = mExpectingBetter.keyAt(i); 2625 if (!mPackages.containsKey(packageName)) { 2626 final File scanFile = mExpectingBetter.valueAt(i); 2627 2628 logCriticalInfo(Log.WARN, "Expected better " + packageName 2629 + " but never showed up; reverting to system"); 2630 2631 int reparseFlags = mDefParseFlags; 2632 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2633 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2634 | PackageParser.PARSE_IS_SYSTEM_DIR 2635 | PackageParser.PARSE_IS_PRIVILEGED; 2636 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2637 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2638 | PackageParser.PARSE_IS_SYSTEM_DIR; 2639 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2640 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2641 | PackageParser.PARSE_IS_SYSTEM_DIR; 2642 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2643 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2644 | PackageParser.PARSE_IS_SYSTEM_DIR; 2645 } else { 2646 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2647 continue; 2648 } 2649 2650 mSettings.enableSystemPackageLPw(packageName); 2651 2652 try { 2653 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2654 } catch (PackageManagerException e) { 2655 Slog.e(TAG, "Failed to parse original system package: " 2656 + e.getMessage()); 2657 } 2658 } 2659 } 2660 } 2661 mExpectingBetter.clear(); 2662 2663 // Resolve protected action filters. Only the setup wizard is allowed to 2664 // have a high priority filter for these actions. 2665 mSetupWizardPackage = getSetupWizardPackageName(); 2666 if (mProtectedFilters.size() > 0) { 2667 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2668 Slog.i(TAG, "No setup wizard;" 2669 + " All protected intents capped to priority 0"); 2670 } 2671 for (ActivityIntentInfo filter : mProtectedFilters) { 2672 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2673 if (DEBUG_FILTERS) { 2674 Slog.i(TAG, "Found setup wizard;" 2675 + " allow priority " + filter.getPriority() + ";" 2676 + " package: " + filter.activity.info.packageName 2677 + " activity: " + filter.activity.className 2678 + " priority: " + filter.getPriority()); 2679 } 2680 // skip setup wizard; allow it to keep the high priority filter 2681 continue; 2682 } 2683 Slog.w(TAG, "Protected action; cap priority to 0;" 2684 + " package: " + filter.activity.info.packageName 2685 + " activity: " + filter.activity.className 2686 + " origPrio: " + filter.getPriority()); 2687 filter.setPriority(0); 2688 } 2689 } 2690 mDeferProtectedFilters = false; 2691 mProtectedFilters.clear(); 2692 2693 // Now that we know all of the shared libraries, update all clients to have 2694 // the correct library paths. 2695 updateAllSharedLibrariesLPw(); 2696 2697 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2698 // NOTE: We ignore potential failures here during a system scan (like 2699 // the rest of the commands above) because there's precious little we 2700 // can do about it. A settings error is reported, though. 2701 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2702 false /* boot complete */); 2703 } 2704 2705 // Now that we know all the packages we are keeping, 2706 // read and update their last usage times. 2707 mPackageUsage.readLP(); 2708 2709 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2710 SystemClock.uptimeMillis()); 2711 Slog.i(TAG, "Time to scan packages: " 2712 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2713 + " seconds"); 2714 2715 // If the platform SDK has changed since the last time we booted, 2716 // we need to re-grant app permission to catch any new ones that 2717 // appear. This is really a hack, and means that apps can in some 2718 // cases get permissions that the user didn't initially explicitly 2719 // allow... it would be nice to have some better way to handle 2720 // this situation. 2721 int updateFlags = UPDATE_PERMISSIONS_ALL; 2722 if (ver.sdkVersion != mSdkVersion) { 2723 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2724 + mSdkVersion + "; regranting permissions for internal storage"); 2725 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2726 } 2727 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2728 ver.sdkVersion = mSdkVersion; 2729 2730 // If this is the first boot or an update from pre-M, and it is a normal 2731 // boot, then we need to initialize the default preferred apps across 2732 // all defined users. 2733 if (!onlyCore && (mPromoteSystemApps || mFirstBoot)) { 2734 for (UserInfo user : sUserManager.getUsers(true)) { 2735 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2736 applyFactoryDefaultBrowserLPw(user.id); 2737 primeDomainVerificationsLPw(user.id); 2738 } 2739 } 2740 2741 // Prepare storage for system user really early during boot, 2742 // since core system apps like SettingsProvider and SystemUI 2743 // can't wait for user to start 2744 final int storageFlags; 2745 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2746 storageFlags = StorageManager.FLAG_STORAGE_DE; 2747 } else { 2748 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2749 } 2750 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2751 storageFlags); 2752 2753 // If this is first boot after an OTA, and a normal boot, then 2754 // we need to clear code cache directories. 2755 // Note that we do *not* clear the application profiles. These remain valid 2756 // across OTAs and are used to drive profile verification (post OTA) and 2757 // profile compilation (without waiting to collect a fresh set of profiles). 2758 if (mIsUpgrade && !onlyCore) { 2759 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2760 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2761 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2762 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2763 // No apps are running this early, so no need to freeze 2764 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2765 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2766 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2767 } 2768 } 2769 ver.fingerprint = Build.FINGERPRINT; 2770 } 2771 2772 checkDefaultBrowser(); 2773 2774 // clear only after permissions and other defaults have been updated 2775 mExistingSystemPackages.clear(); 2776 mPromoteSystemApps = false; 2777 2778 // All the changes are done during package scanning. 2779 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2780 2781 // can downgrade to reader 2782 mSettings.writeLPr(); 2783 2784 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2785 // early on (before the package manager declares itself as early) because other 2786 // components in the system server might ask for package contexts for these apps. 2787 // 2788 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2789 // (i.e, that the data partition is unavailable). 2790 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2791 long start = System.nanoTime(); 2792 List<PackageParser.Package> coreApps = new ArrayList<>(); 2793 for (PackageParser.Package pkg : mPackages.values()) { 2794 if (pkg.coreApp) { 2795 coreApps.add(pkg); 2796 } 2797 } 2798 2799 int[] stats = performDexOpt(coreApps, false, 2800 getCompilerFilterForReason(REASON_CORE_APP)); 2801 2802 final int elapsedTimeSeconds = 2803 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2804 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2805 2806 if (DEBUG_DEXOPT) { 2807 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2808 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2809 } 2810 2811 2812 // TODO: Should we log these stats to tron too ? 2813 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2814 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2815 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2816 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2817 } 2818 2819 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2820 SystemClock.uptimeMillis()); 2821 2822 if (!mOnlyCore) { 2823 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2824 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2825 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2826 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2827 mIntentFilterVerifierComponent); 2828 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2829 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2830 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2831 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2832 } else { 2833 mRequiredVerifierPackage = null; 2834 mRequiredInstallerPackage = null; 2835 mIntentFilterVerifierComponent = null; 2836 mIntentFilterVerifier = null; 2837 mServicesSystemSharedLibraryPackageName = null; 2838 mSharedSystemSharedLibraryPackageName = null; 2839 } 2840 2841 mInstallerService = new PackageInstallerService(context, this); 2842 2843 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2844 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2845 // both the installer and resolver must be present to enable ephemeral 2846 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2847 if (DEBUG_EPHEMERAL) { 2848 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2849 + " installer:" + ephemeralInstallerComponent); 2850 } 2851 mEphemeralResolverComponent = ephemeralResolverComponent; 2852 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2853 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2854 mEphemeralResolverConnection = 2855 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2856 } else { 2857 if (DEBUG_EPHEMERAL) { 2858 final String missingComponent = 2859 (ephemeralResolverComponent == null) 2860 ? (ephemeralInstallerComponent == null) 2861 ? "resolver and installer" 2862 : "resolver" 2863 : "installer"; 2864 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2865 } 2866 mEphemeralResolverComponent = null; 2867 mEphemeralInstallerComponent = null; 2868 mEphemeralResolverConnection = null; 2869 } 2870 2871 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2872 } // synchronized (mPackages) 2873 } // synchronized (mInstallLock) 2874 2875 // Now after opening every single application zip, make sure they 2876 // are all flushed. Not really needed, but keeps things nice and 2877 // tidy. 2878 Runtime.getRuntime().gc(); 2879 2880 // The initial scanning above does many calls into installd while 2881 // holding the mPackages lock, but we're mostly interested in yelling 2882 // once we have a booted system. 2883 mInstaller.setWarnIfHeld(mPackages); 2884 2885 // Expose private service for system components to use. 2886 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2887 } 2888 2889 @Override 2890 public boolean isFirstBoot() { 2891 return mFirstBoot; 2892 } 2893 2894 @Override 2895 public boolean isOnlyCoreApps() { 2896 return mOnlyCore; 2897 } 2898 2899 @Override 2900 public boolean isUpgrade() { 2901 return mIsUpgrade; 2902 } 2903 2904 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2905 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2906 2907 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2908 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2909 UserHandle.USER_SYSTEM); 2910 if (matches.size() == 1) { 2911 return matches.get(0).getComponentInfo().packageName; 2912 } else { 2913 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2914 return null; 2915 } 2916 } 2917 2918 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2919 synchronized (mPackages) { 2920 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2921 if (libraryEntry == null) { 2922 throw new IllegalStateException("Missing required shared library:" + libraryName); 2923 } 2924 return libraryEntry.apk; 2925 } 2926 } 2927 2928 private @NonNull String getRequiredInstallerLPr() { 2929 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2930 intent.addCategory(Intent.CATEGORY_DEFAULT); 2931 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2932 2933 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2934 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2935 UserHandle.USER_SYSTEM); 2936 if (matches.size() == 1) { 2937 ResolveInfo resolveInfo = matches.get(0); 2938 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2939 throw new RuntimeException("The installer must be a privileged app"); 2940 } 2941 return matches.get(0).getComponentInfo().packageName; 2942 } else { 2943 throw new RuntimeException("There must be exactly one installer; found " + matches); 2944 } 2945 } 2946 2947 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2948 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2949 2950 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2951 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2952 UserHandle.USER_SYSTEM); 2953 ResolveInfo best = null; 2954 final int N = matches.size(); 2955 for (int i = 0; i < N; i++) { 2956 final ResolveInfo cur = matches.get(i); 2957 final String packageName = cur.getComponentInfo().packageName; 2958 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2959 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2960 continue; 2961 } 2962 2963 if (best == null || cur.priority > best.priority) { 2964 best = cur; 2965 } 2966 } 2967 2968 if (best != null) { 2969 return best.getComponentInfo().getComponentName(); 2970 } else { 2971 throw new RuntimeException("There must be at least one intent filter verifier"); 2972 } 2973 } 2974 2975 private @Nullable ComponentName getEphemeralResolverLPr() { 2976 final String[] packageArray = 2977 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2978 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2979 if (DEBUG_EPHEMERAL) { 2980 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2981 } 2982 return null; 2983 } 2984 2985 final int resolveFlags = 2986 MATCH_DIRECT_BOOT_AWARE 2987 | MATCH_DIRECT_BOOT_UNAWARE 2988 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2989 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2990 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2991 resolveFlags, UserHandle.USER_SYSTEM); 2992 2993 final int N = resolvers.size(); 2994 if (N == 0) { 2995 if (DEBUG_EPHEMERAL) { 2996 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2997 } 2998 return null; 2999 } 3000 3001 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 3002 for (int i = 0; i < N; i++) { 3003 final ResolveInfo info = resolvers.get(i); 3004 3005 if (info.serviceInfo == null) { 3006 continue; 3007 } 3008 3009 final String packageName = info.serviceInfo.packageName; 3010 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 3011 if (DEBUG_EPHEMERAL) { 3012 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 3013 + " pkg: " + packageName + ", info:" + info); 3014 } 3015 continue; 3016 } 3017 3018 if (DEBUG_EPHEMERAL) { 3019 Slog.v(TAG, "Ephemeral resolver found;" 3020 + " pkg: " + packageName + ", info:" + info); 3021 } 3022 return new ComponentName(packageName, info.serviceInfo.name); 3023 } 3024 if (DEBUG_EPHEMERAL) { 3025 Slog.v(TAG, "Ephemeral resolver NOT found"); 3026 } 3027 return null; 3028 } 3029 3030 private @Nullable ComponentName getEphemeralInstallerLPr() { 3031 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 3032 intent.addCategory(Intent.CATEGORY_DEFAULT); 3033 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 3034 3035 final int resolveFlags = 3036 MATCH_DIRECT_BOOT_AWARE 3037 | MATCH_DIRECT_BOOT_UNAWARE 3038 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3039 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3040 resolveFlags, UserHandle.USER_SYSTEM); 3041 if (matches.size() == 0) { 3042 return null; 3043 } else if (matches.size() == 1) { 3044 return matches.get(0).getComponentInfo().getComponentName(); 3045 } else { 3046 throw new RuntimeException( 3047 "There must be at most one ephemeral installer; found " + matches); 3048 } 3049 } 3050 3051 private void primeDomainVerificationsLPw(int userId) { 3052 if (DEBUG_DOMAIN_VERIFICATION) { 3053 Slog.d(TAG, "Priming domain verifications in user " + userId); 3054 } 3055 3056 SystemConfig systemConfig = SystemConfig.getInstance(); 3057 ArraySet<String> packages = systemConfig.getLinkedApps(); 3058 ArraySet<String> domains = new ArraySet<String>(); 3059 3060 for (String packageName : packages) { 3061 PackageParser.Package pkg = mPackages.get(packageName); 3062 if (pkg != null) { 3063 if (!pkg.isSystemApp()) { 3064 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3065 continue; 3066 } 3067 3068 domains.clear(); 3069 for (PackageParser.Activity a : pkg.activities) { 3070 for (ActivityIntentInfo filter : a.intents) { 3071 if (hasValidDomains(filter)) { 3072 domains.addAll(filter.getHostsList()); 3073 } 3074 } 3075 } 3076 3077 if (domains.size() > 0) { 3078 if (DEBUG_DOMAIN_VERIFICATION) { 3079 Slog.v(TAG, " + " + packageName); 3080 } 3081 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3082 // state w.r.t. the formal app-linkage "no verification attempted" state; 3083 // and then 'always' in the per-user state actually used for intent resolution. 3084 final IntentFilterVerificationInfo ivi; 3085 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3086 new ArrayList<String>(domains)); 3087 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3088 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3089 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3090 } else { 3091 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3092 + "' does not handle web links"); 3093 } 3094 } else { 3095 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3096 } 3097 } 3098 3099 scheduleWritePackageRestrictionsLocked(userId); 3100 scheduleWriteSettingsLocked(); 3101 } 3102 3103 private void applyFactoryDefaultBrowserLPw(int userId) { 3104 // The default browser app's package name is stored in a string resource, 3105 // with a product-specific overlay used for vendor customization. 3106 String browserPkg = mContext.getResources().getString( 3107 com.android.internal.R.string.default_browser); 3108 if (!TextUtils.isEmpty(browserPkg)) { 3109 // non-empty string => required to be a known package 3110 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3111 if (ps == null) { 3112 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3113 browserPkg = null; 3114 } else { 3115 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3116 } 3117 } 3118 3119 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3120 // default. If there's more than one, just leave everything alone. 3121 if (browserPkg == null) { 3122 calculateDefaultBrowserLPw(userId); 3123 } 3124 } 3125 3126 private void calculateDefaultBrowserLPw(int userId) { 3127 List<String> allBrowsers = resolveAllBrowserApps(userId); 3128 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3129 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3130 } 3131 3132 private List<String> resolveAllBrowserApps(int userId) { 3133 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3134 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3135 PackageManager.MATCH_ALL, userId); 3136 3137 final int count = list.size(); 3138 List<String> result = new ArrayList<String>(count); 3139 for (int i=0; i<count; i++) { 3140 ResolveInfo info = list.get(i); 3141 if (info.activityInfo == null 3142 || !info.handleAllWebDataURI 3143 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3144 || result.contains(info.activityInfo.packageName)) { 3145 continue; 3146 } 3147 result.add(info.activityInfo.packageName); 3148 } 3149 3150 return result; 3151 } 3152 3153 private boolean packageIsBrowser(String packageName, int userId) { 3154 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3155 PackageManager.MATCH_ALL, userId); 3156 final int N = list.size(); 3157 for (int i = 0; i < N; i++) { 3158 ResolveInfo info = list.get(i); 3159 if (packageName.equals(info.activityInfo.packageName)) { 3160 return true; 3161 } 3162 } 3163 return false; 3164 } 3165 3166 private void checkDefaultBrowser() { 3167 final int myUserId = UserHandle.myUserId(); 3168 final String packageName = getDefaultBrowserPackageName(myUserId); 3169 if (packageName != null) { 3170 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3171 if (info == null) { 3172 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3173 synchronized (mPackages) { 3174 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3175 } 3176 } 3177 } 3178 } 3179 3180 @Override 3181 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3182 throws RemoteException { 3183 try { 3184 return super.onTransact(code, data, reply, flags); 3185 } catch (RuntimeException e) { 3186 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3187 Slog.wtf(TAG, "Package Manager Crash", e); 3188 } 3189 throw e; 3190 } 3191 } 3192 3193 static int[] appendInts(int[] cur, int[] add) { 3194 if (add == null) return cur; 3195 if (cur == null) return add; 3196 final int N = add.length; 3197 for (int i=0; i<N; i++) { 3198 cur = appendInt(cur, add[i]); 3199 } 3200 return cur; 3201 } 3202 3203 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3204 if (!sUserManager.exists(userId)) return null; 3205 if (ps == null) { 3206 return null; 3207 } 3208 final PackageParser.Package p = ps.pkg; 3209 if (p == null) { 3210 return null; 3211 } 3212 3213 final PermissionsState permissionsState = ps.getPermissionsState(); 3214 3215 final int[] gids = permissionsState.computeGids(userId); 3216 final Set<String> permissions = permissionsState.getPermissions(userId); 3217 final PackageUserState state = ps.readUserState(userId); 3218 3219 return PackageParser.generatePackageInfo(p, gids, flags, 3220 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3221 } 3222 3223 @Override 3224 public void checkPackageStartable(String packageName, int userId) { 3225 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3226 3227 synchronized (mPackages) { 3228 final PackageSetting ps = mSettings.mPackages.get(packageName); 3229 if (ps == null) { 3230 throw new SecurityException("Package " + packageName + " was not found!"); 3231 } 3232 3233 if (!ps.getInstalled(userId)) { 3234 throw new SecurityException( 3235 "Package " + packageName + " was not installed for user " + userId + "!"); 3236 } 3237 3238 if (mSafeMode && !ps.isSystem()) { 3239 throw new SecurityException("Package " + packageName + " not a system app!"); 3240 } 3241 3242 if (mFrozenPackages.contains(packageName)) { 3243 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3244 } 3245 3246 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3247 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3248 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3249 } 3250 } 3251 } 3252 3253 @Override 3254 public boolean isPackageAvailable(String packageName, int userId) { 3255 if (!sUserManager.exists(userId)) return false; 3256 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3257 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3258 synchronized (mPackages) { 3259 PackageParser.Package p = mPackages.get(packageName); 3260 if (p != null) { 3261 final PackageSetting ps = (PackageSetting) p.mExtras; 3262 if (ps != null) { 3263 final PackageUserState state = ps.readUserState(userId); 3264 if (state != null) { 3265 return PackageParser.isAvailable(state); 3266 } 3267 } 3268 } 3269 } 3270 return false; 3271 } 3272 3273 @Override 3274 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3275 if (!sUserManager.exists(userId)) return null; 3276 flags = updateFlagsForPackage(flags, userId, packageName); 3277 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3278 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3279 // reader 3280 synchronized (mPackages) { 3281 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3282 PackageParser.Package p = null; 3283 if (matchFactoryOnly) { 3284 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3285 if (ps != null) { 3286 return generatePackageInfo(ps, flags, userId); 3287 } 3288 } 3289 if (p == null) { 3290 p = mPackages.get(packageName); 3291 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3292 return null; 3293 } 3294 } 3295 if (DEBUG_PACKAGE_INFO) 3296 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3297 if (p != null) { 3298 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3299 } 3300 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3301 final PackageSetting ps = mSettings.mPackages.get(packageName); 3302 return generatePackageInfo(ps, flags, userId); 3303 } 3304 } 3305 return null; 3306 } 3307 3308 @Override 3309 public String[] currentToCanonicalPackageNames(String[] names) { 3310 String[] out = new String[names.length]; 3311 // reader 3312 synchronized (mPackages) { 3313 for (int i=names.length-1; i>=0; i--) { 3314 PackageSetting ps = mSettings.mPackages.get(names[i]); 3315 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3316 } 3317 } 3318 return out; 3319 } 3320 3321 @Override 3322 public String[] canonicalToCurrentPackageNames(String[] names) { 3323 String[] out = new String[names.length]; 3324 // reader 3325 synchronized (mPackages) { 3326 for (int i=names.length-1; i>=0; i--) { 3327 String cur = mSettings.mRenamedPackages.get(names[i]); 3328 out[i] = cur != null ? cur : names[i]; 3329 } 3330 } 3331 return out; 3332 } 3333 3334 @Override 3335 public int getPackageUid(String packageName, int flags, int userId) { 3336 if (!sUserManager.exists(userId)) return -1; 3337 flags = updateFlagsForPackage(flags, userId, packageName); 3338 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3339 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3340 3341 // reader 3342 synchronized (mPackages) { 3343 final PackageParser.Package p = mPackages.get(packageName); 3344 if (p != null && p.isMatch(flags)) { 3345 return UserHandle.getUid(userId, p.applicationInfo.uid); 3346 } 3347 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3348 final PackageSetting ps = mSettings.mPackages.get(packageName); 3349 if (ps != null && ps.isMatch(flags)) { 3350 return UserHandle.getUid(userId, ps.appId); 3351 } 3352 } 3353 } 3354 3355 return -1; 3356 } 3357 3358 @Override 3359 public int[] getPackageGids(String packageName, int flags, int userId) { 3360 if (!sUserManager.exists(userId)) return null; 3361 flags = updateFlagsForPackage(flags, userId, packageName); 3362 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3363 false /* requireFullPermission */, false /* checkShell */, 3364 "getPackageGids"); 3365 3366 // reader 3367 synchronized (mPackages) { 3368 final PackageParser.Package p = mPackages.get(packageName); 3369 if (p != null && p.isMatch(flags)) { 3370 PackageSetting ps = (PackageSetting) p.mExtras; 3371 return ps.getPermissionsState().computeGids(userId); 3372 } 3373 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3374 final PackageSetting ps = mSettings.mPackages.get(packageName); 3375 if (ps != null && ps.isMatch(flags)) { 3376 return ps.getPermissionsState().computeGids(userId); 3377 } 3378 } 3379 } 3380 3381 return null; 3382 } 3383 3384 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3385 if (bp.perm != null) { 3386 return PackageParser.generatePermissionInfo(bp.perm, flags); 3387 } 3388 PermissionInfo pi = new PermissionInfo(); 3389 pi.name = bp.name; 3390 pi.packageName = bp.sourcePackage; 3391 pi.nonLocalizedLabel = bp.name; 3392 pi.protectionLevel = bp.protectionLevel; 3393 return pi; 3394 } 3395 3396 @Override 3397 public PermissionInfo getPermissionInfo(String name, int flags) { 3398 // reader 3399 synchronized (mPackages) { 3400 final BasePermission p = mSettings.mPermissions.get(name); 3401 if (p != null) { 3402 return generatePermissionInfo(p, flags); 3403 } 3404 return null; 3405 } 3406 } 3407 3408 @Override 3409 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3410 int flags) { 3411 // reader 3412 synchronized (mPackages) { 3413 if (group != null && !mPermissionGroups.containsKey(group)) { 3414 // This is thrown as NameNotFoundException 3415 return null; 3416 } 3417 3418 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3419 for (BasePermission p : mSettings.mPermissions.values()) { 3420 if (group == null) { 3421 if (p.perm == null || p.perm.info.group == null) { 3422 out.add(generatePermissionInfo(p, flags)); 3423 } 3424 } else { 3425 if (p.perm != null && group.equals(p.perm.info.group)) { 3426 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3427 } 3428 } 3429 } 3430 return new ParceledListSlice<>(out); 3431 } 3432 } 3433 3434 @Override 3435 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3436 // reader 3437 synchronized (mPackages) { 3438 return PackageParser.generatePermissionGroupInfo( 3439 mPermissionGroups.get(name), flags); 3440 } 3441 } 3442 3443 @Override 3444 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3445 // reader 3446 synchronized (mPackages) { 3447 final int N = mPermissionGroups.size(); 3448 ArrayList<PermissionGroupInfo> out 3449 = new ArrayList<PermissionGroupInfo>(N); 3450 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3451 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3452 } 3453 return new ParceledListSlice<>(out); 3454 } 3455 } 3456 3457 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3458 int userId) { 3459 if (!sUserManager.exists(userId)) return null; 3460 PackageSetting ps = mSettings.mPackages.get(packageName); 3461 if (ps != null) { 3462 if (ps.pkg == null) { 3463 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3464 if (pInfo != null) { 3465 return pInfo.applicationInfo; 3466 } 3467 return null; 3468 } 3469 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3470 ps.readUserState(userId), userId); 3471 } 3472 return null; 3473 } 3474 3475 @Override 3476 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3477 if (!sUserManager.exists(userId)) return null; 3478 flags = updateFlagsForApplication(flags, userId, packageName); 3479 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3480 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3481 // writer 3482 synchronized (mPackages) { 3483 PackageParser.Package p = mPackages.get(packageName); 3484 if (DEBUG_PACKAGE_INFO) Log.v( 3485 TAG, "getApplicationInfo " + packageName 3486 + ": " + p); 3487 if (p != null) { 3488 PackageSetting ps = mSettings.mPackages.get(packageName); 3489 if (ps == null) return null; 3490 // Note: isEnabledLP() does not apply here - always return info 3491 return PackageParser.generateApplicationInfo( 3492 p, flags, ps.readUserState(userId), userId); 3493 } 3494 if ("android".equals(packageName)||"system".equals(packageName)) { 3495 return mAndroidApplication; 3496 } 3497 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3498 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3499 } 3500 } 3501 return null; 3502 } 3503 3504 @Override 3505 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3506 final IPackageDataObserver observer) { 3507 mContext.enforceCallingOrSelfPermission( 3508 android.Manifest.permission.CLEAR_APP_CACHE, null); 3509 // Queue up an async operation since clearing cache may take a little while. 3510 mHandler.post(new Runnable() { 3511 public void run() { 3512 mHandler.removeCallbacks(this); 3513 boolean success = true; 3514 synchronized (mInstallLock) { 3515 try { 3516 mInstaller.freeCache(volumeUuid, freeStorageSize); 3517 } catch (InstallerException e) { 3518 Slog.w(TAG, "Couldn't clear application caches: " + e); 3519 success = false; 3520 } 3521 } 3522 if (observer != null) { 3523 try { 3524 observer.onRemoveCompleted(null, success); 3525 } catch (RemoteException e) { 3526 Slog.w(TAG, "RemoveException when invoking call back"); 3527 } 3528 } 3529 } 3530 }); 3531 } 3532 3533 @Override 3534 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3535 final IntentSender pi) { 3536 mContext.enforceCallingOrSelfPermission( 3537 android.Manifest.permission.CLEAR_APP_CACHE, null); 3538 // Queue up an async operation since clearing cache may take a little while. 3539 mHandler.post(new Runnable() { 3540 public void run() { 3541 mHandler.removeCallbacks(this); 3542 boolean success = true; 3543 synchronized (mInstallLock) { 3544 try { 3545 mInstaller.freeCache(volumeUuid, freeStorageSize); 3546 } catch (InstallerException e) { 3547 Slog.w(TAG, "Couldn't clear application caches: " + e); 3548 success = false; 3549 } 3550 } 3551 if(pi != null) { 3552 try { 3553 // Callback via pending intent 3554 int code = success ? 1 : 0; 3555 pi.sendIntent(null, code, null, 3556 null, null); 3557 } catch (SendIntentException e1) { 3558 Slog.i(TAG, "Failed to send pending intent"); 3559 } 3560 } 3561 } 3562 }); 3563 } 3564 3565 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3566 synchronized (mInstallLock) { 3567 try { 3568 mInstaller.freeCache(volumeUuid, freeStorageSize); 3569 } catch (InstallerException e) { 3570 throw new IOException("Failed to free enough space", e); 3571 } 3572 } 3573 } 3574 3575 /** 3576 * Update given flags based on encryption status of current user. 3577 */ 3578 private int updateFlags(int flags, int userId) { 3579 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3580 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3581 // Caller expressed an explicit opinion about what encryption 3582 // aware/unaware components they want to see, so fall through and 3583 // give them what they want 3584 } else { 3585 // Caller expressed no opinion, so match based on user state 3586 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3587 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3588 } else { 3589 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3590 } 3591 } 3592 return flags; 3593 } 3594 3595 private UserManagerInternal getUserManagerInternal() { 3596 if (mUserManagerInternal == null) { 3597 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3598 } 3599 return mUserManagerInternal; 3600 } 3601 3602 /** 3603 * Update given flags when being used to request {@link PackageInfo}. 3604 */ 3605 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3606 boolean triaged = true; 3607 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3608 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3609 // Caller is asking for component details, so they'd better be 3610 // asking for specific encryption matching behavior, or be triaged 3611 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3612 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3613 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3614 triaged = false; 3615 } 3616 } 3617 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3618 | PackageManager.MATCH_SYSTEM_ONLY 3619 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3620 triaged = false; 3621 } 3622 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3623 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3624 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3625 } 3626 return updateFlags(flags, userId); 3627 } 3628 3629 /** 3630 * Update given flags when being used to request {@link ApplicationInfo}. 3631 */ 3632 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3633 return updateFlagsForPackage(flags, userId, cookie); 3634 } 3635 3636 /** 3637 * Update given flags when being used to request {@link ComponentInfo}. 3638 */ 3639 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3640 if (cookie instanceof Intent) { 3641 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3642 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3643 } 3644 } 3645 3646 boolean triaged = true; 3647 // Caller is asking for component details, so they'd better be 3648 // asking for specific encryption matching behavior, or be triaged 3649 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3650 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3651 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3652 triaged = false; 3653 } 3654 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3655 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3656 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3657 } 3658 3659 return updateFlags(flags, userId); 3660 } 3661 3662 /** 3663 * Update given flags when being used to request {@link ResolveInfo}. 3664 */ 3665 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3666 // Safe mode means we shouldn't match any third-party components 3667 if (mSafeMode) { 3668 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3669 } 3670 3671 return updateFlagsForComponent(flags, userId, cookie); 3672 } 3673 3674 @Override 3675 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3676 if (!sUserManager.exists(userId)) return null; 3677 flags = updateFlagsForComponent(flags, userId, component); 3678 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3679 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3680 synchronized (mPackages) { 3681 PackageParser.Activity a = mActivities.mActivities.get(component); 3682 3683 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3684 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3685 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3686 if (ps == null) return null; 3687 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3688 userId); 3689 } 3690 if (mResolveComponentName.equals(component)) { 3691 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3692 new PackageUserState(), userId); 3693 } 3694 } 3695 return null; 3696 } 3697 3698 @Override 3699 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3700 String resolvedType) { 3701 synchronized (mPackages) { 3702 if (component.equals(mResolveComponentName)) { 3703 // The resolver supports EVERYTHING! 3704 return true; 3705 } 3706 PackageParser.Activity a = mActivities.mActivities.get(component); 3707 if (a == null) { 3708 return false; 3709 } 3710 for (int i=0; i<a.intents.size(); i++) { 3711 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3712 intent.getData(), intent.getCategories(), TAG) >= 0) { 3713 return true; 3714 } 3715 } 3716 return false; 3717 } 3718 } 3719 3720 @Override 3721 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3722 if (!sUserManager.exists(userId)) return null; 3723 flags = updateFlagsForComponent(flags, userId, component); 3724 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3725 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3726 synchronized (mPackages) { 3727 PackageParser.Activity a = mReceivers.mActivities.get(component); 3728 if (DEBUG_PACKAGE_INFO) Log.v( 3729 TAG, "getReceiverInfo " + component + ": " + a); 3730 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3731 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3732 if (ps == null) return null; 3733 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3734 userId); 3735 } 3736 } 3737 return null; 3738 } 3739 3740 @Override 3741 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3742 if (!sUserManager.exists(userId)) return null; 3743 flags = updateFlagsForComponent(flags, userId, component); 3744 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3745 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3746 synchronized (mPackages) { 3747 PackageParser.Service s = mServices.mServices.get(component); 3748 if (DEBUG_PACKAGE_INFO) Log.v( 3749 TAG, "getServiceInfo " + component + ": " + s); 3750 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3751 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3752 if (ps == null) return null; 3753 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3754 userId); 3755 } 3756 } 3757 return null; 3758 } 3759 3760 @Override 3761 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3762 if (!sUserManager.exists(userId)) return null; 3763 flags = updateFlagsForComponent(flags, userId, component); 3764 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3765 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3766 synchronized (mPackages) { 3767 PackageParser.Provider p = mProviders.mProviders.get(component); 3768 if (DEBUG_PACKAGE_INFO) Log.v( 3769 TAG, "getProviderInfo " + component + ": " + p); 3770 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3771 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3772 if (ps == null) return null; 3773 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3774 userId); 3775 } 3776 } 3777 return null; 3778 } 3779 3780 @Override 3781 public String[] getSystemSharedLibraryNames() { 3782 Set<String> libSet; 3783 synchronized (mPackages) { 3784 libSet = mSharedLibraries.keySet(); 3785 int size = libSet.size(); 3786 if (size > 0) { 3787 String[] libs = new String[size]; 3788 libSet.toArray(libs); 3789 return libs; 3790 } 3791 } 3792 return null; 3793 } 3794 3795 @Override 3796 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3797 synchronized (mPackages) { 3798 return mServicesSystemSharedLibraryPackageName; 3799 } 3800 } 3801 3802 @Override 3803 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3804 synchronized (mPackages) { 3805 return mSharedSystemSharedLibraryPackageName; 3806 } 3807 } 3808 3809 @Override 3810 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3811 synchronized (mPackages) { 3812 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3813 3814 final FeatureInfo fi = new FeatureInfo(); 3815 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3816 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3817 res.add(fi); 3818 3819 return new ParceledListSlice<>(res); 3820 } 3821 } 3822 3823 @Override 3824 public boolean hasSystemFeature(String name, int version) { 3825 synchronized (mPackages) { 3826 final FeatureInfo feat = mAvailableFeatures.get(name); 3827 if (feat == null) { 3828 return false; 3829 } else { 3830 return feat.version >= version; 3831 } 3832 } 3833 } 3834 3835 @Override 3836 public int checkPermission(String permName, String pkgName, int userId) { 3837 if (!sUserManager.exists(userId)) { 3838 return PackageManager.PERMISSION_DENIED; 3839 } 3840 3841 synchronized (mPackages) { 3842 final PackageParser.Package p = mPackages.get(pkgName); 3843 if (p != null && p.mExtras != null) { 3844 final PackageSetting ps = (PackageSetting) p.mExtras; 3845 final PermissionsState permissionsState = ps.getPermissionsState(); 3846 if (permissionsState.hasPermission(permName, userId)) { 3847 return PackageManager.PERMISSION_GRANTED; 3848 } 3849 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3850 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3851 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3852 return PackageManager.PERMISSION_GRANTED; 3853 } 3854 } 3855 } 3856 3857 return PackageManager.PERMISSION_DENIED; 3858 } 3859 3860 @Override 3861 public int checkUidPermission(String permName, int uid) { 3862 final int userId = UserHandle.getUserId(uid); 3863 3864 if (!sUserManager.exists(userId)) { 3865 return PackageManager.PERMISSION_DENIED; 3866 } 3867 3868 synchronized (mPackages) { 3869 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3870 if (obj != null) { 3871 final SettingBase ps = (SettingBase) obj; 3872 final PermissionsState permissionsState = ps.getPermissionsState(); 3873 if (permissionsState.hasPermission(permName, userId)) { 3874 return PackageManager.PERMISSION_GRANTED; 3875 } 3876 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3877 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3878 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3879 return PackageManager.PERMISSION_GRANTED; 3880 } 3881 } else { 3882 ArraySet<String> perms = mSystemPermissions.get(uid); 3883 if (perms != null) { 3884 if (perms.contains(permName)) { 3885 return PackageManager.PERMISSION_GRANTED; 3886 } 3887 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3888 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3889 return PackageManager.PERMISSION_GRANTED; 3890 } 3891 } 3892 } 3893 } 3894 3895 return PackageManager.PERMISSION_DENIED; 3896 } 3897 3898 @Override 3899 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3900 if (UserHandle.getCallingUserId() != userId) { 3901 mContext.enforceCallingPermission( 3902 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3903 "isPermissionRevokedByPolicy for user " + userId); 3904 } 3905 3906 if (checkPermission(permission, packageName, userId) 3907 == PackageManager.PERMISSION_GRANTED) { 3908 return false; 3909 } 3910 3911 final long identity = Binder.clearCallingIdentity(); 3912 try { 3913 final int flags = getPermissionFlags(permission, packageName, userId); 3914 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3915 } finally { 3916 Binder.restoreCallingIdentity(identity); 3917 } 3918 } 3919 3920 @Override 3921 public String getPermissionControllerPackageName() { 3922 synchronized (mPackages) { 3923 return mRequiredInstallerPackage; 3924 } 3925 } 3926 3927 /** 3928 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3929 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3930 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3931 * @param message the message to log on security exception 3932 */ 3933 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3934 boolean checkShell, String message) { 3935 if (userId < 0) { 3936 throw new IllegalArgumentException("Invalid userId " + userId); 3937 } 3938 if (checkShell) { 3939 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3940 } 3941 if (userId == UserHandle.getUserId(callingUid)) return; 3942 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3943 if (requireFullPermission) { 3944 mContext.enforceCallingOrSelfPermission( 3945 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3946 } else { 3947 try { 3948 mContext.enforceCallingOrSelfPermission( 3949 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3950 } catch (SecurityException se) { 3951 mContext.enforceCallingOrSelfPermission( 3952 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3953 } 3954 } 3955 } 3956 } 3957 3958 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3959 if (callingUid == Process.SHELL_UID) { 3960 if (userHandle >= 0 3961 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3962 throw new SecurityException("Shell does not have permission to access user " 3963 + userHandle); 3964 } else if (userHandle < 0) { 3965 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3966 + Debug.getCallers(3)); 3967 } 3968 } 3969 } 3970 3971 private BasePermission findPermissionTreeLP(String permName) { 3972 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3973 if (permName.startsWith(bp.name) && 3974 permName.length() > bp.name.length() && 3975 permName.charAt(bp.name.length()) == '.') { 3976 return bp; 3977 } 3978 } 3979 return null; 3980 } 3981 3982 private BasePermission checkPermissionTreeLP(String permName) { 3983 if (permName != null) { 3984 BasePermission bp = findPermissionTreeLP(permName); 3985 if (bp != null) { 3986 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3987 return bp; 3988 } 3989 throw new SecurityException("Calling uid " 3990 + Binder.getCallingUid() 3991 + " is not allowed to add to permission tree " 3992 + bp.name + " owned by uid " + bp.uid); 3993 } 3994 } 3995 throw new SecurityException("No permission tree found for " + permName); 3996 } 3997 3998 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3999 if (s1 == null) { 4000 return s2 == null; 4001 } 4002 if (s2 == null) { 4003 return false; 4004 } 4005 if (s1.getClass() != s2.getClass()) { 4006 return false; 4007 } 4008 return s1.equals(s2); 4009 } 4010 4011 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 4012 if (pi1.icon != pi2.icon) return false; 4013 if (pi1.logo != pi2.logo) return false; 4014 if (pi1.protectionLevel != pi2.protectionLevel) return false; 4015 if (!compareStrings(pi1.name, pi2.name)) return false; 4016 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 4017 // We'll take care of setting this one. 4018 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 4019 // These are not currently stored in settings. 4020 //if (!compareStrings(pi1.group, pi2.group)) return false; 4021 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 4022 //if (pi1.labelRes != pi2.labelRes) return false; 4023 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 4024 return true; 4025 } 4026 4027 int permissionInfoFootprint(PermissionInfo info) { 4028 int size = info.name.length(); 4029 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 4030 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 4031 return size; 4032 } 4033 4034 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 4035 int size = 0; 4036 for (BasePermission perm : mSettings.mPermissions.values()) { 4037 if (perm.uid == tree.uid) { 4038 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4039 } 4040 } 4041 return size; 4042 } 4043 4044 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4045 // We calculate the max size of permissions defined by this uid and throw 4046 // if that plus the size of 'info' would exceed our stated maximum. 4047 if (tree.uid != Process.SYSTEM_UID) { 4048 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4049 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4050 throw new SecurityException("Permission tree size cap exceeded"); 4051 } 4052 } 4053 } 4054 4055 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4056 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4057 throw new SecurityException("Label must be specified in permission"); 4058 } 4059 BasePermission tree = checkPermissionTreeLP(info.name); 4060 BasePermission bp = mSettings.mPermissions.get(info.name); 4061 boolean added = bp == null; 4062 boolean changed = true; 4063 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4064 if (added) { 4065 enforcePermissionCapLocked(info, tree); 4066 bp = new BasePermission(info.name, tree.sourcePackage, 4067 BasePermission.TYPE_DYNAMIC); 4068 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4069 throw new SecurityException( 4070 "Not allowed to modify non-dynamic permission " 4071 + info.name); 4072 } else { 4073 if (bp.protectionLevel == fixedLevel 4074 && bp.perm.owner.equals(tree.perm.owner) 4075 && bp.uid == tree.uid 4076 && comparePermissionInfos(bp.perm.info, info)) { 4077 changed = false; 4078 } 4079 } 4080 bp.protectionLevel = fixedLevel; 4081 info = new PermissionInfo(info); 4082 info.protectionLevel = fixedLevel; 4083 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4084 bp.perm.info.packageName = tree.perm.info.packageName; 4085 bp.uid = tree.uid; 4086 if (added) { 4087 mSettings.mPermissions.put(info.name, bp); 4088 } 4089 if (changed) { 4090 if (!async) { 4091 mSettings.writeLPr(); 4092 } else { 4093 scheduleWriteSettingsLocked(); 4094 } 4095 } 4096 return added; 4097 } 4098 4099 @Override 4100 public boolean addPermission(PermissionInfo info) { 4101 synchronized (mPackages) { 4102 return addPermissionLocked(info, false); 4103 } 4104 } 4105 4106 @Override 4107 public boolean addPermissionAsync(PermissionInfo info) { 4108 synchronized (mPackages) { 4109 return addPermissionLocked(info, true); 4110 } 4111 } 4112 4113 @Override 4114 public void removePermission(String name) { 4115 synchronized (mPackages) { 4116 checkPermissionTreeLP(name); 4117 BasePermission bp = mSettings.mPermissions.get(name); 4118 if (bp != null) { 4119 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4120 throw new SecurityException( 4121 "Not allowed to modify non-dynamic permission " 4122 + name); 4123 } 4124 mSettings.mPermissions.remove(name); 4125 mSettings.writeLPr(); 4126 } 4127 } 4128 } 4129 4130 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4131 BasePermission bp) { 4132 int index = pkg.requestedPermissions.indexOf(bp.name); 4133 if (index == -1) { 4134 throw new SecurityException("Package " + pkg.packageName 4135 + " has not requested permission " + bp.name); 4136 } 4137 if (!bp.isRuntime() && !bp.isDevelopment()) { 4138 throw new SecurityException("Permission " + bp.name 4139 + " is not a changeable permission type"); 4140 } 4141 } 4142 4143 @Override 4144 public void grantRuntimePermission(String packageName, String name, final int userId) { 4145 if (!sUserManager.exists(userId)) { 4146 Log.e(TAG, "No such user:" + userId); 4147 return; 4148 } 4149 4150 mContext.enforceCallingOrSelfPermission( 4151 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4152 "grantRuntimePermission"); 4153 4154 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4155 true /* requireFullPermission */, true /* checkShell */, 4156 "grantRuntimePermission"); 4157 4158 final int uid; 4159 final SettingBase sb; 4160 4161 synchronized (mPackages) { 4162 final PackageParser.Package pkg = mPackages.get(packageName); 4163 if (pkg == null) { 4164 throw new IllegalArgumentException("Unknown package: " + packageName); 4165 } 4166 4167 final BasePermission bp = mSettings.mPermissions.get(name); 4168 if (bp == null) { 4169 throw new IllegalArgumentException("Unknown permission: " + name); 4170 } 4171 4172 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4173 4174 // If a permission review is required for legacy apps we represent 4175 // their permissions as always granted runtime ones since we need 4176 // to keep the review required permission flag per user while an 4177 // install permission's state is shared across all users. 4178 if (Build.PERMISSIONS_REVIEW_REQUIRED 4179 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4180 && bp.isRuntime()) { 4181 return; 4182 } 4183 4184 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4185 sb = (SettingBase) pkg.mExtras; 4186 if (sb == null) { 4187 throw new IllegalArgumentException("Unknown package: " + packageName); 4188 } 4189 4190 final PermissionsState permissionsState = sb.getPermissionsState(); 4191 4192 final int flags = permissionsState.getPermissionFlags(name, userId); 4193 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4194 throw new SecurityException("Cannot grant system fixed permission " 4195 + name + " for package " + packageName); 4196 } 4197 4198 if (bp.isDevelopment()) { 4199 // Development permissions must be handled specially, since they are not 4200 // normal runtime permissions. For now they apply to all users. 4201 if (permissionsState.grantInstallPermission(bp) != 4202 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4203 scheduleWriteSettingsLocked(); 4204 } 4205 return; 4206 } 4207 4208 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4209 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4210 return; 4211 } 4212 4213 final int result = permissionsState.grantRuntimePermission(bp, userId); 4214 switch (result) { 4215 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4216 return; 4217 } 4218 4219 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4220 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4221 mHandler.post(new Runnable() { 4222 @Override 4223 public void run() { 4224 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4225 } 4226 }); 4227 } 4228 break; 4229 } 4230 4231 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4232 4233 // Not critical if that is lost - app has to request again. 4234 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4235 } 4236 4237 // Only need to do this if user is initialized. Otherwise it's a new user 4238 // and there are no processes running as the user yet and there's no need 4239 // to make an expensive call to remount processes for the changed permissions. 4240 if (READ_EXTERNAL_STORAGE.equals(name) 4241 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4242 final long token = Binder.clearCallingIdentity(); 4243 try { 4244 if (sUserManager.isInitialized(userId)) { 4245 MountServiceInternal mountServiceInternal = LocalServices.getService( 4246 MountServiceInternal.class); 4247 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4248 } 4249 } finally { 4250 Binder.restoreCallingIdentity(token); 4251 } 4252 } 4253 } 4254 4255 @Override 4256 public void revokeRuntimePermission(String packageName, String name, int userId) { 4257 if (!sUserManager.exists(userId)) { 4258 Log.e(TAG, "No such user:" + userId); 4259 return; 4260 } 4261 4262 mContext.enforceCallingOrSelfPermission( 4263 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4264 "revokeRuntimePermission"); 4265 4266 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4267 true /* requireFullPermission */, true /* checkShell */, 4268 "revokeRuntimePermission"); 4269 4270 final int appId; 4271 4272 synchronized (mPackages) { 4273 final PackageParser.Package pkg = mPackages.get(packageName); 4274 if (pkg == null) { 4275 throw new IllegalArgumentException("Unknown package: " + packageName); 4276 } 4277 4278 final BasePermission bp = mSettings.mPermissions.get(name); 4279 if (bp == null) { 4280 throw new IllegalArgumentException("Unknown permission: " + name); 4281 } 4282 4283 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4284 4285 // If a permission review is required for legacy apps we represent 4286 // their permissions as always granted runtime ones since we need 4287 // to keep the review required permission flag per user while an 4288 // install permission's state is shared across all users. 4289 if (Build.PERMISSIONS_REVIEW_REQUIRED 4290 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4291 && bp.isRuntime()) { 4292 return; 4293 } 4294 4295 SettingBase sb = (SettingBase) pkg.mExtras; 4296 if (sb == null) { 4297 throw new IllegalArgumentException("Unknown package: " + packageName); 4298 } 4299 4300 final PermissionsState permissionsState = sb.getPermissionsState(); 4301 4302 final int flags = permissionsState.getPermissionFlags(name, userId); 4303 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4304 throw new SecurityException("Cannot revoke system fixed permission " 4305 + name + " for package " + packageName); 4306 } 4307 4308 if (bp.isDevelopment()) { 4309 // Development permissions must be handled specially, since they are not 4310 // normal runtime permissions. For now they apply to all users. 4311 if (permissionsState.revokeInstallPermission(bp) != 4312 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4313 scheduleWriteSettingsLocked(); 4314 } 4315 return; 4316 } 4317 4318 if (permissionsState.revokeRuntimePermission(bp, userId) == 4319 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4320 return; 4321 } 4322 4323 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4324 4325 // Critical, after this call app should never have the permission. 4326 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4327 4328 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4329 } 4330 4331 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4332 } 4333 4334 @Override 4335 public void resetRuntimePermissions() { 4336 mContext.enforceCallingOrSelfPermission( 4337 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4338 "revokeRuntimePermission"); 4339 4340 int callingUid = Binder.getCallingUid(); 4341 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4342 mContext.enforceCallingOrSelfPermission( 4343 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4344 "resetRuntimePermissions"); 4345 } 4346 4347 synchronized (mPackages) { 4348 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4349 for (int userId : UserManagerService.getInstance().getUserIds()) { 4350 final int packageCount = mPackages.size(); 4351 for (int i = 0; i < packageCount; i++) { 4352 PackageParser.Package pkg = mPackages.valueAt(i); 4353 if (!(pkg.mExtras instanceof PackageSetting)) { 4354 continue; 4355 } 4356 PackageSetting ps = (PackageSetting) pkg.mExtras; 4357 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4358 } 4359 } 4360 } 4361 } 4362 4363 @Override 4364 public int getPermissionFlags(String name, String packageName, int userId) { 4365 if (!sUserManager.exists(userId)) { 4366 return 0; 4367 } 4368 4369 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4370 4371 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4372 true /* requireFullPermission */, false /* checkShell */, 4373 "getPermissionFlags"); 4374 4375 synchronized (mPackages) { 4376 final PackageParser.Package pkg = mPackages.get(packageName); 4377 if (pkg == null) { 4378 return 0; 4379 } 4380 4381 final BasePermission bp = mSettings.mPermissions.get(name); 4382 if (bp == null) { 4383 return 0; 4384 } 4385 4386 SettingBase sb = (SettingBase) pkg.mExtras; 4387 if (sb == null) { 4388 return 0; 4389 } 4390 4391 PermissionsState permissionsState = sb.getPermissionsState(); 4392 return permissionsState.getPermissionFlags(name, userId); 4393 } 4394 } 4395 4396 @Override 4397 public void updatePermissionFlags(String name, String packageName, int flagMask, 4398 int flagValues, int userId) { 4399 if (!sUserManager.exists(userId)) { 4400 return; 4401 } 4402 4403 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4404 4405 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4406 true /* requireFullPermission */, true /* checkShell */, 4407 "updatePermissionFlags"); 4408 4409 // Only the system can change these flags and nothing else. 4410 if (getCallingUid() != Process.SYSTEM_UID) { 4411 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4412 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4413 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4414 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4415 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4416 } 4417 4418 synchronized (mPackages) { 4419 final PackageParser.Package pkg = mPackages.get(packageName); 4420 if (pkg == null) { 4421 throw new IllegalArgumentException("Unknown package: " + packageName); 4422 } 4423 4424 final BasePermission bp = mSettings.mPermissions.get(name); 4425 if (bp == null) { 4426 throw new IllegalArgumentException("Unknown permission: " + name); 4427 } 4428 4429 SettingBase sb = (SettingBase) pkg.mExtras; 4430 if (sb == null) { 4431 throw new IllegalArgumentException("Unknown package: " + packageName); 4432 } 4433 4434 PermissionsState permissionsState = sb.getPermissionsState(); 4435 4436 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4437 4438 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4439 // Install and runtime permissions are stored in different places, 4440 // so figure out what permission changed and persist the change. 4441 if (permissionsState.getInstallPermissionState(name) != null) { 4442 scheduleWriteSettingsLocked(); 4443 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4444 || hadState) { 4445 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4446 } 4447 } 4448 } 4449 } 4450 4451 /** 4452 * Update the permission flags for all packages and runtime permissions of a user in order 4453 * to allow device or profile owner to remove POLICY_FIXED. 4454 */ 4455 @Override 4456 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4457 if (!sUserManager.exists(userId)) { 4458 return; 4459 } 4460 4461 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4462 4463 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4464 true /* requireFullPermission */, true /* checkShell */, 4465 "updatePermissionFlagsForAllApps"); 4466 4467 // Only the system can change system fixed flags. 4468 if (getCallingUid() != Process.SYSTEM_UID) { 4469 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4470 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4471 } 4472 4473 synchronized (mPackages) { 4474 boolean changed = false; 4475 final int packageCount = mPackages.size(); 4476 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4477 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4478 SettingBase sb = (SettingBase) pkg.mExtras; 4479 if (sb == null) { 4480 continue; 4481 } 4482 PermissionsState permissionsState = sb.getPermissionsState(); 4483 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4484 userId, flagMask, flagValues); 4485 } 4486 if (changed) { 4487 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4488 } 4489 } 4490 } 4491 4492 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4493 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4494 != PackageManager.PERMISSION_GRANTED 4495 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4496 != PackageManager.PERMISSION_GRANTED) { 4497 throw new SecurityException(message + " requires " 4498 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4499 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4500 } 4501 } 4502 4503 @Override 4504 public boolean shouldShowRequestPermissionRationale(String permissionName, 4505 String packageName, int userId) { 4506 if (UserHandle.getCallingUserId() != userId) { 4507 mContext.enforceCallingPermission( 4508 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4509 "canShowRequestPermissionRationale for user " + userId); 4510 } 4511 4512 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4513 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4514 return false; 4515 } 4516 4517 if (checkPermission(permissionName, packageName, userId) 4518 == PackageManager.PERMISSION_GRANTED) { 4519 return false; 4520 } 4521 4522 final int flags; 4523 4524 final long identity = Binder.clearCallingIdentity(); 4525 try { 4526 flags = getPermissionFlags(permissionName, 4527 packageName, userId); 4528 } finally { 4529 Binder.restoreCallingIdentity(identity); 4530 } 4531 4532 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4533 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4534 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4535 4536 if ((flags & fixedFlags) != 0) { 4537 return false; 4538 } 4539 4540 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4541 } 4542 4543 @Override 4544 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4545 mContext.enforceCallingOrSelfPermission( 4546 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4547 "addOnPermissionsChangeListener"); 4548 4549 synchronized (mPackages) { 4550 mOnPermissionChangeListeners.addListenerLocked(listener); 4551 } 4552 } 4553 4554 @Override 4555 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4556 synchronized (mPackages) { 4557 mOnPermissionChangeListeners.removeListenerLocked(listener); 4558 } 4559 } 4560 4561 @Override 4562 public boolean isProtectedBroadcast(String actionName) { 4563 synchronized (mPackages) { 4564 if (mProtectedBroadcasts.contains(actionName)) { 4565 return true; 4566 } else if (actionName != null) { 4567 // TODO: remove these terrible hacks 4568 if (actionName.startsWith("android.net.netmon.lingerExpired") 4569 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4570 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4571 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4572 return true; 4573 } 4574 } 4575 } 4576 return false; 4577 } 4578 4579 @Override 4580 public int checkSignatures(String pkg1, String pkg2) { 4581 synchronized (mPackages) { 4582 final PackageParser.Package p1 = mPackages.get(pkg1); 4583 final PackageParser.Package p2 = mPackages.get(pkg2); 4584 if (p1 == null || p1.mExtras == null 4585 || p2 == null || p2.mExtras == null) { 4586 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4587 } 4588 return compareSignatures(p1.mSignatures, p2.mSignatures); 4589 } 4590 } 4591 4592 @Override 4593 public int checkUidSignatures(int uid1, int uid2) { 4594 // Map to base uids. 4595 uid1 = UserHandle.getAppId(uid1); 4596 uid2 = UserHandle.getAppId(uid2); 4597 // reader 4598 synchronized (mPackages) { 4599 Signature[] s1; 4600 Signature[] s2; 4601 Object obj = mSettings.getUserIdLPr(uid1); 4602 if (obj != null) { 4603 if (obj instanceof SharedUserSetting) { 4604 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4605 } else if (obj instanceof PackageSetting) { 4606 s1 = ((PackageSetting)obj).signatures.mSignatures; 4607 } else { 4608 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4609 } 4610 } else { 4611 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4612 } 4613 obj = mSettings.getUserIdLPr(uid2); 4614 if (obj != null) { 4615 if (obj instanceof SharedUserSetting) { 4616 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4617 } else if (obj instanceof PackageSetting) { 4618 s2 = ((PackageSetting)obj).signatures.mSignatures; 4619 } else { 4620 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4621 } 4622 } else { 4623 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4624 } 4625 return compareSignatures(s1, s2); 4626 } 4627 } 4628 4629 /** 4630 * This method should typically only be used when granting or revoking 4631 * permissions, since the app may immediately restart after this call. 4632 * <p> 4633 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4634 * guard your work against the app being relaunched. 4635 */ 4636 private void killUid(int appId, int userId, String reason) { 4637 final long identity = Binder.clearCallingIdentity(); 4638 try { 4639 IActivityManager am = ActivityManagerNative.getDefault(); 4640 if (am != null) { 4641 try { 4642 am.killUid(appId, userId, reason); 4643 } catch (RemoteException e) { 4644 /* ignore - same process */ 4645 } 4646 } 4647 } finally { 4648 Binder.restoreCallingIdentity(identity); 4649 } 4650 } 4651 4652 /** 4653 * Compares two sets of signatures. Returns: 4654 * <br /> 4655 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4656 * <br /> 4657 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4658 * <br /> 4659 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4660 * <br /> 4661 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4662 * <br /> 4663 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4664 */ 4665 static int compareSignatures(Signature[] s1, Signature[] s2) { 4666 if (s1 == null) { 4667 return s2 == null 4668 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4669 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4670 } 4671 4672 if (s2 == null) { 4673 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4674 } 4675 4676 if (s1.length != s2.length) { 4677 return PackageManager.SIGNATURE_NO_MATCH; 4678 } 4679 4680 // Since both signature sets are of size 1, we can compare without HashSets. 4681 if (s1.length == 1) { 4682 return s1[0].equals(s2[0]) ? 4683 PackageManager.SIGNATURE_MATCH : 4684 PackageManager.SIGNATURE_NO_MATCH; 4685 } 4686 4687 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4688 for (Signature sig : s1) { 4689 set1.add(sig); 4690 } 4691 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4692 for (Signature sig : s2) { 4693 set2.add(sig); 4694 } 4695 // Make sure s2 contains all signatures in s1. 4696 if (set1.equals(set2)) { 4697 return PackageManager.SIGNATURE_MATCH; 4698 } 4699 return PackageManager.SIGNATURE_NO_MATCH; 4700 } 4701 4702 /** 4703 * If the database version for this type of package (internal storage or 4704 * external storage) is less than the version where package signatures 4705 * were updated, return true. 4706 */ 4707 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4708 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4709 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4710 } 4711 4712 /** 4713 * Used for backward compatibility to make sure any packages with 4714 * certificate chains get upgraded to the new style. {@code existingSigs} 4715 * will be in the old format (since they were stored on disk from before the 4716 * system upgrade) and {@code scannedSigs} will be in the newer format. 4717 */ 4718 private int compareSignaturesCompat(PackageSignatures existingSigs, 4719 PackageParser.Package scannedPkg) { 4720 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4721 return PackageManager.SIGNATURE_NO_MATCH; 4722 } 4723 4724 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4725 for (Signature sig : existingSigs.mSignatures) { 4726 existingSet.add(sig); 4727 } 4728 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4729 for (Signature sig : scannedPkg.mSignatures) { 4730 try { 4731 Signature[] chainSignatures = sig.getChainSignatures(); 4732 for (Signature chainSig : chainSignatures) { 4733 scannedCompatSet.add(chainSig); 4734 } 4735 } catch (CertificateEncodingException e) { 4736 scannedCompatSet.add(sig); 4737 } 4738 } 4739 /* 4740 * Make sure the expanded scanned set contains all signatures in the 4741 * existing one. 4742 */ 4743 if (scannedCompatSet.equals(existingSet)) { 4744 // Migrate the old signatures to the new scheme. 4745 existingSigs.assignSignatures(scannedPkg.mSignatures); 4746 // The new KeySets will be re-added later in the scanning process. 4747 synchronized (mPackages) { 4748 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4749 } 4750 return PackageManager.SIGNATURE_MATCH; 4751 } 4752 return PackageManager.SIGNATURE_NO_MATCH; 4753 } 4754 4755 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4756 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4757 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4758 } 4759 4760 private int compareSignaturesRecover(PackageSignatures existingSigs, 4761 PackageParser.Package scannedPkg) { 4762 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4763 return PackageManager.SIGNATURE_NO_MATCH; 4764 } 4765 4766 String msg = null; 4767 try { 4768 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4769 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4770 + scannedPkg.packageName); 4771 return PackageManager.SIGNATURE_MATCH; 4772 } 4773 } catch (CertificateException e) { 4774 msg = e.getMessage(); 4775 } 4776 4777 logCriticalInfo(Log.INFO, 4778 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4779 return PackageManager.SIGNATURE_NO_MATCH; 4780 } 4781 4782 @Override 4783 public List<String> getAllPackages() { 4784 synchronized (mPackages) { 4785 return new ArrayList<String>(mPackages.keySet()); 4786 } 4787 } 4788 4789 @Override 4790 public String[] getPackagesForUid(int uid) { 4791 uid = UserHandle.getAppId(uid); 4792 // reader 4793 synchronized (mPackages) { 4794 Object obj = mSettings.getUserIdLPr(uid); 4795 if (obj instanceof SharedUserSetting) { 4796 final SharedUserSetting sus = (SharedUserSetting) obj; 4797 final int N = sus.packages.size(); 4798 final String[] res = new String[N]; 4799 for (int i = 0; i < N; i++) { 4800 res[i] = sus.packages.valueAt(i).name; 4801 } 4802 return res; 4803 } else if (obj instanceof PackageSetting) { 4804 final PackageSetting ps = (PackageSetting) obj; 4805 return new String[] { ps.name }; 4806 } 4807 } 4808 return null; 4809 } 4810 4811 @Override 4812 public String getNameForUid(int uid) { 4813 // reader 4814 synchronized (mPackages) { 4815 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4816 if (obj instanceof SharedUserSetting) { 4817 final SharedUserSetting sus = (SharedUserSetting) obj; 4818 return sus.name + ":" + sus.userId; 4819 } else if (obj instanceof PackageSetting) { 4820 final PackageSetting ps = (PackageSetting) obj; 4821 return ps.name; 4822 } 4823 } 4824 return null; 4825 } 4826 4827 @Override 4828 public int getUidForSharedUser(String sharedUserName) { 4829 if(sharedUserName == null) { 4830 return -1; 4831 } 4832 // reader 4833 synchronized (mPackages) { 4834 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4835 if (suid == null) { 4836 return -1; 4837 } 4838 return suid.userId; 4839 } 4840 } 4841 4842 @Override 4843 public int getFlagsForUid(int uid) { 4844 synchronized (mPackages) { 4845 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4846 if (obj instanceof SharedUserSetting) { 4847 final SharedUserSetting sus = (SharedUserSetting) obj; 4848 return sus.pkgFlags; 4849 } else if (obj instanceof PackageSetting) { 4850 final PackageSetting ps = (PackageSetting) obj; 4851 return ps.pkgFlags; 4852 } 4853 } 4854 return 0; 4855 } 4856 4857 @Override 4858 public int getPrivateFlagsForUid(int uid) { 4859 synchronized (mPackages) { 4860 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4861 if (obj instanceof SharedUserSetting) { 4862 final SharedUserSetting sus = (SharedUserSetting) obj; 4863 return sus.pkgPrivateFlags; 4864 } else if (obj instanceof PackageSetting) { 4865 final PackageSetting ps = (PackageSetting) obj; 4866 return ps.pkgPrivateFlags; 4867 } 4868 } 4869 return 0; 4870 } 4871 4872 @Override 4873 public boolean isUidPrivileged(int uid) { 4874 uid = UserHandle.getAppId(uid); 4875 // reader 4876 synchronized (mPackages) { 4877 Object obj = mSettings.getUserIdLPr(uid); 4878 if (obj instanceof SharedUserSetting) { 4879 final SharedUserSetting sus = (SharedUserSetting) obj; 4880 final Iterator<PackageSetting> it = sus.packages.iterator(); 4881 while (it.hasNext()) { 4882 if (it.next().isPrivileged()) { 4883 return true; 4884 } 4885 } 4886 } else if (obj instanceof PackageSetting) { 4887 final PackageSetting ps = (PackageSetting) obj; 4888 return ps.isPrivileged(); 4889 } 4890 } 4891 return false; 4892 } 4893 4894 @Override 4895 public String[] getAppOpPermissionPackages(String permissionName) { 4896 synchronized (mPackages) { 4897 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4898 if (pkgs == null) { 4899 return null; 4900 } 4901 return pkgs.toArray(new String[pkgs.size()]); 4902 } 4903 } 4904 4905 @Override 4906 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4907 int flags, int userId) { 4908 try { 4909 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4910 4911 if (!sUserManager.exists(userId)) return null; 4912 flags = updateFlagsForResolve(flags, userId, intent); 4913 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4914 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4915 4916 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4917 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4918 flags, userId); 4919 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4920 4921 final ResolveInfo bestChoice = 4922 chooseBestActivity(intent, resolvedType, flags, query, userId); 4923 4924 if (isEphemeralAllowed(intent, query, userId)) { 4925 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4926 final EphemeralResolveInfo ai = 4927 getEphemeralResolveInfo(intent, resolvedType, userId); 4928 if (ai != null) { 4929 if (DEBUG_EPHEMERAL) { 4930 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4931 } 4932 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4933 bestChoice.ephemeralResolveInfo = ai; 4934 } 4935 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4936 } 4937 return bestChoice; 4938 } finally { 4939 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4940 } 4941 } 4942 4943 @Override 4944 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4945 IntentFilter filter, int match, ComponentName activity) { 4946 final int userId = UserHandle.getCallingUserId(); 4947 if (DEBUG_PREFERRED) { 4948 Log.v(TAG, "setLastChosenActivity intent=" + intent 4949 + " resolvedType=" + resolvedType 4950 + " flags=" + flags 4951 + " filter=" + filter 4952 + " match=" + match 4953 + " activity=" + activity); 4954 filter.dump(new PrintStreamPrinter(System.out), " "); 4955 } 4956 intent.setComponent(null); 4957 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4958 userId); 4959 // Find any earlier preferred or last chosen entries and nuke them 4960 findPreferredActivity(intent, resolvedType, 4961 flags, query, 0, false, true, false, userId); 4962 // Add the new activity as the last chosen for this filter 4963 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4964 "Setting last chosen"); 4965 } 4966 4967 @Override 4968 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4969 final int userId = UserHandle.getCallingUserId(); 4970 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4971 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4972 userId); 4973 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4974 false, false, false, userId); 4975 } 4976 4977 4978 private boolean isEphemeralAllowed( 4979 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4980 // Short circuit and return early if possible. 4981 if (DISABLE_EPHEMERAL_APPS) { 4982 return false; 4983 } 4984 final int callingUser = UserHandle.getCallingUserId(); 4985 if (callingUser != UserHandle.USER_SYSTEM) { 4986 return false; 4987 } 4988 if (mEphemeralResolverConnection == null) { 4989 return false; 4990 } 4991 if (intent.getComponent() != null) { 4992 return false; 4993 } 4994 if (intent.getPackage() != null) { 4995 return false; 4996 } 4997 final boolean isWebUri = hasWebURI(intent); 4998 if (!isWebUri) { 4999 return false; 5000 } 5001 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 5002 synchronized (mPackages) { 5003 final int count = resolvedActivites.size(); 5004 for (int n = 0; n < count; n++) { 5005 ResolveInfo info = resolvedActivites.get(n); 5006 String packageName = info.activityInfo.packageName; 5007 PackageSetting ps = mSettings.mPackages.get(packageName); 5008 if (ps != null) { 5009 // Try to get the status from User settings first 5010 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5011 int status = (int) (packedStatus >> 32); 5012 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 5013 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5014 if (DEBUG_EPHEMERAL) { 5015 Slog.v(TAG, "DENY ephemeral apps;" 5016 + " pkg: " + packageName + ", status: " + status); 5017 } 5018 return false; 5019 } 5020 } 5021 } 5022 } 5023 // We've exhausted all ways to deny ephemeral application; let the system look for them. 5024 return true; 5025 } 5026 5027 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 5028 int userId) { 5029 final int ephemeralPrefixMask = Global.getInt(mContext.getContentResolver(), 5030 Global.EPHEMERAL_HASH_PREFIX_MASK, DEFAULT_EPHEMERAL_HASH_PREFIX_MASK); 5031 final int ephemeralPrefixCount = Global.getInt(mContext.getContentResolver(), 5032 Global.EPHEMERAL_HASH_PREFIX_COUNT, DEFAULT_EPHEMERAL_HASH_PREFIX_COUNT); 5033 final EphemeralDigest digest = new EphemeralDigest(intent.getData(), ephemeralPrefixCount); 5034 final int[] shaPrefix = digest.getDigestPrefix(); 5035 final byte[][] digestBytes = digest.getDigestBytes(); 5036 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5037 mEphemeralResolverConnection.getEphemeralResolveInfoList( 5038 shaPrefix, ephemeralPrefixMask); 5039 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5040 // No hash prefix match; there are no ephemeral apps for this domain. 5041 return null; 5042 } 5043 5044 // Go in reverse order so we match the narrowest scope first. 5045 for (int i = shaPrefix.length; i >= 0 ; --i) { 5046 for (EphemeralResolveInfo ephemeralApplication : ephemeralResolveInfoList) { 5047 if (!Arrays.equals(digestBytes[i], ephemeralApplication.getDigestBytes())) { 5048 continue; 5049 } 5050 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5051 // No filters; this should never happen. 5052 if (filters.isEmpty()) { 5053 continue; 5054 } 5055 // We have a domain match; resolve the filters to see if anything matches. 5056 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5057 for (int j = filters.size() - 1; j >= 0; --j) { 5058 final EphemeralResolveIntentInfo intentInfo = 5059 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5060 ephemeralResolver.addFilter(intentInfo); 5061 } 5062 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5063 intent, resolvedType, false /*defaultOnly*/, userId); 5064 if (!matchedResolveInfoList.isEmpty()) { 5065 return matchedResolveInfoList.get(0); 5066 } 5067 } 5068 } 5069 // Hash or filter mis-match; no ephemeral apps for this domain. 5070 return null; 5071 } 5072 5073 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5074 int flags, List<ResolveInfo> query, int userId) { 5075 if (query != null) { 5076 final int N = query.size(); 5077 if (N == 1) { 5078 return query.get(0); 5079 } else if (N > 1) { 5080 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5081 // If there is more than one activity with the same priority, 5082 // then let the user decide between them. 5083 ResolveInfo r0 = query.get(0); 5084 ResolveInfo r1 = query.get(1); 5085 if (DEBUG_INTENT_MATCHING || debug) { 5086 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5087 + r1.activityInfo.name + "=" + r1.priority); 5088 } 5089 // If the first activity has a higher priority, or a different 5090 // default, then it is always desirable to pick it. 5091 if (r0.priority != r1.priority 5092 || r0.preferredOrder != r1.preferredOrder 5093 || r0.isDefault != r1.isDefault) { 5094 return query.get(0); 5095 } 5096 // If we have saved a preference for a preferred activity for 5097 // this Intent, use that. 5098 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5099 flags, query, r0.priority, true, false, debug, userId); 5100 if (ri != null) { 5101 return ri; 5102 } 5103 ri = new ResolveInfo(mResolveInfo); 5104 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5105 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5106 // If all of the options come from the same package, show the application's 5107 // label and icon instead of the generic resolver's. 5108 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5109 // and then throw away the ResolveInfo itself, meaning that the caller loses 5110 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5111 // a fallback for this case; we only set the target package's resources on 5112 // the ResolveInfo, not the ActivityInfo. 5113 final String intentPackage = intent.getPackage(); 5114 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5115 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5116 ri.resolvePackageName = intentPackage; 5117 if (userNeedsBadging(userId)) { 5118 ri.noResourceId = true; 5119 } else { 5120 ri.icon = appi.icon; 5121 } 5122 ri.iconResourceId = appi.icon; 5123 ri.labelRes = appi.labelRes; 5124 } 5125 ri.activityInfo.applicationInfo = new ApplicationInfo( 5126 ri.activityInfo.applicationInfo); 5127 if (userId != 0) { 5128 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5129 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5130 } 5131 // Make sure that the resolver is displayable in car mode 5132 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5133 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5134 return ri; 5135 } 5136 } 5137 return null; 5138 } 5139 5140 /** 5141 * Return true if the given list is not empty and all of its contents have 5142 * an activityInfo with the given package name. 5143 */ 5144 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5145 if (ArrayUtils.isEmpty(list)) { 5146 return false; 5147 } 5148 for (int i = 0, N = list.size(); i < N; i++) { 5149 final ResolveInfo ri = list.get(i); 5150 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5151 if (ai == null || !packageName.equals(ai.packageName)) { 5152 return false; 5153 } 5154 } 5155 return true; 5156 } 5157 5158 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5159 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5160 final int N = query.size(); 5161 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5162 .get(userId); 5163 // Get the list of persistent preferred activities that handle the intent 5164 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5165 List<PersistentPreferredActivity> pprefs = ppir != null 5166 ? ppir.queryIntent(intent, resolvedType, 5167 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5168 : null; 5169 if (pprefs != null && pprefs.size() > 0) { 5170 final int M = pprefs.size(); 5171 for (int i=0; i<M; i++) { 5172 final PersistentPreferredActivity ppa = pprefs.get(i); 5173 if (DEBUG_PREFERRED || debug) { 5174 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5175 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5176 + "\n component=" + ppa.mComponent); 5177 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5178 } 5179 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5180 flags | MATCH_DISABLED_COMPONENTS, userId); 5181 if (DEBUG_PREFERRED || debug) { 5182 Slog.v(TAG, "Found persistent preferred activity:"); 5183 if (ai != null) { 5184 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5185 } else { 5186 Slog.v(TAG, " null"); 5187 } 5188 } 5189 if (ai == null) { 5190 // This previously registered persistent preferred activity 5191 // component is no longer known. Ignore it and do NOT remove it. 5192 continue; 5193 } 5194 for (int j=0; j<N; j++) { 5195 final ResolveInfo ri = query.get(j); 5196 if (!ri.activityInfo.applicationInfo.packageName 5197 .equals(ai.applicationInfo.packageName)) { 5198 continue; 5199 } 5200 if (!ri.activityInfo.name.equals(ai.name)) { 5201 continue; 5202 } 5203 // Found a persistent preference that can handle the intent. 5204 if (DEBUG_PREFERRED || debug) { 5205 Slog.v(TAG, "Returning persistent preferred activity: " + 5206 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5207 } 5208 return ri; 5209 } 5210 } 5211 } 5212 return null; 5213 } 5214 5215 // TODO: handle preferred activities missing while user has amnesia 5216 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5217 List<ResolveInfo> query, int priority, boolean always, 5218 boolean removeMatches, boolean debug, int userId) { 5219 if (!sUserManager.exists(userId)) return null; 5220 flags = updateFlagsForResolve(flags, userId, intent); 5221 // writer 5222 synchronized (mPackages) { 5223 if (intent.getSelector() != null) { 5224 intent = intent.getSelector(); 5225 } 5226 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5227 5228 // Try to find a matching persistent preferred activity. 5229 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5230 debug, userId); 5231 5232 // If a persistent preferred activity matched, use it. 5233 if (pri != null) { 5234 return pri; 5235 } 5236 5237 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5238 // Get the list of preferred activities that handle the intent 5239 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5240 List<PreferredActivity> prefs = pir != null 5241 ? pir.queryIntent(intent, resolvedType, 5242 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5243 : null; 5244 if (prefs != null && prefs.size() > 0) { 5245 boolean changed = false; 5246 try { 5247 // First figure out how good the original match set is. 5248 // We will only allow preferred activities that came 5249 // from the same match quality. 5250 int match = 0; 5251 5252 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5253 5254 final int N = query.size(); 5255 for (int j=0; j<N; j++) { 5256 final ResolveInfo ri = query.get(j); 5257 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5258 + ": 0x" + Integer.toHexString(match)); 5259 if (ri.match > match) { 5260 match = ri.match; 5261 } 5262 } 5263 5264 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5265 + Integer.toHexString(match)); 5266 5267 match &= IntentFilter.MATCH_CATEGORY_MASK; 5268 final int M = prefs.size(); 5269 for (int i=0; i<M; i++) { 5270 final PreferredActivity pa = prefs.get(i); 5271 if (DEBUG_PREFERRED || debug) { 5272 Slog.v(TAG, "Checking PreferredActivity ds=" 5273 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5274 + "\n component=" + pa.mPref.mComponent); 5275 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5276 } 5277 if (pa.mPref.mMatch != match) { 5278 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5279 + Integer.toHexString(pa.mPref.mMatch)); 5280 continue; 5281 } 5282 // If it's not an "always" type preferred activity and that's what we're 5283 // looking for, skip it. 5284 if (always && !pa.mPref.mAlways) { 5285 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5286 continue; 5287 } 5288 final ActivityInfo ai = getActivityInfo( 5289 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5290 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5291 userId); 5292 if (DEBUG_PREFERRED || debug) { 5293 Slog.v(TAG, "Found preferred activity:"); 5294 if (ai != null) { 5295 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5296 } else { 5297 Slog.v(TAG, " null"); 5298 } 5299 } 5300 if (ai == null) { 5301 // This previously registered preferred activity 5302 // component is no longer known. Most likely an update 5303 // to the app was installed and in the new version this 5304 // component no longer exists. Clean it up by removing 5305 // it from the preferred activities list, and skip it. 5306 Slog.w(TAG, "Removing dangling preferred activity: " 5307 + pa.mPref.mComponent); 5308 pir.removeFilter(pa); 5309 changed = true; 5310 continue; 5311 } 5312 for (int j=0; j<N; j++) { 5313 final ResolveInfo ri = query.get(j); 5314 if (!ri.activityInfo.applicationInfo.packageName 5315 .equals(ai.applicationInfo.packageName)) { 5316 continue; 5317 } 5318 if (!ri.activityInfo.name.equals(ai.name)) { 5319 continue; 5320 } 5321 5322 if (removeMatches) { 5323 pir.removeFilter(pa); 5324 changed = true; 5325 if (DEBUG_PREFERRED) { 5326 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5327 } 5328 break; 5329 } 5330 5331 // Okay we found a previously set preferred or last chosen app. 5332 // If the result set is different from when this 5333 // was created, we need to clear it and re-ask the 5334 // user their preference, if we're looking for an "always" type entry. 5335 if (always && !pa.mPref.sameSet(query)) { 5336 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5337 + intent + " type " + resolvedType); 5338 if (DEBUG_PREFERRED) { 5339 Slog.v(TAG, "Removing preferred activity since set changed " 5340 + pa.mPref.mComponent); 5341 } 5342 pir.removeFilter(pa); 5343 // Re-add the filter as a "last chosen" entry (!always) 5344 PreferredActivity lastChosen = new PreferredActivity( 5345 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5346 pir.addFilter(lastChosen); 5347 changed = true; 5348 return null; 5349 } 5350 5351 // Yay! Either the set matched or we're looking for the last chosen 5352 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5353 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5354 return ri; 5355 } 5356 } 5357 } finally { 5358 if (changed) { 5359 if (DEBUG_PREFERRED) { 5360 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5361 } 5362 scheduleWritePackageRestrictionsLocked(userId); 5363 } 5364 } 5365 } 5366 } 5367 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5368 return null; 5369 } 5370 5371 /* 5372 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5373 */ 5374 @Override 5375 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5376 int targetUserId) { 5377 mContext.enforceCallingOrSelfPermission( 5378 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5379 List<CrossProfileIntentFilter> matches = 5380 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5381 if (matches != null) { 5382 int size = matches.size(); 5383 for (int i = 0; i < size; i++) { 5384 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5385 } 5386 } 5387 if (hasWebURI(intent)) { 5388 // cross-profile app linking works only towards the parent. 5389 final UserInfo parent = getProfileParent(sourceUserId); 5390 synchronized(mPackages) { 5391 int flags = updateFlagsForResolve(0, parent.id, intent); 5392 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5393 intent, resolvedType, flags, sourceUserId, parent.id); 5394 return xpDomainInfo != null; 5395 } 5396 } 5397 return false; 5398 } 5399 5400 private UserInfo getProfileParent(int userId) { 5401 final long identity = Binder.clearCallingIdentity(); 5402 try { 5403 return sUserManager.getProfileParent(userId); 5404 } finally { 5405 Binder.restoreCallingIdentity(identity); 5406 } 5407 } 5408 5409 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5410 String resolvedType, int userId) { 5411 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5412 if (resolver != null) { 5413 return resolver.queryIntent(intent, resolvedType, false, userId); 5414 } 5415 return null; 5416 } 5417 5418 @Override 5419 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5420 String resolvedType, int flags, int userId) { 5421 try { 5422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5423 5424 return new ParceledListSlice<>( 5425 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5426 } finally { 5427 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5428 } 5429 } 5430 5431 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5432 String resolvedType, int flags, int userId) { 5433 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5434 flags = updateFlagsForResolve(flags, userId, intent); 5435 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5436 false /* requireFullPermission */, false /* checkShell */, 5437 "query intent activities"); 5438 ComponentName comp = intent.getComponent(); 5439 if (comp == null) { 5440 if (intent.getSelector() != null) { 5441 intent = intent.getSelector(); 5442 comp = intent.getComponent(); 5443 } 5444 } 5445 5446 if (comp != null) { 5447 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5448 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5449 if (ai != null) { 5450 final ResolveInfo ri = new ResolveInfo(); 5451 ri.activityInfo = ai; 5452 list.add(ri); 5453 } 5454 return list; 5455 } 5456 5457 // reader 5458 synchronized (mPackages) { 5459 final String pkgName = intent.getPackage(); 5460 if (pkgName == null) { 5461 List<CrossProfileIntentFilter> matchingFilters = 5462 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5463 // Check for results that need to skip the current profile. 5464 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5465 resolvedType, flags, userId); 5466 if (xpResolveInfo != null) { 5467 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5468 result.add(xpResolveInfo); 5469 return filterIfNotSystemUser(result, userId); 5470 } 5471 5472 // Check for results in the current profile. 5473 List<ResolveInfo> result = mActivities.queryIntent( 5474 intent, resolvedType, flags, userId); 5475 result = filterIfNotSystemUser(result, userId); 5476 5477 // Check for cross profile results. 5478 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5479 xpResolveInfo = queryCrossProfileIntents( 5480 matchingFilters, intent, resolvedType, flags, userId, 5481 hasNonNegativePriorityResult); 5482 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5483 boolean isVisibleToUser = filterIfNotSystemUser( 5484 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5485 if (isVisibleToUser) { 5486 result.add(xpResolveInfo); 5487 Collections.sort(result, mResolvePrioritySorter); 5488 } 5489 } 5490 if (hasWebURI(intent)) { 5491 CrossProfileDomainInfo xpDomainInfo = null; 5492 final UserInfo parent = getProfileParent(userId); 5493 if (parent != null) { 5494 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5495 flags, userId, parent.id); 5496 } 5497 if (xpDomainInfo != null) { 5498 if (xpResolveInfo != null) { 5499 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5500 // in the result. 5501 result.remove(xpResolveInfo); 5502 } 5503 if (result.size() == 0) { 5504 result.add(xpDomainInfo.resolveInfo); 5505 return result; 5506 } 5507 } else if (result.size() <= 1) { 5508 return result; 5509 } 5510 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5511 xpDomainInfo, userId); 5512 Collections.sort(result, mResolvePrioritySorter); 5513 } 5514 return result; 5515 } 5516 final PackageParser.Package pkg = mPackages.get(pkgName); 5517 if (pkg != null) { 5518 return filterIfNotSystemUser( 5519 mActivities.queryIntentForPackage( 5520 intent, resolvedType, flags, pkg.activities, userId), 5521 userId); 5522 } 5523 return new ArrayList<ResolveInfo>(); 5524 } 5525 } 5526 5527 private static class CrossProfileDomainInfo { 5528 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5529 ResolveInfo resolveInfo; 5530 /* Best domain verification status of the activities found in the other profile */ 5531 int bestDomainVerificationStatus; 5532 } 5533 5534 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5535 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5536 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5537 sourceUserId)) { 5538 return null; 5539 } 5540 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5541 resolvedType, flags, parentUserId); 5542 5543 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5544 return null; 5545 } 5546 CrossProfileDomainInfo result = null; 5547 int size = resultTargetUser.size(); 5548 for (int i = 0; i < size; i++) { 5549 ResolveInfo riTargetUser = resultTargetUser.get(i); 5550 // Intent filter verification is only for filters that specify a host. So don't return 5551 // those that handle all web uris. 5552 if (riTargetUser.handleAllWebDataURI) { 5553 continue; 5554 } 5555 String packageName = riTargetUser.activityInfo.packageName; 5556 PackageSetting ps = mSettings.mPackages.get(packageName); 5557 if (ps == null) { 5558 continue; 5559 } 5560 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5561 int status = (int)(verificationState >> 32); 5562 if (result == null) { 5563 result = new CrossProfileDomainInfo(); 5564 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5565 sourceUserId, parentUserId); 5566 result.bestDomainVerificationStatus = status; 5567 } else { 5568 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5569 result.bestDomainVerificationStatus); 5570 } 5571 } 5572 // Don't consider matches with status NEVER across profiles. 5573 if (result != null && result.bestDomainVerificationStatus 5574 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5575 return null; 5576 } 5577 return result; 5578 } 5579 5580 /** 5581 * Verification statuses are ordered from the worse to the best, except for 5582 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5583 */ 5584 private int bestDomainVerificationStatus(int status1, int status2) { 5585 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5586 return status2; 5587 } 5588 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5589 return status1; 5590 } 5591 return (int) MathUtils.max(status1, status2); 5592 } 5593 5594 private boolean isUserEnabled(int userId) { 5595 long callingId = Binder.clearCallingIdentity(); 5596 try { 5597 UserInfo userInfo = sUserManager.getUserInfo(userId); 5598 return userInfo != null && userInfo.isEnabled(); 5599 } finally { 5600 Binder.restoreCallingIdentity(callingId); 5601 } 5602 } 5603 5604 /** 5605 * Filter out activities with systemUserOnly flag set, when current user is not System. 5606 * 5607 * @return filtered list 5608 */ 5609 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5610 if (userId == UserHandle.USER_SYSTEM) { 5611 return resolveInfos; 5612 } 5613 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5614 ResolveInfo info = resolveInfos.get(i); 5615 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5616 resolveInfos.remove(i); 5617 } 5618 } 5619 return resolveInfos; 5620 } 5621 5622 /** 5623 * @param resolveInfos list of resolve infos in descending priority order 5624 * @return if the list contains a resolve info with non-negative priority 5625 */ 5626 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5627 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5628 } 5629 5630 private static boolean hasWebURI(Intent intent) { 5631 if (intent.getData() == null) { 5632 return false; 5633 } 5634 final String scheme = intent.getScheme(); 5635 if (TextUtils.isEmpty(scheme)) { 5636 return false; 5637 } 5638 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5639 } 5640 5641 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5642 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5643 int userId) { 5644 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5645 5646 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5647 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5648 candidates.size()); 5649 } 5650 5651 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5652 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5653 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5654 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5655 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5656 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5657 5658 synchronized (mPackages) { 5659 final int count = candidates.size(); 5660 // First, try to use linked apps. Partition the candidates into four lists: 5661 // one for the final results, one for the "do not use ever", one for "undefined status" 5662 // and finally one for "browser app type". 5663 for (int n=0; n<count; n++) { 5664 ResolveInfo info = candidates.get(n); 5665 String packageName = info.activityInfo.packageName; 5666 PackageSetting ps = mSettings.mPackages.get(packageName); 5667 if (ps != null) { 5668 // Add to the special match all list (Browser use case) 5669 if (info.handleAllWebDataURI) { 5670 matchAllList.add(info); 5671 continue; 5672 } 5673 // Try to get the status from User settings first 5674 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5675 int status = (int)(packedStatus >> 32); 5676 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5677 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5678 if (DEBUG_DOMAIN_VERIFICATION) { 5679 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5680 + " : linkgen=" + linkGeneration); 5681 } 5682 // Use link-enabled generation as preferredOrder, i.e. 5683 // prefer newly-enabled over earlier-enabled. 5684 info.preferredOrder = linkGeneration; 5685 alwaysList.add(info); 5686 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5687 if (DEBUG_DOMAIN_VERIFICATION) { 5688 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5689 } 5690 neverList.add(info); 5691 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5692 if (DEBUG_DOMAIN_VERIFICATION) { 5693 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5694 } 5695 alwaysAskList.add(info); 5696 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5697 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5698 if (DEBUG_DOMAIN_VERIFICATION) { 5699 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5700 } 5701 undefinedList.add(info); 5702 } 5703 } 5704 } 5705 5706 // We'll want to include browser possibilities in a few cases 5707 boolean includeBrowser = false; 5708 5709 // First try to add the "always" resolution(s) for the current user, if any 5710 if (alwaysList.size() > 0) { 5711 result.addAll(alwaysList); 5712 } else { 5713 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5714 result.addAll(undefinedList); 5715 // Maybe add one for the other profile. 5716 if (xpDomainInfo != null && ( 5717 xpDomainInfo.bestDomainVerificationStatus 5718 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5719 result.add(xpDomainInfo.resolveInfo); 5720 } 5721 includeBrowser = true; 5722 } 5723 5724 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5725 // If there were 'always' entries their preferred order has been set, so we also 5726 // back that off to make the alternatives equivalent 5727 if (alwaysAskList.size() > 0) { 5728 for (ResolveInfo i : result) { 5729 i.preferredOrder = 0; 5730 } 5731 result.addAll(alwaysAskList); 5732 includeBrowser = true; 5733 } 5734 5735 if (includeBrowser) { 5736 // Also add browsers (all of them or only the default one) 5737 if (DEBUG_DOMAIN_VERIFICATION) { 5738 Slog.v(TAG, " ...including browsers in candidate set"); 5739 } 5740 if ((matchFlags & MATCH_ALL) != 0) { 5741 result.addAll(matchAllList); 5742 } else { 5743 // Browser/generic handling case. If there's a default browser, go straight 5744 // to that (but only if there is no other higher-priority match). 5745 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5746 int maxMatchPrio = 0; 5747 ResolveInfo defaultBrowserMatch = null; 5748 final int numCandidates = matchAllList.size(); 5749 for (int n = 0; n < numCandidates; n++) { 5750 ResolveInfo info = matchAllList.get(n); 5751 // track the highest overall match priority... 5752 if (info.priority > maxMatchPrio) { 5753 maxMatchPrio = info.priority; 5754 } 5755 // ...and the highest-priority default browser match 5756 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5757 if (defaultBrowserMatch == null 5758 || (defaultBrowserMatch.priority < info.priority)) { 5759 if (debug) { 5760 Slog.v(TAG, "Considering default browser match " + info); 5761 } 5762 defaultBrowserMatch = info; 5763 } 5764 } 5765 } 5766 if (defaultBrowserMatch != null 5767 && defaultBrowserMatch.priority >= maxMatchPrio 5768 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5769 { 5770 if (debug) { 5771 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5772 } 5773 result.add(defaultBrowserMatch); 5774 } else { 5775 result.addAll(matchAllList); 5776 } 5777 } 5778 5779 // If there is nothing selected, add all candidates and remove the ones that the user 5780 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5781 if (result.size() == 0) { 5782 result.addAll(candidates); 5783 result.removeAll(neverList); 5784 } 5785 } 5786 } 5787 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5788 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5789 result.size()); 5790 for (ResolveInfo info : result) { 5791 Slog.v(TAG, " + " + info.activityInfo); 5792 } 5793 } 5794 return result; 5795 } 5796 5797 // Returns a packed value as a long: 5798 // 5799 // high 'int'-sized word: link status: undefined/ask/never/always. 5800 // low 'int'-sized word: relative priority among 'always' results. 5801 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5802 long result = ps.getDomainVerificationStatusForUser(userId); 5803 // if none available, get the master status 5804 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5805 if (ps.getIntentFilterVerificationInfo() != null) { 5806 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5807 } 5808 } 5809 return result; 5810 } 5811 5812 private ResolveInfo querySkipCurrentProfileIntents( 5813 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5814 int flags, int sourceUserId) { 5815 if (matchingFilters != null) { 5816 int size = matchingFilters.size(); 5817 for (int i = 0; i < size; i ++) { 5818 CrossProfileIntentFilter filter = matchingFilters.get(i); 5819 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5820 // Checking if there are activities in the target user that can handle the 5821 // intent. 5822 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5823 resolvedType, flags, sourceUserId); 5824 if (resolveInfo != null) { 5825 return resolveInfo; 5826 } 5827 } 5828 } 5829 } 5830 return null; 5831 } 5832 5833 // Return matching ResolveInfo in target user if any. 5834 private ResolveInfo queryCrossProfileIntents( 5835 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5836 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5837 if (matchingFilters != null) { 5838 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5839 // match the same intent. For performance reasons, it is better not to 5840 // run queryIntent twice for the same userId 5841 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5842 int size = matchingFilters.size(); 5843 for (int i = 0; i < size; i++) { 5844 CrossProfileIntentFilter filter = matchingFilters.get(i); 5845 int targetUserId = filter.getTargetUserId(); 5846 boolean skipCurrentProfile = 5847 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5848 boolean skipCurrentProfileIfNoMatchFound = 5849 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5850 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5851 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5852 // Checking if there are activities in the target user that can handle the 5853 // intent. 5854 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5855 resolvedType, flags, sourceUserId); 5856 if (resolveInfo != null) return resolveInfo; 5857 alreadyTriedUserIds.put(targetUserId, true); 5858 } 5859 } 5860 } 5861 return null; 5862 } 5863 5864 /** 5865 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5866 * will forward the intent to the filter's target user. 5867 * Otherwise, returns null. 5868 */ 5869 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5870 String resolvedType, int flags, int sourceUserId) { 5871 int targetUserId = filter.getTargetUserId(); 5872 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5873 resolvedType, flags, targetUserId); 5874 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5875 // If all the matches in the target profile are suspended, return null. 5876 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5877 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5878 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5879 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5880 targetUserId); 5881 } 5882 } 5883 } 5884 return null; 5885 } 5886 5887 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5888 int sourceUserId, int targetUserId) { 5889 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5890 long ident = Binder.clearCallingIdentity(); 5891 boolean targetIsProfile; 5892 try { 5893 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5894 } finally { 5895 Binder.restoreCallingIdentity(ident); 5896 } 5897 String className; 5898 if (targetIsProfile) { 5899 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5900 } else { 5901 className = FORWARD_INTENT_TO_PARENT; 5902 } 5903 ComponentName forwardingActivityComponentName = new ComponentName( 5904 mAndroidApplication.packageName, className); 5905 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5906 sourceUserId); 5907 if (!targetIsProfile) { 5908 forwardingActivityInfo.showUserIcon = targetUserId; 5909 forwardingResolveInfo.noResourceId = true; 5910 } 5911 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5912 forwardingResolveInfo.priority = 0; 5913 forwardingResolveInfo.preferredOrder = 0; 5914 forwardingResolveInfo.match = 0; 5915 forwardingResolveInfo.isDefault = true; 5916 forwardingResolveInfo.filter = filter; 5917 forwardingResolveInfo.targetUserId = targetUserId; 5918 return forwardingResolveInfo; 5919 } 5920 5921 @Override 5922 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5923 Intent[] specifics, String[] specificTypes, Intent intent, 5924 String resolvedType, int flags, int userId) { 5925 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5926 specificTypes, intent, resolvedType, flags, userId)); 5927 } 5928 5929 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5930 Intent[] specifics, String[] specificTypes, Intent intent, 5931 String resolvedType, int flags, int userId) { 5932 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5933 flags = updateFlagsForResolve(flags, userId, intent); 5934 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5935 false /* requireFullPermission */, false /* checkShell */, 5936 "query intent activity options"); 5937 final String resultsAction = intent.getAction(); 5938 5939 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5940 | PackageManager.GET_RESOLVED_FILTER, userId); 5941 5942 if (DEBUG_INTENT_MATCHING) { 5943 Log.v(TAG, "Query " + intent + ": " + results); 5944 } 5945 5946 int specificsPos = 0; 5947 int N; 5948 5949 // todo: note that the algorithm used here is O(N^2). This 5950 // isn't a problem in our current environment, but if we start running 5951 // into situations where we have more than 5 or 10 matches then this 5952 // should probably be changed to something smarter... 5953 5954 // First we go through and resolve each of the specific items 5955 // that were supplied, taking care of removing any corresponding 5956 // duplicate items in the generic resolve list. 5957 if (specifics != null) { 5958 for (int i=0; i<specifics.length; i++) { 5959 final Intent sintent = specifics[i]; 5960 if (sintent == null) { 5961 continue; 5962 } 5963 5964 if (DEBUG_INTENT_MATCHING) { 5965 Log.v(TAG, "Specific #" + i + ": " + sintent); 5966 } 5967 5968 String action = sintent.getAction(); 5969 if (resultsAction != null && resultsAction.equals(action)) { 5970 // If this action was explicitly requested, then don't 5971 // remove things that have it. 5972 action = null; 5973 } 5974 5975 ResolveInfo ri = null; 5976 ActivityInfo ai = null; 5977 5978 ComponentName comp = sintent.getComponent(); 5979 if (comp == null) { 5980 ri = resolveIntent( 5981 sintent, 5982 specificTypes != null ? specificTypes[i] : null, 5983 flags, userId); 5984 if (ri == null) { 5985 continue; 5986 } 5987 if (ri == mResolveInfo) { 5988 // ACK! Must do something better with this. 5989 } 5990 ai = ri.activityInfo; 5991 comp = new ComponentName(ai.applicationInfo.packageName, 5992 ai.name); 5993 } else { 5994 ai = getActivityInfo(comp, flags, userId); 5995 if (ai == null) { 5996 continue; 5997 } 5998 } 5999 6000 // Look for any generic query activities that are duplicates 6001 // of this specific one, and remove them from the results. 6002 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 6003 N = results.size(); 6004 int j; 6005 for (j=specificsPos; j<N; j++) { 6006 ResolveInfo sri = results.get(j); 6007 if ((sri.activityInfo.name.equals(comp.getClassName()) 6008 && sri.activityInfo.applicationInfo.packageName.equals( 6009 comp.getPackageName())) 6010 || (action != null && sri.filter.matchAction(action))) { 6011 results.remove(j); 6012 if (DEBUG_INTENT_MATCHING) Log.v( 6013 TAG, "Removing duplicate item from " + j 6014 + " due to specific " + specificsPos); 6015 if (ri == null) { 6016 ri = sri; 6017 } 6018 j--; 6019 N--; 6020 } 6021 } 6022 6023 // Add this specific item to its proper place. 6024 if (ri == null) { 6025 ri = new ResolveInfo(); 6026 ri.activityInfo = ai; 6027 } 6028 results.add(specificsPos, ri); 6029 ri.specificIndex = i; 6030 specificsPos++; 6031 } 6032 } 6033 6034 // Now we go through the remaining generic results and remove any 6035 // duplicate actions that are found here. 6036 N = results.size(); 6037 for (int i=specificsPos; i<N-1; i++) { 6038 final ResolveInfo rii = results.get(i); 6039 if (rii.filter == null) { 6040 continue; 6041 } 6042 6043 // Iterate over all of the actions of this result's intent 6044 // filter... typically this should be just one. 6045 final Iterator<String> it = rii.filter.actionsIterator(); 6046 if (it == null) { 6047 continue; 6048 } 6049 while (it.hasNext()) { 6050 final String action = it.next(); 6051 if (resultsAction != null && resultsAction.equals(action)) { 6052 // If this action was explicitly requested, then don't 6053 // remove things that have it. 6054 continue; 6055 } 6056 for (int j=i+1; j<N; j++) { 6057 final ResolveInfo rij = results.get(j); 6058 if (rij.filter != null && rij.filter.hasAction(action)) { 6059 results.remove(j); 6060 if (DEBUG_INTENT_MATCHING) Log.v( 6061 TAG, "Removing duplicate item from " + j 6062 + " due to action " + action + " at " + i); 6063 j--; 6064 N--; 6065 } 6066 } 6067 } 6068 6069 // If the caller didn't request filter information, drop it now 6070 // so we don't have to marshall/unmarshall it. 6071 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6072 rii.filter = null; 6073 } 6074 } 6075 6076 // Filter out the caller activity if so requested. 6077 if (caller != null) { 6078 N = results.size(); 6079 for (int i=0; i<N; i++) { 6080 ActivityInfo ainfo = results.get(i).activityInfo; 6081 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6082 && caller.getClassName().equals(ainfo.name)) { 6083 results.remove(i); 6084 break; 6085 } 6086 } 6087 } 6088 6089 // If the caller didn't request filter information, 6090 // drop them now so we don't have to 6091 // marshall/unmarshall it. 6092 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6093 N = results.size(); 6094 for (int i=0; i<N; i++) { 6095 results.get(i).filter = null; 6096 } 6097 } 6098 6099 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6100 return results; 6101 } 6102 6103 @Override 6104 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6105 String resolvedType, int flags, int userId) { 6106 return new ParceledListSlice<>( 6107 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6108 } 6109 6110 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6111 String resolvedType, int flags, int userId) { 6112 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6113 flags = updateFlagsForResolve(flags, userId, intent); 6114 ComponentName comp = intent.getComponent(); 6115 if (comp == null) { 6116 if (intent.getSelector() != null) { 6117 intent = intent.getSelector(); 6118 comp = intent.getComponent(); 6119 } 6120 } 6121 if (comp != null) { 6122 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6123 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6124 if (ai != null) { 6125 ResolveInfo ri = new ResolveInfo(); 6126 ri.activityInfo = ai; 6127 list.add(ri); 6128 } 6129 return list; 6130 } 6131 6132 // reader 6133 synchronized (mPackages) { 6134 String pkgName = intent.getPackage(); 6135 if (pkgName == null) { 6136 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6137 } 6138 final PackageParser.Package pkg = mPackages.get(pkgName); 6139 if (pkg != null) { 6140 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6141 userId); 6142 } 6143 return Collections.emptyList(); 6144 } 6145 } 6146 6147 @Override 6148 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6149 if (!sUserManager.exists(userId)) return null; 6150 flags = updateFlagsForResolve(flags, userId, intent); 6151 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6152 if (query != null) { 6153 if (query.size() >= 1) { 6154 // If there is more than one service with the same priority, 6155 // just arbitrarily pick the first one. 6156 return query.get(0); 6157 } 6158 } 6159 return null; 6160 } 6161 6162 @Override 6163 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6164 String resolvedType, int flags, int userId) { 6165 return new ParceledListSlice<>( 6166 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6167 } 6168 6169 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6170 String resolvedType, int flags, int userId) { 6171 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6172 flags = updateFlagsForResolve(flags, userId, intent); 6173 ComponentName comp = intent.getComponent(); 6174 if (comp == null) { 6175 if (intent.getSelector() != null) { 6176 intent = intent.getSelector(); 6177 comp = intent.getComponent(); 6178 } 6179 } 6180 if (comp != null) { 6181 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6182 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6183 if (si != null) { 6184 final ResolveInfo ri = new ResolveInfo(); 6185 ri.serviceInfo = si; 6186 list.add(ri); 6187 } 6188 return list; 6189 } 6190 6191 // reader 6192 synchronized (mPackages) { 6193 String pkgName = intent.getPackage(); 6194 if (pkgName == null) { 6195 return mServices.queryIntent(intent, resolvedType, flags, userId); 6196 } 6197 final PackageParser.Package pkg = mPackages.get(pkgName); 6198 if (pkg != null) { 6199 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6200 userId); 6201 } 6202 return Collections.emptyList(); 6203 } 6204 } 6205 6206 @Override 6207 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6208 String resolvedType, int flags, int userId) { 6209 return new ParceledListSlice<>( 6210 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6211 } 6212 6213 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6214 Intent intent, String resolvedType, int flags, int userId) { 6215 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6216 flags = updateFlagsForResolve(flags, userId, intent); 6217 ComponentName comp = intent.getComponent(); 6218 if (comp == null) { 6219 if (intent.getSelector() != null) { 6220 intent = intent.getSelector(); 6221 comp = intent.getComponent(); 6222 } 6223 } 6224 if (comp != null) { 6225 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6226 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6227 if (pi != null) { 6228 final ResolveInfo ri = new ResolveInfo(); 6229 ri.providerInfo = pi; 6230 list.add(ri); 6231 } 6232 return list; 6233 } 6234 6235 // reader 6236 synchronized (mPackages) { 6237 String pkgName = intent.getPackage(); 6238 if (pkgName == null) { 6239 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6240 } 6241 final PackageParser.Package pkg = mPackages.get(pkgName); 6242 if (pkg != null) { 6243 return mProviders.queryIntentForPackage( 6244 intent, resolvedType, flags, pkg.providers, userId); 6245 } 6246 return Collections.emptyList(); 6247 } 6248 } 6249 6250 @Override 6251 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6252 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6253 flags = updateFlagsForPackage(flags, userId, null); 6254 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6255 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6256 true /* requireFullPermission */, false /* checkShell */, 6257 "get installed packages"); 6258 6259 // writer 6260 synchronized (mPackages) { 6261 ArrayList<PackageInfo> list; 6262 if (listUninstalled) { 6263 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6264 for (PackageSetting ps : mSettings.mPackages.values()) { 6265 final PackageInfo pi; 6266 if (ps.pkg != null) { 6267 pi = generatePackageInfo(ps, flags, userId); 6268 } else { 6269 pi = generatePackageInfo(ps, flags, userId); 6270 } 6271 if (pi != null) { 6272 list.add(pi); 6273 } 6274 } 6275 } else { 6276 list = new ArrayList<PackageInfo>(mPackages.size()); 6277 for (PackageParser.Package p : mPackages.values()) { 6278 final PackageInfo pi = 6279 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6280 if (pi != null) { 6281 list.add(pi); 6282 } 6283 } 6284 } 6285 6286 return new ParceledListSlice<PackageInfo>(list); 6287 } 6288 } 6289 6290 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6291 String[] permissions, boolean[] tmp, int flags, int userId) { 6292 int numMatch = 0; 6293 final PermissionsState permissionsState = ps.getPermissionsState(); 6294 for (int i=0; i<permissions.length; i++) { 6295 final String permission = permissions[i]; 6296 if (permissionsState.hasPermission(permission, userId)) { 6297 tmp[i] = true; 6298 numMatch++; 6299 } else { 6300 tmp[i] = false; 6301 } 6302 } 6303 if (numMatch == 0) { 6304 return; 6305 } 6306 final PackageInfo pi; 6307 if (ps.pkg != null) { 6308 pi = generatePackageInfo(ps, flags, userId); 6309 } else { 6310 pi = generatePackageInfo(ps, flags, userId); 6311 } 6312 // The above might return null in cases of uninstalled apps or install-state 6313 // skew across users/profiles. 6314 if (pi != null) { 6315 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6316 if (numMatch == permissions.length) { 6317 pi.requestedPermissions = permissions; 6318 } else { 6319 pi.requestedPermissions = new String[numMatch]; 6320 numMatch = 0; 6321 for (int i=0; i<permissions.length; i++) { 6322 if (tmp[i]) { 6323 pi.requestedPermissions[numMatch] = permissions[i]; 6324 numMatch++; 6325 } 6326 } 6327 } 6328 } 6329 list.add(pi); 6330 } 6331 } 6332 6333 @Override 6334 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6335 String[] permissions, int flags, int userId) { 6336 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6337 flags = updateFlagsForPackage(flags, userId, permissions); 6338 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6339 6340 // writer 6341 synchronized (mPackages) { 6342 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6343 boolean[] tmpBools = new boolean[permissions.length]; 6344 if (listUninstalled) { 6345 for (PackageSetting ps : mSettings.mPackages.values()) { 6346 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6347 } 6348 } else { 6349 for (PackageParser.Package pkg : mPackages.values()) { 6350 PackageSetting ps = (PackageSetting)pkg.mExtras; 6351 if (ps != null) { 6352 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6353 userId); 6354 } 6355 } 6356 } 6357 6358 return new ParceledListSlice<PackageInfo>(list); 6359 } 6360 } 6361 6362 @Override 6363 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6364 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6365 flags = updateFlagsForApplication(flags, userId, null); 6366 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6367 6368 // writer 6369 synchronized (mPackages) { 6370 ArrayList<ApplicationInfo> list; 6371 if (listUninstalled) { 6372 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6373 for (PackageSetting ps : mSettings.mPackages.values()) { 6374 ApplicationInfo ai; 6375 if (ps.pkg != null) { 6376 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6377 ps.readUserState(userId), userId); 6378 } else { 6379 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6380 } 6381 if (ai != null) { 6382 list.add(ai); 6383 } 6384 } 6385 } else { 6386 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6387 for (PackageParser.Package p : mPackages.values()) { 6388 if (p.mExtras != null) { 6389 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6390 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6391 if (ai != null) { 6392 list.add(ai); 6393 } 6394 } 6395 } 6396 } 6397 6398 return new ParceledListSlice<ApplicationInfo>(list); 6399 } 6400 } 6401 6402 @Override 6403 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6404 if (DISABLE_EPHEMERAL_APPS) { 6405 return null; 6406 } 6407 6408 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6409 "getEphemeralApplications"); 6410 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6411 true /* requireFullPermission */, false /* checkShell */, 6412 "getEphemeralApplications"); 6413 synchronized (mPackages) { 6414 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6415 .getEphemeralApplicationsLPw(userId); 6416 if (ephemeralApps != null) { 6417 return new ParceledListSlice<>(ephemeralApps); 6418 } 6419 } 6420 return null; 6421 } 6422 6423 @Override 6424 public boolean isEphemeralApplication(String packageName, int userId) { 6425 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6426 true /* requireFullPermission */, false /* checkShell */, 6427 "isEphemeral"); 6428 if (DISABLE_EPHEMERAL_APPS) { 6429 return false; 6430 } 6431 6432 if (!isCallerSameApp(packageName)) { 6433 return false; 6434 } 6435 synchronized (mPackages) { 6436 PackageParser.Package pkg = mPackages.get(packageName); 6437 if (pkg != null) { 6438 return pkg.applicationInfo.isEphemeralApp(); 6439 } 6440 } 6441 return false; 6442 } 6443 6444 @Override 6445 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6446 if (DISABLE_EPHEMERAL_APPS) { 6447 return null; 6448 } 6449 6450 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6451 true /* requireFullPermission */, false /* checkShell */, 6452 "getCookie"); 6453 if (!isCallerSameApp(packageName)) { 6454 return null; 6455 } 6456 synchronized (mPackages) { 6457 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6458 packageName, userId); 6459 } 6460 } 6461 6462 @Override 6463 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6464 if (DISABLE_EPHEMERAL_APPS) { 6465 return true; 6466 } 6467 6468 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6469 true /* requireFullPermission */, true /* checkShell */, 6470 "setCookie"); 6471 if (!isCallerSameApp(packageName)) { 6472 return false; 6473 } 6474 synchronized (mPackages) { 6475 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6476 packageName, cookie, userId); 6477 } 6478 } 6479 6480 @Override 6481 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6482 if (DISABLE_EPHEMERAL_APPS) { 6483 return null; 6484 } 6485 6486 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6487 "getEphemeralApplicationIcon"); 6488 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6489 true /* requireFullPermission */, false /* checkShell */, 6490 "getEphemeralApplicationIcon"); 6491 synchronized (mPackages) { 6492 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6493 packageName, userId); 6494 } 6495 } 6496 6497 private boolean isCallerSameApp(String packageName) { 6498 PackageParser.Package pkg = mPackages.get(packageName); 6499 return pkg != null 6500 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6501 } 6502 6503 @Override 6504 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6505 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6506 } 6507 6508 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6509 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6510 6511 // reader 6512 synchronized (mPackages) { 6513 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6514 final int userId = UserHandle.getCallingUserId(); 6515 while (i.hasNext()) { 6516 final PackageParser.Package p = i.next(); 6517 if (p.applicationInfo == null) continue; 6518 6519 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6520 && !p.applicationInfo.isDirectBootAware(); 6521 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6522 && p.applicationInfo.isDirectBootAware(); 6523 6524 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6525 && (!mSafeMode || isSystemApp(p)) 6526 && (matchesUnaware || matchesAware)) { 6527 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6528 if (ps != null) { 6529 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6530 ps.readUserState(userId), userId); 6531 if (ai != null) { 6532 finalList.add(ai); 6533 } 6534 } 6535 } 6536 } 6537 } 6538 6539 return finalList; 6540 } 6541 6542 @Override 6543 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6544 if (!sUserManager.exists(userId)) return null; 6545 flags = updateFlagsForComponent(flags, userId, name); 6546 // reader 6547 synchronized (mPackages) { 6548 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6549 PackageSetting ps = provider != null 6550 ? mSettings.mPackages.get(provider.owner.packageName) 6551 : null; 6552 return ps != null 6553 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6554 ? PackageParser.generateProviderInfo(provider, flags, 6555 ps.readUserState(userId), userId) 6556 : null; 6557 } 6558 } 6559 6560 /** 6561 * @deprecated 6562 */ 6563 @Deprecated 6564 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6565 // reader 6566 synchronized (mPackages) { 6567 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6568 .entrySet().iterator(); 6569 final int userId = UserHandle.getCallingUserId(); 6570 while (i.hasNext()) { 6571 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6572 PackageParser.Provider p = entry.getValue(); 6573 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6574 6575 if (ps != null && p.syncable 6576 && (!mSafeMode || (p.info.applicationInfo.flags 6577 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6578 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6579 ps.readUserState(userId), userId); 6580 if (info != null) { 6581 outNames.add(entry.getKey()); 6582 outInfo.add(info); 6583 } 6584 } 6585 } 6586 } 6587 } 6588 6589 @Override 6590 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6591 int uid, int flags) { 6592 final int userId = processName != null ? UserHandle.getUserId(uid) 6593 : UserHandle.getCallingUserId(); 6594 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6595 flags = updateFlagsForComponent(flags, userId, processName); 6596 6597 ArrayList<ProviderInfo> finalList = null; 6598 // reader 6599 synchronized (mPackages) { 6600 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6601 while (i.hasNext()) { 6602 final PackageParser.Provider p = i.next(); 6603 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6604 if (ps != null && p.info.authority != null 6605 && (processName == null 6606 || (p.info.processName.equals(processName) 6607 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6608 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6609 if (finalList == null) { 6610 finalList = new ArrayList<ProviderInfo>(3); 6611 } 6612 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6613 ps.readUserState(userId), userId); 6614 if (info != null) { 6615 finalList.add(info); 6616 } 6617 } 6618 } 6619 } 6620 6621 if (finalList != null) { 6622 Collections.sort(finalList, mProviderInitOrderSorter); 6623 return new ParceledListSlice<ProviderInfo>(finalList); 6624 } 6625 6626 return ParceledListSlice.emptyList(); 6627 } 6628 6629 @Override 6630 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6631 // reader 6632 synchronized (mPackages) { 6633 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6634 return PackageParser.generateInstrumentationInfo(i, flags); 6635 } 6636 } 6637 6638 @Override 6639 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6640 String targetPackage, int flags) { 6641 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6642 } 6643 6644 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6645 int flags) { 6646 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6647 6648 // reader 6649 synchronized (mPackages) { 6650 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6651 while (i.hasNext()) { 6652 final PackageParser.Instrumentation p = i.next(); 6653 if (targetPackage == null 6654 || targetPackage.equals(p.info.targetPackage)) { 6655 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6656 flags); 6657 if (ii != null) { 6658 finalList.add(ii); 6659 } 6660 } 6661 } 6662 } 6663 6664 return finalList; 6665 } 6666 6667 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6668 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6669 if (overlays == null) { 6670 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6671 return; 6672 } 6673 for (PackageParser.Package opkg : overlays.values()) { 6674 // Not much to do if idmap fails: we already logged the error 6675 // and we certainly don't want to abort installation of pkg simply 6676 // because an overlay didn't fit properly. For these reasons, 6677 // ignore the return value of createIdmapForPackagePairLI. 6678 createIdmapForPackagePairLI(pkg, opkg); 6679 } 6680 } 6681 6682 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6683 PackageParser.Package opkg) { 6684 if (!opkg.mTrustedOverlay) { 6685 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6686 opkg.baseCodePath + ": overlay not trusted"); 6687 return false; 6688 } 6689 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6690 if (overlaySet == null) { 6691 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6692 opkg.baseCodePath + " but target package has no known overlays"); 6693 return false; 6694 } 6695 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6696 // TODO: generate idmap for split APKs 6697 try { 6698 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6699 } catch (InstallerException e) { 6700 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6701 + opkg.baseCodePath); 6702 return false; 6703 } 6704 PackageParser.Package[] overlayArray = 6705 overlaySet.values().toArray(new PackageParser.Package[0]); 6706 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6707 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6708 return p1.mOverlayPriority - p2.mOverlayPriority; 6709 } 6710 }; 6711 Arrays.sort(overlayArray, cmp); 6712 6713 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6714 int i = 0; 6715 for (PackageParser.Package p : overlayArray) { 6716 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6717 } 6718 return true; 6719 } 6720 6721 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6722 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6723 try { 6724 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6725 } finally { 6726 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6727 } 6728 } 6729 6730 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6731 final File[] files = dir.listFiles(); 6732 if (ArrayUtils.isEmpty(files)) { 6733 Log.d(TAG, "No files in app dir " + dir); 6734 return; 6735 } 6736 6737 if (DEBUG_PACKAGE_SCANNING) { 6738 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6739 + " flags=0x" + Integer.toHexString(parseFlags)); 6740 } 6741 6742 for (File file : files) { 6743 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6744 && !PackageInstallerService.isStageName(file.getName()); 6745 if (!isPackage) { 6746 // Ignore entries which are not packages 6747 continue; 6748 } 6749 try { 6750 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6751 scanFlags, currentTime, null); 6752 } catch (PackageManagerException e) { 6753 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6754 6755 // Delete invalid userdata apps 6756 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6757 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6758 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6759 removeCodePathLI(file); 6760 } 6761 } 6762 } 6763 } 6764 6765 private static File getSettingsProblemFile() { 6766 File dataDir = Environment.getDataDirectory(); 6767 File systemDir = new File(dataDir, "system"); 6768 File fname = new File(systemDir, "uiderrors.txt"); 6769 return fname; 6770 } 6771 6772 static void reportSettingsProblem(int priority, String msg) { 6773 logCriticalInfo(priority, msg); 6774 } 6775 6776 static void logCriticalInfo(int priority, String msg) { 6777 Slog.println(priority, TAG, msg); 6778 EventLogTags.writePmCriticalInfo(msg); 6779 try { 6780 File fname = getSettingsProblemFile(); 6781 FileOutputStream out = new FileOutputStream(fname, true); 6782 PrintWriter pw = new FastPrintWriter(out); 6783 SimpleDateFormat formatter = new SimpleDateFormat(); 6784 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6785 pw.println(dateString + ": " + msg); 6786 pw.close(); 6787 FileUtils.setPermissions( 6788 fname.toString(), 6789 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6790 -1, -1); 6791 } catch (java.io.IOException e) { 6792 } 6793 } 6794 6795 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6796 final int policyFlags) throws PackageManagerException { 6797 if (ps != null 6798 && ps.codePath.equals(srcFile) 6799 && ps.timeStamp == srcFile.lastModified() 6800 && !isCompatSignatureUpdateNeeded(pkg) 6801 && !isRecoverSignatureUpdateNeeded(pkg)) { 6802 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6803 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6804 ArraySet<PublicKey> signingKs; 6805 synchronized (mPackages) { 6806 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6807 } 6808 if (ps.signatures.mSignatures != null 6809 && ps.signatures.mSignatures.length != 0 6810 && signingKs != null) { 6811 // Optimization: reuse the existing cached certificates 6812 // if the package appears to be unchanged. 6813 pkg.mSignatures = ps.signatures.mSignatures; 6814 pkg.mSigningKeys = signingKs; 6815 return; 6816 } 6817 6818 Slog.w(TAG, "PackageSetting for " + ps.name 6819 + " is missing signatures. Collecting certs again to recover them."); 6820 } else { 6821 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6822 } 6823 6824 try { 6825 PackageParser.collectCertificates(pkg, policyFlags); 6826 } catch (PackageParserException e) { 6827 throw PackageManagerException.from(e); 6828 } 6829 } 6830 6831 /** 6832 * Traces a package scan. 6833 * @see #scanPackageLI(File, int, int, long, UserHandle) 6834 */ 6835 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6836 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6837 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6838 try { 6839 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6840 } finally { 6841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6842 } 6843 } 6844 6845 /** 6846 * Scans a package and returns the newly parsed package. 6847 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6848 */ 6849 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6850 long currentTime, UserHandle user) throws PackageManagerException { 6851 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6852 PackageParser pp = new PackageParser(); 6853 pp.setSeparateProcesses(mSeparateProcesses); 6854 pp.setOnlyCoreApps(mOnlyCore); 6855 pp.setDisplayMetrics(mMetrics); 6856 6857 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6858 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6859 } 6860 6861 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6862 final PackageParser.Package pkg; 6863 try { 6864 pkg = pp.parsePackage(scanFile, parseFlags); 6865 } catch (PackageParserException e) { 6866 throw PackageManagerException.from(e); 6867 } finally { 6868 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6869 } 6870 6871 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6872 } 6873 6874 /** 6875 * Scans a package and returns the newly parsed package. 6876 * @throws PackageManagerException on a parse error. 6877 */ 6878 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6879 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6880 throws PackageManagerException { 6881 // If the package has children and this is the first dive in the function 6882 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6883 // packages (parent and children) would be successfully scanned before the 6884 // actual scan since scanning mutates internal state and we want to atomically 6885 // install the package and its children. 6886 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6887 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6888 scanFlags |= SCAN_CHECK_ONLY; 6889 } 6890 } else { 6891 scanFlags &= ~SCAN_CHECK_ONLY; 6892 } 6893 6894 // Scan the parent 6895 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6896 scanFlags, currentTime, user); 6897 6898 // Scan the children 6899 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6900 for (int i = 0; i < childCount; i++) { 6901 PackageParser.Package childPackage = pkg.childPackages.get(i); 6902 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6903 currentTime, user); 6904 } 6905 6906 6907 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6908 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6909 } 6910 6911 return scannedPkg; 6912 } 6913 6914 /** 6915 * Scans a package and returns the newly parsed package. 6916 * @throws PackageManagerException on a parse error. 6917 */ 6918 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6919 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6920 throws PackageManagerException { 6921 PackageSetting ps = null; 6922 PackageSetting updatedPkg; 6923 // reader 6924 synchronized (mPackages) { 6925 // Look to see if we already know about this package. 6926 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6927 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6928 // This package has been renamed to its original name. Let's 6929 // use that. 6930 ps = mSettings.peekPackageLPr(oldName); 6931 } 6932 // If there was no original package, see one for the real package name. 6933 if (ps == null) { 6934 ps = mSettings.peekPackageLPr(pkg.packageName); 6935 } 6936 // Check to see if this package could be hiding/updating a system 6937 // package. Must look for it either under the original or real 6938 // package name depending on our state. 6939 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6940 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6941 6942 // If this is a package we don't know about on the system partition, we 6943 // may need to remove disabled child packages on the system partition 6944 // or may need to not add child packages if the parent apk is updated 6945 // on the data partition and no longer defines this child package. 6946 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6947 // If this is a parent package for an updated system app and this system 6948 // app got an OTA update which no longer defines some of the child packages 6949 // we have to prune them from the disabled system packages. 6950 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6951 if (disabledPs != null) { 6952 final int scannedChildCount = (pkg.childPackages != null) 6953 ? pkg.childPackages.size() : 0; 6954 final int disabledChildCount = disabledPs.childPackageNames != null 6955 ? disabledPs.childPackageNames.size() : 0; 6956 for (int i = 0; i < disabledChildCount; i++) { 6957 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6958 boolean disabledPackageAvailable = false; 6959 for (int j = 0; j < scannedChildCount; j++) { 6960 PackageParser.Package childPkg = pkg.childPackages.get(j); 6961 if (childPkg.packageName.equals(disabledChildPackageName)) { 6962 disabledPackageAvailable = true; 6963 break; 6964 } 6965 } 6966 if (!disabledPackageAvailable) { 6967 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6968 } 6969 } 6970 } 6971 } 6972 } 6973 6974 boolean updatedPkgBetter = false; 6975 // First check if this is a system package that may involve an update 6976 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6977 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6978 // it needs to drop FLAG_PRIVILEGED. 6979 if (locationIsPrivileged(scanFile)) { 6980 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6981 } else { 6982 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6983 } 6984 6985 if (ps != null && !ps.codePath.equals(scanFile)) { 6986 // The path has changed from what was last scanned... check the 6987 // version of the new path against what we have stored to determine 6988 // what to do. 6989 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6990 if (pkg.mVersionCode <= ps.versionCode) { 6991 // The system package has been updated and the code path does not match 6992 // Ignore entry. Skip it. 6993 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6994 + " ignored: updated version " + ps.versionCode 6995 + " better than this " + pkg.mVersionCode); 6996 if (!updatedPkg.codePath.equals(scanFile)) { 6997 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6998 + ps.name + " changing from " + updatedPkg.codePathString 6999 + " to " + scanFile); 7000 updatedPkg.codePath = scanFile; 7001 updatedPkg.codePathString = scanFile.toString(); 7002 updatedPkg.resourcePath = scanFile; 7003 updatedPkg.resourcePathString = scanFile.toString(); 7004 } 7005 updatedPkg.pkg = pkg; 7006 updatedPkg.versionCode = pkg.mVersionCode; 7007 7008 // Update the disabled system child packages to point to the package too. 7009 final int childCount = updatedPkg.childPackageNames != null 7010 ? updatedPkg.childPackageNames.size() : 0; 7011 for (int i = 0; i < childCount; i++) { 7012 String childPackageName = updatedPkg.childPackageNames.get(i); 7013 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 7014 childPackageName); 7015 if (updatedChildPkg != null) { 7016 updatedChildPkg.pkg = pkg; 7017 updatedChildPkg.versionCode = pkg.mVersionCode; 7018 } 7019 } 7020 7021 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 7022 + scanFile + " ignored: updated version " + ps.versionCode 7023 + " better than this " + pkg.mVersionCode); 7024 } else { 7025 // The current app on the system partition is better than 7026 // what we have updated to on the data partition; switch 7027 // back to the system partition version. 7028 // At this point, its safely assumed that package installation for 7029 // apps in system partition will go through. If not there won't be a working 7030 // version of the app 7031 // writer 7032 synchronized (mPackages) { 7033 // Just remove the loaded entries from package lists. 7034 mPackages.remove(ps.name); 7035 } 7036 7037 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7038 + " reverting from " + ps.codePathString 7039 + ": new version " + pkg.mVersionCode 7040 + " better than installed " + ps.versionCode); 7041 7042 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7043 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7044 synchronized (mInstallLock) { 7045 args.cleanUpResourcesLI(); 7046 } 7047 synchronized (mPackages) { 7048 mSettings.enableSystemPackageLPw(ps.name); 7049 } 7050 updatedPkgBetter = true; 7051 } 7052 } 7053 } 7054 7055 if (updatedPkg != null) { 7056 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7057 // initially 7058 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7059 7060 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7061 // flag set initially 7062 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7063 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7064 } 7065 } 7066 7067 // Verify certificates against what was last scanned 7068 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7069 7070 /* 7071 * A new system app appeared, but we already had a non-system one of the 7072 * same name installed earlier. 7073 */ 7074 boolean shouldHideSystemApp = false; 7075 if (updatedPkg == null && ps != null 7076 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7077 /* 7078 * Check to make sure the signatures match first. If they don't, 7079 * wipe the installed application and its data. 7080 */ 7081 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7082 != PackageManager.SIGNATURE_MATCH) { 7083 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7084 + " signatures don't match existing userdata copy; removing"); 7085 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7086 "scanPackageInternalLI")) { 7087 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7088 } 7089 ps = null; 7090 } else { 7091 /* 7092 * If the newly-added system app is an older version than the 7093 * already installed version, hide it. It will be scanned later 7094 * and re-added like an update. 7095 */ 7096 if (pkg.mVersionCode <= ps.versionCode) { 7097 shouldHideSystemApp = true; 7098 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7099 + " but new version " + pkg.mVersionCode + " better than installed " 7100 + ps.versionCode + "; hiding system"); 7101 } else { 7102 /* 7103 * The newly found system app is a newer version that the 7104 * one previously installed. Simply remove the 7105 * already-installed application and replace it with our own 7106 * while keeping the application data. 7107 */ 7108 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7109 + " reverting from " + ps.codePathString + ": new version " 7110 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7111 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7112 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7113 synchronized (mInstallLock) { 7114 args.cleanUpResourcesLI(); 7115 } 7116 } 7117 } 7118 } 7119 7120 // The apk is forward locked (not public) if its code and resources 7121 // are kept in different files. (except for app in either system or 7122 // vendor path). 7123 // TODO grab this value from PackageSettings 7124 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7125 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7126 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7127 } 7128 } 7129 7130 // TODO: extend to support forward-locked splits 7131 String resourcePath = null; 7132 String baseResourcePath = null; 7133 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7134 if (ps != null && ps.resourcePathString != null) { 7135 resourcePath = ps.resourcePathString; 7136 baseResourcePath = ps.resourcePathString; 7137 } else { 7138 // Should not happen at all. Just log an error. 7139 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7140 } 7141 } else { 7142 resourcePath = pkg.codePath; 7143 baseResourcePath = pkg.baseCodePath; 7144 } 7145 7146 // Set application objects path explicitly. 7147 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7148 pkg.setApplicationInfoCodePath(pkg.codePath); 7149 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7150 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7151 pkg.setApplicationInfoResourcePath(resourcePath); 7152 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7153 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7154 7155 // Note that we invoke the following method only if we are about to unpack an application 7156 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7157 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7158 7159 /* 7160 * If the system app should be overridden by a previously installed 7161 * data, hide the system app now and let the /data/app scan pick it up 7162 * again. 7163 */ 7164 if (shouldHideSystemApp) { 7165 synchronized (mPackages) { 7166 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7167 } 7168 } 7169 7170 return scannedPkg; 7171 } 7172 7173 private static String fixProcessName(String defProcessName, 7174 String processName, int uid) { 7175 if (processName == null) { 7176 return defProcessName; 7177 } 7178 return processName; 7179 } 7180 7181 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7182 throws PackageManagerException { 7183 if (pkgSetting.signatures.mSignatures != null) { 7184 // Already existing package. Make sure signatures match 7185 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7186 == PackageManager.SIGNATURE_MATCH; 7187 if (!match) { 7188 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7189 == PackageManager.SIGNATURE_MATCH; 7190 } 7191 if (!match) { 7192 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7193 == PackageManager.SIGNATURE_MATCH; 7194 } 7195 if (!match) { 7196 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7197 + pkg.packageName + " signatures do not match the " 7198 + "previously installed version; ignoring!"); 7199 } 7200 } 7201 7202 // Check for shared user signatures 7203 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7204 // Already existing package. Make sure signatures match 7205 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7206 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7207 if (!match) { 7208 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7209 == PackageManager.SIGNATURE_MATCH; 7210 } 7211 if (!match) { 7212 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7213 == PackageManager.SIGNATURE_MATCH; 7214 } 7215 if (!match) { 7216 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7217 "Package " + pkg.packageName 7218 + " has no signatures that match those in shared user " 7219 + pkgSetting.sharedUser.name + "; ignoring!"); 7220 } 7221 } 7222 } 7223 7224 /** 7225 * Enforces that only the system UID or root's UID can call a method exposed 7226 * via Binder. 7227 * 7228 * @param message used as message if SecurityException is thrown 7229 * @throws SecurityException if the caller is not system or root 7230 */ 7231 private static final void enforceSystemOrRoot(String message) { 7232 final int uid = Binder.getCallingUid(); 7233 if (uid != Process.SYSTEM_UID && uid != 0) { 7234 throw new SecurityException(message); 7235 } 7236 } 7237 7238 @Override 7239 public void performFstrimIfNeeded() { 7240 enforceSystemOrRoot("Only the system can request fstrim"); 7241 7242 // Before everything else, see whether we need to fstrim. 7243 try { 7244 IMountService ms = PackageHelper.getMountService(); 7245 if (ms != null) { 7246 final boolean isUpgrade = isUpgrade(); 7247 boolean doTrim = isUpgrade; 7248 if (doTrim) { 7249 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7250 } else { 7251 final long interval = android.provider.Settings.Global.getLong( 7252 mContext.getContentResolver(), 7253 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7254 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7255 if (interval > 0) { 7256 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7257 if (timeSinceLast > interval) { 7258 doTrim = true; 7259 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7260 + "; running immediately"); 7261 } 7262 } 7263 } 7264 if (doTrim) { 7265 if (!isFirstBoot()) { 7266 try { 7267 ActivityManagerNative.getDefault().showBootMessage( 7268 mContext.getResources().getString( 7269 R.string.android_upgrading_fstrim), true); 7270 } catch (RemoteException e) { 7271 } 7272 } 7273 ms.runMaintenance(); 7274 } 7275 } else { 7276 Slog.e(TAG, "Mount service unavailable!"); 7277 } 7278 } catch (RemoteException e) { 7279 // Can't happen; MountService is local 7280 } 7281 } 7282 7283 @Override 7284 public void updatePackagesIfNeeded() { 7285 enforceSystemOrRoot("Only the system can request package update"); 7286 7287 // We need to re-extract after an OTA. 7288 boolean causeUpgrade = isUpgrade(); 7289 7290 // First boot or factory reset. 7291 // Note: we also handle devices that are upgrading to N right now as if it is their 7292 // first boot, as they do not have profile data. 7293 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7294 7295 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7296 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7297 7298 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7299 return; 7300 } 7301 7302 List<PackageParser.Package> pkgs; 7303 synchronized (mPackages) { 7304 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7305 } 7306 7307 final long startTime = System.nanoTime(); 7308 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7309 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7310 7311 final int elapsedTimeSeconds = 7312 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7313 7314 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7315 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7316 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7317 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7318 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7319 } 7320 7321 /** 7322 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7323 * containing statistics about the invocation. The array consists of three elements, 7324 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7325 * and {@code numberOfPackagesFailed}. 7326 */ 7327 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7328 String compilerFilter) { 7329 7330 int numberOfPackagesVisited = 0; 7331 int numberOfPackagesOptimized = 0; 7332 int numberOfPackagesSkipped = 0; 7333 int numberOfPackagesFailed = 0; 7334 final int numberOfPackagesToDexopt = pkgs.size(); 7335 7336 for (PackageParser.Package pkg : pkgs) { 7337 numberOfPackagesVisited++; 7338 7339 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7340 if (DEBUG_DEXOPT) { 7341 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7342 } 7343 numberOfPackagesSkipped++; 7344 continue; 7345 } 7346 7347 if (DEBUG_DEXOPT) { 7348 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7349 numberOfPackagesToDexopt + ": " + pkg.packageName); 7350 } 7351 7352 if (showDialog) { 7353 try { 7354 ActivityManagerNative.getDefault().showBootMessage( 7355 mContext.getResources().getString(R.string.android_upgrading_apk, 7356 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7357 } catch (RemoteException e) { 7358 } 7359 } 7360 7361 // checkProfiles is false to avoid merging profiles during boot which 7362 // might interfere with background compilation (b/28612421). 7363 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7364 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7365 // trade-off worth doing to save boot time work. 7366 int dexOptStatus = performDexOptTraced(pkg.packageName, 7367 false /* checkProfiles */, 7368 compilerFilter, 7369 false /* force */); 7370 switch (dexOptStatus) { 7371 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7372 numberOfPackagesOptimized++; 7373 break; 7374 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7375 numberOfPackagesSkipped++; 7376 break; 7377 case PackageDexOptimizer.DEX_OPT_FAILED: 7378 numberOfPackagesFailed++; 7379 break; 7380 default: 7381 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7382 break; 7383 } 7384 } 7385 7386 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7387 numberOfPackagesFailed }; 7388 } 7389 7390 @Override 7391 public void notifyPackageUse(String packageName, int reason) { 7392 synchronized (mPackages) { 7393 PackageParser.Package p = mPackages.get(packageName); 7394 if (p == null) { 7395 return; 7396 } 7397 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7398 } 7399 } 7400 7401 // TODO: this is not used nor needed. Delete it. 7402 @Override 7403 public boolean performDexOptIfNeeded(String packageName) { 7404 int dexOptStatus = performDexOptTraced(packageName, 7405 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7406 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7407 } 7408 7409 @Override 7410 public boolean performDexOpt(String packageName, 7411 boolean checkProfiles, int compileReason, boolean force) { 7412 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7413 getCompilerFilterForReason(compileReason), force); 7414 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7415 } 7416 7417 @Override 7418 public boolean performDexOptMode(String packageName, 7419 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7420 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7421 targetCompilerFilter, force); 7422 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7423 } 7424 7425 private int performDexOptTraced(String packageName, 7426 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7428 try { 7429 return performDexOptInternal(packageName, checkProfiles, 7430 targetCompilerFilter, force); 7431 } finally { 7432 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7433 } 7434 } 7435 7436 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7437 // if the package can now be considered up to date for the given filter. 7438 private int performDexOptInternal(String packageName, 7439 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7440 PackageParser.Package p; 7441 synchronized (mPackages) { 7442 p = mPackages.get(packageName); 7443 if (p == null) { 7444 // Package could not be found. Report failure. 7445 return PackageDexOptimizer.DEX_OPT_FAILED; 7446 } 7447 mPackageUsage.write(false); 7448 } 7449 long callingId = Binder.clearCallingIdentity(); 7450 try { 7451 synchronized (mInstallLock) { 7452 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7453 targetCompilerFilter, force); 7454 } 7455 } finally { 7456 Binder.restoreCallingIdentity(callingId); 7457 } 7458 } 7459 7460 public ArraySet<String> getOptimizablePackages() { 7461 ArraySet<String> pkgs = new ArraySet<String>(); 7462 synchronized (mPackages) { 7463 for (PackageParser.Package p : mPackages.values()) { 7464 if (PackageDexOptimizer.canOptimizePackage(p)) { 7465 pkgs.add(p.packageName); 7466 } 7467 } 7468 } 7469 return pkgs; 7470 } 7471 7472 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7473 boolean checkProfiles, String targetCompilerFilter, 7474 boolean force) { 7475 // Select the dex optimizer based on the force parameter. 7476 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7477 // allocate an object here. 7478 PackageDexOptimizer pdo = force 7479 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7480 : mPackageDexOptimizer; 7481 7482 // Optimize all dependencies first. Note: we ignore the return value and march on 7483 // on errors. 7484 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7485 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7486 if (!deps.isEmpty()) { 7487 for (PackageParser.Package depPackage : deps) { 7488 // TODO: Analyze and investigate if we (should) profile libraries. 7489 // Currently this will do a full compilation of the library by default. 7490 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7491 false /* checkProfiles */, 7492 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7493 } 7494 } 7495 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7496 targetCompilerFilter); 7497 } 7498 7499 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7500 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7501 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7502 Set<String> collectedNames = new HashSet<>(); 7503 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7504 7505 retValue.remove(p); 7506 7507 return retValue; 7508 } else { 7509 return Collections.emptyList(); 7510 } 7511 } 7512 7513 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7514 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7515 if (!collectedNames.contains(p.packageName)) { 7516 collectedNames.add(p.packageName); 7517 collected.add(p); 7518 7519 if (p.usesLibraries != null) { 7520 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7521 } 7522 if (p.usesOptionalLibraries != null) { 7523 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7524 collectedNames); 7525 } 7526 } 7527 } 7528 7529 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7530 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7531 for (String libName : libs) { 7532 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7533 if (libPkg != null) { 7534 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7535 } 7536 } 7537 } 7538 7539 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7540 synchronized (mPackages) { 7541 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7542 if (lib != null && lib.apk != null) { 7543 return mPackages.get(lib.apk); 7544 } 7545 } 7546 return null; 7547 } 7548 7549 public void shutdown() { 7550 mPackageUsage.write(true); 7551 } 7552 7553 @Override 7554 public void dumpProfiles(String packageName) { 7555 PackageParser.Package pkg; 7556 synchronized (mPackages) { 7557 pkg = mPackages.get(packageName); 7558 if (pkg == null) { 7559 throw new IllegalArgumentException("Unknown package: " + packageName); 7560 } 7561 } 7562 /* Only the shell, root, or the app user should be able to dump profiles. */ 7563 int callingUid = Binder.getCallingUid(); 7564 if (callingUid != Process.SHELL_UID && 7565 callingUid != Process.ROOT_UID && 7566 callingUid != pkg.applicationInfo.uid) { 7567 throw new SecurityException("dumpProfiles"); 7568 } 7569 7570 synchronized (mInstallLock) { 7571 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7572 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7573 try { 7574 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7575 String gid = Integer.toString(sharedGid); 7576 String codePaths = TextUtils.join(";", allCodePaths); 7577 mInstaller.dumpProfiles(gid, packageName, codePaths); 7578 } catch (InstallerException e) { 7579 Slog.w(TAG, "Failed to dump profiles", e); 7580 } 7581 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7582 } 7583 } 7584 7585 @Override 7586 public void forceDexOpt(String packageName) { 7587 enforceSystemOrRoot("forceDexOpt"); 7588 7589 PackageParser.Package pkg; 7590 synchronized (mPackages) { 7591 pkg = mPackages.get(packageName); 7592 if (pkg == null) { 7593 throw new IllegalArgumentException("Unknown package: " + packageName); 7594 } 7595 } 7596 7597 synchronized (mInstallLock) { 7598 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7599 7600 // Whoever is calling forceDexOpt wants a fully compiled package. 7601 // Don't use profiles since that may cause compilation to be skipped. 7602 final int res = performDexOptInternalWithDependenciesLI(pkg, 7603 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7604 true /* force */); 7605 7606 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7607 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7608 throw new IllegalStateException("Failed to dexopt: " + res); 7609 } 7610 } 7611 } 7612 7613 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7614 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7615 Slog.w(TAG, "Unable to update from " + oldPkg.name 7616 + " to " + newPkg.packageName 7617 + ": old package not in system partition"); 7618 return false; 7619 } else if (mPackages.get(oldPkg.name) != null) { 7620 Slog.w(TAG, "Unable to update from " + oldPkg.name 7621 + " to " + newPkg.packageName 7622 + ": old package still exists"); 7623 return false; 7624 } 7625 return true; 7626 } 7627 7628 void removeCodePathLI(File codePath) { 7629 if (codePath.isDirectory()) { 7630 try { 7631 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7632 } catch (InstallerException e) { 7633 Slog.w(TAG, "Failed to remove code path", e); 7634 } 7635 } else { 7636 codePath.delete(); 7637 } 7638 } 7639 7640 private int[] resolveUserIds(int userId) { 7641 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7642 } 7643 7644 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7645 if (pkg == null) { 7646 Slog.wtf(TAG, "Package was null!", new Throwable()); 7647 return; 7648 } 7649 clearAppDataLeafLIF(pkg, userId, flags); 7650 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7651 for (int i = 0; i < childCount; i++) { 7652 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7653 } 7654 } 7655 7656 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7657 final PackageSetting ps; 7658 synchronized (mPackages) { 7659 ps = mSettings.mPackages.get(pkg.packageName); 7660 } 7661 for (int realUserId : resolveUserIds(userId)) { 7662 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7663 try { 7664 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7665 ceDataInode); 7666 } catch (InstallerException e) { 7667 Slog.w(TAG, String.valueOf(e)); 7668 } 7669 } 7670 } 7671 7672 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7673 if (pkg == null) { 7674 Slog.wtf(TAG, "Package was null!", new Throwable()); 7675 return; 7676 } 7677 destroyAppDataLeafLIF(pkg, userId, flags); 7678 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7679 for (int i = 0; i < childCount; i++) { 7680 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7681 } 7682 } 7683 7684 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7685 final PackageSetting ps; 7686 synchronized (mPackages) { 7687 ps = mSettings.mPackages.get(pkg.packageName); 7688 } 7689 for (int realUserId : resolveUserIds(userId)) { 7690 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7691 try { 7692 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7693 ceDataInode); 7694 } catch (InstallerException e) { 7695 Slog.w(TAG, String.valueOf(e)); 7696 } 7697 } 7698 } 7699 7700 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7701 if (pkg == null) { 7702 Slog.wtf(TAG, "Package was null!", new Throwable()); 7703 return; 7704 } 7705 destroyAppProfilesLeafLIF(pkg); 7706 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7707 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7708 for (int i = 0; i < childCount; i++) { 7709 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7710 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7711 true /* removeBaseMarker */); 7712 } 7713 } 7714 7715 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7716 boolean removeBaseMarker) { 7717 if (pkg.isForwardLocked()) { 7718 return; 7719 } 7720 7721 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7722 try { 7723 path = PackageManagerServiceUtils.realpath(new File(path)); 7724 } catch (IOException e) { 7725 // TODO: Should we return early here ? 7726 Slog.w(TAG, "Failed to get canonical path", e); 7727 continue; 7728 } 7729 7730 final String useMarker = path.replace('/', '@'); 7731 for (int realUserId : resolveUserIds(userId)) { 7732 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7733 if (removeBaseMarker) { 7734 File foreignUseMark = new File(profileDir, useMarker); 7735 if (foreignUseMark.exists()) { 7736 if (!foreignUseMark.delete()) { 7737 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7738 + pkg.packageName); 7739 } 7740 } 7741 } 7742 7743 File[] markers = profileDir.listFiles(); 7744 if (markers != null) { 7745 final String searchString = "@" + pkg.packageName + "@"; 7746 // We also delete all markers that contain the package name we're 7747 // uninstalling. These are associated with secondary dex-files belonging 7748 // to the package. Reconstructing the path of these dex files is messy 7749 // in general. 7750 for (File marker : markers) { 7751 if (marker.getName().indexOf(searchString) > 0) { 7752 if (!marker.delete()) { 7753 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7754 + pkg.packageName); 7755 } 7756 } 7757 } 7758 } 7759 } 7760 } 7761 } 7762 7763 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7764 try { 7765 mInstaller.destroyAppProfiles(pkg.packageName); 7766 } catch (InstallerException e) { 7767 Slog.w(TAG, String.valueOf(e)); 7768 } 7769 } 7770 7771 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7772 if (pkg == null) { 7773 Slog.wtf(TAG, "Package was null!", new Throwable()); 7774 return; 7775 } 7776 clearAppProfilesLeafLIF(pkg); 7777 // We don't remove the base foreign use marker when clearing profiles because 7778 // we will rename it when the app is updated. Unlike the actual profile contents, 7779 // the foreign use marker is good across installs. 7780 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7781 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7782 for (int i = 0; i < childCount; i++) { 7783 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7784 } 7785 } 7786 7787 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7788 try { 7789 mInstaller.clearAppProfiles(pkg.packageName); 7790 } catch (InstallerException e) { 7791 Slog.w(TAG, String.valueOf(e)); 7792 } 7793 } 7794 7795 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7796 long lastUpdateTime) { 7797 // Set parent install/update time 7798 PackageSetting ps = (PackageSetting) pkg.mExtras; 7799 if (ps != null) { 7800 ps.firstInstallTime = firstInstallTime; 7801 ps.lastUpdateTime = lastUpdateTime; 7802 } 7803 // Set children install/update time 7804 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7805 for (int i = 0; i < childCount; i++) { 7806 PackageParser.Package childPkg = pkg.childPackages.get(i); 7807 ps = (PackageSetting) childPkg.mExtras; 7808 if (ps != null) { 7809 ps.firstInstallTime = firstInstallTime; 7810 ps.lastUpdateTime = lastUpdateTime; 7811 } 7812 } 7813 } 7814 7815 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7816 PackageParser.Package changingLib) { 7817 if (file.path != null) { 7818 usesLibraryFiles.add(file.path); 7819 return; 7820 } 7821 PackageParser.Package p = mPackages.get(file.apk); 7822 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7823 // If we are doing this while in the middle of updating a library apk, 7824 // then we need to make sure to use that new apk for determining the 7825 // dependencies here. (We haven't yet finished committing the new apk 7826 // to the package manager state.) 7827 if (p == null || p.packageName.equals(changingLib.packageName)) { 7828 p = changingLib; 7829 } 7830 } 7831 if (p != null) { 7832 usesLibraryFiles.addAll(p.getAllCodePaths()); 7833 } 7834 } 7835 7836 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7837 PackageParser.Package changingLib) throws PackageManagerException { 7838 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7839 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7840 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7841 for (int i=0; i<N; i++) { 7842 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7843 if (file == null) { 7844 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7845 "Package " + pkg.packageName + " requires unavailable shared library " 7846 + pkg.usesLibraries.get(i) + "; failing!"); 7847 } 7848 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7849 } 7850 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7851 for (int i=0; i<N; i++) { 7852 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7853 if (file == null) { 7854 Slog.w(TAG, "Package " + pkg.packageName 7855 + " desires unavailable shared library " 7856 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7857 } else { 7858 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7859 } 7860 } 7861 N = usesLibraryFiles.size(); 7862 if (N > 0) { 7863 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7864 } else { 7865 pkg.usesLibraryFiles = null; 7866 } 7867 } 7868 } 7869 7870 private static boolean hasString(List<String> list, List<String> which) { 7871 if (list == null) { 7872 return false; 7873 } 7874 for (int i=list.size()-1; i>=0; i--) { 7875 for (int j=which.size()-1; j>=0; j--) { 7876 if (which.get(j).equals(list.get(i))) { 7877 return true; 7878 } 7879 } 7880 } 7881 return false; 7882 } 7883 7884 private void updateAllSharedLibrariesLPw() { 7885 for (PackageParser.Package pkg : mPackages.values()) { 7886 try { 7887 updateSharedLibrariesLPw(pkg, null); 7888 } catch (PackageManagerException e) { 7889 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7890 } 7891 } 7892 } 7893 7894 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7895 PackageParser.Package changingPkg) { 7896 ArrayList<PackageParser.Package> res = null; 7897 for (PackageParser.Package pkg : mPackages.values()) { 7898 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7899 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7900 if (res == null) { 7901 res = new ArrayList<PackageParser.Package>(); 7902 } 7903 res.add(pkg); 7904 try { 7905 updateSharedLibrariesLPw(pkg, changingPkg); 7906 } catch (PackageManagerException e) { 7907 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7908 } 7909 } 7910 } 7911 return res; 7912 } 7913 7914 /** 7915 * Derive the value of the {@code cpuAbiOverride} based on the provided 7916 * value and an optional stored value from the package settings. 7917 */ 7918 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7919 String cpuAbiOverride = null; 7920 7921 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7922 cpuAbiOverride = null; 7923 } else if (abiOverride != null) { 7924 cpuAbiOverride = abiOverride; 7925 } else if (settings != null) { 7926 cpuAbiOverride = settings.cpuAbiOverrideString; 7927 } 7928 7929 return cpuAbiOverride; 7930 } 7931 7932 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7933 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7934 throws PackageManagerException { 7935 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7936 // If the package has children and this is the first dive in the function 7937 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7938 // whether all packages (parent and children) would be successfully scanned 7939 // before the actual scan since scanning mutates internal state and we want 7940 // to atomically install the package and its children. 7941 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7942 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7943 scanFlags |= SCAN_CHECK_ONLY; 7944 } 7945 } else { 7946 scanFlags &= ~SCAN_CHECK_ONLY; 7947 } 7948 7949 final PackageParser.Package scannedPkg; 7950 try { 7951 // Scan the parent 7952 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7953 // Scan the children 7954 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7955 for (int i = 0; i < childCount; i++) { 7956 PackageParser.Package childPkg = pkg.childPackages.get(i); 7957 scanPackageLI(childPkg, policyFlags, 7958 scanFlags, currentTime, user); 7959 } 7960 } finally { 7961 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7962 } 7963 7964 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7965 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7966 } 7967 7968 return scannedPkg; 7969 } 7970 7971 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7972 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7973 boolean success = false; 7974 try { 7975 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7976 currentTime, user); 7977 success = true; 7978 return res; 7979 } finally { 7980 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7981 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7982 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7983 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7984 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7985 } 7986 } 7987 } 7988 7989 /** 7990 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7991 */ 7992 private static boolean apkHasCode(String fileName) { 7993 StrictJarFile jarFile = null; 7994 try { 7995 jarFile = new StrictJarFile(fileName, 7996 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7997 return jarFile.findEntry("classes.dex") != null; 7998 } catch (IOException ignore) { 7999 } finally { 8000 try { 8001 jarFile.close(); 8002 } catch (IOException ignore) {} 8003 } 8004 return false; 8005 } 8006 8007 /** 8008 * Enforces code policy for the package. This ensures that if an APK has 8009 * declared hasCode="true" in its manifest that the APK actually contains 8010 * code. 8011 * 8012 * @throws PackageManagerException If bytecode could not be found when it should exist 8013 */ 8014 private static void enforceCodePolicy(PackageParser.Package pkg) 8015 throws PackageManagerException { 8016 final boolean shouldHaveCode = 8017 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 8018 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 8019 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8020 "Package " + pkg.baseCodePath + " code is missing"); 8021 } 8022 8023 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 8024 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 8025 final boolean splitShouldHaveCode = 8026 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 8027 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 8028 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8029 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8030 } 8031 } 8032 } 8033 } 8034 8035 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8036 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8037 throws PackageManagerException { 8038 final File scanFile = new File(pkg.codePath); 8039 if (pkg.applicationInfo.getCodePath() == null || 8040 pkg.applicationInfo.getResourcePath() == null) { 8041 // Bail out. The resource and code paths haven't been set. 8042 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8043 "Code and resource paths haven't been set correctly"); 8044 } 8045 8046 // Apply policy 8047 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8048 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8049 if (pkg.applicationInfo.isDirectBootAware()) { 8050 // we're direct boot aware; set for all components 8051 for (PackageParser.Service s : pkg.services) { 8052 s.info.encryptionAware = s.info.directBootAware = true; 8053 } 8054 for (PackageParser.Provider p : pkg.providers) { 8055 p.info.encryptionAware = p.info.directBootAware = true; 8056 } 8057 for (PackageParser.Activity a : pkg.activities) { 8058 a.info.encryptionAware = a.info.directBootAware = true; 8059 } 8060 for (PackageParser.Activity r : pkg.receivers) { 8061 r.info.encryptionAware = r.info.directBootAware = true; 8062 } 8063 } 8064 } else { 8065 // Only allow system apps to be flagged as core apps. 8066 pkg.coreApp = false; 8067 // clear flags not applicable to regular apps 8068 pkg.applicationInfo.privateFlags &= 8069 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8070 pkg.applicationInfo.privateFlags &= 8071 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8072 } 8073 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8074 8075 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8076 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8077 } 8078 8079 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8080 enforceCodePolicy(pkg); 8081 } 8082 8083 if (mCustomResolverComponentName != null && 8084 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8085 setUpCustomResolverActivity(pkg); 8086 } 8087 8088 if (pkg.packageName.equals("android")) { 8089 synchronized (mPackages) { 8090 if (mAndroidApplication != null) { 8091 Slog.w(TAG, "*************************************************"); 8092 Slog.w(TAG, "Core android package being redefined. Skipping."); 8093 Slog.w(TAG, " file=" + scanFile); 8094 Slog.w(TAG, "*************************************************"); 8095 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8096 "Core android package being redefined. Skipping."); 8097 } 8098 8099 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8100 // Set up information for our fall-back user intent resolution activity. 8101 mPlatformPackage = pkg; 8102 pkg.mVersionCode = mSdkVersion; 8103 mAndroidApplication = pkg.applicationInfo; 8104 8105 if (!mResolverReplaced) { 8106 mResolveActivity.applicationInfo = mAndroidApplication; 8107 mResolveActivity.name = ResolverActivity.class.getName(); 8108 mResolveActivity.packageName = mAndroidApplication.packageName; 8109 mResolveActivity.processName = "system:ui"; 8110 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8111 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8112 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8113 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8114 mResolveActivity.exported = true; 8115 mResolveActivity.enabled = true; 8116 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8117 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8118 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8119 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8120 | ActivityInfo.CONFIG_ORIENTATION 8121 | ActivityInfo.CONFIG_KEYBOARD 8122 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8123 mResolveInfo.activityInfo = mResolveActivity; 8124 mResolveInfo.priority = 0; 8125 mResolveInfo.preferredOrder = 0; 8126 mResolveInfo.match = 0; 8127 mResolveComponentName = new ComponentName( 8128 mAndroidApplication.packageName, mResolveActivity.name); 8129 } 8130 } 8131 } 8132 } 8133 8134 if (DEBUG_PACKAGE_SCANNING) { 8135 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8136 Log.d(TAG, "Scanning package " + pkg.packageName); 8137 } 8138 8139 synchronized (mPackages) { 8140 if (mPackages.containsKey(pkg.packageName) 8141 || mSharedLibraries.containsKey(pkg.packageName)) { 8142 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8143 "Application package " + pkg.packageName 8144 + " already installed. Skipping duplicate."); 8145 } 8146 8147 // If we're only installing presumed-existing packages, require that the 8148 // scanned APK is both already known and at the path previously established 8149 // for it. Previously unknown packages we pick up normally, but if we have an 8150 // a priori expectation about this package's install presence, enforce it. 8151 // With a singular exception for new system packages. When an OTA contains 8152 // a new system package, we allow the codepath to change from a system location 8153 // to the user-installed location. If we don't allow this change, any newer, 8154 // user-installed version of the application will be ignored. 8155 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8156 if (mExpectingBetter.containsKey(pkg.packageName)) { 8157 logCriticalInfo(Log.WARN, 8158 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8159 } else { 8160 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8161 if (known != null) { 8162 if (DEBUG_PACKAGE_SCANNING) { 8163 Log.d(TAG, "Examining " + pkg.codePath 8164 + " and requiring known paths " + known.codePathString 8165 + " & " + known.resourcePathString); 8166 } 8167 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8168 || !pkg.applicationInfo.getResourcePath().equals( 8169 known.resourcePathString)) { 8170 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8171 "Application package " + pkg.packageName 8172 + " found at " + pkg.applicationInfo.getCodePath() 8173 + " but expected at " + known.codePathString 8174 + "; ignoring."); 8175 } 8176 } 8177 } 8178 } 8179 } 8180 8181 // Initialize package source and resource directories 8182 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8183 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8184 8185 SharedUserSetting suid = null; 8186 PackageSetting pkgSetting = null; 8187 8188 if (!isSystemApp(pkg)) { 8189 // Only system apps can use these features. 8190 pkg.mOriginalPackages = null; 8191 pkg.mRealPackage = null; 8192 pkg.mAdoptPermissions = null; 8193 } 8194 8195 // Getting the package setting may have a side-effect, so if we 8196 // are only checking if scan would succeed, stash a copy of the 8197 // old setting to restore at the end. 8198 PackageSetting nonMutatedPs = null; 8199 8200 // writer 8201 synchronized (mPackages) { 8202 if (pkg.mSharedUserId != null) { 8203 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8204 if (suid == null) { 8205 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8206 "Creating application package " + pkg.packageName 8207 + " for shared user failed"); 8208 } 8209 if (DEBUG_PACKAGE_SCANNING) { 8210 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8211 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8212 + "): packages=" + suid.packages); 8213 } 8214 } 8215 8216 // Check if we are renaming from an original package name. 8217 PackageSetting origPackage = null; 8218 String realName = null; 8219 if (pkg.mOriginalPackages != null) { 8220 // This package may need to be renamed to a previously 8221 // installed name. Let's check on that... 8222 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8223 if (pkg.mOriginalPackages.contains(renamed)) { 8224 // This package had originally been installed as the 8225 // original name, and we have already taken care of 8226 // transitioning to the new one. Just update the new 8227 // one to continue using the old name. 8228 realName = pkg.mRealPackage; 8229 if (!pkg.packageName.equals(renamed)) { 8230 // Callers into this function may have already taken 8231 // care of renaming the package; only do it here if 8232 // it is not already done. 8233 pkg.setPackageName(renamed); 8234 } 8235 8236 } else { 8237 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8238 if ((origPackage = mSettings.peekPackageLPr( 8239 pkg.mOriginalPackages.get(i))) != null) { 8240 // We do have the package already installed under its 8241 // original name... should we use it? 8242 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8243 // New package is not compatible with original. 8244 origPackage = null; 8245 continue; 8246 } else if (origPackage.sharedUser != null) { 8247 // Make sure uid is compatible between packages. 8248 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8249 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8250 + " to " + pkg.packageName + ": old uid " 8251 + origPackage.sharedUser.name 8252 + " differs from " + pkg.mSharedUserId); 8253 origPackage = null; 8254 continue; 8255 } 8256 // TODO: Add case when shared user id is added [b/28144775] 8257 } else { 8258 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8259 + pkg.packageName + " to old name " + origPackage.name); 8260 } 8261 break; 8262 } 8263 } 8264 } 8265 } 8266 8267 if (mTransferedPackages.contains(pkg.packageName)) { 8268 Slog.w(TAG, "Package " + pkg.packageName 8269 + " was transferred to another, but its .apk remains"); 8270 } 8271 8272 // See comments in nonMutatedPs declaration 8273 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8274 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8275 if (foundPs != null) { 8276 nonMutatedPs = new PackageSetting(foundPs); 8277 } 8278 } 8279 8280 // Just create the setting, don't add it yet. For already existing packages 8281 // the PkgSetting exists already and doesn't have to be created. 8282 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8283 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8284 pkg.applicationInfo.primaryCpuAbi, 8285 pkg.applicationInfo.secondaryCpuAbi, 8286 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8287 user, false); 8288 if (pkgSetting == null) { 8289 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8290 "Creating application package " + pkg.packageName + " failed"); 8291 } 8292 8293 if (pkgSetting.origPackage != null) { 8294 // If we are first transitioning from an original package, 8295 // fix up the new package's name now. We need to do this after 8296 // looking up the package under its new name, so getPackageLP 8297 // can take care of fiddling things correctly. 8298 pkg.setPackageName(origPackage.name); 8299 8300 // File a report about this. 8301 String msg = "New package " + pkgSetting.realName 8302 + " renamed to replace old package " + pkgSetting.name; 8303 reportSettingsProblem(Log.WARN, msg); 8304 8305 // Make a note of it. 8306 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8307 mTransferedPackages.add(origPackage.name); 8308 } 8309 8310 // No longer need to retain this. 8311 pkgSetting.origPackage = null; 8312 } 8313 8314 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8315 // Make a note of it. 8316 mTransferedPackages.add(pkg.packageName); 8317 } 8318 8319 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8320 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8321 } 8322 8323 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8324 // Check all shared libraries and map to their actual file path. 8325 // We only do this here for apps not on a system dir, because those 8326 // are the only ones that can fail an install due to this. We 8327 // will take care of the system apps by updating all of their 8328 // library paths after the scan is done. 8329 updateSharedLibrariesLPw(pkg, null); 8330 } 8331 8332 if (mFoundPolicyFile) { 8333 SELinuxMMAC.assignSeinfoValue(pkg); 8334 } 8335 8336 pkg.applicationInfo.uid = pkgSetting.appId; 8337 pkg.mExtras = pkgSetting; 8338 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8339 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8340 // We just determined the app is signed correctly, so bring 8341 // over the latest parsed certs. 8342 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8343 } else { 8344 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8345 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8346 "Package " + pkg.packageName + " upgrade keys do not match the " 8347 + "previously installed version"); 8348 } else { 8349 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8350 String msg = "System package " + pkg.packageName 8351 + " signature changed; retaining data."; 8352 reportSettingsProblem(Log.WARN, msg); 8353 } 8354 } 8355 } else { 8356 try { 8357 verifySignaturesLP(pkgSetting, pkg); 8358 // We just determined the app is signed correctly, so bring 8359 // over the latest parsed certs. 8360 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8361 } catch (PackageManagerException e) { 8362 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8363 throw e; 8364 } 8365 // The signature has changed, but this package is in the system 8366 // image... let's recover! 8367 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8368 // However... if this package is part of a shared user, but it 8369 // doesn't match the signature of the shared user, let's fail. 8370 // What this means is that you can't change the signatures 8371 // associated with an overall shared user, which doesn't seem all 8372 // that unreasonable. 8373 if (pkgSetting.sharedUser != null) { 8374 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8375 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8376 throw new PackageManagerException( 8377 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8378 "Signature mismatch for shared user: " 8379 + pkgSetting.sharedUser); 8380 } 8381 } 8382 // File a report about this. 8383 String msg = "System package " + pkg.packageName 8384 + " signature changed; retaining data."; 8385 reportSettingsProblem(Log.WARN, msg); 8386 } 8387 } 8388 // Verify that this new package doesn't have any content providers 8389 // that conflict with existing packages. Only do this if the 8390 // package isn't already installed, since we don't want to break 8391 // things that are installed. 8392 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8393 final int N = pkg.providers.size(); 8394 int i; 8395 for (i=0; i<N; i++) { 8396 PackageParser.Provider p = pkg.providers.get(i); 8397 if (p.info.authority != null) { 8398 String names[] = p.info.authority.split(";"); 8399 for (int j = 0; j < names.length; j++) { 8400 if (mProvidersByAuthority.containsKey(names[j])) { 8401 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8402 final String otherPackageName = 8403 ((other != null && other.getComponentName() != null) ? 8404 other.getComponentName().getPackageName() : "?"); 8405 throw new PackageManagerException( 8406 INSTALL_FAILED_CONFLICTING_PROVIDER, 8407 "Can't install because provider name " + names[j] 8408 + " (in package " + pkg.applicationInfo.packageName 8409 + ") is already used by " + otherPackageName); 8410 } 8411 } 8412 } 8413 } 8414 } 8415 8416 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8417 // This package wants to adopt ownership of permissions from 8418 // another package. 8419 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8420 final String origName = pkg.mAdoptPermissions.get(i); 8421 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8422 if (orig != null) { 8423 if (verifyPackageUpdateLPr(orig, pkg)) { 8424 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8425 + pkg.packageName); 8426 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8427 } 8428 } 8429 } 8430 } 8431 } 8432 8433 final String pkgName = pkg.packageName; 8434 8435 final long scanFileTime = scanFile.lastModified(); 8436 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8437 pkg.applicationInfo.processName = fixProcessName( 8438 pkg.applicationInfo.packageName, 8439 pkg.applicationInfo.processName, 8440 pkg.applicationInfo.uid); 8441 8442 if (pkg != mPlatformPackage) { 8443 // Get all of our default paths setup 8444 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8445 } 8446 8447 final String path = scanFile.getPath(); 8448 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8449 8450 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8451 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8452 8453 // Some system apps still use directory structure for native libraries 8454 // in which case we might end up not detecting abi solely based on apk 8455 // structure. Try to detect abi based on directory structure. 8456 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8457 pkg.applicationInfo.primaryCpuAbi == null) { 8458 setBundledAppAbisAndRoots(pkg, pkgSetting); 8459 setNativeLibraryPaths(pkg); 8460 } 8461 8462 } else { 8463 if ((scanFlags & SCAN_MOVE) != 0) { 8464 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8465 // but we already have this packages package info in the PackageSetting. We just 8466 // use that and derive the native library path based on the new codepath. 8467 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8468 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8469 } 8470 8471 // Set native library paths again. For moves, the path will be updated based on the 8472 // ABIs we've determined above. For non-moves, the path will be updated based on the 8473 // ABIs we determined during compilation, but the path will depend on the final 8474 // package path (after the rename away from the stage path). 8475 setNativeLibraryPaths(pkg); 8476 } 8477 8478 // This is a special case for the "system" package, where the ABI is 8479 // dictated by the zygote configuration (and init.rc). We should keep track 8480 // of this ABI so that we can deal with "normal" applications that run under 8481 // the same UID correctly. 8482 if (mPlatformPackage == pkg) { 8483 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8484 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8485 } 8486 8487 // If there's a mismatch between the abi-override in the package setting 8488 // and the abiOverride specified for the install. Warn about this because we 8489 // would've already compiled the app without taking the package setting into 8490 // account. 8491 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8492 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8493 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8494 " for package " + pkg.packageName); 8495 } 8496 } 8497 8498 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8499 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8500 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8501 8502 // Copy the derived override back to the parsed package, so that we can 8503 // update the package settings accordingly. 8504 pkg.cpuAbiOverride = cpuAbiOverride; 8505 8506 if (DEBUG_ABI_SELECTION) { 8507 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8508 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8509 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8510 } 8511 8512 // Push the derived path down into PackageSettings so we know what to 8513 // clean up at uninstall time. 8514 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8515 8516 if (DEBUG_ABI_SELECTION) { 8517 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8518 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8519 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8520 } 8521 8522 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8523 // We don't do this here during boot because we can do it all 8524 // at once after scanning all existing packages. 8525 // 8526 // We also do this *before* we perform dexopt on this package, so that 8527 // we can avoid redundant dexopts, and also to make sure we've got the 8528 // code and package path correct. 8529 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8530 pkg, true /* boot complete */); 8531 } 8532 8533 if (mFactoryTest && pkg.requestedPermissions.contains( 8534 android.Manifest.permission.FACTORY_TEST)) { 8535 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8536 } 8537 8538 ArrayList<PackageParser.Package> clientLibPkgs = null; 8539 8540 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8541 if (nonMutatedPs != null) { 8542 synchronized (mPackages) { 8543 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8544 } 8545 } 8546 return pkg; 8547 } 8548 8549 // Only privileged apps and updated privileged apps can add child packages. 8550 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8551 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8552 throw new PackageManagerException("Only privileged apps and updated " 8553 + "privileged apps can add child packages. Ignoring package " 8554 + pkg.packageName); 8555 } 8556 final int childCount = pkg.childPackages.size(); 8557 for (int i = 0; i < childCount; i++) { 8558 PackageParser.Package childPkg = pkg.childPackages.get(i); 8559 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8560 childPkg.packageName)) { 8561 throw new PackageManagerException("Cannot override a child package of " 8562 + "another disabled system app. Ignoring package " + pkg.packageName); 8563 } 8564 } 8565 } 8566 8567 // writer 8568 synchronized (mPackages) { 8569 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8570 // Only system apps can add new shared libraries. 8571 if (pkg.libraryNames != null) { 8572 for (int i=0; i<pkg.libraryNames.size(); i++) { 8573 String name = pkg.libraryNames.get(i); 8574 boolean allowed = false; 8575 if (pkg.isUpdatedSystemApp()) { 8576 // New library entries can only be added through the 8577 // system image. This is important to get rid of a lot 8578 // of nasty edge cases: for example if we allowed a non- 8579 // system update of the app to add a library, then uninstalling 8580 // the update would make the library go away, and assumptions 8581 // we made such as through app install filtering would now 8582 // have allowed apps on the device which aren't compatible 8583 // with it. Better to just have the restriction here, be 8584 // conservative, and create many fewer cases that can negatively 8585 // impact the user experience. 8586 final PackageSetting sysPs = mSettings 8587 .getDisabledSystemPkgLPr(pkg.packageName); 8588 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8589 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8590 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8591 allowed = true; 8592 break; 8593 } 8594 } 8595 } 8596 } else { 8597 allowed = true; 8598 } 8599 if (allowed) { 8600 if (!mSharedLibraries.containsKey(name)) { 8601 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8602 } else if (!name.equals(pkg.packageName)) { 8603 Slog.w(TAG, "Package " + pkg.packageName + " library " 8604 + name + " already exists; skipping"); 8605 } 8606 } else { 8607 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8608 + name + " that is not declared on system image; skipping"); 8609 } 8610 } 8611 if ((scanFlags & SCAN_BOOTING) == 0) { 8612 // If we are not booting, we need to update any applications 8613 // that are clients of our shared library. If we are booting, 8614 // this will all be done once the scan is complete. 8615 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8616 } 8617 } 8618 } 8619 } 8620 8621 if ((scanFlags & SCAN_BOOTING) != 0) { 8622 // No apps can run during boot scan, so they don't need to be frozen 8623 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8624 // Caller asked to not kill app, so it's probably not frozen 8625 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8626 // Caller asked us to ignore frozen check for some reason; they 8627 // probably didn't know the package name 8628 } else { 8629 // We're doing major surgery on this package, so it better be frozen 8630 // right now to keep it from launching 8631 checkPackageFrozen(pkgName); 8632 } 8633 8634 // Also need to kill any apps that are dependent on the library. 8635 if (clientLibPkgs != null) { 8636 for (int i=0; i<clientLibPkgs.size(); i++) { 8637 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8638 killApplication(clientPkg.applicationInfo.packageName, 8639 clientPkg.applicationInfo.uid, "update lib"); 8640 } 8641 } 8642 8643 // Make sure we're not adding any bogus keyset info 8644 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8645 ksms.assertScannedPackageValid(pkg); 8646 8647 // writer 8648 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8649 8650 boolean createIdmapFailed = false; 8651 synchronized (mPackages) { 8652 // We don't expect installation to fail beyond this point 8653 8654 if (pkgSetting.pkg != null) { 8655 // Note that |user| might be null during the initial boot scan. If a codePath 8656 // for an app has changed during a boot scan, it's due to an app update that's 8657 // part of the system partition and marker changes must be applied to all users. 8658 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8659 (user != null) ? user : UserHandle.ALL); 8660 } 8661 8662 // Add the new setting to mSettings 8663 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8664 // Add the new setting to mPackages 8665 mPackages.put(pkg.applicationInfo.packageName, pkg); 8666 // Make sure we don't accidentally delete its data. 8667 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8668 while (iter.hasNext()) { 8669 PackageCleanItem item = iter.next(); 8670 if (pkgName.equals(item.packageName)) { 8671 iter.remove(); 8672 } 8673 } 8674 8675 // Take care of first install / last update times. 8676 if (currentTime != 0) { 8677 if (pkgSetting.firstInstallTime == 0) { 8678 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8679 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8680 pkgSetting.lastUpdateTime = currentTime; 8681 } 8682 } else if (pkgSetting.firstInstallTime == 0) { 8683 // We need *something*. Take time time stamp of the file. 8684 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8685 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8686 if (scanFileTime != pkgSetting.timeStamp) { 8687 // A package on the system image has changed; consider this 8688 // to be an update. 8689 pkgSetting.lastUpdateTime = scanFileTime; 8690 } 8691 } 8692 8693 // Add the package's KeySets to the global KeySetManagerService 8694 ksms.addScannedPackageLPw(pkg); 8695 8696 int N = pkg.providers.size(); 8697 StringBuilder r = null; 8698 int i; 8699 for (i=0; i<N; i++) { 8700 PackageParser.Provider p = pkg.providers.get(i); 8701 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8702 p.info.processName, pkg.applicationInfo.uid); 8703 mProviders.addProvider(p); 8704 p.syncable = p.info.isSyncable; 8705 if (p.info.authority != null) { 8706 String names[] = p.info.authority.split(";"); 8707 p.info.authority = null; 8708 for (int j = 0; j < names.length; j++) { 8709 if (j == 1 && p.syncable) { 8710 // We only want the first authority for a provider to possibly be 8711 // syncable, so if we already added this provider using a different 8712 // authority clear the syncable flag. We copy the provider before 8713 // changing it because the mProviders object contains a reference 8714 // to a provider that we don't want to change. 8715 // Only do this for the second authority since the resulting provider 8716 // object can be the same for all future authorities for this provider. 8717 p = new PackageParser.Provider(p); 8718 p.syncable = false; 8719 } 8720 if (!mProvidersByAuthority.containsKey(names[j])) { 8721 mProvidersByAuthority.put(names[j], p); 8722 if (p.info.authority == null) { 8723 p.info.authority = names[j]; 8724 } else { 8725 p.info.authority = p.info.authority + ";" + names[j]; 8726 } 8727 if (DEBUG_PACKAGE_SCANNING) { 8728 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8729 Log.d(TAG, "Registered content provider: " + names[j] 8730 + ", className = " + p.info.name + ", isSyncable = " 8731 + p.info.isSyncable); 8732 } 8733 } else { 8734 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8735 Slog.w(TAG, "Skipping provider name " + names[j] + 8736 " (in package " + pkg.applicationInfo.packageName + 8737 "): name already used by " 8738 + ((other != null && other.getComponentName() != null) 8739 ? other.getComponentName().getPackageName() : "?")); 8740 } 8741 } 8742 } 8743 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8744 if (r == null) { 8745 r = new StringBuilder(256); 8746 } else { 8747 r.append(' '); 8748 } 8749 r.append(p.info.name); 8750 } 8751 } 8752 if (r != null) { 8753 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8754 } 8755 8756 N = pkg.services.size(); 8757 r = null; 8758 for (i=0; i<N; i++) { 8759 PackageParser.Service s = pkg.services.get(i); 8760 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8761 s.info.processName, pkg.applicationInfo.uid); 8762 mServices.addService(s); 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(s.info.name); 8770 } 8771 } 8772 if (r != null) { 8773 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8774 } 8775 8776 N = pkg.receivers.size(); 8777 r = null; 8778 for (i=0; i<N; i++) { 8779 PackageParser.Activity a = pkg.receivers.get(i); 8780 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8781 a.info.processName, pkg.applicationInfo.uid); 8782 mReceivers.addActivity(a, "receiver"); 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(a.info.name); 8790 } 8791 } 8792 if (r != null) { 8793 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8794 } 8795 8796 N = pkg.activities.size(); 8797 r = null; 8798 for (i=0; i<N; i++) { 8799 PackageParser.Activity a = pkg.activities.get(i); 8800 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8801 a.info.processName, pkg.applicationInfo.uid); 8802 mActivities.addActivity(a, "activity"); 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, " Activities: " + r); 8814 } 8815 8816 N = pkg.permissionGroups.size(); 8817 r = null; 8818 for (i=0; i<N; i++) { 8819 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8820 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8821 if (cur == null) { 8822 mPermissionGroups.put(pg.info.name, pg); 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(pg.info.name); 8830 } 8831 } else { 8832 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8833 + pg.info.packageName + " ignored: original from " 8834 + cur.info.packageName); 8835 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8836 if (r == null) { 8837 r = new StringBuilder(256); 8838 } else { 8839 r.append(' '); 8840 } 8841 r.append("DUP:"); 8842 r.append(pg.info.name); 8843 } 8844 } 8845 } 8846 if (r != null) { 8847 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8848 } 8849 8850 N = pkg.permissions.size(); 8851 r = null; 8852 for (i=0; i<N; i++) { 8853 PackageParser.Permission p = pkg.permissions.get(i); 8854 8855 // Assume by default that we did not install this permission into the system. 8856 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8857 8858 // Now that permission groups have a special meaning, we ignore permission 8859 // groups for legacy apps to prevent unexpected behavior. In particular, 8860 // permissions for one app being granted to someone just becase they happen 8861 // to be in a group defined by another app (before this had no implications). 8862 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8863 p.group = mPermissionGroups.get(p.info.group); 8864 // Warn for a permission in an unknown group. 8865 if (p.info.group != null && p.group == null) { 8866 Slog.w(TAG, "Permission " + p.info.name + " from package " 8867 + p.info.packageName + " in an unknown group " + p.info.group); 8868 } 8869 } 8870 8871 ArrayMap<String, BasePermission> permissionMap = 8872 p.tree ? mSettings.mPermissionTrees 8873 : mSettings.mPermissions; 8874 BasePermission bp = permissionMap.get(p.info.name); 8875 8876 // Allow system apps to redefine non-system permissions 8877 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8878 final boolean currentOwnerIsSystem = (bp.perm != null 8879 && isSystemApp(bp.perm.owner)); 8880 if (isSystemApp(p.owner)) { 8881 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8882 // It's a built-in permission and no owner, take ownership now 8883 bp.packageSetting = pkgSetting; 8884 bp.perm = p; 8885 bp.uid = pkg.applicationInfo.uid; 8886 bp.sourcePackage = p.info.packageName; 8887 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8888 } else if (!currentOwnerIsSystem) { 8889 String msg = "New decl " + p.owner + " of permission " 8890 + p.info.name + " is system; overriding " + bp.sourcePackage; 8891 reportSettingsProblem(Log.WARN, msg); 8892 bp = null; 8893 } 8894 } 8895 } 8896 8897 if (bp == null) { 8898 bp = new BasePermission(p.info.name, p.info.packageName, 8899 BasePermission.TYPE_NORMAL); 8900 permissionMap.put(p.info.name, bp); 8901 } 8902 8903 if (bp.perm == null) { 8904 if (bp.sourcePackage == null 8905 || bp.sourcePackage.equals(p.info.packageName)) { 8906 BasePermission tree = findPermissionTreeLP(p.info.name); 8907 if (tree == null 8908 || tree.sourcePackage.equals(p.info.packageName)) { 8909 bp.packageSetting = pkgSetting; 8910 bp.perm = p; 8911 bp.uid = pkg.applicationInfo.uid; 8912 bp.sourcePackage = p.info.packageName; 8913 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8914 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8915 if (r == null) { 8916 r = new StringBuilder(256); 8917 } else { 8918 r.append(' '); 8919 } 8920 r.append(p.info.name); 8921 } 8922 } else { 8923 Slog.w(TAG, "Permission " + p.info.name + " from package " 8924 + p.info.packageName + " ignored: base tree " 8925 + tree.name + " is from package " 8926 + tree.sourcePackage); 8927 } 8928 } else { 8929 Slog.w(TAG, "Permission " + p.info.name + " from package " 8930 + p.info.packageName + " ignored: original from " 8931 + bp.sourcePackage); 8932 } 8933 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8934 if (r == null) { 8935 r = new StringBuilder(256); 8936 } else { 8937 r.append(' '); 8938 } 8939 r.append("DUP:"); 8940 r.append(p.info.name); 8941 } 8942 if (bp.perm == p) { 8943 bp.protectionLevel = p.info.protectionLevel; 8944 } 8945 } 8946 8947 if (r != null) { 8948 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8949 } 8950 8951 N = pkg.instrumentation.size(); 8952 r = null; 8953 for (i=0; i<N; i++) { 8954 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8955 a.info.packageName = pkg.applicationInfo.packageName; 8956 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8957 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8958 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8959 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8960 a.info.dataDir = pkg.applicationInfo.dataDir; 8961 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8962 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8963 8964 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8965 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8966 mInstrumentation.put(a.getComponentName(), a); 8967 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8968 if (r == null) { 8969 r = new StringBuilder(256); 8970 } else { 8971 r.append(' '); 8972 } 8973 r.append(a.info.name); 8974 } 8975 } 8976 if (r != null) { 8977 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8978 } 8979 8980 if (pkg.protectedBroadcasts != null) { 8981 N = pkg.protectedBroadcasts.size(); 8982 for (i=0; i<N; i++) { 8983 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8984 } 8985 } 8986 8987 pkgSetting.setTimeStamp(scanFileTime); 8988 8989 // Create idmap files for pairs of (packages, overlay packages). 8990 // Note: "android", ie framework-res.apk, is handled by native layers. 8991 if (pkg.mOverlayTarget != null) { 8992 // This is an overlay package. 8993 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8994 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8995 mOverlays.put(pkg.mOverlayTarget, 8996 new ArrayMap<String, PackageParser.Package>()); 8997 } 8998 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8999 map.put(pkg.packageName, pkg); 9000 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 9001 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 9002 createIdmapFailed = true; 9003 } 9004 } 9005 } else if (mOverlays.containsKey(pkg.packageName) && 9006 !pkg.packageName.equals("android")) { 9007 // This is a regular package, with one or more known overlay packages. 9008 createIdmapsForPackageLI(pkg); 9009 } 9010 } 9011 9012 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9013 9014 if (createIdmapFailed) { 9015 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 9016 "scanPackageLI failed to createIdmap"); 9017 } 9018 return pkg; 9019 } 9020 9021 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 9022 PackageParser.Package update, UserHandle user) { 9023 if (existing.applicationInfo == null || update.applicationInfo == null) { 9024 // This isn't due to an app installation. 9025 return; 9026 } 9027 9028 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 9029 final File newCodePath = new File(update.applicationInfo.getCodePath()); 9030 9031 // The codePath hasn't changed, so there's nothing for us to do. 9032 if (Objects.equals(oldCodePath, newCodePath)) { 9033 return; 9034 } 9035 9036 File canonicalNewCodePath; 9037 try { 9038 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9039 } catch (IOException e) { 9040 Slog.w(TAG, "Failed to get canonical path.", e); 9041 return; 9042 } 9043 9044 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9045 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9046 // that the last component of the path (i.e, the name) doesn't need canonicalization 9047 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9048 // but may change in the future. Hopefully this function won't exist at that point. 9049 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9050 oldCodePath.getName()); 9051 9052 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9053 // with "@". 9054 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9055 if (!oldMarkerPrefix.endsWith("@")) { 9056 oldMarkerPrefix += "@"; 9057 } 9058 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9059 if (!newMarkerPrefix.endsWith("@")) { 9060 newMarkerPrefix += "@"; 9061 } 9062 9063 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9064 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9065 for (String updatedPath : updatedPaths) { 9066 String updatedPathName = new File(updatedPath).getName(); 9067 markerSuffixes.add(updatedPathName.replace('/', '@')); 9068 } 9069 9070 for (int userId : resolveUserIds(user.getIdentifier())) { 9071 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9072 9073 for (String markerSuffix : markerSuffixes) { 9074 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9075 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9076 if (oldForeignUseMark.exists()) { 9077 try { 9078 Os.rename(oldForeignUseMark.getAbsolutePath(), 9079 newForeignUseMark.getAbsolutePath()); 9080 } catch (ErrnoException e) { 9081 Slog.w(TAG, "Failed to rename foreign use marker", e); 9082 oldForeignUseMark.delete(); 9083 } 9084 } 9085 } 9086 } 9087 } 9088 9089 /** 9090 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9091 * is derived purely on the basis of the contents of {@code scanFile} and 9092 * {@code cpuAbiOverride}. 9093 * 9094 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9095 */ 9096 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9097 String cpuAbiOverride, boolean extractLibs) 9098 throws PackageManagerException { 9099 // TODO: We can probably be smarter about this stuff. For installed apps, 9100 // we can calculate this information at install time once and for all. For 9101 // system apps, we can probably assume that this information doesn't change 9102 // after the first boot scan. As things stand, we do lots of unnecessary work. 9103 9104 // Give ourselves some initial paths; we'll come back for another 9105 // pass once we've determined ABI below. 9106 setNativeLibraryPaths(pkg); 9107 9108 // We would never need to extract libs for forward-locked and external packages, 9109 // since the container service will do it for us. We shouldn't attempt to 9110 // extract libs from system app when it was not updated. 9111 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9112 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9113 extractLibs = false; 9114 } 9115 9116 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9117 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9118 9119 NativeLibraryHelper.Handle handle = null; 9120 try { 9121 handle = NativeLibraryHelper.Handle.create(pkg); 9122 // TODO(multiArch): This can be null for apps that didn't go through the 9123 // usual installation process. We can calculate it again, like we 9124 // do during install time. 9125 // 9126 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9127 // unnecessary. 9128 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9129 9130 // Null out the abis so that they can be recalculated. 9131 pkg.applicationInfo.primaryCpuAbi = null; 9132 pkg.applicationInfo.secondaryCpuAbi = null; 9133 if (isMultiArch(pkg.applicationInfo)) { 9134 // Warn if we've set an abiOverride for multi-lib packages.. 9135 // By definition, we need to copy both 32 and 64 bit libraries for 9136 // such packages. 9137 if (pkg.cpuAbiOverride != null 9138 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9139 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9140 } 9141 9142 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9143 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9144 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9145 if (extractLibs) { 9146 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9147 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9148 useIsaSpecificSubdirs); 9149 } else { 9150 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9151 } 9152 } 9153 9154 maybeThrowExceptionForMultiArchCopy( 9155 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9156 9157 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9158 if (extractLibs) { 9159 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9160 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9161 useIsaSpecificSubdirs); 9162 } else { 9163 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9164 } 9165 } 9166 9167 maybeThrowExceptionForMultiArchCopy( 9168 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9169 9170 if (abi64 >= 0) { 9171 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9172 } 9173 9174 if (abi32 >= 0) { 9175 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9176 if (abi64 >= 0) { 9177 if (pkg.use32bitAbi) { 9178 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9179 pkg.applicationInfo.primaryCpuAbi = abi; 9180 } else { 9181 pkg.applicationInfo.secondaryCpuAbi = abi; 9182 } 9183 } else { 9184 pkg.applicationInfo.primaryCpuAbi = abi; 9185 } 9186 } 9187 9188 } else { 9189 String[] abiList = (cpuAbiOverride != null) ? 9190 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9191 9192 // Enable gross and lame hacks for apps that are built with old 9193 // SDK tools. We must scan their APKs for renderscript bitcode and 9194 // not launch them if it's present. Don't bother checking on devices 9195 // that don't have 64 bit support. 9196 boolean needsRenderScriptOverride = false; 9197 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9198 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9199 abiList = Build.SUPPORTED_32_BIT_ABIS; 9200 needsRenderScriptOverride = true; 9201 } 9202 9203 final int copyRet; 9204 if (extractLibs) { 9205 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9206 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9207 } else { 9208 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9209 } 9210 9211 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9212 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9213 "Error unpackaging native libs for app, errorCode=" + copyRet); 9214 } 9215 9216 if (copyRet >= 0) { 9217 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9218 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9219 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9220 } else if (needsRenderScriptOverride) { 9221 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9222 } 9223 } 9224 } catch (IOException ioe) { 9225 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9226 } finally { 9227 IoUtils.closeQuietly(handle); 9228 } 9229 9230 // Now that we've calculated the ABIs and determined if it's an internal app, 9231 // we will go ahead and populate the nativeLibraryPath. 9232 setNativeLibraryPaths(pkg); 9233 } 9234 9235 /** 9236 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9237 * i.e, so that all packages can be run inside a single process if required. 9238 * 9239 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9240 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9241 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9242 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9243 * updating a package that belongs to a shared user. 9244 * 9245 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9246 * adds unnecessary complexity. 9247 */ 9248 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9249 PackageParser.Package scannedPackage, boolean bootComplete) { 9250 String requiredInstructionSet = null; 9251 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9252 requiredInstructionSet = VMRuntime.getInstructionSet( 9253 scannedPackage.applicationInfo.primaryCpuAbi); 9254 } 9255 9256 PackageSetting requirer = null; 9257 for (PackageSetting ps : packagesForUser) { 9258 // If packagesForUser contains scannedPackage, we skip it. This will happen 9259 // when scannedPackage is an update of an existing package. Without this check, 9260 // we will never be able to change the ABI of any package belonging to a shared 9261 // user, even if it's compatible with other packages. 9262 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9263 if (ps.primaryCpuAbiString == null) { 9264 continue; 9265 } 9266 9267 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9268 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9269 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9270 // this but there's not much we can do. 9271 String errorMessage = "Instruction set mismatch, " 9272 + ((requirer == null) ? "[caller]" : requirer) 9273 + " requires " + requiredInstructionSet + " whereas " + ps 9274 + " requires " + instructionSet; 9275 Slog.w(TAG, errorMessage); 9276 } 9277 9278 if (requiredInstructionSet == null) { 9279 requiredInstructionSet = instructionSet; 9280 requirer = ps; 9281 } 9282 } 9283 } 9284 9285 if (requiredInstructionSet != null) { 9286 String adjustedAbi; 9287 if (requirer != null) { 9288 // requirer != null implies that either scannedPackage was null or that scannedPackage 9289 // did not require an ABI, in which case we have to adjust scannedPackage to match 9290 // the ABI of the set (which is the same as requirer's ABI) 9291 adjustedAbi = requirer.primaryCpuAbiString; 9292 if (scannedPackage != null) { 9293 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9294 } 9295 } else { 9296 // requirer == null implies that we're updating all ABIs in the set to 9297 // match scannedPackage. 9298 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9299 } 9300 9301 for (PackageSetting ps : packagesForUser) { 9302 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9303 if (ps.primaryCpuAbiString != null) { 9304 continue; 9305 } 9306 9307 ps.primaryCpuAbiString = adjustedAbi; 9308 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9309 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9310 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9311 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9312 + " (requirer=" 9313 + (requirer == null ? "null" : requirer.pkg.packageName) 9314 + ", scannedPackage=" 9315 + (scannedPackage != null ? scannedPackage.packageName : "null") 9316 + ")"); 9317 try { 9318 mInstaller.rmdex(ps.codePathString, 9319 getDexCodeInstructionSet(getPreferredInstructionSet())); 9320 } catch (InstallerException ignored) { 9321 } 9322 } 9323 } 9324 } 9325 } 9326 } 9327 9328 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9329 synchronized (mPackages) { 9330 mResolverReplaced = true; 9331 // Set up information for custom user intent resolution activity. 9332 mResolveActivity.applicationInfo = pkg.applicationInfo; 9333 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9334 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9335 mResolveActivity.processName = pkg.applicationInfo.packageName; 9336 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9337 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9338 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9339 mResolveActivity.theme = 0; 9340 mResolveActivity.exported = true; 9341 mResolveActivity.enabled = true; 9342 mResolveInfo.activityInfo = mResolveActivity; 9343 mResolveInfo.priority = 0; 9344 mResolveInfo.preferredOrder = 0; 9345 mResolveInfo.match = 0; 9346 mResolveComponentName = mCustomResolverComponentName; 9347 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9348 mResolveComponentName); 9349 } 9350 } 9351 9352 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9353 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9354 9355 // Set up information for ephemeral installer activity 9356 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9357 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9358 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9359 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9360 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9361 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9362 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9363 mEphemeralInstallerActivity.theme = 0; 9364 mEphemeralInstallerActivity.exported = true; 9365 mEphemeralInstallerActivity.enabled = true; 9366 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9367 mEphemeralInstallerInfo.priority = 0; 9368 mEphemeralInstallerInfo.preferredOrder = 0; 9369 mEphemeralInstallerInfo.match = 0; 9370 9371 if (DEBUG_EPHEMERAL) { 9372 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9373 } 9374 } 9375 9376 private static String calculateBundledApkRoot(final String codePathString) { 9377 final File codePath = new File(codePathString); 9378 final File codeRoot; 9379 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9380 codeRoot = Environment.getRootDirectory(); 9381 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9382 codeRoot = Environment.getOemDirectory(); 9383 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9384 codeRoot = Environment.getVendorDirectory(); 9385 } else { 9386 // Unrecognized code path; take its top real segment as the apk root: 9387 // e.g. /something/app/blah.apk => /something 9388 try { 9389 File f = codePath.getCanonicalFile(); 9390 File parent = f.getParentFile(); // non-null because codePath is a file 9391 File tmp; 9392 while ((tmp = parent.getParentFile()) != null) { 9393 f = parent; 9394 parent = tmp; 9395 } 9396 codeRoot = f; 9397 Slog.w(TAG, "Unrecognized code path " 9398 + codePath + " - using " + codeRoot); 9399 } catch (IOException e) { 9400 // Can't canonicalize the code path -- shenanigans? 9401 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9402 return Environment.getRootDirectory().getPath(); 9403 } 9404 } 9405 return codeRoot.getPath(); 9406 } 9407 9408 /** 9409 * Derive and set the location of native libraries for the given package, 9410 * which varies depending on where and how the package was installed. 9411 */ 9412 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9413 final ApplicationInfo info = pkg.applicationInfo; 9414 final String codePath = pkg.codePath; 9415 final File codeFile = new File(codePath); 9416 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9417 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9418 9419 info.nativeLibraryRootDir = null; 9420 info.nativeLibraryRootRequiresIsa = false; 9421 info.nativeLibraryDir = null; 9422 info.secondaryNativeLibraryDir = null; 9423 9424 if (isApkFile(codeFile)) { 9425 // Monolithic install 9426 if (bundledApp) { 9427 // If "/system/lib64/apkname" exists, assume that is the per-package 9428 // native library directory to use; otherwise use "/system/lib/apkname". 9429 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9430 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9431 getPrimaryInstructionSet(info)); 9432 9433 // This is a bundled system app so choose the path based on the ABI. 9434 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9435 // is just the default path. 9436 final String apkName = deriveCodePathName(codePath); 9437 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9438 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9439 apkName).getAbsolutePath(); 9440 9441 if (info.secondaryCpuAbi != null) { 9442 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9443 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9444 secondaryLibDir, apkName).getAbsolutePath(); 9445 } 9446 } else if (asecApp) { 9447 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9448 .getAbsolutePath(); 9449 } else { 9450 final String apkName = deriveCodePathName(codePath); 9451 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9452 .getAbsolutePath(); 9453 } 9454 9455 info.nativeLibraryRootRequiresIsa = false; 9456 info.nativeLibraryDir = info.nativeLibraryRootDir; 9457 } else { 9458 // Cluster install 9459 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9460 info.nativeLibraryRootRequiresIsa = true; 9461 9462 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9463 getPrimaryInstructionSet(info)).getAbsolutePath(); 9464 9465 if (info.secondaryCpuAbi != null) { 9466 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9467 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9468 } 9469 } 9470 } 9471 9472 /** 9473 * Calculate the abis and roots for a bundled app. These can uniquely 9474 * be determined from the contents of the system partition, i.e whether 9475 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9476 * of this information, and instead assume that the system was built 9477 * sensibly. 9478 */ 9479 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9480 PackageSetting pkgSetting) { 9481 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9482 9483 // If "/system/lib64/apkname" exists, assume that is the per-package 9484 // native library directory to use; otherwise use "/system/lib/apkname". 9485 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9486 setBundledAppAbi(pkg, apkRoot, apkName); 9487 // pkgSetting might be null during rescan following uninstall of updates 9488 // to a bundled app, so accommodate that possibility. The settings in 9489 // that case will be established later from the parsed package. 9490 // 9491 // If the settings aren't null, sync them up with what we've just derived. 9492 // note that apkRoot isn't stored in the package settings. 9493 if (pkgSetting != null) { 9494 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9495 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9496 } 9497 } 9498 9499 /** 9500 * Deduces the ABI of a bundled app and sets the relevant fields on the 9501 * parsed pkg object. 9502 * 9503 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9504 * under which system libraries are installed. 9505 * @param apkName the name of the installed package. 9506 */ 9507 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9508 final File codeFile = new File(pkg.codePath); 9509 9510 final boolean has64BitLibs; 9511 final boolean has32BitLibs; 9512 if (isApkFile(codeFile)) { 9513 // Monolithic install 9514 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9515 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9516 } else { 9517 // Cluster install 9518 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9519 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9520 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9521 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9522 has64BitLibs = (new File(rootDir, isa)).exists(); 9523 } else { 9524 has64BitLibs = false; 9525 } 9526 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9527 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9528 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9529 has32BitLibs = (new File(rootDir, isa)).exists(); 9530 } else { 9531 has32BitLibs = false; 9532 } 9533 } 9534 9535 if (has64BitLibs && !has32BitLibs) { 9536 // The package has 64 bit libs, but not 32 bit libs. Its primary 9537 // ABI should be 64 bit. We can safely assume here that the bundled 9538 // native libraries correspond to the most preferred ABI in the list. 9539 9540 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9541 pkg.applicationInfo.secondaryCpuAbi = null; 9542 } else if (has32BitLibs && !has64BitLibs) { 9543 // The package has 32 bit libs but not 64 bit libs. Its primary 9544 // ABI should be 32 bit. 9545 9546 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9547 pkg.applicationInfo.secondaryCpuAbi = null; 9548 } else if (has32BitLibs && has64BitLibs) { 9549 // The application has both 64 and 32 bit bundled libraries. We check 9550 // here that the app declares multiArch support, and warn if it doesn't. 9551 // 9552 // We will be lenient here and record both ABIs. The primary will be the 9553 // ABI that's higher on the list, i.e, a device that's configured to prefer 9554 // 64 bit apps will see a 64 bit primary ABI, 9555 9556 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9557 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9558 } 9559 9560 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9561 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9562 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9563 } else { 9564 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9565 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9566 } 9567 } else { 9568 pkg.applicationInfo.primaryCpuAbi = null; 9569 pkg.applicationInfo.secondaryCpuAbi = null; 9570 } 9571 } 9572 9573 private void killApplication(String pkgName, int appId, String reason) { 9574 // Request the ActivityManager to kill the process(only for existing packages) 9575 // so that we do not end up in a confused state while the user is still using the older 9576 // version of the application while the new one gets installed. 9577 final long token = Binder.clearCallingIdentity(); 9578 try { 9579 IActivityManager am = ActivityManagerNative.getDefault(); 9580 if (am != null) { 9581 try { 9582 am.killApplicationWithAppId(pkgName, appId, reason); 9583 } catch (RemoteException e) { 9584 } 9585 } 9586 } finally { 9587 Binder.restoreCallingIdentity(token); 9588 } 9589 } 9590 9591 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9592 // Remove the parent package setting 9593 PackageSetting ps = (PackageSetting) pkg.mExtras; 9594 if (ps != null) { 9595 removePackageLI(ps, chatty); 9596 } 9597 // Remove the child package setting 9598 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9599 for (int i = 0; i < childCount; i++) { 9600 PackageParser.Package childPkg = pkg.childPackages.get(i); 9601 ps = (PackageSetting) childPkg.mExtras; 9602 if (ps != null) { 9603 removePackageLI(ps, chatty); 9604 } 9605 } 9606 } 9607 9608 void removePackageLI(PackageSetting ps, boolean chatty) { 9609 if (DEBUG_INSTALL) { 9610 if (chatty) 9611 Log.d(TAG, "Removing package " + ps.name); 9612 } 9613 9614 // writer 9615 synchronized (mPackages) { 9616 mPackages.remove(ps.name); 9617 final PackageParser.Package pkg = ps.pkg; 9618 if (pkg != null) { 9619 cleanPackageDataStructuresLILPw(pkg, chatty); 9620 } 9621 } 9622 } 9623 9624 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9625 if (DEBUG_INSTALL) { 9626 if (chatty) 9627 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9628 } 9629 9630 // writer 9631 synchronized (mPackages) { 9632 // Remove the parent package 9633 mPackages.remove(pkg.applicationInfo.packageName); 9634 cleanPackageDataStructuresLILPw(pkg, chatty); 9635 9636 // Remove the child packages 9637 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9638 for (int i = 0; i < childCount; i++) { 9639 PackageParser.Package childPkg = pkg.childPackages.get(i); 9640 mPackages.remove(childPkg.applicationInfo.packageName); 9641 cleanPackageDataStructuresLILPw(childPkg, chatty); 9642 } 9643 } 9644 } 9645 9646 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9647 int N = pkg.providers.size(); 9648 StringBuilder r = null; 9649 int i; 9650 for (i=0; i<N; i++) { 9651 PackageParser.Provider p = pkg.providers.get(i); 9652 mProviders.removeProvider(p); 9653 if (p.info.authority == null) { 9654 9655 /* There was another ContentProvider with this authority when 9656 * this app was installed so this authority is null, 9657 * Ignore it as we don't have to unregister the provider. 9658 */ 9659 continue; 9660 } 9661 String names[] = p.info.authority.split(";"); 9662 for (int j = 0; j < names.length; j++) { 9663 if (mProvidersByAuthority.get(names[j]) == p) { 9664 mProvidersByAuthority.remove(names[j]); 9665 if (DEBUG_REMOVE) { 9666 if (chatty) 9667 Log.d(TAG, "Unregistered content provider: " + names[j] 9668 + ", className = " + p.info.name + ", isSyncable = " 9669 + p.info.isSyncable); 9670 } 9671 } 9672 } 9673 if (DEBUG_REMOVE && chatty) { 9674 if (r == null) { 9675 r = new StringBuilder(256); 9676 } else { 9677 r.append(' '); 9678 } 9679 r.append(p.info.name); 9680 } 9681 } 9682 if (r != null) { 9683 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9684 } 9685 9686 N = pkg.services.size(); 9687 r = null; 9688 for (i=0; i<N; i++) { 9689 PackageParser.Service s = pkg.services.get(i); 9690 mServices.removeService(s); 9691 if (chatty) { 9692 if (r == null) { 9693 r = new StringBuilder(256); 9694 } else { 9695 r.append(' '); 9696 } 9697 r.append(s.info.name); 9698 } 9699 } 9700 if (r != null) { 9701 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9702 } 9703 9704 N = pkg.receivers.size(); 9705 r = null; 9706 for (i=0; i<N; i++) { 9707 PackageParser.Activity a = pkg.receivers.get(i); 9708 mReceivers.removeActivity(a, "receiver"); 9709 if (DEBUG_REMOVE && chatty) { 9710 if (r == null) { 9711 r = new StringBuilder(256); 9712 } else { 9713 r.append(' '); 9714 } 9715 r.append(a.info.name); 9716 } 9717 } 9718 if (r != null) { 9719 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9720 } 9721 9722 N = pkg.activities.size(); 9723 r = null; 9724 for (i=0; i<N; i++) { 9725 PackageParser.Activity a = pkg.activities.get(i); 9726 mActivities.removeActivity(a, "activity"); 9727 if (DEBUG_REMOVE && chatty) { 9728 if (r == null) { 9729 r = new StringBuilder(256); 9730 } else { 9731 r.append(' '); 9732 } 9733 r.append(a.info.name); 9734 } 9735 } 9736 if (r != null) { 9737 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9738 } 9739 9740 N = pkg.permissions.size(); 9741 r = null; 9742 for (i=0; i<N; i++) { 9743 PackageParser.Permission p = pkg.permissions.get(i); 9744 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9745 if (bp == null) { 9746 bp = mSettings.mPermissionTrees.get(p.info.name); 9747 } 9748 if (bp != null && bp.perm == p) { 9749 bp.perm = null; 9750 if (DEBUG_REMOVE && chatty) { 9751 if (r == null) { 9752 r = new StringBuilder(256); 9753 } else { 9754 r.append(' '); 9755 } 9756 r.append(p.info.name); 9757 } 9758 } 9759 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9760 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9761 if (appOpPkgs != null) { 9762 appOpPkgs.remove(pkg.packageName); 9763 } 9764 } 9765 } 9766 if (r != null) { 9767 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9768 } 9769 9770 N = pkg.requestedPermissions.size(); 9771 r = null; 9772 for (i=0; i<N; i++) { 9773 String perm = pkg.requestedPermissions.get(i); 9774 BasePermission bp = mSettings.mPermissions.get(perm); 9775 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9776 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9777 if (appOpPkgs != null) { 9778 appOpPkgs.remove(pkg.packageName); 9779 if (appOpPkgs.isEmpty()) { 9780 mAppOpPermissionPackages.remove(perm); 9781 } 9782 } 9783 } 9784 } 9785 if (r != null) { 9786 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9787 } 9788 9789 N = pkg.instrumentation.size(); 9790 r = null; 9791 for (i=0; i<N; i++) { 9792 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9793 mInstrumentation.remove(a.getComponentName()); 9794 if (DEBUG_REMOVE && chatty) { 9795 if (r == null) { 9796 r = new StringBuilder(256); 9797 } else { 9798 r.append(' '); 9799 } 9800 r.append(a.info.name); 9801 } 9802 } 9803 if (r != null) { 9804 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9805 } 9806 9807 r = null; 9808 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9809 // Only system apps can hold shared libraries. 9810 if (pkg.libraryNames != null) { 9811 for (i=0; i<pkg.libraryNames.size(); i++) { 9812 String name = pkg.libraryNames.get(i); 9813 SharedLibraryEntry cur = mSharedLibraries.get(name); 9814 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9815 mSharedLibraries.remove(name); 9816 if (DEBUG_REMOVE && chatty) { 9817 if (r == null) { 9818 r = new StringBuilder(256); 9819 } else { 9820 r.append(' '); 9821 } 9822 r.append(name); 9823 } 9824 } 9825 } 9826 } 9827 } 9828 if (r != null) { 9829 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9830 } 9831 } 9832 9833 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9834 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9835 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9836 return true; 9837 } 9838 } 9839 return false; 9840 } 9841 9842 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9843 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9844 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9845 9846 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9847 // Update the parent permissions 9848 updatePermissionsLPw(pkg.packageName, pkg, flags); 9849 // Update the child permissions 9850 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9851 for (int i = 0; i < childCount; i++) { 9852 PackageParser.Package childPkg = pkg.childPackages.get(i); 9853 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9854 } 9855 } 9856 9857 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9858 int flags) { 9859 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9860 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9861 } 9862 9863 private void updatePermissionsLPw(String changingPkg, 9864 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9865 // Make sure there are no dangling permission trees. 9866 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9867 while (it.hasNext()) { 9868 final BasePermission bp = it.next(); 9869 if (bp.packageSetting == null) { 9870 // We may not yet have parsed the package, so just see if 9871 // we still know about its settings. 9872 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9873 } 9874 if (bp.packageSetting == null) { 9875 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9876 + " from package " + bp.sourcePackage); 9877 it.remove(); 9878 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9879 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9880 Slog.i(TAG, "Removing old permission tree: " + bp.name 9881 + " from package " + bp.sourcePackage); 9882 flags |= UPDATE_PERMISSIONS_ALL; 9883 it.remove(); 9884 } 9885 } 9886 } 9887 9888 // Make sure all dynamic permissions have been assigned to a package, 9889 // and make sure there are no dangling permissions. 9890 it = mSettings.mPermissions.values().iterator(); 9891 while (it.hasNext()) { 9892 final BasePermission bp = it.next(); 9893 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9894 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9895 + bp.name + " pkg=" + bp.sourcePackage 9896 + " info=" + bp.pendingInfo); 9897 if (bp.packageSetting == null && bp.pendingInfo != null) { 9898 final BasePermission tree = findPermissionTreeLP(bp.name); 9899 if (tree != null && tree.perm != null) { 9900 bp.packageSetting = tree.packageSetting; 9901 bp.perm = new PackageParser.Permission(tree.perm.owner, 9902 new PermissionInfo(bp.pendingInfo)); 9903 bp.perm.info.packageName = tree.perm.info.packageName; 9904 bp.perm.info.name = bp.name; 9905 bp.uid = tree.uid; 9906 } 9907 } 9908 } 9909 if (bp.packageSetting == null) { 9910 // We may not yet have parsed the package, so just see if 9911 // we still know about its settings. 9912 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9913 } 9914 if (bp.packageSetting == null) { 9915 Slog.w(TAG, "Removing dangling permission: " + bp.name 9916 + " from package " + bp.sourcePackage); 9917 it.remove(); 9918 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9919 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9920 Slog.i(TAG, "Removing old permission: " + bp.name 9921 + " from package " + bp.sourcePackage); 9922 flags |= UPDATE_PERMISSIONS_ALL; 9923 it.remove(); 9924 } 9925 } 9926 } 9927 9928 // Now update the permissions for all packages, in particular 9929 // replace the granted permissions of the system packages. 9930 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9931 for (PackageParser.Package pkg : mPackages.values()) { 9932 if (pkg != pkgInfo) { 9933 // Only replace for packages on requested volume 9934 final String volumeUuid = getVolumeUuidForPackage(pkg); 9935 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9936 && Objects.equals(replaceVolumeUuid, volumeUuid); 9937 grantPermissionsLPw(pkg, replace, changingPkg); 9938 } 9939 } 9940 } 9941 9942 if (pkgInfo != null) { 9943 // Only replace for packages on requested volume 9944 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9945 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9946 && Objects.equals(replaceVolumeUuid, volumeUuid); 9947 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9948 } 9949 } 9950 9951 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9952 String packageOfInterest) { 9953 // IMPORTANT: There are two types of permissions: install and runtime. 9954 // Install time permissions are granted when the app is installed to 9955 // all device users and users added in the future. Runtime permissions 9956 // are granted at runtime explicitly to specific users. Normal and signature 9957 // protected permissions are install time permissions. Dangerous permissions 9958 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9959 // otherwise they are runtime permissions. This function does not manage 9960 // runtime permissions except for the case an app targeting Lollipop MR1 9961 // being upgraded to target a newer SDK, in which case dangerous permissions 9962 // are transformed from install time to runtime ones. 9963 9964 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9965 if (ps == null) { 9966 return; 9967 } 9968 9969 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9970 9971 PermissionsState permissionsState = ps.getPermissionsState(); 9972 PermissionsState origPermissions = permissionsState; 9973 9974 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9975 9976 boolean runtimePermissionsRevoked = false; 9977 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9978 9979 boolean changedInstallPermission = false; 9980 9981 if (replace) { 9982 ps.installPermissionsFixed = false; 9983 if (!ps.isSharedUser()) { 9984 origPermissions = new PermissionsState(permissionsState); 9985 permissionsState.reset(); 9986 } else { 9987 // We need to know only about runtime permission changes since the 9988 // calling code always writes the install permissions state but 9989 // the runtime ones are written only if changed. The only cases of 9990 // changed runtime permissions here are promotion of an install to 9991 // runtime and revocation of a runtime from a shared user. 9992 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9993 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9994 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9995 runtimePermissionsRevoked = true; 9996 } 9997 } 9998 } 9999 10000 permissionsState.setGlobalGids(mGlobalGids); 10001 10002 final int N = pkg.requestedPermissions.size(); 10003 for (int i=0; i<N; i++) { 10004 final String name = pkg.requestedPermissions.get(i); 10005 final BasePermission bp = mSettings.mPermissions.get(name); 10006 10007 if (DEBUG_INSTALL) { 10008 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 10009 } 10010 10011 if (bp == null || bp.packageSetting == null) { 10012 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10013 Slog.w(TAG, "Unknown permission " + name 10014 + " in package " + pkg.packageName); 10015 } 10016 continue; 10017 } 10018 10019 final String perm = bp.name; 10020 boolean allowedSig = false; 10021 int grant = GRANT_DENIED; 10022 10023 // Keep track of app op permissions. 10024 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 10025 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 10026 if (pkgs == null) { 10027 pkgs = new ArraySet<>(); 10028 mAppOpPermissionPackages.put(bp.name, pkgs); 10029 } 10030 pkgs.add(pkg.packageName); 10031 } 10032 10033 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10034 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10035 >= Build.VERSION_CODES.M; 10036 switch (level) { 10037 case PermissionInfo.PROTECTION_NORMAL: { 10038 // For all apps normal permissions are install time ones. 10039 grant = GRANT_INSTALL; 10040 } break; 10041 10042 case PermissionInfo.PROTECTION_DANGEROUS: { 10043 // If a permission review is required for legacy apps we represent 10044 // their permissions as always granted runtime ones since we need 10045 // to keep the review required permission flag per user while an 10046 // install permission's state is shared across all users. 10047 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10048 // For legacy apps dangerous permissions are install time ones. 10049 grant = GRANT_INSTALL; 10050 } else if (origPermissions.hasInstallPermission(bp.name)) { 10051 // For legacy apps that became modern, install becomes runtime. 10052 grant = GRANT_UPGRADE; 10053 } else if (mPromoteSystemApps 10054 && isSystemApp(ps) 10055 && mExistingSystemPackages.contains(ps.name)) { 10056 // For legacy system apps, install becomes runtime. 10057 // We cannot check hasInstallPermission() for system apps since those 10058 // permissions were granted implicitly and not persisted pre-M. 10059 grant = GRANT_UPGRADE; 10060 } else { 10061 // For modern apps keep runtime permissions unchanged. 10062 grant = GRANT_RUNTIME; 10063 } 10064 } break; 10065 10066 case PermissionInfo.PROTECTION_SIGNATURE: { 10067 // For all apps signature permissions are install time ones. 10068 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10069 if (allowedSig) { 10070 grant = GRANT_INSTALL; 10071 } 10072 } break; 10073 } 10074 10075 if (DEBUG_INSTALL) { 10076 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10077 } 10078 10079 if (grant != GRANT_DENIED) { 10080 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10081 // If this is an existing, non-system package, then 10082 // we can't add any new permissions to it. 10083 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10084 // Except... if this is a permission that was added 10085 // to the platform (note: need to only do this when 10086 // updating the platform). 10087 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10088 grant = GRANT_DENIED; 10089 } 10090 } 10091 } 10092 10093 switch (grant) { 10094 case GRANT_INSTALL: { 10095 // Revoke this as runtime permission to handle the case of 10096 // a runtime permission being downgraded to an install one. 10097 // Also in permission review mode we keep dangerous permissions 10098 // for legacy apps 10099 for (int userId : UserManagerService.getInstance().getUserIds()) { 10100 if (origPermissions.getRuntimePermissionState( 10101 bp.name, userId) != null) { 10102 // Revoke the runtime permission and clear the flags. 10103 origPermissions.revokeRuntimePermission(bp, userId); 10104 origPermissions.updatePermissionFlags(bp, userId, 10105 PackageManager.MASK_PERMISSION_FLAGS, 0); 10106 // If we revoked a permission permission, we have to write. 10107 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10108 changedRuntimePermissionUserIds, userId); 10109 } 10110 } 10111 // Grant an install permission. 10112 if (permissionsState.grantInstallPermission(bp) != 10113 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10114 changedInstallPermission = true; 10115 } 10116 } break; 10117 10118 case GRANT_RUNTIME: { 10119 // Grant previously granted runtime permissions. 10120 for (int userId : UserManagerService.getInstance().getUserIds()) { 10121 PermissionState permissionState = origPermissions 10122 .getRuntimePermissionState(bp.name, userId); 10123 int flags = permissionState != null 10124 ? permissionState.getFlags() : 0; 10125 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10126 if (permissionsState.grantRuntimePermission(bp, userId) == 10127 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10128 // If we cannot put the permission as it was, we have to write. 10129 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10130 changedRuntimePermissionUserIds, userId); 10131 } 10132 // If the app supports runtime permissions no need for a review. 10133 if (Build.PERMISSIONS_REVIEW_REQUIRED 10134 && appSupportsRuntimePermissions 10135 && (flags & PackageManager 10136 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10137 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10138 // Since we changed the flags, we have to write. 10139 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10140 changedRuntimePermissionUserIds, userId); 10141 } 10142 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10143 && !appSupportsRuntimePermissions) { 10144 // For legacy apps that need a permission review, every new 10145 // runtime permission is granted but it is pending a review. 10146 // We also need to review only platform defined runtime 10147 // permissions as these are the only ones the platform knows 10148 // how to disable the API to simulate revocation as legacy 10149 // apps don't expect to run with revoked permissions. 10150 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10151 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10152 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10153 // We changed the flags, hence have to write. 10154 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10155 changedRuntimePermissionUserIds, userId); 10156 } 10157 } 10158 if (permissionsState.grantRuntimePermission(bp, userId) 10159 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10160 // We changed the permission, hence have to write. 10161 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10162 changedRuntimePermissionUserIds, userId); 10163 } 10164 } 10165 // Propagate the permission flags. 10166 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10167 } 10168 } break; 10169 10170 case GRANT_UPGRADE: { 10171 // Grant runtime permissions for a previously held install permission. 10172 PermissionState permissionState = origPermissions 10173 .getInstallPermissionState(bp.name); 10174 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10175 10176 if (origPermissions.revokeInstallPermission(bp) 10177 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10178 // We will be transferring the permission flags, so clear them. 10179 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10180 PackageManager.MASK_PERMISSION_FLAGS, 0); 10181 changedInstallPermission = true; 10182 } 10183 10184 // If the permission is not to be promoted to runtime we ignore it and 10185 // also its other flags as they are not applicable to install permissions. 10186 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10187 for (int userId : currentUserIds) { 10188 if (permissionsState.grantRuntimePermission(bp, userId) != 10189 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10190 // Transfer the permission flags. 10191 permissionsState.updatePermissionFlags(bp, userId, 10192 flags, flags); 10193 // If we granted the permission, we have to write. 10194 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10195 changedRuntimePermissionUserIds, userId); 10196 } 10197 } 10198 } 10199 } break; 10200 10201 default: { 10202 if (packageOfInterest == null 10203 || packageOfInterest.equals(pkg.packageName)) { 10204 Slog.w(TAG, "Not granting permission " + perm 10205 + " to package " + pkg.packageName 10206 + " because it was previously installed without"); 10207 } 10208 } break; 10209 } 10210 } else { 10211 if (permissionsState.revokeInstallPermission(bp) != 10212 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10213 // Also drop the permission flags. 10214 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10215 PackageManager.MASK_PERMISSION_FLAGS, 0); 10216 changedInstallPermission = true; 10217 Slog.i(TAG, "Un-granting permission " + perm 10218 + " from package " + pkg.packageName 10219 + " (protectionLevel=" + bp.protectionLevel 10220 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10221 + ")"); 10222 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10223 // Don't print warning for app op permissions, since it is fine for them 10224 // not to be granted, there is a UI for the user to decide. 10225 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10226 Slog.w(TAG, "Not granting permission " + perm 10227 + " to package " + pkg.packageName 10228 + " (protectionLevel=" + bp.protectionLevel 10229 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10230 + ")"); 10231 } 10232 } 10233 } 10234 } 10235 10236 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10237 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10238 // This is the first that we have heard about this package, so the 10239 // permissions we have now selected are fixed until explicitly 10240 // changed. 10241 ps.installPermissionsFixed = true; 10242 } 10243 10244 // Persist the runtime permissions state for users with changes. If permissions 10245 // were revoked because no app in the shared user declares them we have to 10246 // write synchronously to avoid losing runtime permissions state. 10247 for (int userId : changedRuntimePermissionUserIds) { 10248 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10249 } 10250 10251 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10252 } 10253 10254 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10255 boolean allowed = false; 10256 final int NP = PackageParser.NEW_PERMISSIONS.length; 10257 for (int ip=0; ip<NP; ip++) { 10258 final PackageParser.NewPermissionInfo npi 10259 = PackageParser.NEW_PERMISSIONS[ip]; 10260 if (npi.name.equals(perm) 10261 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10262 allowed = true; 10263 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10264 + pkg.packageName); 10265 break; 10266 } 10267 } 10268 return allowed; 10269 } 10270 10271 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10272 BasePermission bp, PermissionsState origPermissions) { 10273 boolean allowed; 10274 allowed = (compareSignatures( 10275 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10276 == PackageManager.SIGNATURE_MATCH) 10277 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10278 == PackageManager.SIGNATURE_MATCH); 10279 if (!allowed && (bp.protectionLevel 10280 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10281 if (isSystemApp(pkg)) { 10282 // For updated system applications, a system permission 10283 // is granted only if it had been defined by the original application. 10284 if (pkg.isUpdatedSystemApp()) { 10285 final PackageSetting sysPs = mSettings 10286 .getDisabledSystemPkgLPr(pkg.packageName); 10287 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10288 // If the original was granted this permission, we take 10289 // that grant decision as read and propagate it to the 10290 // update. 10291 if (sysPs.isPrivileged()) { 10292 allowed = true; 10293 } 10294 } else { 10295 // The system apk may have been updated with an older 10296 // version of the one on the data partition, but which 10297 // granted a new system permission that it didn't have 10298 // before. In this case we do want to allow the app to 10299 // now get the new permission if the ancestral apk is 10300 // privileged to get it. 10301 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10302 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10303 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10304 allowed = true; 10305 break; 10306 } 10307 } 10308 } 10309 // Also if a privileged parent package on the system image or any of 10310 // its children requested a privileged permission, the updated child 10311 // packages can also get the permission. 10312 if (pkg.parentPackage != null) { 10313 final PackageSetting disabledSysParentPs = mSettings 10314 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10315 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10316 && disabledSysParentPs.isPrivileged()) { 10317 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10318 allowed = true; 10319 } else if (disabledSysParentPs.pkg.childPackages != null) { 10320 final int count = disabledSysParentPs.pkg.childPackages.size(); 10321 for (int i = 0; i < count; i++) { 10322 PackageParser.Package disabledSysChildPkg = 10323 disabledSysParentPs.pkg.childPackages.get(i); 10324 if (isPackageRequestingPermission(disabledSysChildPkg, 10325 perm)) { 10326 allowed = true; 10327 break; 10328 } 10329 } 10330 } 10331 } 10332 } 10333 } 10334 } else { 10335 allowed = isPrivilegedApp(pkg); 10336 } 10337 } 10338 } 10339 if (!allowed) { 10340 if (!allowed && (bp.protectionLevel 10341 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10342 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10343 // If this was a previously normal/dangerous permission that got moved 10344 // to a system permission as part of the runtime permission redesign, then 10345 // we still want to blindly grant it to old apps. 10346 allowed = true; 10347 } 10348 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10349 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10350 // If this permission is to be granted to the system installer and 10351 // this app is an installer, then it gets the permission. 10352 allowed = true; 10353 } 10354 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10355 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10356 // If this permission is to be granted to the system verifier and 10357 // this app is a verifier, then it gets the permission. 10358 allowed = true; 10359 } 10360 if (!allowed && (bp.protectionLevel 10361 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10362 && isSystemApp(pkg)) { 10363 // Any pre-installed system app is allowed to get this permission. 10364 allowed = true; 10365 } 10366 if (!allowed && (bp.protectionLevel 10367 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10368 // For development permissions, a development permission 10369 // is granted only if it was already granted. 10370 allowed = origPermissions.hasInstallPermission(perm); 10371 } 10372 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10373 && pkg.packageName.equals(mSetupWizardPackage)) { 10374 // If this permission is to be granted to the system setup wizard and 10375 // this app is a setup wizard, then it gets the permission. 10376 allowed = true; 10377 } 10378 } 10379 return allowed; 10380 } 10381 10382 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10383 final int permCount = pkg.requestedPermissions.size(); 10384 for (int j = 0; j < permCount; j++) { 10385 String requestedPermission = pkg.requestedPermissions.get(j); 10386 if (permission.equals(requestedPermission)) { 10387 return true; 10388 } 10389 } 10390 return false; 10391 } 10392 10393 final class ActivityIntentResolver 10394 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10395 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10396 boolean defaultOnly, int userId) { 10397 if (!sUserManager.exists(userId)) return null; 10398 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10399 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10400 } 10401 10402 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10403 int userId) { 10404 if (!sUserManager.exists(userId)) return null; 10405 mFlags = flags; 10406 return super.queryIntent(intent, resolvedType, 10407 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10408 } 10409 10410 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10411 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10412 if (!sUserManager.exists(userId)) return null; 10413 if (packageActivities == null) { 10414 return null; 10415 } 10416 mFlags = flags; 10417 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10418 final int N = packageActivities.size(); 10419 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10420 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10421 10422 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10423 for (int i = 0; i < N; ++i) { 10424 intentFilters = packageActivities.get(i).intents; 10425 if (intentFilters != null && intentFilters.size() > 0) { 10426 PackageParser.ActivityIntentInfo[] array = 10427 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10428 intentFilters.toArray(array); 10429 listCut.add(array); 10430 } 10431 } 10432 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10433 } 10434 10435 /** 10436 * Finds a privileged activity that matches the specified activity names. 10437 */ 10438 private PackageParser.Activity findMatchingActivity( 10439 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10440 for (PackageParser.Activity sysActivity : activityList) { 10441 if (sysActivity.info.name.equals(activityInfo.name)) { 10442 return sysActivity; 10443 } 10444 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10445 return sysActivity; 10446 } 10447 if (sysActivity.info.targetActivity != null) { 10448 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10449 return sysActivity; 10450 } 10451 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10452 return sysActivity; 10453 } 10454 } 10455 } 10456 return null; 10457 } 10458 10459 public class IterGenerator<E> { 10460 public Iterator<E> generate(ActivityIntentInfo info) { 10461 return null; 10462 } 10463 } 10464 10465 public class ActionIterGenerator extends IterGenerator<String> { 10466 @Override 10467 public Iterator<String> generate(ActivityIntentInfo info) { 10468 return info.actionsIterator(); 10469 } 10470 } 10471 10472 public class CategoriesIterGenerator extends IterGenerator<String> { 10473 @Override 10474 public Iterator<String> generate(ActivityIntentInfo info) { 10475 return info.categoriesIterator(); 10476 } 10477 } 10478 10479 public class SchemesIterGenerator extends IterGenerator<String> { 10480 @Override 10481 public Iterator<String> generate(ActivityIntentInfo info) { 10482 return info.schemesIterator(); 10483 } 10484 } 10485 10486 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10487 @Override 10488 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10489 return info.authoritiesIterator(); 10490 } 10491 } 10492 10493 /** 10494 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10495 * MODIFIED. Do not pass in a list that should not be changed. 10496 */ 10497 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10498 IterGenerator<T> generator, Iterator<T> searchIterator) { 10499 // loop through the set of actions; every one must be found in the intent filter 10500 while (searchIterator.hasNext()) { 10501 // we must have at least one filter in the list to consider a match 10502 if (intentList.size() == 0) { 10503 break; 10504 } 10505 10506 final T searchAction = searchIterator.next(); 10507 10508 // loop through the set of intent filters 10509 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10510 while (intentIter.hasNext()) { 10511 final ActivityIntentInfo intentInfo = intentIter.next(); 10512 boolean selectionFound = false; 10513 10514 // loop through the intent filter's selection criteria; at least one 10515 // of them must match the searched criteria 10516 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10517 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10518 final T intentSelection = intentSelectionIter.next(); 10519 if (intentSelection != null && intentSelection.equals(searchAction)) { 10520 selectionFound = true; 10521 break; 10522 } 10523 } 10524 10525 // the selection criteria wasn't found in this filter's set; this filter 10526 // is not a potential match 10527 if (!selectionFound) { 10528 intentIter.remove(); 10529 } 10530 } 10531 } 10532 } 10533 10534 private boolean isProtectedAction(ActivityIntentInfo filter) { 10535 final Iterator<String> actionsIter = filter.actionsIterator(); 10536 while (actionsIter != null && actionsIter.hasNext()) { 10537 final String filterAction = actionsIter.next(); 10538 if (PROTECTED_ACTIONS.contains(filterAction)) { 10539 return true; 10540 } 10541 } 10542 return false; 10543 } 10544 10545 /** 10546 * Adjusts the priority of the given intent filter according to policy. 10547 * <p> 10548 * <ul> 10549 * <li>The priority for non privileged applications is capped to '0'</li> 10550 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10551 * <li>The priority for unbundled updates to privileged applications is capped to the 10552 * priority defined on the system partition</li> 10553 * </ul> 10554 * <p> 10555 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10556 * allowed to obtain any priority on any action. 10557 */ 10558 private void adjustPriority( 10559 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10560 // nothing to do; priority is fine as-is 10561 if (intent.getPriority() <= 0) { 10562 return; 10563 } 10564 10565 final ActivityInfo activityInfo = intent.activity.info; 10566 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10567 10568 final boolean privilegedApp = 10569 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10570 if (!privilegedApp) { 10571 // non-privileged applications can never define a priority >0 10572 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10573 + " package: " + applicationInfo.packageName 10574 + " activity: " + intent.activity.className 10575 + " origPrio: " + intent.getPriority()); 10576 intent.setPriority(0); 10577 return; 10578 } 10579 10580 if (systemActivities == null) { 10581 // the system package is not disabled; we're parsing the system partition 10582 if (isProtectedAction(intent)) { 10583 if (mDeferProtectedFilters) { 10584 // We can't deal with these just yet. No component should ever obtain a 10585 // >0 priority for a protected actions, with ONE exception -- the setup 10586 // wizard. The setup wizard, however, cannot be known until we're able to 10587 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10588 // until all intent filters have been processed. Chicken, meet egg. 10589 // Let the filter temporarily have a high priority and rectify the 10590 // priorities after all system packages have been scanned. 10591 mProtectedFilters.add(intent); 10592 if (DEBUG_FILTERS) { 10593 Slog.i(TAG, "Protected action; save for later;" 10594 + " package: " + applicationInfo.packageName 10595 + " activity: " + intent.activity.className 10596 + " origPrio: " + intent.getPriority()); 10597 } 10598 return; 10599 } else { 10600 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10601 Slog.i(TAG, "No setup wizard;" 10602 + " All protected intents capped to priority 0"); 10603 } 10604 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10605 if (DEBUG_FILTERS) { 10606 Slog.i(TAG, "Found setup wizard;" 10607 + " allow priority " + intent.getPriority() + ";" 10608 + " package: " + intent.activity.info.packageName 10609 + " activity: " + intent.activity.className 10610 + " priority: " + intent.getPriority()); 10611 } 10612 // setup wizard gets whatever it wants 10613 return; 10614 } 10615 Slog.w(TAG, "Protected action; cap priority to 0;" 10616 + " package: " + intent.activity.info.packageName 10617 + " activity: " + intent.activity.className 10618 + " origPrio: " + intent.getPriority()); 10619 intent.setPriority(0); 10620 return; 10621 } 10622 } 10623 // privileged apps on the system image get whatever priority they request 10624 return; 10625 } 10626 10627 // privileged app unbundled update ... try to find the same activity 10628 final PackageParser.Activity foundActivity = 10629 findMatchingActivity(systemActivities, activityInfo); 10630 if (foundActivity == null) { 10631 // this is a new activity; it cannot obtain >0 priority 10632 if (DEBUG_FILTERS) { 10633 Slog.i(TAG, "New activity; cap priority to 0;" 10634 + " package: " + applicationInfo.packageName 10635 + " activity: " + intent.activity.className 10636 + " origPrio: " + intent.getPriority()); 10637 } 10638 intent.setPriority(0); 10639 return; 10640 } 10641 10642 // found activity, now check for filter equivalence 10643 10644 // a shallow copy is enough; we modify the list, not its contents 10645 final List<ActivityIntentInfo> intentListCopy = 10646 new ArrayList<>(foundActivity.intents); 10647 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10648 10649 // find matching action subsets 10650 final Iterator<String> actionsIterator = intent.actionsIterator(); 10651 if (actionsIterator != null) { 10652 getIntentListSubset( 10653 intentListCopy, new ActionIterGenerator(), actionsIterator); 10654 if (intentListCopy.size() == 0) { 10655 // no more intents to match; we're not equivalent 10656 if (DEBUG_FILTERS) { 10657 Slog.i(TAG, "Mismatched action; 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 10667 // find matching category subsets 10668 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10669 if (categoriesIterator != null) { 10670 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10671 categoriesIterator); 10672 if (intentListCopy.size() == 0) { 10673 // no more intents to match; we're not equivalent 10674 if (DEBUG_FILTERS) { 10675 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10676 + " package: " + applicationInfo.packageName 10677 + " activity: " + intent.activity.className 10678 + " origPrio: " + intent.getPriority()); 10679 } 10680 intent.setPriority(0); 10681 return; 10682 } 10683 } 10684 10685 // find matching schemes subsets 10686 final Iterator<String> schemesIterator = intent.schemesIterator(); 10687 if (schemesIterator != null) { 10688 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10689 schemesIterator); 10690 if (intentListCopy.size() == 0) { 10691 // no more intents to match; we're not equivalent 10692 if (DEBUG_FILTERS) { 10693 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10694 + " package: " + applicationInfo.packageName 10695 + " activity: " + intent.activity.className 10696 + " origPrio: " + intent.getPriority()); 10697 } 10698 intent.setPriority(0); 10699 return; 10700 } 10701 } 10702 10703 // find matching authorities subsets 10704 final Iterator<IntentFilter.AuthorityEntry> 10705 authoritiesIterator = intent.authoritiesIterator(); 10706 if (authoritiesIterator != null) { 10707 getIntentListSubset(intentListCopy, 10708 new AuthoritiesIterGenerator(), 10709 authoritiesIterator); 10710 if (intentListCopy.size() == 0) { 10711 // no more intents to match; we're not equivalent 10712 if (DEBUG_FILTERS) { 10713 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10714 + " package: " + applicationInfo.packageName 10715 + " activity: " + intent.activity.className 10716 + " origPrio: " + intent.getPriority()); 10717 } 10718 intent.setPriority(0); 10719 return; 10720 } 10721 } 10722 10723 // we found matching filter(s); app gets the max priority of all intents 10724 int cappedPriority = 0; 10725 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10726 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10727 } 10728 if (intent.getPriority() > cappedPriority) { 10729 if (DEBUG_FILTERS) { 10730 Slog.i(TAG, "Found matching filter(s);" 10731 + " cap priority to " + cappedPriority + ";" 10732 + " package: " + applicationInfo.packageName 10733 + " activity: " + intent.activity.className 10734 + " origPrio: " + intent.getPriority()); 10735 } 10736 intent.setPriority(cappedPriority); 10737 return; 10738 } 10739 // all this for nothing; the requested priority was <= what was on the system 10740 } 10741 10742 public final void addActivity(PackageParser.Activity a, String type) { 10743 mActivities.put(a.getComponentName(), a); 10744 if (DEBUG_SHOW_INFO) 10745 Log.v( 10746 TAG, " " + type + " " + 10747 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10748 if (DEBUG_SHOW_INFO) 10749 Log.v(TAG, " Class=" + a.info.name); 10750 final int NI = a.intents.size(); 10751 for (int j=0; j<NI; j++) { 10752 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10753 if ("activity".equals(type)) { 10754 final PackageSetting ps = 10755 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10756 final List<PackageParser.Activity> systemActivities = 10757 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10758 adjustPriority(systemActivities, intent); 10759 } 10760 if (DEBUG_SHOW_INFO) { 10761 Log.v(TAG, " IntentFilter:"); 10762 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10763 } 10764 if (!intent.debugCheck()) { 10765 Log.w(TAG, "==> For Activity " + a.info.name); 10766 } 10767 addFilter(intent); 10768 } 10769 } 10770 10771 public final void removeActivity(PackageParser.Activity a, String type) { 10772 mActivities.remove(a.getComponentName()); 10773 if (DEBUG_SHOW_INFO) { 10774 Log.v(TAG, " " + type + " " 10775 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10776 : a.info.name) + ":"); 10777 Log.v(TAG, " Class=" + a.info.name); 10778 } 10779 final int NI = a.intents.size(); 10780 for (int j=0; j<NI; j++) { 10781 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10782 if (DEBUG_SHOW_INFO) { 10783 Log.v(TAG, " IntentFilter:"); 10784 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10785 } 10786 removeFilter(intent); 10787 } 10788 } 10789 10790 @Override 10791 protected boolean allowFilterResult( 10792 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10793 ActivityInfo filterAi = filter.activity.info; 10794 for (int i=dest.size()-1; i>=0; i--) { 10795 ActivityInfo destAi = dest.get(i).activityInfo; 10796 if (destAi.name == filterAi.name 10797 && destAi.packageName == filterAi.packageName) { 10798 return false; 10799 } 10800 } 10801 return true; 10802 } 10803 10804 @Override 10805 protected ActivityIntentInfo[] newArray(int size) { 10806 return new ActivityIntentInfo[size]; 10807 } 10808 10809 @Override 10810 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10811 if (!sUserManager.exists(userId)) return true; 10812 PackageParser.Package p = filter.activity.owner; 10813 if (p != null) { 10814 PackageSetting ps = (PackageSetting)p.mExtras; 10815 if (ps != null) { 10816 // System apps are never considered stopped for purposes of 10817 // filtering, because there may be no way for the user to 10818 // actually re-launch them. 10819 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10820 && ps.getStopped(userId); 10821 } 10822 } 10823 return false; 10824 } 10825 10826 @Override 10827 protected boolean isPackageForFilter(String packageName, 10828 PackageParser.ActivityIntentInfo info) { 10829 return packageName.equals(info.activity.owner.packageName); 10830 } 10831 10832 @Override 10833 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10834 int match, int userId) { 10835 if (!sUserManager.exists(userId)) return null; 10836 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10837 return null; 10838 } 10839 final PackageParser.Activity activity = info.activity; 10840 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10841 if (ps == null) { 10842 return null; 10843 } 10844 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10845 ps.readUserState(userId), userId); 10846 if (ai == null) { 10847 return null; 10848 } 10849 final ResolveInfo res = new ResolveInfo(); 10850 res.activityInfo = ai; 10851 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10852 res.filter = info; 10853 } 10854 if (info != null) { 10855 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10856 } 10857 res.priority = info.getPriority(); 10858 res.preferredOrder = activity.owner.mPreferredOrder; 10859 //System.out.println("Result: " + res.activityInfo.className + 10860 // " = " + res.priority); 10861 res.match = match; 10862 res.isDefault = info.hasDefault; 10863 res.labelRes = info.labelRes; 10864 res.nonLocalizedLabel = info.nonLocalizedLabel; 10865 if (userNeedsBadging(userId)) { 10866 res.noResourceId = true; 10867 } else { 10868 res.icon = info.icon; 10869 } 10870 res.iconResourceId = info.icon; 10871 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10872 return res; 10873 } 10874 10875 @Override 10876 protected void sortResults(List<ResolveInfo> results) { 10877 Collections.sort(results, mResolvePrioritySorter); 10878 } 10879 10880 @Override 10881 protected void dumpFilter(PrintWriter out, String prefix, 10882 PackageParser.ActivityIntentInfo filter) { 10883 out.print(prefix); out.print( 10884 Integer.toHexString(System.identityHashCode(filter.activity))); 10885 out.print(' '); 10886 filter.activity.printComponentShortName(out); 10887 out.print(" filter "); 10888 out.println(Integer.toHexString(System.identityHashCode(filter))); 10889 } 10890 10891 @Override 10892 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10893 return filter.activity; 10894 } 10895 10896 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10897 PackageParser.Activity activity = (PackageParser.Activity)label; 10898 out.print(prefix); out.print( 10899 Integer.toHexString(System.identityHashCode(activity))); 10900 out.print(' '); 10901 activity.printComponentShortName(out); 10902 if (count > 1) { 10903 out.print(" ("); out.print(count); out.print(" filters)"); 10904 } 10905 out.println(); 10906 } 10907 10908 // Keys are String (activity class name), values are Activity. 10909 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10910 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10911 private int mFlags; 10912 } 10913 10914 private final class ServiceIntentResolver 10915 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10916 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10917 boolean defaultOnly, int userId) { 10918 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10919 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10920 } 10921 10922 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10923 int userId) { 10924 if (!sUserManager.exists(userId)) return null; 10925 mFlags = flags; 10926 return super.queryIntent(intent, resolvedType, 10927 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10928 } 10929 10930 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10931 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10932 if (!sUserManager.exists(userId)) return null; 10933 if (packageServices == null) { 10934 return null; 10935 } 10936 mFlags = flags; 10937 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10938 final int N = packageServices.size(); 10939 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10940 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10941 10942 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10943 for (int i = 0; i < N; ++i) { 10944 intentFilters = packageServices.get(i).intents; 10945 if (intentFilters != null && intentFilters.size() > 0) { 10946 PackageParser.ServiceIntentInfo[] array = 10947 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10948 intentFilters.toArray(array); 10949 listCut.add(array); 10950 } 10951 } 10952 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10953 } 10954 10955 public final void addService(PackageParser.Service s) { 10956 mServices.put(s.getComponentName(), s); 10957 if (DEBUG_SHOW_INFO) { 10958 Log.v(TAG, " " 10959 + (s.info.nonLocalizedLabel != null 10960 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10961 Log.v(TAG, " Class=" + s.info.name); 10962 } 10963 final int NI = s.intents.size(); 10964 int j; 10965 for (j=0; j<NI; j++) { 10966 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10967 if (DEBUG_SHOW_INFO) { 10968 Log.v(TAG, " IntentFilter:"); 10969 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10970 } 10971 if (!intent.debugCheck()) { 10972 Log.w(TAG, "==> For Service " + s.info.name); 10973 } 10974 addFilter(intent); 10975 } 10976 } 10977 10978 public final void removeService(PackageParser.Service s) { 10979 mServices.remove(s.getComponentName()); 10980 if (DEBUG_SHOW_INFO) { 10981 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10982 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10983 Log.v(TAG, " Class=" + s.info.name); 10984 } 10985 final int NI = s.intents.size(); 10986 int j; 10987 for (j=0; j<NI; j++) { 10988 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10989 if (DEBUG_SHOW_INFO) { 10990 Log.v(TAG, " IntentFilter:"); 10991 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10992 } 10993 removeFilter(intent); 10994 } 10995 } 10996 10997 @Override 10998 protected boolean allowFilterResult( 10999 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 11000 ServiceInfo filterSi = filter.service.info; 11001 for (int i=dest.size()-1; i>=0; i--) { 11002 ServiceInfo destAi = dest.get(i).serviceInfo; 11003 if (destAi.name == filterSi.name 11004 && destAi.packageName == filterSi.packageName) { 11005 return false; 11006 } 11007 } 11008 return true; 11009 } 11010 11011 @Override 11012 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 11013 return new PackageParser.ServiceIntentInfo[size]; 11014 } 11015 11016 @Override 11017 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 11018 if (!sUserManager.exists(userId)) return true; 11019 PackageParser.Package p = filter.service.owner; 11020 if (p != null) { 11021 PackageSetting ps = (PackageSetting)p.mExtras; 11022 if (ps != null) { 11023 // System apps are never considered stopped for purposes of 11024 // filtering, because there may be no way for the user to 11025 // actually re-launch them. 11026 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11027 && ps.getStopped(userId); 11028 } 11029 } 11030 return false; 11031 } 11032 11033 @Override 11034 protected boolean isPackageForFilter(String packageName, 11035 PackageParser.ServiceIntentInfo info) { 11036 return packageName.equals(info.service.owner.packageName); 11037 } 11038 11039 @Override 11040 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11041 int match, int userId) { 11042 if (!sUserManager.exists(userId)) return null; 11043 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11044 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11045 return null; 11046 } 11047 final PackageParser.Service service = info.service; 11048 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11049 if (ps == null) { 11050 return null; 11051 } 11052 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11053 ps.readUserState(userId), userId); 11054 if (si == null) { 11055 return null; 11056 } 11057 final ResolveInfo res = new ResolveInfo(); 11058 res.serviceInfo = si; 11059 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11060 res.filter = filter; 11061 } 11062 res.priority = info.getPriority(); 11063 res.preferredOrder = service.owner.mPreferredOrder; 11064 res.match = match; 11065 res.isDefault = info.hasDefault; 11066 res.labelRes = info.labelRes; 11067 res.nonLocalizedLabel = info.nonLocalizedLabel; 11068 res.icon = info.icon; 11069 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11070 return res; 11071 } 11072 11073 @Override 11074 protected void sortResults(List<ResolveInfo> results) { 11075 Collections.sort(results, mResolvePrioritySorter); 11076 } 11077 11078 @Override 11079 protected void dumpFilter(PrintWriter out, String prefix, 11080 PackageParser.ServiceIntentInfo filter) { 11081 out.print(prefix); out.print( 11082 Integer.toHexString(System.identityHashCode(filter.service))); 11083 out.print(' '); 11084 filter.service.printComponentShortName(out); 11085 out.print(" filter "); 11086 out.println(Integer.toHexString(System.identityHashCode(filter))); 11087 } 11088 11089 @Override 11090 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11091 return filter.service; 11092 } 11093 11094 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11095 PackageParser.Service service = (PackageParser.Service)label; 11096 out.print(prefix); out.print( 11097 Integer.toHexString(System.identityHashCode(service))); 11098 out.print(' '); 11099 service.printComponentShortName(out); 11100 if (count > 1) { 11101 out.print(" ("); out.print(count); out.print(" filters)"); 11102 } 11103 out.println(); 11104 } 11105 11106// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11107// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11108// final List<ResolveInfo> retList = Lists.newArrayList(); 11109// while (i.hasNext()) { 11110// final ResolveInfo resolveInfo = (ResolveInfo) i; 11111// if (isEnabledLP(resolveInfo.serviceInfo)) { 11112// retList.add(resolveInfo); 11113// } 11114// } 11115// return retList; 11116// } 11117 11118 // Keys are String (activity class name), values are Activity. 11119 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11120 = new ArrayMap<ComponentName, PackageParser.Service>(); 11121 private int mFlags; 11122 }; 11123 11124 private final class ProviderIntentResolver 11125 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11126 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11127 boolean defaultOnly, int userId) { 11128 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11129 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11130 } 11131 11132 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11133 int userId) { 11134 if (!sUserManager.exists(userId)) 11135 return null; 11136 mFlags = flags; 11137 return super.queryIntent(intent, resolvedType, 11138 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11139 } 11140 11141 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11142 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11143 if (!sUserManager.exists(userId)) 11144 return null; 11145 if (packageProviders == null) { 11146 return null; 11147 } 11148 mFlags = flags; 11149 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11150 final int N = packageProviders.size(); 11151 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11152 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11153 11154 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11155 for (int i = 0; i < N; ++i) { 11156 intentFilters = packageProviders.get(i).intents; 11157 if (intentFilters != null && intentFilters.size() > 0) { 11158 PackageParser.ProviderIntentInfo[] array = 11159 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11160 intentFilters.toArray(array); 11161 listCut.add(array); 11162 } 11163 } 11164 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11165 } 11166 11167 public final void addProvider(PackageParser.Provider p) { 11168 if (mProviders.containsKey(p.getComponentName())) { 11169 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11170 return; 11171 } 11172 11173 mProviders.put(p.getComponentName(), p); 11174 if (DEBUG_SHOW_INFO) { 11175 Log.v(TAG, " " 11176 + (p.info.nonLocalizedLabel != null 11177 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11178 Log.v(TAG, " Class=" + p.info.name); 11179 } 11180 final int NI = p.intents.size(); 11181 int j; 11182 for (j = 0; j < NI; j++) { 11183 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11184 if (DEBUG_SHOW_INFO) { 11185 Log.v(TAG, " IntentFilter:"); 11186 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11187 } 11188 if (!intent.debugCheck()) { 11189 Log.w(TAG, "==> For Provider " + p.info.name); 11190 } 11191 addFilter(intent); 11192 } 11193 } 11194 11195 public final void removeProvider(PackageParser.Provider p) { 11196 mProviders.remove(p.getComponentName()); 11197 if (DEBUG_SHOW_INFO) { 11198 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11199 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11200 Log.v(TAG, " Class=" + p.info.name); 11201 } 11202 final int NI = p.intents.size(); 11203 int j; 11204 for (j = 0; j < NI; j++) { 11205 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11206 if (DEBUG_SHOW_INFO) { 11207 Log.v(TAG, " IntentFilter:"); 11208 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11209 } 11210 removeFilter(intent); 11211 } 11212 } 11213 11214 @Override 11215 protected boolean allowFilterResult( 11216 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11217 ProviderInfo filterPi = filter.provider.info; 11218 for (int i = dest.size() - 1; i >= 0; i--) { 11219 ProviderInfo destPi = dest.get(i).providerInfo; 11220 if (destPi.name == filterPi.name 11221 && destPi.packageName == filterPi.packageName) { 11222 return false; 11223 } 11224 } 11225 return true; 11226 } 11227 11228 @Override 11229 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11230 return new PackageParser.ProviderIntentInfo[size]; 11231 } 11232 11233 @Override 11234 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11235 if (!sUserManager.exists(userId)) 11236 return true; 11237 PackageParser.Package p = filter.provider.owner; 11238 if (p != null) { 11239 PackageSetting ps = (PackageSetting) p.mExtras; 11240 if (ps != null) { 11241 // System apps are never considered stopped for purposes of 11242 // filtering, because there may be no way for the user to 11243 // actually re-launch them. 11244 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11245 && ps.getStopped(userId); 11246 } 11247 } 11248 return false; 11249 } 11250 11251 @Override 11252 protected boolean isPackageForFilter(String packageName, 11253 PackageParser.ProviderIntentInfo info) { 11254 return packageName.equals(info.provider.owner.packageName); 11255 } 11256 11257 @Override 11258 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11259 int match, int userId) { 11260 if (!sUserManager.exists(userId)) 11261 return null; 11262 final PackageParser.ProviderIntentInfo info = filter; 11263 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11264 return null; 11265 } 11266 final PackageParser.Provider provider = info.provider; 11267 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11268 if (ps == null) { 11269 return null; 11270 } 11271 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11272 ps.readUserState(userId), userId); 11273 if (pi == null) { 11274 return null; 11275 } 11276 final ResolveInfo res = new ResolveInfo(); 11277 res.providerInfo = pi; 11278 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11279 res.filter = filter; 11280 } 11281 res.priority = info.getPriority(); 11282 res.preferredOrder = provider.owner.mPreferredOrder; 11283 res.match = match; 11284 res.isDefault = info.hasDefault; 11285 res.labelRes = info.labelRes; 11286 res.nonLocalizedLabel = info.nonLocalizedLabel; 11287 res.icon = info.icon; 11288 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11289 return res; 11290 } 11291 11292 @Override 11293 protected void sortResults(List<ResolveInfo> results) { 11294 Collections.sort(results, mResolvePrioritySorter); 11295 } 11296 11297 @Override 11298 protected void dumpFilter(PrintWriter out, String prefix, 11299 PackageParser.ProviderIntentInfo filter) { 11300 out.print(prefix); 11301 out.print( 11302 Integer.toHexString(System.identityHashCode(filter.provider))); 11303 out.print(' '); 11304 filter.provider.printComponentShortName(out); 11305 out.print(" filter "); 11306 out.println(Integer.toHexString(System.identityHashCode(filter))); 11307 } 11308 11309 @Override 11310 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11311 return filter.provider; 11312 } 11313 11314 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11315 PackageParser.Provider provider = (PackageParser.Provider)label; 11316 out.print(prefix); out.print( 11317 Integer.toHexString(System.identityHashCode(provider))); 11318 out.print(' '); 11319 provider.printComponentShortName(out); 11320 if (count > 1) { 11321 out.print(" ("); out.print(count); out.print(" filters)"); 11322 } 11323 out.println(); 11324 } 11325 11326 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11327 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11328 private int mFlags; 11329 } 11330 11331 private static final class EphemeralIntentResolver 11332 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11333 @Override 11334 protected EphemeralResolveIntentInfo[] newArray(int size) { 11335 return new EphemeralResolveIntentInfo[size]; 11336 } 11337 11338 @Override 11339 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11340 return true; 11341 } 11342 11343 @Override 11344 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11345 int userId) { 11346 if (!sUserManager.exists(userId)) { 11347 return null; 11348 } 11349 return info.getEphemeralResolveInfo(); 11350 } 11351 } 11352 11353 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11354 new Comparator<ResolveInfo>() { 11355 public int compare(ResolveInfo r1, ResolveInfo r2) { 11356 int v1 = r1.priority; 11357 int v2 = r2.priority; 11358 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11359 if (v1 != v2) { 11360 return (v1 > v2) ? -1 : 1; 11361 } 11362 v1 = r1.preferredOrder; 11363 v2 = r2.preferredOrder; 11364 if (v1 != v2) { 11365 return (v1 > v2) ? -1 : 1; 11366 } 11367 if (r1.isDefault != r2.isDefault) { 11368 return r1.isDefault ? -1 : 1; 11369 } 11370 v1 = r1.match; 11371 v2 = r2.match; 11372 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11373 if (v1 != v2) { 11374 return (v1 > v2) ? -1 : 1; 11375 } 11376 if (r1.system != r2.system) { 11377 return r1.system ? -1 : 1; 11378 } 11379 if (r1.activityInfo != null) { 11380 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11381 } 11382 if (r1.serviceInfo != null) { 11383 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11384 } 11385 if (r1.providerInfo != null) { 11386 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11387 } 11388 return 0; 11389 } 11390 }; 11391 11392 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11393 new Comparator<ProviderInfo>() { 11394 public int compare(ProviderInfo p1, ProviderInfo p2) { 11395 final int v1 = p1.initOrder; 11396 final int v2 = p2.initOrder; 11397 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11398 } 11399 }; 11400 11401 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11402 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11403 final int[] userIds) { 11404 mHandler.post(new Runnable() { 11405 @Override 11406 public void run() { 11407 try { 11408 final IActivityManager am = ActivityManagerNative.getDefault(); 11409 if (am == null) return; 11410 final int[] resolvedUserIds; 11411 if (userIds == null) { 11412 resolvedUserIds = am.getRunningUserIds(); 11413 } else { 11414 resolvedUserIds = userIds; 11415 } 11416 for (int id : resolvedUserIds) { 11417 final Intent intent = new Intent(action, 11418 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11419 if (extras != null) { 11420 intent.putExtras(extras); 11421 } 11422 if (targetPkg != null) { 11423 intent.setPackage(targetPkg); 11424 } 11425 // Modify the UID when posting to other users 11426 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11427 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11428 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11429 intent.putExtra(Intent.EXTRA_UID, uid); 11430 } 11431 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11432 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11433 if (DEBUG_BROADCASTS) { 11434 RuntimeException here = new RuntimeException("here"); 11435 here.fillInStackTrace(); 11436 Slog.d(TAG, "Sending to user " + id + ": " 11437 + intent.toShortString(false, true, false, false) 11438 + " " + intent.getExtras(), here); 11439 } 11440 am.broadcastIntent(null, intent, null, finishedReceiver, 11441 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11442 null, finishedReceiver != null, false, id); 11443 } 11444 } catch (RemoteException ex) { 11445 } 11446 } 11447 }); 11448 } 11449 11450 /** 11451 * Check if the external storage media is available. This is true if there 11452 * is a mounted external storage medium or if the external storage is 11453 * emulated. 11454 */ 11455 private boolean isExternalMediaAvailable() { 11456 return mMediaMounted || Environment.isExternalStorageEmulated(); 11457 } 11458 11459 @Override 11460 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11461 // writer 11462 synchronized (mPackages) { 11463 if (!isExternalMediaAvailable()) { 11464 // If the external storage is no longer mounted at this point, 11465 // the caller may not have been able to delete all of this 11466 // packages files and can not delete any more. Bail. 11467 return null; 11468 } 11469 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11470 if (lastPackage != null) { 11471 pkgs.remove(lastPackage); 11472 } 11473 if (pkgs.size() > 0) { 11474 return pkgs.get(0); 11475 } 11476 } 11477 return null; 11478 } 11479 11480 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11481 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11482 userId, andCode ? 1 : 0, packageName); 11483 if (mSystemReady) { 11484 msg.sendToTarget(); 11485 } else { 11486 if (mPostSystemReadyMessages == null) { 11487 mPostSystemReadyMessages = new ArrayList<>(); 11488 } 11489 mPostSystemReadyMessages.add(msg); 11490 } 11491 } 11492 11493 void startCleaningPackages() { 11494 // reader 11495 if (!isExternalMediaAvailable()) { 11496 return; 11497 } 11498 synchronized (mPackages) { 11499 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11500 return; 11501 } 11502 } 11503 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11504 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11505 IActivityManager am = ActivityManagerNative.getDefault(); 11506 if (am != null) { 11507 try { 11508 am.startService(null, intent, null, mContext.getOpPackageName(), 11509 UserHandle.USER_SYSTEM); 11510 } catch (RemoteException e) { 11511 } 11512 } 11513 } 11514 11515 @Override 11516 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11517 int installFlags, String installerPackageName, int userId) { 11518 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11519 11520 final int callingUid = Binder.getCallingUid(); 11521 enforceCrossUserPermission(callingUid, userId, 11522 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11523 11524 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11525 try { 11526 if (observer != null) { 11527 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11528 } 11529 } catch (RemoteException re) { 11530 } 11531 return; 11532 } 11533 11534 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11535 installFlags |= PackageManager.INSTALL_FROM_ADB; 11536 11537 } else { 11538 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11539 // about installerPackageName. 11540 11541 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11542 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11543 } 11544 11545 UserHandle user; 11546 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11547 user = UserHandle.ALL; 11548 } else { 11549 user = new UserHandle(userId); 11550 } 11551 11552 // Only system components can circumvent runtime permissions when installing. 11553 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11554 && mContext.checkCallingOrSelfPermission(Manifest.permission 11555 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11556 throw new SecurityException("You need the " 11557 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11558 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11559 } 11560 11561 final File originFile = new File(originPath); 11562 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11563 11564 final Message msg = mHandler.obtainMessage(INIT_COPY); 11565 final VerificationInfo verificationInfo = new VerificationInfo( 11566 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11567 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11568 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11569 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11570 null /*certificates*/); 11571 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11572 msg.obj = params; 11573 11574 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11575 System.identityHashCode(msg.obj)); 11576 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11577 System.identityHashCode(msg.obj)); 11578 11579 mHandler.sendMessage(msg); 11580 } 11581 11582 void installStage(String packageName, File stagedDir, String stagedCid, 11583 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11584 String installerPackageName, int installerUid, UserHandle user, 11585 Certificate[][] certificates) { 11586 if (DEBUG_EPHEMERAL) { 11587 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11588 Slog.d(TAG, "Ephemeral install of " + packageName); 11589 } 11590 } 11591 final VerificationInfo verificationInfo = new VerificationInfo( 11592 sessionParams.originatingUri, sessionParams.referrerUri, 11593 sessionParams.originatingUid, installerUid); 11594 11595 final OriginInfo origin; 11596 if (stagedDir != null) { 11597 origin = OriginInfo.fromStagedFile(stagedDir); 11598 } else { 11599 origin = OriginInfo.fromStagedContainer(stagedCid); 11600 } 11601 11602 final Message msg = mHandler.obtainMessage(INIT_COPY); 11603 final InstallParams params = new InstallParams(origin, null, observer, 11604 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11605 verificationInfo, user, sessionParams.abiOverride, 11606 sessionParams.grantedRuntimePermissions, certificates); 11607 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11608 msg.obj = params; 11609 11610 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11611 System.identityHashCode(msg.obj)); 11612 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11613 System.identityHashCode(msg.obj)); 11614 11615 mHandler.sendMessage(msg); 11616 } 11617 11618 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11619 int userId) { 11620 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11621 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11622 } 11623 11624 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11625 int appId, int userId) { 11626 Bundle extras = new Bundle(1); 11627 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11628 11629 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11630 packageName, extras, 0, null, null, new int[] {userId}); 11631 try { 11632 IActivityManager am = ActivityManagerNative.getDefault(); 11633 if (isSystem && am.isUserRunning(userId, 0)) { 11634 // The just-installed/enabled app is bundled on the system, so presumed 11635 // to be able to run automatically without needing an explicit launch. 11636 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11637 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11638 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11639 .setPackage(packageName); 11640 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11641 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11642 } 11643 } catch (RemoteException e) { 11644 // shouldn't happen 11645 Slog.w(TAG, "Unable to bootstrap installed package", e); 11646 } 11647 } 11648 11649 @Override 11650 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11651 int userId) { 11652 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11653 PackageSetting pkgSetting; 11654 final int uid = Binder.getCallingUid(); 11655 enforceCrossUserPermission(uid, userId, 11656 true /* requireFullPermission */, true /* checkShell */, 11657 "setApplicationHiddenSetting for user " + userId); 11658 11659 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11660 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11661 return false; 11662 } 11663 11664 long callingId = Binder.clearCallingIdentity(); 11665 try { 11666 boolean sendAdded = false; 11667 boolean sendRemoved = false; 11668 // writer 11669 synchronized (mPackages) { 11670 pkgSetting = mSettings.mPackages.get(packageName); 11671 if (pkgSetting == null) { 11672 return false; 11673 } 11674 if (pkgSetting.getHidden(userId) != hidden) { 11675 pkgSetting.setHidden(hidden, userId); 11676 mSettings.writePackageRestrictionsLPr(userId); 11677 if (hidden) { 11678 sendRemoved = true; 11679 } else { 11680 sendAdded = true; 11681 } 11682 } 11683 } 11684 if (sendAdded) { 11685 sendPackageAddedForUser(packageName, pkgSetting, userId); 11686 return true; 11687 } 11688 if (sendRemoved) { 11689 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11690 "hiding pkg"); 11691 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11692 return true; 11693 } 11694 } finally { 11695 Binder.restoreCallingIdentity(callingId); 11696 } 11697 return false; 11698 } 11699 11700 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11701 int userId) { 11702 final PackageRemovedInfo info = new PackageRemovedInfo(); 11703 info.removedPackage = packageName; 11704 info.removedUsers = new int[] {userId}; 11705 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11706 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11707 } 11708 11709 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11710 if (pkgList.length > 0) { 11711 Bundle extras = new Bundle(1); 11712 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11713 11714 sendPackageBroadcast( 11715 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11716 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11717 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11718 new int[] {userId}); 11719 } 11720 } 11721 11722 /** 11723 * Returns true if application is not found or there was an error. Otherwise it returns 11724 * the hidden state of the package for the given user. 11725 */ 11726 @Override 11727 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11728 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11729 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11730 true /* requireFullPermission */, false /* checkShell */, 11731 "getApplicationHidden for user " + userId); 11732 PackageSetting pkgSetting; 11733 long callingId = Binder.clearCallingIdentity(); 11734 try { 11735 // writer 11736 synchronized (mPackages) { 11737 pkgSetting = mSettings.mPackages.get(packageName); 11738 if (pkgSetting == null) { 11739 return true; 11740 } 11741 return pkgSetting.getHidden(userId); 11742 } 11743 } finally { 11744 Binder.restoreCallingIdentity(callingId); 11745 } 11746 } 11747 11748 /** 11749 * @hide 11750 */ 11751 @Override 11752 public int installExistingPackageAsUser(String packageName, int userId) { 11753 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11754 null); 11755 PackageSetting pkgSetting; 11756 final int uid = Binder.getCallingUid(); 11757 enforceCrossUserPermission(uid, userId, 11758 true /* requireFullPermission */, true /* checkShell */, 11759 "installExistingPackage for user " + userId); 11760 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11761 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11762 } 11763 11764 long callingId = Binder.clearCallingIdentity(); 11765 try { 11766 boolean installed = false; 11767 11768 // writer 11769 synchronized (mPackages) { 11770 pkgSetting = mSettings.mPackages.get(packageName); 11771 if (pkgSetting == null) { 11772 return PackageManager.INSTALL_FAILED_INVALID_URI; 11773 } 11774 if (!pkgSetting.getInstalled(userId)) { 11775 pkgSetting.setInstalled(true, userId); 11776 pkgSetting.setHidden(false, userId); 11777 mSettings.writePackageRestrictionsLPr(userId); 11778 installed = true; 11779 } 11780 } 11781 11782 if (installed) { 11783 if (pkgSetting.pkg != null) { 11784 synchronized (mInstallLock) { 11785 // We don't need to freeze for a brand new install 11786 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11787 } 11788 } 11789 sendPackageAddedForUser(packageName, pkgSetting, userId); 11790 } 11791 } finally { 11792 Binder.restoreCallingIdentity(callingId); 11793 } 11794 11795 return PackageManager.INSTALL_SUCCEEDED; 11796 } 11797 11798 boolean isUserRestricted(int userId, String restrictionKey) { 11799 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11800 if (restrictions.getBoolean(restrictionKey, false)) { 11801 Log.w(TAG, "User is restricted: " + restrictionKey); 11802 return true; 11803 } 11804 return false; 11805 } 11806 11807 @Override 11808 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11809 int userId) { 11810 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11811 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11812 true /* requireFullPermission */, true /* checkShell */, 11813 "setPackagesSuspended for user " + userId); 11814 11815 if (ArrayUtils.isEmpty(packageNames)) { 11816 return packageNames; 11817 } 11818 11819 // List of package names for whom the suspended state has changed. 11820 List<String> changedPackages = new ArrayList<>(packageNames.length); 11821 // List of package names for whom the suspended state is not set as requested in this 11822 // method. 11823 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11824 long callingId = Binder.clearCallingIdentity(); 11825 try { 11826 for (int i = 0; i < packageNames.length; i++) { 11827 String packageName = packageNames[i]; 11828 boolean changed = false; 11829 final int appId; 11830 synchronized (mPackages) { 11831 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11832 if (pkgSetting == null) { 11833 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11834 + "\". Skipping suspending/un-suspending."); 11835 unactionedPackages.add(packageName); 11836 continue; 11837 } 11838 appId = pkgSetting.appId; 11839 if (pkgSetting.getSuspended(userId) != suspended) { 11840 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11841 unactionedPackages.add(packageName); 11842 continue; 11843 } 11844 pkgSetting.setSuspended(suspended, userId); 11845 mSettings.writePackageRestrictionsLPr(userId); 11846 changed = true; 11847 changedPackages.add(packageName); 11848 } 11849 } 11850 11851 if (changed && suspended) { 11852 killApplication(packageName, UserHandle.getUid(userId, appId), 11853 "suspending package"); 11854 } 11855 } 11856 } finally { 11857 Binder.restoreCallingIdentity(callingId); 11858 } 11859 11860 if (!changedPackages.isEmpty()) { 11861 sendPackagesSuspendedForUser(changedPackages.toArray( 11862 new String[changedPackages.size()]), userId, suspended); 11863 } 11864 11865 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11866 } 11867 11868 @Override 11869 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11870 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11871 true /* requireFullPermission */, false /* checkShell */, 11872 "isPackageSuspendedForUser for user " + userId); 11873 synchronized (mPackages) { 11874 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11875 if (pkgSetting == null) { 11876 throw new IllegalArgumentException("Unknown target package: " + packageName); 11877 } 11878 return pkgSetting.getSuspended(userId); 11879 } 11880 } 11881 11882 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11883 if (isPackageDeviceAdmin(packageName, userId)) { 11884 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11885 + "\": has an active device admin"); 11886 return false; 11887 } 11888 11889 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11890 if (packageName.equals(activeLauncherPackageName)) { 11891 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11892 + "\": contains the active launcher"); 11893 return false; 11894 } 11895 11896 if (packageName.equals(mRequiredInstallerPackage)) { 11897 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11898 + "\": required for package installation"); 11899 return false; 11900 } 11901 11902 if (packageName.equals(mRequiredVerifierPackage)) { 11903 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11904 + "\": required for package verification"); 11905 return false; 11906 } 11907 11908 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11909 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11910 + "\": is the default dialer"); 11911 return false; 11912 } 11913 11914 return true; 11915 } 11916 11917 private String getActiveLauncherPackageName(int userId) { 11918 Intent intent = new Intent(Intent.ACTION_MAIN); 11919 intent.addCategory(Intent.CATEGORY_HOME); 11920 ResolveInfo resolveInfo = resolveIntent( 11921 intent, 11922 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11923 PackageManager.MATCH_DEFAULT_ONLY, 11924 userId); 11925 11926 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11927 } 11928 11929 private String getDefaultDialerPackageName(int userId) { 11930 synchronized (mPackages) { 11931 return mSettings.getDefaultDialerPackageNameLPw(userId); 11932 } 11933 } 11934 11935 @Override 11936 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11937 mContext.enforceCallingOrSelfPermission( 11938 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11939 "Only package verification agents can verify applications"); 11940 11941 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11942 final PackageVerificationResponse response = new PackageVerificationResponse( 11943 verificationCode, Binder.getCallingUid()); 11944 msg.arg1 = id; 11945 msg.obj = response; 11946 mHandler.sendMessage(msg); 11947 } 11948 11949 @Override 11950 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11951 long millisecondsToDelay) { 11952 mContext.enforceCallingOrSelfPermission( 11953 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11954 "Only package verification agents can extend verification timeouts"); 11955 11956 final PackageVerificationState state = mPendingVerification.get(id); 11957 final PackageVerificationResponse response = new PackageVerificationResponse( 11958 verificationCodeAtTimeout, Binder.getCallingUid()); 11959 11960 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11961 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11962 } 11963 if (millisecondsToDelay < 0) { 11964 millisecondsToDelay = 0; 11965 } 11966 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11967 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11968 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11969 } 11970 11971 if ((state != null) && !state.timeoutExtended()) { 11972 state.extendTimeout(); 11973 11974 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11975 msg.arg1 = id; 11976 msg.obj = response; 11977 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11978 } 11979 } 11980 11981 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11982 int verificationCode, UserHandle user) { 11983 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11984 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11985 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11986 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11987 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11988 11989 mContext.sendBroadcastAsUser(intent, user, 11990 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11991 } 11992 11993 private ComponentName matchComponentForVerifier(String packageName, 11994 List<ResolveInfo> receivers) { 11995 ActivityInfo targetReceiver = null; 11996 11997 final int NR = receivers.size(); 11998 for (int i = 0; i < NR; i++) { 11999 final ResolveInfo info = receivers.get(i); 12000 if (info.activityInfo == null) { 12001 continue; 12002 } 12003 12004 if (packageName.equals(info.activityInfo.packageName)) { 12005 targetReceiver = info.activityInfo; 12006 break; 12007 } 12008 } 12009 12010 if (targetReceiver == null) { 12011 return null; 12012 } 12013 12014 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 12015 } 12016 12017 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 12018 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 12019 if (pkgInfo.verifiers.length == 0) { 12020 return null; 12021 } 12022 12023 final int N = pkgInfo.verifiers.length; 12024 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 12025 for (int i = 0; i < N; i++) { 12026 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 12027 12028 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 12029 receivers); 12030 if (comp == null) { 12031 continue; 12032 } 12033 12034 final int verifierUid = getUidForVerifier(verifierInfo); 12035 if (verifierUid == -1) { 12036 continue; 12037 } 12038 12039 if (DEBUG_VERIFY) { 12040 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12041 + " with the correct signature"); 12042 } 12043 sufficientVerifiers.add(comp); 12044 verificationState.addSufficientVerifier(verifierUid); 12045 } 12046 12047 return sufficientVerifiers; 12048 } 12049 12050 private int getUidForVerifier(VerifierInfo verifierInfo) { 12051 synchronized (mPackages) { 12052 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12053 if (pkg == null) { 12054 return -1; 12055 } else if (pkg.mSignatures.length != 1) { 12056 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12057 + " has more than one signature; ignoring"); 12058 return -1; 12059 } 12060 12061 /* 12062 * If the public key of the package's signature does not match 12063 * our expected public key, then this is a different package and 12064 * we should skip. 12065 */ 12066 12067 final byte[] expectedPublicKey; 12068 try { 12069 final Signature verifierSig = pkg.mSignatures[0]; 12070 final PublicKey publicKey = verifierSig.getPublicKey(); 12071 expectedPublicKey = publicKey.getEncoded(); 12072 } catch (CertificateException e) { 12073 return -1; 12074 } 12075 12076 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12077 12078 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12079 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12080 + " does not have the expected public key; ignoring"); 12081 return -1; 12082 } 12083 12084 return pkg.applicationInfo.uid; 12085 } 12086 } 12087 12088 @Override 12089 public void finishPackageInstall(int token, boolean didLaunch) { 12090 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12091 12092 if (DEBUG_INSTALL) { 12093 Slog.v(TAG, "BM finishing package install for " + token); 12094 } 12095 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12096 12097 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12098 mHandler.sendMessage(msg); 12099 } 12100 12101 /** 12102 * Get the verification agent timeout. 12103 * 12104 * @return verification timeout in milliseconds 12105 */ 12106 private long getVerificationTimeout() { 12107 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12108 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12109 DEFAULT_VERIFICATION_TIMEOUT); 12110 } 12111 12112 /** 12113 * Get the default verification agent response code. 12114 * 12115 * @return default verification response code 12116 */ 12117 private int getDefaultVerificationResponse() { 12118 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12119 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12120 DEFAULT_VERIFICATION_RESPONSE); 12121 } 12122 12123 /** 12124 * Check whether or not package verification has been enabled. 12125 * 12126 * @return true if verification should be performed 12127 */ 12128 private boolean isVerificationEnabled(int userId, int installFlags) { 12129 if (!DEFAULT_VERIFY_ENABLE) { 12130 return false; 12131 } 12132 // Ephemeral apps don't get the full verification treatment 12133 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12134 if (DEBUG_EPHEMERAL) { 12135 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12136 } 12137 return false; 12138 } 12139 12140 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12141 12142 // Check if installing from ADB 12143 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12144 // Do not run verification in a test harness environment 12145 if (ActivityManager.isRunningInTestHarness()) { 12146 return false; 12147 } 12148 if (ensureVerifyAppsEnabled) { 12149 return true; 12150 } 12151 // Check if the developer does not want package verification for ADB installs 12152 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12153 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12154 return false; 12155 } 12156 } 12157 12158 if (ensureVerifyAppsEnabled) { 12159 return true; 12160 } 12161 12162 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12163 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12164 } 12165 12166 @Override 12167 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12168 throws RemoteException { 12169 mContext.enforceCallingOrSelfPermission( 12170 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12171 "Only intentfilter verification agents can verify applications"); 12172 12173 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12174 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12175 Binder.getCallingUid(), verificationCode, failedDomains); 12176 msg.arg1 = id; 12177 msg.obj = response; 12178 mHandler.sendMessage(msg); 12179 } 12180 12181 @Override 12182 public int getIntentVerificationStatus(String packageName, int userId) { 12183 synchronized (mPackages) { 12184 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12185 } 12186 } 12187 12188 @Override 12189 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12190 mContext.enforceCallingOrSelfPermission( 12191 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12192 12193 boolean result = false; 12194 synchronized (mPackages) { 12195 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12196 } 12197 if (result) { 12198 scheduleWritePackageRestrictionsLocked(userId); 12199 } 12200 return result; 12201 } 12202 12203 @Override 12204 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12205 String packageName) { 12206 synchronized (mPackages) { 12207 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12208 } 12209 } 12210 12211 @Override 12212 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12213 if (TextUtils.isEmpty(packageName)) { 12214 return ParceledListSlice.emptyList(); 12215 } 12216 synchronized (mPackages) { 12217 PackageParser.Package pkg = mPackages.get(packageName); 12218 if (pkg == null || pkg.activities == null) { 12219 return ParceledListSlice.emptyList(); 12220 } 12221 final int count = pkg.activities.size(); 12222 ArrayList<IntentFilter> result = new ArrayList<>(); 12223 for (int n=0; n<count; n++) { 12224 PackageParser.Activity activity = pkg.activities.get(n); 12225 if (activity.intents != null && activity.intents.size() > 0) { 12226 result.addAll(activity.intents); 12227 } 12228 } 12229 return new ParceledListSlice<>(result); 12230 } 12231 } 12232 12233 @Override 12234 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12235 mContext.enforceCallingOrSelfPermission( 12236 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12237 12238 synchronized (mPackages) { 12239 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12240 if (packageName != null) { 12241 result |= updateIntentVerificationStatus(packageName, 12242 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12243 userId); 12244 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12245 packageName, userId); 12246 } 12247 return result; 12248 } 12249 } 12250 12251 @Override 12252 public String getDefaultBrowserPackageName(int userId) { 12253 synchronized (mPackages) { 12254 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12255 } 12256 } 12257 12258 /** 12259 * Get the "allow unknown sources" setting. 12260 * 12261 * @return the current "allow unknown sources" setting 12262 */ 12263 private int getUnknownSourcesSettings() { 12264 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12265 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12266 -1); 12267 } 12268 12269 @Override 12270 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12271 final int uid = Binder.getCallingUid(); 12272 // writer 12273 synchronized (mPackages) { 12274 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12275 if (targetPackageSetting == null) { 12276 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12277 } 12278 12279 PackageSetting installerPackageSetting; 12280 if (installerPackageName != null) { 12281 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12282 if (installerPackageSetting == null) { 12283 throw new IllegalArgumentException("Unknown installer package: " 12284 + installerPackageName); 12285 } 12286 } else { 12287 installerPackageSetting = null; 12288 } 12289 12290 Signature[] callerSignature; 12291 Object obj = mSettings.getUserIdLPr(uid); 12292 if (obj != null) { 12293 if (obj instanceof SharedUserSetting) { 12294 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12295 } else if (obj instanceof PackageSetting) { 12296 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12297 } else { 12298 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12299 } 12300 } else { 12301 throw new SecurityException("Unknown calling UID: " + uid); 12302 } 12303 12304 // Verify: can't set installerPackageName to a package that is 12305 // not signed with the same cert as the caller. 12306 if (installerPackageSetting != null) { 12307 if (compareSignatures(callerSignature, 12308 installerPackageSetting.signatures.mSignatures) 12309 != PackageManager.SIGNATURE_MATCH) { 12310 throw new SecurityException( 12311 "Caller does not have same cert as new installer package " 12312 + installerPackageName); 12313 } 12314 } 12315 12316 // Verify: if target already has an installer package, it must 12317 // be signed with the same cert as the caller. 12318 if (targetPackageSetting.installerPackageName != null) { 12319 PackageSetting setting = mSettings.mPackages.get( 12320 targetPackageSetting.installerPackageName); 12321 // If the currently set package isn't valid, then it's always 12322 // okay to change it. 12323 if (setting != null) { 12324 if (compareSignatures(callerSignature, 12325 setting.signatures.mSignatures) 12326 != PackageManager.SIGNATURE_MATCH) { 12327 throw new SecurityException( 12328 "Caller does not have same cert as old installer package " 12329 + targetPackageSetting.installerPackageName); 12330 } 12331 } 12332 } 12333 12334 // Okay! 12335 targetPackageSetting.installerPackageName = installerPackageName; 12336 if (installerPackageName != null) { 12337 mSettings.mInstallerPackages.add(installerPackageName); 12338 } 12339 scheduleWriteSettingsLocked(); 12340 } 12341 } 12342 12343 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12344 // Queue up an async operation since the package installation may take a little while. 12345 mHandler.post(new Runnable() { 12346 public void run() { 12347 mHandler.removeCallbacks(this); 12348 // Result object to be returned 12349 PackageInstalledInfo res = new PackageInstalledInfo(); 12350 res.setReturnCode(currentStatus); 12351 res.uid = -1; 12352 res.pkg = null; 12353 res.removedInfo = null; 12354 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12355 args.doPreInstall(res.returnCode); 12356 synchronized (mInstallLock) { 12357 installPackageTracedLI(args, res); 12358 } 12359 args.doPostInstall(res.returnCode, res.uid); 12360 } 12361 12362 // A restore should be performed at this point if (a) the install 12363 // succeeded, (b) the operation is not an update, and (c) the new 12364 // package has not opted out of backup participation. 12365 final boolean update = res.removedInfo != null 12366 && res.removedInfo.removedPackage != null; 12367 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12368 boolean doRestore = !update 12369 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12370 12371 // Set up the post-install work request bookkeeping. This will be used 12372 // and cleaned up by the post-install event handling regardless of whether 12373 // there's a restore pass performed. Token values are >= 1. 12374 int token; 12375 if (mNextInstallToken < 0) mNextInstallToken = 1; 12376 token = mNextInstallToken++; 12377 12378 PostInstallData data = new PostInstallData(args, res); 12379 mRunningInstalls.put(token, data); 12380 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12381 12382 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12383 // Pass responsibility to the Backup Manager. It will perform a 12384 // restore if appropriate, then pass responsibility back to the 12385 // Package Manager to run the post-install observer callbacks 12386 // and broadcasts. 12387 IBackupManager bm = IBackupManager.Stub.asInterface( 12388 ServiceManager.getService(Context.BACKUP_SERVICE)); 12389 if (bm != null) { 12390 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12391 + " to BM for possible restore"); 12392 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12393 try { 12394 // TODO: http://b/22388012 12395 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12396 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12397 } else { 12398 doRestore = false; 12399 } 12400 } catch (RemoteException e) { 12401 // can't happen; the backup manager is local 12402 } catch (Exception e) { 12403 Slog.e(TAG, "Exception trying to enqueue restore", e); 12404 doRestore = false; 12405 } 12406 } else { 12407 Slog.e(TAG, "Backup Manager not found!"); 12408 doRestore = false; 12409 } 12410 } 12411 12412 if (!doRestore) { 12413 // No restore possible, or the Backup Manager was mysteriously not 12414 // available -- just fire the post-install work request directly. 12415 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12416 12417 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12418 12419 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12420 mHandler.sendMessage(msg); 12421 } 12422 } 12423 }); 12424 } 12425 12426 /** 12427 * Callback from PackageSettings whenever an app is first transitioned out of the 12428 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12429 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12430 * here whether the app is the target of an ongoing install, and only send the 12431 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12432 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12433 * handling. 12434 */ 12435 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12436 // Serialize this with the rest of the install-process message chain. In the 12437 // restore-at-install case, this Runnable will necessarily run before the 12438 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12439 // are coherent. In the non-restore case, the app has already completed install 12440 // and been launched through some other means, so it is not in a problematic 12441 // state for observers to see the FIRST_LAUNCH signal. 12442 mHandler.post(new Runnable() { 12443 @Override 12444 public void run() { 12445 for (int i = 0; i < mRunningInstalls.size(); i++) { 12446 final PostInstallData data = mRunningInstalls.valueAt(i); 12447 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12448 // right package; but is it for the right user? 12449 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12450 if (userId == data.res.newUsers[uIndex]) { 12451 if (DEBUG_BACKUP) { 12452 Slog.i(TAG, "Package " + pkgName 12453 + " being restored so deferring FIRST_LAUNCH"); 12454 } 12455 return; 12456 } 12457 } 12458 } 12459 } 12460 // didn't find it, so not being restored 12461 if (DEBUG_BACKUP) { 12462 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12463 } 12464 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12465 } 12466 }); 12467 } 12468 12469 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12470 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12471 installerPkg, null, userIds); 12472 } 12473 12474 private abstract class HandlerParams { 12475 private static final int MAX_RETRIES = 4; 12476 12477 /** 12478 * Number of times startCopy() has been attempted and had a non-fatal 12479 * error. 12480 */ 12481 private int mRetries = 0; 12482 12483 /** User handle for the user requesting the information or installation. */ 12484 private final UserHandle mUser; 12485 String traceMethod; 12486 int traceCookie; 12487 12488 HandlerParams(UserHandle user) { 12489 mUser = user; 12490 } 12491 12492 UserHandle getUser() { 12493 return mUser; 12494 } 12495 12496 HandlerParams setTraceMethod(String traceMethod) { 12497 this.traceMethod = traceMethod; 12498 return this; 12499 } 12500 12501 HandlerParams setTraceCookie(int traceCookie) { 12502 this.traceCookie = traceCookie; 12503 return this; 12504 } 12505 12506 final boolean startCopy() { 12507 boolean res; 12508 try { 12509 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12510 12511 if (++mRetries > MAX_RETRIES) { 12512 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12513 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12514 handleServiceError(); 12515 return false; 12516 } else { 12517 handleStartCopy(); 12518 res = true; 12519 } 12520 } catch (RemoteException e) { 12521 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12522 mHandler.sendEmptyMessage(MCS_RECONNECT); 12523 res = false; 12524 } 12525 handleReturnCode(); 12526 return res; 12527 } 12528 12529 final void serviceError() { 12530 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12531 handleServiceError(); 12532 handleReturnCode(); 12533 } 12534 12535 abstract void handleStartCopy() throws RemoteException; 12536 abstract void handleServiceError(); 12537 abstract void handleReturnCode(); 12538 } 12539 12540 class MeasureParams extends HandlerParams { 12541 private final PackageStats mStats; 12542 private boolean mSuccess; 12543 12544 private final IPackageStatsObserver mObserver; 12545 12546 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12547 super(new UserHandle(stats.userHandle)); 12548 mObserver = observer; 12549 mStats = stats; 12550 } 12551 12552 @Override 12553 public String toString() { 12554 return "MeasureParams{" 12555 + Integer.toHexString(System.identityHashCode(this)) 12556 + " " + mStats.packageName + "}"; 12557 } 12558 12559 @Override 12560 void handleStartCopy() throws RemoteException { 12561 synchronized (mInstallLock) { 12562 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12563 } 12564 12565 if (mSuccess) { 12566 final boolean mounted; 12567 if (Environment.isExternalStorageEmulated()) { 12568 mounted = true; 12569 } else { 12570 final String status = Environment.getExternalStorageState(); 12571 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12572 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12573 } 12574 12575 if (mounted) { 12576 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12577 12578 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12579 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12580 12581 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12582 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12583 12584 // Always subtract cache size, since it's a subdirectory 12585 mStats.externalDataSize -= mStats.externalCacheSize; 12586 12587 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12588 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12589 12590 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12591 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12592 } 12593 } 12594 } 12595 12596 @Override 12597 void handleReturnCode() { 12598 if (mObserver != null) { 12599 try { 12600 mObserver.onGetStatsCompleted(mStats, mSuccess); 12601 } catch (RemoteException e) { 12602 Slog.i(TAG, "Observer no longer exists."); 12603 } 12604 } 12605 } 12606 12607 @Override 12608 void handleServiceError() { 12609 Slog.e(TAG, "Could not measure application " + mStats.packageName 12610 + " external storage"); 12611 } 12612 } 12613 12614 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12615 throws RemoteException { 12616 long result = 0; 12617 for (File path : paths) { 12618 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12619 } 12620 return result; 12621 } 12622 12623 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12624 for (File path : paths) { 12625 try { 12626 mcs.clearDirectory(path.getAbsolutePath()); 12627 } catch (RemoteException e) { 12628 } 12629 } 12630 } 12631 12632 static class OriginInfo { 12633 /** 12634 * Location where install is coming from, before it has been 12635 * copied/renamed into place. This could be a single monolithic APK 12636 * file, or a cluster directory. This location may be untrusted. 12637 */ 12638 final File file; 12639 final String cid; 12640 12641 /** 12642 * Flag indicating that {@link #file} or {@link #cid} has already been 12643 * staged, meaning downstream users don't need to defensively copy the 12644 * contents. 12645 */ 12646 final boolean staged; 12647 12648 /** 12649 * Flag indicating that {@link #file} or {@link #cid} is an already 12650 * installed app that is being moved. 12651 */ 12652 final boolean existing; 12653 12654 final String resolvedPath; 12655 final File resolvedFile; 12656 12657 static OriginInfo fromNothing() { 12658 return new OriginInfo(null, null, false, false); 12659 } 12660 12661 static OriginInfo fromUntrustedFile(File file) { 12662 return new OriginInfo(file, null, false, false); 12663 } 12664 12665 static OriginInfo fromExistingFile(File file) { 12666 return new OriginInfo(file, null, false, true); 12667 } 12668 12669 static OriginInfo fromStagedFile(File file) { 12670 return new OriginInfo(file, null, true, false); 12671 } 12672 12673 static OriginInfo fromStagedContainer(String cid) { 12674 return new OriginInfo(null, cid, true, false); 12675 } 12676 12677 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12678 this.file = file; 12679 this.cid = cid; 12680 this.staged = staged; 12681 this.existing = existing; 12682 12683 if (cid != null) { 12684 resolvedPath = PackageHelper.getSdDir(cid); 12685 resolvedFile = new File(resolvedPath); 12686 } else if (file != null) { 12687 resolvedPath = file.getAbsolutePath(); 12688 resolvedFile = file; 12689 } else { 12690 resolvedPath = null; 12691 resolvedFile = null; 12692 } 12693 } 12694 } 12695 12696 static class MoveInfo { 12697 final int moveId; 12698 final String fromUuid; 12699 final String toUuid; 12700 final String packageName; 12701 final String dataAppName; 12702 final int appId; 12703 final String seinfo; 12704 final int targetSdkVersion; 12705 12706 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12707 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12708 this.moveId = moveId; 12709 this.fromUuid = fromUuid; 12710 this.toUuid = toUuid; 12711 this.packageName = packageName; 12712 this.dataAppName = dataAppName; 12713 this.appId = appId; 12714 this.seinfo = seinfo; 12715 this.targetSdkVersion = targetSdkVersion; 12716 } 12717 } 12718 12719 static class VerificationInfo { 12720 /** A constant used to indicate that a uid value is not present. */ 12721 public static final int NO_UID = -1; 12722 12723 /** URI referencing where the package was downloaded from. */ 12724 final Uri originatingUri; 12725 12726 /** HTTP referrer URI associated with the originatingURI. */ 12727 final Uri referrer; 12728 12729 /** UID of the application that the install request originated from. */ 12730 final int originatingUid; 12731 12732 /** UID of application requesting the install */ 12733 final int installerUid; 12734 12735 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12736 this.originatingUri = originatingUri; 12737 this.referrer = referrer; 12738 this.originatingUid = originatingUid; 12739 this.installerUid = installerUid; 12740 } 12741 } 12742 12743 class InstallParams extends HandlerParams { 12744 final OriginInfo origin; 12745 final MoveInfo move; 12746 final IPackageInstallObserver2 observer; 12747 int installFlags; 12748 final String installerPackageName; 12749 final String volumeUuid; 12750 private InstallArgs mArgs; 12751 private int mRet; 12752 final String packageAbiOverride; 12753 final String[] grantedRuntimePermissions; 12754 final VerificationInfo verificationInfo; 12755 final Certificate[][] certificates; 12756 12757 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12758 int installFlags, String installerPackageName, String volumeUuid, 12759 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12760 String[] grantedPermissions, Certificate[][] certificates) { 12761 super(user); 12762 this.origin = origin; 12763 this.move = move; 12764 this.observer = observer; 12765 this.installFlags = installFlags; 12766 this.installerPackageName = installerPackageName; 12767 this.volumeUuid = volumeUuid; 12768 this.verificationInfo = verificationInfo; 12769 this.packageAbiOverride = packageAbiOverride; 12770 this.grantedRuntimePermissions = grantedPermissions; 12771 this.certificates = certificates; 12772 } 12773 12774 @Override 12775 public String toString() { 12776 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12777 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12778 } 12779 12780 private int installLocationPolicy(PackageInfoLite pkgLite) { 12781 String packageName = pkgLite.packageName; 12782 int installLocation = pkgLite.installLocation; 12783 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12784 // reader 12785 synchronized (mPackages) { 12786 // Currently installed package which the new package is attempting to replace or 12787 // null if no such package is installed. 12788 PackageParser.Package installedPkg = mPackages.get(packageName); 12789 // Package which currently owns the data which the new package will own if installed. 12790 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12791 // will be null whereas dataOwnerPkg will contain information about the package 12792 // which was uninstalled while keeping its data. 12793 PackageParser.Package dataOwnerPkg = installedPkg; 12794 if (dataOwnerPkg == null) { 12795 PackageSetting ps = mSettings.mPackages.get(packageName); 12796 if (ps != null) { 12797 dataOwnerPkg = ps.pkg; 12798 } 12799 } 12800 12801 if (dataOwnerPkg != null) { 12802 // If installed, the package will get access to data left on the device by its 12803 // predecessor. As a security measure, this is permited only if this is not a 12804 // version downgrade or if the predecessor package is marked as debuggable and 12805 // a downgrade is explicitly requested. 12806 // 12807 // On debuggable platform builds, downgrades are permitted even for 12808 // non-debuggable packages to make testing easier. Debuggable platform builds do 12809 // not offer security guarantees and thus it's OK to disable some security 12810 // mechanisms to make debugging/testing easier on those builds. However, even on 12811 // debuggable builds downgrades of packages are permitted only if requested via 12812 // installFlags. This is because we aim to keep the behavior of debuggable 12813 // platform builds as close as possible to the behavior of non-debuggable 12814 // platform builds. 12815 final boolean downgradeRequested = 12816 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12817 final boolean packageDebuggable = 12818 (dataOwnerPkg.applicationInfo.flags 12819 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12820 final boolean downgradePermitted = 12821 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12822 if (!downgradePermitted) { 12823 try { 12824 checkDowngrade(dataOwnerPkg, pkgLite); 12825 } catch (PackageManagerException e) { 12826 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12827 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12828 } 12829 } 12830 } 12831 12832 if (installedPkg != null) { 12833 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12834 // Check for updated system application. 12835 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12836 if (onSd) { 12837 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12838 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12839 } 12840 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12841 } else { 12842 if (onSd) { 12843 // Install flag overrides everything. 12844 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12845 } 12846 // If current upgrade specifies particular preference 12847 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12848 // Application explicitly specified internal. 12849 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12850 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12851 // App explictly prefers external. Let policy decide 12852 } else { 12853 // Prefer previous location 12854 if (isExternal(installedPkg)) { 12855 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12856 } 12857 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12858 } 12859 } 12860 } else { 12861 // Invalid install. Return error code 12862 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12863 } 12864 } 12865 } 12866 // All the special cases have been taken care of. 12867 // Return result based on recommended install location. 12868 if (onSd) { 12869 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12870 } 12871 return pkgLite.recommendedInstallLocation; 12872 } 12873 12874 /* 12875 * Invoke remote method to get package information and install 12876 * location values. Override install location based on default 12877 * policy if needed and then create install arguments based 12878 * on the install location. 12879 */ 12880 public void handleStartCopy() throws RemoteException { 12881 int ret = PackageManager.INSTALL_SUCCEEDED; 12882 12883 // If we're already staged, we've firmly committed to an install location 12884 if (origin.staged) { 12885 if (origin.file != null) { 12886 installFlags |= PackageManager.INSTALL_INTERNAL; 12887 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12888 } else if (origin.cid != null) { 12889 installFlags |= PackageManager.INSTALL_EXTERNAL; 12890 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12891 } else { 12892 throw new IllegalStateException("Invalid stage location"); 12893 } 12894 } 12895 12896 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12897 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12898 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12899 PackageInfoLite pkgLite = null; 12900 12901 if (onInt && onSd) { 12902 // Check if both bits are set. 12903 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12904 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12905 } else if (onSd && ephemeral) { 12906 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12907 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12908 } else { 12909 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12910 packageAbiOverride); 12911 12912 if (DEBUG_EPHEMERAL && ephemeral) { 12913 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12914 } 12915 12916 /* 12917 * If we have too little free space, try to free cache 12918 * before giving up. 12919 */ 12920 if (!origin.staged && pkgLite.recommendedInstallLocation 12921 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12922 // TODO: focus freeing disk space on the target device 12923 final StorageManager storage = StorageManager.from(mContext); 12924 final long lowThreshold = storage.getStorageLowBytes( 12925 Environment.getDataDirectory()); 12926 12927 final long sizeBytes = mContainerService.calculateInstalledSize( 12928 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12929 12930 try { 12931 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12932 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12933 installFlags, packageAbiOverride); 12934 } catch (InstallerException e) { 12935 Slog.w(TAG, "Failed to free cache", e); 12936 } 12937 12938 /* 12939 * The cache free must have deleted the file we 12940 * downloaded to install. 12941 * 12942 * TODO: fix the "freeCache" call to not delete 12943 * the file we care about. 12944 */ 12945 if (pkgLite.recommendedInstallLocation 12946 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12947 pkgLite.recommendedInstallLocation 12948 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12949 } 12950 } 12951 } 12952 12953 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12954 int loc = pkgLite.recommendedInstallLocation; 12955 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12956 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12957 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12958 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12959 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12960 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12961 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12962 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12963 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12964 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12965 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12966 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12967 } else { 12968 // Override with defaults if needed. 12969 loc = installLocationPolicy(pkgLite); 12970 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12971 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12972 } else if (!onSd && !onInt) { 12973 // Override install location with flags 12974 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12975 // Set the flag to install on external media. 12976 installFlags |= PackageManager.INSTALL_EXTERNAL; 12977 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12978 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12979 if (DEBUG_EPHEMERAL) { 12980 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12981 } 12982 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12983 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12984 |PackageManager.INSTALL_INTERNAL); 12985 } else { 12986 // Make sure the flag for installing on external 12987 // media is unset 12988 installFlags |= PackageManager.INSTALL_INTERNAL; 12989 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12990 } 12991 } 12992 } 12993 } 12994 12995 final InstallArgs args = createInstallArgs(this); 12996 mArgs = args; 12997 12998 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12999 // TODO: http://b/22976637 13000 // Apps installed for "all" users use the device owner to verify the app 13001 UserHandle verifierUser = getUser(); 13002 if (verifierUser == UserHandle.ALL) { 13003 verifierUser = UserHandle.SYSTEM; 13004 } 13005 13006 /* 13007 * Determine if we have any installed package verifiers. If we 13008 * do, then we'll defer to them to verify the packages. 13009 */ 13010 final int requiredUid = mRequiredVerifierPackage == null ? -1 13011 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 13012 verifierUser.getIdentifier()); 13013 if (!origin.existing && requiredUid != -1 13014 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 13015 final Intent verification = new Intent( 13016 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 13017 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 13018 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 13019 PACKAGE_MIME_TYPE); 13020 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 13021 13022 // Query all live verifiers based on current user state 13023 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 13024 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 13025 13026 if (DEBUG_VERIFY) { 13027 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 13028 + verification.toString() + " with " + pkgLite.verifiers.length 13029 + " optional verifiers"); 13030 } 13031 13032 final int verificationId = mPendingVerificationToken++; 13033 13034 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13035 13036 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13037 installerPackageName); 13038 13039 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13040 installFlags); 13041 13042 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13043 pkgLite.packageName); 13044 13045 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13046 pkgLite.versionCode); 13047 13048 if (verificationInfo != null) { 13049 if (verificationInfo.originatingUri != null) { 13050 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13051 verificationInfo.originatingUri); 13052 } 13053 if (verificationInfo.referrer != null) { 13054 verification.putExtra(Intent.EXTRA_REFERRER, 13055 verificationInfo.referrer); 13056 } 13057 if (verificationInfo.originatingUid >= 0) { 13058 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13059 verificationInfo.originatingUid); 13060 } 13061 if (verificationInfo.installerUid >= 0) { 13062 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13063 verificationInfo.installerUid); 13064 } 13065 } 13066 13067 final PackageVerificationState verificationState = new PackageVerificationState( 13068 requiredUid, args); 13069 13070 mPendingVerification.append(verificationId, verificationState); 13071 13072 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13073 receivers, verificationState); 13074 13075 /* 13076 * If any sufficient verifiers were listed in the package 13077 * manifest, attempt to ask them. 13078 */ 13079 if (sufficientVerifiers != null) { 13080 final int N = sufficientVerifiers.size(); 13081 if (N == 0) { 13082 Slog.i(TAG, "Additional verifiers required, but none installed."); 13083 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13084 } else { 13085 for (int i = 0; i < N; i++) { 13086 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13087 13088 final Intent sufficientIntent = new Intent(verification); 13089 sufficientIntent.setComponent(verifierComponent); 13090 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13091 } 13092 } 13093 } 13094 13095 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13096 mRequiredVerifierPackage, receivers); 13097 if (ret == PackageManager.INSTALL_SUCCEEDED 13098 && mRequiredVerifierPackage != null) { 13099 Trace.asyncTraceBegin( 13100 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13101 /* 13102 * Send the intent to the required verification agent, 13103 * but only start the verification timeout after the 13104 * target BroadcastReceivers have run. 13105 */ 13106 verification.setComponent(requiredVerifierComponent); 13107 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13108 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13109 new BroadcastReceiver() { 13110 @Override 13111 public void onReceive(Context context, Intent intent) { 13112 final Message msg = mHandler 13113 .obtainMessage(CHECK_PENDING_VERIFICATION); 13114 msg.arg1 = verificationId; 13115 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13116 } 13117 }, null, 0, null, null); 13118 13119 /* 13120 * We don't want the copy to proceed until verification 13121 * succeeds, so null out this field. 13122 */ 13123 mArgs = null; 13124 } 13125 } else { 13126 /* 13127 * No package verification is enabled, so immediately start 13128 * the remote call to initiate copy using temporary file. 13129 */ 13130 ret = args.copyApk(mContainerService, true); 13131 } 13132 } 13133 13134 mRet = ret; 13135 } 13136 13137 @Override 13138 void handleReturnCode() { 13139 // If mArgs is null, then MCS couldn't be reached. When it 13140 // reconnects, it will try again to install. At that point, this 13141 // will succeed. 13142 if (mArgs != null) { 13143 processPendingInstall(mArgs, mRet); 13144 } 13145 } 13146 13147 @Override 13148 void handleServiceError() { 13149 mArgs = createInstallArgs(this); 13150 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13151 } 13152 13153 public boolean isForwardLocked() { 13154 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13155 } 13156 } 13157 13158 /** 13159 * Used during creation of InstallArgs 13160 * 13161 * @param installFlags package installation flags 13162 * @return true if should be installed on external storage 13163 */ 13164 private static boolean installOnExternalAsec(int installFlags) { 13165 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13166 return false; 13167 } 13168 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13169 return true; 13170 } 13171 return false; 13172 } 13173 13174 /** 13175 * Used during creation of InstallArgs 13176 * 13177 * @param installFlags package installation flags 13178 * @return true if should be installed as forward locked 13179 */ 13180 private static boolean installForwardLocked(int installFlags) { 13181 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13182 } 13183 13184 private InstallArgs createInstallArgs(InstallParams params) { 13185 if (params.move != null) { 13186 return new MoveInstallArgs(params); 13187 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13188 return new AsecInstallArgs(params); 13189 } else { 13190 return new FileInstallArgs(params); 13191 } 13192 } 13193 13194 /** 13195 * Create args that describe an existing installed package. Typically used 13196 * when cleaning up old installs, or used as a move source. 13197 */ 13198 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13199 String resourcePath, String[] instructionSets) { 13200 final boolean isInAsec; 13201 if (installOnExternalAsec(installFlags)) { 13202 /* Apps on SD card are always in ASEC containers. */ 13203 isInAsec = true; 13204 } else if (installForwardLocked(installFlags) 13205 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13206 /* 13207 * Forward-locked apps are only in ASEC containers if they're the 13208 * new style 13209 */ 13210 isInAsec = true; 13211 } else { 13212 isInAsec = false; 13213 } 13214 13215 if (isInAsec) { 13216 return new AsecInstallArgs(codePath, instructionSets, 13217 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13218 } else { 13219 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13220 } 13221 } 13222 13223 static abstract class InstallArgs { 13224 /** @see InstallParams#origin */ 13225 final OriginInfo origin; 13226 /** @see InstallParams#move */ 13227 final MoveInfo move; 13228 13229 final IPackageInstallObserver2 observer; 13230 // Always refers to PackageManager flags only 13231 final int installFlags; 13232 final String installerPackageName; 13233 final String volumeUuid; 13234 final UserHandle user; 13235 final String abiOverride; 13236 final String[] installGrantPermissions; 13237 /** If non-null, drop an async trace when the install completes */ 13238 final String traceMethod; 13239 final int traceCookie; 13240 final Certificate[][] certificates; 13241 13242 // The list of instruction sets supported by this app. This is currently 13243 // only used during the rmdex() phase to clean up resources. We can get rid of this 13244 // if we move dex files under the common app path. 13245 /* nullable */ String[] instructionSets; 13246 13247 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13248 int installFlags, String installerPackageName, String volumeUuid, 13249 UserHandle user, String[] instructionSets, 13250 String abiOverride, String[] installGrantPermissions, 13251 String traceMethod, int traceCookie, Certificate[][] certificates) { 13252 this.origin = origin; 13253 this.move = move; 13254 this.installFlags = installFlags; 13255 this.observer = observer; 13256 this.installerPackageName = installerPackageName; 13257 this.volumeUuid = volumeUuid; 13258 this.user = user; 13259 this.instructionSets = instructionSets; 13260 this.abiOverride = abiOverride; 13261 this.installGrantPermissions = installGrantPermissions; 13262 this.traceMethod = traceMethod; 13263 this.traceCookie = traceCookie; 13264 this.certificates = certificates; 13265 } 13266 13267 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13268 abstract int doPreInstall(int status); 13269 13270 /** 13271 * Rename package into final resting place. All paths on the given 13272 * scanned package should be updated to reflect the rename. 13273 */ 13274 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13275 abstract int doPostInstall(int status, int uid); 13276 13277 /** @see PackageSettingBase#codePathString */ 13278 abstract String getCodePath(); 13279 /** @see PackageSettingBase#resourcePathString */ 13280 abstract String getResourcePath(); 13281 13282 // Need installer lock especially for dex file removal. 13283 abstract void cleanUpResourcesLI(); 13284 abstract boolean doPostDeleteLI(boolean delete); 13285 13286 /** 13287 * Called before the source arguments are copied. This is used mostly 13288 * for MoveParams when it needs to read the source file to put it in the 13289 * destination. 13290 */ 13291 int doPreCopy() { 13292 return PackageManager.INSTALL_SUCCEEDED; 13293 } 13294 13295 /** 13296 * Called after the source arguments are copied. This is used mostly for 13297 * MoveParams when it needs to read the source file to put it in the 13298 * destination. 13299 */ 13300 int doPostCopy(int uid) { 13301 return PackageManager.INSTALL_SUCCEEDED; 13302 } 13303 13304 protected boolean isFwdLocked() { 13305 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13306 } 13307 13308 protected boolean isExternalAsec() { 13309 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13310 } 13311 13312 protected boolean isEphemeral() { 13313 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13314 } 13315 13316 UserHandle getUser() { 13317 return user; 13318 } 13319 } 13320 13321 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13322 if (!allCodePaths.isEmpty()) { 13323 if (instructionSets == null) { 13324 throw new IllegalStateException("instructionSet == null"); 13325 } 13326 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13327 for (String codePath : allCodePaths) { 13328 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13329 try { 13330 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13331 } catch (InstallerException ignored) { 13332 } 13333 } 13334 } 13335 } 13336 } 13337 13338 /** 13339 * Logic to handle installation of non-ASEC applications, including copying 13340 * and renaming logic. 13341 */ 13342 class FileInstallArgs extends InstallArgs { 13343 private File codeFile; 13344 private File resourceFile; 13345 13346 // Example topology: 13347 // /data/app/com.example/base.apk 13348 // /data/app/com.example/split_foo.apk 13349 // /data/app/com.example/lib/arm/libfoo.so 13350 // /data/app/com.example/lib/arm64/libfoo.so 13351 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13352 13353 /** New install */ 13354 FileInstallArgs(InstallParams params) { 13355 super(params.origin, params.move, params.observer, params.installFlags, 13356 params.installerPackageName, params.volumeUuid, 13357 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13358 params.grantedRuntimePermissions, 13359 params.traceMethod, params.traceCookie, params.certificates); 13360 if (isFwdLocked()) { 13361 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13362 } 13363 } 13364 13365 /** Existing install */ 13366 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13367 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13368 null, null, null, 0, null /*certificates*/); 13369 this.codeFile = (codePath != null) ? new File(codePath) : null; 13370 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13371 } 13372 13373 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13375 try { 13376 return doCopyApk(imcs, temp); 13377 } finally { 13378 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13379 } 13380 } 13381 13382 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13383 if (origin.staged) { 13384 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13385 codeFile = origin.file; 13386 resourceFile = origin.file; 13387 return PackageManager.INSTALL_SUCCEEDED; 13388 } 13389 13390 try { 13391 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13392 final File tempDir = 13393 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13394 codeFile = tempDir; 13395 resourceFile = tempDir; 13396 } catch (IOException e) { 13397 Slog.w(TAG, "Failed to create copy file: " + e); 13398 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13399 } 13400 13401 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13402 @Override 13403 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13404 if (!FileUtils.isValidExtFilename(name)) { 13405 throw new IllegalArgumentException("Invalid filename: " + name); 13406 } 13407 try { 13408 final File file = new File(codeFile, name); 13409 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13410 O_RDWR | O_CREAT, 0644); 13411 Os.chmod(file.getAbsolutePath(), 0644); 13412 return new ParcelFileDescriptor(fd); 13413 } catch (ErrnoException e) { 13414 throw new RemoteException("Failed to open: " + e.getMessage()); 13415 } 13416 } 13417 }; 13418 13419 int ret = PackageManager.INSTALL_SUCCEEDED; 13420 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13421 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13422 Slog.e(TAG, "Failed to copy package"); 13423 return ret; 13424 } 13425 13426 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13427 NativeLibraryHelper.Handle handle = null; 13428 try { 13429 handle = NativeLibraryHelper.Handle.create(codeFile); 13430 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13431 abiOverride); 13432 } catch (IOException e) { 13433 Slog.e(TAG, "Copying native libraries failed", e); 13434 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13435 } finally { 13436 IoUtils.closeQuietly(handle); 13437 } 13438 13439 return ret; 13440 } 13441 13442 int doPreInstall(int status) { 13443 if (status != PackageManager.INSTALL_SUCCEEDED) { 13444 cleanUp(); 13445 } 13446 return status; 13447 } 13448 13449 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13450 if (status != PackageManager.INSTALL_SUCCEEDED) { 13451 cleanUp(); 13452 return false; 13453 } 13454 13455 final File targetDir = codeFile.getParentFile(); 13456 final File beforeCodeFile = codeFile; 13457 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13458 13459 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13460 try { 13461 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13462 } catch (ErrnoException e) { 13463 Slog.w(TAG, "Failed to rename", e); 13464 return false; 13465 } 13466 13467 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13468 Slog.w(TAG, "Failed to restorecon"); 13469 return false; 13470 } 13471 13472 // Reflect the rename internally 13473 codeFile = afterCodeFile; 13474 resourceFile = afterCodeFile; 13475 13476 // Reflect the rename in scanned details 13477 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13478 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13479 afterCodeFile, pkg.baseCodePath)); 13480 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13481 afterCodeFile, pkg.splitCodePaths)); 13482 13483 // Reflect the rename in app info 13484 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13485 pkg.setApplicationInfoCodePath(pkg.codePath); 13486 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13487 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13488 pkg.setApplicationInfoResourcePath(pkg.codePath); 13489 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13490 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13491 13492 return true; 13493 } 13494 13495 int doPostInstall(int status, int uid) { 13496 if (status != PackageManager.INSTALL_SUCCEEDED) { 13497 cleanUp(); 13498 } 13499 return status; 13500 } 13501 13502 @Override 13503 String getCodePath() { 13504 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13505 } 13506 13507 @Override 13508 String getResourcePath() { 13509 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13510 } 13511 13512 private boolean cleanUp() { 13513 if (codeFile == null || !codeFile.exists()) { 13514 return false; 13515 } 13516 13517 removeCodePathLI(codeFile); 13518 13519 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13520 resourceFile.delete(); 13521 } 13522 13523 return true; 13524 } 13525 13526 void cleanUpResourcesLI() { 13527 // Try enumerating all code paths before deleting 13528 List<String> allCodePaths = Collections.EMPTY_LIST; 13529 if (codeFile != null && codeFile.exists()) { 13530 try { 13531 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13532 allCodePaths = pkg.getAllCodePaths(); 13533 } catch (PackageParserException e) { 13534 // Ignored; we tried our best 13535 } 13536 } 13537 13538 cleanUp(); 13539 removeDexFiles(allCodePaths, instructionSets); 13540 } 13541 13542 boolean doPostDeleteLI(boolean delete) { 13543 // XXX err, shouldn't we respect the delete flag? 13544 cleanUpResourcesLI(); 13545 return true; 13546 } 13547 } 13548 13549 private boolean isAsecExternal(String cid) { 13550 final String asecPath = PackageHelper.getSdFilesystem(cid); 13551 return !asecPath.startsWith(mAsecInternalPath); 13552 } 13553 13554 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13555 PackageManagerException { 13556 if (copyRet < 0) { 13557 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13558 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13559 throw new PackageManagerException(copyRet, message); 13560 } 13561 } 13562 } 13563 13564 /** 13565 * Extract the MountService "container ID" from the full code path of an 13566 * .apk. 13567 */ 13568 static String cidFromCodePath(String fullCodePath) { 13569 int eidx = fullCodePath.lastIndexOf("/"); 13570 String subStr1 = fullCodePath.substring(0, eidx); 13571 int sidx = subStr1.lastIndexOf("/"); 13572 return subStr1.substring(sidx+1, eidx); 13573 } 13574 13575 /** 13576 * Logic to handle installation of ASEC applications, including copying and 13577 * renaming logic. 13578 */ 13579 class AsecInstallArgs extends InstallArgs { 13580 static final String RES_FILE_NAME = "pkg.apk"; 13581 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13582 13583 String cid; 13584 String packagePath; 13585 String resourcePath; 13586 13587 /** New install */ 13588 AsecInstallArgs(InstallParams params) { 13589 super(params.origin, params.move, params.observer, params.installFlags, 13590 params.installerPackageName, params.volumeUuid, 13591 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13592 params.grantedRuntimePermissions, 13593 params.traceMethod, params.traceCookie, params.certificates); 13594 } 13595 13596 /** Existing install */ 13597 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13598 boolean isExternal, boolean isForwardLocked) { 13599 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13600 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13601 instructionSets, null, null, null, 0, null /*certificates*/); 13602 // Hackily pretend we're still looking at a full code path 13603 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13604 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13605 } 13606 13607 // Extract cid from fullCodePath 13608 int eidx = fullCodePath.lastIndexOf("/"); 13609 String subStr1 = fullCodePath.substring(0, eidx); 13610 int sidx = subStr1.lastIndexOf("/"); 13611 cid = subStr1.substring(sidx+1, eidx); 13612 setMountPath(subStr1); 13613 } 13614 13615 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13616 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13617 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13618 instructionSets, null, null, null, 0, null /*certificates*/); 13619 this.cid = cid; 13620 setMountPath(PackageHelper.getSdDir(cid)); 13621 } 13622 13623 void createCopyFile() { 13624 cid = mInstallerService.allocateExternalStageCidLegacy(); 13625 } 13626 13627 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13628 if (origin.staged && origin.cid != null) { 13629 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13630 cid = origin.cid; 13631 setMountPath(PackageHelper.getSdDir(cid)); 13632 return PackageManager.INSTALL_SUCCEEDED; 13633 } 13634 13635 if (temp) { 13636 createCopyFile(); 13637 } else { 13638 /* 13639 * Pre-emptively destroy the container since it's destroyed if 13640 * copying fails due to it existing anyway. 13641 */ 13642 PackageHelper.destroySdDir(cid); 13643 } 13644 13645 final String newMountPath = imcs.copyPackageToContainer( 13646 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13647 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13648 13649 if (newMountPath != null) { 13650 setMountPath(newMountPath); 13651 return PackageManager.INSTALL_SUCCEEDED; 13652 } else { 13653 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13654 } 13655 } 13656 13657 @Override 13658 String getCodePath() { 13659 return packagePath; 13660 } 13661 13662 @Override 13663 String getResourcePath() { 13664 return resourcePath; 13665 } 13666 13667 int doPreInstall(int status) { 13668 if (status != PackageManager.INSTALL_SUCCEEDED) { 13669 // Destroy container 13670 PackageHelper.destroySdDir(cid); 13671 } else { 13672 boolean mounted = PackageHelper.isContainerMounted(cid); 13673 if (!mounted) { 13674 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13675 Process.SYSTEM_UID); 13676 if (newMountPath != null) { 13677 setMountPath(newMountPath); 13678 } else { 13679 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13680 } 13681 } 13682 } 13683 return status; 13684 } 13685 13686 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13687 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13688 String newMountPath = null; 13689 if (PackageHelper.isContainerMounted(cid)) { 13690 // Unmount the container 13691 if (!PackageHelper.unMountSdDir(cid)) { 13692 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13693 return false; 13694 } 13695 } 13696 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13697 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13698 " which might be stale. Will try to clean up."); 13699 // Clean up the stale container and proceed to recreate. 13700 if (!PackageHelper.destroySdDir(newCacheId)) { 13701 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13702 return false; 13703 } 13704 // Successfully cleaned up stale container. Try to rename again. 13705 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13706 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13707 + " inspite of cleaning it up."); 13708 return false; 13709 } 13710 } 13711 if (!PackageHelper.isContainerMounted(newCacheId)) { 13712 Slog.w(TAG, "Mounting container " + newCacheId); 13713 newMountPath = PackageHelper.mountSdDir(newCacheId, 13714 getEncryptKey(), Process.SYSTEM_UID); 13715 } else { 13716 newMountPath = PackageHelper.getSdDir(newCacheId); 13717 } 13718 if (newMountPath == null) { 13719 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13720 return false; 13721 } 13722 Log.i(TAG, "Succesfully renamed " + cid + 13723 " to " + newCacheId + 13724 " at new path: " + newMountPath); 13725 cid = newCacheId; 13726 13727 final File beforeCodeFile = new File(packagePath); 13728 setMountPath(newMountPath); 13729 final File afterCodeFile = new File(packagePath); 13730 13731 // Reflect the rename in scanned details 13732 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13733 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13734 afterCodeFile, pkg.baseCodePath)); 13735 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13736 afterCodeFile, pkg.splitCodePaths)); 13737 13738 // Reflect the rename in app info 13739 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13740 pkg.setApplicationInfoCodePath(pkg.codePath); 13741 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13742 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13743 pkg.setApplicationInfoResourcePath(pkg.codePath); 13744 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13745 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13746 13747 return true; 13748 } 13749 13750 private void setMountPath(String mountPath) { 13751 final File mountFile = new File(mountPath); 13752 13753 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13754 if (monolithicFile.exists()) { 13755 packagePath = monolithicFile.getAbsolutePath(); 13756 if (isFwdLocked()) { 13757 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13758 } else { 13759 resourcePath = packagePath; 13760 } 13761 } else { 13762 packagePath = mountFile.getAbsolutePath(); 13763 resourcePath = packagePath; 13764 } 13765 } 13766 13767 int doPostInstall(int status, int uid) { 13768 if (status != PackageManager.INSTALL_SUCCEEDED) { 13769 cleanUp(); 13770 } else { 13771 final int groupOwner; 13772 final String protectedFile; 13773 if (isFwdLocked()) { 13774 groupOwner = UserHandle.getSharedAppGid(uid); 13775 protectedFile = RES_FILE_NAME; 13776 } else { 13777 groupOwner = -1; 13778 protectedFile = null; 13779 } 13780 13781 if (uid < Process.FIRST_APPLICATION_UID 13782 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13783 Slog.e(TAG, "Failed to finalize " + cid); 13784 PackageHelper.destroySdDir(cid); 13785 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13786 } 13787 13788 boolean mounted = PackageHelper.isContainerMounted(cid); 13789 if (!mounted) { 13790 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13791 } 13792 } 13793 return status; 13794 } 13795 13796 private void cleanUp() { 13797 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13798 13799 // Destroy secure container 13800 PackageHelper.destroySdDir(cid); 13801 } 13802 13803 private List<String> getAllCodePaths() { 13804 final File codeFile = new File(getCodePath()); 13805 if (codeFile != null && codeFile.exists()) { 13806 try { 13807 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13808 return pkg.getAllCodePaths(); 13809 } catch (PackageParserException e) { 13810 // Ignored; we tried our best 13811 } 13812 } 13813 return Collections.EMPTY_LIST; 13814 } 13815 13816 void cleanUpResourcesLI() { 13817 // Enumerate all code paths before deleting 13818 cleanUpResourcesLI(getAllCodePaths()); 13819 } 13820 13821 private void cleanUpResourcesLI(List<String> allCodePaths) { 13822 cleanUp(); 13823 removeDexFiles(allCodePaths, instructionSets); 13824 } 13825 13826 String getPackageName() { 13827 return getAsecPackageName(cid); 13828 } 13829 13830 boolean doPostDeleteLI(boolean delete) { 13831 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13832 final List<String> allCodePaths = getAllCodePaths(); 13833 boolean mounted = PackageHelper.isContainerMounted(cid); 13834 if (mounted) { 13835 // Unmount first 13836 if (PackageHelper.unMountSdDir(cid)) { 13837 mounted = false; 13838 } 13839 } 13840 if (!mounted && delete) { 13841 cleanUpResourcesLI(allCodePaths); 13842 } 13843 return !mounted; 13844 } 13845 13846 @Override 13847 int doPreCopy() { 13848 if (isFwdLocked()) { 13849 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13850 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13851 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13852 } 13853 } 13854 13855 return PackageManager.INSTALL_SUCCEEDED; 13856 } 13857 13858 @Override 13859 int doPostCopy(int uid) { 13860 if (isFwdLocked()) { 13861 if (uid < Process.FIRST_APPLICATION_UID 13862 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13863 RES_FILE_NAME)) { 13864 Slog.e(TAG, "Failed to finalize " + cid); 13865 PackageHelper.destroySdDir(cid); 13866 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13867 } 13868 } 13869 13870 return PackageManager.INSTALL_SUCCEEDED; 13871 } 13872 } 13873 13874 /** 13875 * Logic to handle movement of existing installed applications. 13876 */ 13877 class MoveInstallArgs extends InstallArgs { 13878 private File codeFile; 13879 private File resourceFile; 13880 13881 /** New install */ 13882 MoveInstallArgs(InstallParams params) { 13883 super(params.origin, params.move, params.observer, params.installFlags, 13884 params.installerPackageName, params.volumeUuid, 13885 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13886 params.grantedRuntimePermissions, 13887 params.traceMethod, params.traceCookie, params.certificates); 13888 } 13889 13890 int copyApk(IMediaContainerService imcs, boolean temp) { 13891 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13892 + move.fromUuid + " to " + move.toUuid); 13893 synchronized (mInstaller) { 13894 try { 13895 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13896 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13897 } catch (InstallerException e) { 13898 Slog.w(TAG, "Failed to move app", e); 13899 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13900 } 13901 } 13902 13903 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13904 resourceFile = codeFile; 13905 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13906 13907 return PackageManager.INSTALL_SUCCEEDED; 13908 } 13909 13910 int doPreInstall(int status) { 13911 if (status != PackageManager.INSTALL_SUCCEEDED) { 13912 cleanUp(move.toUuid); 13913 } 13914 return status; 13915 } 13916 13917 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13918 if (status != PackageManager.INSTALL_SUCCEEDED) { 13919 cleanUp(move.toUuid); 13920 return false; 13921 } 13922 13923 // Reflect the move in app info 13924 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13925 pkg.setApplicationInfoCodePath(pkg.codePath); 13926 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13927 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13928 pkg.setApplicationInfoResourcePath(pkg.codePath); 13929 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13930 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13931 13932 return true; 13933 } 13934 13935 int doPostInstall(int status, int uid) { 13936 if (status == PackageManager.INSTALL_SUCCEEDED) { 13937 cleanUp(move.fromUuid); 13938 } else { 13939 cleanUp(move.toUuid); 13940 } 13941 return status; 13942 } 13943 13944 @Override 13945 String getCodePath() { 13946 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13947 } 13948 13949 @Override 13950 String getResourcePath() { 13951 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13952 } 13953 13954 private boolean cleanUp(String volumeUuid) { 13955 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13956 move.dataAppName); 13957 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13958 final int[] userIds = sUserManager.getUserIds(); 13959 synchronized (mInstallLock) { 13960 // Clean up both app data and code 13961 // All package moves are frozen until finished 13962 for (int userId : userIds) { 13963 try { 13964 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13965 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13966 } catch (InstallerException e) { 13967 Slog.w(TAG, String.valueOf(e)); 13968 } 13969 } 13970 removeCodePathLI(codeFile); 13971 } 13972 return true; 13973 } 13974 13975 void cleanUpResourcesLI() { 13976 throw new UnsupportedOperationException(); 13977 } 13978 13979 boolean doPostDeleteLI(boolean delete) { 13980 throw new UnsupportedOperationException(); 13981 } 13982 } 13983 13984 static String getAsecPackageName(String packageCid) { 13985 int idx = packageCid.lastIndexOf("-"); 13986 if (idx == -1) { 13987 return packageCid; 13988 } 13989 return packageCid.substring(0, idx); 13990 } 13991 13992 // Utility method used to create code paths based on package name and available index. 13993 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13994 String idxStr = ""; 13995 int idx = 1; 13996 // Fall back to default value of idx=1 if prefix is not 13997 // part of oldCodePath 13998 if (oldCodePath != null) { 13999 String subStr = oldCodePath; 14000 // Drop the suffix right away 14001 if (suffix != null && subStr.endsWith(suffix)) { 14002 subStr = subStr.substring(0, subStr.length() - suffix.length()); 14003 } 14004 // If oldCodePath already contains prefix find out the 14005 // ending index to either increment or decrement. 14006 int sidx = subStr.lastIndexOf(prefix); 14007 if (sidx != -1) { 14008 subStr = subStr.substring(sidx + prefix.length()); 14009 if (subStr != null) { 14010 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 14011 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 14012 } 14013 try { 14014 idx = Integer.parseInt(subStr); 14015 if (idx <= 1) { 14016 idx++; 14017 } else { 14018 idx--; 14019 } 14020 } catch(NumberFormatException e) { 14021 } 14022 } 14023 } 14024 } 14025 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 14026 return prefix + idxStr; 14027 } 14028 14029 private File getNextCodePath(File targetDir, String packageName) { 14030 int suffix = 1; 14031 File result; 14032 do { 14033 result = new File(targetDir, packageName + "-" + suffix); 14034 suffix++; 14035 } while (result.exists()); 14036 return result; 14037 } 14038 14039 // Utility method that returns the relative package path with respect 14040 // to the installation directory. Like say for /data/data/com.test-1.apk 14041 // string com.test-1 is returned. 14042 static String deriveCodePathName(String codePath) { 14043 if (codePath == null) { 14044 return null; 14045 } 14046 final File codeFile = new File(codePath); 14047 final String name = codeFile.getName(); 14048 if (codeFile.isDirectory()) { 14049 return name; 14050 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14051 final int lastDot = name.lastIndexOf('.'); 14052 return name.substring(0, lastDot); 14053 } else { 14054 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14055 return null; 14056 } 14057 } 14058 14059 static class PackageInstalledInfo { 14060 String name; 14061 int uid; 14062 // The set of users that originally had this package installed. 14063 int[] origUsers; 14064 // The set of users that now have this package installed. 14065 int[] newUsers; 14066 PackageParser.Package pkg; 14067 int returnCode; 14068 String returnMsg; 14069 PackageRemovedInfo removedInfo; 14070 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14071 14072 public void setError(int code, String msg) { 14073 setReturnCode(code); 14074 setReturnMessage(msg); 14075 Slog.w(TAG, msg); 14076 } 14077 14078 public void setError(String msg, PackageParserException e) { 14079 setReturnCode(e.error); 14080 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14081 Slog.w(TAG, msg, e); 14082 } 14083 14084 public void setError(String msg, PackageManagerException e) { 14085 returnCode = e.error; 14086 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14087 Slog.w(TAG, msg, e); 14088 } 14089 14090 public void setReturnCode(int returnCode) { 14091 this.returnCode = returnCode; 14092 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14093 for (int i = 0; i < childCount; i++) { 14094 addedChildPackages.valueAt(i).returnCode = returnCode; 14095 } 14096 } 14097 14098 private void setReturnMessage(String returnMsg) { 14099 this.returnMsg = returnMsg; 14100 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14101 for (int i = 0; i < childCount; i++) { 14102 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14103 } 14104 } 14105 14106 // In some error cases we want to convey more info back to the observer 14107 String origPackage; 14108 String origPermission; 14109 } 14110 14111 /* 14112 * Install a non-existing package. 14113 */ 14114 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14115 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14116 PackageInstalledInfo res) { 14117 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14118 14119 // Remember this for later, in case we need to rollback this install 14120 String pkgName = pkg.packageName; 14121 14122 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14123 14124 synchronized(mPackages) { 14125 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14126 // A package with the same name is already installed, though 14127 // it has been renamed to an older name. The package we 14128 // are trying to install should be installed as an update to 14129 // the existing one, but that has not been requested, so bail. 14130 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14131 + " without first uninstalling package running as " 14132 + mSettings.mRenamedPackages.get(pkgName)); 14133 return; 14134 } 14135 if (mPackages.containsKey(pkgName)) { 14136 // Don't allow installation over an existing package with the same name. 14137 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14138 + " without first uninstalling."); 14139 return; 14140 } 14141 } 14142 14143 try { 14144 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14145 System.currentTimeMillis(), user); 14146 14147 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14148 14149 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14150 prepareAppDataAfterInstallLIF(newPackage); 14151 14152 } else { 14153 // Remove package from internal structures, but keep around any 14154 // data that might have already existed 14155 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14156 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14157 } 14158 } catch (PackageManagerException e) { 14159 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14160 } 14161 14162 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14163 } 14164 14165 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14166 // Can't rotate keys during boot or if sharedUser. 14167 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14168 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14169 return false; 14170 } 14171 // app is using upgradeKeySets; make sure all are valid 14172 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14173 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14174 for (int i = 0; i < upgradeKeySets.length; i++) { 14175 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14176 Slog.wtf(TAG, "Package " 14177 + (oldPs.name != null ? oldPs.name : "<null>") 14178 + " contains upgrade-key-set reference to unknown key-set: " 14179 + upgradeKeySets[i] 14180 + " reverting to signatures check."); 14181 return false; 14182 } 14183 } 14184 return true; 14185 } 14186 14187 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14188 // Upgrade keysets are being used. Determine if new package has a superset of the 14189 // required keys. 14190 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14191 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14192 for (int i = 0; i < upgradeKeySets.length; i++) { 14193 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14194 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14195 return true; 14196 } 14197 } 14198 return false; 14199 } 14200 14201 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14202 try (DigestInputStream digestStream = 14203 new DigestInputStream(new FileInputStream(file), digest)) { 14204 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14205 } 14206 } 14207 14208 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14209 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14210 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14211 14212 final PackageParser.Package oldPackage; 14213 final String pkgName = pkg.packageName; 14214 final int[] allUsers; 14215 final int[] installedUsers; 14216 14217 synchronized(mPackages) { 14218 oldPackage = mPackages.get(pkgName); 14219 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14220 14221 // don't allow upgrade to target a release SDK from a pre-release SDK 14222 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14223 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14224 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14225 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14226 if (oldTargetsPreRelease 14227 && !newTargetsPreRelease 14228 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14229 Slog.w(TAG, "Can't install package targeting released sdk"); 14230 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14231 return; 14232 } 14233 14234 // don't allow an upgrade from full to ephemeral 14235 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14236 if (isEphemeral && !oldIsEphemeral) { 14237 // can't downgrade from full to ephemeral 14238 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14239 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14240 return; 14241 } 14242 14243 // verify signatures are valid 14244 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14245 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14246 if (!checkUpgradeKeySetLP(ps, pkg)) { 14247 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14248 "New package not signed by keys specified by upgrade-keysets: " 14249 + pkgName); 14250 return; 14251 } 14252 } else { 14253 // default to original signature matching 14254 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14255 != PackageManager.SIGNATURE_MATCH) { 14256 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14257 "New package has a different signature: " + pkgName); 14258 return; 14259 } 14260 } 14261 14262 // don't allow a system upgrade unless the upgrade hash matches 14263 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14264 byte[] digestBytes = null; 14265 try { 14266 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14267 updateDigest(digest, new File(pkg.baseCodePath)); 14268 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14269 for (String path : pkg.splitCodePaths) { 14270 updateDigest(digest, new File(path)); 14271 } 14272 } 14273 digestBytes = digest.digest(); 14274 } catch (NoSuchAlgorithmException | IOException e) { 14275 res.setError(INSTALL_FAILED_INVALID_APK, 14276 "Could not compute hash: " + pkgName); 14277 return; 14278 } 14279 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14280 res.setError(INSTALL_FAILED_INVALID_APK, 14281 "New package fails restrict-update check: " + pkgName); 14282 return; 14283 } 14284 // retain upgrade restriction 14285 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14286 } 14287 14288 // Check for shared user id changes 14289 String invalidPackageName = 14290 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14291 if (invalidPackageName != null) { 14292 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14293 "Package " + invalidPackageName + " tried to change user " 14294 + oldPackage.mSharedUserId); 14295 return; 14296 } 14297 14298 // In case of rollback, remember per-user/profile install state 14299 allUsers = sUserManager.getUserIds(); 14300 installedUsers = ps.queryInstalledUsers(allUsers, true); 14301 } 14302 14303 // Update what is removed 14304 res.removedInfo = new PackageRemovedInfo(); 14305 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14306 res.removedInfo.removedPackage = oldPackage.packageName; 14307 res.removedInfo.isUpdate = true; 14308 res.removedInfo.origUsers = installedUsers; 14309 final int childCount = (oldPackage.childPackages != null) 14310 ? oldPackage.childPackages.size() : 0; 14311 for (int i = 0; i < childCount; i++) { 14312 boolean childPackageUpdated = false; 14313 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14314 if (res.addedChildPackages != null) { 14315 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14316 if (childRes != null) { 14317 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14318 childRes.removedInfo.removedPackage = childPkg.packageName; 14319 childRes.removedInfo.isUpdate = true; 14320 childPackageUpdated = true; 14321 } 14322 } 14323 if (!childPackageUpdated) { 14324 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14325 childRemovedRes.removedPackage = childPkg.packageName; 14326 childRemovedRes.isUpdate = false; 14327 childRemovedRes.dataRemoved = true; 14328 synchronized (mPackages) { 14329 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14330 if (childPs != null) { 14331 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14332 } 14333 } 14334 if (res.removedInfo.removedChildPackages == null) { 14335 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14336 } 14337 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14338 } 14339 } 14340 14341 boolean sysPkg = (isSystemApp(oldPackage)); 14342 if (sysPkg) { 14343 // Set the system/privileged flags as needed 14344 final boolean privileged = 14345 (oldPackage.applicationInfo.privateFlags 14346 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14347 final int systemPolicyFlags = policyFlags 14348 | PackageParser.PARSE_IS_SYSTEM 14349 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14350 14351 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14352 user, allUsers, installerPackageName, res); 14353 } else { 14354 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14355 user, allUsers, installerPackageName, res); 14356 } 14357 } 14358 14359 public List<String> getPreviousCodePaths(String packageName) { 14360 final PackageSetting ps = mSettings.mPackages.get(packageName); 14361 final List<String> result = new ArrayList<String>(); 14362 if (ps != null && ps.oldCodePaths != null) { 14363 result.addAll(ps.oldCodePaths); 14364 } 14365 return result; 14366 } 14367 14368 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14369 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14370 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14371 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14372 + deletedPackage); 14373 14374 String pkgName = deletedPackage.packageName; 14375 boolean deletedPkg = true; 14376 boolean addedPkg = false; 14377 boolean updatedSettings = false; 14378 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14379 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14380 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14381 14382 final long origUpdateTime = (pkg.mExtras != null) 14383 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14384 14385 // First delete the existing package while retaining the data directory 14386 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14387 res.removedInfo, true, pkg)) { 14388 // If the existing package wasn't successfully deleted 14389 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14390 deletedPkg = false; 14391 } else { 14392 // Successfully deleted the old package; proceed with replace. 14393 14394 // If deleted package lived in a container, give users a chance to 14395 // relinquish resources before killing. 14396 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14397 if (DEBUG_INSTALL) { 14398 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14399 } 14400 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14401 final ArrayList<String> pkgList = new ArrayList<String>(1); 14402 pkgList.add(deletedPackage.applicationInfo.packageName); 14403 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14404 } 14405 14406 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14407 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14408 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14409 14410 try { 14411 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14412 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14413 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14414 14415 // Update the in-memory copy of the previous code paths. 14416 PackageSetting ps = mSettings.mPackages.get(pkgName); 14417 if (!killApp) { 14418 if (ps.oldCodePaths == null) { 14419 ps.oldCodePaths = new ArraySet<>(); 14420 } 14421 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14422 if (deletedPackage.splitCodePaths != null) { 14423 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14424 } 14425 } else { 14426 ps.oldCodePaths = null; 14427 } 14428 if (ps.childPackageNames != null) { 14429 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14430 final String childPkgName = ps.childPackageNames.get(i); 14431 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14432 childPs.oldCodePaths = ps.oldCodePaths; 14433 } 14434 } 14435 prepareAppDataAfterInstallLIF(newPackage); 14436 addedPkg = true; 14437 } catch (PackageManagerException e) { 14438 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14439 } 14440 } 14441 14442 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14443 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14444 14445 // Revert all internal state mutations and added folders for the failed install 14446 if (addedPkg) { 14447 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14448 res.removedInfo, true, null); 14449 } 14450 14451 // Restore the old package 14452 if (deletedPkg) { 14453 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14454 File restoreFile = new File(deletedPackage.codePath); 14455 // Parse old package 14456 boolean oldExternal = isExternal(deletedPackage); 14457 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14458 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14459 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14460 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14461 try { 14462 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14463 null); 14464 } catch (PackageManagerException e) { 14465 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14466 + e.getMessage()); 14467 return; 14468 } 14469 14470 synchronized (mPackages) { 14471 // Ensure the installer package name up to date 14472 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14473 14474 // Update permissions for restored package 14475 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14476 14477 mSettings.writeLPr(); 14478 } 14479 14480 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14481 } 14482 } else { 14483 synchronized (mPackages) { 14484 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14485 if (ps != null) { 14486 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14487 if (res.removedInfo.removedChildPackages != null) { 14488 final int childCount = res.removedInfo.removedChildPackages.size(); 14489 // Iterate in reverse as we may modify the collection 14490 for (int i = childCount - 1; i >= 0; i--) { 14491 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14492 if (res.addedChildPackages.containsKey(childPackageName)) { 14493 res.removedInfo.removedChildPackages.removeAt(i); 14494 } else { 14495 PackageRemovedInfo childInfo = res.removedInfo 14496 .removedChildPackages.valueAt(i); 14497 childInfo.removedForAllUsers = mPackages.get( 14498 childInfo.removedPackage) == null; 14499 } 14500 } 14501 } 14502 } 14503 } 14504 } 14505 } 14506 14507 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14508 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14509 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14510 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14511 + ", old=" + deletedPackage); 14512 14513 final boolean disabledSystem; 14514 14515 // Remove existing system package 14516 removePackageLI(deletedPackage, true); 14517 14518 synchronized (mPackages) { 14519 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14520 } 14521 if (!disabledSystem) { 14522 // We didn't need to disable the .apk as a current system package, 14523 // which means we are replacing another update that is already 14524 // installed. We need to make sure to delete the older one's .apk. 14525 res.removedInfo.args = createInstallArgsForExisting(0, 14526 deletedPackage.applicationInfo.getCodePath(), 14527 deletedPackage.applicationInfo.getResourcePath(), 14528 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14529 } else { 14530 res.removedInfo.args = null; 14531 } 14532 14533 // Successfully disabled the old package. Now proceed with re-installation 14534 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14535 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14536 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14537 14538 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14539 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14540 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14541 14542 PackageParser.Package newPackage = null; 14543 try { 14544 // Add the package to the internal data structures 14545 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14546 14547 // Set the update and install times 14548 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14549 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14550 System.currentTimeMillis()); 14551 14552 // Update the package dynamic state if succeeded 14553 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14554 // Now that the install succeeded make sure we remove data 14555 // directories for any child package the update removed. 14556 final int deletedChildCount = (deletedPackage.childPackages != null) 14557 ? deletedPackage.childPackages.size() : 0; 14558 final int newChildCount = (newPackage.childPackages != null) 14559 ? newPackage.childPackages.size() : 0; 14560 for (int i = 0; i < deletedChildCount; i++) { 14561 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14562 boolean childPackageDeleted = true; 14563 for (int j = 0; j < newChildCount; j++) { 14564 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14565 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14566 childPackageDeleted = false; 14567 break; 14568 } 14569 } 14570 if (childPackageDeleted) { 14571 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14572 deletedChildPkg.packageName); 14573 if (ps != null && res.removedInfo.removedChildPackages != null) { 14574 PackageRemovedInfo removedChildRes = res.removedInfo 14575 .removedChildPackages.get(deletedChildPkg.packageName); 14576 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14577 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14578 } 14579 } 14580 } 14581 14582 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14583 prepareAppDataAfterInstallLIF(newPackage); 14584 } 14585 } catch (PackageManagerException e) { 14586 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14587 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14588 } 14589 14590 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14591 // Re installation failed. Restore old information 14592 // Remove new pkg information 14593 if (newPackage != null) { 14594 removeInstalledPackageLI(newPackage, true); 14595 } 14596 // Add back the old system package 14597 try { 14598 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14599 } catch (PackageManagerException e) { 14600 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14601 } 14602 14603 synchronized (mPackages) { 14604 if (disabledSystem) { 14605 enableSystemPackageLPw(deletedPackage); 14606 } 14607 14608 // Ensure the installer package name up to date 14609 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14610 14611 // Update permissions for restored package 14612 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14613 14614 mSettings.writeLPr(); 14615 } 14616 14617 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14618 + " after failed upgrade"); 14619 } 14620 } 14621 14622 /** 14623 * Checks whether the parent or any of the child packages have a change shared 14624 * user. For a package to be a valid update the shred users of the parent and 14625 * the children should match. We may later support changing child shared users. 14626 * @param oldPkg The updated package. 14627 * @param newPkg The update package. 14628 * @return The shared user that change between the versions. 14629 */ 14630 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14631 PackageParser.Package newPkg) { 14632 // Check parent shared user 14633 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14634 return newPkg.packageName; 14635 } 14636 // Check child shared users 14637 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14638 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14639 for (int i = 0; i < newChildCount; i++) { 14640 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14641 // If this child was present, did it have the same shared user? 14642 for (int j = 0; j < oldChildCount; j++) { 14643 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14644 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14645 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14646 return newChildPkg.packageName; 14647 } 14648 } 14649 } 14650 return null; 14651 } 14652 14653 private void removeNativeBinariesLI(PackageSetting ps) { 14654 // Remove the lib path for the parent package 14655 if (ps != null) { 14656 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14657 // Remove the lib path for the child packages 14658 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14659 for (int i = 0; i < childCount; i++) { 14660 PackageSetting childPs = null; 14661 synchronized (mPackages) { 14662 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14663 } 14664 if (childPs != null) { 14665 NativeLibraryHelper.removeNativeBinariesLI(childPs 14666 .legacyNativeLibraryPathString); 14667 } 14668 } 14669 } 14670 } 14671 14672 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14673 // Enable the parent package 14674 mSettings.enableSystemPackageLPw(pkg.packageName); 14675 // Enable the child packages 14676 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14677 for (int i = 0; i < childCount; i++) { 14678 PackageParser.Package childPkg = pkg.childPackages.get(i); 14679 mSettings.enableSystemPackageLPw(childPkg.packageName); 14680 } 14681 } 14682 14683 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14684 PackageParser.Package newPkg) { 14685 // Disable the parent package (parent always replaced) 14686 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14687 // Disable the child packages 14688 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14689 for (int i = 0; i < childCount; i++) { 14690 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14691 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14692 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14693 } 14694 return disabled; 14695 } 14696 14697 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14698 String installerPackageName) { 14699 // Enable the parent package 14700 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14701 // Enable the child packages 14702 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14703 for (int i = 0; i < childCount; i++) { 14704 PackageParser.Package childPkg = pkg.childPackages.get(i); 14705 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14706 } 14707 } 14708 14709 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14710 // Collect all used permissions in the UID 14711 ArraySet<String> usedPermissions = new ArraySet<>(); 14712 final int packageCount = su.packages.size(); 14713 for (int i = 0; i < packageCount; i++) { 14714 PackageSetting ps = su.packages.valueAt(i); 14715 if (ps.pkg == null) { 14716 continue; 14717 } 14718 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14719 for (int j = 0; j < requestedPermCount; j++) { 14720 String permission = ps.pkg.requestedPermissions.get(j); 14721 BasePermission bp = mSettings.mPermissions.get(permission); 14722 if (bp != null) { 14723 usedPermissions.add(permission); 14724 } 14725 } 14726 } 14727 14728 PermissionsState permissionsState = su.getPermissionsState(); 14729 // Prune install permissions 14730 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14731 final int installPermCount = installPermStates.size(); 14732 for (int i = installPermCount - 1; i >= 0; i--) { 14733 PermissionState permissionState = installPermStates.get(i); 14734 if (!usedPermissions.contains(permissionState.getName())) { 14735 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14736 if (bp != null) { 14737 permissionsState.revokeInstallPermission(bp); 14738 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14739 PackageManager.MASK_PERMISSION_FLAGS, 0); 14740 } 14741 } 14742 } 14743 14744 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14745 14746 // Prune runtime permissions 14747 for (int userId : allUserIds) { 14748 List<PermissionState> runtimePermStates = permissionsState 14749 .getRuntimePermissionStates(userId); 14750 final int runtimePermCount = runtimePermStates.size(); 14751 for (int i = runtimePermCount - 1; i >= 0; i--) { 14752 PermissionState permissionState = runtimePermStates.get(i); 14753 if (!usedPermissions.contains(permissionState.getName())) { 14754 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14755 if (bp != null) { 14756 permissionsState.revokeRuntimePermission(bp, userId); 14757 permissionsState.updatePermissionFlags(bp, userId, 14758 PackageManager.MASK_PERMISSION_FLAGS, 0); 14759 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14760 runtimePermissionChangedUserIds, userId); 14761 } 14762 } 14763 } 14764 } 14765 14766 return runtimePermissionChangedUserIds; 14767 } 14768 14769 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14770 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14771 // Update the parent package setting 14772 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14773 res, user); 14774 // Update the child packages setting 14775 final int childCount = (newPackage.childPackages != null) 14776 ? newPackage.childPackages.size() : 0; 14777 for (int i = 0; i < childCount; i++) { 14778 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14779 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14780 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14781 childRes.origUsers, childRes, user); 14782 } 14783 } 14784 14785 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14786 String installerPackageName, int[] allUsers, int[] installedForUsers, 14787 PackageInstalledInfo res, UserHandle user) { 14788 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14789 14790 String pkgName = newPackage.packageName; 14791 synchronized (mPackages) { 14792 //write settings. the installStatus will be incomplete at this stage. 14793 //note that the new package setting would have already been 14794 //added to mPackages. It hasn't been persisted yet. 14795 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14796 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14797 mSettings.writeLPr(); 14798 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14799 } 14800 14801 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14802 synchronized (mPackages) { 14803 updatePermissionsLPw(newPackage.packageName, newPackage, 14804 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14805 ? UPDATE_PERMISSIONS_ALL : 0)); 14806 // For system-bundled packages, we assume that installing an upgraded version 14807 // of the package implies that the user actually wants to run that new code, 14808 // so we enable the package. 14809 PackageSetting ps = mSettings.mPackages.get(pkgName); 14810 final int userId = user.getIdentifier(); 14811 if (ps != null) { 14812 if (isSystemApp(newPackage)) { 14813 if (DEBUG_INSTALL) { 14814 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14815 } 14816 // Enable system package for requested users 14817 if (res.origUsers != null) { 14818 for (int origUserId : res.origUsers) { 14819 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14820 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14821 origUserId, installerPackageName); 14822 } 14823 } 14824 } 14825 // Also convey the prior install/uninstall state 14826 if (allUsers != null && installedForUsers != null) { 14827 for (int currentUserId : allUsers) { 14828 final boolean installed = ArrayUtils.contains( 14829 installedForUsers, currentUserId); 14830 if (DEBUG_INSTALL) { 14831 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14832 } 14833 ps.setInstalled(installed, currentUserId); 14834 } 14835 // these install state changes will be persisted in the 14836 // upcoming call to mSettings.writeLPr(). 14837 } 14838 } 14839 // It's implied that when a user requests installation, they want the app to be 14840 // installed and enabled. 14841 if (userId != UserHandle.USER_ALL) { 14842 ps.setInstalled(true, userId); 14843 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14844 } 14845 } 14846 res.name = pkgName; 14847 res.uid = newPackage.applicationInfo.uid; 14848 res.pkg = newPackage; 14849 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14850 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14851 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14852 //to update install status 14853 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14854 mSettings.writeLPr(); 14855 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14856 } 14857 14858 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14859 } 14860 14861 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14862 try { 14863 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14864 installPackageLI(args, res); 14865 } finally { 14866 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14867 } 14868 } 14869 14870 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14871 final int installFlags = args.installFlags; 14872 final String installerPackageName = args.installerPackageName; 14873 final String volumeUuid = args.volumeUuid; 14874 final File tmpPackageFile = new File(args.getCodePath()); 14875 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14876 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14877 || (args.volumeUuid != null)); 14878 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14879 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14880 boolean replace = false; 14881 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14882 if (args.move != null) { 14883 // moving a complete application; perform an initial scan on the new install location 14884 scanFlags |= SCAN_INITIAL; 14885 } 14886 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14887 scanFlags |= SCAN_DONT_KILL_APP; 14888 } 14889 14890 // Result object to be returned 14891 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14892 14893 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14894 14895 // Sanity check 14896 if (ephemeral && (forwardLocked || onExternal)) { 14897 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14898 + " external=" + onExternal); 14899 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14900 return; 14901 } 14902 14903 // Retrieve PackageSettings and parse package 14904 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14905 | PackageParser.PARSE_ENFORCE_CODE 14906 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14907 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14908 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14909 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14910 PackageParser pp = new PackageParser(); 14911 pp.setSeparateProcesses(mSeparateProcesses); 14912 pp.setDisplayMetrics(mMetrics); 14913 14914 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14915 final PackageParser.Package pkg; 14916 try { 14917 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14918 } catch (PackageParserException e) { 14919 res.setError("Failed parse during installPackageLI", e); 14920 return; 14921 } finally { 14922 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14923 } 14924 14925 // If we are installing a clustered package add results for the children 14926 if (pkg.childPackages != null) { 14927 synchronized (mPackages) { 14928 final int childCount = pkg.childPackages.size(); 14929 for (int i = 0; i < childCount; i++) { 14930 PackageParser.Package childPkg = pkg.childPackages.get(i); 14931 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14932 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14933 childRes.pkg = childPkg; 14934 childRes.name = childPkg.packageName; 14935 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14936 if (childPs != null) { 14937 childRes.origUsers = childPs.queryInstalledUsers( 14938 sUserManager.getUserIds(), true); 14939 } 14940 if ((mPackages.containsKey(childPkg.packageName))) { 14941 childRes.removedInfo = new PackageRemovedInfo(); 14942 childRes.removedInfo.removedPackage = childPkg.packageName; 14943 } 14944 if (res.addedChildPackages == null) { 14945 res.addedChildPackages = new ArrayMap<>(); 14946 } 14947 res.addedChildPackages.put(childPkg.packageName, childRes); 14948 } 14949 } 14950 } 14951 14952 // If package doesn't declare API override, mark that we have an install 14953 // time CPU ABI override. 14954 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14955 pkg.cpuAbiOverride = args.abiOverride; 14956 } 14957 14958 String pkgName = res.name = pkg.packageName; 14959 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14960 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14961 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14962 return; 14963 } 14964 } 14965 14966 try { 14967 // either use what we've been given or parse directly from the APK 14968 if (args.certificates != null) { 14969 try { 14970 PackageParser.populateCertificates(pkg, args.certificates); 14971 } catch (PackageParserException e) { 14972 // there was something wrong with the certificates we were given; 14973 // try to pull them from the APK 14974 PackageParser.collectCertificates(pkg, parseFlags); 14975 } 14976 } else { 14977 PackageParser.collectCertificates(pkg, parseFlags); 14978 } 14979 } catch (PackageParserException e) { 14980 res.setError("Failed collect during installPackageLI", e); 14981 return; 14982 } 14983 14984 // Get rid of all references to package scan path via parser. 14985 pp = null; 14986 String oldCodePath = null; 14987 boolean systemApp = false; 14988 synchronized (mPackages) { 14989 // Check if installing already existing package 14990 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14991 String oldName = mSettings.mRenamedPackages.get(pkgName); 14992 if (pkg.mOriginalPackages != null 14993 && pkg.mOriginalPackages.contains(oldName) 14994 && mPackages.containsKey(oldName)) { 14995 // This package is derived from an original package, 14996 // and this device has been updating from that original 14997 // name. We must continue using the original name, so 14998 // rename the new package here. 14999 pkg.setPackageName(oldName); 15000 pkgName = pkg.packageName; 15001 replace = true; 15002 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 15003 + oldName + " pkgName=" + pkgName); 15004 } else if (mPackages.containsKey(pkgName)) { 15005 // This package, under its official name, already exists 15006 // on the device; we should replace it. 15007 replace = true; 15008 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 15009 } 15010 15011 // Child packages are installed through the parent package 15012 if (pkg.parentPackage != null) { 15013 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15014 "Package " + pkg.packageName + " is child of package " 15015 + pkg.parentPackage.parentPackage + ". Child packages " 15016 + "can be updated only through the parent package."); 15017 return; 15018 } 15019 15020 if (replace) { 15021 // Prevent apps opting out from runtime permissions 15022 PackageParser.Package oldPackage = mPackages.get(pkgName); 15023 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 15024 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 15025 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 15026 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 15027 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 15028 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 15029 + " doesn't support runtime permissions but the old" 15030 + " target SDK " + oldTargetSdk + " does."); 15031 return; 15032 } 15033 15034 // Prevent installing of child packages 15035 if (oldPackage.parentPackage != null) { 15036 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15037 "Package " + pkg.packageName + " is child of package " 15038 + oldPackage.parentPackage + ". Child packages " 15039 + "can be updated only through the parent package."); 15040 return; 15041 } 15042 } 15043 } 15044 15045 PackageSetting ps = mSettings.mPackages.get(pkgName); 15046 if (ps != null) { 15047 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15048 15049 // Quick sanity check that we're signed correctly if updating; 15050 // we'll check this again later when scanning, but we want to 15051 // bail early here before tripping over redefined permissions. 15052 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15053 if (!checkUpgradeKeySetLP(ps, pkg)) { 15054 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15055 + pkg.packageName + " upgrade keys do not match the " 15056 + "previously installed version"); 15057 return; 15058 } 15059 } else { 15060 try { 15061 verifySignaturesLP(ps, pkg); 15062 } catch (PackageManagerException e) { 15063 res.setError(e.error, e.getMessage()); 15064 return; 15065 } 15066 } 15067 15068 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15069 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15070 systemApp = (ps.pkg.applicationInfo.flags & 15071 ApplicationInfo.FLAG_SYSTEM) != 0; 15072 } 15073 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15074 } 15075 15076 // Check whether the newly-scanned package wants to define an already-defined perm 15077 int N = pkg.permissions.size(); 15078 for (int i = N-1; i >= 0; i--) { 15079 PackageParser.Permission perm = pkg.permissions.get(i); 15080 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15081 if (bp != null) { 15082 // If the defining package is signed with our cert, it's okay. This 15083 // also includes the "updating the same package" case, of course. 15084 // "updating same package" could also involve key-rotation. 15085 final boolean sigsOk; 15086 if (bp.sourcePackage.equals(pkg.packageName) 15087 && (bp.packageSetting instanceof PackageSetting) 15088 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15089 scanFlags))) { 15090 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15091 } else { 15092 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15093 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15094 } 15095 if (!sigsOk) { 15096 // If the owning package is the system itself, we log but allow 15097 // install to proceed; we fail the install on all other permission 15098 // redefinitions. 15099 if (!bp.sourcePackage.equals("android")) { 15100 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15101 + pkg.packageName + " attempting to redeclare permission " 15102 + perm.info.name + " already owned by " + bp.sourcePackage); 15103 res.origPermission = perm.info.name; 15104 res.origPackage = bp.sourcePackage; 15105 return; 15106 } else { 15107 Slog.w(TAG, "Package " + pkg.packageName 15108 + " attempting to redeclare system permission " 15109 + perm.info.name + "; ignoring new declaration"); 15110 pkg.permissions.remove(i); 15111 } 15112 } 15113 } 15114 } 15115 } 15116 15117 if (systemApp) { 15118 if (onExternal) { 15119 // Abort update; system app can't be replaced with app on sdcard 15120 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15121 "Cannot install updates to system apps on sdcard"); 15122 return; 15123 } else if (ephemeral) { 15124 // Abort update; system app can't be replaced with an ephemeral app 15125 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15126 "Cannot update a system app with an ephemeral app"); 15127 return; 15128 } 15129 } 15130 15131 if (args.move != null) { 15132 // We did an in-place move, so dex is ready to roll 15133 scanFlags |= SCAN_NO_DEX; 15134 scanFlags |= SCAN_MOVE; 15135 15136 synchronized (mPackages) { 15137 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15138 if (ps == null) { 15139 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15140 "Missing settings for moved package " + pkgName); 15141 } 15142 15143 // We moved the entire application as-is, so bring over the 15144 // previously derived ABI information. 15145 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15146 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15147 } 15148 15149 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15150 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15151 scanFlags |= SCAN_NO_DEX; 15152 15153 try { 15154 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15155 args.abiOverride : pkg.cpuAbiOverride); 15156 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15157 true /* extract libs */); 15158 } catch (PackageManagerException pme) { 15159 Slog.e(TAG, "Error deriving application ABI", pme); 15160 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15161 return; 15162 } 15163 15164 // Shared libraries for the package need to be updated. 15165 synchronized (mPackages) { 15166 try { 15167 updateSharedLibrariesLPw(pkg, null); 15168 } catch (PackageManagerException e) { 15169 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15170 } 15171 } 15172 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15173 // Do not run PackageDexOptimizer through the local performDexOpt 15174 // method because `pkg` is not in `mPackages` yet. 15175 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15176 null /* instructionSets */, false /* checkProfiles */, 15177 getCompilerFilterForReason(REASON_INSTALL)); 15178 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15179 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 15180 String msg = "Extracting package failed for " + pkgName; 15181 res.setError(INSTALL_FAILED_DEXOPT, msg); 15182 return; 15183 } 15184 15185 // Notify BackgroundDexOptService that the package has been changed. 15186 // If this is an update of a package which used to fail to compile, 15187 // BDOS will remove it from its blacklist. 15188 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15189 } 15190 15191 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15192 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15193 return; 15194 } 15195 15196 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15197 15198 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15199 "installPackageLI")) { 15200 if (replace) { 15201 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15202 installerPackageName, res); 15203 } else { 15204 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15205 args.user, installerPackageName, volumeUuid, res); 15206 } 15207 } 15208 synchronized (mPackages) { 15209 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15210 if (ps != null) { 15211 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15212 } 15213 15214 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15215 for (int i = 0; i < childCount; i++) { 15216 PackageParser.Package childPkg = pkg.childPackages.get(i); 15217 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15218 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15219 if (childPs != null) { 15220 childRes.newUsers = childPs.queryInstalledUsers( 15221 sUserManager.getUserIds(), true); 15222 } 15223 } 15224 } 15225 } 15226 15227 private void startIntentFilterVerifications(int userId, boolean replacing, 15228 PackageParser.Package pkg) { 15229 if (mIntentFilterVerifierComponent == null) { 15230 Slog.w(TAG, "No IntentFilter verification will not be done as " 15231 + "there is no IntentFilterVerifier available!"); 15232 return; 15233 } 15234 15235 final int verifierUid = getPackageUid( 15236 mIntentFilterVerifierComponent.getPackageName(), 15237 MATCH_DEBUG_TRIAGED_MISSING, 15238 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15239 15240 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15241 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15242 mHandler.sendMessage(msg); 15243 15244 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15245 for (int i = 0; i < childCount; i++) { 15246 PackageParser.Package childPkg = pkg.childPackages.get(i); 15247 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15248 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15249 mHandler.sendMessage(msg); 15250 } 15251 } 15252 15253 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15254 PackageParser.Package pkg) { 15255 int size = pkg.activities.size(); 15256 if (size == 0) { 15257 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15258 "No activity, so no need to verify any IntentFilter!"); 15259 return; 15260 } 15261 15262 final boolean hasDomainURLs = hasDomainURLs(pkg); 15263 if (!hasDomainURLs) { 15264 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15265 "No domain URLs, so no need to verify any IntentFilter!"); 15266 return; 15267 } 15268 15269 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15270 + " if any IntentFilter from the " + size 15271 + " Activities needs verification ..."); 15272 15273 int count = 0; 15274 final String packageName = pkg.packageName; 15275 15276 synchronized (mPackages) { 15277 // If this is a new install and we see that we've already run verification for this 15278 // package, we have nothing to do: it means the state was restored from backup. 15279 if (!replacing) { 15280 IntentFilterVerificationInfo ivi = 15281 mSettings.getIntentFilterVerificationLPr(packageName); 15282 if (ivi != null) { 15283 if (DEBUG_DOMAIN_VERIFICATION) { 15284 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15285 + ivi.getStatusString()); 15286 } 15287 return; 15288 } 15289 } 15290 15291 // If any filters need to be verified, then all need to be. 15292 boolean needToVerify = false; 15293 for (PackageParser.Activity a : pkg.activities) { 15294 for (ActivityIntentInfo filter : a.intents) { 15295 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15296 if (DEBUG_DOMAIN_VERIFICATION) { 15297 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15298 } 15299 needToVerify = true; 15300 break; 15301 } 15302 } 15303 } 15304 15305 if (needToVerify) { 15306 final int verificationId = mIntentFilterVerificationToken++; 15307 for (PackageParser.Activity a : pkg.activities) { 15308 for (ActivityIntentInfo filter : a.intents) { 15309 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15310 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15311 "Verification needed for IntentFilter:" + filter.toString()); 15312 mIntentFilterVerifier.addOneIntentFilterVerification( 15313 verifierUid, userId, verificationId, filter, packageName); 15314 count++; 15315 } 15316 } 15317 } 15318 } 15319 } 15320 15321 if (count > 0) { 15322 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15323 + " IntentFilter verification" + (count > 1 ? "s" : "") 15324 + " for userId:" + userId); 15325 mIntentFilterVerifier.startVerifications(userId); 15326 } else { 15327 if (DEBUG_DOMAIN_VERIFICATION) { 15328 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15329 } 15330 } 15331 } 15332 15333 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15334 final ComponentName cn = filter.activity.getComponentName(); 15335 final String packageName = cn.getPackageName(); 15336 15337 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15338 packageName); 15339 if (ivi == null) { 15340 return true; 15341 } 15342 int status = ivi.getStatus(); 15343 switch (status) { 15344 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15345 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15346 return true; 15347 15348 default: 15349 // Nothing to do 15350 return false; 15351 } 15352 } 15353 15354 private static boolean isMultiArch(ApplicationInfo info) { 15355 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15356 } 15357 15358 private static boolean isExternal(PackageParser.Package pkg) { 15359 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15360 } 15361 15362 private static boolean isExternal(PackageSetting ps) { 15363 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15364 } 15365 15366 private static boolean isEphemeral(PackageParser.Package pkg) { 15367 return pkg.applicationInfo.isEphemeralApp(); 15368 } 15369 15370 private static boolean isEphemeral(PackageSetting ps) { 15371 return ps.pkg != null && isEphemeral(ps.pkg); 15372 } 15373 15374 private static boolean isSystemApp(PackageParser.Package pkg) { 15375 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15376 } 15377 15378 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15379 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15380 } 15381 15382 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15383 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15384 } 15385 15386 private static boolean isSystemApp(PackageSetting ps) { 15387 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15388 } 15389 15390 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15391 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15392 } 15393 15394 private int packageFlagsToInstallFlags(PackageSetting ps) { 15395 int installFlags = 0; 15396 if (isEphemeral(ps)) { 15397 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15398 } 15399 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15400 // This existing package was an external ASEC install when we have 15401 // the external flag without a UUID 15402 installFlags |= PackageManager.INSTALL_EXTERNAL; 15403 } 15404 if (ps.isForwardLocked()) { 15405 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15406 } 15407 return installFlags; 15408 } 15409 15410 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15411 if (isExternal(pkg)) { 15412 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15413 return StorageManager.UUID_PRIMARY_PHYSICAL; 15414 } else { 15415 return pkg.volumeUuid; 15416 } 15417 } else { 15418 return StorageManager.UUID_PRIVATE_INTERNAL; 15419 } 15420 } 15421 15422 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15423 if (isExternal(pkg)) { 15424 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15425 return mSettings.getExternalVersion(); 15426 } else { 15427 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15428 } 15429 } else { 15430 return mSettings.getInternalVersion(); 15431 } 15432 } 15433 15434 private void deleteTempPackageFiles() { 15435 final FilenameFilter filter = new FilenameFilter() { 15436 public boolean accept(File dir, String name) { 15437 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15438 } 15439 }; 15440 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15441 file.delete(); 15442 } 15443 } 15444 15445 @Override 15446 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15447 int flags) { 15448 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15449 flags); 15450 } 15451 15452 @Override 15453 public void deletePackage(final String packageName, 15454 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15455 mContext.enforceCallingOrSelfPermission( 15456 android.Manifest.permission.DELETE_PACKAGES, null); 15457 Preconditions.checkNotNull(packageName); 15458 Preconditions.checkNotNull(observer); 15459 final int uid = Binder.getCallingUid(); 15460 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15461 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15462 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15463 mContext.enforceCallingOrSelfPermission( 15464 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15465 "deletePackage for user " + userId); 15466 } 15467 15468 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15469 try { 15470 observer.onPackageDeleted(packageName, 15471 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15472 } catch (RemoteException re) { 15473 } 15474 return; 15475 } 15476 15477 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15478 try { 15479 observer.onPackageDeleted(packageName, 15480 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15481 } catch (RemoteException re) { 15482 } 15483 return; 15484 } 15485 15486 if (DEBUG_REMOVE) { 15487 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15488 + " deleteAllUsers: " + deleteAllUsers ); 15489 } 15490 // Queue up an async operation since the package deletion may take a little while. 15491 mHandler.post(new Runnable() { 15492 public void run() { 15493 mHandler.removeCallbacks(this); 15494 int returnCode; 15495 if (!deleteAllUsers) { 15496 returnCode = deletePackageX(packageName, userId, deleteFlags); 15497 } else { 15498 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15499 // If nobody is blocking uninstall, proceed with delete for all users 15500 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15501 returnCode = deletePackageX(packageName, userId, deleteFlags); 15502 } else { 15503 // Otherwise uninstall individually for users with blockUninstalls=false 15504 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15505 for (int userId : users) { 15506 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15507 returnCode = deletePackageX(packageName, userId, userFlags); 15508 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15509 Slog.w(TAG, "Package delete failed for user " + userId 15510 + ", returnCode " + returnCode); 15511 } 15512 } 15513 } 15514 // The app has only been marked uninstalled for certain users. 15515 // We still need to report that delete was blocked 15516 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15517 } 15518 } 15519 try { 15520 observer.onPackageDeleted(packageName, returnCode, null); 15521 } catch (RemoteException e) { 15522 Log.i(TAG, "Observer no longer exists."); 15523 } //end catch 15524 } //end run 15525 }); 15526 } 15527 15528 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15529 int[] result = EMPTY_INT_ARRAY; 15530 for (int userId : userIds) { 15531 if (getBlockUninstallForUser(packageName, userId)) { 15532 result = ArrayUtils.appendInt(result, userId); 15533 } 15534 } 15535 return result; 15536 } 15537 15538 @Override 15539 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15540 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15541 } 15542 15543 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15544 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15545 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15546 try { 15547 if (dpm != null) { 15548 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15549 /* callingUserOnly =*/ false); 15550 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15551 : deviceOwnerComponentName.getPackageName(); 15552 // Does the package contains the device owner? 15553 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15554 // this check is probably not needed, since DO should be registered as a device 15555 // admin on some user too. (Original bug for this: b/17657954) 15556 if (packageName.equals(deviceOwnerPackageName)) { 15557 return true; 15558 } 15559 // Does it contain a device admin for any user? 15560 int[] users; 15561 if (userId == UserHandle.USER_ALL) { 15562 users = sUserManager.getUserIds(); 15563 } else { 15564 users = new int[]{userId}; 15565 } 15566 for (int i = 0; i < users.length; ++i) { 15567 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15568 return true; 15569 } 15570 } 15571 } 15572 } catch (RemoteException e) { 15573 } 15574 return false; 15575 } 15576 15577 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15578 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15579 } 15580 15581 /** 15582 * This method is an internal method that could be get invoked either 15583 * to delete an installed package or to clean up a failed installation. 15584 * After deleting an installed package, a broadcast is sent to notify any 15585 * listeners that the package has been removed. For cleaning up a failed 15586 * installation, the broadcast is not necessary since the package's 15587 * installation wouldn't have sent the initial broadcast either 15588 * The key steps in deleting a package are 15589 * deleting the package information in internal structures like mPackages, 15590 * deleting the packages base directories through installd 15591 * updating mSettings to reflect current status 15592 * persisting settings for later use 15593 * sending a broadcast if necessary 15594 */ 15595 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15596 final PackageRemovedInfo info = new PackageRemovedInfo(); 15597 final boolean res; 15598 15599 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15600 ? UserHandle.ALL : new UserHandle(userId); 15601 15602 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15603 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15604 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15605 } 15606 15607 PackageSetting uninstalledPs = null; 15608 15609 // for the uninstall-updates case and restricted profiles, remember the per- 15610 // user handle installed state 15611 int[] allUsers; 15612 synchronized (mPackages) { 15613 uninstalledPs = mSettings.mPackages.get(packageName); 15614 if (uninstalledPs == null) { 15615 Slog.w(TAG, "Not removing non-existent package " + packageName); 15616 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15617 } 15618 allUsers = sUserManager.getUserIds(); 15619 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15620 } 15621 15622 synchronized (mInstallLock) { 15623 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15624 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15625 "deletePackageX")) { 15626 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15627 deleteFlags | REMOVE_CHATTY, info, true, null); 15628 } 15629 synchronized (mPackages) { 15630 if (res) { 15631 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15632 } 15633 } 15634 } 15635 15636 if (res) { 15637 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15638 info.sendPackageRemovedBroadcasts(killApp); 15639 info.sendSystemPackageUpdatedBroadcasts(); 15640 info.sendSystemPackageAppearedBroadcasts(); 15641 } 15642 // Force a gc here. 15643 Runtime.getRuntime().gc(); 15644 // Delete the resources here after sending the broadcast to let 15645 // other processes clean up before deleting resources. 15646 if (info.args != null) { 15647 synchronized (mInstallLock) { 15648 info.args.doPostDeleteLI(true); 15649 } 15650 } 15651 15652 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15653 } 15654 15655 class PackageRemovedInfo { 15656 String removedPackage; 15657 int uid = -1; 15658 int removedAppId = -1; 15659 int[] origUsers; 15660 int[] removedUsers = null; 15661 boolean isRemovedPackageSystemUpdate = false; 15662 boolean isUpdate; 15663 boolean dataRemoved; 15664 boolean removedForAllUsers; 15665 // Clean up resources deleted packages. 15666 InstallArgs args = null; 15667 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15668 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15669 15670 void sendPackageRemovedBroadcasts(boolean killApp) { 15671 sendPackageRemovedBroadcastInternal(killApp); 15672 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15673 for (int i = 0; i < childCount; i++) { 15674 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15675 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15676 } 15677 } 15678 15679 void sendSystemPackageUpdatedBroadcasts() { 15680 if (isRemovedPackageSystemUpdate) { 15681 sendSystemPackageUpdatedBroadcastsInternal(); 15682 final int childCount = (removedChildPackages != null) 15683 ? removedChildPackages.size() : 0; 15684 for (int i = 0; i < childCount; i++) { 15685 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15686 if (childInfo.isRemovedPackageSystemUpdate) { 15687 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15688 } 15689 } 15690 } 15691 } 15692 15693 void sendSystemPackageAppearedBroadcasts() { 15694 final int packageCount = (appearedChildPackages != null) 15695 ? appearedChildPackages.size() : 0; 15696 for (int i = 0; i < packageCount; i++) { 15697 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15698 for (int userId : installedInfo.newUsers) { 15699 sendPackageAddedForUser(installedInfo.name, true, 15700 UserHandle.getAppId(installedInfo.uid), userId); 15701 } 15702 } 15703 } 15704 15705 private void sendSystemPackageUpdatedBroadcastsInternal() { 15706 Bundle extras = new Bundle(2); 15707 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15708 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15709 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15710 extras, 0, null, null, null); 15711 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15712 extras, 0, null, null, null); 15713 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15714 null, 0, removedPackage, null, null); 15715 } 15716 15717 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15718 Bundle extras = new Bundle(2); 15719 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15720 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15721 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15722 if (isUpdate || isRemovedPackageSystemUpdate) { 15723 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15724 } 15725 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15726 if (removedPackage != null) { 15727 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15728 extras, 0, null, null, removedUsers); 15729 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15730 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15731 removedPackage, extras, 0, null, null, removedUsers); 15732 } 15733 } 15734 if (removedAppId >= 0) { 15735 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15736 removedUsers); 15737 } 15738 } 15739 } 15740 15741 /* 15742 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15743 * flag is not set, the data directory is removed as well. 15744 * make sure this flag is set for partially installed apps. If not its meaningless to 15745 * delete a partially installed application. 15746 */ 15747 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15748 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15749 String packageName = ps.name; 15750 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15751 // Retrieve object to delete permissions for shared user later on 15752 final PackageParser.Package deletedPkg; 15753 final PackageSetting deletedPs; 15754 // reader 15755 synchronized (mPackages) { 15756 deletedPkg = mPackages.get(packageName); 15757 deletedPs = mSettings.mPackages.get(packageName); 15758 if (outInfo != null) { 15759 outInfo.removedPackage = packageName; 15760 outInfo.removedUsers = deletedPs != null 15761 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15762 : null; 15763 } 15764 } 15765 15766 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15767 15768 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15769 final PackageParser.Package resolvedPkg; 15770 if (deletedPkg != null) { 15771 resolvedPkg = deletedPkg; 15772 } else { 15773 // We don't have a parsed package when it lives on an ejected 15774 // adopted storage device, so fake something together 15775 resolvedPkg = new PackageParser.Package(ps.name); 15776 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15777 } 15778 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15779 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15780 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15781 if (outInfo != null) { 15782 outInfo.dataRemoved = true; 15783 } 15784 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15785 } 15786 15787 // writer 15788 synchronized (mPackages) { 15789 if (deletedPs != null) { 15790 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15791 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15792 clearDefaultBrowserIfNeeded(packageName); 15793 if (outInfo != null) { 15794 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15795 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15796 } 15797 updatePermissionsLPw(deletedPs.name, null, 0); 15798 if (deletedPs.sharedUser != null) { 15799 // Remove permissions associated with package. Since runtime 15800 // permissions are per user we have to kill the removed package 15801 // or packages running under the shared user of the removed 15802 // package if revoking the permissions requested only by the removed 15803 // package is successful and this causes a change in gids. 15804 for (int userId : UserManagerService.getInstance().getUserIds()) { 15805 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15806 userId); 15807 if (userIdToKill == UserHandle.USER_ALL 15808 || userIdToKill >= UserHandle.USER_SYSTEM) { 15809 // If gids changed for this user, kill all affected packages. 15810 mHandler.post(new Runnable() { 15811 @Override 15812 public void run() { 15813 // This has to happen with no lock held. 15814 killApplication(deletedPs.name, deletedPs.appId, 15815 KILL_APP_REASON_GIDS_CHANGED); 15816 } 15817 }); 15818 break; 15819 } 15820 } 15821 } 15822 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15823 } 15824 // make sure to preserve per-user disabled state if this removal was just 15825 // a downgrade of a system app to the factory package 15826 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15827 if (DEBUG_REMOVE) { 15828 Slog.d(TAG, "Propagating install state across downgrade"); 15829 } 15830 for (int userId : allUserHandles) { 15831 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15832 if (DEBUG_REMOVE) { 15833 Slog.d(TAG, " user " + userId + " => " + installed); 15834 } 15835 ps.setInstalled(installed, userId); 15836 } 15837 } 15838 } 15839 // can downgrade to reader 15840 if (writeSettings) { 15841 // Save settings now 15842 mSettings.writeLPr(); 15843 } 15844 } 15845 if (outInfo != null) { 15846 // A user ID was deleted here. Go through all users and remove it 15847 // from KeyStore. 15848 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15849 } 15850 } 15851 15852 static boolean locationIsPrivileged(File path) { 15853 try { 15854 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15855 .getCanonicalPath(); 15856 return path.getCanonicalPath().startsWith(privilegedAppDir); 15857 } catch (IOException e) { 15858 Slog.e(TAG, "Unable to access code path " + path); 15859 } 15860 return false; 15861 } 15862 15863 /* 15864 * Tries to delete system package. 15865 */ 15866 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15867 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15868 boolean writeSettings) { 15869 if (deletedPs.parentPackageName != null) { 15870 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15871 return false; 15872 } 15873 15874 final boolean applyUserRestrictions 15875 = (allUserHandles != null) && (outInfo.origUsers != null); 15876 final PackageSetting disabledPs; 15877 // Confirm if the system package has been updated 15878 // An updated system app can be deleted. This will also have to restore 15879 // the system pkg from system partition 15880 // reader 15881 synchronized (mPackages) { 15882 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15883 } 15884 15885 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15886 + " disabledPs=" + disabledPs); 15887 15888 if (disabledPs == null) { 15889 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15890 return false; 15891 } else if (DEBUG_REMOVE) { 15892 Slog.d(TAG, "Deleting system pkg from data partition"); 15893 } 15894 15895 if (DEBUG_REMOVE) { 15896 if (applyUserRestrictions) { 15897 Slog.d(TAG, "Remembering install states:"); 15898 for (int userId : allUserHandles) { 15899 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15900 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15901 } 15902 } 15903 } 15904 15905 // Delete the updated package 15906 outInfo.isRemovedPackageSystemUpdate = true; 15907 if (outInfo.removedChildPackages != null) { 15908 final int childCount = (deletedPs.childPackageNames != null) 15909 ? deletedPs.childPackageNames.size() : 0; 15910 for (int i = 0; i < childCount; i++) { 15911 String childPackageName = deletedPs.childPackageNames.get(i); 15912 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15913 .contains(childPackageName)) { 15914 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15915 childPackageName); 15916 if (childInfo != null) { 15917 childInfo.isRemovedPackageSystemUpdate = true; 15918 } 15919 } 15920 } 15921 } 15922 15923 if (disabledPs.versionCode < deletedPs.versionCode) { 15924 // Delete data for downgrades 15925 flags &= ~PackageManager.DELETE_KEEP_DATA; 15926 } else { 15927 // Preserve data by setting flag 15928 flags |= PackageManager.DELETE_KEEP_DATA; 15929 } 15930 15931 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15932 outInfo, writeSettings, disabledPs.pkg); 15933 if (!ret) { 15934 return false; 15935 } 15936 15937 // writer 15938 synchronized (mPackages) { 15939 // Reinstate the old system package 15940 enableSystemPackageLPw(disabledPs.pkg); 15941 // Remove any native libraries from the upgraded package. 15942 removeNativeBinariesLI(deletedPs); 15943 } 15944 15945 // Install the system package 15946 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15947 int parseFlags = mDefParseFlags 15948 | PackageParser.PARSE_MUST_BE_APK 15949 | PackageParser.PARSE_IS_SYSTEM 15950 | PackageParser.PARSE_IS_SYSTEM_DIR; 15951 if (locationIsPrivileged(disabledPs.codePath)) { 15952 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15953 } 15954 15955 final PackageParser.Package newPkg; 15956 try { 15957 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15958 } catch (PackageManagerException e) { 15959 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15960 + e.getMessage()); 15961 return false; 15962 } 15963 15964 prepareAppDataAfterInstallLIF(newPkg); 15965 15966 // writer 15967 synchronized (mPackages) { 15968 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15969 15970 // Propagate the permissions state as we do not want to drop on the floor 15971 // runtime permissions. The update permissions method below will take 15972 // care of removing obsolete permissions and grant install permissions. 15973 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15974 updatePermissionsLPw(newPkg.packageName, newPkg, 15975 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15976 15977 if (applyUserRestrictions) { 15978 if (DEBUG_REMOVE) { 15979 Slog.d(TAG, "Propagating install state across reinstall"); 15980 } 15981 for (int userId : allUserHandles) { 15982 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15983 if (DEBUG_REMOVE) { 15984 Slog.d(TAG, " user " + userId + " => " + installed); 15985 } 15986 ps.setInstalled(installed, userId); 15987 15988 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15989 } 15990 // Regardless of writeSettings we need to ensure that this restriction 15991 // state propagation is persisted 15992 mSettings.writeAllUsersPackageRestrictionsLPr(); 15993 } 15994 // can downgrade to reader here 15995 if (writeSettings) { 15996 mSettings.writeLPr(); 15997 } 15998 } 15999 return true; 16000 } 16001 16002 private boolean deleteInstalledPackageLIF(PackageSetting ps, 16003 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 16004 PackageRemovedInfo outInfo, boolean writeSettings, 16005 PackageParser.Package replacingPackage) { 16006 synchronized (mPackages) { 16007 if (outInfo != null) { 16008 outInfo.uid = ps.appId; 16009 } 16010 16011 if (outInfo != null && outInfo.removedChildPackages != null) { 16012 final int childCount = (ps.childPackageNames != null) 16013 ? ps.childPackageNames.size() : 0; 16014 for (int i = 0; i < childCount; i++) { 16015 String childPackageName = ps.childPackageNames.get(i); 16016 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 16017 if (childPs == null) { 16018 return false; 16019 } 16020 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 16021 childPackageName); 16022 if (childInfo != null) { 16023 childInfo.uid = childPs.appId; 16024 } 16025 } 16026 } 16027 } 16028 16029 // Delete package data from internal structures and also remove data if flag is set 16030 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 16031 16032 // Delete the child packages data 16033 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 16034 for (int i = 0; i < childCount; i++) { 16035 PackageSetting childPs; 16036 synchronized (mPackages) { 16037 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16038 } 16039 if (childPs != null) { 16040 PackageRemovedInfo childOutInfo = (outInfo != null 16041 && outInfo.removedChildPackages != null) 16042 ? outInfo.removedChildPackages.get(childPs.name) : null; 16043 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16044 && (replacingPackage != null 16045 && !replacingPackage.hasChildPackage(childPs.name)) 16046 ? flags & ~DELETE_KEEP_DATA : flags; 16047 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16048 deleteFlags, writeSettings); 16049 } 16050 } 16051 16052 // Delete application code and resources only for parent packages 16053 if (ps.parentPackageName == null) { 16054 if (deleteCodeAndResources && (outInfo != null)) { 16055 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16056 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16057 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16058 } 16059 } 16060 16061 return true; 16062 } 16063 16064 @Override 16065 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16066 int userId) { 16067 mContext.enforceCallingOrSelfPermission( 16068 android.Manifest.permission.DELETE_PACKAGES, null); 16069 synchronized (mPackages) { 16070 PackageSetting ps = mSettings.mPackages.get(packageName); 16071 if (ps == null) { 16072 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16073 return false; 16074 } 16075 if (!ps.getInstalled(userId)) { 16076 // Can't block uninstall for an app that is not installed or enabled. 16077 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16078 return false; 16079 } 16080 ps.setBlockUninstall(blockUninstall, userId); 16081 mSettings.writePackageRestrictionsLPr(userId); 16082 } 16083 return true; 16084 } 16085 16086 @Override 16087 public boolean getBlockUninstallForUser(String packageName, int userId) { 16088 synchronized (mPackages) { 16089 PackageSetting ps = mSettings.mPackages.get(packageName); 16090 if (ps == null) { 16091 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16092 return false; 16093 } 16094 return ps.getBlockUninstall(userId); 16095 } 16096 } 16097 16098 @Override 16099 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16100 int callingUid = Binder.getCallingUid(); 16101 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16102 throw new SecurityException( 16103 "setRequiredForSystemUser can only be run by the system or root"); 16104 } 16105 synchronized (mPackages) { 16106 PackageSetting ps = mSettings.mPackages.get(packageName); 16107 if (ps == null) { 16108 Log.w(TAG, "Package doesn't exist: " + packageName); 16109 return false; 16110 } 16111 if (systemUserApp) { 16112 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16113 } else { 16114 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16115 } 16116 mSettings.writeLPr(); 16117 } 16118 return true; 16119 } 16120 16121 /* 16122 * This method handles package deletion in general 16123 */ 16124 private boolean deletePackageLIF(String packageName, UserHandle user, 16125 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16126 PackageRemovedInfo outInfo, boolean writeSettings, 16127 PackageParser.Package replacingPackage) { 16128 if (packageName == null) { 16129 Slog.w(TAG, "Attempt to delete null packageName."); 16130 return false; 16131 } 16132 16133 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16134 16135 PackageSetting ps; 16136 16137 synchronized (mPackages) { 16138 ps = mSettings.mPackages.get(packageName); 16139 if (ps == null) { 16140 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16141 return false; 16142 } 16143 16144 if (ps.parentPackageName != null && (!isSystemApp(ps) 16145 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16146 if (DEBUG_REMOVE) { 16147 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16148 + ((user == null) ? UserHandle.USER_ALL : user)); 16149 } 16150 final int removedUserId = (user != null) ? user.getIdentifier() 16151 : UserHandle.USER_ALL; 16152 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16153 return false; 16154 } 16155 markPackageUninstalledForUserLPw(ps, user); 16156 scheduleWritePackageRestrictionsLocked(user); 16157 return true; 16158 } 16159 } 16160 16161 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16162 && user.getIdentifier() != UserHandle.USER_ALL)) { 16163 // The caller is asking that the package only be deleted for a single 16164 // user. To do this, we just mark its uninstalled state and delete 16165 // its data. If this is a system app, we only allow this to happen if 16166 // they have set the special DELETE_SYSTEM_APP which requests different 16167 // semantics than normal for uninstalling system apps. 16168 markPackageUninstalledForUserLPw(ps, user); 16169 16170 if (!isSystemApp(ps)) { 16171 // Do not uninstall the APK if an app should be cached 16172 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16173 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16174 // Other user still have this package installed, so all 16175 // we need to do is clear this user's data and save that 16176 // it is uninstalled. 16177 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16178 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16179 return false; 16180 } 16181 scheduleWritePackageRestrictionsLocked(user); 16182 return true; 16183 } else { 16184 // We need to set it back to 'installed' so the uninstall 16185 // broadcasts will be sent correctly. 16186 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16187 ps.setInstalled(true, user.getIdentifier()); 16188 } 16189 } else { 16190 // This is a system app, so we assume that the 16191 // other users still have this package installed, so all 16192 // we need to do is clear this user's data and save that 16193 // it is uninstalled. 16194 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16195 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16196 return false; 16197 } 16198 scheduleWritePackageRestrictionsLocked(user); 16199 return true; 16200 } 16201 } 16202 16203 // If we are deleting a composite package for all users, keep track 16204 // of result for each child. 16205 if (ps.childPackageNames != null && outInfo != null) { 16206 synchronized (mPackages) { 16207 final int childCount = ps.childPackageNames.size(); 16208 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16209 for (int i = 0; i < childCount; i++) { 16210 String childPackageName = ps.childPackageNames.get(i); 16211 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16212 childInfo.removedPackage = childPackageName; 16213 outInfo.removedChildPackages.put(childPackageName, childInfo); 16214 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16215 if (childPs != null) { 16216 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16217 } 16218 } 16219 } 16220 } 16221 16222 boolean ret = false; 16223 if (isSystemApp(ps)) { 16224 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16225 // When an updated system application is deleted we delete the existing resources 16226 // as well and fall back to existing code in system partition 16227 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16228 } else { 16229 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16230 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16231 outInfo, writeSettings, replacingPackage); 16232 } 16233 16234 // Take a note whether we deleted the package for all users 16235 if (outInfo != null) { 16236 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16237 if (outInfo.removedChildPackages != null) { 16238 synchronized (mPackages) { 16239 final int childCount = outInfo.removedChildPackages.size(); 16240 for (int i = 0; i < childCount; i++) { 16241 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16242 if (childInfo != null) { 16243 childInfo.removedForAllUsers = mPackages.get( 16244 childInfo.removedPackage) == null; 16245 } 16246 } 16247 } 16248 } 16249 // If we uninstalled an update to a system app there may be some 16250 // child packages that appeared as they are declared in the system 16251 // app but were not declared in the update. 16252 if (isSystemApp(ps)) { 16253 synchronized (mPackages) { 16254 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16255 final int childCount = (updatedPs.childPackageNames != null) 16256 ? updatedPs.childPackageNames.size() : 0; 16257 for (int i = 0; i < childCount; i++) { 16258 String childPackageName = updatedPs.childPackageNames.get(i); 16259 if (outInfo.removedChildPackages == null 16260 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16261 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16262 if (childPs == null) { 16263 continue; 16264 } 16265 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16266 installRes.name = childPackageName; 16267 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16268 installRes.pkg = mPackages.get(childPackageName); 16269 installRes.uid = childPs.pkg.applicationInfo.uid; 16270 if (outInfo.appearedChildPackages == null) { 16271 outInfo.appearedChildPackages = new ArrayMap<>(); 16272 } 16273 outInfo.appearedChildPackages.put(childPackageName, installRes); 16274 } 16275 } 16276 } 16277 } 16278 } 16279 16280 return ret; 16281 } 16282 16283 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16284 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16285 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16286 for (int nextUserId : userIds) { 16287 if (DEBUG_REMOVE) { 16288 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16289 } 16290 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16291 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16292 false /*hidden*/, false /*suspended*/, null, null, null, 16293 false /*blockUninstall*/, 16294 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16295 } 16296 } 16297 16298 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16299 PackageRemovedInfo outInfo) { 16300 final PackageParser.Package pkg; 16301 synchronized (mPackages) { 16302 pkg = mPackages.get(ps.name); 16303 } 16304 16305 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16306 : new int[] {userId}; 16307 for (int nextUserId : userIds) { 16308 if (DEBUG_REMOVE) { 16309 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16310 + nextUserId); 16311 } 16312 16313 destroyAppDataLIF(pkg, userId, 16314 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16315 destroyAppProfilesLIF(pkg, userId); 16316 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16317 schedulePackageCleaning(ps.name, nextUserId, false); 16318 synchronized (mPackages) { 16319 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16320 scheduleWritePackageRestrictionsLocked(nextUserId); 16321 } 16322 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16323 } 16324 } 16325 16326 if (outInfo != null) { 16327 outInfo.removedPackage = ps.name; 16328 outInfo.removedAppId = ps.appId; 16329 outInfo.removedUsers = userIds; 16330 } 16331 16332 return true; 16333 } 16334 16335 private final class ClearStorageConnection implements ServiceConnection { 16336 IMediaContainerService mContainerService; 16337 16338 @Override 16339 public void onServiceConnected(ComponentName name, IBinder service) { 16340 synchronized (this) { 16341 mContainerService = IMediaContainerService.Stub.asInterface(service); 16342 notifyAll(); 16343 } 16344 } 16345 16346 @Override 16347 public void onServiceDisconnected(ComponentName name) { 16348 } 16349 } 16350 16351 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16352 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16353 16354 final boolean mounted; 16355 if (Environment.isExternalStorageEmulated()) { 16356 mounted = true; 16357 } else { 16358 final String status = Environment.getExternalStorageState(); 16359 16360 mounted = status.equals(Environment.MEDIA_MOUNTED) 16361 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16362 } 16363 16364 if (!mounted) { 16365 return; 16366 } 16367 16368 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16369 int[] users; 16370 if (userId == UserHandle.USER_ALL) { 16371 users = sUserManager.getUserIds(); 16372 } else { 16373 users = new int[] { userId }; 16374 } 16375 final ClearStorageConnection conn = new ClearStorageConnection(); 16376 if (mContext.bindServiceAsUser( 16377 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16378 try { 16379 for (int curUser : users) { 16380 long timeout = SystemClock.uptimeMillis() + 5000; 16381 synchronized (conn) { 16382 long now; 16383 while (conn.mContainerService == null && 16384 (now = SystemClock.uptimeMillis()) < timeout) { 16385 try { 16386 conn.wait(timeout - now); 16387 } catch (InterruptedException e) { 16388 } 16389 } 16390 } 16391 if (conn.mContainerService == null) { 16392 return; 16393 } 16394 16395 final UserEnvironment userEnv = new UserEnvironment(curUser); 16396 clearDirectory(conn.mContainerService, 16397 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16398 if (allData) { 16399 clearDirectory(conn.mContainerService, 16400 userEnv.buildExternalStorageAppDataDirs(packageName)); 16401 clearDirectory(conn.mContainerService, 16402 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16403 } 16404 } 16405 } finally { 16406 mContext.unbindService(conn); 16407 } 16408 } 16409 } 16410 16411 @Override 16412 public void clearApplicationProfileData(String packageName) { 16413 enforceSystemOrRoot("Only the system can clear all profile data"); 16414 16415 final PackageParser.Package pkg; 16416 synchronized (mPackages) { 16417 pkg = mPackages.get(packageName); 16418 } 16419 16420 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16421 synchronized (mInstallLock) { 16422 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16423 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16424 true /* removeBaseMarker */); 16425 } 16426 } 16427 } 16428 16429 @Override 16430 public void clearApplicationUserData(final String packageName, 16431 final IPackageDataObserver observer, final int userId) { 16432 mContext.enforceCallingOrSelfPermission( 16433 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16434 16435 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16436 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16437 16438 if (mProtectedPackages.canPackageBeWiped(userId, packageName)) { 16439 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16440 } 16441 // Queue up an async operation since the package deletion may take a little while. 16442 mHandler.post(new Runnable() { 16443 public void run() { 16444 mHandler.removeCallbacks(this); 16445 final boolean succeeded; 16446 try (PackageFreezer freezer = freezePackage(packageName, 16447 "clearApplicationUserData")) { 16448 synchronized (mInstallLock) { 16449 succeeded = clearApplicationUserDataLIF(packageName, userId); 16450 } 16451 clearExternalStorageDataSync(packageName, userId, true); 16452 } 16453 if (succeeded) { 16454 // invoke DeviceStorageMonitor's update method to clear any notifications 16455 DeviceStorageMonitorInternal dsm = LocalServices 16456 .getService(DeviceStorageMonitorInternal.class); 16457 if (dsm != null) { 16458 dsm.checkMemory(); 16459 } 16460 } 16461 if(observer != null) { 16462 try { 16463 observer.onRemoveCompleted(packageName, succeeded); 16464 } catch (RemoteException e) { 16465 Log.i(TAG, "Observer no longer exists."); 16466 } 16467 } //end if observer 16468 } //end run 16469 }); 16470 } 16471 16472 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16473 if (packageName == null) { 16474 Slog.w(TAG, "Attempt to delete null packageName."); 16475 return false; 16476 } 16477 16478 // Try finding details about the requested package 16479 PackageParser.Package pkg; 16480 synchronized (mPackages) { 16481 pkg = mPackages.get(packageName); 16482 if (pkg == null) { 16483 final PackageSetting ps = mSettings.mPackages.get(packageName); 16484 if (ps != null) { 16485 pkg = ps.pkg; 16486 } 16487 } 16488 16489 if (pkg == null) { 16490 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16491 return false; 16492 } 16493 16494 PackageSetting ps = (PackageSetting) pkg.mExtras; 16495 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16496 } 16497 16498 clearAppDataLIF(pkg, userId, 16499 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16500 16501 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16502 removeKeystoreDataIfNeeded(userId, appId); 16503 16504 UserManagerInternal umInternal = getUserManagerInternal(); 16505 final int flags; 16506 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16507 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16508 } else if (umInternal.isUserRunning(userId)) { 16509 flags = StorageManager.FLAG_STORAGE_DE; 16510 } else { 16511 flags = 0; 16512 } 16513 prepareAppDataContentsLIF(pkg, userId, flags); 16514 16515 return true; 16516 } 16517 16518 /** 16519 * Reverts user permission state changes (permissions and flags) in 16520 * all packages for a given user. 16521 * 16522 * @param userId The device user for which to do a reset. 16523 */ 16524 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16525 final int packageCount = mPackages.size(); 16526 for (int i = 0; i < packageCount; i++) { 16527 PackageParser.Package pkg = mPackages.valueAt(i); 16528 PackageSetting ps = (PackageSetting) pkg.mExtras; 16529 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16530 } 16531 } 16532 16533 private void resetNetworkPolicies(int userId) { 16534 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16535 } 16536 16537 /** 16538 * Reverts user permission state changes (permissions and flags). 16539 * 16540 * @param ps The package for which to reset. 16541 * @param userId The device user for which to do a reset. 16542 */ 16543 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16544 final PackageSetting ps, final int userId) { 16545 if (ps.pkg == null) { 16546 return; 16547 } 16548 16549 // These are flags that can change base on user actions. 16550 final int userSettableMask = FLAG_PERMISSION_USER_SET 16551 | FLAG_PERMISSION_USER_FIXED 16552 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16553 | FLAG_PERMISSION_REVIEW_REQUIRED; 16554 16555 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16556 | FLAG_PERMISSION_POLICY_FIXED; 16557 16558 boolean writeInstallPermissions = false; 16559 boolean writeRuntimePermissions = false; 16560 16561 final int permissionCount = ps.pkg.requestedPermissions.size(); 16562 for (int i = 0; i < permissionCount; i++) { 16563 String permission = ps.pkg.requestedPermissions.get(i); 16564 16565 BasePermission bp = mSettings.mPermissions.get(permission); 16566 if (bp == null) { 16567 continue; 16568 } 16569 16570 // If shared user we just reset the state to which only this app contributed. 16571 if (ps.sharedUser != null) { 16572 boolean used = false; 16573 final int packageCount = ps.sharedUser.packages.size(); 16574 for (int j = 0; j < packageCount; j++) { 16575 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16576 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16577 && pkg.pkg.requestedPermissions.contains(permission)) { 16578 used = true; 16579 break; 16580 } 16581 } 16582 if (used) { 16583 continue; 16584 } 16585 } 16586 16587 PermissionsState permissionsState = ps.getPermissionsState(); 16588 16589 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16590 16591 // Always clear the user settable flags. 16592 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16593 bp.name) != null; 16594 // If permission review is enabled and this is a legacy app, mark the 16595 // permission as requiring a review as this is the initial state. 16596 int flags = 0; 16597 if (Build.PERMISSIONS_REVIEW_REQUIRED 16598 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16599 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16600 } 16601 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16602 if (hasInstallState) { 16603 writeInstallPermissions = true; 16604 } else { 16605 writeRuntimePermissions = true; 16606 } 16607 } 16608 16609 // Below is only runtime permission handling. 16610 if (!bp.isRuntime()) { 16611 continue; 16612 } 16613 16614 // Never clobber system or policy. 16615 if ((oldFlags & policyOrSystemFlags) != 0) { 16616 continue; 16617 } 16618 16619 // If this permission was granted by default, make sure it is. 16620 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16621 if (permissionsState.grantRuntimePermission(bp, userId) 16622 != PERMISSION_OPERATION_FAILURE) { 16623 writeRuntimePermissions = true; 16624 } 16625 // If permission review is enabled the permissions for a legacy apps 16626 // are represented as constantly granted runtime ones, so don't revoke. 16627 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16628 // Otherwise, reset the permission. 16629 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16630 switch (revokeResult) { 16631 case PERMISSION_OPERATION_SUCCESS: 16632 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16633 writeRuntimePermissions = true; 16634 final int appId = ps.appId; 16635 mHandler.post(new Runnable() { 16636 @Override 16637 public void run() { 16638 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16639 } 16640 }); 16641 } break; 16642 } 16643 } 16644 } 16645 16646 // Synchronously write as we are taking permissions away. 16647 if (writeRuntimePermissions) { 16648 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16649 } 16650 16651 // Synchronously write as we are taking permissions away. 16652 if (writeInstallPermissions) { 16653 mSettings.writeLPr(); 16654 } 16655 } 16656 16657 /** 16658 * Remove entries from the keystore daemon. Will only remove it if the 16659 * {@code appId} is valid. 16660 */ 16661 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16662 if (appId < 0) { 16663 return; 16664 } 16665 16666 final KeyStore keyStore = KeyStore.getInstance(); 16667 if (keyStore != null) { 16668 if (userId == UserHandle.USER_ALL) { 16669 for (final int individual : sUserManager.getUserIds()) { 16670 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16671 } 16672 } else { 16673 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16674 } 16675 } else { 16676 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16677 } 16678 } 16679 16680 @Override 16681 public void deleteApplicationCacheFiles(final String packageName, 16682 final IPackageDataObserver observer) { 16683 final int userId = UserHandle.getCallingUserId(); 16684 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16685 } 16686 16687 @Override 16688 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16689 final IPackageDataObserver observer) { 16690 mContext.enforceCallingOrSelfPermission( 16691 android.Manifest.permission.DELETE_CACHE_FILES, null); 16692 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16693 /* requireFullPermission= */ true, /* checkShell= */ false, 16694 "delete application cache files"); 16695 16696 final PackageParser.Package pkg; 16697 synchronized (mPackages) { 16698 pkg = mPackages.get(packageName); 16699 } 16700 16701 // Queue up an async operation since the package deletion may take a little while. 16702 mHandler.post(new Runnable() { 16703 public void run() { 16704 synchronized (mInstallLock) { 16705 final int flags = StorageManager.FLAG_STORAGE_DE 16706 | StorageManager.FLAG_STORAGE_CE; 16707 // We're only clearing cache files, so we don't care if the 16708 // app is unfrozen and still able to run 16709 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16710 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16711 } 16712 clearExternalStorageDataSync(packageName, userId, false); 16713 if (observer != null) { 16714 try { 16715 observer.onRemoveCompleted(packageName, true); 16716 } catch (RemoteException e) { 16717 Log.i(TAG, "Observer no longer exists."); 16718 } 16719 } 16720 } 16721 }); 16722 } 16723 16724 @Override 16725 public void getPackageSizeInfo(final String packageName, int userHandle, 16726 final IPackageStatsObserver observer) { 16727 mContext.enforceCallingOrSelfPermission( 16728 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16729 if (packageName == null) { 16730 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16731 } 16732 16733 PackageStats stats = new PackageStats(packageName, userHandle); 16734 16735 /* 16736 * Queue up an async operation since the package measurement may take a 16737 * little while. 16738 */ 16739 Message msg = mHandler.obtainMessage(INIT_COPY); 16740 msg.obj = new MeasureParams(stats, observer); 16741 mHandler.sendMessage(msg); 16742 } 16743 16744 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16745 final PackageSetting ps; 16746 synchronized (mPackages) { 16747 ps = mSettings.mPackages.get(packageName); 16748 if (ps == null) { 16749 Slog.w(TAG, "Failed to find settings for " + packageName); 16750 return false; 16751 } 16752 } 16753 try { 16754 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16755 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16756 ps.getCeDataInode(userId), ps.codePathString, stats); 16757 } catch (InstallerException e) { 16758 Slog.w(TAG, String.valueOf(e)); 16759 return false; 16760 } 16761 16762 // For now, ignore code size of packages on system partition 16763 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16764 stats.codeSize = 0; 16765 } 16766 16767 return true; 16768 } 16769 16770 private int getUidTargetSdkVersionLockedLPr(int uid) { 16771 Object obj = mSettings.getUserIdLPr(uid); 16772 if (obj instanceof SharedUserSetting) { 16773 final SharedUserSetting sus = (SharedUserSetting) obj; 16774 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16775 final Iterator<PackageSetting> it = sus.packages.iterator(); 16776 while (it.hasNext()) { 16777 final PackageSetting ps = it.next(); 16778 if (ps.pkg != null) { 16779 int v = ps.pkg.applicationInfo.targetSdkVersion; 16780 if (v < vers) vers = v; 16781 } 16782 } 16783 return vers; 16784 } else if (obj instanceof PackageSetting) { 16785 final PackageSetting ps = (PackageSetting) obj; 16786 if (ps.pkg != null) { 16787 return ps.pkg.applicationInfo.targetSdkVersion; 16788 } 16789 } 16790 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16791 } 16792 16793 @Override 16794 public void addPreferredActivity(IntentFilter filter, int match, 16795 ComponentName[] set, ComponentName activity, int userId) { 16796 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16797 "Adding preferred"); 16798 } 16799 16800 private void addPreferredActivityInternal(IntentFilter filter, int match, 16801 ComponentName[] set, ComponentName activity, boolean always, int userId, 16802 String opname) { 16803 // writer 16804 int callingUid = Binder.getCallingUid(); 16805 enforceCrossUserPermission(callingUid, userId, 16806 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16807 if (filter.countActions() == 0) { 16808 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16809 return; 16810 } 16811 synchronized (mPackages) { 16812 if (mContext.checkCallingOrSelfPermission( 16813 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16814 != PackageManager.PERMISSION_GRANTED) { 16815 if (getUidTargetSdkVersionLockedLPr(callingUid) 16816 < Build.VERSION_CODES.FROYO) { 16817 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16818 + callingUid); 16819 return; 16820 } 16821 mContext.enforceCallingOrSelfPermission( 16822 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16823 } 16824 16825 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16826 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16827 + userId + ":"); 16828 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16829 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16830 scheduleWritePackageRestrictionsLocked(userId); 16831 } 16832 } 16833 16834 @Override 16835 public void replacePreferredActivity(IntentFilter filter, int match, 16836 ComponentName[] set, ComponentName activity, int userId) { 16837 if (filter.countActions() != 1) { 16838 throw new IllegalArgumentException( 16839 "replacePreferredActivity expects filter to have only 1 action."); 16840 } 16841 if (filter.countDataAuthorities() != 0 16842 || filter.countDataPaths() != 0 16843 || filter.countDataSchemes() > 1 16844 || filter.countDataTypes() != 0) { 16845 throw new IllegalArgumentException( 16846 "replacePreferredActivity expects filter to have no data authorities, " + 16847 "paths, or types; and at most one scheme."); 16848 } 16849 16850 final int callingUid = Binder.getCallingUid(); 16851 enforceCrossUserPermission(callingUid, userId, 16852 true /* requireFullPermission */, false /* checkShell */, 16853 "replace preferred activity"); 16854 synchronized (mPackages) { 16855 if (mContext.checkCallingOrSelfPermission( 16856 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16857 != PackageManager.PERMISSION_GRANTED) { 16858 if (getUidTargetSdkVersionLockedLPr(callingUid) 16859 < Build.VERSION_CODES.FROYO) { 16860 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16861 + Binder.getCallingUid()); 16862 return; 16863 } 16864 mContext.enforceCallingOrSelfPermission( 16865 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16866 } 16867 16868 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16869 if (pir != null) { 16870 // Get all of the existing entries that exactly match this filter. 16871 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16872 if (existing != null && existing.size() == 1) { 16873 PreferredActivity cur = existing.get(0); 16874 if (DEBUG_PREFERRED) { 16875 Slog.i(TAG, "Checking replace of preferred:"); 16876 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16877 if (!cur.mPref.mAlways) { 16878 Slog.i(TAG, " -- CUR; not mAlways!"); 16879 } else { 16880 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16881 Slog.i(TAG, " -- CUR: mSet=" 16882 + Arrays.toString(cur.mPref.mSetComponents)); 16883 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16884 Slog.i(TAG, " -- NEW: mMatch=" 16885 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16886 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16887 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16888 } 16889 } 16890 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16891 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16892 && cur.mPref.sameSet(set)) { 16893 // Setting the preferred activity to what it happens to be already 16894 if (DEBUG_PREFERRED) { 16895 Slog.i(TAG, "Replacing with same preferred activity " 16896 + cur.mPref.mShortComponent + " for user " 16897 + userId + ":"); 16898 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16899 } 16900 return; 16901 } 16902 } 16903 16904 if (existing != null) { 16905 if (DEBUG_PREFERRED) { 16906 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16907 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16908 } 16909 for (int i = 0; i < existing.size(); i++) { 16910 PreferredActivity pa = existing.get(i); 16911 if (DEBUG_PREFERRED) { 16912 Slog.i(TAG, "Removing existing preferred activity " 16913 + pa.mPref.mComponent + ":"); 16914 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16915 } 16916 pir.removeFilter(pa); 16917 } 16918 } 16919 } 16920 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16921 "Replacing preferred"); 16922 } 16923 } 16924 16925 @Override 16926 public void clearPackagePreferredActivities(String packageName) { 16927 final int uid = Binder.getCallingUid(); 16928 // writer 16929 synchronized (mPackages) { 16930 PackageParser.Package pkg = mPackages.get(packageName); 16931 if (pkg == null || pkg.applicationInfo.uid != uid) { 16932 if (mContext.checkCallingOrSelfPermission( 16933 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16934 != PackageManager.PERMISSION_GRANTED) { 16935 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16936 < Build.VERSION_CODES.FROYO) { 16937 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16938 + Binder.getCallingUid()); 16939 return; 16940 } 16941 mContext.enforceCallingOrSelfPermission( 16942 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16943 } 16944 } 16945 16946 int user = UserHandle.getCallingUserId(); 16947 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16948 scheduleWritePackageRestrictionsLocked(user); 16949 } 16950 } 16951 } 16952 16953 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16954 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16955 ArrayList<PreferredActivity> removed = null; 16956 boolean changed = false; 16957 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16958 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16959 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16960 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16961 continue; 16962 } 16963 Iterator<PreferredActivity> it = pir.filterIterator(); 16964 while (it.hasNext()) { 16965 PreferredActivity pa = it.next(); 16966 // Mark entry for removal only if it matches the package name 16967 // and the entry is of type "always". 16968 if (packageName == null || 16969 (pa.mPref.mComponent.getPackageName().equals(packageName) 16970 && pa.mPref.mAlways)) { 16971 if (removed == null) { 16972 removed = new ArrayList<PreferredActivity>(); 16973 } 16974 removed.add(pa); 16975 } 16976 } 16977 if (removed != null) { 16978 for (int j=0; j<removed.size(); j++) { 16979 PreferredActivity pa = removed.get(j); 16980 pir.removeFilter(pa); 16981 } 16982 changed = true; 16983 } 16984 } 16985 return changed; 16986 } 16987 16988 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16989 private void clearIntentFilterVerificationsLPw(int userId) { 16990 final int packageCount = mPackages.size(); 16991 for (int i = 0; i < packageCount; i++) { 16992 PackageParser.Package pkg = mPackages.valueAt(i); 16993 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16994 } 16995 } 16996 16997 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16998 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16999 if (userId == UserHandle.USER_ALL) { 17000 if (mSettings.removeIntentFilterVerificationLPw(packageName, 17001 sUserManager.getUserIds())) { 17002 for (int oneUserId : sUserManager.getUserIds()) { 17003 scheduleWritePackageRestrictionsLocked(oneUserId); 17004 } 17005 } 17006 } else { 17007 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 17008 scheduleWritePackageRestrictionsLocked(userId); 17009 } 17010 } 17011 } 17012 17013 void clearDefaultBrowserIfNeeded(String packageName) { 17014 for (int oneUserId : sUserManager.getUserIds()) { 17015 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 17016 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 17017 if (packageName.equals(defaultBrowserPackageName)) { 17018 setDefaultBrowserPackageName(null, oneUserId); 17019 } 17020 } 17021 } 17022 17023 @Override 17024 public void resetApplicationPreferences(int userId) { 17025 mContext.enforceCallingOrSelfPermission( 17026 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 17027 final long identity = Binder.clearCallingIdentity(); 17028 // writer 17029 try { 17030 synchronized (mPackages) { 17031 clearPackagePreferredActivitiesLPw(null, userId); 17032 mSettings.applyDefaultPreferredAppsLPw(this, userId); 17033 // TODO: We have to reset the default SMS and Phone. This requires 17034 // significant refactoring to keep all default apps in the package 17035 // manager (cleaner but more work) or have the services provide 17036 // callbacks to the package manager to request a default app reset. 17037 applyFactoryDefaultBrowserLPw(userId); 17038 clearIntentFilterVerificationsLPw(userId); 17039 primeDomainVerificationsLPw(userId); 17040 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17041 scheduleWritePackageRestrictionsLocked(userId); 17042 } 17043 resetNetworkPolicies(userId); 17044 } finally { 17045 Binder.restoreCallingIdentity(identity); 17046 } 17047 } 17048 17049 @Override 17050 public int getPreferredActivities(List<IntentFilter> outFilters, 17051 List<ComponentName> outActivities, String packageName) { 17052 17053 int num = 0; 17054 final int userId = UserHandle.getCallingUserId(); 17055 // reader 17056 synchronized (mPackages) { 17057 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17058 if (pir != null) { 17059 final Iterator<PreferredActivity> it = pir.filterIterator(); 17060 while (it.hasNext()) { 17061 final PreferredActivity pa = it.next(); 17062 if (packageName == null 17063 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17064 && pa.mPref.mAlways)) { 17065 if (outFilters != null) { 17066 outFilters.add(new IntentFilter(pa)); 17067 } 17068 if (outActivities != null) { 17069 outActivities.add(pa.mPref.mComponent); 17070 } 17071 } 17072 } 17073 } 17074 } 17075 17076 return num; 17077 } 17078 17079 @Override 17080 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17081 int userId) { 17082 int callingUid = Binder.getCallingUid(); 17083 if (callingUid != Process.SYSTEM_UID) { 17084 throw new SecurityException( 17085 "addPersistentPreferredActivity can only be run by the system"); 17086 } 17087 if (filter.countActions() == 0) { 17088 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17089 return; 17090 } 17091 synchronized (mPackages) { 17092 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17093 ":"); 17094 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17095 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17096 new PersistentPreferredActivity(filter, activity)); 17097 scheduleWritePackageRestrictionsLocked(userId); 17098 } 17099 } 17100 17101 @Override 17102 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17103 int callingUid = Binder.getCallingUid(); 17104 if (callingUid != Process.SYSTEM_UID) { 17105 throw new SecurityException( 17106 "clearPackagePersistentPreferredActivities can only be run by the system"); 17107 } 17108 ArrayList<PersistentPreferredActivity> removed = null; 17109 boolean changed = false; 17110 synchronized (mPackages) { 17111 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17112 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17113 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17114 .valueAt(i); 17115 if (userId != thisUserId) { 17116 continue; 17117 } 17118 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17119 while (it.hasNext()) { 17120 PersistentPreferredActivity ppa = it.next(); 17121 // Mark entry for removal only if it matches the package name. 17122 if (ppa.mComponent.getPackageName().equals(packageName)) { 17123 if (removed == null) { 17124 removed = new ArrayList<PersistentPreferredActivity>(); 17125 } 17126 removed.add(ppa); 17127 } 17128 } 17129 if (removed != null) { 17130 for (int j=0; j<removed.size(); j++) { 17131 PersistentPreferredActivity ppa = removed.get(j); 17132 ppir.removeFilter(ppa); 17133 } 17134 changed = true; 17135 } 17136 } 17137 17138 if (changed) { 17139 scheduleWritePackageRestrictionsLocked(userId); 17140 } 17141 } 17142 } 17143 17144 /** 17145 * Common machinery for picking apart a restored XML blob and passing 17146 * it to a caller-supplied functor to be applied to the running system. 17147 */ 17148 private void restoreFromXml(XmlPullParser parser, int userId, 17149 String expectedStartTag, BlobXmlRestorer functor) 17150 throws IOException, XmlPullParserException { 17151 int type; 17152 while ((type = parser.next()) != XmlPullParser.START_TAG 17153 && type != XmlPullParser.END_DOCUMENT) { 17154 } 17155 if (type != XmlPullParser.START_TAG) { 17156 // oops didn't find a start tag?! 17157 if (DEBUG_BACKUP) { 17158 Slog.e(TAG, "Didn't find start tag during restore"); 17159 } 17160 return; 17161 } 17162Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17163 // this is supposed to be TAG_PREFERRED_BACKUP 17164 if (!expectedStartTag.equals(parser.getName())) { 17165 if (DEBUG_BACKUP) { 17166 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17167 } 17168 return; 17169 } 17170 17171 // skip interfering stuff, then we're aligned with the backing implementation 17172 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17173Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17174 functor.apply(parser, userId); 17175 } 17176 17177 private interface BlobXmlRestorer { 17178 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17179 } 17180 17181 /** 17182 * Non-Binder method, support for the backup/restore mechanism: write the 17183 * full set of preferred activities in its canonical XML format. Returns the 17184 * XML output as a byte array, or null if there is none. 17185 */ 17186 @Override 17187 public byte[] getPreferredActivityBackup(int userId) { 17188 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17189 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17190 } 17191 17192 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17193 try { 17194 final XmlSerializer serializer = new FastXmlSerializer(); 17195 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17196 serializer.startDocument(null, true); 17197 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17198 17199 synchronized (mPackages) { 17200 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17201 } 17202 17203 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17204 serializer.endDocument(); 17205 serializer.flush(); 17206 } catch (Exception e) { 17207 if (DEBUG_BACKUP) { 17208 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17209 } 17210 return null; 17211 } 17212 17213 return dataStream.toByteArray(); 17214 } 17215 17216 @Override 17217 public void restorePreferredActivities(byte[] backup, int userId) { 17218 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17219 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17220 } 17221 17222 try { 17223 final XmlPullParser parser = Xml.newPullParser(); 17224 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17225 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17226 new BlobXmlRestorer() { 17227 @Override 17228 public void apply(XmlPullParser parser, int userId) 17229 throws XmlPullParserException, IOException { 17230 synchronized (mPackages) { 17231 mSettings.readPreferredActivitiesLPw(parser, userId); 17232 } 17233 } 17234 } ); 17235 } catch (Exception e) { 17236 if (DEBUG_BACKUP) { 17237 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17238 } 17239 } 17240 } 17241 17242 /** 17243 * Non-Binder method, support for the backup/restore mechanism: write the 17244 * default browser (etc) settings in its canonical XML format. Returns the default 17245 * browser XML representation as a byte array, or null if there is none. 17246 */ 17247 @Override 17248 public byte[] getDefaultAppsBackup(int userId) { 17249 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17250 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17251 } 17252 17253 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17254 try { 17255 final XmlSerializer serializer = new FastXmlSerializer(); 17256 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17257 serializer.startDocument(null, true); 17258 serializer.startTag(null, TAG_DEFAULT_APPS); 17259 17260 synchronized (mPackages) { 17261 mSettings.writeDefaultAppsLPr(serializer, userId); 17262 } 17263 17264 serializer.endTag(null, TAG_DEFAULT_APPS); 17265 serializer.endDocument(); 17266 serializer.flush(); 17267 } catch (Exception e) { 17268 if (DEBUG_BACKUP) { 17269 Slog.e(TAG, "Unable to write default apps for backup", e); 17270 } 17271 return null; 17272 } 17273 17274 return dataStream.toByteArray(); 17275 } 17276 17277 @Override 17278 public void restoreDefaultApps(byte[] backup, int userId) { 17279 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17280 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17281 } 17282 17283 try { 17284 final XmlPullParser parser = Xml.newPullParser(); 17285 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17286 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17287 new BlobXmlRestorer() { 17288 @Override 17289 public void apply(XmlPullParser parser, int userId) 17290 throws XmlPullParserException, IOException { 17291 synchronized (mPackages) { 17292 mSettings.readDefaultAppsLPw(parser, userId); 17293 } 17294 } 17295 } ); 17296 } catch (Exception e) { 17297 if (DEBUG_BACKUP) { 17298 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17299 } 17300 } 17301 } 17302 17303 @Override 17304 public byte[] getIntentFilterVerificationBackup(int userId) { 17305 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17306 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17307 } 17308 17309 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17310 try { 17311 final XmlSerializer serializer = new FastXmlSerializer(); 17312 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17313 serializer.startDocument(null, true); 17314 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17315 17316 synchronized (mPackages) { 17317 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17318 } 17319 17320 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17321 serializer.endDocument(); 17322 serializer.flush(); 17323 } catch (Exception e) { 17324 if (DEBUG_BACKUP) { 17325 Slog.e(TAG, "Unable to write default apps for backup", e); 17326 } 17327 return null; 17328 } 17329 17330 return dataStream.toByteArray(); 17331 } 17332 17333 @Override 17334 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17335 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17336 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17337 } 17338 17339 try { 17340 final XmlPullParser parser = Xml.newPullParser(); 17341 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17342 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17343 new BlobXmlRestorer() { 17344 @Override 17345 public void apply(XmlPullParser parser, int userId) 17346 throws XmlPullParserException, IOException { 17347 synchronized (mPackages) { 17348 mSettings.readAllDomainVerificationsLPr(parser, userId); 17349 mSettings.writeLPr(); 17350 } 17351 } 17352 } ); 17353 } catch (Exception e) { 17354 if (DEBUG_BACKUP) { 17355 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17356 } 17357 } 17358 } 17359 17360 @Override 17361 public byte[] getPermissionGrantBackup(int userId) { 17362 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17363 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17364 } 17365 17366 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17367 try { 17368 final XmlSerializer serializer = new FastXmlSerializer(); 17369 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17370 serializer.startDocument(null, true); 17371 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17372 17373 synchronized (mPackages) { 17374 serializeRuntimePermissionGrantsLPr(serializer, userId); 17375 } 17376 17377 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17378 serializer.endDocument(); 17379 serializer.flush(); 17380 } catch (Exception e) { 17381 if (DEBUG_BACKUP) { 17382 Slog.e(TAG, "Unable to write default apps for backup", e); 17383 } 17384 return null; 17385 } 17386 17387 return dataStream.toByteArray(); 17388 } 17389 17390 @Override 17391 public void restorePermissionGrants(byte[] backup, int userId) { 17392 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17393 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17394 } 17395 17396 try { 17397 final XmlPullParser parser = Xml.newPullParser(); 17398 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17399 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17400 new BlobXmlRestorer() { 17401 @Override 17402 public void apply(XmlPullParser parser, int userId) 17403 throws XmlPullParserException, IOException { 17404 synchronized (mPackages) { 17405 processRestoredPermissionGrantsLPr(parser, userId); 17406 } 17407 } 17408 } ); 17409 } catch (Exception e) { 17410 if (DEBUG_BACKUP) { 17411 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17412 } 17413 } 17414 } 17415 17416 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17417 throws IOException { 17418 serializer.startTag(null, TAG_ALL_GRANTS); 17419 17420 final int N = mSettings.mPackages.size(); 17421 for (int i = 0; i < N; i++) { 17422 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17423 boolean pkgGrantsKnown = false; 17424 17425 PermissionsState packagePerms = ps.getPermissionsState(); 17426 17427 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17428 final int grantFlags = state.getFlags(); 17429 // only look at grants that are not system/policy fixed 17430 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17431 final boolean isGranted = state.isGranted(); 17432 // And only back up the user-twiddled state bits 17433 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17434 final String packageName = mSettings.mPackages.keyAt(i); 17435 if (!pkgGrantsKnown) { 17436 serializer.startTag(null, TAG_GRANT); 17437 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17438 pkgGrantsKnown = true; 17439 } 17440 17441 final boolean userSet = 17442 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17443 final boolean userFixed = 17444 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17445 final boolean revoke = 17446 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17447 17448 serializer.startTag(null, TAG_PERMISSION); 17449 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17450 if (isGranted) { 17451 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17452 } 17453 if (userSet) { 17454 serializer.attribute(null, ATTR_USER_SET, "true"); 17455 } 17456 if (userFixed) { 17457 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17458 } 17459 if (revoke) { 17460 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17461 } 17462 serializer.endTag(null, TAG_PERMISSION); 17463 } 17464 } 17465 } 17466 17467 if (pkgGrantsKnown) { 17468 serializer.endTag(null, TAG_GRANT); 17469 } 17470 } 17471 17472 serializer.endTag(null, TAG_ALL_GRANTS); 17473 } 17474 17475 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17476 throws XmlPullParserException, IOException { 17477 String pkgName = null; 17478 int outerDepth = parser.getDepth(); 17479 int type; 17480 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17481 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17482 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17483 continue; 17484 } 17485 17486 final String tagName = parser.getName(); 17487 if (tagName.equals(TAG_GRANT)) { 17488 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17489 if (DEBUG_BACKUP) { 17490 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17491 } 17492 } else if (tagName.equals(TAG_PERMISSION)) { 17493 17494 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17495 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17496 17497 int newFlagSet = 0; 17498 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17499 newFlagSet |= FLAG_PERMISSION_USER_SET; 17500 } 17501 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17502 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17503 } 17504 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17505 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17506 } 17507 if (DEBUG_BACKUP) { 17508 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17509 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17510 } 17511 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17512 if (ps != null) { 17513 // Already installed so we apply the grant immediately 17514 if (DEBUG_BACKUP) { 17515 Slog.v(TAG, " + already installed; applying"); 17516 } 17517 PermissionsState perms = ps.getPermissionsState(); 17518 BasePermission bp = mSettings.mPermissions.get(permName); 17519 if (bp != null) { 17520 if (isGranted) { 17521 perms.grantRuntimePermission(bp, userId); 17522 } 17523 if (newFlagSet != 0) { 17524 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17525 } 17526 } 17527 } else { 17528 // Need to wait for post-restore install to apply the grant 17529 if (DEBUG_BACKUP) { 17530 Slog.v(TAG, " - not yet installed; saving for later"); 17531 } 17532 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17533 isGranted, newFlagSet, userId); 17534 } 17535 } else { 17536 PackageManagerService.reportSettingsProblem(Log.WARN, 17537 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17538 XmlUtils.skipCurrentTag(parser); 17539 } 17540 } 17541 17542 scheduleWriteSettingsLocked(); 17543 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17544 } 17545 17546 @Override 17547 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17548 int sourceUserId, int targetUserId, int flags) { 17549 mContext.enforceCallingOrSelfPermission( 17550 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17551 int callingUid = Binder.getCallingUid(); 17552 enforceOwnerRights(ownerPackage, callingUid); 17553 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17554 if (intentFilter.countActions() == 0) { 17555 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17556 return; 17557 } 17558 synchronized (mPackages) { 17559 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17560 ownerPackage, targetUserId, flags); 17561 CrossProfileIntentResolver resolver = 17562 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17563 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17564 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17565 if (existing != null) { 17566 int size = existing.size(); 17567 for (int i = 0; i < size; i++) { 17568 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17569 return; 17570 } 17571 } 17572 } 17573 resolver.addFilter(newFilter); 17574 scheduleWritePackageRestrictionsLocked(sourceUserId); 17575 } 17576 } 17577 17578 @Override 17579 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17580 mContext.enforceCallingOrSelfPermission( 17581 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17582 int callingUid = Binder.getCallingUid(); 17583 enforceOwnerRights(ownerPackage, callingUid); 17584 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17585 synchronized (mPackages) { 17586 CrossProfileIntentResolver resolver = 17587 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17588 ArraySet<CrossProfileIntentFilter> set = 17589 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17590 for (CrossProfileIntentFilter filter : set) { 17591 if (filter.getOwnerPackage().equals(ownerPackage)) { 17592 resolver.removeFilter(filter); 17593 } 17594 } 17595 scheduleWritePackageRestrictionsLocked(sourceUserId); 17596 } 17597 } 17598 17599 // Enforcing that callingUid is owning pkg on userId 17600 private void enforceOwnerRights(String pkg, int callingUid) { 17601 // The system owns everything. 17602 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17603 return; 17604 } 17605 int callingUserId = UserHandle.getUserId(callingUid); 17606 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17607 if (pi == null) { 17608 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17609 + callingUserId); 17610 } 17611 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17612 throw new SecurityException("Calling uid " + callingUid 17613 + " does not own package " + pkg); 17614 } 17615 } 17616 17617 @Override 17618 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17619 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17620 } 17621 17622 private Intent getHomeIntent() { 17623 Intent intent = new Intent(Intent.ACTION_MAIN); 17624 intent.addCategory(Intent.CATEGORY_HOME); 17625 return intent; 17626 } 17627 17628 private IntentFilter getHomeFilter() { 17629 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17630 filter.addCategory(Intent.CATEGORY_HOME); 17631 filter.addCategory(Intent.CATEGORY_DEFAULT); 17632 return filter; 17633 } 17634 17635 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17636 int userId) { 17637 Intent intent = getHomeIntent(); 17638 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17639 PackageManager.GET_META_DATA, userId); 17640 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17641 true, false, false, userId); 17642 17643 allHomeCandidates.clear(); 17644 if (list != null) { 17645 for (ResolveInfo ri : list) { 17646 allHomeCandidates.add(ri); 17647 } 17648 } 17649 return (preferred == null || preferred.activityInfo == null) 17650 ? null 17651 : new ComponentName(preferred.activityInfo.packageName, 17652 preferred.activityInfo.name); 17653 } 17654 17655 @Override 17656 public void setHomeActivity(ComponentName comp, int userId) { 17657 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17658 getHomeActivitiesAsUser(homeActivities, userId); 17659 17660 boolean found = false; 17661 17662 final int size = homeActivities.size(); 17663 final ComponentName[] set = new ComponentName[size]; 17664 for (int i = 0; i < size; i++) { 17665 final ResolveInfo candidate = homeActivities.get(i); 17666 final ActivityInfo info = candidate.activityInfo; 17667 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17668 set[i] = activityName; 17669 if (!found && activityName.equals(comp)) { 17670 found = true; 17671 } 17672 } 17673 if (!found) { 17674 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17675 + userId); 17676 } 17677 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17678 set, comp, userId); 17679 } 17680 17681 private @Nullable String getSetupWizardPackageName() { 17682 final Intent intent = new Intent(Intent.ACTION_MAIN); 17683 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17684 17685 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17686 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17687 | MATCH_DISABLED_COMPONENTS, 17688 UserHandle.myUserId()); 17689 if (matches.size() == 1) { 17690 return matches.get(0).getComponentInfo().packageName; 17691 } else { 17692 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17693 + ": matches=" + matches); 17694 return null; 17695 } 17696 } 17697 17698 @Override 17699 public void setApplicationEnabledSetting(String appPackageName, 17700 int newState, int flags, int userId, String callingPackage) { 17701 if (!sUserManager.exists(userId)) return; 17702 if (callingPackage == null) { 17703 callingPackage = Integer.toString(Binder.getCallingUid()); 17704 } 17705 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17706 } 17707 17708 @Override 17709 public void setComponentEnabledSetting(ComponentName componentName, 17710 int newState, int flags, int userId) { 17711 if (!sUserManager.exists(userId)) return; 17712 setEnabledSetting(componentName.getPackageName(), 17713 componentName.getClassName(), newState, flags, userId, null); 17714 } 17715 17716 private void setEnabledSetting(final String packageName, String className, int newState, 17717 final int flags, int userId, String callingPackage) { 17718 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17719 || newState == COMPONENT_ENABLED_STATE_ENABLED 17720 || newState == COMPONENT_ENABLED_STATE_DISABLED 17721 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17722 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17723 throw new IllegalArgumentException("Invalid new component state: " 17724 + newState); 17725 } 17726 PackageSetting pkgSetting; 17727 final int uid = Binder.getCallingUid(); 17728 final int permission; 17729 if (uid == Process.SYSTEM_UID) { 17730 permission = PackageManager.PERMISSION_GRANTED; 17731 } else { 17732 permission = mContext.checkCallingOrSelfPermission( 17733 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17734 } 17735 enforceCrossUserPermission(uid, userId, 17736 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17737 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17738 boolean sendNow = false; 17739 boolean isApp = (className == null); 17740 String componentName = isApp ? packageName : className; 17741 int packageUid = -1; 17742 ArrayList<String> components; 17743 17744 // writer 17745 synchronized (mPackages) { 17746 pkgSetting = mSettings.mPackages.get(packageName); 17747 if (pkgSetting == null) { 17748 if (className == null) { 17749 throw new IllegalArgumentException("Unknown package: " + packageName); 17750 } 17751 throw new IllegalArgumentException( 17752 "Unknown component: " + packageName + "/" + className); 17753 } 17754 } 17755 17756 // Limit who can change which apps 17757 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17758 // Don't allow apps that don't have permission to modify other apps 17759 if (!allowedByPermission) { 17760 throw new SecurityException( 17761 "Permission Denial: attempt to change component state from pid=" 17762 + Binder.getCallingPid() 17763 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17764 } 17765 // Don't allow changing profile and device owners. 17766 if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) { 17767 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17768 } 17769 } 17770 17771 synchronized (mPackages) { 17772 if (uid == Process.SHELL_UID) { 17773 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17774 int oldState = pkgSetting.getEnabled(userId); 17775 if (className == null 17776 && 17777 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17778 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17779 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17780 && 17781 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17782 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17783 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17784 // ok 17785 } else { 17786 throw new SecurityException( 17787 "Shell cannot change component state for " + packageName + "/" 17788 + className + " to " + newState); 17789 } 17790 } 17791 if (className == null) { 17792 // We're dealing with an application/package level state change 17793 if (pkgSetting.getEnabled(userId) == newState) { 17794 // Nothing to do 17795 return; 17796 } 17797 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17798 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17799 // Don't care about who enables an app. 17800 callingPackage = null; 17801 } 17802 pkgSetting.setEnabled(newState, userId, callingPackage); 17803 // pkgSetting.pkg.mSetEnabled = newState; 17804 } else { 17805 // We're dealing with a component level state change 17806 // First, verify that this is a valid class name. 17807 PackageParser.Package pkg = pkgSetting.pkg; 17808 if (pkg == null || !pkg.hasComponentClassName(className)) { 17809 if (pkg != null && 17810 pkg.applicationInfo.targetSdkVersion >= 17811 Build.VERSION_CODES.JELLY_BEAN) { 17812 throw new IllegalArgumentException("Component class " + className 17813 + " does not exist in " + packageName); 17814 } else { 17815 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17816 + className + " does not exist in " + packageName); 17817 } 17818 } 17819 switch (newState) { 17820 case COMPONENT_ENABLED_STATE_ENABLED: 17821 if (!pkgSetting.enableComponentLPw(className, userId)) { 17822 return; 17823 } 17824 break; 17825 case COMPONENT_ENABLED_STATE_DISABLED: 17826 if (!pkgSetting.disableComponentLPw(className, userId)) { 17827 return; 17828 } 17829 break; 17830 case COMPONENT_ENABLED_STATE_DEFAULT: 17831 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17832 return; 17833 } 17834 break; 17835 default: 17836 Slog.e(TAG, "Invalid new component state: " + newState); 17837 return; 17838 } 17839 } 17840 scheduleWritePackageRestrictionsLocked(userId); 17841 components = mPendingBroadcasts.get(userId, packageName); 17842 final boolean newPackage = components == null; 17843 if (newPackage) { 17844 components = new ArrayList<String>(); 17845 } 17846 if (!components.contains(componentName)) { 17847 components.add(componentName); 17848 } 17849 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17850 sendNow = true; 17851 // Purge entry from pending broadcast list if another one exists already 17852 // since we are sending one right away. 17853 mPendingBroadcasts.remove(userId, packageName); 17854 } else { 17855 if (newPackage) { 17856 mPendingBroadcasts.put(userId, packageName, components); 17857 } 17858 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17859 // Schedule a message 17860 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17861 } 17862 } 17863 } 17864 17865 long callingId = Binder.clearCallingIdentity(); 17866 try { 17867 if (sendNow) { 17868 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17869 sendPackageChangedBroadcast(packageName, 17870 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17871 } 17872 } finally { 17873 Binder.restoreCallingIdentity(callingId); 17874 } 17875 } 17876 17877 @Override 17878 public void flushPackageRestrictionsAsUser(int userId) { 17879 if (!sUserManager.exists(userId)) { 17880 return; 17881 } 17882 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17883 false /* checkShell */, "flushPackageRestrictions"); 17884 synchronized (mPackages) { 17885 mSettings.writePackageRestrictionsLPr(userId); 17886 mDirtyUsers.remove(userId); 17887 if (mDirtyUsers.isEmpty()) { 17888 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17889 } 17890 } 17891 } 17892 17893 private void sendPackageChangedBroadcast(String packageName, 17894 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17895 if (DEBUG_INSTALL) 17896 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17897 + componentNames); 17898 Bundle extras = new Bundle(4); 17899 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17900 String nameList[] = new String[componentNames.size()]; 17901 componentNames.toArray(nameList); 17902 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17903 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17904 extras.putInt(Intent.EXTRA_UID, packageUid); 17905 // If this is not reporting a change of the overall package, then only send it 17906 // to registered receivers. We don't want to launch a swath of apps for every 17907 // little component state change. 17908 final int flags = !componentNames.contains(packageName) 17909 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17910 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17911 new int[] {UserHandle.getUserId(packageUid)}); 17912 } 17913 17914 @Override 17915 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17916 if (!sUserManager.exists(userId)) return; 17917 final int uid = Binder.getCallingUid(); 17918 final int permission = mContext.checkCallingOrSelfPermission( 17919 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17920 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17921 enforceCrossUserPermission(uid, userId, 17922 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17923 // writer 17924 synchronized (mPackages) { 17925 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17926 allowedByPermission, uid, userId)) { 17927 scheduleWritePackageRestrictionsLocked(userId); 17928 } 17929 } 17930 } 17931 17932 @Override 17933 public String getInstallerPackageName(String packageName) { 17934 // reader 17935 synchronized (mPackages) { 17936 return mSettings.getInstallerPackageNameLPr(packageName); 17937 } 17938 } 17939 17940 public boolean isOrphaned(String packageName) { 17941 // reader 17942 synchronized (mPackages) { 17943 return mSettings.isOrphaned(packageName); 17944 } 17945 } 17946 17947 @Override 17948 public int getApplicationEnabledSetting(String packageName, int userId) { 17949 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17950 int uid = Binder.getCallingUid(); 17951 enforceCrossUserPermission(uid, userId, 17952 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17953 // reader 17954 synchronized (mPackages) { 17955 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17956 } 17957 } 17958 17959 @Override 17960 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17961 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17962 int uid = Binder.getCallingUid(); 17963 enforceCrossUserPermission(uid, userId, 17964 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17965 // reader 17966 synchronized (mPackages) { 17967 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17968 } 17969 } 17970 17971 @Override 17972 public void enterSafeMode() { 17973 enforceSystemOrRoot("Only the system can request entering safe mode"); 17974 17975 if (!mSystemReady) { 17976 mSafeMode = true; 17977 } 17978 } 17979 17980 @Override 17981 public void systemReady() { 17982 mSystemReady = true; 17983 17984 // Read the compatibilty setting when the system is ready. 17985 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17986 mContext.getContentResolver(), 17987 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17988 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17989 if (DEBUG_SETTINGS) { 17990 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17991 } 17992 17993 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17994 17995 synchronized (mPackages) { 17996 // Verify that all of the preferred activity components actually 17997 // exist. It is possible for applications to be updated and at 17998 // that point remove a previously declared activity component that 17999 // had been set as a preferred activity. We try to clean this up 18000 // the next time we encounter that preferred activity, but it is 18001 // possible for the user flow to never be able to return to that 18002 // situation so here we do a sanity check to make sure we haven't 18003 // left any junk around. 18004 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 18005 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18006 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18007 removed.clear(); 18008 for (PreferredActivity pa : pir.filterSet()) { 18009 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 18010 removed.add(pa); 18011 } 18012 } 18013 if (removed.size() > 0) { 18014 for (int r=0; r<removed.size(); r++) { 18015 PreferredActivity pa = removed.get(r); 18016 Slog.w(TAG, "Removing dangling preferred activity: " 18017 + pa.mPref.mComponent); 18018 pir.removeFilter(pa); 18019 } 18020 mSettings.writePackageRestrictionsLPr( 18021 mSettings.mPreferredActivities.keyAt(i)); 18022 } 18023 } 18024 18025 for (int userId : UserManagerService.getInstance().getUserIds()) { 18026 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 18027 grantPermissionsUserIds = ArrayUtils.appendInt( 18028 grantPermissionsUserIds, userId); 18029 } 18030 } 18031 } 18032 sUserManager.systemReady(); 18033 18034 // If we upgraded grant all default permissions before kicking off. 18035 for (int userId : grantPermissionsUserIds) { 18036 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18037 } 18038 18039 // Kick off any messages waiting for system ready 18040 if (mPostSystemReadyMessages != null) { 18041 for (Message msg : mPostSystemReadyMessages) { 18042 msg.sendToTarget(); 18043 } 18044 mPostSystemReadyMessages = null; 18045 } 18046 18047 // Watch for external volumes that come and go over time 18048 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18049 storage.registerListener(mStorageListener); 18050 18051 mInstallerService.systemReady(); 18052 mPackageDexOptimizer.systemReady(); 18053 18054 MountServiceInternal mountServiceInternal = LocalServices.getService( 18055 MountServiceInternal.class); 18056 mountServiceInternal.addExternalStoragePolicy( 18057 new MountServiceInternal.ExternalStorageMountPolicy() { 18058 @Override 18059 public int getMountMode(int uid, String packageName) { 18060 if (Process.isIsolated(uid)) { 18061 return Zygote.MOUNT_EXTERNAL_NONE; 18062 } 18063 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18064 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18065 } 18066 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18067 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18068 } 18069 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18070 return Zygote.MOUNT_EXTERNAL_READ; 18071 } 18072 return Zygote.MOUNT_EXTERNAL_WRITE; 18073 } 18074 18075 @Override 18076 public boolean hasExternalStorage(int uid, String packageName) { 18077 return true; 18078 } 18079 }); 18080 18081 // Now that we're mostly running, clean up stale users and apps 18082 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18083 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18084 } 18085 18086 @Override 18087 public boolean isSafeMode() { 18088 return mSafeMode; 18089 } 18090 18091 @Override 18092 public boolean hasSystemUidErrors() { 18093 return mHasSystemUidErrors; 18094 } 18095 18096 static String arrayToString(int[] array) { 18097 StringBuffer buf = new StringBuffer(128); 18098 buf.append('['); 18099 if (array != null) { 18100 for (int i=0; i<array.length; i++) { 18101 if (i > 0) buf.append(", "); 18102 buf.append(array[i]); 18103 } 18104 } 18105 buf.append(']'); 18106 return buf.toString(); 18107 } 18108 18109 static class DumpState { 18110 public static final int DUMP_LIBS = 1 << 0; 18111 public static final int DUMP_FEATURES = 1 << 1; 18112 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18113 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18114 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18115 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18116 public static final int DUMP_PERMISSIONS = 1 << 6; 18117 public static final int DUMP_PACKAGES = 1 << 7; 18118 public static final int DUMP_SHARED_USERS = 1 << 8; 18119 public static final int DUMP_MESSAGES = 1 << 9; 18120 public static final int DUMP_PROVIDERS = 1 << 10; 18121 public static final int DUMP_VERIFIERS = 1 << 11; 18122 public static final int DUMP_PREFERRED = 1 << 12; 18123 public static final int DUMP_PREFERRED_XML = 1 << 13; 18124 public static final int DUMP_KEYSETS = 1 << 14; 18125 public static final int DUMP_VERSION = 1 << 15; 18126 public static final int DUMP_INSTALLS = 1 << 16; 18127 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18128 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18129 public static final int DUMP_FROZEN = 1 << 19; 18130 public static final int DUMP_DEXOPT = 1 << 20; 18131 18132 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18133 18134 private int mTypes; 18135 18136 private int mOptions; 18137 18138 private boolean mTitlePrinted; 18139 18140 private SharedUserSetting mSharedUser; 18141 18142 public boolean isDumping(int type) { 18143 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18144 return true; 18145 } 18146 18147 return (mTypes & type) != 0; 18148 } 18149 18150 public void setDump(int type) { 18151 mTypes |= type; 18152 } 18153 18154 public boolean isOptionEnabled(int option) { 18155 return (mOptions & option) != 0; 18156 } 18157 18158 public void setOptionEnabled(int option) { 18159 mOptions |= option; 18160 } 18161 18162 public boolean onTitlePrinted() { 18163 final boolean printed = mTitlePrinted; 18164 mTitlePrinted = true; 18165 return printed; 18166 } 18167 18168 public boolean getTitlePrinted() { 18169 return mTitlePrinted; 18170 } 18171 18172 public void setTitlePrinted(boolean enabled) { 18173 mTitlePrinted = enabled; 18174 } 18175 18176 public SharedUserSetting getSharedUser() { 18177 return mSharedUser; 18178 } 18179 18180 public void setSharedUser(SharedUserSetting user) { 18181 mSharedUser = user; 18182 } 18183 } 18184 18185 @Override 18186 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18187 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18188 (new PackageManagerShellCommand(this)).exec( 18189 this, in, out, err, args, resultReceiver); 18190 } 18191 18192 @Override 18193 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18194 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18195 != PackageManager.PERMISSION_GRANTED) { 18196 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18197 + Binder.getCallingPid() 18198 + ", uid=" + Binder.getCallingUid() 18199 + " without permission " 18200 + android.Manifest.permission.DUMP); 18201 return; 18202 } 18203 18204 DumpState dumpState = new DumpState(); 18205 boolean fullPreferred = false; 18206 boolean checkin = false; 18207 18208 String packageName = null; 18209 ArraySet<String> permissionNames = null; 18210 18211 int opti = 0; 18212 while (opti < args.length) { 18213 String opt = args[opti]; 18214 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18215 break; 18216 } 18217 opti++; 18218 18219 if ("-a".equals(opt)) { 18220 // Right now we only know how to print all. 18221 } else if ("-h".equals(opt)) { 18222 pw.println("Package manager dump options:"); 18223 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18224 pw.println(" --checkin: dump for a checkin"); 18225 pw.println(" -f: print details of intent filters"); 18226 pw.println(" -h: print this help"); 18227 pw.println(" cmd may be one of:"); 18228 pw.println(" l[ibraries]: list known shared libraries"); 18229 pw.println(" f[eatures]: list device features"); 18230 pw.println(" k[eysets]: print known keysets"); 18231 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18232 pw.println(" perm[issions]: dump permissions"); 18233 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18234 pw.println(" pref[erred]: print preferred package settings"); 18235 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18236 pw.println(" prov[iders]: dump content providers"); 18237 pw.println(" p[ackages]: dump installed packages"); 18238 pw.println(" s[hared-users]: dump shared user IDs"); 18239 pw.println(" m[essages]: print collected runtime messages"); 18240 pw.println(" v[erifiers]: print package verifier info"); 18241 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18242 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18243 pw.println(" version: print database version info"); 18244 pw.println(" write: write current settings now"); 18245 pw.println(" installs: details about install sessions"); 18246 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18247 pw.println(" dexopt: dump dexopt state"); 18248 pw.println(" <package.name>: info about given package"); 18249 return; 18250 } else if ("--checkin".equals(opt)) { 18251 checkin = true; 18252 } else if ("-f".equals(opt)) { 18253 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18254 } else { 18255 pw.println("Unknown argument: " + opt + "; use -h for help"); 18256 } 18257 } 18258 18259 // Is the caller requesting to dump a particular piece of data? 18260 if (opti < args.length) { 18261 String cmd = args[opti]; 18262 opti++; 18263 // Is this a package name? 18264 if ("android".equals(cmd) || cmd.contains(".")) { 18265 packageName = cmd; 18266 // When dumping a single package, we always dump all of its 18267 // filter information since the amount of data will be reasonable. 18268 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18269 } else if ("check-permission".equals(cmd)) { 18270 if (opti >= args.length) { 18271 pw.println("Error: check-permission missing permission argument"); 18272 return; 18273 } 18274 String perm = args[opti]; 18275 opti++; 18276 if (opti >= args.length) { 18277 pw.println("Error: check-permission missing package argument"); 18278 return; 18279 } 18280 String pkg = args[opti]; 18281 opti++; 18282 int user = UserHandle.getUserId(Binder.getCallingUid()); 18283 if (opti < args.length) { 18284 try { 18285 user = Integer.parseInt(args[opti]); 18286 } catch (NumberFormatException e) { 18287 pw.println("Error: check-permission user argument is not a number: " 18288 + args[opti]); 18289 return; 18290 } 18291 } 18292 pw.println(checkPermission(perm, pkg, user)); 18293 return; 18294 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18295 dumpState.setDump(DumpState.DUMP_LIBS); 18296 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18297 dumpState.setDump(DumpState.DUMP_FEATURES); 18298 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18299 if (opti >= args.length) { 18300 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18301 | DumpState.DUMP_SERVICE_RESOLVERS 18302 | DumpState.DUMP_RECEIVER_RESOLVERS 18303 | DumpState.DUMP_CONTENT_RESOLVERS); 18304 } else { 18305 while (opti < args.length) { 18306 String name = args[opti]; 18307 if ("a".equals(name) || "activity".equals(name)) { 18308 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18309 } else if ("s".equals(name) || "service".equals(name)) { 18310 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18311 } else if ("r".equals(name) || "receiver".equals(name)) { 18312 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18313 } else if ("c".equals(name) || "content".equals(name)) { 18314 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18315 } else { 18316 pw.println("Error: unknown resolver table type: " + name); 18317 return; 18318 } 18319 opti++; 18320 } 18321 } 18322 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18323 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18324 } else if ("permission".equals(cmd)) { 18325 if (opti >= args.length) { 18326 pw.println("Error: permission requires permission name"); 18327 return; 18328 } 18329 permissionNames = new ArraySet<>(); 18330 while (opti < args.length) { 18331 permissionNames.add(args[opti]); 18332 opti++; 18333 } 18334 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18335 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18336 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18337 dumpState.setDump(DumpState.DUMP_PREFERRED); 18338 } else if ("preferred-xml".equals(cmd)) { 18339 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18340 if (opti < args.length && "--full".equals(args[opti])) { 18341 fullPreferred = true; 18342 opti++; 18343 } 18344 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18345 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18346 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18347 dumpState.setDump(DumpState.DUMP_PACKAGES); 18348 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18349 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18350 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18351 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18352 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18353 dumpState.setDump(DumpState.DUMP_MESSAGES); 18354 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18355 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18356 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18357 || "intent-filter-verifiers".equals(cmd)) { 18358 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18359 } else if ("version".equals(cmd)) { 18360 dumpState.setDump(DumpState.DUMP_VERSION); 18361 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18362 dumpState.setDump(DumpState.DUMP_KEYSETS); 18363 } else if ("installs".equals(cmd)) { 18364 dumpState.setDump(DumpState.DUMP_INSTALLS); 18365 } else if ("frozen".equals(cmd)) { 18366 dumpState.setDump(DumpState.DUMP_FROZEN); 18367 } else if ("dexopt".equals(cmd)) { 18368 dumpState.setDump(DumpState.DUMP_DEXOPT); 18369 } else if ("write".equals(cmd)) { 18370 synchronized (mPackages) { 18371 mSettings.writeLPr(); 18372 pw.println("Settings written."); 18373 return; 18374 } 18375 } 18376 } 18377 18378 if (checkin) { 18379 pw.println("vers,1"); 18380 } 18381 18382 // reader 18383 synchronized (mPackages) { 18384 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18385 if (!checkin) { 18386 if (dumpState.onTitlePrinted()) 18387 pw.println(); 18388 pw.println("Database versions:"); 18389 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18390 } 18391 } 18392 18393 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18394 if (!checkin) { 18395 if (dumpState.onTitlePrinted()) 18396 pw.println(); 18397 pw.println("Verifiers:"); 18398 pw.print(" Required: "); 18399 pw.print(mRequiredVerifierPackage); 18400 pw.print(" (uid="); 18401 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18402 UserHandle.USER_SYSTEM)); 18403 pw.println(")"); 18404 } else if (mRequiredVerifierPackage != null) { 18405 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18406 pw.print(","); 18407 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18408 UserHandle.USER_SYSTEM)); 18409 } 18410 } 18411 18412 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18413 packageName == null) { 18414 if (mIntentFilterVerifierComponent != null) { 18415 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18416 if (!checkin) { 18417 if (dumpState.onTitlePrinted()) 18418 pw.println(); 18419 pw.println("Intent Filter Verifier:"); 18420 pw.print(" Using: "); 18421 pw.print(verifierPackageName); 18422 pw.print(" (uid="); 18423 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18424 UserHandle.USER_SYSTEM)); 18425 pw.println(")"); 18426 } else if (verifierPackageName != null) { 18427 pw.print("ifv,"); pw.print(verifierPackageName); 18428 pw.print(","); 18429 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18430 UserHandle.USER_SYSTEM)); 18431 } 18432 } else { 18433 pw.println(); 18434 pw.println("No Intent Filter Verifier available!"); 18435 } 18436 } 18437 18438 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18439 boolean printedHeader = false; 18440 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18441 while (it.hasNext()) { 18442 String name = it.next(); 18443 SharedLibraryEntry ent = mSharedLibraries.get(name); 18444 if (!checkin) { 18445 if (!printedHeader) { 18446 if (dumpState.onTitlePrinted()) 18447 pw.println(); 18448 pw.println("Libraries:"); 18449 printedHeader = true; 18450 } 18451 pw.print(" "); 18452 } else { 18453 pw.print("lib,"); 18454 } 18455 pw.print(name); 18456 if (!checkin) { 18457 pw.print(" -> "); 18458 } 18459 if (ent.path != null) { 18460 if (!checkin) { 18461 pw.print("(jar) "); 18462 pw.print(ent.path); 18463 } else { 18464 pw.print(",jar,"); 18465 pw.print(ent.path); 18466 } 18467 } else { 18468 if (!checkin) { 18469 pw.print("(apk) "); 18470 pw.print(ent.apk); 18471 } else { 18472 pw.print(",apk,"); 18473 pw.print(ent.apk); 18474 } 18475 } 18476 pw.println(); 18477 } 18478 } 18479 18480 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18481 if (dumpState.onTitlePrinted()) 18482 pw.println(); 18483 if (!checkin) { 18484 pw.println("Features:"); 18485 } 18486 18487 for (FeatureInfo feat : mAvailableFeatures.values()) { 18488 if (checkin) { 18489 pw.print("feat,"); 18490 pw.print(feat.name); 18491 pw.print(","); 18492 pw.println(feat.version); 18493 } else { 18494 pw.print(" "); 18495 pw.print(feat.name); 18496 if (feat.version > 0) { 18497 pw.print(" version="); 18498 pw.print(feat.version); 18499 } 18500 pw.println(); 18501 } 18502 } 18503 } 18504 18505 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18506 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18507 : "Activity Resolver Table:", " ", packageName, 18508 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18509 dumpState.setTitlePrinted(true); 18510 } 18511 } 18512 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18513 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18514 : "Receiver Resolver Table:", " ", packageName, 18515 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18516 dumpState.setTitlePrinted(true); 18517 } 18518 } 18519 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18520 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18521 : "Service Resolver Table:", " ", packageName, 18522 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18523 dumpState.setTitlePrinted(true); 18524 } 18525 } 18526 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18527 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18528 : "Provider Resolver Table:", " ", packageName, 18529 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18530 dumpState.setTitlePrinted(true); 18531 } 18532 } 18533 18534 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18535 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18536 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18537 int user = mSettings.mPreferredActivities.keyAt(i); 18538 if (pir.dump(pw, 18539 dumpState.getTitlePrinted() 18540 ? "\nPreferred Activities User " + user + ":" 18541 : "Preferred Activities User " + user + ":", " ", 18542 packageName, true, false)) { 18543 dumpState.setTitlePrinted(true); 18544 } 18545 } 18546 } 18547 18548 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18549 pw.flush(); 18550 FileOutputStream fout = new FileOutputStream(fd); 18551 BufferedOutputStream str = new BufferedOutputStream(fout); 18552 XmlSerializer serializer = new FastXmlSerializer(); 18553 try { 18554 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18555 serializer.startDocument(null, true); 18556 serializer.setFeature( 18557 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18558 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18559 serializer.endDocument(); 18560 serializer.flush(); 18561 } catch (IllegalArgumentException e) { 18562 pw.println("Failed writing: " + e); 18563 } catch (IllegalStateException e) { 18564 pw.println("Failed writing: " + e); 18565 } catch (IOException e) { 18566 pw.println("Failed writing: " + e); 18567 } 18568 } 18569 18570 if (!checkin 18571 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18572 && packageName == null) { 18573 pw.println(); 18574 int count = mSettings.mPackages.size(); 18575 if (count == 0) { 18576 pw.println("No applications!"); 18577 pw.println(); 18578 } else { 18579 final String prefix = " "; 18580 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18581 if (allPackageSettings.size() == 0) { 18582 pw.println("No domain preferred apps!"); 18583 pw.println(); 18584 } else { 18585 pw.println("App verification status:"); 18586 pw.println(); 18587 count = 0; 18588 for (PackageSetting ps : allPackageSettings) { 18589 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18590 if (ivi == null || ivi.getPackageName() == null) continue; 18591 pw.println(prefix + "Package: " + ivi.getPackageName()); 18592 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18593 pw.println(prefix + "Status: " + ivi.getStatusString()); 18594 pw.println(); 18595 count++; 18596 } 18597 if (count == 0) { 18598 pw.println(prefix + "No app verification established."); 18599 pw.println(); 18600 } 18601 for (int userId : sUserManager.getUserIds()) { 18602 pw.println("App linkages for user " + userId + ":"); 18603 pw.println(); 18604 count = 0; 18605 for (PackageSetting ps : allPackageSettings) { 18606 final long status = ps.getDomainVerificationStatusForUser(userId); 18607 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18608 continue; 18609 } 18610 pw.println(prefix + "Package: " + ps.name); 18611 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18612 String statusStr = IntentFilterVerificationInfo. 18613 getStatusStringFromValue(status); 18614 pw.println(prefix + "Status: " + statusStr); 18615 pw.println(); 18616 count++; 18617 } 18618 if (count == 0) { 18619 pw.println(prefix + "No configured app linkages."); 18620 pw.println(); 18621 } 18622 } 18623 } 18624 } 18625 } 18626 18627 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18628 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18629 if (packageName == null && permissionNames == null) { 18630 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18631 if (iperm == 0) { 18632 if (dumpState.onTitlePrinted()) 18633 pw.println(); 18634 pw.println("AppOp Permissions:"); 18635 } 18636 pw.print(" AppOp Permission "); 18637 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18638 pw.println(":"); 18639 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18640 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18641 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18642 } 18643 } 18644 } 18645 } 18646 18647 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18648 boolean printedSomething = false; 18649 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18650 if (packageName != null && !packageName.equals(p.info.packageName)) { 18651 continue; 18652 } 18653 if (!printedSomething) { 18654 if (dumpState.onTitlePrinted()) 18655 pw.println(); 18656 pw.println("Registered ContentProviders:"); 18657 printedSomething = true; 18658 } 18659 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18660 pw.print(" "); pw.println(p.toString()); 18661 } 18662 printedSomething = false; 18663 for (Map.Entry<String, PackageParser.Provider> entry : 18664 mProvidersByAuthority.entrySet()) { 18665 PackageParser.Provider p = entry.getValue(); 18666 if (packageName != null && !packageName.equals(p.info.packageName)) { 18667 continue; 18668 } 18669 if (!printedSomething) { 18670 if (dumpState.onTitlePrinted()) 18671 pw.println(); 18672 pw.println("ContentProvider Authorities:"); 18673 printedSomething = true; 18674 } 18675 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18676 pw.print(" "); pw.println(p.toString()); 18677 if (p.info != null && p.info.applicationInfo != null) { 18678 final String appInfo = p.info.applicationInfo.toString(); 18679 pw.print(" applicationInfo="); pw.println(appInfo); 18680 } 18681 } 18682 } 18683 18684 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18685 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18686 } 18687 18688 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18689 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18690 } 18691 18692 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18693 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18694 } 18695 18696 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18697 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18698 } 18699 18700 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18701 // XXX should handle packageName != null by dumping only install data that 18702 // the given package is involved with. 18703 if (dumpState.onTitlePrinted()) pw.println(); 18704 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18705 } 18706 18707 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18708 // XXX should handle packageName != null by dumping only install data that 18709 // the given package is involved with. 18710 if (dumpState.onTitlePrinted()) pw.println(); 18711 18712 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18713 ipw.println(); 18714 ipw.println("Frozen packages:"); 18715 ipw.increaseIndent(); 18716 if (mFrozenPackages.size() == 0) { 18717 ipw.println("(none)"); 18718 } else { 18719 for (int i = 0; i < mFrozenPackages.size(); i++) { 18720 ipw.println(mFrozenPackages.valueAt(i)); 18721 } 18722 } 18723 ipw.decreaseIndent(); 18724 } 18725 18726 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18727 if (dumpState.onTitlePrinted()) pw.println(); 18728 dumpDexoptStateLPr(pw, packageName); 18729 } 18730 18731 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18732 if (dumpState.onTitlePrinted()) pw.println(); 18733 mSettings.dumpReadMessagesLPr(pw, dumpState); 18734 18735 pw.println(); 18736 pw.println("Package warning messages:"); 18737 BufferedReader in = null; 18738 String line = null; 18739 try { 18740 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18741 while ((line = in.readLine()) != null) { 18742 if (line.contains("ignored: updated version")) continue; 18743 pw.println(line); 18744 } 18745 } catch (IOException ignored) { 18746 } finally { 18747 IoUtils.closeQuietly(in); 18748 } 18749 } 18750 18751 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18752 BufferedReader in = null; 18753 String line = null; 18754 try { 18755 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18756 while ((line = in.readLine()) != null) { 18757 if (line.contains("ignored: updated version")) continue; 18758 pw.print("msg,"); 18759 pw.println(line); 18760 } 18761 } catch (IOException ignored) { 18762 } finally { 18763 IoUtils.closeQuietly(in); 18764 } 18765 } 18766 } 18767 } 18768 18769 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18770 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18771 ipw.println(); 18772 ipw.println("Dexopt state:"); 18773 ipw.increaseIndent(); 18774 Collection<PackageParser.Package> packages = null; 18775 if (packageName != null) { 18776 PackageParser.Package targetPackage = mPackages.get(packageName); 18777 if (targetPackage != null) { 18778 packages = Collections.singletonList(targetPackage); 18779 } else { 18780 ipw.println("Unable to find package: " + packageName); 18781 return; 18782 } 18783 } else { 18784 packages = mPackages.values(); 18785 } 18786 18787 for (PackageParser.Package pkg : packages) { 18788 ipw.println("[" + pkg.packageName + "]"); 18789 ipw.increaseIndent(); 18790 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18791 ipw.decreaseIndent(); 18792 } 18793 } 18794 18795 private String dumpDomainString(String packageName) { 18796 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18797 .getList(); 18798 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18799 18800 ArraySet<String> result = new ArraySet<>(); 18801 if (iviList.size() > 0) { 18802 for (IntentFilterVerificationInfo ivi : iviList) { 18803 for (String host : ivi.getDomains()) { 18804 result.add(host); 18805 } 18806 } 18807 } 18808 if (filters != null && filters.size() > 0) { 18809 for (IntentFilter filter : filters) { 18810 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18811 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18812 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18813 result.addAll(filter.getHostsList()); 18814 } 18815 } 18816 } 18817 18818 StringBuilder sb = new StringBuilder(result.size() * 16); 18819 for (String domain : result) { 18820 if (sb.length() > 0) sb.append(" "); 18821 sb.append(domain); 18822 } 18823 return sb.toString(); 18824 } 18825 18826 // ------- apps on sdcard specific code ------- 18827 static final boolean DEBUG_SD_INSTALL = false; 18828 18829 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18830 18831 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18832 18833 private boolean mMediaMounted = false; 18834 18835 static String getEncryptKey() { 18836 try { 18837 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18838 SD_ENCRYPTION_KEYSTORE_NAME); 18839 if (sdEncKey == null) { 18840 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18841 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18842 if (sdEncKey == null) { 18843 Slog.e(TAG, "Failed to create encryption keys"); 18844 return null; 18845 } 18846 } 18847 return sdEncKey; 18848 } catch (NoSuchAlgorithmException nsae) { 18849 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18850 return null; 18851 } catch (IOException ioe) { 18852 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18853 return null; 18854 } 18855 } 18856 18857 /* 18858 * Update media status on PackageManager. 18859 */ 18860 @Override 18861 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18862 int callingUid = Binder.getCallingUid(); 18863 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18864 throw new SecurityException("Media status can only be updated by the system"); 18865 } 18866 // reader; this apparently protects mMediaMounted, but should probably 18867 // be a different lock in that case. 18868 synchronized (mPackages) { 18869 Log.i(TAG, "Updating external media status from " 18870 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18871 + (mediaStatus ? "mounted" : "unmounted")); 18872 if (DEBUG_SD_INSTALL) 18873 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18874 + ", mMediaMounted=" + mMediaMounted); 18875 if (mediaStatus == mMediaMounted) { 18876 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18877 : 0, -1); 18878 mHandler.sendMessage(msg); 18879 return; 18880 } 18881 mMediaMounted = mediaStatus; 18882 } 18883 // Queue up an async operation since the package installation may take a 18884 // little while. 18885 mHandler.post(new Runnable() { 18886 public void run() { 18887 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18888 } 18889 }); 18890 } 18891 18892 /** 18893 * Called by MountService when the initial ASECs to scan are available. 18894 * Should block until all the ASEC containers are finished being scanned. 18895 */ 18896 public void scanAvailableAsecs() { 18897 updateExternalMediaStatusInner(true, false, false); 18898 } 18899 18900 /* 18901 * Collect information of applications on external media, map them against 18902 * existing containers and update information based on current mount status. 18903 * Please note that we always have to report status if reportStatus has been 18904 * set to true especially when unloading packages. 18905 */ 18906 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18907 boolean externalStorage) { 18908 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18909 int[] uidArr = EmptyArray.INT; 18910 18911 final String[] list = PackageHelper.getSecureContainerList(); 18912 if (ArrayUtils.isEmpty(list)) { 18913 Log.i(TAG, "No secure containers found"); 18914 } else { 18915 // Process list of secure containers and categorize them 18916 // as active or stale based on their package internal state. 18917 18918 // reader 18919 synchronized (mPackages) { 18920 for (String cid : list) { 18921 // Leave stages untouched for now; installer service owns them 18922 if (PackageInstallerService.isStageName(cid)) continue; 18923 18924 if (DEBUG_SD_INSTALL) 18925 Log.i(TAG, "Processing container " + cid); 18926 String pkgName = getAsecPackageName(cid); 18927 if (pkgName == null) { 18928 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18929 continue; 18930 } 18931 if (DEBUG_SD_INSTALL) 18932 Log.i(TAG, "Looking for pkg : " + pkgName); 18933 18934 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18935 if (ps == null) { 18936 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18937 continue; 18938 } 18939 18940 /* 18941 * Skip packages that are not external if we're unmounting 18942 * external storage. 18943 */ 18944 if (externalStorage && !isMounted && !isExternal(ps)) { 18945 continue; 18946 } 18947 18948 final AsecInstallArgs args = new AsecInstallArgs(cid, 18949 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18950 // The package status is changed only if the code path 18951 // matches between settings and the container id. 18952 if (ps.codePathString != null 18953 && ps.codePathString.startsWith(args.getCodePath())) { 18954 if (DEBUG_SD_INSTALL) { 18955 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18956 + " at code path: " + ps.codePathString); 18957 } 18958 18959 // We do have a valid package installed on sdcard 18960 processCids.put(args, ps.codePathString); 18961 final int uid = ps.appId; 18962 if (uid != -1) { 18963 uidArr = ArrayUtils.appendInt(uidArr, uid); 18964 } 18965 } else { 18966 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18967 + ps.codePathString); 18968 } 18969 } 18970 } 18971 18972 Arrays.sort(uidArr); 18973 } 18974 18975 // Process packages with valid entries. 18976 if (isMounted) { 18977 if (DEBUG_SD_INSTALL) 18978 Log.i(TAG, "Loading packages"); 18979 loadMediaPackages(processCids, uidArr, externalStorage); 18980 startCleaningPackages(); 18981 mInstallerService.onSecureContainersAvailable(); 18982 } else { 18983 if (DEBUG_SD_INSTALL) 18984 Log.i(TAG, "Unloading packages"); 18985 unloadMediaPackages(processCids, uidArr, reportStatus); 18986 } 18987 } 18988 18989 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18990 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18991 final int size = infos.size(); 18992 final String[] packageNames = new String[size]; 18993 final int[] packageUids = new int[size]; 18994 for (int i = 0; i < size; i++) { 18995 final ApplicationInfo info = infos.get(i); 18996 packageNames[i] = info.packageName; 18997 packageUids[i] = info.uid; 18998 } 18999 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 19000 finishedReceiver); 19001 } 19002 19003 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19004 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19005 sendResourcesChangedBroadcast(mediaStatus, replacing, 19006 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 19007 } 19008 19009 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 19010 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 19011 int size = pkgList.length; 19012 if (size > 0) { 19013 // Send broadcasts here 19014 Bundle extras = new Bundle(); 19015 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 19016 if (uidArr != null) { 19017 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 19018 } 19019 if (replacing) { 19020 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 19021 } 19022 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 19023 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 19024 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 19025 } 19026 } 19027 19028 /* 19029 * Look at potentially valid container ids from processCids If package 19030 * information doesn't match the one on record or package scanning fails, 19031 * the cid is added to list of removeCids. We currently don't delete stale 19032 * containers. 19033 */ 19034 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19035 boolean externalStorage) { 19036 ArrayList<String> pkgList = new ArrayList<String>(); 19037 Set<AsecInstallArgs> keys = processCids.keySet(); 19038 19039 for (AsecInstallArgs args : keys) { 19040 String codePath = processCids.get(args); 19041 if (DEBUG_SD_INSTALL) 19042 Log.i(TAG, "Loading container : " + args.cid); 19043 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19044 try { 19045 // Make sure there are no container errors first. 19046 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19047 Slog.e(TAG, "Failed to mount cid : " + args.cid 19048 + " when installing from sdcard"); 19049 continue; 19050 } 19051 // Check code path here. 19052 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19053 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19054 + " does not match one in settings " + codePath); 19055 continue; 19056 } 19057 // Parse package 19058 int parseFlags = mDefParseFlags; 19059 if (args.isExternalAsec()) { 19060 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19061 } 19062 if (args.isFwdLocked()) { 19063 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19064 } 19065 19066 synchronized (mInstallLock) { 19067 PackageParser.Package pkg = null; 19068 try { 19069 // Sadly we don't know the package name yet to freeze it 19070 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19071 SCAN_IGNORE_FROZEN, 0, null); 19072 } catch (PackageManagerException e) { 19073 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19074 } 19075 // Scan the package 19076 if (pkg != null) { 19077 /* 19078 * TODO why is the lock being held? doPostInstall is 19079 * called in other places without the lock. This needs 19080 * to be straightened out. 19081 */ 19082 // writer 19083 synchronized (mPackages) { 19084 retCode = PackageManager.INSTALL_SUCCEEDED; 19085 pkgList.add(pkg.packageName); 19086 // Post process args 19087 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19088 pkg.applicationInfo.uid); 19089 } 19090 } else { 19091 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19092 } 19093 } 19094 19095 } finally { 19096 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19097 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19098 } 19099 } 19100 } 19101 // writer 19102 synchronized (mPackages) { 19103 // If the platform SDK has changed since the last time we booted, 19104 // we need to re-grant app permission to catch any new ones that 19105 // appear. This is really a hack, and means that apps can in some 19106 // cases get permissions that the user didn't initially explicitly 19107 // allow... it would be nice to have some better way to handle 19108 // this situation. 19109 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19110 : mSettings.getInternalVersion(); 19111 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19112 : StorageManager.UUID_PRIVATE_INTERNAL; 19113 19114 int updateFlags = UPDATE_PERMISSIONS_ALL; 19115 if (ver.sdkVersion != mSdkVersion) { 19116 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19117 + mSdkVersion + "; regranting permissions for external"); 19118 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19119 } 19120 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19121 19122 // Yay, everything is now upgraded 19123 ver.forceCurrent(); 19124 19125 // can downgrade to reader 19126 // Persist settings 19127 mSettings.writeLPr(); 19128 } 19129 // Send a broadcast to let everyone know we are done processing 19130 if (pkgList.size() > 0) { 19131 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19132 } 19133 } 19134 19135 /* 19136 * Utility method to unload a list of specified containers 19137 */ 19138 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19139 // Just unmount all valid containers. 19140 for (AsecInstallArgs arg : cidArgs) { 19141 synchronized (mInstallLock) { 19142 arg.doPostDeleteLI(false); 19143 } 19144 } 19145 } 19146 19147 /* 19148 * Unload packages mounted on external media. This involves deleting package 19149 * data from internal structures, sending broadcasts about disabled packages, 19150 * gc'ing to free up references, unmounting all secure containers 19151 * corresponding to packages on external media, and posting a 19152 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19153 * that we always have to post this message if status has been requested no 19154 * matter what. 19155 */ 19156 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19157 final boolean reportStatus) { 19158 if (DEBUG_SD_INSTALL) 19159 Log.i(TAG, "unloading media packages"); 19160 ArrayList<String> pkgList = new ArrayList<String>(); 19161 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19162 final Set<AsecInstallArgs> keys = processCids.keySet(); 19163 for (AsecInstallArgs args : keys) { 19164 String pkgName = args.getPackageName(); 19165 if (DEBUG_SD_INSTALL) 19166 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19167 // Delete package internally 19168 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19169 synchronized (mInstallLock) { 19170 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19171 final boolean res; 19172 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19173 "unloadMediaPackages")) { 19174 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19175 null); 19176 } 19177 if (res) { 19178 pkgList.add(pkgName); 19179 } else { 19180 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19181 failedList.add(args); 19182 } 19183 } 19184 } 19185 19186 // reader 19187 synchronized (mPackages) { 19188 // We didn't update the settings after removing each package; 19189 // write them now for all packages. 19190 mSettings.writeLPr(); 19191 } 19192 19193 // We have to absolutely send UPDATED_MEDIA_STATUS only 19194 // after confirming that all the receivers processed the ordered 19195 // broadcast when packages get disabled, force a gc to clean things up. 19196 // and unload all the containers. 19197 if (pkgList.size() > 0) { 19198 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19199 new IIntentReceiver.Stub() { 19200 public void performReceive(Intent intent, int resultCode, String data, 19201 Bundle extras, boolean ordered, boolean sticky, 19202 int sendingUser) throws RemoteException { 19203 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19204 reportStatus ? 1 : 0, 1, keys); 19205 mHandler.sendMessage(msg); 19206 } 19207 }); 19208 } else { 19209 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19210 keys); 19211 mHandler.sendMessage(msg); 19212 } 19213 } 19214 19215 private void loadPrivatePackages(final VolumeInfo vol) { 19216 mHandler.post(new Runnable() { 19217 @Override 19218 public void run() { 19219 loadPrivatePackagesInner(vol); 19220 } 19221 }); 19222 } 19223 19224 private void loadPrivatePackagesInner(VolumeInfo vol) { 19225 final String volumeUuid = vol.fsUuid; 19226 if (TextUtils.isEmpty(volumeUuid)) { 19227 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19228 return; 19229 } 19230 19231 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19232 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19233 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19234 19235 final VersionInfo ver; 19236 final List<PackageSetting> packages; 19237 synchronized (mPackages) { 19238 ver = mSettings.findOrCreateVersion(volumeUuid); 19239 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19240 } 19241 19242 for (PackageSetting ps : packages) { 19243 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19244 synchronized (mInstallLock) { 19245 final PackageParser.Package pkg; 19246 try { 19247 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19248 loaded.add(pkg.applicationInfo); 19249 19250 } catch (PackageManagerException e) { 19251 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19252 } 19253 19254 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19255 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19256 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19257 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19258 } 19259 } 19260 } 19261 19262 // Reconcile app data for all started/unlocked users 19263 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19264 final UserManager um = mContext.getSystemService(UserManager.class); 19265 UserManagerInternal umInternal = getUserManagerInternal(); 19266 for (UserInfo user : um.getUsers()) { 19267 final int flags; 19268 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19269 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19270 } else if (umInternal.isUserRunning(user.id)) { 19271 flags = StorageManager.FLAG_STORAGE_DE; 19272 } else { 19273 continue; 19274 } 19275 19276 try { 19277 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19278 synchronized (mInstallLock) { 19279 reconcileAppsDataLI(volumeUuid, user.id, flags); 19280 } 19281 } catch (IllegalStateException e) { 19282 // Device was probably ejected, and we'll process that event momentarily 19283 Slog.w(TAG, "Failed to prepare storage: " + e); 19284 } 19285 } 19286 19287 synchronized (mPackages) { 19288 int updateFlags = UPDATE_PERMISSIONS_ALL; 19289 if (ver.sdkVersion != mSdkVersion) { 19290 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19291 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19292 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19293 } 19294 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19295 19296 // Yay, everything is now upgraded 19297 ver.forceCurrent(); 19298 19299 mSettings.writeLPr(); 19300 } 19301 19302 for (PackageFreezer freezer : freezers) { 19303 freezer.close(); 19304 } 19305 19306 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19307 sendResourcesChangedBroadcast(true, false, loaded, null); 19308 } 19309 19310 private void unloadPrivatePackages(final VolumeInfo vol) { 19311 mHandler.post(new Runnable() { 19312 @Override 19313 public void run() { 19314 unloadPrivatePackagesInner(vol); 19315 } 19316 }); 19317 } 19318 19319 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19320 final String volumeUuid = vol.fsUuid; 19321 if (TextUtils.isEmpty(volumeUuid)) { 19322 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19323 return; 19324 } 19325 19326 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19327 synchronized (mInstallLock) { 19328 synchronized (mPackages) { 19329 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19330 for (PackageSetting ps : packages) { 19331 if (ps.pkg == null) continue; 19332 19333 final ApplicationInfo info = ps.pkg.applicationInfo; 19334 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19335 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19336 19337 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19338 "unloadPrivatePackagesInner")) { 19339 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19340 false, null)) { 19341 unloaded.add(info); 19342 } else { 19343 Slog.w(TAG, "Failed to unload " + ps.codePath); 19344 } 19345 } 19346 19347 // Try very hard to release any references to this package 19348 // so we don't risk the system server being killed due to 19349 // open FDs 19350 AttributeCache.instance().removePackage(ps.name); 19351 } 19352 19353 mSettings.writeLPr(); 19354 } 19355 } 19356 19357 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19358 sendResourcesChangedBroadcast(false, false, unloaded, null); 19359 19360 // Try very hard to release any references to this path so we don't risk 19361 // the system server being killed due to open FDs 19362 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19363 19364 for (int i = 0; i < 3; i++) { 19365 System.gc(); 19366 System.runFinalization(); 19367 } 19368 } 19369 19370 /** 19371 * Prepare storage areas for given user on all mounted devices. 19372 */ 19373 void prepareUserData(int userId, int userSerial, int flags) { 19374 synchronized (mInstallLock) { 19375 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19376 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19377 final String volumeUuid = vol.getFsUuid(); 19378 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19379 } 19380 } 19381 } 19382 19383 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19384 boolean allowRecover) { 19385 // Prepare storage and verify that serial numbers are consistent; if 19386 // there's a mismatch we need to destroy to avoid leaking data 19387 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19388 try { 19389 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19390 19391 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19392 UserManagerService.enforceSerialNumber( 19393 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19394 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19395 UserManagerService.enforceSerialNumber( 19396 Environment.getDataSystemDeDirectory(userId), userSerial); 19397 } 19398 } 19399 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19400 UserManagerService.enforceSerialNumber( 19401 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19402 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19403 UserManagerService.enforceSerialNumber( 19404 Environment.getDataSystemCeDirectory(userId), userSerial); 19405 } 19406 } 19407 19408 synchronized (mInstallLock) { 19409 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19410 } 19411 } catch (Exception e) { 19412 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19413 + " because we failed to prepare: " + e); 19414 destroyUserDataLI(volumeUuid, userId, 19415 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19416 19417 if (allowRecover) { 19418 // Try one last time; if we fail again we're really in trouble 19419 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19420 } 19421 } 19422 } 19423 19424 /** 19425 * Destroy storage areas for given user on all mounted devices. 19426 */ 19427 void destroyUserData(int userId, int flags) { 19428 synchronized (mInstallLock) { 19429 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19430 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19431 final String volumeUuid = vol.getFsUuid(); 19432 destroyUserDataLI(volumeUuid, userId, flags); 19433 } 19434 } 19435 } 19436 19437 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19438 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19439 try { 19440 // Clean up app data, profile data, and media data 19441 mInstaller.destroyUserData(volumeUuid, userId, flags); 19442 19443 // Clean up system data 19444 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19445 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19446 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19447 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19448 } 19449 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19450 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19451 } 19452 } 19453 19454 // Data with special labels is now gone, so finish the job 19455 storage.destroyUserStorage(volumeUuid, userId, flags); 19456 19457 } catch (Exception e) { 19458 logCriticalInfo(Log.WARN, 19459 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19460 } 19461 } 19462 19463 /** 19464 * Examine all users present on given mounted volume, and destroy data 19465 * belonging to users that are no longer valid, or whose user ID has been 19466 * recycled. 19467 */ 19468 private void reconcileUsers(String volumeUuid) { 19469 final List<File> files = new ArrayList<>(); 19470 Collections.addAll(files, FileUtils 19471 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19472 Collections.addAll(files, FileUtils 19473 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19474 Collections.addAll(files, FileUtils 19475 .listFilesOrEmpty(Environment.getDataSystemDeDirectory())); 19476 Collections.addAll(files, FileUtils 19477 .listFilesOrEmpty(Environment.getDataSystemCeDirectory())); 19478 for (File file : files) { 19479 if (!file.isDirectory()) continue; 19480 19481 final int userId; 19482 final UserInfo info; 19483 try { 19484 userId = Integer.parseInt(file.getName()); 19485 info = sUserManager.getUserInfo(userId); 19486 } catch (NumberFormatException e) { 19487 Slog.w(TAG, "Invalid user directory " + file); 19488 continue; 19489 } 19490 19491 boolean destroyUser = false; 19492 if (info == null) { 19493 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19494 + " because no matching user was found"); 19495 destroyUser = true; 19496 } else if (!mOnlyCore) { 19497 try { 19498 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19499 } catch (IOException e) { 19500 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19501 + " because we failed to enforce serial number: " + e); 19502 destroyUser = true; 19503 } 19504 } 19505 19506 if (destroyUser) { 19507 synchronized (mInstallLock) { 19508 destroyUserDataLI(volumeUuid, userId, 19509 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19510 } 19511 } 19512 } 19513 } 19514 19515 private void assertPackageKnown(String volumeUuid, String packageName) 19516 throws PackageManagerException { 19517 synchronized (mPackages) { 19518 final PackageSetting ps = mSettings.mPackages.get(packageName); 19519 if (ps == null) { 19520 throw new PackageManagerException("Package " + packageName + " is unknown"); 19521 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19522 throw new PackageManagerException( 19523 "Package " + packageName + " found on unknown volume " + volumeUuid 19524 + "; expected volume " + ps.volumeUuid); 19525 } 19526 } 19527 } 19528 19529 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19530 throws PackageManagerException { 19531 synchronized (mPackages) { 19532 final PackageSetting ps = mSettings.mPackages.get(packageName); 19533 if (ps == null) { 19534 throw new PackageManagerException("Package " + packageName + " is unknown"); 19535 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19536 throw new PackageManagerException( 19537 "Package " + packageName + " found on unknown volume " + volumeUuid 19538 + "; expected volume " + ps.volumeUuid); 19539 } else if (!ps.getInstalled(userId)) { 19540 throw new PackageManagerException( 19541 "Package " + packageName + " not installed for user " + userId); 19542 } 19543 } 19544 } 19545 19546 /** 19547 * Examine all apps present on given mounted volume, and destroy apps that 19548 * aren't expected, either due to uninstallation or reinstallation on 19549 * another volume. 19550 */ 19551 private void reconcileApps(String volumeUuid) { 19552 final File[] files = FileUtils 19553 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19554 for (File file : files) { 19555 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19556 && !PackageInstallerService.isStageName(file.getName()); 19557 if (!isPackage) { 19558 // Ignore entries which are not packages 19559 continue; 19560 } 19561 19562 try { 19563 final PackageLite pkg = PackageParser.parsePackageLite(file, 19564 PackageParser.PARSE_MUST_BE_APK); 19565 assertPackageKnown(volumeUuid, pkg.packageName); 19566 19567 } catch (PackageParserException | PackageManagerException e) { 19568 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19569 synchronized (mInstallLock) { 19570 removeCodePathLI(file); 19571 } 19572 } 19573 } 19574 } 19575 19576 /** 19577 * Reconcile all app data for the given user. 19578 * <p> 19579 * Verifies that directories exist and that ownership and labeling is 19580 * correct for all installed apps on all mounted volumes. 19581 */ 19582 void reconcileAppsData(int userId, int flags) { 19583 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19584 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19585 final String volumeUuid = vol.getFsUuid(); 19586 synchronized (mInstallLock) { 19587 reconcileAppsDataLI(volumeUuid, userId, flags); 19588 } 19589 } 19590 } 19591 19592 /** 19593 * Reconcile all app data on given mounted volume. 19594 * <p> 19595 * Destroys app data that isn't expected, either due to uninstallation or 19596 * reinstallation on another volume. 19597 * <p> 19598 * Verifies that directories exist and that ownership and labeling is 19599 * correct for all installed apps. 19600 */ 19601 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19602 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19603 + Integer.toHexString(flags)); 19604 19605 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19606 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19607 19608 boolean restoreconNeeded = false; 19609 19610 // First look for stale data that doesn't belong, and check if things 19611 // have changed since we did our last restorecon 19612 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19613 if (StorageManager.isFileEncryptedNativeOrEmulated() 19614 && !StorageManager.isUserKeyUnlocked(userId)) { 19615 throw new RuntimeException( 19616 "Yikes, someone asked us to reconcile CE storage while " + userId 19617 + " was still locked; this would have caused massive data loss!"); 19618 } 19619 19620 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19621 19622 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19623 for (File file : files) { 19624 final String packageName = file.getName(); 19625 try { 19626 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19627 } catch (PackageManagerException e) { 19628 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19629 try { 19630 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19631 StorageManager.FLAG_STORAGE_CE, 0); 19632 } catch (InstallerException e2) { 19633 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19634 } 19635 } 19636 } 19637 } 19638 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19639 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19640 19641 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19642 for (File file : files) { 19643 final String packageName = file.getName(); 19644 try { 19645 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19646 } catch (PackageManagerException e) { 19647 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19648 try { 19649 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19650 StorageManager.FLAG_STORAGE_DE, 0); 19651 } catch (InstallerException e2) { 19652 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19653 } 19654 } 19655 } 19656 } 19657 19658 // Ensure that data directories are ready to roll for all packages 19659 // installed for this volume and user 19660 final List<PackageSetting> packages; 19661 synchronized (mPackages) { 19662 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19663 } 19664 int preparedCount = 0; 19665 for (PackageSetting ps : packages) { 19666 final String packageName = ps.name; 19667 if (ps.pkg == null) { 19668 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19669 // TODO: might be due to legacy ASEC apps; we should circle back 19670 // and reconcile again once they're scanned 19671 continue; 19672 } 19673 19674 if (ps.getInstalled(userId)) { 19675 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19676 19677 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19678 // We may have just shuffled around app data directories, so 19679 // prepare them one more time 19680 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19681 } 19682 19683 preparedCount++; 19684 } 19685 } 19686 19687 if (restoreconNeeded) { 19688 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19689 SELinuxMMAC.setRestoreconDone(ceDir); 19690 } 19691 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19692 SELinuxMMAC.setRestoreconDone(deDir); 19693 } 19694 } 19695 19696 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19697 + " packages; restoreconNeeded was " + restoreconNeeded); 19698 } 19699 19700 /** 19701 * Prepare app data for the given app just after it was installed or 19702 * upgraded. This method carefully only touches users that it's installed 19703 * for, and it forces a restorecon to handle any seinfo changes. 19704 * <p> 19705 * Verifies that directories exist and that ownership and labeling is 19706 * correct for all installed apps. If there is an ownership mismatch, it 19707 * will try recovering system apps by wiping data; third-party app data is 19708 * left intact. 19709 * <p> 19710 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19711 */ 19712 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19713 final PackageSetting ps; 19714 synchronized (mPackages) { 19715 ps = mSettings.mPackages.get(pkg.packageName); 19716 mSettings.writeKernelMappingLPr(ps); 19717 } 19718 19719 final UserManager um = mContext.getSystemService(UserManager.class); 19720 UserManagerInternal umInternal = getUserManagerInternal(); 19721 for (UserInfo user : um.getUsers()) { 19722 final int flags; 19723 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19724 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19725 } else if (umInternal.isUserRunning(user.id)) { 19726 flags = StorageManager.FLAG_STORAGE_DE; 19727 } else { 19728 continue; 19729 } 19730 19731 if (ps.getInstalled(user.id)) { 19732 // Whenever an app changes, force a restorecon of its data 19733 // TODO: when user data is locked, mark that we're still dirty 19734 prepareAppDataLIF(pkg, user.id, flags, true); 19735 } 19736 } 19737 } 19738 19739 /** 19740 * Prepare app data for the given app. 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, this 19744 * will try recovering system apps by wiping data; third-party app data is 19745 * left intact. 19746 */ 19747 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19748 boolean restoreconNeeded) { 19749 if (pkg == null) { 19750 Slog.wtf(TAG, "Package was null!", new Throwable()); 19751 return; 19752 } 19753 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19754 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19755 for (int i = 0; i < childCount; i++) { 19756 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19757 } 19758 } 19759 19760 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19761 boolean restoreconNeeded) { 19762 if (DEBUG_APP_DATA) { 19763 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19764 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19765 } 19766 19767 final String volumeUuid = pkg.volumeUuid; 19768 final String packageName = pkg.packageName; 19769 final ApplicationInfo app = pkg.applicationInfo; 19770 final int appId = UserHandle.getAppId(app.uid); 19771 19772 Preconditions.checkNotNull(app.seinfo); 19773 19774 try { 19775 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19776 appId, app.seinfo, app.targetSdkVersion); 19777 } catch (InstallerException e) { 19778 if (app.isSystemApp()) { 19779 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19780 + ", but trying to recover: " + e); 19781 destroyAppDataLeafLIF(pkg, userId, flags); 19782 try { 19783 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19784 appId, app.seinfo, app.targetSdkVersion); 19785 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19786 } catch (InstallerException e2) { 19787 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19788 } 19789 } else { 19790 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19791 } 19792 } 19793 19794 if (restoreconNeeded) { 19795 try { 19796 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19797 app.seinfo); 19798 } catch (InstallerException e) { 19799 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19800 } 19801 } 19802 19803 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19804 try { 19805 // CE storage is unlocked right now, so read out the inode and 19806 // remember for use later when it's locked 19807 // TODO: mark this structure as dirty so we persist it! 19808 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19809 StorageManager.FLAG_STORAGE_CE); 19810 synchronized (mPackages) { 19811 final PackageSetting ps = mSettings.mPackages.get(packageName); 19812 if (ps != null) { 19813 ps.setCeDataInode(ceDataInode, userId); 19814 } 19815 } 19816 } catch (InstallerException e) { 19817 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19818 } 19819 } 19820 19821 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19822 } 19823 19824 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19825 if (pkg == null) { 19826 Slog.wtf(TAG, "Package was null!", new Throwable()); 19827 return; 19828 } 19829 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19830 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19831 for (int i = 0; i < childCount; i++) { 19832 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19833 } 19834 } 19835 19836 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19837 final String volumeUuid = pkg.volumeUuid; 19838 final String packageName = pkg.packageName; 19839 final ApplicationInfo app = pkg.applicationInfo; 19840 19841 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19842 // Create a native library symlink only if we have native libraries 19843 // and if the native libraries are 32 bit libraries. We do not provide 19844 // this symlink for 64 bit libraries. 19845 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19846 final String nativeLibPath = app.nativeLibraryDir; 19847 try { 19848 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19849 nativeLibPath, userId); 19850 } catch (InstallerException e) { 19851 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19852 } 19853 } 19854 } 19855 } 19856 19857 /** 19858 * For system apps on non-FBE devices, this method migrates any existing 19859 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19860 * requested by the app. 19861 */ 19862 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19863 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19864 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19865 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19866 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19867 try { 19868 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19869 storageTarget); 19870 } catch (InstallerException e) { 19871 logCriticalInfo(Log.WARN, 19872 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19873 } 19874 return true; 19875 } else { 19876 return false; 19877 } 19878 } 19879 19880 public PackageFreezer freezePackage(String packageName, String killReason) { 19881 return new PackageFreezer(packageName, killReason); 19882 } 19883 19884 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19885 String killReason) { 19886 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19887 return new PackageFreezer(); 19888 } else { 19889 return freezePackage(packageName, killReason); 19890 } 19891 } 19892 19893 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19894 String killReason) { 19895 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19896 return new PackageFreezer(); 19897 } else { 19898 return freezePackage(packageName, killReason); 19899 } 19900 } 19901 19902 /** 19903 * Class that freezes and kills the given package upon creation, and 19904 * unfreezes it upon closing. This is typically used when doing surgery on 19905 * app code/data to prevent the app from running while you're working. 19906 */ 19907 private class PackageFreezer implements AutoCloseable { 19908 private final String mPackageName; 19909 private final PackageFreezer[] mChildren; 19910 19911 private final boolean mWeFroze; 19912 19913 private final AtomicBoolean mClosed = new AtomicBoolean(); 19914 private final CloseGuard mCloseGuard = CloseGuard.get(); 19915 19916 /** 19917 * Create and return a stub freezer that doesn't actually do anything, 19918 * typically used when someone requested 19919 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19920 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19921 */ 19922 public PackageFreezer() { 19923 mPackageName = null; 19924 mChildren = null; 19925 mWeFroze = false; 19926 mCloseGuard.open("close"); 19927 } 19928 19929 public PackageFreezer(String packageName, String killReason) { 19930 synchronized (mPackages) { 19931 mPackageName = packageName; 19932 mWeFroze = mFrozenPackages.add(mPackageName); 19933 19934 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19935 if (ps != null) { 19936 killApplication(ps.name, ps.appId, killReason); 19937 } 19938 19939 final PackageParser.Package p = mPackages.get(packageName); 19940 if (p != null && p.childPackages != null) { 19941 final int N = p.childPackages.size(); 19942 mChildren = new PackageFreezer[N]; 19943 for (int i = 0; i < N; i++) { 19944 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19945 killReason); 19946 } 19947 } else { 19948 mChildren = null; 19949 } 19950 } 19951 mCloseGuard.open("close"); 19952 } 19953 19954 @Override 19955 protected void finalize() throws Throwable { 19956 try { 19957 mCloseGuard.warnIfOpen(); 19958 close(); 19959 } finally { 19960 super.finalize(); 19961 } 19962 } 19963 19964 @Override 19965 public void close() { 19966 mCloseGuard.close(); 19967 if (mClosed.compareAndSet(false, true)) { 19968 synchronized (mPackages) { 19969 if (mWeFroze) { 19970 mFrozenPackages.remove(mPackageName); 19971 } 19972 19973 if (mChildren != null) { 19974 for (PackageFreezer freezer : mChildren) { 19975 freezer.close(); 19976 } 19977 } 19978 } 19979 } 19980 } 19981 } 19982 19983 /** 19984 * Verify that given package is currently frozen. 19985 */ 19986 private void checkPackageFrozen(String packageName) { 19987 synchronized (mPackages) { 19988 if (!mFrozenPackages.contains(packageName)) { 19989 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19990 } 19991 } 19992 } 19993 19994 @Override 19995 public int movePackage(final String packageName, final String volumeUuid) { 19996 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19997 19998 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19999 final int moveId = mNextMoveId.getAndIncrement(); 20000 mHandler.post(new Runnable() { 20001 @Override 20002 public void run() { 20003 try { 20004 movePackageInternal(packageName, volumeUuid, moveId, user); 20005 } catch (PackageManagerException e) { 20006 Slog.w(TAG, "Failed to move " + packageName, e); 20007 mMoveCallbacks.notifyStatusChanged(moveId, 20008 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20009 } 20010 } 20011 }); 20012 return moveId; 20013 } 20014 20015 private void movePackageInternal(final String packageName, final String volumeUuid, 20016 final int moveId, UserHandle user) throws PackageManagerException { 20017 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20018 final PackageManager pm = mContext.getPackageManager(); 20019 20020 final boolean currentAsec; 20021 final String currentVolumeUuid; 20022 final File codeFile; 20023 final String installerPackageName; 20024 final String packageAbiOverride; 20025 final int appId; 20026 final String seinfo; 20027 final String label; 20028 final int targetSdkVersion; 20029 final PackageFreezer freezer; 20030 final int[] installedUserIds; 20031 20032 // reader 20033 synchronized (mPackages) { 20034 final PackageParser.Package pkg = mPackages.get(packageName); 20035 final PackageSetting ps = mSettings.mPackages.get(packageName); 20036 if (pkg == null || ps == null) { 20037 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 20038 } 20039 20040 if (pkg.applicationInfo.isSystemApp()) { 20041 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 20042 "Cannot move system application"); 20043 } 20044 20045 if (pkg.applicationInfo.isExternalAsec()) { 20046 currentAsec = true; 20047 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20048 } else if (pkg.applicationInfo.isForwardLocked()) { 20049 currentAsec = true; 20050 currentVolumeUuid = "forward_locked"; 20051 } else { 20052 currentAsec = false; 20053 currentVolumeUuid = ps.volumeUuid; 20054 20055 final File probe = new File(pkg.codePath); 20056 final File probeOat = new File(probe, "oat"); 20057 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20058 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20059 "Move only supported for modern cluster style installs"); 20060 } 20061 } 20062 20063 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20064 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20065 "Package already moved to " + volumeUuid); 20066 } 20067 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20068 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20069 "Device admin cannot be moved"); 20070 } 20071 20072 if (mFrozenPackages.contains(packageName)) { 20073 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20074 "Failed to move already frozen package"); 20075 } 20076 20077 codeFile = new File(pkg.codePath); 20078 installerPackageName = ps.installerPackageName; 20079 packageAbiOverride = ps.cpuAbiOverrideString; 20080 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20081 seinfo = pkg.applicationInfo.seinfo; 20082 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20083 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20084 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20085 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20086 } 20087 20088 final Bundle extras = new Bundle(); 20089 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20090 extras.putString(Intent.EXTRA_TITLE, label); 20091 mMoveCallbacks.notifyCreated(moveId, extras); 20092 20093 int installFlags; 20094 final boolean moveCompleteApp; 20095 final File measurePath; 20096 20097 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20098 installFlags = INSTALL_INTERNAL; 20099 moveCompleteApp = !currentAsec; 20100 measurePath = Environment.getDataAppDirectory(volumeUuid); 20101 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20102 installFlags = INSTALL_EXTERNAL; 20103 moveCompleteApp = false; 20104 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20105 } else { 20106 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20107 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20108 || !volume.isMountedWritable()) { 20109 freezer.close(); 20110 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20111 "Move location not mounted private volume"); 20112 } 20113 20114 Preconditions.checkState(!currentAsec); 20115 20116 installFlags = INSTALL_INTERNAL; 20117 moveCompleteApp = true; 20118 measurePath = Environment.getDataAppDirectory(volumeUuid); 20119 } 20120 20121 final PackageStats stats = new PackageStats(null, -1); 20122 synchronized (mInstaller) { 20123 for (int userId : installedUserIds) { 20124 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20125 freezer.close(); 20126 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20127 "Failed to measure package size"); 20128 } 20129 } 20130 } 20131 20132 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20133 + stats.dataSize); 20134 20135 final long startFreeBytes = measurePath.getFreeSpace(); 20136 final long sizeBytes; 20137 if (moveCompleteApp) { 20138 sizeBytes = stats.codeSize + stats.dataSize; 20139 } else { 20140 sizeBytes = stats.codeSize; 20141 } 20142 20143 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20144 freezer.close(); 20145 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20146 "Not enough free space to move"); 20147 } 20148 20149 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20150 20151 final CountDownLatch installedLatch = new CountDownLatch(1); 20152 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20153 @Override 20154 public void onUserActionRequired(Intent intent) throws RemoteException { 20155 throw new IllegalStateException(); 20156 } 20157 20158 @Override 20159 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20160 Bundle extras) throws RemoteException { 20161 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20162 + PackageManager.installStatusToString(returnCode, msg)); 20163 20164 installedLatch.countDown(); 20165 freezer.close(); 20166 20167 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20168 switch (status) { 20169 case PackageInstaller.STATUS_SUCCESS: 20170 mMoveCallbacks.notifyStatusChanged(moveId, 20171 PackageManager.MOVE_SUCCEEDED); 20172 break; 20173 case PackageInstaller.STATUS_FAILURE_STORAGE: 20174 mMoveCallbacks.notifyStatusChanged(moveId, 20175 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20176 break; 20177 default: 20178 mMoveCallbacks.notifyStatusChanged(moveId, 20179 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20180 break; 20181 } 20182 } 20183 }; 20184 20185 final MoveInfo move; 20186 if (moveCompleteApp) { 20187 // Kick off a thread to report progress estimates 20188 new Thread() { 20189 @Override 20190 public void run() { 20191 while (true) { 20192 try { 20193 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20194 break; 20195 } 20196 } catch (InterruptedException ignored) { 20197 } 20198 20199 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20200 final int progress = 10 + (int) MathUtils.constrain( 20201 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20202 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20203 } 20204 } 20205 }.start(); 20206 20207 final String dataAppName = codeFile.getName(); 20208 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20209 dataAppName, appId, seinfo, targetSdkVersion); 20210 } else { 20211 move = null; 20212 } 20213 20214 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20215 20216 final Message msg = mHandler.obtainMessage(INIT_COPY); 20217 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20218 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20219 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20220 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20221 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20222 msg.obj = params; 20223 20224 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20225 System.identityHashCode(msg.obj)); 20226 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20227 System.identityHashCode(msg.obj)); 20228 20229 mHandler.sendMessage(msg); 20230 } 20231 20232 @Override 20233 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20234 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20235 20236 final int realMoveId = mNextMoveId.getAndIncrement(); 20237 final Bundle extras = new Bundle(); 20238 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20239 mMoveCallbacks.notifyCreated(realMoveId, extras); 20240 20241 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20242 @Override 20243 public void onCreated(int moveId, Bundle extras) { 20244 // Ignored 20245 } 20246 20247 @Override 20248 public void onStatusChanged(int moveId, int status, long estMillis) { 20249 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20250 } 20251 }; 20252 20253 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20254 storage.setPrimaryStorageUuid(volumeUuid, callback); 20255 return realMoveId; 20256 } 20257 20258 @Override 20259 public int getMoveStatus(int moveId) { 20260 mContext.enforceCallingOrSelfPermission( 20261 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20262 return mMoveCallbacks.mLastStatus.get(moveId); 20263 } 20264 20265 @Override 20266 public void registerMoveCallback(IPackageMoveObserver callback) { 20267 mContext.enforceCallingOrSelfPermission( 20268 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20269 mMoveCallbacks.register(callback); 20270 } 20271 20272 @Override 20273 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20274 mContext.enforceCallingOrSelfPermission( 20275 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20276 mMoveCallbacks.unregister(callback); 20277 } 20278 20279 @Override 20280 public boolean setInstallLocation(int loc) { 20281 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20282 null); 20283 if (getInstallLocation() == loc) { 20284 return true; 20285 } 20286 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20287 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20288 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20289 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20290 return true; 20291 } 20292 return false; 20293 } 20294 20295 @Override 20296 public int getInstallLocation() { 20297 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20298 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20299 PackageHelper.APP_INSTALL_AUTO); 20300 } 20301 20302 /** Called by UserManagerService */ 20303 void cleanUpUser(UserManagerService userManager, int userHandle) { 20304 synchronized (mPackages) { 20305 mDirtyUsers.remove(userHandle); 20306 mUserNeedsBadging.delete(userHandle); 20307 mSettings.removeUserLPw(userHandle); 20308 mPendingBroadcasts.remove(userHandle); 20309 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20310 removeUnusedPackagesLPw(userManager, userHandle); 20311 } 20312 } 20313 20314 /** 20315 * We're removing userHandle and would like to remove any downloaded packages 20316 * that are no longer in use by any other user. 20317 * @param userHandle the user being removed 20318 */ 20319 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20320 final boolean DEBUG_CLEAN_APKS = false; 20321 int [] users = userManager.getUserIds(); 20322 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20323 while (psit.hasNext()) { 20324 PackageSetting ps = psit.next(); 20325 if (ps.pkg == null) { 20326 continue; 20327 } 20328 final String packageName = ps.pkg.packageName; 20329 // Skip over if system app 20330 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20331 continue; 20332 } 20333 if (DEBUG_CLEAN_APKS) { 20334 Slog.i(TAG, "Checking package " + packageName); 20335 } 20336 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20337 if (keep) { 20338 if (DEBUG_CLEAN_APKS) { 20339 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20340 } 20341 } else { 20342 for (int i = 0; i < users.length; i++) { 20343 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20344 keep = true; 20345 if (DEBUG_CLEAN_APKS) { 20346 Slog.i(TAG, " Keeping package " + packageName + " for user " 20347 + users[i]); 20348 } 20349 break; 20350 } 20351 } 20352 } 20353 if (!keep) { 20354 if (DEBUG_CLEAN_APKS) { 20355 Slog.i(TAG, " Removing package " + packageName); 20356 } 20357 mHandler.post(new Runnable() { 20358 public void run() { 20359 deletePackageX(packageName, userHandle, 0); 20360 } //end run 20361 }); 20362 } 20363 } 20364 } 20365 20366 /** Called by UserManagerService */ 20367 void createNewUser(int userId) { 20368 synchronized (mInstallLock) { 20369 mSettings.createNewUserLI(this, mInstaller, userId); 20370 } 20371 synchronized (mPackages) { 20372 scheduleWritePackageRestrictionsLocked(userId); 20373 scheduleWritePackageListLocked(userId); 20374 applyFactoryDefaultBrowserLPw(userId); 20375 primeDomainVerificationsLPw(userId); 20376 } 20377 } 20378 20379 void onBeforeUserStartUninitialized(final int userId) { 20380 synchronized (mPackages) { 20381 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20382 return; 20383 } 20384 } 20385 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20386 // If permission review for legacy apps is required, we represent 20387 // dagerous permissions for such apps as always granted runtime 20388 // permissions to keep per user flag state whether review is needed. 20389 // Hence, if a new user is added we have to propagate dangerous 20390 // permission grants for these legacy apps. 20391 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20392 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20393 | UPDATE_PERMISSIONS_REPLACE_ALL); 20394 } 20395 } 20396 20397 @Override 20398 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20399 mContext.enforceCallingOrSelfPermission( 20400 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20401 "Only package verification agents can read the verifier device identity"); 20402 20403 synchronized (mPackages) { 20404 return mSettings.getVerifierDeviceIdentityLPw(); 20405 } 20406 } 20407 20408 @Override 20409 public void setPermissionEnforced(String permission, boolean enforced) { 20410 // TODO: Now that we no longer change GID for storage, this should to away. 20411 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20412 "setPermissionEnforced"); 20413 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20414 synchronized (mPackages) { 20415 if (mSettings.mReadExternalStorageEnforced == null 20416 || mSettings.mReadExternalStorageEnforced != enforced) { 20417 mSettings.mReadExternalStorageEnforced = enforced; 20418 mSettings.writeLPr(); 20419 } 20420 } 20421 // kill any non-foreground processes so we restart them and 20422 // grant/revoke the GID. 20423 final IActivityManager am = ActivityManagerNative.getDefault(); 20424 if (am != null) { 20425 final long token = Binder.clearCallingIdentity(); 20426 try { 20427 am.killProcessesBelowForeground("setPermissionEnforcement"); 20428 } catch (RemoteException e) { 20429 } finally { 20430 Binder.restoreCallingIdentity(token); 20431 } 20432 } 20433 } else { 20434 throw new IllegalArgumentException("No selective enforcement for " + permission); 20435 } 20436 } 20437 20438 @Override 20439 @Deprecated 20440 public boolean isPermissionEnforced(String permission) { 20441 return true; 20442 } 20443 20444 @Override 20445 public boolean isStorageLow() { 20446 final long token = Binder.clearCallingIdentity(); 20447 try { 20448 final DeviceStorageMonitorInternal 20449 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20450 if (dsm != null) { 20451 return dsm.isMemoryLow(); 20452 } else { 20453 return false; 20454 } 20455 } finally { 20456 Binder.restoreCallingIdentity(token); 20457 } 20458 } 20459 20460 @Override 20461 public IPackageInstaller getPackageInstaller() { 20462 return mInstallerService; 20463 } 20464 20465 private boolean userNeedsBadging(int userId) { 20466 int index = mUserNeedsBadging.indexOfKey(userId); 20467 if (index < 0) { 20468 final UserInfo userInfo; 20469 final long token = Binder.clearCallingIdentity(); 20470 try { 20471 userInfo = sUserManager.getUserInfo(userId); 20472 } finally { 20473 Binder.restoreCallingIdentity(token); 20474 } 20475 final boolean b; 20476 if (userInfo != null && userInfo.isManagedProfile()) { 20477 b = true; 20478 } else { 20479 b = false; 20480 } 20481 mUserNeedsBadging.put(userId, b); 20482 return b; 20483 } 20484 return mUserNeedsBadging.valueAt(index); 20485 } 20486 20487 @Override 20488 public KeySet getKeySetByAlias(String packageName, String alias) { 20489 if (packageName == null || alias == null) { 20490 return null; 20491 } 20492 synchronized(mPackages) { 20493 final PackageParser.Package pkg = mPackages.get(packageName); 20494 if (pkg == null) { 20495 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20496 throw new IllegalArgumentException("Unknown package: " + packageName); 20497 } 20498 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20499 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20500 } 20501 } 20502 20503 @Override 20504 public KeySet getSigningKeySet(String packageName) { 20505 if (packageName == null) { 20506 return null; 20507 } 20508 synchronized(mPackages) { 20509 final PackageParser.Package pkg = mPackages.get(packageName); 20510 if (pkg == null) { 20511 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20512 throw new IllegalArgumentException("Unknown package: " + packageName); 20513 } 20514 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20515 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20516 throw new SecurityException("May not access signing KeySet of other apps."); 20517 } 20518 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20519 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20520 } 20521 } 20522 20523 @Override 20524 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20525 if (packageName == null || ks == null) { 20526 return false; 20527 } 20528 synchronized(mPackages) { 20529 final PackageParser.Package pkg = mPackages.get(packageName); 20530 if (pkg == null) { 20531 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20532 throw new IllegalArgumentException("Unknown package: " + packageName); 20533 } 20534 IBinder ksh = ks.getToken(); 20535 if (ksh instanceof KeySetHandle) { 20536 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20537 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20538 } 20539 return false; 20540 } 20541 } 20542 20543 @Override 20544 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20545 if (packageName == null || ks == null) { 20546 return false; 20547 } 20548 synchronized(mPackages) { 20549 final PackageParser.Package pkg = mPackages.get(packageName); 20550 if (pkg == null) { 20551 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20552 throw new IllegalArgumentException("Unknown package: " + packageName); 20553 } 20554 IBinder ksh = ks.getToken(); 20555 if (ksh instanceof KeySetHandle) { 20556 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20557 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20558 } 20559 return false; 20560 } 20561 } 20562 20563 private void deletePackageIfUnusedLPr(final String packageName) { 20564 PackageSetting ps = mSettings.mPackages.get(packageName); 20565 if (ps == null) { 20566 return; 20567 } 20568 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20569 // TODO Implement atomic delete if package is unused 20570 // It is currently possible that the package will be deleted even if it is installed 20571 // after this method returns. 20572 mHandler.post(new Runnable() { 20573 public void run() { 20574 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20575 } 20576 }); 20577 } 20578 } 20579 20580 /** 20581 * Check and throw if the given before/after packages would be considered a 20582 * downgrade. 20583 */ 20584 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20585 throws PackageManagerException { 20586 if (after.versionCode < before.mVersionCode) { 20587 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20588 "Update version code " + after.versionCode + " is older than current " 20589 + before.mVersionCode); 20590 } else if (after.versionCode == before.mVersionCode) { 20591 if (after.baseRevisionCode < before.baseRevisionCode) { 20592 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20593 "Update base revision code " + after.baseRevisionCode 20594 + " is older than current " + before.baseRevisionCode); 20595 } 20596 20597 if (!ArrayUtils.isEmpty(after.splitNames)) { 20598 for (int i = 0; i < after.splitNames.length; i++) { 20599 final String splitName = after.splitNames[i]; 20600 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20601 if (j != -1) { 20602 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20603 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20604 "Update split " + splitName + " revision code " 20605 + after.splitRevisionCodes[i] + " is older than current " 20606 + before.splitRevisionCodes[j]); 20607 } 20608 } 20609 } 20610 } 20611 } 20612 } 20613 20614 private static class MoveCallbacks extends Handler { 20615 private static final int MSG_CREATED = 1; 20616 private static final int MSG_STATUS_CHANGED = 2; 20617 20618 private final RemoteCallbackList<IPackageMoveObserver> 20619 mCallbacks = new RemoteCallbackList<>(); 20620 20621 private final SparseIntArray mLastStatus = new SparseIntArray(); 20622 20623 public MoveCallbacks(Looper looper) { 20624 super(looper); 20625 } 20626 20627 public void register(IPackageMoveObserver callback) { 20628 mCallbacks.register(callback); 20629 } 20630 20631 public void unregister(IPackageMoveObserver callback) { 20632 mCallbacks.unregister(callback); 20633 } 20634 20635 @Override 20636 public void handleMessage(Message msg) { 20637 final SomeArgs args = (SomeArgs) msg.obj; 20638 final int n = mCallbacks.beginBroadcast(); 20639 for (int i = 0; i < n; i++) { 20640 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20641 try { 20642 invokeCallback(callback, msg.what, args); 20643 } catch (RemoteException ignored) { 20644 } 20645 } 20646 mCallbacks.finishBroadcast(); 20647 args.recycle(); 20648 } 20649 20650 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20651 throws RemoteException { 20652 switch (what) { 20653 case MSG_CREATED: { 20654 callback.onCreated(args.argi1, (Bundle) args.arg2); 20655 break; 20656 } 20657 case MSG_STATUS_CHANGED: { 20658 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20659 break; 20660 } 20661 } 20662 } 20663 20664 private void notifyCreated(int moveId, Bundle extras) { 20665 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20666 20667 final SomeArgs args = SomeArgs.obtain(); 20668 args.argi1 = moveId; 20669 args.arg2 = extras; 20670 obtainMessage(MSG_CREATED, args).sendToTarget(); 20671 } 20672 20673 private void notifyStatusChanged(int moveId, int status) { 20674 notifyStatusChanged(moveId, status, -1); 20675 } 20676 20677 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20678 Slog.v(TAG, "Move " + moveId + " status " + status); 20679 20680 final SomeArgs args = SomeArgs.obtain(); 20681 args.argi1 = moveId; 20682 args.argi2 = status; 20683 args.arg3 = estMillis; 20684 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20685 20686 synchronized (mLastStatus) { 20687 mLastStatus.put(moveId, status); 20688 } 20689 } 20690 } 20691 20692 private final static class OnPermissionChangeListeners extends Handler { 20693 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20694 20695 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20696 new RemoteCallbackList<>(); 20697 20698 public OnPermissionChangeListeners(Looper looper) { 20699 super(looper); 20700 } 20701 20702 @Override 20703 public void handleMessage(Message msg) { 20704 switch (msg.what) { 20705 case MSG_ON_PERMISSIONS_CHANGED: { 20706 final int uid = msg.arg1; 20707 handleOnPermissionsChanged(uid); 20708 } break; 20709 } 20710 } 20711 20712 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20713 mPermissionListeners.register(listener); 20714 20715 } 20716 20717 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20718 mPermissionListeners.unregister(listener); 20719 } 20720 20721 public void onPermissionsChanged(int uid) { 20722 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20723 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20724 } 20725 } 20726 20727 private void handleOnPermissionsChanged(int uid) { 20728 final int count = mPermissionListeners.beginBroadcast(); 20729 try { 20730 for (int i = 0; i < count; i++) { 20731 IOnPermissionsChangeListener callback = mPermissionListeners 20732 .getBroadcastItem(i); 20733 try { 20734 callback.onPermissionsChanged(uid); 20735 } catch (RemoteException e) { 20736 Log.e(TAG, "Permission listener is dead", e); 20737 } 20738 } 20739 } finally { 20740 mPermissionListeners.finishBroadcast(); 20741 } 20742 } 20743 } 20744 20745 private class PackageManagerInternalImpl extends PackageManagerInternal { 20746 @Override 20747 public void setLocationPackagesProvider(PackagesProvider provider) { 20748 synchronized (mPackages) { 20749 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20750 } 20751 } 20752 20753 @Override 20754 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20755 synchronized (mPackages) { 20756 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20757 } 20758 } 20759 20760 @Override 20761 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20762 synchronized (mPackages) { 20763 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20764 } 20765 } 20766 20767 @Override 20768 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20769 synchronized (mPackages) { 20770 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20771 } 20772 } 20773 20774 @Override 20775 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20776 synchronized (mPackages) { 20777 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20778 } 20779 } 20780 20781 @Override 20782 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20783 synchronized (mPackages) { 20784 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20785 } 20786 } 20787 20788 @Override 20789 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20790 synchronized (mPackages) { 20791 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20792 packageName, userId); 20793 } 20794 } 20795 20796 @Override 20797 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20798 synchronized (mPackages) { 20799 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20800 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20801 packageName, userId); 20802 } 20803 } 20804 20805 @Override 20806 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20807 synchronized (mPackages) { 20808 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20809 packageName, userId); 20810 } 20811 } 20812 20813 @Override 20814 public void setKeepUninstalledPackages(final List<String> packageList) { 20815 Preconditions.checkNotNull(packageList); 20816 List<String> removedFromList = null; 20817 synchronized (mPackages) { 20818 if (mKeepUninstalledPackages != null) { 20819 final int packagesCount = mKeepUninstalledPackages.size(); 20820 for (int i = 0; i < packagesCount; i++) { 20821 String oldPackage = mKeepUninstalledPackages.get(i); 20822 if (packageList != null && packageList.contains(oldPackage)) { 20823 continue; 20824 } 20825 if (removedFromList == null) { 20826 removedFromList = new ArrayList<>(); 20827 } 20828 removedFromList.add(oldPackage); 20829 } 20830 } 20831 mKeepUninstalledPackages = new ArrayList<>(packageList); 20832 if (removedFromList != null) { 20833 final int removedCount = removedFromList.size(); 20834 for (int i = 0; i < removedCount; i++) { 20835 deletePackageIfUnusedLPr(removedFromList.get(i)); 20836 } 20837 } 20838 } 20839 } 20840 20841 @Override 20842 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20843 synchronized (mPackages) { 20844 // If we do not support permission review, done. 20845 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20846 return false; 20847 } 20848 20849 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20850 if (packageSetting == null) { 20851 return false; 20852 } 20853 20854 // Permission review applies only to apps not supporting the new permission model. 20855 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20856 return false; 20857 } 20858 20859 // Legacy apps have the permission and get user consent on launch. 20860 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20861 return permissionsState.isPermissionReviewRequired(userId); 20862 } 20863 } 20864 20865 @Override 20866 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20867 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20868 } 20869 20870 @Override 20871 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20872 int userId) { 20873 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20874 } 20875 20876 @Override 20877 public void setDeviceAndProfileOwnerPackages( 20878 int deviceOwnerUserId, String deviceOwnerPackage, 20879 SparseArray<String> profileOwnerPackages) { 20880 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20881 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20882 } 20883 20884 @Override 20885 public boolean canPackageBeWiped(int userId, String packageName) { 20886 return mProtectedPackages.canPackageBeWiped(userId, 20887 packageName); 20888 } 20889 } 20890 20891 @Override 20892 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20893 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20894 synchronized (mPackages) { 20895 final long identity = Binder.clearCallingIdentity(); 20896 try { 20897 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20898 packageNames, userId); 20899 } finally { 20900 Binder.restoreCallingIdentity(identity); 20901 } 20902 } 20903 } 20904 20905 private static void enforceSystemOrPhoneCaller(String tag) { 20906 int callingUid = Binder.getCallingUid(); 20907 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20908 throw new SecurityException( 20909 "Cannot call " + tag + " from UID " + callingUid); 20910 } 20911 } 20912 20913 boolean isHistoricalPackageUsageAvailable() { 20914 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20915 } 20916 20917 /** 20918 * Return a <b>copy</b> of the collection of packages known to the package manager. 20919 * @return A copy of the values of mPackages. 20920 */ 20921 Collection<PackageParser.Package> getPackages() { 20922 synchronized (mPackages) { 20923 return new ArrayList<>(mPackages.values()); 20924 } 20925 } 20926 20927 /** 20928 * Logs process start information (including base APK hash) to the security log. 20929 * @hide 20930 */ 20931 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20932 String apkFile, int pid) { 20933 if (!SecurityLog.isLoggingEnabled()) { 20934 return; 20935 } 20936 Bundle data = new Bundle(); 20937 data.putLong("startTimestamp", System.currentTimeMillis()); 20938 data.putString("processName", processName); 20939 data.putInt("uid", uid); 20940 data.putString("seinfo", seinfo); 20941 data.putString("apkFile", apkFile); 20942 data.putInt("pid", pid); 20943 Message msg = mProcessLoggingHandler.obtainMessage( 20944 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20945 msg.setData(data); 20946 mProcessLoggingHandler.sendMessage(msg); 20947 } 20948} 20949