PackageManagerService.java revision c29f62c7388f550da2c7368c5dbc0aec7d1564fe
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.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.security.KeyStore; 201import android.security.SystemKeyStore; 202import android.system.ErrnoException; 203import android.system.Os; 204import android.text.TextUtils; 205import android.text.format.DateUtils; 206import android.util.ArrayMap; 207import android.util.ArraySet; 208import android.util.AtomicFile; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.AttributeCache; 243import com.android.server.EventLogTags; 244import com.android.server.FgThread; 245import com.android.server.IntentResolver; 246import com.android.server.LocalServices; 247import com.android.server.ServiceThread; 248import com.android.server.SystemConfig; 249import com.android.server.Watchdog; 250import com.android.server.net.NetworkPolicyManagerInternal; 251import com.android.server.pm.PermissionsState.PermissionState; 252import com.android.server.pm.Settings.DatabaseVersion; 253import com.android.server.pm.Settings.VersionInfo; 254import com.android.server.storage.DeviceStorageMonitorInternal; 255 256import dalvik.system.CloseGuard; 257import dalvik.system.DexFile; 258import dalvik.system.VMRuntime; 259 260import libcore.io.IoUtils; 261import libcore.util.EmptyArray; 262 263import org.xmlpull.v1.XmlPullParser; 264import org.xmlpull.v1.XmlPullParserException; 265import org.xmlpull.v1.XmlSerializer; 266 267import java.io.BufferedInputStream; 268import java.io.BufferedOutputStream; 269import java.io.BufferedReader; 270import java.io.ByteArrayInputStream; 271import java.io.ByteArrayOutputStream; 272import java.io.File; 273import java.io.FileDescriptor; 274import java.io.FileInputStream; 275import java.io.FileNotFoundException; 276import java.io.FileOutputStream; 277import java.io.FileReader; 278import java.io.FilenameFilter; 279import java.io.IOException; 280import java.io.InputStream; 281import java.io.PrintWriter; 282import java.nio.charset.StandardCharsets; 283import java.security.DigestInputStream; 284import java.security.MessageDigest; 285import java.security.NoSuchAlgorithmException; 286import java.security.PublicKey; 287import java.security.cert.Certificate; 288import java.security.cert.CertificateEncodingException; 289import java.security.cert.CertificateException; 290import java.text.SimpleDateFormat; 291import java.util.ArrayList; 292import java.util.Arrays; 293import java.util.Collection; 294import java.util.Collections; 295import java.util.Comparator; 296import java.util.Date; 297import java.util.HashSet; 298import java.util.Iterator; 299import java.util.List; 300import java.util.Map; 301import java.util.Objects; 302import java.util.Set; 303import java.util.concurrent.CountDownLatch; 304import java.util.concurrent.TimeUnit; 305import java.util.concurrent.atomic.AtomicBoolean; 306import java.util.concurrent.atomic.AtomicInteger; 307import java.util.concurrent.atomic.AtomicLong; 308 309/** 310 * Keep track of all those APKs everywhere. 311 * <p> 312 * Internally there are two important locks: 313 * <ul> 314 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 315 * and other related state. It is a fine-grained lock that should only be held 316 * momentarily, as it's one of the most contended locks in the system. 317 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 318 * operations typically involve heavy lifting of application data on disk. Since 319 * {@code installd} is single-threaded, and it's operations can often be slow, 320 * this lock should never be acquired while already holding {@link #mPackages}. 321 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 322 * holding {@link #mInstallLock}. 323 * </ul> 324 * Many internal methods rely on the caller to hold the appropriate locks, and 325 * this contract is expressed through method name suffixes: 326 * <ul> 327 * <li>fooLI(): the caller must hold {@link #mInstallLock} 328 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 329 * being modified must be frozen 330 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 331 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 332 * </ul> 333 * <p> 334 * Because this class is very central to the platform's security; please run all 335 * CTS and unit tests whenever making modifications: 336 * 337 * <pre> 338 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 339 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 340 * </pre> 341 */ 342public class PackageManagerService extends IPackageManager.Stub { 343 static final String TAG = "PackageManager"; 344 static final boolean DEBUG_SETTINGS = false; 345 static final boolean DEBUG_PREFERRED = false; 346 static final boolean DEBUG_UPGRADE = false; 347 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 348 private static final boolean DEBUG_BACKUP = false; 349 private static final boolean DEBUG_INSTALL = false; 350 private static final boolean DEBUG_REMOVE = false; 351 private static final boolean DEBUG_BROADCASTS = false; 352 private static final boolean DEBUG_SHOW_INFO = false; 353 private static final boolean DEBUG_PACKAGE_INFO = false; 354 private static final boolean DEBUG_INTENT_MATCHING = false; 355 private static final boolean DEBUG_PACKAGE_SCANNING = false; 356 private static final boolean DEBUG_VERIFY = false; 357 private static final boolean DEBUG_FILTERS = false; 358 359 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 360 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 361 // user, but by default initialize to this. 362 static final boolean DEBUG_DEXOPT = false; 363 364 private static final boolean DEBUG_ABI_SELECTION = false; 365 private static final boolean DEBUG_EPHEMERAL = false; 366 private static final boolean DEBUG_TRIAGED_MISSING = false; 367 private static final boolean DEBUG_APP_DATA = false; 368 369 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 370 371 private static final boolean DISABLE_EPHEMERAL_APPS = true; 372 373 private static final int RADIO_UID = Process.PHONE_UID; 374 private static final int LOG_UID = Process.LOG_UID; 375 private static final int NFC_UID = Process.NFC_UID; 376 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 377 private static final int SHELL_UID = Process.SHELL_UID; 378 379 // Cap the size of permission trees that 3rd party apps can define 380 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 381 382 // Suffix used during package installation when copying/moving 383 // package apks to install directory. 384 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 385 386 static final int SCAN_NO_DEX = 1<<1; 387 static final int SCAN_FORCE_DEX = 1<<2; 388 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 389 static final int SCAN_NEW_INSTALL = 1<<4; 390 static final int SCAN_NO_PATHS = 1<<5; 391 static final int SCAN_UPDATE_TIME = 1<<6; 392 static final int SCAN_DEFER_DEX = 1<<7; 393 static final int SCAN_BOOTING = 1<<8; 394 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 395 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 396 static final int SCAN_REPLACING = 1<<11; 397 static final int SCAN_REQUIRE_KNOWN = 1<<12; 398 static final int SCAN_MOVE = 1<<13; 399 static final int SCAN_INITIAL = 1<<14; 400 static final int SCAN_CHECK_ONLY = 1<<15; 401 static final int SCAN_DONT_KILL_APP = 1<<17; 402 static final int SCAN_IGNORE_FROZEN = 1<<18; 403 404 static final int REMOVE_CHATTY = 1<<16; 405 406 private static final int[] EMPTY_INT_ARRAY = new int[0]; 407 408 /** 409 * Timeout (in milliseconds) after which the watchdog should declare that 410 * our handler thread is wedged. The usual default for such things is one 411 * minute but we sometimes do very lengthy I/O operations on this thread, 412 * such as installing multi-gigabyte applications, so ours needs to be longer. 413 */ 414 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 415 416 /** 417 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 418 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 419 * settings entry if available, otherwise we use the hardcoded default. If it's been 420 * more than this long since the last fstrim, we force one during the boot sequence. 421 * 422 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 423 * one gets run at the next available charging+idle time. This final mandatory 424 * no-fstrim check kicks in only of the other scheduling criteria is never met. 425 */ 426 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 427 428 /** 429 * Whether verification is enabled by default. 430 */ 431 private static final boolean DEFAULT_VERIFY_ENABLE = true; 432 433 /** 434 * The default maximum time to wait for the verification agent to return in 435 * milliseconds. 436 */ 437 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 438 439 /** 440 * The default response for package verification timeout. 441 * 442 * This can be either PackageManager.VERIFICATION_ALLOW or 443 * PackageManager.VERIFICATION_REJECT. 444 */ 445 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 446 447 static final String PLATFORM_PACKAGE_NAME = "android"; 448 449 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 450 451 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 452 DEFAULT_CONTAINER_PACKAGE, 453 "com.android.defcontainer.DefaultContainerService"); 454 455 private static final String KILL_APP_REASON_GIDS_CHANGED = 456 "permission grant or revoke changed gids"; 457 458 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 459 "permissions revoked"; 460 461 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 462 463 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 464 465 /** Permission grant: not grant the permission. */ 466 private static final int GRANT_DENIED = 1; 467 468 /** Permission grant: grant the permission as an install permission. */ 469 private static final int GRANT_INSTALL = 2; 470 471 /** Permission grant: grant the permission as a runtime one. */ 472 private static final int GRANT_RUNTIME = 3; 473 474 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 475 private static final int GRANT_UPGRADE = 4; 476 477 /** Canonical intent used to identify what counts as a "web browser" app */ 478 private static final Intent sBrowserIntent; 479 static { 480 sBrowserIntent = new Intent(); 481 sBrowserIntent.setAction(Intent.ACTION_VIEW); 482 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 483 sBrowserIntent.setData(Uri.parse("http:")); 484 } 485 486 /** 487 * The set of all protected actions [i.e. those actions for which a high priority 488 * intent filter is disallowed]. 489 */ 490 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 491 static { 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 494 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 495 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 496 } 497 498 // Compilation reasons. 499 public static final int REASON_FIRST_BOOT = 0; 500 public static final int REASON_BOOT = 1; 501 public static final int REASON_INSTALL = 2; 502 public static final int REASON_BACKGROUND_DEXOPT = 3; 503 public static final int REASON_AB_OTA = 4; 504 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 505 public static final int REASON_SHARED_APK = 6; 506 public static final int REASON_FORCED_DEXOPT = 7; 507 public static final int REASON_CORE_APP = 8; 508 509 public static final int REASON_LAST = REASON_CORE_APP; 510 511 /** Special library name that skips shared libraries check during compilation. */ 512 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 513 514 final ServiceThread mHandlerThread; 515 516 final PackageHandler mHandler; 517 518 private final ProcessLoggingHandler mProcessLoggingHandler; 519 520 /** 521 * Messages for {@link #mHandler} that need to wait for system ready before 522 * being dispatched. 523 */ 524 private ArrayList<Message> mPostSystemReadyMessages; 525 526 final int mSdkVersion = Build.VERSION.SDK_INT; 527 528 final Context mContext; 529 final boolean mFactoryTest; 530 final boolean mOnlyCore; 531 final DisplayMetrics mMetrics; 532 final int mDefParseFlags; 533 final String[] mSeparateProcesses; 534 final boolean mIsUpgrade; 535 final boolean mIsPreNUpgrade; 536 537 /** The location for ASEC container files on internal storage. */ 538 final String mAsecInternalPath; 539 540 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 541 // LOCK HELD. Can be called with mInstallLock held. 542 @GuardedBy("mInstallLock") 543 final Installer mInstaller; 544 545 /** Directory where installed third-party apps stored */ 546 final File mAppInstallDir; 547 final File mEphemeralInstallDir; 548 549 /** 550 * Directory to which applications installed internally have their 551 * 32 bit native libraries copied. 552 */ 553 private File mAppLib32InstallDir; 554 555 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 556 // apps. 557 final File mDrmAppPrivateInstallDir; 558 559 // ---------------------------------------------------------------- 560 561 // Lock for state used when installing and doing other long running 562 // operations. Methods that must be called with this lock held have 563 // the suffix "LI". 564 final Object mInstallLock = new Object(); 565 566 // ---------------------------------------------------------------- 567 568 // Keys are String (package name), values are Package. This also serves 569 // as the lock for the global state. Methods that must be called with 570 // this lock held have the prefix "LP". 571 @GuardedBy("mPackages") 572 final ArrayMap<String, PackageParser.Package> mPackages = 573 new ArrayMap<String, PackageParser.Package>(); 574 575 final ArrayMap<String, Set<String>> mKnownCodebase = 576 new ArrayMap<String, Set<String>>(); 577 578 // Tracks available target package names -> overlay package paths. 579 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 580 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 581 582 /** 583 * Tracks new system packages [received in an OTA] that we expect to 584 * find updated user-installed versions. Keys are package name, values 585 * are package location. 586 */ 587 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 588 /** 589 * Tracks high priority intent filters for protected actions. During boot, certain 590 * filter actions are protected and should never be allowed to have a high priority 591 * intent filter for them. However, there is one, and only one exception -- the 592 * setup wizard. It must be able to define a high priority intent filter for these 593 * actions to ensure there are no escapes from the wizard. We need to delay processing 594 * of these during boot as we need to look at all of the system packages in order 595 * to know which component is the setup wizard. 596 */ 597 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 598 /** 599 * Whether or not processing protected filters should be deferred. 600 */ 601 private boolean mDeferProtectedFilters = true; 602 603 /** 604 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 605 */ 606 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 607 /** 608 * Whether or not system app permissions should be promoted from install to runtime. 609 */ 610 boolean mPromoteSystemApps; 611 612 @GuardedBy("mPackages") 613 final Settings mSettings; 614 615 /** 616 * Set of package names that are currently "frozen", which means active 617 * surgery is being done on the code/data for that package. The platform 618 * will refuse to launch frozen packages to avoid race conditions. 619 * 620 * @see PackageFreezer 621 */ 622 @GuardedBy("mPackages") 623 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 624 625 final ProtectedPackages mProtectedPackages = new ProtectedPackages(); 626 627 boolean mRestoredSettings; 628 629 // System configuration read by SystemConfig. 630 final int[] mGlobalGids; 631 final SparseArray<ArraySet<String>> mSystemPermissions; 632 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 633 634 // If mac_permissions.xml was found for seinfo labeling. 635 boolean mFoundPolicyFile; 636 637 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 638 639 public static final class SharedLibraryEntry { 640 public final String path; 641 public final String apk; 642 643 SharedLibraryEntry(String _path, String _apk) { 644 path = _path; 645 apk = _apk; 646 } 647 } 648 649 // Currently known shared libraries. 650 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 651 new ArrayMap<String, SharedLibraryEntry>(); 652 653 // All available activities, for your resolving pleasure. 654 final ActivityIntentResolver mActivities = 655 new ActivityIntentResolver(); 656 657 // All available receivers, for your resolving pleasure. 658 final ActivityIntentResolver mReceivers = 659 new ActivityIntentResolver(); 660 661 // All available services, for your resolving pleasure. 662 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 663 664 // All available providers, for your resolving pleasure. 665 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 666 667 // Mapping from provider base names (first directory in content URI codePath) 668 // to the provider information. 669 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 670 new ArrayMap<String, PackageParser.Provider>(); 671 672 // Mapping from instrumentation class names to info about them. 673 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 674 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 675 676 // Mapping from permission names to info about them. 677 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 678 new ArrayMap<String, PackageParser.PermissionGroup>(); 679 680 // Packages whose data we have transfered into another package, thus 681 // should no longer exist. 682 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 683 684 // Broadcast actions that are only available to the system. 685 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 686 687 /** List of packages waiting for verification. */ 688 final SparseArray<PackageVerificationState> mPendingVerification 689 = new SparseArray<PackageVerificationState>(); 690 691 /** Set of packages associated with each app op permission. */ 692 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 693 694 final PackageInstallerService mInstallerService; 695 696 private final PackageDexOptimizer mPackageDexOptimizer; 697 698 private AtomicInteger mNextMoveId = new AtomicInteger(); 699 private final MoveCallbacks mMoveCallbacks; 700 701 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 702 703 // Cache of users who need badging. 704 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 705 706 /** Token for keys in mPendingVerification. */ 707 private int mPendingVerificationToken = 0; 708 709 volatile boolean mSystemReady; 710 volatile boolean mSafeMode; 711 volatile boolean mHasSystemUidErrors; 712 713 ApplicationInfo mAndroidApplication; 714 final ActivityInfo mResolveActivity = new ActivityInfo(); 715 final ResolveInfo mResolveInfo = new ResolveInfo(); 716 ComponentName mResolveComponentName; 717 PackageParser.Package mPlatformPackage; 718 ComponentName mCustomResolverComponentName; 719 720 boolean mResolverReplaced = false; 721 722 private final @Nullable ComponentName mIntentFilterVerifierComponent; 723 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 724 725 private int mIntentFilterVerificationToken = 0; 726 727 /** Component that knows whether or not an ephemeral application exists */ 728 final ComponentName mEphemeralResolverComponent; 729 /** The service connection to the ephemeral resolver */ 730 final EphemeralResolverConnection mEphemeralResolverConnection; 731 732 /** Component used to install ephemeral applications */ 733 final ComponentName mEphemeralInstallerComponent; 734 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 735 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 736 737 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 738 = new SparseArray<IntentFilterVerificationState>(); 739 740 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 741 new DefaultPermissionGrantPolicy(this); 742 743 // List of packages names to keep cached, even if they are uninstalled for all users 744 private List<String> mKeepUninstalledPackages; 745 746 private UserManagerInternal mUserManagerInternal; 747 748 private static class IFVerificationParams { 749 PackageParser.Package pkg; 750 boolean replacing; 751 int userId; 752 int verifierUid; 753 754 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 755 int _userId, int _verifierUid) { 756 pkg = _pkg; 757 replacing = _replacing; 758 userId = _userId; 759 replacing = _replacing; 760 verifierUid = _verifierUid; 761 } 762 } 763 764 private interface IntentFilterVerifier<T extends IntentFilter> { 765 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 766 T filter, String packageName); 767 void startVerifications(int userId); 768 void receiveVerificationResponse(int verificationId); 769 } 770 771 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 772 private Context mContext; 773 private ComponentName mIntentFilterVerifierComponent; 774 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 775 776 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 777 mContext = context; 778 mIntentFilterVerifierComponent = verifierComponent; 779 } 780 781 private String getDefaultScheme() { 782 return IntentFilter.SCHEME_HTTPS; 783 } 784 785 @Override 786 public void startVerifications(int userId) { 787 // Launch verifications requests 788 int count = mCurrentIntentFilterVerifications.size(); 789 for (int n=0; n<count; n++) { 790 int verificationId = mCurrentIntentFilterVerifications.get(n); 791 final IntentFilterVerificationState ivs = 792 mIntentFilterVerificationStates.get(verificationId); 793 794 String packageName = ivs.getPackageName(); 795 796 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 797 final int filterCount = filters.size(); 798 ArraySet<String> domainsSet = new ArraySet<>(); 799 for (int m=0; m<filterCount; m++) { 800 PackageParser.ActivityIntentInfo filter = filters.get(m); 801 domainsSet.addAll(filter.getHostsList()); 802 } 803 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 804 synchronized (mPackages) { 805 if (mSettings.createIntentFilterVerificationIfNeededLPw( 806 packageName, domainsList) != null) { 807 scheduleWriteSettingsLocked(); 808 } 809 } 810 sendVerificationRequest(userId, verificationId, ivs); 811 } 812 mCurrentIntentFilterVerifications.clear(); 813 } 814 815 private void sendVerificationRequest(int userId, int verificationId, 816 IntentFilterVerificationState ivs) { 817 818 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 821 verificationId); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 824 getDefaultScheme()); 825 verificationIntent.putExtra( 826 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 827 ivs.getHostsString()); 828 verificationIntent.putExtra( 829 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 830 ivs.getPackageName()); 831 verificationIntent.setComponent(mIntentFilterVerifierComponent); 832 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 833 834 UserHandle user = new UserHandle(userId); 835 mContext.sendBroadcastAsUser(verificationIntent, user); 836 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 837 "Sending IntentFilter verification broadcast"); 838 } 839 840 public void receiveVerificationResponse(int verificationId) { 841 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 842 843 final boolean verified = ivs.isVerified(); 844 845 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 846 final int count = filters.size(); 847 if (DEBUG_DOMAIN_VERIFICATION) { 848 Slog.i(TAG, "Received verification response " + verificationId 849 + " for " + count + " filters, verified=" + verified); 850 } 851 for (int n=0; n<count; n++) { 852 PackageParser.ActivityIntentInfo filter = filters.get(n); 853 filter.setVerified(verified); 854 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 856 + " verified with result:" + verified + " and hosts:" 857 + ivs.getHostsString()); 858 } 859 860 mIntentFilterVerificationStates.remove(verificationId); 861 862 final String packageName = ivs.getPackageName(); 863 IntentFilterVerificationInfo ivi = null; 864 865 synchronized (mPackages) { 866 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 867 } 868 if (ivi == null) { 869 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 870 + verificationId + " packageName:" + packageName); 871 return; 872 } 873 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 874 "Updating IntentFilterVerificationInfo for package " + packageName 875 +" verificationId:" + verificationId); 876 877 synchronized (mPackages) { 878 if (verified) { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 880 } else { 881 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 882 } 883 scheduleWriteSettingsLocked(); 884 885 final int userId = ivs.getUserId(); 886 if (userId != UserHandle.USER_ALL) { 887 final int userStatus = 888 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 889 890 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 891 boolean needUpdate = false; 892 893 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 894 // already been set by the User thru the Disambiguation dialog 895 switch (userStatus) { 896 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 897 if (verified) { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 899 } else { 900 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 901 } 902 needUpdate = true; 903 break; 904 905 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 906 if (verified) { 907 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 908 needUpdate = true; 909 } 910 break; 911 912 default: 913 // Nothing to do 914 } 915 916 if (needUpdate) { 917 mSettings.updateIntentFilterVerificationStatusLPw( 918 packageName, updatedStatus, userId); 919 scheduleWritePackageRestrictionsLocked(userId); 920 } 921 } 922 } 923 } 924 925 @Override 926 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 927 ActivityIntentInfo filter, String packageName) { 928 if (!hasValidDomains(filter)) { 929 return false; 930 } 931 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 932 if (ivs == null) { 933 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 934 packageName); 935 } 936 if (DEBUG_DOMAIN_VERIFICATION) { 937 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 938 } 939 ivs.addFilter(filter); 940 return true; 941 } 942 943 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 944 int userId, int verificationId, String packageName) { 945 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 946 verifierUid, userId, packageName); 947 ivs.setPendingState(); 948 synchronized (mPackages) { 949 mIntentFilterVerificationStates.append(verificationId, ivs); 950 mCurrentIntentFilterVerifications.add(verificationId); 951 } 952 return ivs; 953 } 954 } 955 956 private static boolean hasValidDomains(ActivityIntentInfo filter) { 957 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 958 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 959 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 960 } 961 962 // Set of pending broadcasts for aggregating enable/disable of components. 963 static class PendingPackageBroadcasts { 964 // for each user id, a map of <package name -> components within that package> 965 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 966 967 public PendingPackageBroadcasts() { 968 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 969 } 970 971 public ArrayList<String> get(int userId, String packageName) { 972 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 973 return packages.get(packageName); 974 } 975 976 public void put(int userId, String packageName, ArrayList<String> components) { 977 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 978 packages.put(packageName, components); 979 } 980 981 public void remove(int userId, String packageName) { 982 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 983 if (packages != null) { 984 packages.remove(packageName); 985 } 986 } 987 988 public void remove(int userId) { 989 mUidMap.remove(userId); 990 } 991 992 public int userIdCount() { 993 return mUidMap.size(); 994 } 995 996 public int userIdAt(int n) { 997 return mUidMap.keyAt(n); 998 } 999 1000 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 1001 return mUidMap.get(userId); 1002 } 1003 1004 public int size() { 1005 // total number of pending broadcast entries across all userIds 1006 int num = 0; 1007 for (int i = 0; i< mUidMap.size(); i++) { 1008 num += mUidMap.valueAt(i).size(); 1009 } 1010 return num; 1011 } 1012 1013 public void clear() { 1014 mUidMap.clear(); 1015 } 1016 1017 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1018 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1019 if (map == null) { 1020 map = new ArrayMap<String, ArrayList<String>>(); 1021 mUidMap.put(userId, map); 1022 } 1023 return map; 1024 } 1025 } 1026 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1027 1028 // Service Connection to remote media container service to copy 1029 // package uri's from external media onto secure containers 1030 // or internal storage. 1031 private IMediaContainerService mContainerService = null; 1032 1033 static final int SEND_PENDING_BROADCAST = 1; 1034 static final int MCS_BOUND = 3; 1035 static final int END_COPY = 4; 1036 static final int INIT_COPY = 5; 1037 static final int MCS_UNBIND = 6; 1038 static final int START_CLEANING_PACKAGE = 7; 1039 static final int FIND_INSTALL_LOC = 8; 1040 static final int POST_INSTALL = 9; 1041 static final int MCS_RECONNECT = 10; 1042 static final int MCS_GIVE_UP = 11; 1043 static final int UPDATED_MEDIA_STATUS = 12; 1044 static final int WRITE_SETTINGS = 13; 1045 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1046 static final int PACKAGE_VERIFIED = 15; 1047 static final int CHECK_PENDING_VERIFICATION = 16; 1048 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1049 static final int INTENT_FILTER_VERIFIED = 18; 1050 static final int WRITE_PACKAGE_LIST = 19; 1051 1052 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1053 1054 // Delay time in millisecs 1055 static final int BROADCAST_DELAY = 10 * 1000; 1056 1057 static UserManagerService sUserManager; 1058 1059 // Stores a list of users whose package restrictions file needs to be updated 1060 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1061 1062 final private DefaultContainerConnection mDefContainerConn = 1063 new DefaultContainerConnection(); 1064 class DefaultContainerConnection implements ServiceConnection { 1065 public void onServiceConnected(ComponentName name, IBinder service) { 1066 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1067 IMediaContainerService imcs = 1068 IMediaContainerService.Stub.asInterface(service); 1069 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1070 } 1071 1072 public void onServiceDisconnected(ComponentName name) { 1073 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1074 } 1075 } 1076 1077 // Recordkeeping of restore-after-install operations that are currently in flight 1078 // between the Package Manager and the Backup Manager 1079 static class PostInstallData { 1080 public InstallArgs args; 1081 public PackageInstalledInfo res; 1082 1083 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1084 args = _a; 1085 res = _r; 1086 } 1087 } 1088 1089 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1090 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1091 1092 // XML tags for backup/restore of various bits of state 1093 private static final String TAG_PREFERRED_BACKUP = "pa"; 1094 private static final String TAG_DEFAULT_APPS = "da"; 1095 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1096 1097 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1098 private static final String TAG_ALL_GRANTS = "rt-grants"; 1099 private static final String TAG_GRANT = "grant"; 1100 private static final String ATTR_PACKAGE_NAME = "pkg"; 1101 1102 private static final String TAG_PERMISSION = "perm"; 1103 private static final String ATTR_PERMISSION_NAME = "name"; 1104 private static final String ATTR_IS_GRANTED = "g"; 1105 private static final String ATTR_USER_SET = "set"; 1106 private static final String ATTR_USER_FIXED = "fixed"; 1107 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1108 1109 // System/policy permission grants are not backed up 1110 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1111 FLAG_PERMISSION_POLICY_FIXED 1112 | FLAG_PERMISSION_SYSTEM_FIXED 1113 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1114 1115 // And we back up these user-adjusted states 1116 private static final int USER_RUNTIME_GRANT_MASK = 1117 FLAG_PERMISSION_USER_SET 1118 | FLAG_PERMISSION_USER_FIXED 1119 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1120 1121 final @Nullable String mRequiredVerifierPackage; 1122 final @NonNull String mRequiredInstallerPackage; 1123 final @Nullable String mSetupWizardPackage; 1124 final @NonNull String mServicesSystemSharedLibraryPackageName; 1125 final @NonNull String mSharedSystemSharedLibraryPackageName; 1126 1127 private final PackageUsage mPackageUsage = new PackageUsage(); 1128 1129 private class PackageUsage { 1130 private static final int WRITE_INTERVAL 1131 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1132 1133 private final Object mFileLock = new Object(); 1134 private final AtomicLong mLastWritten = new AtomicLong(0); 1135 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1136 1137 private boolean mIsHistoricalPackageUsageAvailable = true; 1138 1139 boolean isHistoricalPackageUsageAvailable() { 1140 return mIsHistoricalPackageUsageAvailable; 1141 } 1142 1143 void write(boolean force) { 1144 if (force) { 1145 writeInternal(); 1146 return; 1147 } 1148 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1149 && !DEBUG_DEXOPT) { 1150 return; 1151 } 1152 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1153 new Thread("PackageUsage_DiskWriter") { 1154 @Override 1155 public void run() { 1156 try { 1157 writeInternal(); 1158 } finally { 1159 mBackgroundWriteRunning.set(false); 1160 } 1161 } 1162 }.start(); 1163 } 1164 } 1165 1166 private void writeInternal() { 1167 synchronized (mPackages) { 1168 synchronized (mFileLock) { 1169 AtomicFile file = getFile(); 1170 FileOutputStream f = null; 1171 try { 1172 f = file.startWrite(); 1173 BufferedOutputStream out = new BufferedOutputStream(f); 1174 FileUtils.setPermissions(file.getBaseFile().getPath(), 1175 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1176 StringBuilder sb = new StringBuilder(); 1177 1178 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1179 sb.append('\n'); 1180 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1181 1182 for (PackageParser.Package pkg : mPackages.values()) { 1183 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1184 continue; 1185 } 1186 sb.setLength(0); 1187 sb.append(pkg.packageName); 1188 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1189 sb.append(' '); 1190 sb.append(usageTimeInMillis); 1191 } 1192 sb.append('\n'); 1193 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1194 } 1195 out.flush(); 1196 file.finishWrite(f); 1197 } catch (IOException e) { 1198 if (f != null) { 1199 file.failWrite(f); 1200 } 1201 Log.e(TAG, "Failed to write package usage times", e); 1202 } 1203 } 1204 } 1205 mLastWritten.set(SystemClock.elapsedRealtime()); 1206 } 1207 1208 void readLP() { 1209 synchronized (mFileLock) { 1210 AtomicFile file = getFile(); 1211 BufferedInputStream in = null; 1212 try { 1213 in = new BufferedInputStream(file.openRead()); 1214 StringBuffer sb = new StringBuffer(); 1215 1216 String firstLine = readLine(in, sb); 1217 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1218 readVersion1LP(in, sb); 1219 } else { 1220 readVersion0LP(in, sb, firstLine); 1221 } 1222 } catch (FileNotFoundException expected) { 1223 mIsHistoricalPackageUsageAvailable = false; 1224 } catch (IOException e) { 1225 Log.w(TAG, "Failed to read package usage times", e); 1226 } finally { 1227 IoUtils.closeQuietly(in); 1228 } 1229 } 1230 mLastWritten.set(SystemClock.elapsedRealtime()); 1231 } 1232 1233 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1234 throws IOException { 1235 // Initial version of the file had no version number and stored one 1236 // package-timestamp pair per line. 1237 // Note that the first line has already been read from the InputStream. 1238 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1239 String[] tokens = line.split(" "); 1240 if (tokens.length != 2) { 1241 throw new IOException("Failed to parse " + line + 1242 " as package-timestamp pair."); 1243 } 1244 1245 String packageName = tokens[0]; 1246 PackageParser.Package pkg = mPackages.get(packageName); 1247 if (pkg == null) { 1248 continue; 1249 } 1250 1251 long timestamp = parseAsLong(tokens[1]); 1252 for (int reason = 0; 1253 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1254 reason++) { 1255 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1256 } 1257 } 1258 } 1259 1260 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1261 // Version 1 of the file started with the corresponding version 1262 // number and then stored a package name and eight timestamps per line. 1263 String line; 1264 while ((line = readLine(in, sb)) != null) { 1265 String[] tokens = line.split(" "); 1266 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1267 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1268 } 1269 1270 String packageName = tokens[0]; 1271 PackageParser.Package pkg = mPackages.get(packageName); 1272 if (pkg == null) { 1273 continue; 1274 } 1275 1276 for (int reason = 0; 1277 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1278 reason++) { 1279 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1280 } 1281 } 1282 } 1283 1284 private long parseAsLong(String token) throws IOException { 1285 try { 1286 return Long.parseLong(token); 1287 } catch (NumberFormatException e) { 1288 throw new IOException("Failed to parse " + token + " as a long.", e); 1289 } 1290 } 1291 1292 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1293 return readToken(in, sb, '\n'); 1294 } 1295 1296 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1297 throws IOException { 1298 sb.setLength(0); 1299 while (true) { 1300 int ch = in.read(); 1301 if (ch == -1) { 1302 if (sb.length() == 0) { 1303 return null; 1304 } 1305 throw new IOException("Unexpected EOF"); 1306 } 1307 if (ch == endOfToken) { 1308 return sb.toString(); 1309 } 1310 sb.append((char)ch); 1311 } 1312 } 1313 1314 private AtomicFile getFile() { 1315 File dataDir = Environment.getDataDirectory(); 1316 File systemDir = new File(dataDir, "system"); 1317 File fname = new File(systemDir, "package-usage.list"); 1318 return new AtomicFile(fname); 1319 } 1320 1321 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1322 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1323 } 1324 1325 class PackageHandler extends Handler { 1326 private boolean mBound = false; 1327 final ArrayList<HandlerParams> mPendingInstalls = 1328 new ArrayList<HandlerParams>(); 1329 1330 private boolean connectToService() { 1331 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1332 " DefaultContainerService"); 1333 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1334 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1335 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1336 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1338 mBound = true; 1339 return true; 1340 } 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1342 return false; 1343 } 1344 1345 private void disconnectService() { 1346 mContainerService = null; 1347 mBound = false; 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1349 mContext.unbindService(mDefContainerConn); 1350 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1351 } 1352 1353 PackageHandler(Looper looper) { 1354 super(looper); 1355 } 1356 1357 public void handleMessage(Message msg) { 1358 try { 1359 doHandleMessage(msg); 1360 } finally { 1361 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1362 } 1363 } 1364 1365 void doHandleMessage(Message msg) { 1366 switch (msg.what) { 1367 case INIT_COPY: { 1368 HandlerParams params = (HandlerParams) msg.obj; 1369 int idx = mPendingInstalls.size(); 1370 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1371 // If a bind was already initiated we dont really 1372 // need to do anything. The pending install 1373 // will be processed later on. 1374 if (!mBound) { 1375 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1376 System.identityHashCode(mHandler)); 1377 // If this is the only one pending we might 1378 // have to bind to the service again. 1379 if (!connectToService()) { 1380 Slog.e(TAG, "Failed to bind to media container service"); 1381 params.serviceError(); 1382 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1383 System.identityHashCode(mHandler)); 1384 if (params.traceMethod != null) { 1385 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1386 params.traceCookie); 1387 } 1388 return; 1389 } else { 1390 // Once we bind to the service, the first 1391 // pending request will be processed. 1392 mPendingInstalls.add(idx, params); 1393 } 1394 } else { 1395 mPendingInstalls.add(idx, params); 1396 // Already bound to the service. Just make 1397 // sure we trigger off processing the first request. 1398 if (idx == 0) { 1399 mHandler.sendEmptyMessage(MCS_BOUND); 1400 } 1401 } 1402 break; 1403 } 1404 case MCS_BOUND: { 1405 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1406 if (msg.obj != null) { 1407 mContainerService = (IMediaContainerService) msg.obj; 1408 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1409 System.identityHashCode(mHandler)); 1410 } 1411 if (mContainerService == null) { 1412 if (!mBound) { 1413 // Something seriously wrong since we are not bound and we are not 1414 // waiting for connection. Bail out. 1415 Slog.e(TAG, "Cannot bind to media container service"); 1416 for (HandlerParams params : mPendingInstalls) { 1417 // Indicate service bind error 1418 params.serviceError(); 1419 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1420 System.identityHashCode(params)); 1421 if (params.traceMethod != null) { 1422 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1423 params.traceMethod, params.traceCookie); 1424 } 1425 return; 1426 } 1427 mPendingInstalls.clear(); 1428 } else { 1429 Slog.w(TAG, "Waiting to connect to media container service"); 1430 } 1431 } else if (mPendingInstalls.size() > 0) { 1432 HandlerParams params = mPendingInstalls.get(0); 1433 if (params != null) { 1434 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1435 System.identityHashCode(params)); 1436 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1437 if (params.startCopy()) { 1438 // We are done... look for more work or to 1439 // go idle. 1440 if (DEBUG_SD_INSTALL) Log.i(TAG, 1441 "Checking for more work or unbind..."); 1442 // Delete pending install 1443 if (mPendingInstalls.size() > 0) { 1444 mPendingInstalls.remove(0); 1445 } 1446 if (mPendingInstalls.size() == 0) { 1447 if (mBound) { 1448 if (DEBUG_SD_INSTALL) Log.i(TAG, 1449 "Posting delayed MCS_UNBIND"); 1450 removeMessages(MCS_UNBIND); 1451 Message ubmsg = obtainMessage(MCS_UNBIND); 1452 // Unbind after a little delay, to avoid 1453 // continual thrashing. 1454 sendMessageDelayed(ubmsg, 10000); 1455 } 1456 } else { 1457 // There are more pending requests in queue. 1458 // Just post MCS_BOUND message to trigger processing 1459 // of next pending install. 1460 if (DEBUG_SD_INSTALL) Log.i(TAG, 1461 "Posting MCS_BOUND for next work"); 1462 mHandler.sendEmptyMessage(MCS_BOUND); 1463 } 1464 } 1465 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1466 } 1467 } else { 1468 // Should never happen ideally. 1469 Slog.w(TAG, "Empty queue"); 1470 } 1471 break; 1472 } 1473 case MCS_RECONNECT: { 1474 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1475 if (mPendingInstalls.size() > 0) { 1476 if (mBound) { 1477 disconnectService(); 1478 } 1479 if (!connectToService()) { 1480 Slog.e(TAG, "Failed to bind to media container service"); 1481 for (HandlerParams params : mPendingInstalls) { 1482 // Indicate service bind error 1483 params.serviceError(); 1484 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1485 System.identityHashCode(params)); 1486 } 1487 mPendingInstalls.clear(); 1488 } 1489 } 1490 break; 1491 } 1492 case MCS_UNBIND: { 1493 // If there is no actual work left, then time to unbind. 1494 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1495 1496 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1497 if (mBound) { 1498 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1499 1500 disconnectService(); 1501 } 1502 } else if (mPendingInstalls.size() > 0) { 1503 // There are more pending requests in queue. 1504 // Just post MCS_BOUND message to trigger processing 1505 // of next pending install. 1506 mHandler.sendEmptyMessage(MCS_BOUND); 1507 } 1508 1509 break; 1510 } 1511 case MCS_GIVE_UP: { 1512 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1513 HandlerParams params = mPendingInstalls.remove(0); 1514 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1515 System.identityHashCode(params)); 1516 break; 1517 } 1518 case SEND_PENDING_BROADCAST: { 1519 String packages[]; 1520 ArrayList<String> components[]; 1521 int size = 0; 1522 int uids[]; 1523 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1524 synchronized (mPackages) { 1525 if (mPendingBroadcasts == null) { 1526 return; 1527 } 1528 size = mPendingBroadcasts.size(); 1529 if (size <= 0) { 1530 // Nothing to be done. Just return 1531 return; 1532 } 1533 packages = new String[size]; 1534 components = new ArrayList[size]; 1535 uids = new int[size]; 1536 int i = 0; // filling out the above arrays 1537 1538 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1539 int packageUserId = mPendingBroadcasts.userIdAt(n); 1540 Iterator<Map.Entry<String, ArrayList<String>>> it 1541 = mPendingBroadcasts.packagesForUserId(packageUserId) 1542 .entrySet().iterator(); 1543 while (it.hasNext() && i < size) { 1544 Map.Entry<String, ArrayList<String>> ent = it.next(); 1545 packages[i] = ent.getKey(); 1546 components[i] = ent.getValue(); 1547 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1548 uids[i] = (ps != null) 1549 ? UserHandle.getUid(packageUserId, ps.appId) 1550 : -1; 1551 i++; 1552 } 1553 } 1554 size = i; 1555 mPendingBroadcasts.clear(); 1556 } 1557 // Send broadcasts 1558 for (int i = 0; i < size; i++) { 1559 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1560 } 1561 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1562 break; 1563 } 1564 case START_CLEANING_PACKAGE: { 1565 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1566 final String packageName = (String)msg.obj; 1567 final int userId = msg.arg1; 1568 final boolean andCode = msg.arg2 != 0; 1569 synchronized (mPackages) { 1570 if (userId == UserHandle.USER_ALL) { 1571 int[] users = sUserManager.getUserIds(); 1572 for (int user : users) { 1573 mSettings.addPackageToCleanLPw( 1574 new PackageCleanItem(user, packageName, andCode)); 1575 } 1576 } else { 1577 mSettings.addPackageToCleanLPw( 1578 new PackageCleanItem(userId, packageName, andCode)); 1579 } 1580 } 1581 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1582 startCleaningPackages(); 1583 } break; 1584 case POST_INSTALL: { 1585 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1586 1587 PostInstallData data = mRunningInstalls.get(msg.arg1); 1588 final boolean didRestore = (msg.arg2 != 0); 1589 mRunningInstalls.delete(msg.arg1); 1590 1591 if (data != null) { 1592 InstallArgs args = data.args; 1593 PackageInstalledInfo parentRes = data.res; 1594 1595 final boolean grantPermissions = (args.installFlags 1596 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1597 final boolean killApp = (args.installFlags 1598 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1599 final String[] grantedPermissions = args.installGrantPermissions; 1600 1601 // Handle the parent package 1602 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1603 grantedPermissions, didRestore, args.installerPackageName, 1604 args.observer); 1605 1606 // Handle the child packages 1607 final int childCount = (parentRes.addedChildPackages != null) 1608 ? parentRes.addedChildPackages.size() : 0; 1609 for (int i = 0; i < childCount; i++) { 1610 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1611 handlePackagePostInstall(childRes, grantPermissions, killApp, 1612 grantedPermissions, false, args.installerPackageName, 1613 args.observer); 1614 } 1615 1616 // Log tracing if needed 1617 if (args.traceMethod != null) { 1618 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1619 args.traceCookie); 1620 } 1621 } else { 1622 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1623 } 1624 1625 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1626 } break; 1627 case UPDATED_MEDIA_STATUS: { 1628 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1629 boolean reportStatus = msg.arg1 == 1; 1630 boolean doGc = msg.arg2 == 1; 1631 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1632 if (doGc) { 1633 // Force a gc to clear up stale containers. 1634 Runtime.getRuntime().gc(); 1635 } 1636 if (msg.obj != null) { 1637 @SuppressWarnings("unchecked") 1638 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1639 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1640 // Unload containers 1641 unloadAllContainers(args); 1642 } 1643 if (reportStatus) { 1644 try { 1645 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1646 PackageHelper.getMountService().finishMediaUpdate(); 1647 } catch (RemoteException e) { 1648 Log.e(TAG, "MountService not running?"); 1649 } 1650 } 1651 } break; 1652 case WRITE_SETTINGS: { 1653 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1654 synchronized (mPackages) { 1655 removeMessages(WRITE_SETTINGS); 1656 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1657 mSettings.writeLPr(); 1658 mDirtyUsers.clear(); 1659 } 1660 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1661 } break; 1662 case WRITE_PACKAGE_RESTRICTIONS: { 1663 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1664 synchronized (mPackages) { 1665 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1666 for (int userId : mDirtyUsers) { 1667 mSettings.writePackageRestrictionsLPr(userId); 1668 } 1669 mDirtyUsers.clear(); 1670 } 1671 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1672 } break; 1673 case WRITE_PACKAGE_LIST: { 1674 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1675 synchronized (mPackages) { 1676 removeMessages(WRITE_PACKAGE_LIST); 1677 mSettings.writePackageListLPr(msg.arg1); 1678 } 1679 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1680 } break; 1681 case CHECK_PENDING_VERIFICATION: { 1682 final int verificationId = msg.arg1; 1683 final PackageVerificationState state = mPendingVerification.get(verificationId); 1684 1685 if ((state != null) && !state.timeoutExtended()) { 1686 final InstallArgs args = state.getInstallArgs(); 1687 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1688 1689 Slog.i(TAG, "Verification timed out for " + originUri); 1690 mPendingVerification.remove(verificationId); 1691 1692 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1693 1694 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1695 Slog.i(TAG, "Continuing with installation of " + originUri); 1696 state.setVerifierResponse(Binder.getCallingUid(), 1697 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1698 broadcastPackageVerified(verificationId, originUri, 1699 PackageManager.VERIFICATION_ALLOW, 1700 state.getInstallArgs().getUser()); 1701 try { 1702 ret = args.copyApk(mContainerService, true); 1703 } catch (RemoteException e) { 1704 Slog.e(TAG, "Could not contact the ContainerService"); 1705 } 1706 } else { 1707 broadcastPackageVerified(verificationId, originUri, 1708 PackageManager.VERIFICATION_REJECT, 1709 state.getInstallArgs().getUser()); 1710 } 1711 1712 Trace.asyncTraceEnd( 1713 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1714 1715 processPendingInstall(args, ret); 1716 mHandler.sendEmptyMessage(MCS_UNBIND); 1717 } 1718 break; 1719 } 1720 case PACKAGE_VERIFIED: { 1721 final int verificationId = msg.arg1; 1722 1723 final PackageVerificationState state = mPendingVerification.get(verificationId); 1724 if (state == null) { 1725 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1726 break; 1727 } 1728 1729 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1730 1731 state.setVerifierResponse(response.callerUid, response.code); 1732 1733 if (state.isVerificationComplete()) { 1734 mPendingVerification.remove(verificationId); 1735 1736 final InstallArgs args = state.getInstallArgs(); 1737 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1738 1739 int ret; 1740 if (state.isInstallAllowed()) { 1741 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1742 broadcastPackageVerified(verificationId, originUri, 1743 response.code, state.getInstallArgs().getUser()); 1744 try { 1745 ret = args.copyApk(mContainerService, true); 1746 } catch (RemoteException e) { 1747 Slog.e(TAG, "Could not contact the ContainerService"); 1748 } 1749 } else { 1750 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1751 } 1752 1753 Trace.asyncTraceEnd( 1754 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1755 1756 processPendingInstall(args, ret); 1757 mHandler.sendEmptyMessage(MCS_UNBIND); 1758 } 1759 1760 break; 1761 } 1762 case START_INTENT_FILTER_VERIFICATIONS: { 1763 IFVerificationParams params = (IFVerificationParams) msg.obj; 1764 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1765 params.replacing, params.pkg); 1766 break; 1767 } 1768 case INTENT_FILTER_VERIFIED: { 1769 final int verificationId = msg.arg1; 1770 1771 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1772 verificationId); 1773 if (state == null) { 1774 Slog.w(TAG, "Invalid IntentFilter verification token " 1775 + verificationId + " received"); 1776 break; 1777 } 1778 1779 final int userId = state.getUserId(); 1780 1781 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1782 "Processing IntentFilter verification with token:" 1783 + verificationId + " and userId:" + userId); 1784 1785 final IntentFilterVerificationResponse response = 1786 (IntentFilterVerificationResponse) msg.obj; 1787 1788 state.setVerifierResponse(response.callerUid, response.code); 1789 1790 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1791 "IntentFilter verification with token:" + verificationId 1792 + " and userId:" + userId 1793 + " is settings verifier response with response code:" 1794 + response.code); 1795 1796 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1797 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1798 + response.getFailedDomainsString()); 1799 } 1800 1801 if (state.isVerificationComplete()) { 1802 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1803 } else { 1804 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1805 "IntentFilter verification with token:" + verificationId 1806 + " was not said to be complete"); 1807 } 1808 1809 break; 1810 } 1811 } 1812 } 1813 } 1814 1815 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1816 boolean killApp, String[] grantedPermissions, 1817 boolean launchedForRestore, String installerPackage, 1818 IPackageInstallObserver2 installObserver) { 1819 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1820 // Send the removed broadcasts 1821 if (res.removedInfo != null) { 1822 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1823 } 1824 1825 // Now that we successfully installed the package, grant runtime 1826 // permissions if requested before broadcasting the install. 1827 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1828 >= Build.VERSION_CODES.M) { 1829 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1830 } 1831 1832 final boolean update = res.removedInfo != null 1833 && res.removedInfo.removedPackage != null; 1834 1835 // If this is the first time we have child packages for a disabled privileged 1836 // app that had no children, we grant requested runtime permissions to the new 1837 // children if the parent on the system image had them already granted. 1838 if (res.pkg.parentPackage != null) { 1839 synchronized (mPackages) { 1840 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1841 } 1842 } 1843 1844 synchronized (mPackages) { 1845 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1846 } 1847 1848 final String packageName = res.pkg.applicationInfo.packageName; 1849 Bundle extras = new Bundle(1); 1850 extras.putInt(Intent.EXTRA_UID, res.uid); 1851 1852 // Determine the set of users who are adding this package for 1853 // the first time vs. those who are seeing an update. 1854 int[] firstUsers = EMPTY_INT_ARRAY; 1855 int[] updateUsers = EMPTY_INT_ARRAY; 1856 if (res.origUsers == null || res.origUsers.length == 0) { 1857 firstUsers = res.newUsers; 1858 } else { 1859 for (int newUser : res.newUsers) { 1860 boolean isNew = true; 1861 for (int origUser : res.origUsers) { 1862 if (origUser == newUser) { 1863 isNew = false; 1864 break; 1865 } 1866 } 1867 if (isNew) { 1868 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1869 } else { 1870 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1871 } 1872 } 1873 } 1874 1875 // Send installed broadcasts if the install/update is not ephemeral 1876 if (!isEphemeral(res.pkg)) { 1877 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1878 1879 // Send added for users that see the package for the first time 1880 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1881 extras, 0 /*flags*/, null /*targetPackage*/, 1882 null /*finishedReceiver*/, firstUsers); 1883 1884 // Send added for users that don't see the package for the first time 1885 if (update) { 1886 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1887 } 1888 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1889 extras, 0 /*flags*/, null /*targetPackage*/, 1890 null /*finishedReceiver*/, updateUsers); 1891 1892 // Send replaced for users that don't see the package for the first time 1893 if (update) { 1894 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1895 packageName, extras, 0 /*flags*/, 1896 null /*targetPackage*/, null /*finishedReceiver*/, 1897 updateUsers); 1898 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1899 null /*package*/, null /*extras*/, 0 /*flags*/, 1900 packageName /*targetPackage*/, 1901 null /*finishedReceiver*/, updateUsers); 1902 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1903 // First-install and we did a restore, so we're responsible for the 1904 // first-launch broadcast. 1905 if (DEBUG_BACKUP) { 1906 Slog.i(TAG, "Post-restore of " + packageName 1907 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1908 } 1909 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1910 } 1911 1912 // Send broadcast package appeared if forward locked/external for all users 1913 // treat asec-hosted packages like removable media on upgrade 1914 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1915 if (DEBUG_INSTALL) { 1916 Slog.i(TAG, "upgrading pkg " + res.pkg 1917 + " is ASEC-hosted -> AVAILABLE"); 1918 } 1919 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1920 ArrayList<String> pkgList = new ArrayList<>(1); 1921 pkgList.add(packageName); 1922 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1923 } 1924 } 1925 1926 // Work that needs to happen on first install within each user 1927 if (firstUsers != null && firstUsers.length > 0) { 1928 synchronized (mPackages) { 1929 for (int userId : firstUsers) { 1930 // If this app is a browser and it's newly-installed for some 1931 // users, clear any default-browser state in those users. The 1932 // app's nature doesn't depend on the user, so we can just check 1933 // its browser nature in any user and generalize. 1934 if (packageIsBrowser(packageName, userId)) { 1935 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1936 } 1937 1938 // We may also need to apply pending (restored) runtime 1939 // permission grants within these users. 1940 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1941 } 1942 } 1943 } 1944 1945 // Log current value of "unknown sources" setting 1946 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1947 getUnknownSourcesSettings()); 1948 1949 // Force a gc to clear up things 1950 Runtime.getRuntime().gc(); 1951 1952 // Remove the replaced package's older resources safely now 1953 // We delete after a gc for applications on sdcard. 1954 if (res.removedInfo != null && res.removedInfo.args != null) { 1955 synchronized (mInstallLock) { 1956 res.removedInfo.args.doPostDeleteLI(true); 1957 } 1958 } 1959 } 1960 1961 // If someone is watching installs - notify them 1962 if (installObserver != null) { 1963 try { 1964 Bundle extras = extrasForInstallResult(res); 1965 installObserver.onPackageInstalled(res.name, res.returnCode, 1966 res.returnMsg, extras); 1967 } catch (RemoteException e) { 1968 Slog.i(TAG, "Observer no longer exists."); 1969 } 1970 } 1971 } 1972 1973 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1974 PackageParser.Package pkg) { 1975 if (pkg.parentPackage == null) { 1976 return; 1977 } 1978 if (pkg.requestedPermissions == null) { 1979 return; 1980 } 1981 final PackageSetting disabledSysParentPs = mSettings 1982 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1983 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1984 || !disabledSysParentPs.isPrivileged() 1985 || (disabledSysParentPs.childPackageNames != null 1986 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1987 return; 1988 } 1989 final int[] allUserIds = sUserManager.getUserIds(); 1990 final int permCount = pkg.requestedPermissions.size(); 1991 for (int i = 0; i < permCount; i++) { 1992 String permission = pkg.requestedPermissions.get(i); 1993 BasePermission bp = mSettings.mPermissions.get(permission); 1994 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1995 continue; 1996 } 1997 for (int userId : allUserIds) { 1998 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1999 permission, userId)) { 2000 grantRuntimePermission(pkg.packageName, permission, userId); 2001 } 2002 } 2003 } 2004 } 2005 2006 private StorageEventListener mStorageListener = new StorageEventListener() { 2007 @Override 2008 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2009 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2010 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2011 final String volumeUuid = vol.getFsUuid(); 2012 2013 // Clean up any users or apps that were removed or recreated 2014 // while this volume was missing 2015 reconcileUsers(volumeUuid); 2016 reconcileApps(volumeUuid); 2017 2018 // Clean up any install sessions that expired or were 2019 // cancelled while this volume was missing 2020 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2021 2022 loadPrivatePackages(vol); 2023 2024 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2025 unloadPrivatePackages(vol); 2026 } 2027 } 2028 2029 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2030 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2031 updateExternalMediaStatus(true, false); 2032 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2033 updateExternalMediaStatus(false, false); 2034 } 2035 } 2036 } 2037 2038 @Override 2039 public void onVolumeForgotten(String fsUuid) { 2040 if (TextUtils.isEmpty(fsUuid)) { 2041 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2042 return; 2043 } 2044 2045 // Remove any apps installed on the forgotten volume 2046 synchronized (mPackages) { 2047 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2048 for (PackageSetting ps : packages) { 2049 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2050 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2051 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2052 } 2053 2054 mSettings.onVolumeForgotten(fsUuid); 2055 mSettings.writeLPr(); 2056 } 2057 } 2058 }; 2059 2060 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2061 String[] grantedPermissions) { 2062 for (int userId : userIds) { 2063 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2064 } 2065 2066 // We could have touched GID membership, so flush out packages.list 2067 synchronized (mPackages) { 2068 mSettings.writePackageListLPr(); 2069 } 2070 } 2071 2072 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2073 String[] grantedPermissions) { 2074 SettingBase sb = (SettingBase) pkg.mExtras; 2075 if (sb == null) { 2076 return; 2077 } 2078 2079 PermissionsState permissionsState = sb.getPermissionsState(); 2080 2081 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2082 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2083 2084 for (String permission : pkg.requestedPermissions) { 2085 final BasePermission bp; 2086 synchronized (mPackages) { 2087 bp = mSettings.mPermissions.get(permission); 2088 } 2089 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2090 && (grantedPermissions == null 2091 || ArrayUtils.contains(grantedPermissions, permission))) { 2092 final int flags = permissionsState.getPermissionFlags(permission, userId); 2093 // Installer cannot change immutable permissions. 2094 if ((flags & immutableFlags) == 0) { 2095 grantRuntimePermission(pkg.packageName, permission, userId); 2096 } 2097 } 2098 } 2099 } 2100 2101 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2102 Bundle extras = null; 2103 switch (res.returnCode) { 2104 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2105 extras = new Bundle(); 2106 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2107 res.origPermission); 2108 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2109 res.origPackage); 2110 break; 2111 } 2112 case PackageManager.INSTALL_SUCCEEDED: { 2113 extras = new Bundle(); 2114 extras.putBoolean(Intent.EXTRA_REPLACING, 2115 res.removedInfo != null && res.removedInfo.removedPackage != null); 2116 break; 2117 } 2118 } 2119 return extras; 2120 } 2121 2122 void scheduleWriteSettingsLocked() { 2123 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2124 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2125 } 2126 } 2127 2128 void scheduleWritePackageListLocked(int userId) { 2129 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2130 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2131 msg.arg1 = userId; 2132 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2133 } 2134 } 2135 2136 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2137 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2138 scheduleWritePackageRestrictionsLocked(userId); 2139 } 2140 2141 void scheduleWritePackageRestrictionsLocked(int userId) { 2142 final int[] userIds = (userId == UserHandle.USER_ALL) 2143 ? sUserManager.getUserIds() : new int[]{userId}; 2144 for (int nextUserId : userIds) { 2145 if (!sUserManager.exists(nextUserId)) return; 2146 mDirtyUsers.add(nextUserId); 2147 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2148 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2149 } 2150 } 2151 } 2152 2153 public static PackageManagerService main(Context context, Installer installer, 2154 boolean factoryTest, boolean onlyCore) { 2155 // Self-check for initial settings. 2156 PackageManagerServiceCompilerMapping.checkProperties(); 2157 2158 PackageManagerService m = new PackageManagerService(context, installer, 2159 factoryTest, onlyCore); 2160 m.enableSystemUserPackages(); 2161 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2162 // disabled after already being started. 2163 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2164 UserHandle.USER_SYSTEM); 2165 ServiceManager.addService("package", m); 2166 return m; 2167 } 2168 2169 private void enableSystemUserPackages() { 2170 if (!UserManager.isSplitSystemUser()) { 2171 return; 2172 } 2173 // For system user, enable apps based on the following conditions: 2174 // - app is whitelisted or belong to one of these groups: 2175 // -- system app which has no launcher icons 2176 // -- system app which has INTERACT_ACROSS_USERS permission 2177 // -- system IME app 2178 // - app is not in the blacklist 2179 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2180 Set<String> enableApps = new ArraySet<>(); 2181 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2182 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2183 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2184 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2185 enableApps.addAll(wlApps); 2186 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2187 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2188 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2189 enableApps.removeAll(blApps); 2190 Log.i(TAG, "Applications installed for system user: " + enableApps); 2191 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2192 UserHandle.SYSTEM); 2193 final int allAppsSize = allAps.size(); 2194 synchronized (mPackages) { 2195 for (int i = 0; i < allAppsSize; i++) { 2196 String pName = allAps.get(i); 2197 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2198 // Should not happen, but we shouldn't be failing if it does 2199 if (pkgSetting == null) { 2200 continue; 2201 } 2202 boolean install = enableApps.contains(pName); 2203 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2204 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2205 + " for system user"); 2206 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2207 } 2208 } 2209 } 2210 } 2211 2212 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2213 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2214 Context.DISPLAY_SERVICE); 2215 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2216 } 2217 2218 public PackageManagerService(Context context, Installer installer, 2219 boolean factoryTest, boolean onlyCore) { 2220 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2221 SystemClock.uptimeMillis()); 2222 2223 if (mSdkVersion <= 0) { 2224 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2225 } 2226 2227 mContext = context; 2228 mFactoryTest = factoryTest; 2229 mOnlyCore = onlyCore; 2230 mMetrics = new DisplayMetrics(); 2231 mSettings = new Settings(mPackages); 2232 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2243 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2244 2245 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2246 if (separateProcesses != null && separateProcesses.length() > 0) { 2247 if ("*".equals(separateProcesses)) { 2248 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2249 mSeparateProcesses = null; 2250 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2251 } else { 2252 mDefParseFlags = 0; 2253 mSeparateProcesses = separateProcesses.split(","); 2254 Slog.w(TAG, "Running with debug.separate_processes: " 2255 + separateProcesses); 2256 } 2257 } else { 2258 mDefParseFlags = 0; 2259 mSeparateProcesses = null; 2260 } 2261 2262 mInstaller = installer; 2263 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2264 "*dexopt*"); 2265 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2266 2267 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2268 FgThread.get().getLooper()); 2269 2270 getDefaultDisplayMetrics(context, mMetrics); 2271 2272 SystemConfig systemConfig = SystemConfig.getInstance(); 2273 mGlobalGids = systemConfig.getGlobalGids(); 2274 mSystemPermissions = systemConfig.getSystemPermissions(); 2275 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2276 2277 synchronized (mInstallLock) { 2278 // writer 2279 synchronized (mPackages) { 2280 mHandlerThread = new ServiceThread(TAG, 2281 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2282 mHandlerThread.start(); 2283 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2284 mProcessLoggingHandler = new ProcessLoggingHandler(); 2285 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2286 2287 File dataDir = Environment.getDataDirectory(); 2288 mAppInstallDir = new File(dataDir, "app"); 2289 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2290 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2291 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2292 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2293 2294 sUserManager = new UserManagerService(context, this, mPackages); 2295 2296 // Propagate permission configuration in to package manager. 2297 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2298 = systemConfig.getPermissions(); 2299 for (int i=0; i<permConfig.size(); i++) { 2300 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2301 BasePermission bp = mSettings.mPermissions.get(perm.name); 2302 if (bp == null) { 2303 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2304 mSettings.mPermissions.put(perm.name, bp); 2305 } 2306 if (perm.gids != null) { 2307 bp.setGids(perm.gids, perm.perUser); 2308 } 2309 } 2310 2311 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2312 for (int i=0; i<libConfig.size(); i++) { 2313 mSharedLibraries.put(libConfig.keyAt(i), 2314 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2315 } 2316 2317 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2318 2319 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2320 2321 String customResolverActivity = Resources.getSystem().getString( 2322 R.string.config_customResolverActivity); 2323 if (TextUtils.isEmpty(customResolverActivity)) { 2324 customResolverActivity = null; 2325 } else { 2326 mCustomResolverComponentName = ComponentName.unflattenFromString( 2327 customResolverActivity); 2328 } 2329 2330 long startTime = SystemClock.uptimeMillis(); 2331 2332 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2333 startTime); 2334 2335 // Set flag to monitor and not change apk file paths when 2336 // scanning install directories. 2337 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2338 2339 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2340 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2341 2342 if (bootClassPath == null) { 2343 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2344 } 2345 2346 if (systemServerClassPath == null) { 2347 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2348 } 2349 2350 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2351 final String[] dexCodeInstructionSets = 2352 getDexCodeInstructionSets( 2353 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2354 2355 /** 2356 * Ensure all external libraries have had dexopt run on them. 2357 */ 2358 if (mSharedLibraries.size() > 0) { 2359 // NOTE: For now, we're compiling these system "shared libraries" 2360 // (and framework jars) into all available architectures. It's possible 2361 // to compile them only when we come across an app that uses them (there's 2362 // already logic for that in scanPackageLI) but that adds some complexity. 2363 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2364 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2365 final String lib = libEntry.path; 2366 if (lib == null) { 2367 continue; 2368 } 2369 2370 try { 2371 // Shared libraries do not have profiles so we perform a full 2372 // AOT compilation (if needed). 2373 int dexoptNeeded = DexFile.getDexOptNeeded( 2374 lib, dexCodeInstructionSet, 2375 getCompilerFilterForReason(REASON_SHARED_APK), 2376 false /* newProfile */); 2377 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2378 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2379 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2380 getCompilerFilterForReason(REASON_SHARED_APK), 2381 StorageManager.UUID_PRIVATE_INTERNAL, 2382 SKIP_SHARED_LIBRARY_CHECK); 2383 } 2384 } catch (FileNotFoundException e) { 2385 Slog.w(TAG, "Library not found: " + lib); 2386 } catch (IOException | InstallerException e) { 2387 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2388 + e.getMessage()); 2389 } 2390 } 2391 } 2392 } 2393 2394 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2395 2396 final VersionInfo ver = mSettings.getInternalVersion(); 2397 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2398 2399 // when upgrading from pre-M, promote system app permissions from install to runtime 2400 mPromoteSystemApps = 2401 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2402 2403 // When upgrading from pre-N, we need to handle package extraction like first boot, 2404 // as there is no profiling data available. 2405 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2406 2407 // save off the names of pre-existing system packages prior to scanning; we don't 2408 // want to automatically grant runtime permissions for new system apps 2409 if (mPromoteSystemApps) { 2410 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2411 while (pkgSettingIter.hasNext()) { 2412 PackageSetting ps = pkgSettingIter.next(); 2413 if (isSystemApp(ps)) { 2414 mExistingSystemPackages.add(ps.name); 2415 } 2416 } 2417 } 2418 2419 // Collect vendor overlay packages. 2420 // (Do this before scanning any apps.) 2421 // For security and version matching reason, only consider 2422 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2423 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2424 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2425 | PackageParser.PARSE_IS_SYSTEM 2426 | PackageParser.PARSE_IS_SYSTEM_DIR 2427 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2428 2429 // Find base frameworks (resource packages without code). 2430 scanDirTracedLI(frameworkDir, mDefParseFlags 2431 | PackageParser.PARSE_IS_SYSTEM 2432 | PackageParser.PARSE_IS_SYSTEM_DIR 2433 | PackageParser.PARSE_IS_PRIVILEGED, 2434 scanFlags | SCAN_NO_DEX, 0); 2435 2436 // Collected privileged system packages. 2437 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2438 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2439 | PackageParser.PARSE_IS_SYSTEM 2440 | PackageParser.PARSE_IS_SYSTEM_DIR 2441 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2442 2443 // Collect ordinary system packages. 2444 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2445 scanDirTracedLI(systemAppDir, mDefParseFlags 2446 | PackageParser.PARSE_IS_SYSTEM 2447 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2448 2449 // Collect all vendor packages. 2450 File vendorAppDir = new File("/vendor/app"); 2451 try { 2452 vendorAppDir = vendorAppDir.getCanonicalFile(); 2453 } catch (IOException e) { 2454 // failed to look up canonical path, continue with original one 2455 } 2456 scanDirTracedLI(vendorAppDir, mDefParseFlags 2457 | PackageParser.PARSE_IS_SYSTEM 2458 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2459 2460 // Collect all OEM packages. 2461 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2462 scanDirTracedLI(oemAppDir, mDefParseFlags 2463 | PackageParser.PARSE_IS_SYSTEM 2464 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2465 2466 // Prune any system packages that no longer exist. 2467 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2468 if (!mOnlyCore) { 2469 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2470 while (psit.hasNext()) { 2471 PackageSetting ps = psit.next(); 2472 2473 /* 2474 * If this is not a system app, it can't be a 2475 * disable system app. 2476 */ 2477 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2478 continue; 2479 } 2480 2481 /* 2482 * If the package is scanned, it's not erased. 2483 */ 2484 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2485 if (scannedPkg != null) { 2486 /* 2487 * If the system app is both scanned and in the 2488 * disabled packages list, then it must have been 2489 * added via OTA. Remove it from the currently 2490 * scanned package so the previously user-installed 2491 * application can be scanned. 2492 */ 2493 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2494 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2495 + ps.name + "; removing system app. Last known codePath=" 2496 + ps.codePathString + ", installStatus=" + ps.installStatus 2497 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2498 + scannedPkg.mVersionCode); 2499 removePackageLI(scannedPkg, true); 2500 mExpectingBetter.put(ps.name, ps.codePath); 2501 } 2502 2503 continue; 2504 } 2505 2506 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2507 psit.remove(); 2508 logCriticalInfo(Log.WARN, "System package " + ps.name 2509 + " no longer exists; it's data will be wiped"); 2510 // Actual deletion of code and data will be handled by later 2511 // reconciliation step 2512 } else { 2513 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2514 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2515 possiblyDeletedUpdatedSystemApps.add(ps.name); 2516 } 2517 } 2518 } 2519 } 2520 2521 //look for any incomplete package installations 2522 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2523 for (int i = 0; i < deletePkgsList.size(); i++) { 2524 // Actual deletion of code and data will be handled by later 2525 // reconciliation step 2526 final String packageName = deletePkgsList.get(i).name; 2527 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2528 synchronized (mPackages) { 2529 mSettings.removePackageLPw(packageName); 2530 } 2531 } 2532 2533 //delete tmp files 2534 deleteTempPackageFiles(); 2535 2536 // Remove any shared userIDs that have no associated packages 2537 mSettings.pruneSharedUsersLPw(); 2538 2539 if (!mOnlyCore) { 2540 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2541 SystemClock.uptimeMillis()); 2542 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2543 2544 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2545 | PackageParser.PARSE_FORWARD_LOCK, 2546 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2547 2548 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2549 | PackageParser.PARSE_IS_EPHEMERAL, 2550 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2551 2552 /** 2553 * Remove disable package settings for any updated system 2554 * apps that were removed via an OTA. If they're not a 2555 * previously-updated app, remove them completely. 2556 * Otherwise, just revoke their system-level permissions. 2557 */ 2558 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2559 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2560 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2561 2562 String msg; 2563 if (deletedPkg == null) { 2564 msg = "Updated system package " + deletedAppName 2565 + " no longer exists; it's data will be wiped"; 2566 // Actual deletion of code and data will be handled by later 2567 // reconciliation step 2568 } else { 2569 msg = "Updated system app + " + deletedAppName 2570 + " no longer present; removing system privileges for " 2571 + deletedAppName; 2572 2573 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2574 2575 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2576 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2577 } 2578 logCriticalInfo(Log.WARN, msg); 2579 } 2580 2581 /** 2582 * Make sure all system apps that we expected to appear on 2583 * the userdata partition actually showed up. If they never 2584 * appeared, crawl back and revive the system version. 2585 */ 2586 for (int i = 0; i < mExpectingBetter.size(); i++) { 2587 final String packageName = mExpectingBetter.keyAt(i); 2588 if (!mPackages.containsKey(packageName)) { 2589 final File scanFile = mExpectingBetter.valueAt(i); 2590 2591 logCriticalInfo(Log.WARN, "Expected better " + packageName 2592 + " but never showed up; reverting to system"); 2593 2594 int reparseFlags = mDefParseFlags; 2595 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2596 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2597 | PackageParser.PARSE_IS_SYSTEM_DIR 2598 | PackageParser.PARSE_IS_PRIVILEGED; 2599 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2600 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2601 | PackageParser.PARSE_IS_SYSTEM_DIR; 2602 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2603 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2604 | PackageParser.PARSE_IS_SYSTEM_DIR; 2605 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2606 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2607 | PackageParser.PARSE_IS_SYSTEM_DIR; 2608 } else { 2609 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2610 continue; 2611 } 2612 2613 mSettings.enableSystemPackageLPw(packageName); 2614 2615 try { 2616 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2617 } catch (PackageManagerException e) { 2618 Slog.e(TAG, "Failed to parse original system package: " 2619 + e.getMessage()); 2620 } 2621 } 2622 } 2623 } 2624 mExpectingBetter.clear(); 2625 2626 // Resolve protected action filters. Only the setup wizard is allowed to 2627 // have a high priority filter for these actions. 2628 mSetupWizardPackage = getSetupWizardPackageName(); 2629 if (mProtectedFilters.size() > 0) { 2630 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2631 Slog.i(TAG, "No setup wizard;" 2632 + " All protected intents capped to priority 0"); 2633 } 2634 for (ActivityIntentInfo filter : mProtectedFilters) { 2635 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2636 if (DEBUG_FILTERS) { 2637 Slog.i(TAG, "Found setup wizard;" 2638 + " allow priority " + filter.getPriority() + ";" 2639 + " package: " + filter.activity.info.packageName 2640 + " activity: " + filter.activity.className 2641 + " priority: " + filter.getPriority()); 2642 } 2643 // skip setup wizard; allow it to keep the high priority filter 2644 continue; 2645 } 2646 Slog.w(TAG, "Protected action; cap priority to 0;" 2647 + " package: " + filter.activity.info.packageName 2648 + " activity: " + filter.activity.className 2649 + " origPrio: " + filter.getPriority()); 2650 filter.setPriority(0); 2651 } 2652 } 2653 mDeferProtectedFilters = false; 2654 mProtectedFilters.clear(); 2655 2656 // Now that we know all of the shared libraries, update all clients to have 2657 // the correct library paths. 2658 updateAllSharedLibrariesLPw(); 2659 2660 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2661 // NOTE: We ignore potential failures here during a system scan (like 2662 // the rest of the commands above) because there's precious little we 2663 // can do about it. A settings error is reported, though. 2664 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2665 false /* boot complete */); 2666 } 2667 2668 // Now that we know all the packages we are keeping, 2669 // read and update their last usage times. 2670 mPackageUsage.readLP(); 2671 2672 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2673 SystemClock.uptimeMillis()); 2674 Slog.i(TAG, "Time to scan packages: " 2675 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2676 + " seconds"); 2677 2678 // If the platform SDK has changed since the last time we booted, 2679 // we need to re-grant app permission to catch any new ones that 2680 // appear. This is really a hack, and means that apps can in some 2681 // cases get permissions that the user didn't initially explicitly 2682 // allow... it would be nice to have some better way to handle 2683 // this situation. 2684 int updateFlags = UPDATE_PERMISSIONS_ALL; 2685 if (ver.sdkVersion != mSdkVersion) { 2686 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2687 + mSdkVersion + "; regranting permissions for internal storage"); 2688 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2689 } 2690 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2691 ver.sdkVersion = mSdkVersion; 2692 2693 // If this is the first boot or an update from pre-M, and it is a normal 2694 // boot, then we need to initialize the default preferred apps across 2695 // all defined users. 2696 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2697 for (UserInfo user : sUserManager.getUsers(true)) { 2698 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2699 applyFactoryDefaultBrowserLPw(user.id); 2700 primeDomainVerificationsLPw(user.id); 2701 } 2702 } 2703 2704 // Prepare storage for system user really early during boot, 2705 // since core system apps like SettingsProvider and SystemUI 2706 // can't wait for user to start 2707 final int storageFlags; 2708 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2709 storageFlags = StorageManager.FLAG_STORAGE_DE; 2710 } else { 2711 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2712 } 2713 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2714 storageFlags); 2715 2716 // If this is first boot after an OTA, and a normal boot, then 2717 // we need to clear code cache directories. 2718 // Note that we do *not* clear the application profiles. These remain valid 2719 // across OTAs and are used to drive profile verification (post OTA) and 2720 // profile compilation (without waiting to collect a fresh set of profiles). 2721 if (mIsUpgrade && !onlyCore) { 2722 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2723 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2724 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2725 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2726 // No apps are running this early, so no need to freeze 2727 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2728 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2729 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2730 } 2731 } 2732 ver.fingerprint = Build.FINGERPRINT; 2733 } 2734 2735 checkDefaultBrowser(); 2736 2737 // clear only after permissions and other defaults have been updated 2738 mExistingSystemPackages.clear(); 2739 mPromoteSystemApps = false; 2740 2741 // All the changes are done during package scanning. 2742 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2743 2744 // can downgrade to reader 2745 mSettings.writeLPr(); 2746 2747 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2748 // early on (before the package manager declares itself as early) because other 2749 // components in the system server might ask for package contexts for these apps. 2750 // 2751 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2752 // (i.e, that the data partition is unavailable). 2753 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2754 long start = System.nanoTime(); 2755 List<PackageParser.Package> coreApps = new ArrayList<>(); 2756 for (PackageParser.Package pkg : mPackages.values()) { 2757 if (pkg.coreApp) { 2758 coreApps.add(pkg); 2759 } 2760 } 2761 2762 int[] stats = performDexOpt(coreApps, false, 2763 getCompilerFilterForReason(REASON_CORE_APP)); 2764 2765 final int elapsedTimeSeconds = 2766 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2767 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2768 2769 if (DEBUG_DEXOPT) { 2770 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2771 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2772 } 2773 2774 2775 // TODO: Should we log these stats to tron too ? 2776 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2777 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2778 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2779 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2780 } 2781 2782 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2783 SystemClock.uptimeMillis()); 2784 2785 if (!mOnlyCore) { 2786 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2787 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2788 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2789 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2790 mIntentFilterVerifierComponent); 2791 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2792 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2793 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2794 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2795 } else { 2796 mRequiredVerifierPackage = null; 2797 mRequiredInstallerPackage = null; 2798 mIntentFilterVerifierComponent = null; 2799 mIntentFilterVerifier = null; 2800 mServicesSystemSharedLibraryPackageName = null; 2801 mSharedSystemSharedLibraryPackageName = null; 2802 } 2803 2804 mInstallerService = new PackageInstallerService(context, this); 2805 2806 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2807 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2808 // both the installer and resolver must be present to enable ephemeral 2809 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2810 if (DEBUG_EPHEMERAL) { 2811 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2812 + " installer:" + ephemeralInstallerComponent); 2813 } 2814 mEphemeralResolverComponent = ephemeralResolverComponent; 2815 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2816 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2817 mEphemeralResolverConnection = 2818 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2819 } else { 2820 if (DEBUG_EPHEMERAL) { 2821 final String missingComponent = 2822 (ephemeralResolverComponent == null) 2823 ? (ephemeralInstallerComponent == null) 2824 ? "resolver and installer" 2825 : "resolver" 2826 : "installer"; 2827 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2828 } 2829 mEphemeralResolverComponent = null; 2830 mEphemeralInstallerComponent = null; 2831 mEphemeralResolverConnection = null; 2832 } 2833 2834 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2835 } // synchronized (mPackages) 2836 } // synchronized (mInstallLock) 2837 2838 // Now after opening every single application zip, make sure they 2839 // are all flushed. Not really needed, but keeps things nice and 2840 // tidy. 2841 Runtime.getRuntime().gc(); 2842 2843 // The initial scanning above does many calls into installd while 2844 // holding the mPackages lock, but we're mostly interested in yelling 2845 // once we have a booted system. 2846 mInstaller.setWarnIfHeld(mPackages); 2847 2848 // Expose private service for system components to use. 2849 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2850 } 2851 2852 @Override 2853 public boolean isFirstBoot() { 2854 return !mRestoredSettings; 2855 } 2856 2857 @Override 2858 public boolean isOnlyCoreApps() { 2859 return mOnlyCore; 2860 } 2861 2862 @Override 2863 public boolean isUpgrade() { 2864 return mIsUpgrade; 2865 } 2866 2867 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2868 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2869 2870 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2871 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2872 UserHandle.USER_SYSTEM); 2873 if (matches.size() == 1) { 2874 return matches.get(0).getComponentInfo().packageName; 2875 } else { 2876 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2877 return null; 2878 } 2879 } 2880 2881 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2882 synchronized (mPackages) { 2883 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2884 if (libraryEntry == null) { 2885 throw new IllegalStateException("Missing required shared library:" + libraryName); 2886 } 2887 return libraryEntry.apk; 2888 } 2889 } 2890 2891 private @NonNull String getRequiredInstallerLPr() { 2892 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2893 intent.addCategory(Intent.CATEGORY_DEFAULT); 2894 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2895 2896 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2897 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2898 UserHandle.USER_SYSTEM); 2899 if (matches.size() == 1) { 2900 ResolveInfo resolveInfo = matches.get(0); 2901 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2902 throw new RuntimeException("The installer must be a privileged app"); 2903 } 2904 return matches.get(0).getComponentInfo().packageName; 2905 } else { 2906 throw new RuntimeException("There must be exactly one installer; found " + matches); 2907 } 2908 } 2909 2910 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2911 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2912 2913 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2914 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2915 UserHandle.USER_SYSTEM); 2916 ResolveInfo best = null; 2917 final int N = matches.size(); 2918 for (int i = 0; i < N; i++) { 2919 final ResolveInfo cur = matches.get(i); 2920 final String packageName = cur.getComponentInfo().packageName; 2921 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2922 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2923 continue; 2924 } 2925 2926 if (best == null || cur.priority > best.priority) { 2927 best = cur; 2928 } 2929 } 2930 2931 if (best != null) { 2932 return best.getComponentInfo().getComponentName(); 2933 } else { 2934 throw new RuntimeException("There must be at least one intent filter verifier"); 2935 } 2936 } 2937 2938 private @Nullable ComponentName getEphemeralResolverLPr() { 2939 final String[] packageArray = 2940 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2941 if (packageArray.length == 0) { 2942 if (DEBUG_EPHEMERAL) { 2943 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2944 } 2945 return null; 2946 } 2947 2948 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2949 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2950 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2951 UserHandle.USER_SYSTEM); 2952 2953 final int N = resolvers.size(); 2954 if (N == 0) { 2955 if (DEBUG_EPHEMERAL) { 2956 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2957 } 2958 return null; 2959 } 2960 2961 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2962 for (int i = 0; i < N; i++) { 2963 final ResolveInfo info = resolvers.get(i); 2964 2965 if (info.serviceInfo == null) { 2966 continue; 2967 } 2968 2969 final String packageName = info.serviceInfo.packageName; 2970 if (!possiblePackages.contains(packageName)) { 2971 if (DEBUG_EPHEMERAL) { 2972 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2973 + " pkg: " + packageName + ", info:" + info); 2974 } 2975 continue; 2976 } 2977 2978 if (DEBUG_EPHEMERAL) { 2979 Slog.v(TAG, "Ephemeral resolver found;" 2980 + " pkg: " + packageName + ", info:" + info); 2981 } 2982 return new ComponentName(packageName, info.serviceInfo.name); 2983 } 2984 if (DEBUG_EPHEMERAL) { 2985 Slog.v(TAG, "Ephemeral resolver NOT found"); 2986 } 2987 return null; 2988 } 2989 2990 private @Nullable ComponentName getEphemeralInstallerLPr() { 2991 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2992 intent.addCategory(Intent.CATEGORY_DEFAULT); 2993 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2994 2995 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2996 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2997 UserHandle.USER_SYSTEM); 2998 if (matches.size() == 0) { 2999 return null; 3000 } else if (matches.size() == 1) { 3001 return matches.get(0).getComponentInfo().getComponentName(); 3002 } else { 3003 throw new RuntimeException( 3004 "There must be at most one ephemeral installer; found " + matches); 3005 } 3006 } 3007 3008 private void primeDomainVerificationsLPw(int userId) { 3009 if (DEBUG_DOMAIN_VERIFICATION) { 3010 Slog.d(TAG, "Priming domain verifications in user " + userId); 3011 } 3012 3013 SystemConfig systemConfig = SystemConfig.getInstance(); 3014 ArraySet<String> packages = systemConfig.getLinkedApps(); 3015 ArraySet<String> domains = new ArraySet<String>(); 3016 3017 for (String packageName : packages) { 3018 PackageParser.Package pkg = mPackages.get(packageName); 3019 if (pkg != null) { 3020 if (!pkg.isSystemApp()) { 3021 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3022 continue; 3023 } 3024 3025 domains.clear(); 3026 for (PackageParser.Activity a : pkg.activities) { 3027 for (ActivityIntentInfo filter : a.intents) { 3028 if (hasValidDomains(filter)) { 3029 domains.addAll(filter.getHostsList()); 3030 } 3031 } 3032 } 3033 3034 if (domains.size() > 0) { 3035 if (DEBUG_DOMAIN_VERIFICATION) { 3036 Slog.v(TAG, " + " + packageName); 3037 } 3038 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3039 // state w.r.t. the formal app-linkage "no verification attempted" state; 3040 // and then 'always' in the per-user state actually used for intent resolution. 3041 final IntentFilterVerificationInfo ivi; 3042 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3043 new ArrayList<String>(domains)); 3044 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3045 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3046 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3047 } else { 3048 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3049 + "' does not handle web links"); 3050 } 3051 } else { 3052 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3053 } 3054 } 3055 3056 scheduleWritePackageRestrictionsLocked(userId); 3057 scheduleWriteSettingsLocked(); 3058 } 3059 3060 private void applyFactoryDefaultBrowserLPw(int userId) { 3061 // The default browser app's package name is stored in a string resource, 3062 // with a product-specific overlay used for vendor customization. 3063 String browserPkg = mContext.getResources().getString( 3064 com.android.internal.R.string.default_browser); 3065 if (!TextUtils.isEmpty(browserPkg)) { 3066 // non-empty string => required to be a known package 3067 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3068 if (ps == null) { 3069 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3070 browserPkg = null; 3071 } else { 3072 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3073 } 3074 } 3075 3076 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3077 // default. If there's more than one, just leave everything alone. 3078 if (browserPkg == null) { 3079 calculateDefaultBrowserLPw(userId); 3080 } 3081 } 3082 3083 private void calculateDefaultBrowserLPw(int userId) { 3084 List<String> allBrowsers = resolveAllBrowserApps(userId); 3085 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3086 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3087 } 3088 3089 private List<String> resolveAllBrowserApps(int userId) { 3090 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3091 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3092 PackageManager.MATCH_ALL, userId); 3093 3094 final int count = list.size(); 3095 List<String> result = new ArrayList<String>(count); 3096 for (int i=0; i<count; i++) { 3097 ResolveInfo info = list.get(i); 3098 if (info.activityInfo == null 3099 || !info.handleAllWebDataURI 3100 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3101 || result.contains(info.activityInfo.packageName)) { 3102 continue; 3103 } 3104 result.add(info.activityInfo.packageName); 3105 } 3106 3107 return result; 3108 } 3109 3110 private boolean packageIsBrowser(String packageName, int userId) { 3111 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3112 PackageManager.MATCH_ALL, userId); 3113 final int N = list.size(); 3114 for (int i = 0; i < N; i++) { 3115 ResolveInfo info = list.get(i); 3116 if (packageName.equals(info.activityInfo.packageName)) { 3117 return true; 3118 } 3119 } 3120 return false; 3121 } 3122 3123 private void checkDefaultBrowser() { 3124 final int myUserId = UserHandle.myUserId(); 3125 final String packageName = getDefaultBrowserPackageName(myUserId); 3126 if (packageName != null) { 3127 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3128 if (info == null) { 3129 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3130 synchronized (mPackages) { 3131 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3132 } 3133 } 3134 } 3135 } 3136 3137 @Override 3138 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3139 throws RemoteException { 3140 try { 3141 return super.onTransact(code, data, reply, flags); 3142 } catch (RuntimeException e) { 3143 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3144 Slog.wtf(TAG, "Package Manager Crash", e); 3145 } 3146 throw e; 3147 } 3148 } 3149 3150 static int[] appendInts(int[] cur, int[] add) { 3151 if (add == null) return cur; 3152 if (cur == null) return add; 3153 final int N = add.length; 3154 for (int i=0; i<N; i++) { 3155 cur = appendInt(cur, add[i]); 3156 } 3157 return cur; 3158 } 3159 3160 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3161 if (!sUserManager.exists(userId)) return null; 3162 if (ps == null) { 3163 return null; 3164 } 3165 final PackageParser.Package p = ps.pkg; 3166 if (p == null) { 3167 return null; 3168 } 3169 3170 final PermissionsState permissionsState = ps.getPermissionsState(); 3171 3172 final int[] gids = permissionsState.computeGids(userId); 3173 final Set<String> permissions = permissionsState.getPermissions(userId); 3174 final PackageUserState state = ps.readUserState(userId); 3175 3176 return PackageParser.generatePackageInfo(p, gids, flags, 3177 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3178 } 3179 3180 @Override 3181 public void checkPackageStartable(String packageName, int userId) { 3182 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3183 3184 synchronized (mPackages) { 3185 final PackageSetting ps = mSettings.mPackages.get(packageName); 3186 if (ps == null) { 3187 throw new SecurityException("Package " + packageName + " was not found!"); 3188 } 3189 3190 if (!ps.getInstalled(userId)) { 3191 throw new SecurityException( 3192 "Package " + packageName + " was not installed for user " + userId + "!"); 3193 } 3194 3195 if (mSafeMode && !ps.isSystem()) { 3196 throw new SecurityException("Package " + packageName + " not a system app!"); 3197 } 3198 3199 if (mFrozenPackages.contains(packageName)) { 3200 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3201 } 3202 3203 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3204 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3205 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3206 } 3207 } 3208 } 3209 3210 @Override 3211 public boolean isPackageAvailable(String packageName, int userId) { 3212 if (!sUserManager.exists(userId)) return false; 3213 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3214 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3215 synchronized (mPackages) { 3216 PackageParser.Package p = mPackages.get(packageName); 3217 if (p != null) { 3218 final PackageSetting ps = (PackageSetting) p.mExtras; 3219 if (ps != null) { 3220 final PackageUserState state = ps.readUserState(userId); 3221 if (state != null) { 3222 return PackageParser.isAvailable(state); 3223 } 3224 } 3225 } 3226 } 3227 return false; 3228 } 3229 3230 @Override 3231 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3232 if (!sUserManager.exists(userId)) return null; 3233 flags = updateFlagsForPackage(flags, userId, packageName); 3234 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3235 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3236 // reader 3237 synchronized (mPackages) { 3238 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3239 PackageParser.Package p = null; 3240 if (matchFactoryOnly) { 3241 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3242 if (ps != null) { 3243 return generatePackageInfo(ps, flags, userId); 3244 } 3245 } 3246 if (p == null) { 3247 p = mPackages.get(packageName); 3248 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3249 return null; 3250 } 3251 } 3252 if (DEBUG_PACKAGE_INFO) 3253 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3254 if (p != null) { 3255 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3256 } 3257 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3258 final PackageSetting ps = mSettings.mPackages.get(packageName); 3259 return generatePackageInfo(ps, flags, userId); 3260 } 3261 } 3262 return null; 3263 } 3264 3265 @Override 3266 public String[] currentToCanonicalPackageNames(String[] names) { 3267 String[] out = new String[names.length]; 3268 // reader 3269 synchronized (mPackages) { 3270 for (int i=names.length-1; i>=0; i--) { 3271 PackageSetting ps = mSettings.mPackages.get(names[i]); 3272 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3273 } 3274 } 3275 return out; 3276 } 3277 3278 @Override 3279 public String[] canonicalToCurrentPackageNames(String[] names) { 3280 String[] out = new String[names.length]; 3281 // reader 3282 synchronized (mPackages) { 3283 for (int i=names.length-1; i>=0; i--) { 3284 String cur = mSettings.mRenamedPackages.get(names[i]); 3285 out[i] = cur != null ? cur : names[i]; 3286 } 3287 } 3288 return out; 3289 } 3290 3291 @Override 3292 public int getPackageUid(String packageName, int flags, int userId) { 3293 if (!sUserManager.exists(userId)) return -1; 3294 flags = updateFlagsForPackage(flags, userId, packageName); 3295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3296 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3297 3298 // reader 3299 synchronized (mPackages) { 3300 final PackageParser.Package p = mPackages.get(packageName); 3301 if (p != null && p.isMatch(flags)) { 3302 return UserHandle.getUid(userId, p.applicationInfo.uid); 3303 } 3304 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3305 final PackageSetting ps = mSettings.mPackages.get(packageName); 3306 if (ps != null && ps.isMatch(flags)) { 3307 return UserHandle.getUid(userId, ps.appId); 3308 } 3309 } 3310 } 3311 3312 return -1; 3313 } 3314 3315 @Override 3316 public int[] getPackageGids(String packageName, int flags, int userId) { 3317 if (!sUserManager.exists(userId)) return null; 3318 flags = updateFlagsForPackage(flags, userId, packageName); 3319 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3320 false /* requireFullPermission */, false /* checkShell */, 3321 "getPackageGids"); 3322 3323 // reader 3324 synchronized (mPackages) { 3325 final PackageParser.Package p = mPackages.get(packageName); 3326 if (p != null && p.isMatch(flags)) { 3327 PackageSetting ps = (PackageSetting) p.mExtras; 3328 return ps.getPermissionsState().computeGids(userId); 3329 } 3330 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3331 final PackageSetting ps = mSettings.mPackages.get(packageName); 3332 if (ps != null && ps.isMatch(flags)) { 3333 return ps.getPermissionsState().computeGids(userId); 3334 } 3335 } 3336 } 3337 3338 return null; 3339 } 3340 3341 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3342 if (bp.perm != null) { 3343 return PackageParser.generatePermissionInfo(bp.perm, flags); 3344 } 3345 PermissionInfo pi = new PermissionInfo(); 3346 pi.name = bp.name; 3347 pi.packageName = bp.sourcePackage; 3348 pi.nonLocalizedLabel = bp.name; 3349 pi.protectionLevel = bp.protectionLevel; 3350 return pi; 3351 } 3352 3353 @Override 3354 public PermissionInfo getPermissionInfo(String name, int flags) { 3355 // reader 3356 synchronized (mPackages) { 3357 final BasePermission p = mSettings.mPermissions.get(name); 3358 if (p != null) { 3359 return generatePermissionInfo(p, flags); 3360 } 3361 return null; 3362 } 3363 } 3364 3365 @Override 3366 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3367 int flags) { 3368 // reader 3369 synchronized (mPackages) { 3370 if (group != null && !mPermissionGroups.containsKey(group)) { 3371 // This is thrown as NameNotFoundException 3372 return null; 3373 } 3374 3375 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3376 for (BasePermission p : mSettings.mPermissions.values()) { 3377 if (group == null) { 3378 if (p.perm == null || p.perm.info.group == null) { 3379 out.add(generatePermissionInfo(p, flags)); 3380 } 3381 } else { 3382 if (p.perm != null && group.equals(p.perm.info.group)) { 3383 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3384 } 3385 } 3386 } 3387 return new ParceledListSlice<>(out); 3388 } 3389 } 3390 3391 @Override 3392 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3393 // reader 3394 synchronized (mPackages) { 3395 return PackageParser.generatePermissionGroupInfo( 3396 mPermissionGroups.get(name), flags); 3397 } 3398 } 3399 3400 @Override 3401 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3402 // reader 3403 synchronized (mPackages) { 3404 final int N = mPermissionGroups.size(); 3405 ArrayList<PermissionGroupInfo> out 3406 = new ArrayList<PermissionGroupInfo>(N); 3407 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3408 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3409 } 3410 return new ParceledListSlice<>(out); 3411 } 3412 } 3413 3414 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3415 int userId) { 3416 if (!sUserManager.exists(userId)) return null; 3417 PackageSetting ps = mSettings.mPackages.get(packageName); 3418 if (ps != null) { 3419 if (ps.pkg == null) { 3420 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3421 if (pInfo != null) { 3422 return pInfo.applicationInfo; 3423 } 3424 return null; 3425 } 3426 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3427 ps.readUserState(userId), userId); 3428 } 3429 return null; 3430 } 3431 3432 @Override 3433 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3434 if (!sUserManager.exists(userId)) return null; 3435 flags = updateFlagsForApplication(flags, userId, packageName); 3436 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3437 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3438 // writer 3439 synchronized (mPackages) { 3440 PackageParser.Package p = mPackages.get(packageName); 3441 if (DEBUG_PACKAGE_INFO) Log.v( 3442 TAG, "getApplicationInfo " + packageName 3443 + ": " + p); 3444 if (p != null) { 3445 PackageSetting ps = mSettings.mPackages.get(packageName); 3446 if (ps == null) return null; 3447 // Note: isEnabledLP() does not apply here - always return info 3448 return PackageParser.generateApplicationInfo( 3449 p, flags, ps.readUserState(userId), userId); 3450 } 3451 if ("android".equals(packageName)||"system".equals(packageName)) { 3452 return mAndroidApplication; 3453 } 3454 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3455 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3456 } 3457 } 3458 return null; 3459 } 3460 3461 @Override 3462 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3463 final IPackageDataObserver observer) { 3464 mContext.enforceCallingOrSelfPermission( 3465 android.Manifest.permission.CLEAR_APP_CACHE, null); 3466 // Queue up an async operation since clearing cache may take a little while. 3467 mHandler.post(new Runnable() { 3468 public void run() { 3469 mHandler.removeCallbacks(this); 3470 boolean success = true; 3471 synchronized (mInstallLock) { 3472 try { 3473 mInstaller.freeCache(volumeUuid, freeStorageSize); 3474 } catch (InstallerException e) { 3475 Slog.w(TAG, "Couldn't clear application caches: " + e); 3476 success = false; 3477 } 3478 } 3479 if (observer != null) { 3480 try { 3481 observer.onRemoveCompleted(null, success); 3482 } catch (RemoteException e) { 3483 Slog.w(TAG, "RemoveException when invoking call back"); 3484 } 3485 } 3486 } 3487 }); 3488 } 3489 3490 @Override 3491 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3492 final IntentSender pi) { 3493 mContext.enforceCallingOrSelfPermission( 3494 android.Manifest.permission.CLEAR_APP_CACHE, null); 3495 // Queue up an async operation since clearing cache may take a little while. 3496 mHandler.post(new Runnable() { 3497 public void run() { 3498 mHandler.removeCallbacks(this); 3499 boolean success = true; 3500 synchronized (mInstallLock) { 3501 try { 3502 mInstaller.freeCache(volumeUuid, freeStorageSize); 3503 } catch (InstallerException e) { 3504 Slog.w(TAG, "Couldn't clear application caches: " + e); 3505 success = false; 3506 } 3507 } 3508 if(pi != null) { 3509 try { 3510 // Callback via pending intent 3511 int code = success ? 1 : 0; 3512 pi.sendIntent(null, code, null, 3513 null, null); 3514 } catch (SendIntentException e1) { 3515 Slog.i(TAG, "Failed to send pending intent"); 3516 } 3517 } 3518 } 3519 }); 3520 } 3521 3522 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3523 synchronized (mInstallLock) { 3524 try { 3525 mInstaller.freeCache(volumeUuid, freeStorageSize); 3526 } catch (InstallerException e) { 3527 throw new IOException("Failed to free enough space", e); 3528 } 3529 } 3530 } 3531 3532 /** 3533 * Update given flags based on encryption status of current user. 3534 */ 3535 private int updateFlags(int flags, int userId) { 3536 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3537 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3538 // Caller expressed an explicit opinion about what encryption 3539 // aware/unaware components they want to see, so fall through and 3540 // give them what they want 3541 } else { 3542 // Caller expressed no opinion, so match based on user state 3543 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3544 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3545 } else { 3546 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3547 } 3548 } 3549 return flags; 3550 } 3551 3552 private UserManagerInternal getUserManagerInternal() { 3553 if (mUserManagerInternal == null) { 3554 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3555 } 3556 return mUserManagerInternal; 3557 } 3558 3559 /** 3560 * Update given flags when being used to request {@link PackageInfo}. 3561 */ 3562 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3563 boolean triaged = true; 3564 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3565 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3566 // Caller is asking for component details, so they'd better be 3567 // asking for specific encryption matching behavior, or be triaged 3568 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3569 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3570 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3571 triaged = false; 3572 } 3573 } 3574 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3575 | PackageManager.MATCH_SYSTEM_ONLY 3576 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3577 triaged = false; 3578 } 3579 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3580 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3581 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3582 } 3583 return updateFlags(flags, userId); 3584 } 3585 3586 /** 3587 * Update given flags when being used to request {@link ApplicationInfo}. 3588 */ 3589 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3590 return updateFlagsForPackage(flags, userId, cookie); 3591 } 3592 3593 /** 3594 * Update given flags when being used to request {@link ComponentInfo}. 3595 */ 3596 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3597 if (cookie instanceof Intent) { 3598 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3599 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3600 } 3601 } 3602 3603 boolean triaged = true; 3604 // Caller is asking for component details, so they'd better be 3605 // asking for specific encryption matching behavior, or be triaged 3606 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3607 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3608 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3609 triaged = false; 3610 } 3611 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3612 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3613 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3614 } 3615 3616 return updateFlags(flags, userId); 3617 } 3618 3619 /** 3620 * Update given flags when being used to request {@link ResolveInfo}. 3621 */ 3622 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3623 // Safe mode means we shouldn't match any third-party components 3624 if (mSafeMode) { 3625 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3626 } 3627 3628 return updateFlagsForComponent(flags, userId, cookie); 3629 } 3630 3631 @Override 3632 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3633 if (!sUserManager.exists(userId)) return null; 3634 flags = updateFlagsForComponent(flags, userId, component); 3635 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3636 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3637 synchronized (mPackages) { 3638 PackageParser.Activity a = mActivities.mActivities.get(component); 3639 3640 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3641 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3642 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3643 if (ps == null) return null; 3644 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3645 userId); 3646 } 3647 if (mResolveComponentName.equals(component)) { 3648 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3649 new PackageUserState(), userId); 3650 } 3651 } 3652 return null; 3653 } 3654 3655 @Override 3656 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3657 String resolvedType) { 3658 synchronized (mPackages) { 3659 if (component.equals(mResolveComponentName)) { 3660 // The resolver supports EVERYTHING! 3661 return true; 3662 } 3663 PackageParser.Activity a = mActivities.mActivities.get(component); 3664 if (a == null) { 3665 return false; 3666 } 3667 for (int i=0; i<a.intents.size(); i++) { 3668 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3669 intent.getData(), intent.getCategories(), TAG) >= 0) { 3670 return true; 3671 } 3672 } 3673 return false; 3674 } 3675 } 3676 3677 @Override 3678 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3679 if (!sUserManager.exists(userId)) return null; 3680 flags = updateFlagsForComponent(flags, userId, component); 3681 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3682 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3683 synchronized (mPackages) { 3684 PackageParser.Activity a = mReceivers.mActivities.get(component); 3685 if (DEBUG_PACKAGE_INFO) Log.v( 3686 TAG, "getReceiverInfo " + component + ": " + a); 3687 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3688 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3689 if (ps == null) return null; 3690 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3691 userId); 3692 } 3693 } 3694 return null; 3695 } 3696 3697 @Override 3698 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3699 if (!sUserManager.exists(userId)) return null; 3700 flags = updateFlagsForComponent(flags, userId, component); 3701 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3702 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3703 synchronized (mPackages) { 3704 PackageParser.Service s = mServices.mServices.get(component); 3705 if (DEBUG_PACKAGE_INFO) Log.v( 3706 TAG, "getServiceInfo " + component + ": " + s); 3707 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3708 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3709 if (ps == null) return null; 3710 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3711 userId); 3712 } 3713 } 3714 return null; 3715 } 3716 3717 @Override 3718 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3719 if (!sUserManager.exists(userId)) return null; 3720 flags = updateFlagsForComponent(flags, userId, component); 3721 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3722 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3723 synchronized (mPackages) { 3724 PackageParser.Provider p = mProviders.mProviders.get(component); 3725 if (DEBUG_PACKAGE_INFO) Log.v( 3726 TAG, "getProviderInfo " + component + ": " + p); 3727 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3728 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3729 if (ps == null) return null; 3730 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3731 userId); 3732 } 3733 } 3734 return null; 3735 } 3736 3737 @Override 3738 public String[] getSystemSharedLibraryNames() { 3739 Set<String> libSet; 3740 synchronized (mPackages) { 3741 libSet = mSharedLibraries.keySet(); 3742 int size = libSet.size(); 3743 if (size > 0) { 3744 String[] libs = new String[size]; 3745 libSet.toArray(libs); 3746 return libs; 3747 } 3748 } 3749 return null; 3750 } 3751 3752 @Override 3753 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3754 synchronized (mPackages) { 3755 return mServicesSystemSharedLibraryPackageName; 3756 } 3757 } 3758 3759 @Override 3760 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3761 synchronized (mPackages) { 3762 return mSharedSystemSharedLibraryPackageName; 3763 } 3764 } 3765 3766 @Override 3767 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3768 synchronized (mPackages) { 3769 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3770 3771 final FeatureInfo fi = new FeatureInfo(); 3772 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3773 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3774 res.add(fi); 3775 3776 return new ParceledListSlice<>(res); 3777 } 3778 } 3779 3780 @Override 3781 public boolean hasSystemFeature(String name, int version) { 3782 synchronized (mPackages) { 3783 final FeatureInfo feat = mAvailableFeatures.get(name); 3784 if (feat == null) { 3785 return false; 3786 } else { 3787 return feat.version >= version; 3788 } 3789 } 3790 } 3791 3792 @Override 3793 public int checkPermission(String permName, String pkgName, int userId) { 3794 if (!sUserManager.exists(userId)) { 3795 return PackageManager.PERMISSION_DENIED; 3796 } 3797 3798 synchronized (mPackages) { 3799 final PackageParser.Package p = mPackages.get(pkgName); 3800 if (p != null && p.mExtras != null) { 3801 final PackageSetting ps = (PackageSetting) p.mExtras; 3802 final PermissionsState permissionsState = ps.getPermissionsState(); 3803 if (permissionsState.hasPermission(permName, userId)) { 3804 return PackageManager.PERMISSION_GRANTED; 3805 } 3806 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3807 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3808 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3809 return PackageManager.PERMISSION_GRANTED; 3810 } 3811 } 3812 } 3813 3814 return PackageManager.PERMISSION_DENIED; 3815 } 3816 3817 @Override 3818 public int checkUidPermission(String permName, int uid) { 3819 final int userId = UserHandle.getUserId(uid); 3820 3821 if (!sUserManager.exists(userId)) { 3822 return PackageManager.PERMISSION_DENIED; 3823 } 3824 3825 synchronized (mPackages) { 3826 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3827 if (obj != null) { 3828 final SettingBase ps = (SettingBase) obj; 3829 final PermissionsState permissionsState = ps.getPermissionsState(); 3830 if (permissionsState.hasPermission(permName, userId)) { 3831 return PackageManager.PERMISSION_GRANTED; 3832 } 3833 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3834 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3835 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3836 return PackageManager.PERMISSION_GRANTED; 3837 } 3838 } else { 3839 ArraySet<String> perms = mSystemPermissions.get(uid); 3840 if (perms != null) { 3841 if (perms.contains(permName)) { 3842 return PackageManager.PERMISSION_GRANTED; 3843 } 3844 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3845 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3846 return PackageManager.PERMISSION_GRANTED; 3847 } 3848 } 3849 } 3850 } 3851 3852 return PackageManager.PERMISSION_DENIED; 3853 } 3854 3855 @Override 3856 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3857 if (UserHandle.getCallingUserId() != userId) { 3858 mContext.enforceCallingPermission( 3859 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3860 "isPermissionRevokedByPolicy for user " + userId); 3861 } 3862 3863 if (checkPermission(permission, packageName, userId) 3864 == PackageManager.PERMISSION_GRANTED) { 3865 return false; 3866 } 3867 3868 final long identity = Binder.clearCallingIdentity(); 3869 try { 3870 final int flags = getPermissionFlags(permission, packageName, userId); 3871 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3872 } finally { 3873 Binder.restoreCallingIdentity(identity); 3874 } 3875 } 3876 3877 @Override 3878 public String getPermissionControllerPackageName() { 3879 synchronized (mPackages) { 3880 return mRequiredInstallerPackage; 3881 } 3882 } 3883 3884 /** 3885 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3886 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3887 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3888 * @param message the message to log on security exception 3889 */ 3890 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3891 boolean checkShell, String message) { 3892 if (userId < 0) { 3893 throw new IllegalArgumentException("Invalid userId " + userId); 3894 } 3895 if (checkShell) { 3896 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3897 } 3898 if (userId == UserHandle.getUserId(callingUid)) return; 3899 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3900 if (requireFullPermission) { 3901 mContext.enforceCallingOrSelfPermission( 3902 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3903 } else { 3904 try { 3905 mContext.enforceCallingOrSelfPermission( 3906 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3907 } catch (SecurityException se) { 3908 mContext.enforceCallingOrSelfPermission( 3909 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3910 } 3911 } 3912 } 3913 } 3914 3915 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3916 if (callingUid == Process.SHELL_UID) { 3917 if (userHandle >= 0 3918 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3919 throw new SecurityException("Shell does not have permission to access user " 3920 + userHandle); 3921 } else if (userHandle < 0) { 3922 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3923 + Debug.getCallers(3)); 3924 } 3925 } 3926 } 3927 3928 private BasePermission findPermissionTreeLP(String permName) { 3929 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3930 if (permName.startsWith(bp.name) && 3931 permName.length() > bp.name.length() && 3932 permName.charAt(bp.name.length()) == '.') { 3933 return bp; 3934 } 3935 } 3936 return null; 3937 } 3938 3939 private BasePermission checkPermissionTreeLP(String permName) { 3940 if (permName != null) { 3941 BasePermission bp = findPermissionTreeLP(permName); 3942 if (bp != null) { 3943 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3944 return bp; 3945 } 3946 throw new SecurityException("Calling uid " 3947 + Binder.getCallingUid() 3948 + " is not allowed to add to permission tree " 3949 + bp.name + " owned by uid " + bp.uid); 3950 } 3951 } 3952 throw new SecurityException("No permission tree found for " + permName); 3953 } 3954 3955 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3956 if (s1 == null) { 3957 return s2 == null; 3958 } 3959 if (s2 == null) { 3960 return false; 3961 } 3962 if (s1.getClass() != s2.getClass()) { 3963 return false; 3964 } 3965 return s1.equals(s2); 3966 } 3967 3968 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3969 if (pi1.icon != pi2.icon) return false; 3970 if (pi1.logo != pi2.logo) return false; 3971 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3972 if (!compareStrings(pi1.name, pi2.name)) return false; 3973 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3974 // We'll take care of setting this one. 3975 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3976 // These are not currently stored in settings. 3977 //if (!compareStrings(pi1.group, pi2.group)) return false; 3978 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3979 //if (pi1.labelRes != pi2.labelRes) return false; 3980 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3981 return true; 3982 } 3983 3984 int permissionInfoFootprint(PermissionInfo info) { 3985 int size = info.name.length(); 3986 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3987 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3988 return size; 3989 } 3990 3991 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3992 int size = 0; 3993 for (BasePermission perm : mSettings.mPermissions.values()) { 3994 if (perm.uid == tree.uid) { 3995 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3996 } 3997 } 3998 return size; 3999 } 4000 4001 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4002 // We calculate the max size of permissions defined by this uid and throw 4003 // if that plus the size of 'info' would exceed our stated maximum. 4004 if (tree.uid != Process.SYSTEM_UID) { 4005 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4006 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4007 throw new SecurityException("Permission tree size cap exceeded"); 4008 } 4009 } 4010 } 4011 4012 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4013 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4014 throw new SecurityException("Label must be specified in permission"); 4015 } 4016 BasePermission tree = checkPermissionTreeLP(info.name); 4017 BasePermission bp = mSettings.mPermissions.get(info.name); 4018 boolean added = bp == null; 4019 boolean changed = true; 4020 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4021 if (added) { 4022 enforcePermissionCapLocked(info, tree); 4023 bp = new BasePermission(info.name, tree.sourcePackage, 4024 BasePermission.TYPE_DYNAMIC); 4025 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4026 throw new SecurityException( 4027 "Not allowed to modify non-dynamic permission " 4028 + info.name); 4029 } else { 4030 if (bp.protectionLevel == fixedLevel 4031 && bp.perm.owner.equals(tree.perm.owner) 4032 && bp.uid == tree.uid 4033 && comparePermissionInfos(bp.perm.info, info)) { 4034 changed = false; 4035 } 4036 } 4037 bp.protectionLevel = fixedLevel; 4038 info = new PermissionInfo(info); 4039 info.protectionLevel = fixedLevel; 4040 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4041 bp.perm.info.packageName = tree.perm.info.packageName; 4042 bp.uid = tree.uid; 4043 if (added) { 4044 mSettings.mPermissions.put(info.name, bp); 4045 } 4046 if (changed) { 4047 if (!async) { 4048 mSettings.writeLPr(); 4049 } else { 4050 scheduleWriteSettingsLocked(); 4051 } 4052 } 4053 return added; 4054 } 4055 4056 @Override 4057 public boolean addPermission(PermissionInfo info) { 4058 synchronized (mPackages) { 4059 return addPermissionLocked(info, false); 4060 } 4061 } 4062 4063 @Override 4064 public boolean addPermissionAsync(PermissionInfo info) { 4065 synchronized (mPackages) { 4066 return addPermissionLocked(info, true); 4067 } 4068 } 4069 4070 @Override 4071 public void removePermission(String name) { 4072 synchronized (mPackages) { 4073 checkPermissionTreeLP(name); 4074 BasePermission bp = mSettings.mPermissions.get(name); 4075 if (bp != null) { 4076 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4077 throw new SecurityException( 4078 "Not allowed to modify non-dynamic permission " 4079 + name); 4080 } 4081 mSettings.mPermissions.remove(name); 4082 mSettings.writeLPr(); 4083 } 4084 } 4085 } 4086 4087 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4088 BasePermission bp) { 4089 int index = pkg.requestedPermissions.indexOf(bp.name); 4090 if (index == -1) { 4091 throw new SecurityException("Package " + pkg.packageName 4092 + " has not requested permission " + bp.name); 4093 } 4094 if (!bp.isRuntime() && !bp.isDevelopment()) { 4095 throw new SecurityException("Permission " + bp.name 4096 + " is not a changeable permission type"); 4097 } 4098 } 4099 4100 @Override 4101 public void grantRuntimePermission(String packageName, String name, final int userId) { 4102 if (!sUserManager.exists(userId)) { 4103 Log.e(TAG, "No such user:" + userId); 4104 return; 4105 } 4106 4107 mContext.enforceCallingOrSelfPermission( 4108 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4109 "grantRuntimePermission"); 4110 4111 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4112 true /* requireFullPermission */, true /* checkShell */, 4113 "grantRuntimePermission"); 4114 4115 final int uid; 4116 final SettingBase sb; 4117 4118 synchronized (mPackages) { 4119 final PackageParser.Package pkg = mPackages.get(packageName); 4120 if (pkg == null) { 4121 throw new IllegalArgumentException("Unknown package: " + packageName); 4122 } 4123 4124 final BasePermission bp = mSettings.mPermissions.get(name); 4125 if (bp == null) { 4126 throw new IllegalArgumentException("Unknown permission: " + name); 4127 } 4128 4129 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4130 4131 // If a permission review is required for legacy apps we represent 4132 // their permissions as always granted runtime ones since we need 4133 // to keep the review required permission flag per user while an 4134 // install permission's state is shared across all users. 4135 if (Build.PERMISSIONS_REVIEW_REQUIRED 4136 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4137 && bp.isRuntime()) { 4138 return; 4139 } 4140 4141 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4142 sb = (SettingBase) pkg.mExtras; 4143 if (sb == null) { 4144 throw new IllegalArgumentException("Unknown package: " + packageName); 4145 } 4146 4147 final PermissionsState permissionsState = sb.getPermissionsState(); 4148 4149 final int flags = permissionsState.getPermissionFlags(name, userId); 4150 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4151 throw new SecurityException("Cannot grant system fixed permission " 4152 + name + " for package " + packageName); 4153 } 4154 4155 if (bp.isDevelopment()) { 4156 // Development permissions must be handled specially, since they are not 4157 // normal runtime permissions. For now they apply to all users. 4158 if (permissionsState.grantInstallPermission(bp) != 4159 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4160 scheduleWriteSettingsLocked(); 4161 } 4162 return; 4163 } 4164 4165 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4166 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4167 return; 4168 } 4169 4170 final int result = permissionsState.grantRuntimePermission(bp, userId); 4171 switch (result) { 4172 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4173 return; 4174 } 4175 4176 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4177 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4178 mHandler.post(new Runnable() { 4179 @Override 4180 public void run() { 4181 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4182 } 4183 }); 4184 } 4185 break; 4186 } 4187 4188 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4189 4190 // Not critical if that is lost - app has to request again. 4191 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4192 } 4193 4194 // Only need to do this if user is initialized. Otherwise it's a new user 4195 // and there are no processes running as the user yet and there's no need 4196 // to make an expensive call to remount processes for the changed permissions. 4197 if (READ_EXTERNAL_STORAGE.equals(name) 4198 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4199 final long token = Binder.clearCallingIdentity(); 4200 try { 4201 if (sUserManager.isInitialized(userId)) { 4202 MountServiceInternal mountServiceInternal = LocalServices.getService( 4203 MountServiceInternal.class); 4204 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4205 } 4206 } finally { 4207 Binder.restoreCallingIdentity(token); 4208 } 4209 } 4210 } 4211 4212 @Override 4213 public void revokeRuntimePermission(String packageName, String name, int userId) { 4214 if (!sUserManager.exists(userId)) { 4215 Log.e(TAG, "No such user:" + userId); 4216 return; 4217 } 4218 4219 mContext.enforceCallingOrSelfPermission( 4220 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4221 "revokeRuntimePermission"); 4222 4223 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4224 true /* requireFullPermission */, true /* checkShell */, 4225 "revokeRuntimePermission"); 4226 4227 final int appId; 4228 4229 synchronized (mPackages) { 4230 final PackageParser.Package pkg = mPackages.get(packageName); 4231 if (pkg == null) { 4232 throw new IllegalArgumentException("Unknown package: " + packageName); 4233 } 4234 4235 final BasePermission bp = mSettings.mPermissions.get(name); 4236 if (bp == null) { 4237 throw new IllegalArgumentException("Unknown permission: " + name); 4238 } 4239 4240 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4241 4242 // If a permission review is required for legacy apps we represent 4243 // their permissions as always granted runtime ones since we need 4244 // to keep the review required permission flag per user while an 4245 // install permission's state is shared across all users. 4246 if (Build.PERMISSIONS_REVIEW_REQUIRED 4247 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4248 && bp.isRuntime()) { 4249 return; 4250 } 4251 4252 SettingBase sb = (SettingBase) pkg.mExtras; 4253 if (sb == null) { 4254 throw new IllegalArgumentException("Unknown package: " + packageName); 4255 } 4256 4257 final PermissionsState permissionsState = sb.getPermissionsState(); 4258 4259 final int flags = permissionsState.getPermissionFlags(name, userId); 4260 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4261 throw new SecurityException("Cannot revoke system fixed permission " 4262 + name + " for package " + packageName); 4263 } 4264 4265 if (bp.isDevelopment()) { 4266 // Development permissions must be handled specially, since they are not 4267 // normal runtime permissions. For now they apply to all users. 4268 if (permissionsState.revokeInstallPermission(bp) != 4269 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4270 scheduleWriteSettingsLocked(); 4271 } 4272 return; 4273 } 4274 4275 if (permissionsState.revokeRuntimePermission(bp, userId) == 4276 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4277 return; 4278 } 4279 4280 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4281 4282 // Critical, after this call app should never have the permission. 4283 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4284 4285 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4286 } 4287 4288 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4289 } 4290 4291 @Override 4292 public void resetRuntimePermissions() { 4293 mContext.enforceCallingOrSelfPermission( 4294 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4295 "revokeRuntimePermission"); 4296 4297 int callingUid = Binder.getCallingUid(); 4298 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4299 mContext.enforceCallingOrSelfPermission( 4300 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4301 "resetRuntimePermissions"); 4302 } 4303 4304 synchronized (mPackages) { 4305 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4306 for (int userId : UserManagerService.getInstance().getUserIds()) { 4307 final int packageCount = mPackages.size(); 4308 for (int i = 0; i < packageCount; i++) { 4309 PackageParser.Package pkg = mPackages.valueAt(i); 4310 if (!(pkg.mExtras instanceof PackageSetting)) { 4311 continue; 4312 } 4313 PackageSetting ps = (PackageSetting) pkg.mExtras; 4314 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4315 } 4316 } 4317 } 4318 } 4319 4320 @Override 4321 public int getPermissionFlags(String name, String packageName, int userId) { 4322 if (!sUserManager.exists(userId)) { 4323 return 0; 4324 } 4325 4326 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4327 4328 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4329 true /* requireFullPermission */, false /* checkShell */, 4330 "getPermissionFlags"); 4331 4332 synchronized (mPackages) { 4333 final PackageParser.Package pkg = mPackages.get(packageName); 4334 if (pkg == null) { 4335 return 0; 4336 } 4337 4338 final BasePermission bp = mSettings.mPermissions.get(name); 4339 if (bp == null) { 4340 return 0; 4341 } 4342 4343 SettingBase sb = (SettingBase) pkg.mExtras; 4344 if (sb == null) { 4345 return 0; 4346 } 4347 4348 PermissionsState permissionsState = sb.getPermissionsState(); 4349 return permissionsState.getPermissionFlags(name, userId); 4350 } 4351 } 4352 4353 @Override 4354 public void updatePermissionFlags(String name, String packageName, int flagMask, 4355 int flagValues, int userId) { 4356 if (!sUserManager.exists(userId)) { 4357 return; 4358 } 4359 4360 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4361 4362 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4363 true /* requireFullPermission */, true /* checkShell */, 4364 "updatePermissionFlags"); 4365 4366 // Only the system can change these flags and nothing else. 4367 if (getCallingUid() != Process.SYSTEM_UID) { 4368 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4369 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4370 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4371 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4372 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4373 } 4374 4375 synchronized (mPackages) { 4376 final PackageParser.Package pkg = mPackages.get(packageName); 4377 if (pkg == null) { 4378 throw new IllegalArgumentException("Unknown package: " + packageName); 4379 } 4380 4381 final BasePermission bp = mSettings.mPermissions.get(name); 4382 if (bp == null) { 4383 throw new IllegalArgumentException("Unknown permission: " + name); 4384 } 4385 4386 SettingBase sb = (SettingBase) pkg.mExtras; 4387 if (sb == null) { 4388 throw new IllegalArgumentException("Unknown package: " + packageName); 4389 } 4390 4391 PermissionsState permissionsState = sb.getPermissionsState(); 4392 4393 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4394 4395 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4396 // Install and runtime permissions are stored in different places, 4397 // so figure out what permission changed and persist the change. 4398 if (permissionsState.getInstallPermissionState(name) != null) { 4399 scheduleWriteSettingsLocked(); 4400 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4401 || hadState) { 4402 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4403 } 4404 } 4405 } 4406 } 4407 4408 /** 4409 * Update the permission flags for all packages and runtime permissions of a user in order 4410 * to allow device or profile owner to remove POLICY_FIXED. 4411 */ 4412 @Override 4413 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4414 if (!sUserManager.exists(userId)) { 4415 return; 4416 } 4417 4418 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4419 4420 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4421 true /* requireFullPermission */, true /* checkShell */, 4422 "updatePermissionFlagsForAllApps"); 4423 4424 // Only the system can change system fixed flags. 4425 if (getCallingUid() != Process.SYSTEM_UID) { 4426 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4427 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4428 } 4429 4430 synchronized (mPackages) { 4431 boolean changed = false; 4432 final int packageCount = mPackages.size(); 4433 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4434 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4435 SettingBase sb = (SettingBase) pkg.mExtras; 4436 if (sb == null) { 4437 continue; 4438 } 4439 PermissionsState permissionsState = sb.getPermissionsState(); 4440 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4441 userId, flagMask, flagValues); 4442 } 4443 if (changed) { 4444 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4445 } 4446 } 4447 } 4448 4449 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4450 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4451 != PackageManager.PERMISSION_GRANTED 4452 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4453 != PackageManager.PERMISSION_GRANTED) { 4454 throw new SecurityException(message + " requires " 4455 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4456 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4457 } 4458 } 4459 4460 @Override 4461 public boolean shouldShowRequestPermissionRationale(String permissionName, 4462 String packageName, int userId) { 4463 if (UserHandle.getCallingUserId() != userId) { 4464 mContext.enforceCallingPermission( 4465 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4466 "canShowRequestPermissionRationale for user " + userId); 4467 } 4468 4469 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4470 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4471 return false; 4472 } 4473 4474 if (checkPermission(permissionName, packageName, userId) 4475 == PackageManager.PERMISSION_GRANTED) { 4476 return false; 4477 } 4478 4479 final int flags; 4480 4481 final long identity = Binder.clearCallingIdentity(); 4482 try { 4483 flags = getPermissionFlags(permissionName, 4484 packageName, userId); 4485 } finally { 4486 Binder.restoreCallingIdentity(identity); 4487 } 4488 4489 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4490 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4491 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4492 4493 if ((flags & fixedFlags) != 0) { 4494 return false; 4495 } 4496 4497 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4498 } 4499 4500 @Override 4501 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4502 mContext.enforceCallingOrSelfPermission( 4503 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4504 "addOnPermissionsChangeListener"); 4505 4506 synchronized (mPackages) { 4507 mOnPermissionChangeListeners.addListenerLocked(listener); 4508 } 4509 } 4510 4511 @Override 4512 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4513 synchronized (mPackages) { 4514 mOnPermissionChangeListeners.removeListenerLocked(listener); 4515 } 4516 } 4517 4518 @Override 4519 public boolean isProtectedBroadcast(String actionName) { 4520 synchronized (mPackages) { 4521 if (mProtectedBroadcasts.contains(actionName)) { 4522 return true; 4523 } else if (actionName != null) { 4524 // TODO: remove these terrible hacks 4525 if (actionName.startsWith("android.net.netmon.lingerExpired") 4526 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4527 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4528 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4529 return true; 4530 } 4531 } 4532 } 4533 return false; 4534 } 4535 4536 @Override 4537 public int checkSignatures(String pkg1, String pkg2) { 4538 synchronized (mPackages) { 4539 final PackageParser.Package p1 = mPackages.get(pkg1); 4540 final PackageParser.Package p2 = mPackages.get(pkg2); 4541 if (p1 == null || p1.mExtras == null 4542 || p2 == null || p2.mExtras == null) { 4543 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4544 } 4545 return compareSignatures(p1.mSignatures, p2.mSignatures); 4546 } 4547 } 4548 4549 @Override 4550 public int checkUidSignatures(int uid1, int uid2) { 4551 // Map to base uids. 4552 uid1 = UserHandle.getAppId(uid1); 4553 uid2 = UserHandle.getAppId(uid2); 4554 // reader 4555 synchronized (mPackages) { 4556 Signature[] s1; 4557 Signature[] s2; 4558 Object obj = mSettings.getUserIdLPr(uid1); 4559 if (obj != null) { 4560 if (obj instanceof SharedUserSetting) { 4561 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4562 } else if (obj instanceof PackageSetting) { 4563 s1 = ((PackageSetting)obj).signatures.mSignatures; 4564 } else { 4565 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4566 } 4567 } else { 4568 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4569 } 4570 obj = mSettings.getUserIdLPr(uid2); 4571 if (obj != null) { 4572 if (obj instanceof SharedUserSetting) { 4573 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4574 } else if (obj instanceof PackageSetting) { 4575 s2 = ((PackageSetting)obj).signatures.mSignatures; 4576 } else { 4577 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4578 } 4579 } else { 4580 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4581 } 4582 return compareSignatures(s1, s2); 4583 } 4584 } 4585 4586 /** 4587 * This method should typically only be used when granting or revoking 4588 * permissions, since the app may immediately restart after this call. 4589 * <p> 4590 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4591 * guard your work against the app being relaunched. 4592 */ 4593 private void killUid(int appId, int userId, String reason) { 4594 final long identity = Binder.clearCallingIdentity(); 4595 try { 4596 IActivityManager am = ActivityManagerNative.getDefault(); 4597 if (am != null) { 4598 try { 4599 am.killUid(appId, userId, reason); 4600 } catch (RemoteException e) { 4601 /* ignore - same process */ 4602 } 4603 } 4604 } finally { 4605 Binder.restoreCallingIdentity(identity); 4606 } 4607 } 4608 4609 /** 4610 * Compares two sets of signatures. Returns: 4611 * <br /> 4612 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4613 * <br /> 4614 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4615 * <br /> 4616 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4617 * <br /> 4618 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4619 * <br /> 4620 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4621 */ 4622 static int compareSignatures(Signature[] s1, Signature[] s2) { 4623 if (s1 == null) { 4624 return s2 == null 4625 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4626 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4627 } 4628 4629 if (s2 == null) { 4630 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4631 } 4632 4633 if (s1.length != s2.length) { 4634 return PackageManager.SIGNATURE_NO_MATCH; 4635 } 4636 4637 // Since both signature sets are of size 1, we can compare without HashSets. 4638 if (s1.length == 1) { 4639 return s1[0].equals(s2[0]) ? 4640 PackageManager.SIGNATURE_MATCH : 4641 PackageManager.SIGNATURE_NO_MATCH; 4642 } 4643 4644 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4645 for (Signature sig : s1) { 4646 set1.add(sig); 4647 } 4648 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4649 for (Signature sig : s2) { 4650 set2.add(sig); 4651 } 4652 // Make sure s2 contains all signatures in s1. 4653 if (set1.equals(set2)) { 4654 return PackageManager.SIGNATURE_MATCH; 4655 } 4656 return PackageManager.SIGNATURE_NO_MATCH; 4657 } 4658 4659 /** 4660 * If the database version for this type of package (internal storage or 4661 * external storage) is less than the version where package signatures 4662 * were updated, return true. 4663 */ 4664 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4665 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4666 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4667 } 4668 4669 /** 4670 * Used for backward compatibility to make sure any packages with 4671 * certificate chains get upgraded to the new style. {@code existingSigs} 4672 * will be in the old format (since they were stored on disk from before the 4673 * system upgrade) and {@code scannedSigs} will be in the newer format. 4674 */ 4675 private int compareSignaturesCompat(PackageSignatures existingSigs, 4676 PackageParser.Package scannedPkg) { 4677 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4678 return PackageManager.SIGNATURE_NO_MATCH; 4679 } 4680 4681 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4682 for (Signature sig : existingSigs.mSignatures) { 4683 existingSet.add(sig); 4684 } 4685 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4686 for (Signature sig : scannedPkg.mSignatures) { 4687 try { 4688 Signature[] chainSignatures = sig.getChainSignatures(); 4689 for (Signature chainSig : chainSignatures) { 4690 scannedCompatSet.add(chainSig); 4691 } 4692 } catch (CertificateEncodingException e) { 4693 scannedCompatSet.add(sig); 4694 } 4695 } 4696 /* 4697 * Make sure the expanded scanned set contains all signatures in the 4698 * existing one. 4699 */ 4700 if (scannedCompatSet.equals(existingSet)) { 4701 // Migrate the old signatures to the new scheme. 4702 existingSigs.assignSignatures(scannedPkg.mSignatures); 4703 // The new KeySets will be re-added later in the scanning process. 4704 synchronized (mPackages) { 4705 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4706 } 4707 return PackageManager.SIGNATURE_MATCH; 4708 } 4709 return PackageManager.SIGNATURE_NO_MATCH; 4710 } 4711 4712 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4713 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4714 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4715 } 4716 4717 private int compareSignaturesRecover(PackageSignatures existingSigs, 4718 PackageParser.Package scannedPkg) { 4719 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4720 return PackageManager.SIGNATURE_NO_MATCH; 4721 } 4722 4723 String msg = null; 4724 try { 4725 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4726 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4727 + scannedPkg.packageName); 4728 return PackageManager.SIGNATURE_MATCH; 4729 } 4730 } catch (CertificateException e) { 4731 msg = e.getMessage(); 4732 } 4733 4734 logCriticalInfo(Log.INFO, 4735 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4736 return PackageManager.SIGNATURE_NO_MATCH; 4737 } 4738 4739 @Override 4740 public List<String> getAllPackages() { 4741 synchronized (mPackages) { 4742 return new ArrayList<String>(mPackages.keySet()); 4743 } 4744 } 4745 4746 @Override 4747 public String[] getPackagesForUid(int uid) { 4748 uid = UserHandle.getAppId(uid); 4749 // reader 4750 synchronized (mPackages) { 4751 Object obj = mSettings.getUserIdLPr(uid); 4752 if (obj instanceof SharedUserSetting) { 4753 final SharedUserSetting sus = (SharedUserSetting) obj; 4754 final int N = sus.packages.size(); 4755 final String[] res = new String[N]; 4756 final Iterator<PackageSetting> it = sus.packages.iterator(); 4757 int i = 0; 4758 while (it.hasNext()) { 4759 res[i++] = it.next().name; 4760 } 4761 return res; 4762 } else if (obj instanceof PackageSetting) { 4763 final PackageSetting ps = (PackageSetting) obj; 4764 return new String[] { ps.name }; 4765 } 4766 } 4767 return null; 4768 } 4769 4770 @Override 4771 public String getNameForUid(int uid) { 4772 // reader 4773 synchronized (mPackages) { 4774 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4775 if (obj instanceof SharedUserSetting) { 4776 final SharedUserSetting sus = (SharedUserSetting) obj; 4777 return sus.name + ":" + sus.userId; 4778 } else if (obj instanceof PackageSetting) { 4779 final PackageSetting ps = (PackageSetting) obj; 4780 return ps.name; 4781 } 4782 } 4783 return null; 4784 } 4785 4786 @Override 4787 public int getUidForSharedUser(String sharedUserName) { 4788 if(sharedUserName == null) { 4789 return -1; 4790 } 4791 // reader 4792 synchronized (mPackages) { 4793 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4794 if (suid == null) { 4795 return -1; 4796 } 4797 return suid.userId; 4798 } 4799 } 4800 4801 @Override 4802 public int getFlagsForUid(int uid) { 4803 synchronized (mPackages) { 4804 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4805 if (obj instanceof SharedUserSetting) { 4806 final SharedUserSetting sus = (SharedUserSetting) obj; 4807 return sus.pkgFlags; 4808 } else if (obj instanceof PackageSetting) { 4809 final PackageSetting ps = (PackageSetting) obj; 4810 return ps.pkgFlags; 4811 } 4812 } 4813 return 0; 4814 } 4815 4816 @Override 4817 public int getPrivateFlagsForUid(int uid) { 4818 synchronized (mPackages) { 4819 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4820 if (obj instanceof SharedUserSetting) { 4821 final SharedUserSetting sus = (SharedUserSetting) obj; 4822 return sus.pkgPrivateFlags; 4823 } else if (obj instanceof PackageSetting) { 4824 final PackageSetting ps = (PackageSetting) obj; 4825 return ps.pkgPrivateFlags; 4826 } 4827 } 4828 return 0; 4829 } 4830 4831 @Override 4832 public boolean isUidPrivileged(int uid) { 4833 uid = UserHandle.getAppId(uid); 4834 // reader 4835 synchronized (mPackages) { 4836 Object obj = mSettings.getUserIdLPr(uid); 4837 if (obj instanceof SharedUserSetting) { 4838 final SharedUserSetting sus = (SharedUserSetting) obj; 4839 final Iterator<PackageSetting> it = sus.packages.iterator(); 4840 while (it.hasNext()) { 4841 if (it.next().isPrivileged()) { 4842 return true; 4843 } 4844 } 4845 } else if (obj instanceof PackageSetting) { 4846 final PackageSetting ps = (PackageSetting) obj; 4847 return ps.isPrivileged(); 4848 } 4849 } 4850 return false; 4851 } 4852 4853 @Override 4854 public String[] getAppOpPermissionPackages(String permissionName) { 4855 synchronized (mPackages) { 4856 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4857 if (pkgs == null) { 4858 return null; 4859 } 4860 return pkgs.toArray(new String[pkgs.size()]); 4861 } 4862 } 4863 4864 @Override 4865 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4866 int flags, int userId) { 4867 try { 4868 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4869 4870 if (!sUserManager.exists(userId)) return null; 4871 flags = updateFlagsForResolve(flags, userId, intent); 4872 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4873 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4874 4875 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4876 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4877 flags, userId); 4878 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4879 4880 final ResolveInfo bestChoice = 4881 chooseBestActivity(intent, resolvedType, flags, query, userId); 4882 4883 if (isEphemeralAllowed(intent, query, userId)) { 4884 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4885 final EphemeralResolveInfo ai = 4886 getEphemeralResolveInfo(intent, resolvedType, userId); 4887 if (ai != null) { 4888 if (DEBUG_EPHEMERAL) { 4889 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4890 } 4891 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4892 bestChoice.ephemeralResolveInfo = ai; 4893 } 4894 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4895 } 4896 return bestChoice; 4897 } finally { 4898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4899 } 4900 } 4901 4902 @Override 4903 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4904 IntentFilter filter, int match, ComponentName activity) { 4905 final int userId = UserHandle.getCallingUserId(); 4906 if (DEBUG_PREFERRED) { 4907 Log.v(TAG, "setLastChosenActivity intent=" + intent 4908 + " resolvedType=" + resolvedType 4909 + " flags=" + flags 4910 + " filter=" + filter 4911 + " match=" + match 4912 + " activity=" + activity); 4913 filter.dump(new PrintStreamPrinter(System.out), " "); 4914 } 4915 intent.setComponent(null); 4916 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4917 userId); 4918 // Find any earlier preferred or last chosen entries and nuke them 4919 findPreferredActivity(intent, resolvedType, 4920 flags, query, 0, false, true, false, userId); 4921 // Add the new activity as the last chosen for this filter 4922 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4923 "Setting last chosen"); 4924 } 4925 4926 @Override 4927 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4928 final int userId = UserHandle.getCallingUserId(); 4929 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4930 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4931 userId); 4932 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4933 false, false, false, userId); 4934 } 4935 4936 4937 private boolean isEphemeralAllowed( 4938 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4939 // Short circuit and return early if possible. 4940 if (DISABLE_EPHEMERAL_APPS) { 4941 return false; 4942 } 4943 final int callingUser = UserHandle.getCallingUserId(); 4944 if (callingUser != UserHandle.USER_SYSTEM) { 4945 return false; 4946 } 4947 if (mEphemeralResolverConnection == null) { 4948 return false; 4949 } 4950 if (intent.getComponent() != null) { 4951 return false; 4952 } 4953 if (intent.getPackage() != null) { 4954 return false; 4955 } 4956 final boolean isWebUri = hasWebURI(intent); 4957 if (!isWebUri) { 4958 return false; 4959 } 4960 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4961 synchronized (mPackages) { 4962 final int count = resolvedActivites.size(); 4963 for (int n = 0; n < count; n++) { 4964 ResolveInfo info = resolvedActivites.get(n); 4965 String packageName = info.activityInfo.packageName; 4966 PackageSetting ps = mSettings.mPackages.get(packageName); 4967 if (ps != null) { 4968 // Try to get the status from User settings first 4969 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4970 int status = (int) (packedStatus >> 32); 4971 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4972 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4973 if (DEBUG_EPHEMERAL) { 4974 Slog.v(TAG, "DENY ephemeral apps;" 4975 + " pkg: " + packageName + ", status: " + status); 4976 } 4977 return false; 4978 } 4979 } 4980 } 4981 } 4982 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4983 return true; 4984 } 4985 4986 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4987 int userId) { 4988 MessageDigest digest = null; 4989 try { 4990 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4991 } catch (NoSuchAlgorithmException e) { 4992 // If we can't create a digest, ignore ephemeral apps. 4993 return null; 4994 } 4995 4996 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4997 final byte[] digestBytes = digest.digest(hostBytes); 4998 int shaPrefix = 4999 digestBytes[0] << 24 5000 | digestBytes[1] << 16 5001 | digestBytes[2] << 8 5002 | digestBytes[3] << 0; 5003 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5004 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 5005 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5006 // No hash prefix match; there are no ephemeral apps for this domain. 5007 return null; 5008 } 5009 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 5010 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 5011 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 5012 continue; 5013 } 5014 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5015 // No filters; this should never happen. 5016 if (filters.isEmpty()) { 5017 continue; 5018 } 5019 // We have a domain match; resolve the filters to see if anything matches. 5020 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5021 for (int j = filters.size() - 1; j >= 0; --j) { 5022 final EphemeralResolveIntentInfo intentInfo = 5023 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5024 ephemeralResolver.addFilter(intentInfo); 5025 } 5026 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5027 intent, resolvedType, false /*defaultOnly*/, userId); 5028 if (!matchedResolveInfoList.isEmpty()) { 5029 return matchedResolveInfoList.get(0); 5030 } 5031 } 5032 // Hash or filter mis-match; no ephemeral apps for this domain. 5033 return null; 5034 } 5035 5036 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5037 int flags, List<ResolveInfo> query, int userId) { 5038 if (query != null) { 5039 final int N = query.size(); 5040 if (N == 1) { 5041 return query.get(0); 5042 } else if (N > 1) { 5043 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5044 // If there is more than one activity with the same priority, 5045 // then let the user decide between them. 5046 ResolveInfo r0 = query.get(0); 5047 ResolveInfo r1 = query.get(1); 5048 if (DEBUG_INTENT_MATCHING || debug) { 5049 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5050 + r1.activityInfo.name + "=" + r1.priority); 5051 } 5052 // If the first activity has a higher priority, or a different 5053 // default, then it is always desirable to pick it. 5054 if (r0.priority != r1.priority 5055 || r0.preferredOrder != r1.preferredOrder 5056 || r0.isDefault != r1.isDefault) { 5057 return query.get(0); 5058 } 5059 // If we have saved a preference for a preferred activity for 5060 // this Intent, use that. 5061 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5062 flags, query, r0.priority, true, false, debug, userId); 5063 if (ri != null) { 5064 return ri; 5065 } 5066 ri = new ResolveInfo(mResolveInfo); 5067 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5068 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5069 // If all of the options come from the same package, show the application's 5070 // label and icon instead of the generic resolver's. 5071 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5072 // and then throw away the ResolveInfo itself, meaning that the caller loses 5073 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5074 // a fallback for this case; we only set the target package's resources on 5075 // the ResolveInfo, not the ActivityInfo. 5076 final String intentPackage = intent.getPackage(); 5077 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5078 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5079 ri.resolvePackageName = intentPackage; 5080 if (userNeedsBadging(userId)) { 5081 ri.noResourceId = true; 5082 } else { 5083 ri.icon = appi.icon; 5084 } 5085 ri.iconResourceId = appi.icon; 5086 ri.labelRes = appi.labelRes; 5087 } 5088 ri.activityInfo.applicationInfo = new ApplicationInfo( 5089 ri.activityInfo.applicationInfo); 5090 if (userId != 0) { 5091 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5092 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5093 } 5094 // Make sure that the resolver is displayable in car mode 5095 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5096 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5097 return ri; 5098 } 5099 } 5100 return null; 5101 } 5102 5103 /** 5104 * Return true if the given list is not empty and all of its contents have 5105 * an activityInfo with the given package name. 5106 */ 5107 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5108 if (ArrayUtils.isEmpty(list)) { 5109 return false; 5110 } 5111 for (int i = 0, N = list.size(); i < N; i++) { 5112 final ResolveInfo ri = list.get(i); 5113 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5114 if (ai == null || !packageName.equals(ai.packageName)) { 5115 return false; 5116 } 5117 } 5118 return true; 5119 } 5120 5121 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5122 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5123 final int N = query.size(); 5124 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5125 .get(userId); 5126 // Get the list of persistent preferred activities that handle the intent 5127 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5128 List<PersistentPreferredActivity> pprefs = ppir != null 5129 ? ppir.queryIntent(intent, resolvedType, 5130 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5131 : null; 5132 if (pprefs != null && pprefs.size() > 0) { 5133 final int M = pprefs.size(); 5134 for (int i=0; i<M; i++) { 5135 final PersistentPreferredActivity ppa = pprefs.get(i); 5136 if (DEBUG_PREFERRED || debug) { 5137 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5138 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5139 + "\n component=" + ppa.mComponent); 5140 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5141 } 5142 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5143 flags | MATCH_DISABLED_COMPONENTS, userId); 5144 if (DEBUG_PREFERRED || debug) { 5145 Slog.v(TAG, "Found persistent preferred activity:"); 5146 if (ai != null) { 5147 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5148 } else { 5149 Slog.v(TAG, " null"); 5150 } 5151 } 5152 if (ai == null) { 5153 // This previously registered persistent preferred activity 5154 // component is no longer known. Ignore it and do NOT remove it. 5155 continue; 5156 } 5157 for (int j=0; j<N; j++) { 5158 final ResolveInfo ri = query.get(j); 5159 if (!ri.activityInfo.applicationInfo.packageName 5160 .equals(ai.applicationInfo.packageName)) { 5161 continue; 5162 } 5163 if (!ri.activityInfo.name.equals(ai.name)) { 5164 continue; 5165 } 5166 // Found a persistent preference that can handle the intent. 5167 if (DEBUG_PREFERRED || debug) { 5168 Slog.v(TAG, "Returning persistent preferred activity: " + 5169 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5170 } 5171 return ri; 5172 } 5173 } 5174 } 5175 return null; 5176 } 5177 5178 // TODO: handle preferred activities missing while user has amnesia 5179 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5180 List<ResolveInfo> query, int priority, boolean always, 5181 boolean removeMatches, boolean debug, int userId) { 5182 if (!sUserManager.exists(userId)) return null; 5183 flags = updateFlagsForResolve(flags, userId, intent); 5184 // writer 5185 synchronized (mPackages) { 5186 if (intent.getSelector() != null) { 5187 intent = intent.getSelector(); 5188 } 5189 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5190 5191 // Try to find a matching persistent preferred activity. 5192 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5193 debug, userId); 5194 5195 // If a persistent preferred activity matched, use it. 5196 if (pri != null) { 5197 return pri; 5198 } 5199 5200 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5201 // Get the list of preferred activities that handle the intent 5202 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5203 List<PreferredActivity> prefs = pir != null 5204 ? pir.queryIntent(intent, resolvedType, 5205 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5206 : null; 5207 if (prefs != null && prefs.size() > 0) { 5208 boolean changed = false; 5209 try { 5210 // First figure out how good the original match set is. 5211 // We will only allow preferred activities that came 5212 // from the same match quality. 5213 int match = 0; 5214 5215 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5216 5217 final int N = query.size(); 5218 for (int j=0; j<N; j++) { 5219 final ResolveInfo ri = query.get(j); 5220 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5221 + ": 0x" + Integer.toHexString(match)); 5222 if (ri.match > match) { 5223 match = ri.match; 5224 } 5225 } 5226 5227 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5228 + Integer.toHexString(match)); 5229 5230 match &= IntentFilter.MATCH_CATEGORY_MASK; 5231 final int M = prefs.size(); 5232 for (int i=0; i<M; i++) { 5233 final PreferredActivity pa = prefs.get(i); 5234 if (DEBUG_PREFERRED || debug) { 5235 Slog.v(TAG, "Checking PreferredActivity ds=" 5236 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5237 + "\n component=" + pa.mPref.mComponent); 5238 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5239 } 5240 if (pa.mPref.mMatch != match) { 5241 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5242 + Integer.toHexString(pa.mPref.mMatch)); 5243 continue; 5244 } 5245 // If it's not an "always" type preferred activity and that's what we're 5246 // looking for, skip it. 5247 if (always && !pa.mPref.mAlways) { 5248 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5249 continue; 5250 } 5251 final ActivityInfo ai = getActivityInfo( 5252 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5253 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5254 userId); 5255 if (DEBUG_PREFERRED || debug) { 5256 Slog.v(TAG, "Found preferred activity:"); 5257 if (ai != null) { 5258 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5259 } else { 5260 Slog.v(TAG, " null"); 5261 } 5262 } 5263 if (ai == null) { 5264 // This previously registered preferred activity 5265 // component is no longer known. Most likely an update 5266 // to the app was installed and in the new version this 5267 // component no longer exists. Clean it up by removing 5268 // it from the preferred activities list, and skip it. 5269 Slog.w(TAG, "Removing dangling preferred activity: " 5270 + pa.mPref.mComponent); 5271 pir.removeFilter(pa); 5272 changed = true; 5273 continue; 5274 } 5275 for (int j=0; j<N; j++) { 5276 final ResolveInfo ri = query.get(j); 5277 if (!ri.activityInfo.applicationInfo.packageName 5278 .equals(ai.applicationInfo.packageName)) { 5279 continue; 5280 } 5281 if (!ri.activityInfo.name.equals(ai.name)) { 5282 continue; 5283 } 5284 5285 if (removeMatches) { 5286 pir.removeFilter(pa); 5287 changed = true; 5288 if (DEBUG_PREFERRED) { 5289 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5290 } 5291 break; 5292 } 5293 5294 // Okay we found a previously set preferred or last chosen app. 5295 // If the result set is different from when this 5296 // was created, we need to clear it and re-ask the 5297 // user their preference, if we're looking for an "always" type entry. 5298 if (always && !pa.mPref.sameSet(query)) { 5299 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5300 + intent + " type " + resolvedType); 5301 if (DEBUG_PREFERRED) { 5302 Slog.v(TAG, "Removing preferred activity since set changed " 5303 + pa.mPref.mComponent); 5304 } 5305 pir.removeFilter(pa); 5306 // Re-add the filter as a "last chosen" entry (!always) 5307 PreferredActivity lastChosen = new PreferredActivity( 5308 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5309 pir.addFilter(lastChosen); 5310 changed = true; 5311 return null; 5312 } 5313 5314 // Yay! Either the set matched or we're looking for the last chosen 5315 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5316 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5317 return ri; 5318 } 5319 } 5320 } finally { 5321 if (changed) { 5322 if (DEBUG_PREFERRED) { 5323 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5324 } 5325 scheduleWritePackageRestrictionsLocked(userId); 5326 } 5327 } 5328 } 5329 } 5330 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5331 return null; 5332 } 5333 5334 /* 5335 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5336 */ 5337 @Override 5338 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5339 int targetUserId) { 5340 mContext.enforceCallingOrSelfPermission( 5341 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5342 List<CrossProfileIntentFilter> matches = 5343 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5344 if (matches != null) { 5345 int size = matches.size(); 5346 for (int i = 0; i < size; i++) { 5347 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5348 } 5349 } 5350 if (hasWebURI(intent)) { 5351 // cross-profile app linking works only towards the parent. 5352 final UserInfo parent = getProfileParent(sourceUserId); 5353 synchronized(mPackages) { 5354 int flags = updateFlagsForResolve(0, parent.id, intent); 5355 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5356 intent, resolvedType, flags, sourceUserId, parent.id); 5357 return xpDomainInfo != null; 5358 } 5359 } 5360 return false; 5361 } 5362 5363 private UserInfo getProfileParent(int userId) { 5364 final long identity = Binder.clearCallingIdentity(); 5365 try { 5366 return sUserManager.getProfileParent(userId); 5367 } finally { 5368 Binder.restoreCallingIdentity(identity); 5369 } 5370 } 5371 5372 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5373 String resolvedType, int userId) { 5374 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5375 if (resolver != null) { 5376 return resolver.queryIntent(intent, resolvedType, false, userId); 5377 } 5378 return null; 5379 } 5380 5381 @Override 5382 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5383 String resolvedType, int flags, int userId) { 5384 try { 5385 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5386 5387 return new ParceledListSlice<>( 5388 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5389 } finally { 5390 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5391 } 5392 } 5393 5394 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5395 String resolvedType, int flags, int userId) { 5396 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5397 flags = updateFlagsForResolve(flags, userId, intent); 5398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5399 false /* requireFullPermission */, false /* checkShell */, 5400 "query intent activities"); 5401 ComponentName comp = intent.getComponent(); 5402 if (comp == null) { 5403 if (intent.getSelector() != null) { 5404 intent = intent.getSelector(); 5405 comp = intent.getComponent(); 5406 } 5407 } 5408 5409 if (comp != null) { 5410 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5411 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5412 if (ai != null) { 5413 final ResolveInfo ri = new ResolveInfo(); 5414 ri.activityInfo = ai; 5415 list.add(ri); 5416 } 5417 return list; 5418 } 5419 5420 // reader 5421 synchronized (mPackages) { 5422 final String pkgName = intent.getPackage(); 5423 if (pkgName == null) { 5424 List<CrossProfileIntentFilter> matchingFilters = 5425 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5426 // Check for results that need to skip the current profile. 5427 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5428 resolvedType, flags, userId); 5429 if (xpResolveInfo != null) { 5430 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5431 result.add(xpResolveInfo); 5432 return filterIfNotSystemUser(result, userId); 5433 } 5434 5435 // Check for results in the current profile. 5436 List<ResolveInfo> result = mActivities.queryIntent( 5437 intent, resolvedType, flags, userId); 5438 result = filterIfNotSystemUser(result, userId); 5439 5440 // Check for cross profile results. 5441 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5442 xpResolveInfo = queryCrossProfileIntents( 5443 matchingFilters, intent, resolvedType, flags, userId, 5444 hasNonNegativePriorityResult); 5445 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5446 boolean isVisibleToUser = filterIfNotSystemUser( 5447 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5448 if (isVisibleToUser) { 5449 result.add(xpResolveInfo); 5450 Collections.sort(result, mResolvePrioritySorter); 5451 } 5452 } 5453 if (hasWebURI(intent)) { 5454 CrossProfileDomainInfo xpDomainInfo = null; 5455 final UserInfo parent = getProfileParent(userId); 5456 if (parent != null) { 5457 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5458 flags, userId, parent.id); 5459 } 5460 if (xpDomainInfo != null) { 5461 if (xpResolveInfo != null) { 5462 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5463 // in the result. 5464 result.remove(xpResolveInfo); 5465 } 5466 if (result.size() == 0) { 5467 result.add(xpDomainInfo.resolveInfo); 5468 return result; 5469 } 5470 } else if (result.size() <= 1) { 5471 return result; 5472 } 5473 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5474 xpDomainInfo, userId); 5475 Collections.sort(result, mResolvePrioritySorter); 5476 } 5477 return result; 5478 } 5479 final PackageParser.Package pkg = mPackages.get(pkgName); 5480 if (pkg != null) { 5481 return filterIfNotSystemUser( 5482 mActivities.queryIntentForPackage( 5483 intent, resolvedType, flags, pkg.activities, userId), 5484 userId); 5485 } 5486 return new ArrayList<ResolveInfo>(); 5487 } 5488 } 5489 5490 private static class CrossProfileDomainInfo { 5491 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5492 ResolveInfo resolveInfo; 5493 /* Best domain verification status of the activities found in the other profile */ 5494 int bestDomainVerificationStatus; 5495 } 5496 5497 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5498 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5499 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5500 sourceUserId)) { 5501 return null; 5502 } 5503 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5504 resolvedType, flags, parentUserId); 5505 5506 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5507 return null; 5508 } 5509 CrossProfileDomainInfo result = null; 5510 int size = resultTargetUser.size(); 5511 for (int i = 0; i < size; i++) { 5512 ResolveInfo riTargetUser = resultTargetUser.get(i); 5513 // Intent filter verification is only for filters that specify a host. So don't return 5514 // those that handle all web uris. 5515 if (riTargetUser.handleAllWebDataURI) { 5516 continue; 5517 } 5518 String packageName = riTargetUser.activityInfo.packageName; 5519 PackageSetting ps = mSettings.mPackages.get(packageName); 5520 if (ps == null) { 5521 continue; 5522 } 5523 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5524 int status = (int)(verificationState >> 32); 5525 if (result == null) { 5526 result = new CrossProfileDomainInfo(); 5527 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5528 sourceUserId, parentUserId); 5529 result.bestDomainVerificationStatus = status; 5530 } else { 5531 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5532 result.bestDomainVerificationStatus); 5533 } 5534 } 5535 // Don't consider matches with status NEVER across profiles. 5536 if (result != null && result.bestDomainVerificationStatus 5537 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5538 return null; 5539 } 5540 return result; 5541 } 5542 5543 /** 5544 * Verification statuses are ordered from the worse to the best, except for 5545 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5546 */ 5547 private int bestDomainVerificationStatus(int status1, int status2) { 5548 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5549 return status2; 5550 } 5551 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5552 return status1; 5553 } 5554 return (int) MathUtils.max(status1, status2); 5555 } 5556 5557 private boolean isUserEnabled(int userId) { 5558 long callingId = Binder.clearCallingIdentity(); 5559 try { 5560 UserInfo userInfo = sUserManager.getUserInfo(userId); 5561 return userInfo != null && userInfo.isEnabled(); 5562 } finally { 5563 Binder.restoreCallingIdentity(callingId); 5564 } 5565 } 5566 5567 /** 5568 * Filter out activities with systemUserOnly flag set, when current user is not System. 5569 * 5570 * @return filtered list 5571 */ 5572 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5573 if (userId == UserHandle.USER_SYSTEM) { 5574 return resolveInfos; 5575 } 5576 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5577 ResolveInfo info = resolveInfos.get(i); 5578 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5579 resolveInfos.remove(i); 5580 } 5581 } 5582 return resolveInfos; 5583 } 5584 5585 /** 5586 * @param resolveInfos list of resolve infos in descending priority order 5587 * @return if the list contains a resolve info with non-negative priority 5588 */ 5589 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5590 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5591 } 5592 5593 private static boolean hasWebURI(Intent intent) { 5594 if (intent.getData() == null) { 5595 return false; 5596 } 5597 final String scheme = intent.getScheme(); 5598 if (TextUtils.isEmpty(scheme)) { 5599 return false; 5600 } 5601 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5602 } 5603 5604 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5605 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5606 int userId) { 5607 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5608 5609 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5610 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5611 candidates.size()); 5612 } 5613 5614 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5615 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5616 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5617 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5618 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5619 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5620 5621 synchronized (mPackages) { 5622 final int count = candidates.size(); 5623 // First, try to use linked apps. Partition the candidates into four lists: 5624 // one for the final results, one for the "do not use ever", one for "undefined status" 5625 // and finally one for "browser app type". 5626 for (int n=0; n<count; n++) { 5627 ResolveInfo info = candidates.get(n); 5628 String packageName = info.activityInfo.packageName; 5629 PackageSetting ps = mSettings.mPackages.get(packageName); 5630 if (ps != null) { 5631 // Add to the special match all list (Browser use case) 5632 if (info.handleAllWebDataURI) { 5633 matchAllList.add(info); 5634 continue; 5635 } 5636 // Try to get the status from User settings first 5637 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5638 int status = (int)(packedStatus >> 32); 5639 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5640 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5641 if (DEBUG_DOMAIN_VERIFICATION) { 5642 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5643 + " : linkgen=" + linkGeneration); 5644 } 5645 // Use link-enabled generation as preferredOrder, i.e. 5646 // prefer newly-enabled over earlier-enabled. 5647 info.preferredOrder = linkGeneration; 5648 alwaysList.add(info); 5649 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5650 if (DEBUG_DOMAIN_VERIFICATION) { 5651 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5652 } 5653 neverList.add(info); 5654 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5655 if (DEBUG_DOMAIN_VERIFICATION) { 5656 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5657 } 5658 alwaysAskList.add(info); 5659 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5660 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5661 if (DEBUG_DOMAIN_VERIFICATION) { 5662 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5663 } 5664 undefinedList.add(info); 5665 } 5666 } 5667 } 5668 5669 // We'll want to include browser possibilities in a few cases 5670 boolean includeBrowser = false; 5671 5672 // First try to add the "always" resolution(s) for the current user, if any 5673 if (alwaysList.size() > 0) { 5674 result.addAll(alwaysList); 5675 } else { 5676 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5677 result.addAll(undefinedList); 5678 // Maybe add one for the other profile. 5679 if (xpDomainInfo != null && ( 5680 xpDomainInfo.bestDomainVerificationStatus 5681 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5682 result.add(xpDomainInfo.resolveInfo); 5683 } 5684 includeBrowser = true; 5685 } 5686 5687 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5688 // If there were 'always' entries their preferred order has been set, so we also 5689 // back that off to make the alternatives equivalent 5690 if (alwaysAskList.size() > 0) { 5691 for (ResolveInfo i : result) { 5692 i.preferredOrder = 0; 5693 } 5694 result.addAll(alwaysAskList); 5695 includeBrowser = true; 5696 } 5697 5698 if (includeBrowser) { 5699 // Also add browsers (all of them or only the default one) 5700 if (DEBUG_DOMAIN_VERIFICATION) { 5701 Slog.v(TAG, " ...including browsers in candidate set"); 5702 } 5703 if ((matchFlags & MATCH_ALL) != 0) { 5704 result.addAll(matchAllList); 5705 } else { 5706 // Browser/generic handling case. If there's a default browser, go straight 5707 // to that (but only if there is no other higher-priority match). 5708 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5709 int maxMatchPrio = 0; 5710 ResolveInfo defaultBrowserMatch = null; 5711 final int numCandidates = matchAllList.size(); 5712 for (int n = 0; n < numCandidates; n++) { 5713 ResolveInfo info = matchAllList.get(n); 5714 // track the highest overall match priority... 5715 if (info.priority > maxMatchPrio) { 5716 maxMatchPrio = info.priority; 5717 } 5718 // ...and the highest-priority default browser match 5719 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5720 if (defaultBrowserMatch == null 5721 || (defaultBrowserMatch.priority < info.priority)) { 5722 if (debug) { 5723 Slog.v(TAG, "Considering default browser match " + info); 5724 } 5725 defaultBrowserMatch = info; 5726 } 5727 } 5728 } 5729 if (defaultBrowserMatch != null 5730 && defaultBrowserMatch.priority >= maxMatchPrio 5731 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5732 { 5733 if (debug) { 5734 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5735 } 5736 result.add(defaultBrowserMatch); 5737 } else { 5738 result.addAll(matchAllList); 5739 } 5740 } 5741 5742 // If there is nothing selected, add all candidates and remove the ones that the user 5743 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5744 if (result.size() == 0) { 5745 result.addAll(candidates); 5746 result.removeAll(neverList); 5747 } 5748 } 5749 } 5750 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5751 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5752 result.size()); 5753 for (ResolveInfo info : result) { 5754 Slog.v(TAG, " + " + info.activityInfo); 5755 } 5756 } 5757 return result; 5758 } 5759 5760 // Returns a packed value as a long: 5761 // 5762 // high 'int'-sized word: link status: undefined/ask/never/always. 5763 // low 'int'-sized word: relative priority among 'always' results. 5764 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5765 long result = ps.getDomainVerificationStatusForUser(userId); 5766 // if none available, get the master status 5767 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5768 if (ps.getIntentFilterVerificationInfo() != null) { 5769 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5770 } 5771 } 5772 return result; 5773 } 5774 5775 private ResolveInfo querySkipCurrentProfileIntents( 5776 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5777 int flags, int sourceUserId) { 5778 if (matchingFilters != null) { 5779 int size = matchingFilters.size(); 5780 for (int i = 0; i < size; i ++) { 5781 CrossProfileIntentFilter filter = matchingFilters.get(i); 5782 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5783 // Checking if there are activities in the target user that can handle the 5784 // intent. 5785 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5786 resolvedType, flags, sourceUserId); 5787 if (resolveInfo != null) { 5788 return resolveInfo; 5789 } 5790 } 5791 } 5792 } 5793 return null; 5794 } 5795 5796 // Return matching ResolveInfo in target user if any. 5797 private ResolveInfo queryCrossProfileIntents( 5798 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5799 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5800 if (matchingFilters != null) { 5801 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5802 // match the same intent. For performance reasons, it is better not to 5803 // run queryIntent twice for the same userId 5804 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5805 int size = matchingFilters.size(); 5806 for (int i = 0; i < size; i++) { 5807 CrossProfileIntentFilter filter = matchingFilters.get(i); 5808 int targetUserId = filter.getTargetUserId(); 5809 boolean skipCurrentProfile = 5810 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5811 boolean skipCurrentProfileIfNoMatchFound = 5812 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5813 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5814 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5815 // Checking if there are activities in the target user that can handle the 5816 // intent. 5817 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5818 resolvedType, flags, sourceUserId); 5819 if (resolveInfo != null) return resolveInfo; 5820 alreadyTriedUserIds.put(targetUserId, true); 5821 } 5822 } 5823 } 5824 return null; 5825 } 5826 5827 /** 5828 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5829 * will forward the intent to the filter's target user. 5830 * Otherwise, returns null. 5831 */ 5832 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5833 String resolvedType, int flags, int sourceUserId) { 5834 int targetUserId = filter.getTargetUserId(); 5835 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5836 resolvedType, flags, targetUserId); 5837 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5838 // If all the matches in the target profile are suspended, return null. 5839 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5840 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5841 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5842 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5843 targetUserId); 5844 } 5845 } 5846 } 5847 return null; 5848 } 5849 5850 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5851 int sourceUserId, int targetUserId) { 5852 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5853 long ident = Binder.clearCallingIdentity(); 5854 boolean targetIsProfile; 5855 try { 5856 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5857 } finally { 5858 Binder.restoreCallingIdentity(ident); 5859 } 5860 String className; 5861 if (targetIsProfile) { 5862 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5863 } else { 5864 className = FORWARD_INTENT_TO_PARENT; 5865 } 5866 ComponentName forwardingActivityComponentName = new ComponentName( 5867 mAndroidApplication.packageName, className); 5868 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5869 sourceUserId); 5870 if (!targetIsProfile) { 5871 forwardingActivityInfo.showUserIcon = targetUserId; 5872 forwardingResolveInfo.noResourceId = true; 5873 } 5874 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5875 forwardingResolveInfo.priority = 0; 5876 forwardingResolveInfo.preferredOrder = 0; 5877 forwardingResolveInfo.match = 0; 5878 forwardingResolveInfo.isDefault = true; 5879 forwardingResolveInfo.filter = filter; 5880 forwardingResolveInfo.targetUserId = targetUserId; 5881 return forwardingResolveInfo; 5882 } 5883 5884 @Override 5885 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5886 Intent[] specifics, String[] specificTypes, Intent intent, 5887 String resolvedType, int flags, int userId) { 5888 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5889 specificTypes, intent, resolvedType, flags, userId)); 5890 } 5891 5892 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5893 Intent[] specifics, String[] specificTypes, Intent intent, 5894 String resolvedType, int flags, int userId) { 5895 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5896 flags = updateFlagsForResolve(flags, userId, intent); 5897 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5898 false /* requireFullPermission */, false /* checkShell */, 5899 "query intent activity options"); 5900 final String resultsAction = intent.getAction(); 5901 5902 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5903 | PackageManager.GET_RESOLVED_FILTER, userId); 5904 5905 if (DEBUG_INTENT_MATCHING) { 5906 Log.v(TAG, "Query " + intent + ": " + results); 5907 } 5908 5909 int specificsPos = 0; 5910 int N; 5911 5912 // todo: note that the algorithm used here is O(N^2). This 5913 // isn't a problem in our current environment, but if we start running 5914 // into situations where we have more than 5 or 10 matches then this 5915 // should probably be changed to something smarter... 5916 5917 // First we go through and resolve each of the specific items 5918 // that were supplied, taking care of removing any corresponding 5919 // duplicate items in the generic resolve list. 5920 if (specifics != null) { 5921 for (int i=0; i<specifics.length; i++) { 5922 final Intent sintent = specifics[i]; 5923 if (sintent == null) { 5924 continue; 5925 } 5926 5927 if (DEBUG_INTENT_MATCHING) { 5928 Log.v(TAG, "Specific #" + i + ": " + sintent); 5929 } 5930 5931 String action = sintent.getAction(); 5932 if (resultsAction != null && resultsAction.equals(action)) { 5933 // If this action was explicitly requested, then don't 5934 // remove things that have it. 5935 action = null; 5936 } 5937 5938 ResolveInfo ri = null; 5939 ActivityInfo ai = null; 5940 5941 ComponentName comp = sintent.getComponent(); 5942 if (comp == null) { 5943 ri = resolveIntent( 5944 sintent, 5945 specificTypes != null ? specificTypes[i] : null, 5946 flags, userId); 5947 if (ri == null) { 5948 continue; 5949 } 5950 if (ri == mResolveInfo) { 5951 // ACK! Must do something better with this. 5952 } 5953 ai = ri.activityInfo; 5954 comp = new ComponentName(ai.applicationInfo.packageName, 5955 ai.name); 5956 } else { 5957 ai = getActivityInfo(comp, flags, userId); 5958 if (ai == null) { 5959 continue; 5960 } 5961 } 5962 5963 // Look for any generic query activities that are duplicates 5964 // of this specific one, and remove them from the results. 5965 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5966 N = results.size(); 5967 int j; 5968 for (j=specificsPos; j<N; j++) { 5969 ResolveInfo sri = results.get(j); 5970 if ((sri.activityInfo.name.equals(comp.getClassName()) 5971 && sri.activityInfo.applicationInfo.packageName.equals( 5972 comp.getPackageName())) 5973 || (action != null && sri.filter.matchAction(action))) { 5974 results.remove(j); 5975 if (DEBUG_INTENT_MATCHING) Log.v( 5976 TAG, "Removing duplicate item from " + j 5977 + " due to specific " + specificsPos); 5978 if (ri == null) { 5979 ri = sri; 5980 } 5981 j--; 5982 N--; 5983 } 5984 } 5985 5986 // Add this specific item to its proper place. 5987 if (ri == null) { 5988 ri = new ResolveInfo(); 5989 ri.activityInfo = ai; 5990 } 5991 results.add(specificsPos, ri); 5992 ri.specificIndex = i; 5993 specificsPos++; 5994 } 5995 } 5996 5997 // Now we go through the remaining generic results and remove any 5998 // duplicate actions that are found here. 5999 N = results.size(); 6000 for (int i=specificsPos; i<N-1; i++) { 6001 final ResolveInfo rii = results.get(i); 6002 if (rii.filter == null) { 6003 continue; 6004 } 6005 6006 // Iterate over all of the actions of this result's intent 6007 // filter... typically this should be just one. 6008 final Iterator<String> it = rii.filter.actionsIterator(); 6009 if (it == null) { 6010 continue; 6011 } 6012 while (it.hasNext()) { 6013 final String action = it.next(); 6014 if (resultsAction != null && resultsAction.equals(action)) { 6015 // If this action was explicitly requested, then don't 6016 // remove things that have it. 6017 continue; 6018 } 6019 for (int j=i+1; j<N; j++) { 6020 final ResolveInfo rij = results.get(j); 6021 if (rij.filter != null && rij.filter.hasAction(action)) { 6022 results.remove(j); 6023 if (DEBUG_INTENT_MATCHING) Log.v( 6024 TAG, "Removing duplicate item from " + j 6025 + " due to action " + action + " at " + i); 6026 j--; 6027 N--; 6028 } 6029 } 6030 } 6031 6032 // If the caller didn't request filter information, drop it now 6033 // so we don't have to marshall/unmarshall it. 6034 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6035 rii.filter = null; 6036 } 6037 } 6038 6039 // Filter out the caller activity if so requested. 6040 if (caller != null) { 6041 N = results.size(); 6042 for (int i=0; i<N; i++) { 6043 ActivityInfo ainfo = results.get(i).activityInfo; 6044 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6045 && caller.getClassName().equals(ainfo.name)) { 6046 results.remove(i); 6047 break; 6048 } 6049 } 6050 } 6051 6052 // If the caller didn't request filter information, 6053 // drop them now so we don't have to 6054 // marshall/unmarshall it. 6055 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6056 N = results.size(); 6057 for (int i=0; i<N; i++) { 6058 results.get(i).filter = null; 6059 } 6060 } 6061 6062 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6063 return results; 6064 } 6065 6066 @Override 6067 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6068 String resolvedType, int flags, int userId) { 6069 return new ParceledListSlice<>( 6070 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6071 } 6072 6073 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6074 String resolvedType, int flags, int userId) { 6075 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6076 flags = updateFlagsForResolve(flags, userId, intent); 6077 ComponentName comp = intent.getComponent(); 6078 if (comp == null) { 6079 if (intent.getSelector() != null) { 6080 intent = intent.getSelector(); 6081 comp = intent.getComponent(); 6082 } 6083 } 6084 if (comp != null) { 6085 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6086 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6087 if (ai != null) { 6088 ResolveInfo ri = new ResolveInfo(); 6089 ri.activityInfo = ai; 6090 list.add(ri); 6091 } 6092 return list; 6093 } 6094 6095 // reader 6096 synchronized (mPackages) { 6097 String pkgName = intent.getPackage(); 6098 if (pkgName == null) { 6099 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6100 } 6101 final PackageParser.Package pkg = mPackages.get(pkgName); 6102 if (pkg != null) { 6103 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6104 userId); 6105 } 6106 return Collections.emptyList(); 6107 } 6108 } 6109 6110 @Override 6111 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6112 if (!sUserManager.exists(userId)) return null; 6113 flags = updateFlagsForResolve(flags, userId, intent); 6114 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6115 if (query != null) { 6116 if (query.size() >= 1) { 6117 // If there is more than one service with the same priority, 6118 // just arbitrarily pick the first one. 6119 return query.get(0); 6120 } 6121 } 6122 return null; 6123 } 6124 6125 @Override 6126 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6127 String resolvedType, int flags, int userId) { 6128 return new ParceledListSlice<>( 6129 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6130 } 6131 6132 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6133 String resolvedType, int flags, int userId) { 6134 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6135 flags = updateFlagsForResolve(flags, userId, intent); 6136 ComponentName comp = intent.getComponent(); 6137 if (comp == null) { 6138 if (intent.getSelector() != null) { 6139 intent = intent.getSelector(); 6140 comp = intent.getComponent(); 6141 } 6142 } 6143 if (comp != null) { 6144 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6145 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6146 if (si != null) { 6147 final ResolveInfo ri = new ResolveInfo(); 6148 ri.serviceInfo = si; 6149 list.add(ri); 6150 } 6151 return list; 6152 } 6153 6154 // reader 6155 synchronized (mPackages) { 6156 String pkgName = intent.getPackage(); 6157 if (pkgName == null) { 6158 return mServices.queryIntent(intent, resolvedType, flags, userId); 6159 } 6160 final PackageParser.Package pkg = mPackages.get(pkgName); 6161 if (pkg != null) { 6162 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6163 userId); 6164 } 6165 return Collections.emptyList(); 6166 } 6167 } 6168 6169 @Override 6170 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6171 String resolvedType, int flags, int userId) { 6172 return new ParceledListSlice<>( 6173 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6174 } 6175 6176 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6177 Intent intent, String resolvedType, int flags, int userId) { 6178 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6179 flags = updateFlagsForResolve(flags, userId, intent); 6180 ComponentName comp = intent.getComponent(); 6181 if (comp == null) { 6182 if (intent.getSelector() != null) { 6183 intent = intent.getSelector(); 6184 comp = intent.getComponent(); 6185 } 6186 } 6187 if (comp != null) { 6188 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6189 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6190 if (pi != null) { 6191 final ResolveInfo ri = new ResolveInfo(); 6192 ri.providerInfo = pi; 6193 list.add(ri); 6194 } 6195 return list; 6196 } 6197 6198 // reader 6199 synchronized (mPackages) { 6200 String pkgName = intent.getPackage(); 6201 if (pkgName == null) { 6202 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6203 } 6204 final PackageParser.Package pkg = mPackages.get(pkgName); 6205 if (pkg != null) { 6206 return mProviders.queryIntentForPackage( 6207 intent, resolvedType, flags, pkg.providers, userId); 6208 } 6209 return Collections.emptyList(); 6210 } 6211 } 6212 6213 @Override 6214 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6215 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6216 flags = updateFlagsForPackage(flags, userId, null); 6217 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6218 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6219 true /* requireFullPermission */, false /* checkShell */, 6220 "get installed packages"); 6221 6222 // writer 6223 synchronized (mPackages) { 6224 ArrayList<PackageInfo> list; 6225 if (listUninstalled) { 6226 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6227 for (PackageSetting ps : mSettings.mPackages.values()) { 6228 final PackageInfo pi; 6229 if (ps.pkg != null) { 6230 pi = generatePackageInfo(ps, flags, userId); 6231 } else { 6232 pi = generatePackageInfo(ps, flags, userId); 6233 } 6234 if (pi != null) { 6235 list.add(pi); 6236 } 6237 } 6238 } else { 6239 list = new ArrayList<PackageInfo>(mPackages.size()); 6240 for (PackageParser.Package p : mPackages.values()) { 6241 final PackageInfo pi = 6242 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6243 if (pi != null) { 6244 list.add(pi); 6245 } 6246 } 6247 } 6248 6249 return new ParceledListSlice<PackageInfo>(list); 6250 } 6251 } 6252 6253 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6254 String[] permissions, boolean[] tmp, int flags, int userId) { 6255 int numMatch = 0; 6256 final PermissionsState permissionsState = ps.getPermissionsState(); 6257 for (int i=0; i<permissions.length; i++) { 6258 final String permission = permissions[i]; 6259 if (permissionsState.hasPermission(permission, userId)) { 6260 tmp[i] = true; 6261 numMatch++; 6262 } else { 6263 tmp[i] = false; 6264 } 6265 } 6266 if (numMatch == 0) { 6267 return; 6268 } 6269 final PackageInfo pi; 6270 if (ps.pkg != null) { 6271 pi = generatePackageInfo(ps, flags, userId); 6272 } else { 6273 pi = generatePackageInfo(ps, flags, userId); 6274 } 6275 // The above might return null in cases of uninstalled apps or install-state 6276 // skew across users/profiles. 6277 if (pi != null) { 6278 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6279 if (numMatch == permissions.length) { 6280 pi.requestedPermissions = permissions; 6281 } else { 6282 pi.requestedPermissions = new String[numMatch]; 6283 numMatch = 0; 6284 for (int i=0; i<permissions.length; i++) { 6285 if (tmp[i]) { 6286 pi.requestedPermissions[numMatch] = permissions[i]; 6287 numMatch++; 6288 } 6289 } 6290 } 6291 } 6292 list.add(pi); 6293 } 6294 } 6295 6296 @Override 6297 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6298 String[] permissions, int flags, int userId) { 6299 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6300 flags = updateFlagsForPackage(flags, userId, permissions); 6301 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6302 6303 // writer 6304 synchronized (mPackages) { 6305 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6306 boolean[] tmpBools = new boolean[permissions.length]; 6307 if (listUninstalled) { 6308 for (PackageSetting ps : mSettings.mPackages.values()) { 6309 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6310 } 6311 } else { 6312 for (PackageParser.Package pkg : mPackages.values()) { 6313 PackageSetting ps = (PackageSetting)pkg.mExtras; 6314 if (ps != null) { 6315 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6316 userId); 6317 } 6318 } 6319 } 6320 6321 return new ParceledListSlice<PackageInfo>(list); 6322 } 6323 } 6324 6325 @Override 6326 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6327 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6328 flags = updateFlagsForApplication(flags, userId, null); 6329 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6330 6331 // writer 6332 synchronized (mPackages) { 6333 ArrayList<ApplicationInfo> list; 6334 if (listUninstalled) { 6335 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6336 for (PackageSetting ps : mSettings.mPackages.values()) { 6337 ApplicationInfo ai; 6338 if (ps.pkg != null) { 6339 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6340 ps.readUserState(userId), userId); 6341 } else { 6342 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6343 } 6344 if (ai != null) { 6345 list.add(ai); 6346 } 6347 } 6348 } else { 6349 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6350 for (PackageParser.Package p : mPackages.values()) { 6351 if (p.mExtras != null) { 6352 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6353 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6354 if (ai != null) { 6355 list.add(ai); 6356 } 6357 } 6358 } 6359 } 6360 6361 return new ParceledListSlice<ApplicationInfo>(list); 6362 } 6363 } 6364 6365 @Override 6366 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6367 if (DISABLE_EPHEMERAL_APPS) { 6368 return null; 6369 } 6370 6371 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6372 "getEphemeralApplications"); 6373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6374 true /* requireFullPermission */, false /* checkShell */, 6375 "getEphemeralApplications"); 6376 synchronized (mPackages) { 6377 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6378 .getEphemeralApplicationsLPw(userId); 6379 if (ephemeralApps != null) { 6380 return new ParceledListSlice<>(ephemeralApps); 6381 } 6382 } 6383 return null; 6384 } 6385 6386 @Override 6387 public boolean isEphemeralApplication(String packageName, int userId) { 6388 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6389 true /* requireFullPermission */, false /* checkShell */, 6390 "isEphemeral"); 6391 if (DISABLE_EPHEMERAL_APPS) { 6392 return false; 6393 } 6394 6395 if (!isCallerSameApp(packageName)) { 6396 return false; 6397 } 6398 synchronized (mPackages) { 6399 PackageParser.Package pkg = mPackages.get(packageName); 6400 if (pkg != null) { 6401 return pkg.applicationInfo.isEphemeralApp(); 6402 } 6403 } 6404 return false; 6405 } 6406 6407 @Override 6408 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6409 if (DISABLE_EPHEMERAL_APPS) { 6410 return null; 6411 } 6412 6413 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6414 true /* requireFullPermission */, false /* checkShell */, 6415 "getCookie"); 6416 if (!isCallerSameApp(packageName)) { 6417 return null; 6418 } 6419 synchronized (mPackages) { 6420 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6421 packageName, userId); 6422 } 6423 } 6424 6425 @Override 6426 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6427 if (DISABLE_EPHEMERAL_APPS) { 6428 return true; 6429 } 6430 6431 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6432 true /* requireFullPermission */, true /* checkShell */, 6433 "setCookie"); 6434 if (!isCallerSameApp(packageName)) { 6435 return false; 6436 } 6437 synchronized (mPackages) { 6438 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6439 packageName, cookie, userId); 6440 } 6441 } 6442 6443 @Override 6444 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6445 if (DISABLE_EPHEMERAL_APPS) { 6446 return null; 6447 } 6448 6449 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6450 "getEphemeralApplicationIcon"); 6451 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6452 true /* requireFullPermission */, false /* checkShell */, 6453 "getEphemeralApplicationIcon"); 6454 synchronized (mPackages) { 6455 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6456 packageName, userId); 6457 } 6458 } 6459 6460 private boolean isCallerSameApp(String packageName) { 6461 PackageParser.Package pkg = mPackages.get(packageName); 6462 return pkg != null 6463 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6464 } 6465 6466 @Override 6467 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6468 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6469 } 6470 6471 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6472 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6473 6474 // reader 6475 synchronized (mPackages) { 6476 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6477 final int userId = UserHandle.getCallingUserId(); 6478 while (i.hasNext()) { 6479 final PackageParser.Package p = i.next(); 6480 if (p.applicationInfo == null) continue; 6481 6482 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6483 && !p.applicationInfo.isDirectBootAware(); 6484 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6485 && p.applicationInfo.isDirectBootAware(); 6486 6487 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6488 && (!mSafeMode || isSystemApp(p)) 6489 && (matchesUnaware || matchesAware)) { 6490 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6491 if (ps != null) { 6492 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6493 ps.readUserState(userId), userId); 6494 if (ai != null) { 6495 finalList.add(ai); 6496 } 6497 } 6498 } 6499 } 6500 } 6501 6502 return finalList; 6503 } 6504 6505 @Override 6506 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6507 if (!sUserManager.exists(userId)) return null; 6508 flags = updateFlagsForComponent(flags, userId, name); 6509 // reader 6510 synchronized (mPackages) { 6511 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6512 PackageSetting ps = provider != null 6513 ? mSettings.mPackages.get(provider.owner.packageName) 6514 : null; 6515 return ps != null 6516 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6517 ? PackageParser.generateProviderInfo(provider, flags, 6518 ps.readUserState(userId), userId) 6519 : null; 6520 } 6521 } 6522 6523 /** 6524 * @deprecated 6525 */ 6526 @Deprecated 6527 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6528 // reader 6529 synchronized (mPackages) { 6530 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6531 .entrySet().iterator(); 6532 final int userId = UserHandle.getCallingUserId(); 6533 while (i.hasNext()) { 6534 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6535 PackageParser.Provider p = entry.getValue(); 6536 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6537 6538 if (ps != null && p.syncable 6539 && (!mSafeMode || (p.info.applicationInfo.flags 6540 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6541 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6542 ps.readUserState(userId), userId); 6543 if (info != null) { 6544 outNames.add(entry.getKey()); 6545 outInfo.add(info); 6546 } 6547 } 6548 } 6549 } 6550 } 6551 6552 @Override 6553 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6554 int uid, int flags) { 6555 final int userId = processName != null ? UserHandle.getUserId(uid) 6556 : UserHandle.getCallingUserId(); 6557 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6558 flags = updateFlagsForComponent(flags, userId, processName); 6559 6560 ArrayList<ProviderInfo> finalList = null; 6561 // reader 6562 synchronized (mPackages) { 6563 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6564 while (i.hasNext()) { 6565 final PackageParser.Provider p = i.next(); 6566 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6567 if (ps != null && p.info.authority != null 6568 && (processName == null 6569 || (p.info.processName.equals(processName) 6570 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6571 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6572 if (finalList == null) { 6573 finalList = new ArrayList<ProviderInfo>(3); 6574 } 6575 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6576 ps.readUserState(userId), userId); 6577 if (info != null) { 6578 finalList.add(info); 6579 } 6580 } 6581 } 6582 } 6583 6584 if (finalList != null) { 6585 Collections.sort(finalList, mProviderInitOrderSorter); 6586 return new ParceledListSlice<ProviderInfo>(finalList); 6587 } 6588 6589 return ParceledListSlice.emptyList(); 6590 } 6591 6592 @Override 6593 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6594 // reader 6595 synchronized (mPackages) { 6596 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6597 return PackageParser.generateInstrumentationInfo(i, flags); 6598 } 6599 } 6600 6601 @Override 6602 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6603 String targetPackage, int flags) { 6604 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6605 } 6606 6607 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6608 int flags) { 6609 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6610 6611 // reader 6612 synchronized (mPackages) { 6613 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6614 while (i.hasNext()) { 6615 final PackageParser.Instrumentation p = i.next(); 6616 if (targetPackage == null 6617 || targetPackage.equals(p.info.targetPackage)) { 6618 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6619 flags); 6620 if (ii != null) { 6621 finalList.add(ii); 6622 } 6623 } 6624 } 6625 } 6626 6627 return finalList; 6628 } 6629 6630 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6631 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6632 if (overlays == null) { 6633 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6634 return; 6635 } 6636 for (PackageParser.Package opkg : overlays.values()) { 6637 // Not much to do if idmap fails: we already logged the error 6638 // and we certainly don't want to abort installation of pkg simply 6639 // because an overlay didn't fit properly. For these reasons, 6640 // ignore the return value of createIdmapForPackagePairLI. 6641 createIdmapForPackagePairLI(pkg, opkg); 6642 } 6643 } 6644 6645 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6646 PackageParser.Package opkg) { 6647 if (!opkg.mTrustedOverlay) { 6648 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6649 opkg.baseCodePath + ": overlay not trusted"); 6650 return false; 6651 } 6652 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6653 if (overlaySet == null) { 6654 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6655 opkg.baseCodePath + " but target package has no known overlays"); 6656 return false; 6657 } 6658 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6659 // TODO: generate idmap for split APKs 6660 try { 6661 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6662 } catch (InstallerException e) { 6663 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6664 + opkg.baseCodePath); 6665 return false; 6666 } 6667 PackageParser.Package[] overlayArray = 6668 overlaySet.values().toArray(new PackageParser.Package[0]); 6669 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6670 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6671 return p1.mOverlayPriority - p2.mOverlayPriority; 6672 } 6673 }; 6674 Arrays.sort(overlayArray, cmp); 6675 6676 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6677 int i = 0; 6678 for (PackageParser.Package p : overlayArray) { 6679 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6680 } 6681 return true; 6682 } 6683 6684 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6685 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6686 try { 6687 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6688 } finally { 6689 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6690 } 6691 } 6692 6693 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6694 final File[] files = dir.listFiles(); 6695 if (ArrayUtils.isEmpty(files)) { 6696 Log.d(TAG, "No files in app dir " + dir); 6697 return; 6698 } 6699 6700 if (DEBUG_PACKAGE_SCANNING) { 6701 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6702 + " flags=0x" + Integer.toHexString(parseFlags)); 6703 } 6704 6705 for (File file : files) { 6706 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6707 && !PackageInstallerService.isStageName(file.getName()); 6708 if (!isPackage) { 6709 // Ignore entries which are not packages 6710 continue; 6711 } 6712 try { 6713 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6714 scanFlags, currentTime, null); 6715 } catch (PackageManagerException e) { 6716 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6717 6718 // Delete invalid userdata apps 6719 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6720 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6721 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6722 removeCodePathLI(file); 6723 } 6724 } 6725 } 6726 } 6727 6728 private static File getSettingsProblemFile() { 6729 File dataDir = Environment.getDataDirectory(); 6730 File systemDir = new File(dataDir, "system"); 6731 File fname = new File(systemDir, "uiderrors.txt"); 6732 return fname; 6733 } 6734 6735 static void reportSettingsProblem(int priority, String msg) { 6736 logCriticalInfo(priority, msg); 6737 } 6738 6739 static void logCriticalInfo(int priority, String msg) { 6740 Slog.println(priority, TAG, msg); 6741 EventLogTags.writePmCriticalInfo(msg); 6742 try { 6743 File fname = getSettingsProblemFile(); 6744 FileOutputStream out = new FileOutputStream(fname, true); 6745 PrintWriter pw = new FastPrintWriter(out); 6746 SimpleDateFormat formatter = new SimpleDateFormat(); 6747 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6748 pw.println(dateString + ": " + msg); 6749 pw.close(); 6750 FileUtils.setPermissions( 6751 fname.toString(), 6752 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6753 -1, -1); 6754 } catch (java.io.IOException e) { 6755 } 6756 } 6757 6758 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6759 final int policyFlags) throws PackageManagerException { 6760 if (ps != null 6761 && ps.codePath.equals(srcFile) 6762 && ps.timeStamp == srcFile.lastModified() 6763 && !isCompatSignatureUpdateNeeded(pkg) 6764 && !isRecoverSignatureUpdateNeeded(pkg)) { 6765 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6766 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6767 ArraySet<PublicKey> signingKs; 6768 synchronized (mPackages) { 6769 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6770 } 6771 if (ps.signatures.mSignatures != null 6772 && ps.signatures.mSignatures.length != 0 6773 && signingKs != null) { 6774 // Optimization: reuse the existing cached certificates 6775 // if the package appears to be unchanged. 6776 pkg.mSignatures = ps.signatures.mSignatures; 6777 pkg.mSigningKeys = signingKs; 6778 return; 6779 } 6780 6781 Slog.w(TAG, "PackageSetting for " + ps.name 6782 + " is missing signatures. Collecting certs again to recover them."); 6783 } else { 6784 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6785 } 6786 6787 try { 6788 PackageParser.collectCertificates(pkg, policyFlags); 6789 } catch (PackageParserException e) { 6790 throw PackageManagerException.from(e); 6791 } 6792 } 6793 6794 /** 6795 * Traces a package scan. 6796 * @see #scanPackageLI(File, int, int, long, UserHandle) 6797 */ 6798 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6799 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6800 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6801 try { 6802 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6803 } finally { 6804 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6805 } 6806 } 6807 6808 /** 6809 * Scans a package and returns the newly parsed package. 6810 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6811 */ 6812 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6813 long currentTime, UserHandle user) throws PackageManagerException { 6814 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6815 PackageParser pp = new PackageParser(); 6816 pp.setSeparateProcesses(mSeparateProcesses); 6817 pp.setOnlyCoreApps(mOnlyCore); 6818 pp.setDisplayMetrics(mMetrics); 6819 6820 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6821 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6822 } 6823 6824 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6825 final PackageParser.Package pkg; 6826 try { 6827 pkg = pp.parsePackage(scanFile, parseFlags); 6828 } catch (PackageParserException e) { 6829 throw PackageManagerException.from(e); 6830 } finally { 6831 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6832 } 6833 6834 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6835 } 6836 6837 /** 6838 * Scans a package and returns the newly parsed package. 6839 * @throws PackageManagerException on a parse error. 6840 */ 6841 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6842 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6843 throws PackageManagerException { 6844 // If the package has children and this is the first dive in the function 6845 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6846 // packages (parent and children) would be successfully scanned before the 6847 // actual scan since scanning mutates internal state and we want to atomically 6848 // install the package and its children. 6849 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6850 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6851 scanFlags |= SCAN_CHECK_ONLY; 6852 } 6853 } else { 6854 scanFlags &= ~SCAN_CHECK_ONLY; 6855 } 6856 6857 // Scan the parent 6858 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6859 scanFlags, currentTime, user); 6860 6861 // Scan the children 6862 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6863 for (int i = 0; i < childCount; i++) { 6864 PackageParser.Package childPackage = pkg.childPackages.get(i); 6865 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6866 currentTime, user); 6867 } 6868 6869 6870 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6871 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6872 } 6873 6874 return scannedPkg; 6875 } 6876 6877 /** 6878 * Scans a package and returns the newly parsed package. 6879 * @throws PackageManagerException on a parse error. 6880 */ 6881 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6882 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6883 throws PackageManagerException { 6884 PackageSetting ps = null; 6885 PackageSetting updatedPkg; 6886 // reader 6887 synchronized (mPackages) { 6888 // Look to see if we already know about this package. 6889 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6890 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6891 // This package has been renamed to its original name. Let's 6892 // use that. 6893 ps = mSettings.peekPackageLPr(oldName); 6894 } 6895 // If there was no original package, see one for the real package name. 6896 if (ps == null) { 6897 ps = mSettings.peekPackageLPr(pkg.packageName); 6898 } 6899 // Check to see if this package could be hiding/updating a system 6900 // package. Must look for it either under the original or real 6901 // package name depending on our state. 6902 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6903 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6904 6905 // If this is a package we don't know about on the system partition, we 6906 // may need to remove disabled child packages on the system partition 6907 // or may need to not add child packages if the parent apk is updated 6908 // on the data partition and no longer defines this child package. 6909 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6910 // If this is a parent package for an updated system app and this system 6911 // app got an OTA update which no longer defines some of the child packages 6912 // we have to prune them from the disabled system packages. 6913 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6914 if (disabledPs != null) { 6915 final int scannedChildCount = (pkg.childPackages != null) 6916 ? pkg.childPackages.size() : 0; 6917 final int disabledChildCount = disabledPs.childPackageNames != null 6918 ? disabledPs.childPackageNames.size() : 0; 6919 for (int i = 0; i < disabledChildCount; i++) { 6920 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6921 boolean disabledPackageAvailable = false; 6922 for (int j = 0; j < scannedChildCount; j++) { 6923 PackageParser.Package childPkg = pkg.childPackages.get(j); 6924 if (childPkg.packageName.equals(disabledChildPackageName)) { 6925 disabledPackageAvailable = true; 6926 break; 6927 } 6928 } 6929 if (!disabledPackageAvailable) { 6930 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6931 } 6932 } 6933 } 6934 } 6935 } 6936 6937 boolean updatedPkgBetter = false; 6938 // First check if this is a system package that may involve an update 6939 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6940 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6941 // it needs to drop FLAG_PRIVILEGED. 6942 if (locationIsPrivileged(scanFile)) { 6943 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6944 } else { 6945 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6946 } 6947 6948 if (ps != null && !ps.codePath.equals(scanFile)) { 6949 // The path has changed from what was last scanned... check the 6950 // version of the new path against what we have stored to determine 6951 // what to do. 6952 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6953 if (pkg.mVersionCode <= ps.versionCode) { 6954 // The system package has been updated and the code path does not match 6955 // Ignore entry. Skip it. 6956 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6957 + " ignored: updated version " + ps.versionCode 6958 + " better than this " + pkg.mVersionCode); 6959 if (!updatedPkg.codePath.equals(scanFile)) { 6960 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6961 + ps.name + " changing from " + updatedPkg.codePathString 6962 + " to " + scanFile); 6963 updatedPkg.codePath = scanFile; 6964 updatedPkg.codePathString = scanFile.toString(); 6965 updatedPkg.resourcePath = scanFile; 6966 updatedPkg.resourcePathString = scanFile.toString(); 6967 } 6968 updatedPkg.pkg = pkg; 6969 updatedPkg.versionCode = pkg.mVersionCode; 6970 6971 // Update the disabled system child packages to point to the package too. 6972 final int childCount = updatedPkg.childPackageNames != null 6973 ? updatedPkg.childPackageNames.size() : 0; 6974 for (int i = 0; i < childCount; i++) { 6975 String childPackageName = updatedPkg.childPackageNames.get(i); 6976 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6977 childPackageName); 6978 if (updatedChildPkg != null) { 6979 updatedChildPkg.pkg = pkg; 6980 updatedChildPkg.versionCode = pkg.mVersionCode; 6981 } 6982 } 6983 6984 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6985 + scanFile + " ignored: updated version " + ps.versionCode 6986 + " better than this " + pkg.mVersionCode); 6987 } else { 6988 // The current app on the system partition is better than 6989 // what we have updated to on the data partition; switch 6990 // back to the system partition version. 6991 // At this point, its safely assumed that package installation for 6992 // apps in system partition will go through. If not there won't be a working 6993 // version of the app 6994 // writer 6995 synchronized (mPackages) { 6996 // Just remove the loaded entries from package lists. 6997 mPackages.remove(ps.name); 6998 } 6999 7000 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7001 + " reverting from " + ps.codePathString 7002 + ": new version " + pkg.mVersionCode 7003 + " better than installed " + ps.versionCode); 7004 7005 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7006 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7007 synchronized (mInstallLock) { 7008 args.cleanUpResourcesLI(); 7009 } 7010 synchronized (mPackages) { 7011 mSettings.enableSystemPackageLPw(ps.name); 7012 } 7013 updatedPkgBetter = true; 7014 } 7015 } 7016 } 7017 7018 if (updatedPkg != null) { 7019 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7020 // initially 7021 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7022 7023 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7024 // flag set initially 7025 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7026 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7027 } 7028 } 7029 7030 // Verify certificates against what was last scanned 7031 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7032 7033 /* 7034 * A new system app appeared, but we already had a non-system one of the 7035 * same name installed earlier. 7036 */ 7037 boolean shouldHideSystemApp = false; 7038 if (updatedPkg == null && ps != null 7039 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7040 /* 7041 * Check to make sure the signatures match first. If they don't, 7042 * wipe the installed application and its data. 7043 */ 7044 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7045 != PackageManager.SIGNATURE_MATCH) { 7046 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7047 + " signatures don't match existing userdata copy; removing"); 7048 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7049 "scanPackageInternalLI")) { 7050 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7051 } 7052 ps = null; 7053 } else { 7054 /* 7055 * If the newly-added system app is an older version than the 7056 * already installed version, hide it. It will be scanned later 7057 * and re-added like an update. 7058 */ 7059 if (pkg.mVersionCode <= ps.versionCode) { 7060 shouldHideSystemApp = true; 7061 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7062 + " but new version " + pkg.mVersionCode + " better than installed " 7063 + ps.versionCode + "; hiding system"); 7064 } else { 7065 /* 7066 * The newly found system app is a newer version that the 7067 * one previously installed. Simply remove the 7068 * already-installed application and replace it with our own 7069 * while keeping the application data. 7070 */ 7071 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7072 + " reverting from " + ps.codePathString + ": new version " 7073 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7074 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7075 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7076 synchronized (mInstallLock) { 7077 args.cleanUpResourcesLI(); 7078 } 7079 } 7080 } 7081 } 7082 7083 // The apk is forward locked (not public) if its code and resources 7084 // are kept in different files. (except for app in either system or 7085 // vendor path). 7086 // TODO grab this value from PackageSettings 7087 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7088 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7089 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7090 } 7091 } 7092 7093 // TODO: extend to support forward-locked splits 7094 String resourcePath = null; 7095 String baseResourcePath = null; 7096 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7097 if (ps != null && ps.resourcePathString != null) { 7098 resourcePath = ps.resourcePathString; 7099 baseResourcePath = ps.resourcePathString; 7100 } else { 7101 // Should not happen at all. Just log an error. 7102 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7103 } 7104 } else { 7105 resourcePath = pkg.codePath; 7106 baseResourcePath = pkg.baseCodePath; 7107 } 7108 7109 // Set application objects path explicitly. 7110 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7111 pkg.setApplicationInfoCodePath(pkg.codePath); 7112 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7113 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7114 pkg.setApplicationInfoResourcePath(resourcePath); 7115 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7116 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7117 7118 // Note that we invoke the following method only if we are about to unpack an application 7119 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7120 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7121 7122 /* 7123 * If the system app should be overridden by a previously installed 7124 * data, hide the system app now and let the /data/app scan pick it up 7125 * again. 7126 */ 7127 if (shouldHideSystemApp) { 7128 synchronized (mPackages) { 7129 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7130 } 7131 } 7132 7133 return scannedPkg; 7134 } 7135 7136 private static String fixProcessName(String defProcessName, 7137 String processName, int uid) { 7138 if (processName == null) { 7139 return defProcessName; 7140 } 7141 return processName; 7142 } 7143 7144 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7145 throws PackageManagerException { 7146 if (pkgSetting.signatures.mSignatures != null) { 7147 // Already existing package. Make sure signatures match 7148 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7149 == PackageManager.SIGNATURE_MATCH; 7150 if (!match) { 7151 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7152 == PackageManager.SIGNATURE_MATCH; 7153 } 7154 if (!match) { 7155 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7156 == PackageManager.SIGNATURE_MATCH; 7157 } 7158 if (!match) { 7159 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7160 + pkg.packageName + " signatures do not match the " 7161 + "previously installed version; ignoring!"); 7162 } 7163 } 7164 7165 // Check for shared user signatures 7166 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7167 // Already existing package. Make sure signatures match 7168 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7169 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7170 if (!match) { 7171 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7172 == PackageManager.SIGNATURE_MATCH; 7173 } 7174 if (!match) { 7175 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7176 == PackageManager.SIGNATURE_MATCH; 7177 } 7178 if (!match) { 7179 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7180 "Package " + pkg.packageName 7181 + " has no signatures that match those in shared user " 7182 + pkgSetting.sharedUser.name + "; ignoring!"); 7183 } 7184 } 7185 } 7186 7187 /** 7188 * Enforces that only the system UID or root's UID can call a method exposed 7189 * via Binder. 7190 * 7191 * @param message used as message if SecurityException is thrown 7192 * @throws SecurityException if the caller is not system or root 7193 */ 7194 private static final void enforceSystemOrRoot(String message) { 7195 final int uid = Binder.getCallingUid(); 7196 if (uid != Process.SYSTEM_UID && uid != 0) { 7197 throw new SecurityException(message); 7198 } 7199 } 7200 7201 @Override 7202 public void performFstrimIfNeeded() { 7203 enforceSystemOrRoot("Only the system can request fstrim"); 7204 7205 // Before everything else, see whether we need to fstrim. 7206 try { 7207 IMountService ms = PackageHelper.getMountService(); 7208 if (ms != null) { 7209 final boolean isUpgrade = isUpgrade(); 7210 boolean doTrim = isUpgrade; 7211 if (doTrim) { 7212 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7213 } else { 7214 final long interval = android.provider.Settings.Global.getLong( 7215 mContext.getContentResolver(), 7216 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7217 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7218 if (interval > 0) { 7219 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7220 if (timeSinceLast > interval) { 7221 doTrim = true; 7222 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7223 + "; running immediately"); 7224 } 7225 } 7226 } 7227 if (doTrim) { 7228 if (!isFirstBoot()) { 7229 try { 7230 ActivityManagerNative.getDefault().showBootMessage( 7231 mContext.getResources().getString( 7232 R.string.android_upgrading_fstrim), true); 7233 } catch (RemoteException e) { 7234 } 7235 } 7236 ms.runMaintenance(); 7237 } 7238 } else { 7239 Slog.e(TAG, "Mount service unavailable!"); 7240 } 7241 } catch (RemoteException e) { 7242 // Can't happen; MountService is local 7243 } 7244 } 7245 7246 @Override 7247 public void updatePackagesIfNeeded() { 7248 enforceSystemOrRoot("Only the system can request package update"); 7249 7250 // We need to re-extract after an OTA. 7251 boolean causeUpgrade = isUpgrade(); 7252 7253 // First boot or factory reset. 7254 // Note: we also handle devices that are upgrading to N right now as if it is their 7255 // first boot, as they do not have profile data. 7256 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7257 7258 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7259 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7260 7261 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7262 return; 7263 } 7264 7265 List<PackageParser.Package> pkgs; 7266 synchronized (mPackages) { 7267 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7268 } 7269 7270 final long startTime = System.nanoTime(); 7271 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7272 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7273 7274 final int elapsedTimeSeconds = 7275 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7276 7277 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7278 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7279 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7280 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7281 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7282 } 7283 7284 /** 7285 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7286 * containing statistics about the invocation. The array consists of three elements, 7287 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7288 * and {@code numberOfPackagesFailed}. 7289 */ 7290 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7291 String compilerFilter) { 7292 7293 int numberOfPackagesVisited = 0; 7294 int numberOfPackagesOptimized = 0; 7295 int numberOfPackagesSkipped = 0; 7296 int numberOfPackagesFailed = 0; 7297 final int numberOfPackagesToDexopt = pkgs.size(); 7298 7299 for (PackageParser.Package pkg : pkgs) { 7300 numberOfPackagesVisited++; 7301 7302 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7303 if (DEBUG_DEXOPT) { 7304 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7305 } 7306 numberOfPackagesSkipped++; 7307 continue; 7308 } 7309 7310 if (DEBUG_DEXOPT) { 7311 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7312 numberOfPackagesToDexopt + ": " + pkg.packageName); 7313 } 7314 7315 if (showDialog) { 7316 try { 7317 ActivityManagerNative.getDefault().showBootMessage( 7318 mContext.getResources().getString(R.string.android_upgrading_apk, 7319 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7320 } catch (RemoteException e) { 7321 } 7322 } 7323 7324 // checkProfiles is false to avoid merging profiles during boot which 7325 // might interfere with background compilation (b/28612421). 7326 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7327 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7328 // trade-off worth doing to save boot time work. 7329 int dexOptStatus = performDexOptTraced(pkg.packageName, 7330 false /* checkProfiles */, 7331 compilerFilter, 7332 false /* force */); 7333 switch (dexOptStatus) { 7334 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7335 numberOfPackagesOptimized++; 7336 break; 7337 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7338 numberOfPackagesSkipped++; 7339 break; 7340 case PackageDexOptimizer.DEX_OPT_FAILED: 7341 numberOfPackagesFailed++; 7342 break; 7343 default: 7344 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7345 break; 7346 } 7347 } 7348 7349 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7350 numberOfPackagesFailed }; 7351 } 7352 7353 @Override 7354 public void notifyPackageUse(String packageName, int reason) { 7355 synchronized (mPackages) { 7356 PackageParser.Package p = mPackages.get(packageName); 7357 if (p == null) { 7358 return; 7359 } 7360 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7361 } 7362 } 7363 7364 // TODO: this is not used nor needed. Delete it. 7365 @Override 7366 public boolean performDexOptIfNeeded(String packageName) { 7367 int dexOptStatus = performDexOptTraced(packageName, 7368 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7369 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7370 } 7371 7372 @Override 7373 public boolean performDexOpt(String packageName, 7374 boolean checkProfiles, int compileReason, boolean force) { 7375 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7376 getCompilerFilterForReason(compileReason), force); 7377 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7378 } 7379 7380 @Override 7381 public boolean performDexOptMode(String packageName, 7382 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7383 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7384 targetCompilerFilter, force); 7385 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7386 } 7387 7388 private int performDexOptTraced(String packageName, 7389 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7390 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7391 try { 7392 return performDexOptInternal(packageName, checkProfiles, 7393 targetCompilerFilter, force); 7394 } finally { 7395 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7396 } 7397 } 7398 7399 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7400 // if the package can now be considered up to date for the given filter. 7401 private int performDexOptInternal(String packageName, 7402 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7403 PackageParser.Package p; 7404 synchronized (mPackages) { 7405 p = mPackages.get(packageName); 7406 if (p == null) { 7407 // Package could not be found. Report failure. 7408 return PackageDexOptimizer.DEX_OPT_FAILED; 7409 } 7410 mPackageUsage.write(false); 7411 } 7412 long callingId = Binder.clearCallingIdentity(); 7413 try { 7414 synchronized (mInstallLock) { 7415 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7416 targetCompilerFilter, force); 7417 } 7418 } finally { 7419 Binder.restoreCallingIdentity(callingId); 7420 } 7421 } 7422 7423 public ArraySet<String> getOptimizablePackages() { 7424 ArraySet<String> pkgs = new ArraySet<String>(); 7425 synchronized (mPackages) { 7426 for (PackageParser.Package p : mPackages.values()) { 7427 if (PackageDexOptimizer.canOptimizePackage(p)) { 7428 pkgs.add(p.packageName); 7429 } 7430 } 7431 } 7432 return pkgs; 7433 } 7434 7435 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7436 boolean checkProfiles, String targetCompilerFilter, 7437 boolean force) { 7438 // Select the dex optimizer based on the force parameter. 7439 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7440 // allocate an object here. 7441 PackageDexOptimizer pdo = force 7442 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7443 : mPackageDexOptimizer; 7444 7445 // Optimize all dependencies first. Note: we ignore the return value and march on 7446 // on errors. 7447 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7448 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7449 if (!deps.isEmpty()) { 7450 for (PackageParser.Package depPackage : deps) { 7451 // TODO: Analyze and investigate if we (should) profile libraries. 7452 // Currently this will do a full compilation of the library by default. 7453 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7454 false /* checkProfiles */, 7455 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7456 } 7457 } 7458 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7459 targetCompilerFilter); 7460 } 7461 7462 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7463 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7464 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7465 Set<String> collectedNames = new HashSet<>(); 7466 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7467 7468 retValue.remove(p); 7469 7470 return retValue; 7471 } else { 7472 return Collections.emptyList(); 7473 } 7474 } 7475 7476 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7477 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7478 if (!collectedNames.contains(p.packageName)) { 7479 collectedNames.add(p.packageName); 7480 collected.add(p); 7481 7482 if (p.usesLibraries != null) { 7483 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7484 } 7485 if (p.usesOptionalLibraries != null) { 7486 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7487 collectedNames); 7488 } 7489 } 7490 } 7491 7492 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7493 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7494 for (String libName : libs) { 7495 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7496 if (libPkg != null) { 7497 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7498 } 7499 } 7500 } 7501 7502 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7503 synchronized (mPackages) { 7504 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7505 if (lib != null && lib.apk != null) { 7506 return mPackages.get(lib.apk); 7507 } 7508 } 7509 return null; 7510 } 7511 7512 public void shutdown() { 7513 mPackageUsage.write(true); 7514 } 7515 7516 @Override 7517 public void dumpProfiles(String packageName) { 7518 PackageParser.Package pkg; 7519 synchronized (mPackages) { 7520 pkg = mPackages.get(packageName); 7521 if (pkg == null) { 7522 throw new IllegalArgumentException("Unknown package: " + packageName); 7523 } 7524 } 7525 /* Only the shell or the app user should be able to dump profiles. */ 7526 int callingUid = Binder.getCallingUid(); 7527 if (callingUid != Process.SHELL_UID && callingUid != pkg.applicationInfo.uid) { 7528 throw new SecurityException("dumpProfiles"); 7529 } 7530 7531 synchronized (mInstallLock) { 7532 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7533 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7534 try { 7535 final File codeFile = new File(pkg.applicationInfo.getCodePath()); 7536 List<String> allCodePaths = Collections.EMPTY_LIST; 7537 if (codeFile != null && codeFile.exists()) { 7538 try { 7539 final PackageLite codePkg = PackageParser.parsePackageLite(codeFile, 0); 7540 allCodePaths = codePkg.getAllCodePaths(); 7541 } catch (PackageParserException e) { 7542 // Well, we tried. 7543 } 7544 } 7545 String gid = Integer.toString(sharedGid); 7546 String codePaths = TextUtils.join(";", allCodePaths); 7547 mInstaller.dumpProfiles(gid, packageName, codePaths); 7548 } catch (InstallerException e) { 7549 Slog.w(TAG, "Failed to dump profiles", e); 7550 } 7551 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7552 } 7553 } 7554 7555 @Override 7556 public void forceDexOpt(String packageName) { 7557 enforceSystemOrRoot("forceDexOpt"); 7558 7559 PackageParser.Package pkg; 7560 synchronized (mPackages) { 7561 pkg = mPackages.get(packageName); 7562 if (pkg == null) { 7563 throw new IllegalArgumentException("Unknown package: " + packageName); 7564 } 7565 } 7566 7567 synchronized (mInstallLock) { 7568 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7569 7570 // Whoever is calling forceDexOpt wants a fully compiled package. 7571 // Don't use profiles since that may cause compilation to be skipped. 7572 final int res = performDexOptInternalWithDependenciesLI(pkg, 7573 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7574 true /* force */); 7575 7576 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7577 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7578 throw new IllegalStateException("Failed to dexopt: " + res); 7579 } 7580 } 7581 } 7582 7583 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7584 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7585 Slog.w(TAG, "Unable to update from " + oldPkg.name 7586 + " to " + newPkg.packageName 7587 + ": old package not in system partition"); 7588 return false; 7589 } else if (mPackages.get(oldPkg.name) != null) { 7590 Slog.w(TAG, "Unable to update from " + oldPkg.name 7591 + " to " + newPkg.packageName 7592 + ": old package still exists"); 7593 return false; 7594 } 7595 return true; 7596 } 7597 7598 void removeCodePathLI(File codePath) { 7599 if (codePath.isDirectory()) { 7600 try { 7601 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7602 } catch (InstallerException e) { 7603 Slog.w(TAG, "Failed to remove code path", e); 7604 } 7605 } else { 7606 codePath.delete(); 7607 } 7608 } 7609 7610 private int[] resolveUserIds(int userId) { 7611 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7612 } 7613 7614 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7615 if (pkg == null) { 7616 Slog.wtf(TAG, "Package was null!", new Throwable()); 7617 return; 7618 } 7619 clearAppDataLeafLIF(pkg, userId, flags); 7620 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7621 for (int i = 0; i < childCount; i++) { 7622 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7623 } 7624 } 7625 7626 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7627 final PackageSetting ps; 7628 synchronized (mPackages) { 7629 ps = mSettings.mPackages.get(pkg.packageName); 7630 } 7631 for (int realUserId : resolveUserIds(userId)) { 7632 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7633 try { 7634 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7635 ceDataInode); 7636 } catch (InstallerException e) { 7637 Slog.w(TAG, String.valueOf(e)); 7638 } 7639 } 7640 } 7641 7642 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7643 if (pkg == null) { 7644 Slog.wtf(TAG, "Package was null!", new Throwable()); 7645 return; 7646 } 7647 destroyAppDataLeafLIF(pkg, userId, flags); 7648 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7649 for (int i = 0; i < childCount; i++) { 7650 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7651 } 7652 } 7653 7654 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7655 final PackageSetting ps; 7656 synchronized (mPackages) { 7657 ps = mSettings.mPackages.get(pkg.packageName); 7658 } 7659 for (int realUserId : resolveUserIds(userId)) { 7660 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7661 try { 7662 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7663 ceDataInode); 7664 } catch (InstallerException e) { 7665 Slog.w(TAG, String.valueOf(e)); 7666 } 7667 } 7668 } 7669 7670 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7671 if (pkg == null) { 7672 Slog.wtf(TAG, "Package was null!", new Throwable()); 7673 return; 7674 } 7675 destroyAppProfilesLeafLIF(pkg); 7676 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7677 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7678 for (int i = 0; i < childCount; i++) { 7679 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7680 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7681 true /* removeBaseMarker */); 7682 } 7683 } 7684 7685 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7686 boolean removeBaseMarker) { 7687 if (pkg.isForwardLocked()) { 7688 return; 7689 } 7690 7691 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7692 try { 7693 path = PackageManagerServiceUtils.realpath(new File(path)); 7694 } catch (IOException e) { 7695 // TODO: Should we return early here ? 7696 Slog.w(TAG, "Failed to get canonical path", e); 7697 continue; 7698 } 7699 7700 final String useMarker = path.replace('/', '@'); 7701 for (int realUserId : resolveUserIds(userId)) { 7702 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7703 if (removeBaseMarker) { 7704 File foreignUseMark = new File(profileDir, useMarker); 7705 if (foreignUseMark.exists()) { 7706 if (!foreignUseMark.delete()) { 7707 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7708 + pkg.packageName); 7709 } 7710 } 7711 } 7712 7713 File[] markers = profileDir.listFiles(); 7714 if (markers != null) { 7715 final String searchString = "@" + pkg.packageName + "@"; 7716 // We also delete all markers that contain the package name we're 7717 // uninstalling. These are associated with secondary dex-files belonging 7718 // to the package. Reconstructing the path of these dex files is messy 7719 // in general. 7720 for (File marker : markers) { 7721 if (marker.getName().indexOf(searchString) > 0) { 7722 if (!marker.delete()) { 7723 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7724 + pkg.packageName); 7725 } 7726 } 7727 } 7728 } 7729 } 7730 } 7731 } 7732 7733 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7734 try { 7735 mInstaller.destroyAppProfiles(pkg.packageName); 7736 } catch (InstallerException e) { 7737 Slog.w(TAG, String.valueOf(e)); 7738 } 7739 } 7740 7741 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7742 if (pkg == null) { 7743 Slog.wtf(TAG, "Package was null!", new Throwable()); 7744 return; 7745 } 7746 clearAppProfilesLeafLIF(pkg); 7747 // We don't remove the base foreign use marker when clearing profiles because 7748 // we will rename it when the app is updated. Unlike the actual profile contents, 7749 // the foreign use marker is good across installs. 7750 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7751 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7752 for (int i = 0; i < childCount; i++) { 7753 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7754 } 7755 } 7756 7757 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7758 try { 7759 mInstaller.clearAppProfiles(pkg.packageName); 7760 } catch (InstallerException e) { 7761 Slog.w(TAG, String.valueOf(e)); 7762 } 7763 } 7764 7765 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7766 long lastUpdateTime) { 7767 // Set parent install/update time 7768 PackageSetting ps = (PackageSetting) pkg.mExtras; 7769 if (ps != null) { 7770 ps.firstInstallTime = firstInstallTime; 7771 ps.lastUpdateTime = lastUpdateTime; 7772 } 7773 // Set children install/update time 7774 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7775 for (int i = 0; i < childCount; i++) { 7776 PackageParser.Package childPkg = pkg.childPackages.get(i); 7777 ps = (PackageSetting) childPkg.mExtras; 7778 if (ps != null) { 7779 ps.firstInstallTime = firstInstallTime; 7780 ps.lastUpdateTime = lastUpdateTime; 7781 } 7782 } 7783 } 7784 7785 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7786 PackageParser.Package changingLib) { 7787 if (file.path != null) { 7788 usesLibraryFiles.add(file.path); 7789 return; 7790 } 7791 PackageParser.Package p = mPackages.get(file.apk); 7792 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7793 // If we are doing this while in the middle of updating a library apk, 7794 // then we need to make sure to use that new apk for determining the 7795 // dependencies here. (We haven't yet finished committing the new apk 7796 // to the package manager state.) 7797 if (p == null || p.packageName.equals(changingLib.packageName)) { 7798 p = changingLib; 7799 } 7800 } 7801 if (p != null) { 7802 usesLibraryFiles.addAll(p.getAllCodePaths()); 7803 } 7804 } 7805 7806 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7807 PackageParser.Package changingLib) throws PackageManagerException { 7808 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7809 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7810 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7811 for (int i=0; i<N; i++) { 7812 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7813 if (file == null) { 7814 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7815 "Package " + pkg.packageName + " requires unavailable shared library " 7816 + pkg.usesLibraries.get(i) + "; failing!"); 7817 } 7818 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7819 } 7820 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7821 for (int i=0; i<N; i++) { 7822 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7823 if (file == null) { 7824 Slog.w(TAG, "Package " + pkg.packageName 7825 + " desires unavailable shared library " 7826 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7827 } else { 7828 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7829 } 7830 } 7831 N = usesLibraryFiles.size(); 7832 if (N > 0) { 7833 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7834 } else { 7835 pkg.usesLibraryFiles = null; 7836 } 7837 } 7838 } 7839 7840 private static boolean hasString(List<String> list, List<String> which) { 7841 if (list == null) { 7842 return false; 7843 } 7844 for (int i=list.size()-1; i>=0; i--) { 7845 for (int j=which.size()-1; j>=0; j--) { 7846 if (which.get(j).equals(list.get(i))) { 7847 return true; 7848 } 7849 } 7850 } 7851 return false; 7852 } 7853 7854 private void updateAllSharedLibrariesLPw() { 7855 for (PackageParser.Package pkg : mPackages.values()) { 7856 try { 7857 updateSharedLibrariesLPw(pkg, null); 7858 } catch (PackageManagerException e) { 7859 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7860 } 7861 } 7862 } 7863 7864 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7865 PackageParser.Package changingPkg) { 7866 ArrayList<PackageParser.Package> res = null; 7867 for (PackageParser.Package pkg : mPackages.values()) { 7868 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7869 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7870 if (res == null) { 7871 res = new ArrayList<PackageParser.Package>(); 7872 } 7873 res.add(pkg); 7874 try { 7875 updateSharedLibrariesLPw(pkg, changingPkg); 7876 } catch (PackageManagerException e) { 7877 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7878 } 7879 } 7880 } 7881 return res; 7882 } 7883 7884 /** 7885 * Derive the value of the {@code cpuAbiOverride} based on the provided 7886 * value and an optional stored value from the package settings. 7887 */ 7888 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7889 String cpuAbiOverride = null; 7890 7891 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7892 cpuAbiOverride = null; 7893 } else if (abiOverride != null) { 7894 cpuAbiOverride = abiOverride; 7895 } else if (settings != null) { 7896 cpuAbiOverride = settings.cpuAbiOverrideString; 7897 } 7898 7899 return cpuAbiOverride; 7900 } 7901 7902 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7903 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7904 throws PackageManagerException { 7905 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7906 // If the package has children and this is the first dive in the function 7907 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7908 // whether all packages (parent and children) would be successfully scanned 7909 // before the actual scan since scanning mutates internal state and we want 7910 // to atomically install the package and its children. 7911 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7912 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7913 scanFlags |= SCAN_CHECK_ONLY; 7914 } 7915 } else { 7916 scanFlags &= ~SCAN_CHECK_ONLY; 7917 } 7918 7919 final PackageParser.Package scannedPkg; 7920 try { 7921 // Scan the parent 7922 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7923 // Scan the children 7924 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7925 for (int i = 0; i < childCount; i++) { 7926 PackageParser.Package childPkg = pkg.childPackages.get(i); 7927 scanPackageLI(childPkg, policyFlags, 7928 scanFlags, currentTime, user); 7929 } 7930 } finally { 7931 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7932 } 7933 7934 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7935 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7936 } 7937 7938 return scannedPkg; 7939 } 7940 7941 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7942 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7943 boolean success = false; 7944 try { 7945 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7946 currentTime, user); 7947 success = true; 7948 return res; 7949 } finally { 7950 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7951 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7952 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7953 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7954 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7955 } 7956 } 7957 } 7958 7959 /** 7960 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7961 */ 7962 private static boolean apkHasCode(String fileName) { 7963 StrictJarFile jarFile = null; 7964 try { 7965 jarFile = new StrictJarFile(fileName, 7966 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7967 return jarFile.findEntry("classes.dex") != null; 7968 } catch (IOException ignore) { 7969 } finally { 7970 try { 7971 jarFile.close(); 7972 } catch (IOException ignore) {} 7973 } 7974 return false; 7975 } 7976 7977 /** 7978 * Enforces code policy for the package. This ensures that if an APK has 7979 * declared hasCode="true" in its manifest that the APK actually contains 7980 * code. 7981 * 7982 * @throws PackageManagerException If bytecode could not be found when it should exist 7983 */ 7984 private static void enforceCodePolicy(PackageParser.Package pkg) 7985 throws PackageManagerException { 7986 final boolean shouldHaveCode = 7987 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7988 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7989 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7990 "Package " + pkg.baseCodePath + " code is missing"); 7991 } 7992 7993 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7994 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7995 final boolean splitShouldHaveCode = 7996 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7997 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7998 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7999 "Package " + pkg.splitCodePaths[i] + " code is missing"); 8000 } 8001 } 8002 } 8003 } 8004 8005 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8006 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8007 throws PackageManagerException { 8008 final File scanFile = new File(pkg.codePath); 8009 if (pkg.applicationInfo.getCodePath() == null || 8010 pkg.applicationInfo.getResourcePath() == null) { 8011 // Bail out. The resource and code paths haven't been set. 8012 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8013 "Code and resource paths haven't been set correctly"); 8014 } 8015 8016 // Apply policy 8017 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8018 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8019 if (pkg.applicationInfo.isDirectBootAware()) { 8020 // we're direct boot aware; set for all components 8021 for (PackageParser.Service s : pkg.services) { 8022 s.info.encryptionAware = s.info.directBootAware = true; 8023 } 8024 for (PackageParser.Provider p : pkg.providers) { 8025 p.info.encryptionAware = p.info.directBootAware = true; 8026 } 8027 for (PackageParser.Activity a : pkg.activities) { 8028 a.info.encryptionAware = a.info.directBootAware = true; 8029 } 8030 for (PackageParser.Activity r : pkg.receivers) { 8031 r.info.encryptionAware = r.info.directBootAware = true; 8032 } 8033 } 8034 } else { 8035 // Only allow system apps to be flagged as core apps. 8036 pkg.coreApp = false; 8037 // clear flags not applicable to regular apps 8038 pkg.applicationInfo.privateFlags &= 8039 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8040 pkg.applicationInfo.privateFlags &= 8041 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8042 } 8043 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8044 8045 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8046 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8047 } 8048 8049 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8050 enforceCodePolicy(pkg); 8051 } 8052 8053 if (mCustomResolverComponentName != null && 8054 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8055 setUpCustomResolverActivity(pkg); 8056 } 8057 8058 if (pkg.packageName.equals("android")) { 8059 synchronized (mPackages) { 8060 if (mAndroidApplication != null) { 8061 Slog.w(TAG, "*************************************************"); 8062 Slog.w(TAG, "Core android package being redefined. Skipping."); 8063 Slog.w(TAG, " file=" + scanFile); 8064 Slog.w(TAG, "*************************************************"); 8065 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8066 "Core android package being redefined. Skipping."); 8067 } 8068 8069 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8070 // Set up information for our fall-back user intent resolution activity. 8071 mPlatformPackage = pkg; 8072 pkg.mVersionCode = mSdkVersion; 8073 mAndroidApplication = pkg.applicationInfo; 8074 8075 if (!mResolverReplaced) { 8076 mResolveActivity.applicationInfo = mAndroidApplication; 8077 mResolveActivity.name = ResolverActivity.class.getName(); 8078 mResolveActivity.packageName = mAndroidApplication.packageName; 8079 mResolveActivity.processName = "system:ui"; 8080 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8081 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8082 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8083 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8084 mResolveActivity.exported = true; 8085 mResolveActivity.enabled = true; 8086 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8087 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8088 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8089 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8090 | ActivityInfo.CONFIG_ORIENTATION 8091 | ActivityInfo.CONFIG_KEYBOARD 8092 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8093 mResolveInfo.activityInfo = mResolveActivity; 8094 mResolveInfo.priority = 0; 8095 mResolveInfo.preferredOrder = 0; 8096 mResolveInfo.match = 0; 8097 mResolveComponentName = new ComponentName( 8098 mAndroidApplication.packageName, mResolveActivity.name); 8099 } 8100 } 8101 } 8102 } 8103 8104 if (DEBUG_PACKAGE_SCANNING) { 8105 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8106 Log.d(TAG, "Scanning package " + pkg.packageName); 8107 } 8108 8109 synchronized (mPackages) { 8110 if (mPackages.containsKey(pkg.packageName) 8111 || mSharedLibraries.containsKey(pkg.packageName)) { 8112 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8113 "Application package " + pkg.packageName 8114 + " already installed. Skipping duplicate."); 8115 } 8116 8117 // If we're only installing presumed-existing packages, require that the 8118 // scanned APK is both already known and at the path previously established 8119 // for it. Previously unknown packages we pick up normally, but if we have an 8120 // a priori expectation about this package's install presence, enforce it. 8121 // With a singular exception for new system packages. When an OTA contains 8122 // a new system package, we allow the codepath to change from a system location 8123 // to the user-installed location. If we don't allow this change, any newer, 8124 // user-installed version of the application will be ignored. 8125 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8126 if (mExpectingBetter.containsKey(pkg.packageName)) { 8127 logCriticalInfo(Log.WARN, 8128 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8129 } else { 8130 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8131 if (known != null) { 8132 if (DEBUG_PACKAGE_SCANNING) { 8133 Log.d(TAG, "Examining " + pkg.codePath 8134 + " and requiring known paths " + known.codePathString 8135 + " & " + known.resourcePathString); 8136 } 8137 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8138 || !pkg.applicationInfo.getResourcePath().equals( 8139 known.resourcePathString)) { 8140 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8141 "Application package " + pkg.packageName 8142 + " found at " + pkg.applicationInfo.getCodePath() 8143 + " but expected at " + known.codePathString 8144 + "; ignoring."); 8145 } 8146 } 8147 } 8148 } 8149 } 8150 8151 // Initialize package source and resource directories 8152 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8153 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8154 8155 SharedUserSetting suid = null; 8156 PackageSetting pkgSetting = null; 8157 8158 if (!isSystemApp(pkg)) { 8159 // Only system apps can use these features. 8160 pkg.mOriginalPackages = null; 8161 pkg.mRealPackage = null; 8162 pkg.mAdoptPermissions = null; 8163 } 8164 8165 // Getting the package setting may have a side-effect, so if we 8166 // are only checking if scan would succeed, stash a copy of the 8167 // old setting to restore at the end. 8168 PackageSetting nonMutatedPs = null; 8169 8170 // writer 8171 synchronized (mPackages) { 8172 if (pkg.mSharedUserId != null) { 8173 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8174 if (suid == null) { 8175 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8176 "Creating application package " + pkg.packageName 8177 + " for shared user failed"); 8178 } 8179 if (DEBUG_PACKAGE_SCANNING) { 8180 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8181 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8182 + "): packages=" + suid.packages); 8183 } 8184 } 8185 8186 // Check if we are renaming from an original package name. 8187 PackageSetting origPackage = null; 8188 String realName = null; 8189 if (pkg.mOriginalPackages != null) { 8190 // This package may need to be renamed to a previously 8191 // installed name. Let's check on that... 8192 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8193 if (pkg.mOriginalPackages.contains(renamed)) { 8194 // This package had originally been installed as the 8195 // original name, and we have already taken care of 8196 // transitioning to the new one. Just update the new 8197 // one to continue using the old name. 8198 realName = pkg.mRealPackage; 8199 if (!pkg.packageName.equals(renamed)) { 8200 // Callers into this function may have already taken 8201 // care of renaming the package; only do it here if 8202 // it is not already done. 8203 pkg.setPackageName(renamed); 8204 } 8205 8206 } else { 8207 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8208 if ((origPackage = mSettings.peekPackageLPr( 8209 pkg.mOriginalPackages.get(i))) != null) { 8210 // We do have the package already installed under its 8211 // original name... should we use it? 8212 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8213 // New package is not compatible with original. 8214 origPackage = null; 8215 continue; 8216 } else if (origPackage.sharedUser != null) { 8217 // Make sure uid is compatible between packages. 8218 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8219 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8220 + " to " + pkg.packageName + ": old uid " 8221 + origPackage.sharedUser.name 8222 + " differs from " + pkg.mSharedUserId); 8223 origPackage = null; 8224 continue; 8225 } 8226 // TODO: Add case when shared user id is added [b/28144775] 8227 } else { 8228 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8229 + pkg.packageName + " to old name " + origPackage.name); 8230 } 8231 break; 8232 } 8233 } 8234 } 8235 } 8236 8237 if (mTransferedPackages.contains(pkg.packageName)) { 8238 Slog.w(TAG, "Package " + pkg.packageName 8239 + " was transferred to another, but its .apk remains"); 8240 } 8241 8242 // See comments in nonMutatedPs declaration 8243 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8244 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8245 if (foundPs != null) { 8246 nonMutatedPs = new PackageSetting(foundPs); 8247 } 8248 } 8249 8250 // Just create the setting, don't add it yet. For already existing packages 8251 // the PkgSetting exists already and doesn't have to be created. 8252 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8253 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8254 pkg.applicationInfo.primaryCpuAbi, 8255 pkg.applicationInfo.secondaryCpuAbi, 8256 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8257 user, false); 8258 if (pkgSetting == null) { 8259 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8260 "Creating application package " + pkg.packageName + " failed"); 8261 } 8262 8263 if (pkgSetting.origPackage != null) { 8264 // If we are first transitioning from an original package, 8265 // fix up the new package's name now. We need to do this after 8266 // looking up the package under its new name, so getPackageLP 8267 // can take care of fiddling things correctly. 8268 pkg.setPackageName(origPackage.name); 8269 8270 // File a report about this. 8271 String msg = "New package " + pkgSetting.realName 8272 + " renamed to replace old package " + pkgSetting.name; 8273 reportSettingsProblem(Log.WARN, msg); 8274 8275 // Make a note of it. 8276 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8277 mTransferedPackages.add(origPackage.name); 8278 } 8279 8280 // No longer need to retain this. 8281 pkgSetting.origPackage = null; 8282 } 8283 8284 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8285 // Make a note of it. 8286 mTransferedPackages.add(pkg.packageName); 8287 } 8288 8289 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8290 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8291 } 8292 8293 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8294 // Check all shared libraries and map to their actual file path. 8295 // We only do this here for apps not on a system dir, because those 8296 // are the only ones that can fail an install due to this. We 8297 // will take care of the system apps by updating all of their 8298 // library paths after the scan is done. 8299 updateSharedLibrariesLPw(pkg, null); 8300 } 8301 8302 if (mFoundPolicyFile) { 8303 SELinuxMMAC.assignSeinfoValue(pkg); 8304 } 8305 8306 pkg.applicationInfo.uid = pkgSetting.appId; 8307 pkg.mExtras = pkgSetting; 8308 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8309 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8310 // We just determined the app is signed correctly, so bring 8311 // over the latest parsed certs. 8312 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8313 } else { 8314 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8315 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8316 "Package " + pkg.packageName + " upgrade keys do not match the " 8317 + "previously installed version"); 8318 } else { 8319 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8320 String msg = "System package " + pkg.packageName 8321 + " signature changed; retaining data."; 8322 reportSettingsProblem(Log.WARN, msg); 8323 } 8324 } 8325 } else { 8326 try { 8327 verifySignaturesLP(pkgSetting, pkg); 8328 // We just determined the app is signed correctly, so bring 8329 // over the latest parsed certs. 8330 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8331 } catch (PackageManagerException e) { 8332 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8333 throw e; 8334 } 8335 // The signature has changed, but this package is in the system 8336 // image... let's recover! 8337 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8338 // However... if this package is part of a shared user, but it 8339 // doesn't match the signature of the shared user, let's fail. 8340 // What this means is that you can't change the signatures 8341 // associated with an overall shared user, which doesn't seem all 8342 // that unreasonable. 8343 if (pkgSetting.sharedUser != null) { 8344 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8345 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8346 throw new PackageManagerException( 8347 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8348 "Signature mismatch for shared user: " 8349 + pkgSetting.sharedUser); 8350 } 8351 } 8352 // File a report about this. 8353 String msg = "System package " + pkg.packageName 8354 + " signature changed; retaining data."; 8355 reportSettingsProblem(Log.WARN, msg); 8356 } 8357 } 8358 // Verify that this new package doesn't have any content providers 8359 // that conflict with existing packages. Only do this if the 8360 // package isn't already installed, since we don't want to break 8361 // things that are installed. 8362 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8363 final int N = pkg.providers.size(); 8364 int i; 8365 for (i=0; i<N; i++) { 8366 PackageParser.Provider p = pkg.providers.get(i); 8367 if (p.info.authority != null) { 8368 String names[] = p.info.authority.split(";"); 8369 for (int j = 0; j < names.length; j++) { 8370 if (mProvidersByAuthority.containsKey(names[j])) { 8371 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8372 final String otherPackageName = 8373 ((other != null && other.getComponentName() != null) ? 8374 other.getComponentName().getPackageName() : "?"); 8375 throw new PackageManagerException( 8376 INSTALL_FAILED_CONFLICTING_PROVIDER, 8377 "Can't install because provider name " + names[j] 8378 + " (in package " + pkg.applicationInfo.packageName 8379 + ") is already used by " + otherPackageName); 8380 } 8381 } 8382 } 8383 } 8384 } 8385 8386 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8387 // This package wants to adopt ownership of permissions from 8388 // another package. 8389 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8390 final String origName = pkg.mAdoptPermissions.get(i); 8391 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8392 if (orig != null) { 8393 if (verifyPackageUpdateLPr(orig, pkg)) { 8394 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8395 + pkg.packageName); 8396 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8397 } 8398 } 8399 } 8400 } 8401 } 8402 8403 final String pkgName = pkg.packageName; 8404 8405 final long scanFileTime = scanFile.lastModified(); 8406 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8407 pkg.applicationInfo.processName = fixProcessName( 8408 pkg.applicationInfo.packageName, 8409 pkg.applicationInfo.processName, 8410 pkg.applicationInfo.uid); 8411 8412 if (pkg != mPlatformPackage) { 8413 // Get all of our default paths setup 8414 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8415 } 8416 8417 final String path = scanFile.getPath(); 8418 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8419 8420 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8421 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8422 8423 // Some system apps still use directory structure for native libraries 8424 // in which case we might end up not detecting abi solely based on apk 8425 // structure. Try to detect abi based on directory structure. 8426 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8427 pkg.applicationInfo.primaryCpuAbi == null) { 8428 setBundledAppAbisAndRoots(pkg, pkgSetting); 8429 setNativeLibraryPaths(pkg); 8430 } 8431 8432 } else { 8433 if ((scanFlags & SCAN_MOVE) != 0) { 8434 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8435 // but we already have this packages package info in the PackageSetting. We just 8436 // use that and derive the native library path based on the new codepath. 8437 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8438 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8439 } 8440 8441 // Set native library paths again. For moves, the path will be updated based on the 8442 // ABIs we've determined above. For non-moves, the path will be updated based on the 8443 // ABIs we determined during compilation, but the path will depend on the final 8444 // package path (after the rename away from the stage path). 8445 setNativeLibraryPaths(pkg); 8446 } 8447 8448 // This is a special case for the "system" package, where the ABI is 8449 // dictated by the zygote configuration (and init.rc). We should keep track 8450 // of this ABI so that we can deal with "normal" applications that run under 8451 // the same UID correctly. 8452 if (mPlatformPackage == pkg) { 8453 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8454 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8455 } 8456 8457 // If there's a mismatch between the abi-override in the package setting 8458 // and the abiOverride specified for the install. Warn about this because we 8459 // would've already compiled the app without taking the package setting into 8460 // account. 8461 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8462 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8463 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8464 " for package " + pkg.packageName); 8465 } 8466 } 8467 8468 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8469 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8470 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8471 8472 // Copy the derived override back to the parsed package, so that we can 8473 // update the package settings accordingly. 8474 pkg.cpuAbiOverride = cpuAbiOverride; 8475 8476 if (DEBUG_ABI_SELECTION) { 8477 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8478 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8479 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8480 } 8481 8482 // Push the derived path down into PackageSettings so we know what to 8483 // clean up at uninstall time. 8484 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8485 8486 if (DEBUG_ABI_SELECTION) { 8487 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8488 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8489 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8490 } 8491 8492 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8493 // We don't do this here during boot because we can do it all 8494 // at once after scanning all existing packages. 8495 // 8496 // We also do this *before* we perform dexopt on this package, so that 8497 // we can avoid redundant dexopts, and also to make sure we've got the 8498 // code and package path correct. 8499 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8500 pkg, true /* boot complete */); 8501 } 8502 8503 if (mFactoryTest && pkg.requestedPermissions.contains( 8504 android.Manifest.permission.FACTORY_TEST)) { 8505 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8506 } 8507 8508 ArrayList<PackageParser.Package> clientLibPkgs = null; 8509 8510 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8511 if (nonMutatedPs != null) { 8512 synchronized (mPackages) { 8513 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8514 } 8515 } 8516 return pkg; 8517 } 8518 8519 // Only privileged apps and updated privileged apps can add child packages. 8520 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8521 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8522 throw new PackageManagerException("Only privileged apps and updated " 8523 + "privileged apps can add child packages. Ignoring package " 8524 + pkg.packageName); 8525 } 8526 final int childCount = pkg.childPackages.size(); 8527 for (int i = 0; i < childCount; i++) { 8528 PackageParser.Package childPkg = pkg.childPackages.get(i); 8529 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8530 childPkg.packageName)) { 8531 throw new PackageManagerException("Cannot override a child package of " 8532 + "another disabled system app. Ignoring package " + pkg.packageName); 8533 } 8534 } 8535 } 8536 8537 // writer 8538 synchronized (mPackages) { 8539 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8540 // Only system apps can add new shared libraries. 8541 if (pkg.libraryNames != null) { 8542 for (int i=0; i<pkg.libraryNames.size(); i++) { 8543 String name = pkg.libraryNames.get(i); 8544 boolean allowed = false; 8545 if (pkg.isUpdatedSystemApp()) { 8546 // New library entries can only be added through the 8547 // system image. This is important to get rid of a lot 8548 // of nasty edge cases: for example if we allowed a non- 8549 // system update of the app to add a library, then uninstalling 8550 // the update would make the library go away, and assumptions 8551 // we made such as through app install filtering would now 8552 // have allowed apps on the device which aren't compatible 8553 // with it. Better to just have the restriction here, be 8554 // conservative, and create many fewer cases that can negatively 8555 // impact the user experience. 8556 final PackageSetting sysPs = mSettings 8557 .getDisabledSystemPkgLPr(pkg.packageName); 8558 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8559 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8560 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8561 allowed = true; 8562 break; 8563 } 8564 } 8565 } 8566 } else { 8567 allowed = true; 8568 } 8569 if (allowed) { 8570 if (!mSharedLibraries.containsKey(name)) { 8571 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8572 } else if (!name.equals(pkg.packageName)) { 8573 Slog.w(TAG, "Package " + pkg.packageName + " library " 8574 + name + " already exists; skipping"); 8575 } 8576 } else { 8577 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8578 + name + " that is not declared on system image; skipping"); 8579 } 8580 } 8581 if ((scanFlags & SCAN_BOOTING) == 0) { 8582 // If we are not booting, we need to update any applications 8583 // that are clients of our shared library. If we are booting, 8584 // this will all be done once the scan is complete. 8585 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8586 } 8587 } 8588 } 8589 } 8590 8591 if ((scanFlags & SCAN_BOOTING) != 0) { 8592 // No apps can run during boot scan, so they don't need to be frozen 8593 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8594 // Caller asked to not kill app, so it's probably not frozen 8595 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8596 // Caller asked us to ignore frozen check for some reason; they 8597 // probably didn't know the package name 8598 } else { 8599 // We're doing major surgery on this package, so it better be frozen 8600 // right now to keep it from launching 8601 checkPackageFrozen(pkgName); 8602 } 8603 8604 // Also need to kill any apps that are dependent on the library. 8605 if (clientLibPkgs != null) { 8606 for (int i=0; i<clientLibPkgs.size(); i++) { 8607 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8608 killApplication(clientPkg.applicationInfo.packageName, 8609 clientPkg.applicationInfo.uid, "update lib"); 8610 } 8611 } 8612 8613 // Make sure we're not adding any bogus keyset info 8614 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8615 ksms.assertScannedPackageValid(pkg); 8616 8617 // writer 8618 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8619 8620 boolean createIdmapFailed = false; 8621 synchronized (mPackages) { 8622 // We don't expect installation to fail beyond this point 8623 8624 if (pkgSetting.pkg != null) { 8625 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, user); 8626 } 8627 8628 // Add the new setting to mSettings 8629 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8630 // Add the new setting to mPackages 8631 mPackages.put(pkg.applicationInfo.packageName, pkg); 8632 // Make sure we don't accidentally delete its data. 8633 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8634 while (iter.hasNext()) { 8635 PackageCleanItem item = iter.next(); 8636 if (pkgName.equals(item.packageName)) { 8637 iter.remove(); 8638 } 8639 } 8640 8641 // Take care of first install / last update times. 8642 if (currentTime != 0) { 8643 if (pkgSetting.firstInstallTime == 0) { 8644 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8645 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8646 pkgSetting.lastUpdateTime = currentTime; 8647 } 8648 } else if (pkgSetting.firstInstallTime == 0) { 8649 // We need *something*. Take time time stamp of the file. 8650 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8651 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8652 if (scanFileTime != pkgSetting.timeStamp) { 8653 // A package on the system image has changed; consider this 8654 // to be an update. 8655 pkgSetting.lastUpdateTime = scanFileTime; 8656 } 8657 } 8658 8659 // Add the package's KeySets to the global KeySetManagerService 8660 ksms.addScannedPackageLPw(pkg); 8661 8662 int N = pkg.providers.size(); 8663 StringBuilder r = null; 8664 int i; 8665 for (i=0; i<N; i++) { 8666 PackageParser.Provider p = pkg.providers.get(i); 8667 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8668 p.info.processName, pkg.applicationInfo.uid); 8669 mProviders.addProvider(p); 8670 p.syncable = p.info.isSyncable; 8671 if (p.info.authority != null) { 8672 String names[] = p.info.authority.split(";"); 8673 p.info.authority = null; 8674 for (int j = 0; j < names.length; j++) { 8675 if (j == 1 && p.syncable) { 8676 // We only want the first authority for a provider to possibly be 8677 // syncable, so if we already added this provider using a different 8678 // authority clear the syncable flag. We copy the provider before 8679 // changing it because the mProviders object contains a reference 8680 // to a provider that we don't want to change. 8681 // Only do this for the second authority since the resulting provider 8682 // object can be the same for all future authorities for this provider. 8683 p = new PackageParser.Provider(p); 8684 p.syncable = false; 8685 } 8686 if (!mProvidersByAuthority.containsKey(names[j])) { 8687 mProvidersByAuthority.put(names[j], p); 8688 if (p.info.authority == null) { 8689 p.info.authority = names[j]; 8690 } else { 8691 p.info.authority = p.info.authority + ";" + names[j]; 8692 } 8693 if (DEBUG_PACKAGE_SCANNING) { 8694 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8695 Log.d(TAG, "Registered content provider: " + names[j] 8696 + ", className = " + p.info.name + ", isSyncable = " 8697 + p.info.isSyncable); 8698 } 8699 } else { 8700 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8701 Slog.w(TAG, "Skipping provider name " + names[j] + 8702 " (in package " + pkg.applicationInfo.packageName + 8703 "): name already used by " 8704 + ((other != null && other.getComponentName() != null) 8705 ? other.getComponentName().getPackageName() : "?")); 8706 } 8707 } 8708 } 8709 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8710 if (r == null) { 8711 r = new StringBuilder(256); 8712 } else { 8713 r.append(' '); 8714 } 8715 r.append(p.info.name); 8716 } 8717 } 8718 if (r != null) { 8719 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8720 } 8721 8722 N = pkg.services.size(); 8723 r = null; 8724 for (i=0; i<N; i++) { 8725 PackageParser.Service s = pkg.services.get(i); 8726 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8727 s.info.processName, pkg.applicationInfo.uid); 8728 mServices.addService(s); 8729 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8730 if (r == null) { 8731 r = new StringBuilder(256); 8732 } else { 8733 r.append(' '); 8734 } 8735 r.append(s.info.name); 8736 } 8737 } 8738 if (r != null) { 8739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8740 } 8741 8742 N = pkg.receivers.size(); 8743 r = null; 8744 for (i=0; i<N; i++) { 8745 PackageParser.Activity a = pkg.receivers.get(i); 8746 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8747 a.info.processName, pkg.applicationInfo.uid); 8748 mReceivers.addActivity(a, "receiver"); 8749 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8750 if (r == null) { 8751 r = new StringBuilder(256); 8752 } else { 8753 r.append(' '); 8754 } 8755 r.append(a.info.name); 8756 } 8757 } 8758 if (r != null) { 8759 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8760 } 8761 8762 N = pkg.activities.size(); 8763 r = null; 8764 for (i=0; i<N; i++) { 8765 PackageParser.Activity a = pkg.activities.get(i); 8766 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8767 a.info.processName, pkg.applicationInfo.uid); 8768 mActivities.addActivity(a, "activity"); 8769 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8770 if (r == null) { 8771 r = new StringBuilder(256); 8772 } else { 8773 r.append(' '); 8774 } 8775 r.append(a.info.name); 8776 } 8777 } 8778 if (r != null) { 8779 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8780 } 8781 8782 N = pkg.permissionGroups.size(); 8783 r = null; 8784 for (i=0; i<N; i++) { 8785 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8786 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8787 if (cur == null) { 8788 mPermissionGroups.put(pg.info.name, pg); 8789 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8790 if (r == null) { 8791 r = new StringBuilder(256); 8792 } else { 8793 r.append(' '); 8794 } 8795 r.append(pg.info.name); 8796 } 8797 } else { 8798 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8799 + pg.info.packageName + " ignored: original from " 8800 + cur.info.packageName); 8801 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8802 if (r == null) { 8803 r = new StringBuilder(256); 8804 } else { 8805 r.append(' '); 8806 } 8807 r.append("DUP:"); 8808 r.append(pg.info.name); 8809 } 8810 } 8811 } 8812 if (r != null) { 8813 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8814 } 8815 8816 N = pkg.permissions.size(); 8817 r = null; 8818 for (i=0; i<N; i++) { 8819 PackageParser.Permission p = pkg.permissions.get(i); 8820 8821 // Assume by default that we did not install this permission into the system. 8822 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8823 8824 // Now that permission groups have a special meaning, we ignore permission 8825 // groups for legacy apps to prevent unexpected behavior. In particular, 8826 // permissions for one app being granted to someone just becase they happen 8827 // to be in a group defined by another app (before this had no implications). 8828 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8829 p.group = mPermissionGroups.get(p.info.group); 8830 // Warn for a permission in an unknown group. 8831 if (p.info.group != null && p.group == null) { 8832 Slog.w(TAG, "Permission " + p.info.name + " from package " 8833 + p.info.packageName + " in an unknown group " + p.info.group); 8834 } 8835 } 8836 8837 ArrayMap<String, BasePermission> permissionMap = 8838 p.tree ? mSettings.mPermissionTrees 8839 : mSettings.mPermissions; 8840 BasePermission bp = permissionMap.get(p.info.name); 8841 8842 // Allow system apps to redefine non-system permissions 8843 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8844 final boolean currentOwnerIsSystem = (bp.perm != null 8845 && isSystemApp(bp.perm.owner)); 8846 if (isSystemApp(p.owner)) { 8847 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8848 // It's a built-in permission and no owner, take ownership now 8849 bp.packageSetting = pkgSetting; 8850 bp.perm = p; 8851 bp.uid = pkg.applicationInfo.uid; 8852 bp.sourcePackage = p.info.packageName; 8853 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8854 } else if (!currentOwnerIsSystem) { 8855 String msg = "New decl " + p.owner + " of permission " 8856 + p.info.name + " is system; overriding " + bp.sourcePackage; 8857 reportSettingsProblem(Log.WARN, msg); 8858 bp = null; 8859 } 8860 } 8861 } 8862 8863 if (bp == null) { 8864 bp = new BasePermission(p.info.name, p.info.packageName, 8865 BasePermission.TYPE_NORMAL); 8866 permissionMap.put(p.info.name, bp); 8867 } 8868 8869 if (bp.perm == null) { 8870 if (bp.sourcePackage == null 8871 || bp.sourcePackage.equals(p.info.packageName)) { 8872 BasePermission tree = findPermissionTreeLP(p.info.name); 8873 if (tree == null 8874 || tree.sourcePackage.equals(p.info.packageName)) { 8875 bp.packageSetting = pkgSetting; 8876 bp.perm = p; 8877 bp.uid = pkg.applicationInfo.uid; 8878 bp.sourcePackage = p.info.packageName; 8879 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8880 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8881 if (r == null) { 8882 r = new StringBuilder(256); 8883 } else { 8884 r.append(' '); 8885 } 8886 r.append(p.info.name); 8887 } 8888 } else { 8889 Slog.w(TAG, "Permission " + p.info.name + " from package " 8890 + p.info.packageName + " ignored: base tree " 8891 + tree.name + " is from package " 8892 + tree.sourcePackage); 8893 } 8894 } else { 8895 Slog.w(TAG, "Permission " + p.info.name + " from package " 8896 + p.info.packageName + " ignored: original from " 8897 + bp.sourcePackage); 8898 } 8899 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8900 if (r == null) { 8901 r = new StringBuilder(256); 8902 } else { 8903 r.append(' '); 8904 } 8905 r.append("DUP:"); 8906 r.append(p.info.name); 8907 } 8908 if (bp.perm == p) { 8909 bp.protectionLevel = p.info.protectionLevel; 8910 } 8911 } 8912 8913 if (r != null) { 8914 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8915 } 8916 8917 N = pkg.instrumentation.size(); 8918 r = null; 8919 for (i=0; i<N; i++) { 8920 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8921 a.info.packageName = pkg.applicationInfo.packageName; 8922 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8923 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8924 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8925 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8926 a.info.dataDir = pkg.applicationInfo.dataDir; 8927 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8928 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8929 8930 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8931 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8932 mInstrumentation.put(a.getComponentName(), a); 8933 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8934 if (r == null) { 8935 r = new StringBuilder(256); 8936 } else { 8937 r.append(' '); 8938 } 8939 r.append(a.info.name); 8940 } 8941 } 8942 if (r != null) { 8943 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8944 } 8945 8946 if (pkg.protectedBroadcasts != null) { 8947 N = pkg.protectedBroadcasts.size(); 8948 for (i=0; i<N; i++) { 8949 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8950 } 8951 } 8952 8953 pkgSetting.setTimeStamp(scanFileTime); 8954 8955 // Create idmap files for pairs of (packages, overlay packages). 8956 // Note: "android", ie framework-res.apk, is handled by native layers. 8957 if (pkg.mOverlayTarget != null) { 8958 // This is an overlay package. 8959 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8960 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8961 mOverlays.put(pkg.mOverlayTarget, 8962 new ArrayMap<String, PackageParser.Package>()); 8963 } 8964 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8965 map.put(pkg.packageName, pkg); 8966 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8967 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8968 createIdmapFailed = true; 8969 } 8970 } 8971 } else if (mOverlays.containsKey(pkg.packageName) && 8972 !pkg.packageName.equals("android")) { 8973 // This is a regular package, with one or more known overlay packages. 8974 createIdmapsForPackageLI(pkg); 8975 } 8976 } 8977 8978 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8979 8980 if (createIdmapFailed) { 8981 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8982 "scanPackageLI failed to createIdmap"); 8983 } 8984 return pkg; 8985 } 8986 8987 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8988 PackageParser.Package update, UserHandle user) { 8989 if (existing.applicationInfo == null || update.applicationInfo == null) { 8990 // This isn't due to an app installation. 8991 return; 8992 } 8993 8994 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8995 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8996 8997 // The codePath hasn't changed, so there's nothing for us to do. 8998 if (Objects.equals(oldCodePath, newCodePath)) { 8999 return; 9000 } 9001 9002 File canonicalNewCodePath; 9003 try { 9004 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9005 } catch (IOException e) { 9006 Slog.w(TAG, "Failed to get canonical path.", e); 9007 return; 9008 } 9009 9010 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9011 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9012 // that the last component of the path (i.e, the name) doesn't need canonicalization 9013 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9014 // but may change in the future. Hopefully this function won't exist at that point. 9015 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9016 oldCodePath.getName()); 9017 9018 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9019 // with "@". 9020 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9021 if (!oldMarkerPrefix.endsWith("@")) { 9022 oldMarkerPrefix += "@"; 9023 } 9024 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9025 if (!newMarkerPrefix.endsWith("@")) { 9026 newMarkerPrefix += "@"; 9027 } 9028 9029 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9030 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9031 for (String updatedPath : updatedPaths) { 9032 String updatedPathName = new File(updatedPath).getName(); 9033 markerSuffixes.add(updatedPathName.replace('/', '@')); 9034 } 9035 9036 for (int userId : resolveUserIds(user.getIdentifier())) { 9037 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9038 9039 for (String markerSuffix : markerSuffixes) { 9040 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9041 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9042 if (oldForeignUseMark.exists()) { 9043 try { 9044 Os.rename(oldForeignUseMark.getAbsolutePath(), 9045 newForeignUseMark.getAbsolutePath()); 9046 } catch (ErrnoException e) { 9047 Slog.w(TAG, "Failed to rename foreign use marker", e); 9048 oldForeignUseMark.delete(); 9049 } 9050 } 9051 } 9052 } 9053 } 9054 9055 /** 9056 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9057 * is derived purely on the basis of the contents of {@code scanFile} and 9058 * {@code cpuAbiOverride}. 9059 * 9060 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9061 */ 9062 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9063 String cpuAbiOverride, boolean extractLibs) 9064 throws PackageManagerException { 9065 // TODO: We can probably be smarter about this stuff. For installed apps, 9066 // we can calculate this information at install time once and for all. For 9067 // system apps, we can probably assume that this information doesn't change 9068 // after the first boot scan. As things stand, we do lots of unnecessary work. 9069 9070 // Give ourselves some initial paths; we'll come back for another 9071 // pass once we've determined ABI below. 9072 setNativeLibraryPaths(pkg); 9073 9074 // We would never need to extract libs for forward-locked and external packages, 9075 // since the container service will do it for us. We shouldn't attempt to 9076 // extract libs from system app when it was not updated. 9077 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9078 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9079 extractLibs = false; 9080 } 9081 9082 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9083 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9084 9085 NativeLibraryHelper.Handle handle = null; 9086 try { 9087 handle = NativeLibraryHelper.Handle.create(pkg); 9088 // TODO(multiArch): This can be null for apps that didn't go through the 9089 // usual installation process. We can calculate it again, like we 9090 // do during install time. 9091 // 9092 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9093 // unnecessary. 9094 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9095 9096 // Null out the abis so that they can be recalculated. 9097 pkg.applicationInfo.primaryCpuAbi = null; 9098 pkg.applicationInfo.secondaryCpuAbi = null; 9099 if (isMultiArch(pkg.applicationInfo)) { 9100 // Warn if we've set an abiOverride for multi-lib packages.. 9101 // By definition, we need to copy both 32 and 64 bit libraries for 9102 // such packages. 9103 if (pkg.cpuAbiOverride != null 9104 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9105 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9106 } 9107 9108 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9109 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9110 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9111 if (extractLibs) { 9112 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9113 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9114 useIsaSpecificSubdirs); 9115 } else { 9116 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9117 } 9118 } 9119 9120 maybeThrowExceptionForMultiArchCopy( 9121 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9122 9123 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9124 if (extractLibs) { 9125 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9126 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9127 useIsaSpecificSubdirs); 9128 } else { 9129 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9130 } 9131 } 9132 9133 maybeThrowExceptionForMultiArchCopy( 9134 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9135 9136 if (abi64 >= 0) { 9137 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9138 } 9139 9140 if (abi32 >= 0) { 9141 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9142 if (abi64 >= 0) { 9143 if (pkg.use32bitAbi) { 9144 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9145 pkg.applicationInfo.primaryCpuAbi = abi; 9146 } else { 9147 pkg.applicationInfo.secondaryCpuAbi = abi; 9148 } 9149 } else { 9150 pkg.applicationInfo.primaryCpuAbi = abi; 9151 } 9152 } 9153 9154 } else { 9155 String[] abiList = (cpuAbiOverride != null) ? 9156 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9157 9158 // Enable gross and lame hacks for apps that are built with old 9159 // SDK tools. We must scan their APKs for renderscript bitcode and 9160 // not launch them if it's present. Don't bother checking on devices 9161 // that don't have 64 bit support. 9162 boolean needsRenderScriptOverride = false; 9163 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9164 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9165 abiList = Build.SUPPORTED_32_BIT_ABIS; 9166 needsRenderScriptOverride = true; 9167 } 9168 9169 final int copyRet; 9170 if (extractLibs) { 9171 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9172 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9173 } else { 9174 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9175 } 9176 9177 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9178 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9179 "Error unpackaging native libs for app, errorCode=" + copyRet); 9180 } 9181 9182 if (copyRet >= 0) { 9183 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9184 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9185 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9186 } else if (needsRenderScriptOverride) { 9187 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9188 } 9189 } 9190 } catch (IOException ioe) { 9191 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9192 } finally { 9193 IoUtils.closeQuietly(handle); 9194 } 9195 9196 // Now that we've calculated the ABIs and determined if it's an internal app, 9197 // we will go ahead and populate the nativeLibraryPath. 9198 setNativeLibraryPaths(pkg); 9199 } 9200 9201 /** 9202 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9203 * i.e, so that all packages can be run inside a single process if required. 9204 * 9205 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9206 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9207 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9208 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9209 * updating a package that belongs to a shared user. 9210 * 9211 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9212 * adds unnecessary complexity. 9213 */ 9214 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9215 PackageParser.Package scannedPackage, boolean bootComplete) { 9216 String requiredInstructionSet = null; 9217 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9218 requiredInstructionSet = VMRuntime.getInstructionSet( 9219 scannedPackage.applicationInfo.primaryCpuAbi); 9220 } 9221 9222 PackageSetting requirer = null; 9223 for (PackageSetting ps : packagesForUser) { 9224 // If packagesForUser contains scannedPackage, we skip it. This will happen 9225 // when scannedPackage is an update of an existing package. Without this check, 9226 // we will never be able to change the ABI of any package belonging to a shared 9227 // user, even if it's compatible with other packages. 9228 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9229 if (ps.primaryCpuAbiString == null) { 9230 continue; 9231 } 9232 9233 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9234 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9235 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9236 // this but there's not much we can do. 9237 String errorMessage = "Instruction set mismatch, " 9238 + ((requirer == null) ? "[caller]" : requirer) 9239 + " requires " + requiredInstructionSet + " whereas " + ps 9240 + " requires " + instructionSet; 9241 Slog.w(TAG, errorMessage); 9242 } 9243 9244 if (requiredInstructionSet == null) { 9245 requiredInstructionSet = instructionSet; 9246 requirer = ps; 9247 } 9248 } 9249 } 9250 9251 if (requiredInstructionSet != null) { 9252 String adjustedAbi; 9253 if (requirer != null) { 9254 // requirer != null implies that either scannedPackage was null or that scannedPackage 9255 // did not require an ABI, in which case we have to adjust scannedPackage to match 9256 // the ABI of the set (which is the same as requirer's ABI) 9257 adjustedAbi = requirer.primaryCpuAbiString; 9258 if (scannedPackage != null) { 9259 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9260 } 9261 } else { 9262 // requirer == null implies that we're updating all ABIs in the set to 9263 // match scannedPackage. 9264 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9265 } 9266 9267 for (PackageSetting ps : packagesForUser) { 9268 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9269 if (ps.primaryCpuAbiString != null) { 9270 continue; 9271 } 9272 9273 ps.primaryCpuAbiString = adjustedAbi; 9274 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9275 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9276 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9277 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9278 + " (requirer=" 9279 + (requirer == null ? "null" : requirer.pkg.packageName) 9280 + ", scannedPackage=" 9281 + (scannedPackage != null ? scannedPackage.packageName : "null") 9282 + ")"); 9283 try { 9284 mInstaller.rmdex(ps.codePathString, 9285 getDexCodeInstructionSet(getPreferredInstructionSet())); 9286 } catch (InstallerException ignored) { 9287 } 9288 } 9289 } 9290 } 9291 } 9292 } 9293 9294 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9295 synchronized (mPackages) { 9296 mResolverReplaced = true; 9297 // Set up information for custom user intent resolution activity. 9298 mResolveActivity.applicationInfo = pkg.applicationInfo; 9299 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9300 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9301 mResolveActivity.processName = pkg.applicationInfo.packageName; 9302 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9303 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9304 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9305 mResolveActivity.theme = 0; 9306 mResolveActivity.exported = true; 9307 mResolveActivity.enabled = true; 9308 mResolveInfo.activityInfo = mResolveActivity; 9309 mResolveInfo.priority = 0; 9310 mResolveInfo.preferredOrder = 0; 9311 mResolveInfo.match = 0; 9312 mResolveComponentName = mCustomResolverComponentName; 9313 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9314 mResolveComponentName); 9315 } 9316 } 9317 9318 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9319 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9320 9321 // Set up information for ephemeral installer activity 9322 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9323 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9324 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9325 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9326 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9327 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9328 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9329 mEphemeralInstallerActivity.theme = 0; 9330 mEphemeralInstallerActivity.exported = true; 9331 mEphemeralInstallerActivity.enabled = true; 9332 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9333 mEphemeralInstallerInfo.priority = 0; 9334 mEphemeralInstallerInfo.preferredOrder = 0; 9335 mEphemeralInstallerInfo.match = 0; 9336 9337 if (DEBUG_EPHEMERAL) { 9338 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9339 } 9340 } 9341 9342 private static String calculateBundledApkRoot(final String codePathString) { 9343 final File codePath = new File(codePathString); 9344 final File codeRoot; 9345 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9346 codeRoot = Environment.getRootDirectory(); 9347 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9348 codeRoot = Environment.getOemDirectory(); 9349 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9350 codeRoot = Environment.getVendorDirectory(); 9351 } else { 9352 // Unrecognized code path; take its top real segment as the apk root: 9353 // e.g. /something/app/blah.apk => /something 9354 try { 9355 File f = codePath.getCanonicalFile(); 9356 File parent = f.getParentFile(); // non-null because codePath is a file 9357 File tmp; 9358 while ((tmp = parent.getParentFile()) != null) { 9359 f = parent; 9360 parent = tmp; 9361 } 9362 codeRoot = f; 9363 Slog.w(TAG, "Unrecognized code path " 9364 + codePath + " - using " + codeRoot); 9365 } catch (IOException e) { 9366 // Can't canonicalize the code path -- shenanigans? 9367 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9368 return Environment.getRootDirectory().getPath(); 9369 } 9370 } 9371 return codeRoot.getPath(); 9372 } 9373 9374 /** 9375 * Derive and set the location of native libraries for the given package, 9376 * which varies depending on where and how the package was installed. 9377 */ 9378 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9379 final ApplicationInfo info = pkg.applicationInfo; 9380 final String codePath = pkg.codePath; 9381 final File codeFile = new File(codePath); 9382 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9383 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9384 9385 info.nativeLibraryRootDir = null; 9386 info.nativeLibraryRootRequiresIsa = false; 9387 info.nativeLibraryDir = null; 9388 info.secondaryNativeLibraryDir = null; 9389 9390 if (isApkFile(codeFile)) { 9391 // Monolithic install 9392 if (bundledApp) { 9393 // If "/system/lib64/apkname" exists, assume that is the per-package 9394 // native library directory to use; otherwise use "/system/lib/apkname". 9395 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9396 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9397 getPrimaryInstructionSet(info)); 9398 9399 // This is a bundled system app so choose the path based on the ABI. 9400 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9401 // is just the default path. 9402 final String apkName = deriveCodePathName(codePath); 9403 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9404 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9405 apkName).getAbsolutePath(); 9406 9407 if (info.secondaryCpuAbi != null) { 9408 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9409 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9410 secondaryLibDir, apkName).getAbsolutePath(); 9411 } 9412 } else if (asecApp) { 9413 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9414 .getAbsolutePath(); 9415 } else { 9416 final String apkName = deriveCodePathName(codePath); 9417 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9418 .getAbsolutePath(); 9419 } 9420 9421 info.nativeLibraryRootRequiresIsa = false; 9422 info.nativeLibraryDir = info.nativeLibraryRootDir; 9423 } else { 9424 // Cluster install 9425 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9426 info.nativeLibraryRootRequiresIsa = true; 9427 9428 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9429 getPrimaryInstructionSet(info)).getAbsolutePath(); 9430 9431 if (info.secondaryCpuAbi != null) { 9432 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9433 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9434 } 9435 } 9436 } 9437 9438 /** 9439 * Calculate the abis and roots for a bundled app. These can uniquely 9440 * be determined from the contents of the system partition, i.e whether 9441 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9442 * of this information, and instead assume that the system was built 9443 * sensibly. 9444 */ 9445 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9446 PackageSetting pkgSetting) { 9447 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9448 9449 // If "/system/lib64/apkname" exists, assume that is the per-package 9450 // native library directory to use; otherwise use "/system/lib/apkname". 9451 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9452 setBundledAppAbi(pkg, apkRoot, apkName); 9453 // pkgSetting might be null during rescan following uninstall of updates 9454 // to a bundled app, so accommodate that possibility. The settings in 9455 // that case will be established later from the parsed package. 9456 // 9457 // If the settings aren't null, sync them up with what we've just derived. 9458 // note that apkRoot isn't stored in the package settings. 9459 if (pkgSetting != null) { 9460 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9461 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9462 } 9463 } 9464 9465 /** 9466 * Deduces the ABI of a bundled app and sets the relevant fields on the 9467 * parsed pkg object. 9468 * 9469 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9470 * under which system libraries are installed. 9471 * @param apkName the name of the installed package. 9472 */ 9473 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9474 final File codeFile = new File(pkg.codePath); 9475 9476 final boolean has64BitLibs; 9477 final boolean has32BitLibs; 9478 if (isApkFile(codeFile)) { 9479 // Monolithic install 9480 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9481 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9482 } else { 9483 // Cluster install 9484 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9485 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9486 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9487 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9488 has64BitLibs = (new File(rootDir, isa)).exists(); 9489 } else { 9490 has64BitLibs = false; 9491 } 9492 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9493 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9494 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9495 has32BitLibs = (new File(rootDir, isa)).exists(); 9496 } else { 9497 has32BitLibs = false; 9498 } 9499 } 9500 9501 if (has64BitLibs && !has32BitLibs) { 9502 // The package has 64 bit libs, but not 32 bit libs. Its primary 9503 // ABI should be 64 bit. We can safely assume here that the bundled 9504 // native libraries correspond to the most preferred ABI in the list. 9505 9506 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9507 pkg.applicationInfo.secondaryCpuAbi = null; 9508 } else if (has32BitLibs && !has64BitLibs) { 9509 // The package has 32 bit libs but not 64 bit libs. Its primary 9510 // ABI should be 32 bit. 9511 9512 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9513 pkg.applicationInfo.secondaryCpuAbi = null; 9514 } else if (has32BitLibs && has64BitLibs) { 9515 // The application has both 64 and 32 bit bundled libraries. We check 9516 // here that the app declares multiArch support, and warn if it doesn't. 9517 // 9518 // We will be lenient here and record both ABIs. The primary will be the 9519 // ABI that's higher on the list, i.e, a device that's configured to prefer 9520 // 64 bit apps will see a 64 bit primary ABI, 9521 9522 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9523 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9524 } 9525 9526 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9527 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9528 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9529 } else { 9530 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9531 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9532 } 9533 } else { 9534 pkg.applicationInfo.primaryCpuAbi = null; 9535 pkg.applicationInfo.secondaryCpuAbi = null; 9536 } 9537 } 9538 9539 private void killApplication(String pkgName, int appId, String reason) { 9540 // Request the ActivityManager to kill the process(only for existing packages) 9541 // so that we do not end up in a confused state while the user is still using the older 9542 // version of the application while the new one gets installed. 9543 final long token = Binder.clearCallingIdentity(); 9544 try { 9545 IActivityManager am = ActivityManagerNative.getDefault(); 9546 if (am != null) { 9547 try { 9548 am.killApplicationWithAppId(pkgName, appId, reason); 9549 } catch (RemoteException e) { 9550 } 9551 } 9552 } finally { 9553 Binder.restoreCallingIdentity(token); 9554 } 9555 } 9556 9557 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9558 // Remove the parent package setting 9559 PackageSetting ps = (PackageSetting) pkg.mExtras; 9560 if (ps != null) { 9561 removePackageLI(ps, chatty); 9562 } 9563 // Remove the child package setting 9564 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9565 for (int i = 0; i < childCount; i++) { 9566 PackageParser.Package childPkg = pkg.childPackages.get(i); 9567 ps = (PackageSetting) childPkg.mExtras; 9568 if (ps != null) { 9569 removePackageLI(ps, chatty); 9570 } 9571 } 9572 } 9573 9574 void removePackageLI(PackageSetting ps, boolean chatty) { 9575 if (DEBUG_INSTALL) { 9576 if (chatty) 9577 Log.d(TAG, "Removing package " + ps.name); 9578 } 9579 9580 // writer 9581 synchronized (mPackages) { 9582 mPackages.remove(ps.name); 9583 final PackageParser.Package pkg = ps.pkg; 9584 if (pkg != null) { 9585 cleanPackageDataStructuresLILPw(pkg, chatty); 9586 } 9587 } 9588 } 9589 9590 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9591 if (DEBUG_INSTALL) { 9592 if (chatty) 9593 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9594 } 9595 9596 // writer 9597 synchronized (mPackages) { 9598 // Remove the parent package 9599 mPackages.remove(pkg.applicationInfo.packageName); 9600 cleanPackageDataStructuresLILPw(pkg, chatty); 9601 9602 // Remove the child packages 9603 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9604 for (int i = 0; i < childCount; i++) { 9605 PackageParser.Package childPkg = pkg.childPackages.get(i); 9606 mPackages.remove(childPkg.applicationInfo.packageName); 9607 cleanPackageDataStructuresLILPw(childPkg, chatty); 9608 } 9609 } 9610 } 9611 9612 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9613 int N = pkg.providers.size(); 9614 StringBuilder r = null; 9615 int i; 9616 for (i=0; i<N; i++) { 9617 PackageParser.Provider p = pkg.providers.get(i); 9618 mProviders.removeProvider(p); 9619 if (p.info.authority == null) { 9620 9621 /* There was another ContentProvider with this authority when 9622 * this app was installed so this authority is null, 9623 * Ignore it as we don't have to unregister the provider. 9624 */ 9625 continue; 9626 } 9627 String names[] = p.info.authority.split(";"); 9628 for (int j = 0; j < names.length; j++) { 9629 if (mProvidersByAuthority.get(names[j]) == p) { 9630 mProvidersByAuthority.remove(names[j]); 9631 if (DEBUG_REMOVE) { 9632 if (chatty) 9633 Log.d(TAG, "Unregistered content provider: " + names[j] 9634 + ", className = " + p.info.name + ", isSyncable = " 9635 + p.info.isSyncable); 9636 } 9637 } 9638 } 9639 if (DEBUG_REMOVE && chatty) { 9640 if (r == null) { 9641 r = new StringBuilder(256); 9642 } else { 9643 r.append(' '); 9644 } 9645 r.append(p.info.name); 9646 } 9647 } 9648 if (r != null) { 9649 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9650 } 9651 9652 N = pkg.services.size(); 9653 r = null; 9654 for (i=0; i<N; i++) { 9655 PackageParser.Service s = pkg.services.get(i); 9656 mServices.removeService(s); 9657 if (chatty) { 9658 if (r == null) { 9659 r = new StringBuilder(256); 9660 } else { 9661 r.append(' '); 9662 } 9663 r.append(s.info.name); 9664 } 9665 } 9666 if (r != null) { 9667 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9668 } 9669 9670 N = pkg.receivers.size(); 9671 r = null; 9672 for (i=0; i<N; i++) { 9673 PackageParser.Activity a = pkg.receivers.get(i); 9674 mReceivers.removeActivity(a, "receiver"); 9675 if (DEBUG_REMOVE && chatty) { 9676 if (r == null) { 9677 r = new StringBuilder(256); 9678 } else { 9679 r.append(' '); 9680 } 9681 r.append(a.info.name); 9682 } 9683 } 9684 if (r != null) { 9685 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9686 } 9687 9688 N = pkg.activities.size(); 9689 r = null; 9690 for (i=0; i<N; i++) { 9691 PackageParser.Activity a = pkg.activities.get(i); 9692 mActivities.removeActivity(a, "activity"); 9693 if (DEBUG_REMOVE && chatty) { 9694 if (r == null) { 9695 r = new StringBuilder(256); 9696 } else { 9697 r.append(' '); 9698 } 9699 r.append(a.info.name); 9700 } 9701 } 9702 if (r != null) { 9703 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9704 } 9705 9706 N = pkg.permissions.size(); 9707 r = null; 9708 for (i=0; i<N; i++) { 9709 PackageParser.Permission p = pkg.permissions.get(i); 9710 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9711 if (bp == null) { 9712 bp = mSettings.mPermissionTrees.get(p.info.name); 9713 } 9714 if (bp != null && bp.perm == p) { 9715 bp.perm = null; 9716 if (DEBUG_REMOVE && chatty) { 9717 if (r == null) { 9718 r = new StringBuilder(256); 9719 } else { 9720 r.append(' '); 9721 } 9722 r.append(p.info.name); 9723 } 9724 } 9725 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9726 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9727 if (appOpPkgs != null) { 9728 appOpPkgs.remove(pkg.packageName); 9729 } 9730 } 9731 } 9732 if (r != null) { 9733 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9734 } 9735 9736 N = pkg.requestedPermissions.size(); 9737 r = null; 9738 for (i=0; i<N; i++) { 9739 String perm = pkg.requestedPermissions.get(i); 9740 BasePermission bp = mSettings.mPermissions.get(perm); 9741 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9742 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9743 if (appOpPkgs != null) { 9744 appOpPkgs.remove(pkg.packageName); 9745 if (appOpPkgs.isEmpty()) { 9746 mAppOpPermissionPackages.remove(perm); 9747 } 9748 } 9749 } 9750 } 9751 if (r != null) { 9752 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9753 } 9754 9755 N = pkg.instrumentation.size(); 9756 r = null; 9757 for (i=0; i<N; i++) { 9758 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9759 mInstrumentation.remove(a.getComponentName()); 9760 if (DEBUG_REMOVE && chatty) { 9761 if (r == null) { 9762 r = new StringBuilder(256); 9763 } else { 9764 r.append(' '); 9765 } 9766 r.append(a.info.name); 9767 } 9768 } 9769 if (r != null) { 9770 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9771 } 9772 9773 r = null; 9774 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9775 // Only system apps can hold shared libraries. 9776 if (pkg.libraryNames != null) { 9777 for (i=0; i<pkg.libraryNames.size(); i++) { 9778 String name = pkg.libraryNames.get(i); 9779 SharedLibraryEntry cur = mSharedLibraries.get(name); 9780 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9781 mSharedLibraries.remove(name); 9782 if (DEBUG_REMOVE && chatty) { 9783 if (r == null) { 9784 r = new StringBuilder(256); 9785 } else { 9786 r.append(' '); 9787 } 9788 r.append(name); 9789 } 9790 } 9791 } 9792 } 9793 } 9794 if (r != null) { 9795 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9796 } 9797 } 9798 9799 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9800 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9801 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9802 return true; 9803 } 9804 } 9805 return false; 9806 } 9807 9808 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9809 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9810 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9811 9812 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9813 // Update the parent permissions 9814 updatePermissionsLPw(pkg.packageName, pkg, flags); 9815 // Update the child permissions 9816 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9817 for (int i = 0; i < childCount; i++) { 9818 PackageParser.Package childPkg = pkg.childPackages.get(i); 9819 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9820 } 9821 } 9822 9823 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9824 int flags) { 9825 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9826 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9827 } 9828 9829 private void updatePermissionsLPw(String changingPkg, 9830 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9831 // Make sure there are no dangling permission trees. 9832 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9833 while (it.hasNext()) { 9834 final BasePermission bp = it.next(); 9835 if (bp.packageSetting == null) { 9836 // We may not yet have parsed the package, so just see if 9837 // we still know about its settings. 9838 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9839 } 9840 if (bp.packageSetting == null) { 9841 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9842 + " from package " + bp.sourcePackage); 9843 it.remove(); 9844 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9845 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9846 Slog.i(TAG, "Removing old permission tree: " + bp.name 9847 + " from package " + bp.sourcePackage); 9848 flags |= UPDATE_PERMISSIONS_ALL; 9849 it.remove(); 9850 } 9851 } 9852 } 9853 9854 // Make sure all dynamic permissions have been assigned to a package, 9855 // and make sure there are no dangling permissions. 9856 it = mSettings.mPermissions.values().iterator(); 9857 while (it.hasNext()) { 9858 final BasePermission bp = it.next(); 9859 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9860 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9861 + bp.name + " pkg=" + bp.sourcePackage 9862 + " info=" + bp.pendingInfo); 9863 if (bp.packageSetting == null && bp.pendingInfo != null) { 9864 final BasePermission tree = findPermissionTreeLP(bp.name); 9865 if (tree != null && tree.perm != null) { 9866 bp.packageSetting = tree.packageSetting; 9867 bp.perm = new PackageParser.Permission(tree.perm.owner, 9868 new PermissionInfo(bp.pendingInfo)); 9869 bp.perm.info.packageName = tree.perm.info.packageName; 9870 bp.perm.info.name = bp.name; 9871 bp.uid = tree.uid; 9872 } 9873 } 9874 } 9875 if (bp.packageSetting == null) { 9876 // We may not yet have parsed the package, so just see if 9877 // we still know about its settings. 9878 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9879 } 9880 if (bp.packageSetting == null) { 9881 Slog.w(TAG, "Removing dangling permission: " + bp.name 9882 + " from package " + bp.sourcePackage); 9883 it.remove(); 9884 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9885 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9886 Slog.i(TAG, "Removing old permission: " + bp.name 9887 + " from package " + bp.sourcePackage); 9888 flags |= UPDATE_PERMISSIONS_ALL; 9889 it.remove(); 9890 } 9891 } 9892 } 9893 9894 // Now update the permissions for all packages, in particular 9895 // replace the granted permissions of the system packages. 9896 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9897 for (PackageParser.Package pkg : mPackages.values()) { 9898 if (pkg != pkgInfo) { 9899 // Only replace for packages on requested volume 9900 final String volumeUuid = getVolumeUuidForPackage(pkg); 9901 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9902 && Objects.equals(replaceVolumeUuid, volumeUuid); 9903 grantPermissionsLPw(pkg, replace, changingPkg); 9904 } 9905 } 9906 } 9907 9908 if (pkgInfo != null) { 9909 // Only replace for packages on requested volume 9910 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9911 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9912 && Objects.equals(replaceVolumeUuid, volumeUuid); 9913 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9914 } 9915 } 9916 9917 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9918 String packageOfInterest) { 9919 // IMPORTANT: There are two types of permissions: install and runtime. 9920 // Install time permissions are granted when the app is installed to 9921 // all device users and users added in the future. Runtime permissions 9922 // are granted at runtime explicitly to specific users. Normal and signature 9923 // protected permissions are install time permissions. Dangerous permissions 9924 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9925 // otherwise they are runtime permissions. This function does not manage 9926 // runtime permissions except for the case an app targeting Lollipop MR1 9927 // being upgraded to target a newer SDK, in which case dangerous permissions 9928 // are transformed from install time to runtime ones. 9929 9930 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9931 if (ps == null) { 9932 return; 9933 } 9934 9935 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9936 9937 PermissionsState permissionsState = ps.getPermissionsState(); 9938 PermissionsState origPermissions = permissionsState; 9939 9940 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9941 9942 boolean runtimePermissionsRevoked = false; 9943 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9944 9945 boolean changedInstallPermission = false; 9946 9947 if (replace) { 9948 ps.installPermissionsFixed = false; 9949 if (!ps.isSharedUser()) { 9950 origPermissions = new PermissionsState(permissionsState); 9951 permissionsState.reset(); 9952 } else { 9953 // We need to know only about runtime permission changes since the 9954 // calling code always writes the install permissions state but 9955 // the runtime ones are written only if changed. The only cases of 9956 // changed runtime permissions here are promotion of an install to 9957 // runtime and revocation of a runtime from a shared user. 9958 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9959 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9960 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9961 runtimePermissionsRevoked = true; 9962 } 9963 } 9964 } 9965 9966 permissionsState.setGlobalGids(mGlobalGids); 9967 9968 final int N = pkg.requestedPermissions.size(); 9969 for (int i=0; i<N; i++) { 9970 final String name = pkg.requestedPermissions.get(i); 9971 final BasePermission bp = mSettings.mPermissions.get(name); 9972 9973 if (DEBUG_INSTALL) { 9974 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9975 } 9976 9977 if (bp == null || bp.packageSetting == null) { 9978 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9979 Slog.w(TAG, "Unknown permission " + name 9980 + " in package " + pkg.packageName); 9981 } 9982 continue; 9983 } 9984 9985 final String perm = bp.name; 9986 boolean allowedSig = false; 9987 int grant = GRANT_DENIED; 9988 9989 // Keep track of app op permissions. 9990 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9991 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9992 if (pkgs == null) { 9993 pkgs = new ArraySet<>(); 9994 mAppOpPermissionPackages.put(bp.name, pkgs); 9995 } 9996 pkgs.add(pkg.packageName); 9997 } 9998 9999 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10000 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10001 >= Build.VERSION_CODES.M; 10002 switch (level) { 10003 case PermissionInfo.PROTECTION_NORMAL: { 10004 // For all apps normal permissions are install time ones. 10005 grant = GRANT_INSTALL; 10006 } break; 10007 10008 case PermissionInfo.PROTECTION_DANGEROUS: { 10009 // If a permission review is required for legacy apps we represent 10010 // their permissions as always granted runtime ones since we need 10011 // to keep the review required permission flag per user while an 10012 // install permission's state is shared across all users. 10013 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10014 // For legacy apps dangerous permissions are install time ones. 10015 grant = GRANT_INSTALL; 10016 } else if (origPermissions.hasInstallPermission(bp.name)) { 10017 // For legacy apps that became modern, install becomes runtime. 10018 grant = GRANT_UPGRADE; 10019 } else if (mPromoteSystemApps 10020 && isSystemApp(ps) 10021 && mExistingSystemPackages.contains(ps.name)) { 10022 // For legacy system apps, install becomes runtime. 10023 // We cannot check hasInstallPermission() for system apps since those 10024 // permissions were granted implicitly and not persisted pre-M. 10025 grant = GRANT_UPGRADE; 10026 } else { 10027 // For modern apps keep runtime permissions unchanged. 10028 grant = GRANT_RUNTIME; 10029 } 10030 } break; 10031 10032 case PermissionInfo.PROTECTION_SIGNATURE: { 10033 // For all apps signature permissions are install time ones. 10034 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10035 if (allowedSig) { 10036 grant = GRANT_INSTALL; 10037 } 10038 } break; 10039 } 10040 10041 if (DEBUG_INSTALL) { 10042 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10043 } 10044 10045 if (grant != GRANT_DENIED) { 10046 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10047 // If this is an existing, non-system package, then 10048 // we can't add any new permissions to it. 10049 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10050 // Except... if this is a permission that was added 10051 // to the platform (note: need to only do this when 10052 // updating the platform). 10053 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10054 grant = GRANT_DENIED; 10055 } 10056 } 10057 } 10058 10059 switch (grant) { 10060 case GRANT_INSTALL: { 10061 // Revoke this as runtime permission to handle the case of 10062 // a runtime permission being downgraded to an install one. 10063 // Also in permission review mode we keep dangerous permissions 10064 // for legacy apps 10065 for (int userId : UserManagerService.getInstance().getUserIds()) { 10066 if (origPermissions.getRuntimePermissionState( 10067 bp.name, userId) != null) { 10068 // Revoke the runtime permission and clear the flags. 10069 origPermissions.revokeRuntimePermission(bp, userId); 10070 origPermissions.updatePermissionFlags(bp, userId, 10071 PackageManager.MASK_PERMISSION_FLAGS, 0); 10072 // If we revoked a permission permission, we have to write. 10073 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10074 changedRuntimePermissionUserIds, userId); 10075 } 10076 } 10077 // Grant an install permission. 10078 if (permissionsState.grantInstallPermission(bp) != 10079 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10080 changedInstallPermission = true; 10081 } 10082 } break; 10083 10084 case GRANT_RUNTIME: { 10085 // Grant previously granted runtime permissions. 10086 for (int userId : UserManagerService.getInstance().getUserIds()) { 10087 PermissionState permissionState = origPermissions 10088 .getRuntimePermissionState(bp.name, userId); 10089 int flags = permissionState != null 10090 ? permissionState.getFlags() : 0; 10091 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10092 if (permissionsState.grantRuntimePermission(bp, userId) == 10093 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10094 // If we cannot put the permission as it was, we have to write. 10095 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10096 changedRuntimePermissionUserIds, userId); 10097 } 10098 // If the app supports runtime permissions no need for a review. 10099 if (Build.PERMISSIONS_REVIEW_REQUIRED 10100 && appSupportsRuntimePermissions 10101 && (flags & PackageManager 10102 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10103 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10104 // Since we changed the flags, we have to write. 10105 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10106 changedRuntimePermissionUserIds, userId); 10107 } 10108 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10109 && !appSupportsRuntimePermissions) { 10110 // For legacy apps that need a permission review, every new 10111 // runtime permission is granted but it is pending a review. 10112 // We also need to review only platform defined runtime 10113 // permissions as these are the only ones the platform knows 10114 // how to disable the API to simulate revocation as legacy 10115 // apps don't expect to run with revoked permissions. 10116 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10117 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10118 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10119 // We changed the flags, hence have to write. 10120 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10121 changedRuntimePermissionUserIds, userId); 10122 } 10123 } 10124 if (permissionsState.grantRuntimePermission(bp, userId) 10125 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10126 // We changed the permission, hence have to write. 10127 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10128 changedRuntimePermissionUserIds, userId); 10129 } 10130 } 10131 // Propagate the permission flags. 10132 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10133 } 10134 } break; 10135 10136 case GRANT_UPGRADE: { 10137 // Grant runtime permissions for a previously held install permission. 10138 PermissionState permissionState = origPermissions 10139 .getInstallPermissionState(bp.name); 10140 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10141 10142 if (origPermissions.revokeInstallPermission(bp) 10143 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10144 // We will be transferring the permission flags, so clear them. 10145 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10146 PackageManager.MASK_PERMISSION_FLAGS, 0); 10147 changedInstallPermission = true; 10148 } 10149 10150 // If the permission is not to be promoted to runtime we ignore it and 10151 // also its other flags as they are not applicable to install permissions. 10152 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10153 for (int userId : currentUserIds) { 10154 if (permissionsState.grantRuntimePermission(bp, userId) != 10155 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10156 // Transfer the permission flags. 10157 permissionsState.updatePermissionFlags(bp, userId, 10158 flags, flags); 10159 // If we granted the permission, we have to write. 10160 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10161 changedRuntimePermissionUserIds, userId); 10162 } 10163 } 10164 } 10165 } break; 10166 10167 default: { 10168 if (packageOfInterest == null 10169 || packageOfInterest.equals(pkg.packageName)) { 10170 Slog.w(TAG, "Not granting permission " + perm 10171 + " to package " + pkg.packageName 10172 + " because it was previously installed without"); 10173 } 10174 } break; 10175 } 10176 } else { 10177 if (permissionsState.revokeInstallPermission(bp) != 10178 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10179 // Also drop the permission flags. 10180 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10181 PackageManager.MASK_PERMISSION_FLAGS, 0); 10182 changedInstallPermission = true; 10183 Slog.i(TAG, "Un-granting permission " + perm 10184 + " from package " + pkg.packageName 10185 + " (protectionLevel=" + bp.protectionLevel 10186 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10187 + ")"); 10188 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10189 // Don't print warning for app op permissions, since it is fine for them 10190 // not to be granted, there is a UI for the user to decide. 10191 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10192 Slog.w(TAG, "Not granting permission " + perm 10193 + " to package " + pkg.packageName 10194 + " (protectionLevel=" + bp.protectionLevel 10195 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10196 + ")"); 10197 } 10198 } 10199 } 10200 } 10201 10202 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10203 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10204 // This is the first that we have heard about this package, so the 10205 // permissions we have now selected are fixed until explicitly 10206 // changed. 10207 ps.installPermissionsFixed = true; 10208 } 10209 10210 // Persist the runtime permissions state for users with changes. If permissions 10211 // were revoked because no app in the shared user declares them we have to 10212 // write synchronously to avoid losing runtime permissions state. 10213 for (int userId : changedRuntimePermissionUserIds) { 10214 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10215 } 10216 10217 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10218 } 10219 10220 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10221 boolean allowed = false; 10222 final int NP = PackageParser.NEW_PERMISSIONS.length; 10223 for (int ip=0; ip<NP; ip++) { 10224 final PackageParser.NewPermissionInfo npi 10225 = PackageParser.NEW_PERMISSIONS[ip]; 10226 if (npi.name.equals(perm) 10227 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10228 allowed = true; 10229 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10230 + pkg.packageName); 10231 break; 10232 } 10233 } 10234 return allowed; 10235 } 10236 10237 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10238 BasePermission bp, PermissionsState origPermissions) { 10239 boolean allowed; 10240 allowed = (compareSignatures( 10241 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10242 == PackageManager.SIGNATURE_MATCH) 10243 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10244 == PackageManager.SIGNATURE_MATCH); 10245 if (!allowed && (bp.protectionLevel 10246 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10247 if (isSystemApp(pkg)) { 10248 // For updated system applications, a system permission 10249 // is granted only if it had been defined by the original application. 10250 if (pkg.isUpdatedSystemApp()) { 10251 final PackageSetting sysPs = mSettings 10252 .getDisabledSystemPkgLPr(pkg.packageName); 10253 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10254 // If the original was granted this permission, we take 10255 // that grant decision as read and propagate it to the 10256 // update. 10257 if (sysPs.isPrivileged()) { 10258 allowed = true; 10259 } 10260 } else { 10261 // The system apk may have been updated with an older 10262 // version of the one on the data partition, but which 10263 // granted a new system permission that it didn't have 10264 // before. In this case we do want to allow the app to 10265 // now get the new permission if the ancestral apk is 10266 // privileged to get it. 10267 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10268 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10269 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10270 allowed = true; 10271 break; 10272 } 10273 } 10274 } 10275 // Also if a privileged parent package on the system image or any of 10276 // its children requested a privileged permission, the updated child 10277 // packages can also get the permission. 10278 if (pkg.parentPackage != null) { 10279 final PackageSetting disabledSysParentPs = mSettings 10280 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10281 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10282 && disabledSysParentPs.isPrivileged()) { 10283 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10284 allowed = true; 10285 } else if (disabledSysParentPs.pkg.childPackages != null) { 10286 final int count = disabledSysParentPs.pkg.childPackages.size(); 10287 for (int i = 0; i < count; i++) { 10288 PackageParser.Package disabledSysChildPkg = 10289 disabledSysParentPs.pkg.childPackages.get(i); 10290 if (isPackageRequestingPermission(disabledSysChildPkg, 10291 perm)) { 10292 allowed = true; 10293 break; 10294 } 10295 } 10296 } 10297 } 10298 } 10299 } 10300 } else { 10301 allowed = isPrivilegedApp(pkg); 10302 } 10303 } 10304 } 10305 if (!allowed) { 10306 if (!allowed && (bp.protectionLevel 10307 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10308 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10309 // If this was a previously normal/dangerous permission that got moved 10310 // to a system permission as part of the runtime permission redesign, then 10311 // we still want to blindly grant it to old apps. 10312 allowed = true; 10313 } 10314 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10315 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10316 // If this permission is to be granted to the system installer and 10317 // this app is an installer, then it gets the permission. 10318 allowed = true; 10319 } 10320 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10321 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10322 // If this permission is to be granted to the system verifier and 10323 // this app is a verifier, then it gets the permission. 10324 allowed = true; 10325 } 10326 if (!allowed && (bp.protectionLevel 10327 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10328 && isSystemApp(pkg)) { 10329 // Any pre-installed system app is allowed to get this permission. 10330 allowed = true; 10331 } 10332 if (!allowed && (bp.protectionLevel 10333 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10334 // For development permissions, a development permission 10335 // is granted only if it was already granted. 10336 allowed = origPermissions.hasInstallPermission(perm); 10337 } 10338 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10339 && pkg.packageName.equals(mSetupWizardPackage)) { 10340 // If this permission is to be granted to the system setup wizard and 10341 // this app is a setup wizard, then it gets the permission. 10342 allowed = true; 10343 } 10344 } 10345 return allowed; 10346 } 10347 10348 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10349 final int permCount = pkg.requestedPermissions.size(); 10350 for (int j = 0; j < permCount; j++) { 10351 String requestedPermission = pkg.requestedPermissions.get(j); 10352 if (permission.equals(requestedPermission)) { 10353 return true; 10354 } 10355 } 10356 return false; 10357 } 10358 10359 final class ActivityIntentResolver 10360 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10361 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10362 boolean defaultOnly, int userId) { 10363 if (!sUserManager.exists(userId)) return null; 10364 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10365 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10366 } 10367 10368 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10369 int userId) { 10370 if (!sUserManager.exists(userId)) return null; 10371 mFlags = flags; 10372 return super.queryIntent(intent, resolvedType, 10373 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10374 } 10375 10376 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10377 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10378 if (!sUserManager.exists(userId)) return null; 10379 if (packageActivities == null) { 10380 return null; 10381 } 10382 mFlags = flags; 10383 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10384 final int N = packageActivities.size(); 10385 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10386 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10387 10388 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10389 for (int i = 0; i < N; ++i) { 10390 intentFilters = packageActivities.get(i).intents; 10391 if (intentFilters != null && intentFilters.size() > 0) { 10392 PackageParser.ActivityIntentInfo[] array = 10393 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10394 intentFilters.toArray(array); 10395 listCut.add(array); 10396 } 10397 } 10398 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10399 } 10400 10401 /** 10402 * Finds a privileged activity that matches the specified activity names. 10403 */ 10404 private PackageParser.Activity findMatchingActivity( 10405 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10406 for (PackageParser.Activity sysActivity : activityList) { 10407 if (sysActivity.info.name.equals(activityInfo.name)) { 10408 return sysActivity; 10409 } 10410 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10411 return sysActivity; 10412 } 10413 if (sysActivity.info.targetActivity != null) { 10414 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10415 return sysActivity; 10416 } 10417 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10418 return sysActivity; 10419 } 10420 } 10421 } 10422 return null; 10423 } 10424 10425 public class IterGenerator<E> { 10426 public Iterator<E> generate(ActivityIntentInfo info) { 10427 return null; 10428 } 10429 } 10430 10431 public class ActionIterGenerator extends IterGenerator<String> { 10432 @Override 10433 public Iterator<String> generate(ActivityIntentInfo info) { 10434 return info.actionsIterator(); 10435 } 10436 } 10437 10438 public class CategoriesIterGenerator extends IterGenerator<String> { 10439 @Override 10440 public Iterator<String> generate(ActivityIntentInfo info) { 10441 return info.categoriesIterator(); 10442 } 10443 } 10444 10445 public class SchemesIterGenerator extends IterGenerator<String> { 10446 @Override 10447 public Iterator<String> generate(ActivityIntentInfo info) { 10448 return info.schemesIterator(); 10449 } 10450 } 10451 10452 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10453 @Override 10454 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10455 return info.authoritiesIterator(); 10456 } 10457 } 10458 10459 /** 10460 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10461 * MODIFIED. Do not pass in a list that should not be changed. 10462 */ 10463 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10464 IterGenerator<T> generator, Iterator<T> searchIterator) { 10465 // loop through the set of actions; every one must be found in the intent filter 10466 while (searchIterator.hasNext()) { 10467 // we must have at least one filter in the list to consider a match 10468 if (intentList.size() == 0) { 10469 break; 10470 } 10471 10472 final T searchAction = searchIterator.next(); 10473 10474 // loop through the set of intent filters 10475 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10476 while (intentIter.hasNext()) { 10477 final ActivityIntentInfo intentInfo = intentIter.next(); 10478 boolean selectionFound = false; 10479 10480 // loop through the intent filter's selection criteria; at least one 10481 // of them must match the searched criteria 10482 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10483 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10484 final T intentSelection = intentSelectionIter.next(); 10485 if (intentSelection != null && intentSelection.equals(searchAction)) { 10486 selectionFound = true; 10487 break; 10488 } 10489 } 10490 10491 // the selection criteria wasn't found in this filter's set; this filter 10492 // is not a potential match 10493 if (!selectionFound) { 10494 intentIter.remove(); 10495 } 10496 } 10497 } 10498 } 10499 10500 private boolean isProtectedAction(ActivityIntentInfo filter) { 10501 final Iterator<String> actionsIter = filter.actionsIterator(); 10502 while (actionsIter != null && actionsIter.hasNext()) { 10503 final String filterAction = actionsIter.next(); 10504 if (PROTECTED_ACTIONS.contains(filterAction)) { 10505 return true; 10506 } 10507 } 10508 return false; 10509 } 10510 10511 /** 10512 * Adjusts the priority of the given intent filter according to policy. 10513 * <p> 10514 * <ul> 10515 * <li>The priority for non privileged applications is capped to '0'</li> 10516 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10517 * <li>The priority for unbundled updates to privileged applications is capped to the 10518 * priority defined on the system partition</li> 10519 * </ul> 10520 * <p> 10521 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10522 * allowed to obtain any priority on any action. 10523 */ 10524 private void adjustPriority( 10525 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10526 // nothing to do; priority is fine as-is 10527 if (intent.getPriority() <= 0) { 10528 return; 10529 } 10530 10531 final ActivityInfo activityInfo = intent.activity.info; 10532 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10533 10534 final boolean privilegedApp = 10535 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10536 if (!privilegedApp) { 10537 // non-privileged applications can never define a priority >0 10538 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10539 + " package: " + applicationInfo.packageName 10540 + " activity: " + intent.activity.className 10541 + " origPrio: " + intent.getPriority()); 10542 intent.setPriority(0); 10543 return; 10544 } 10545 10546 if (systemActivities == null) { 10547 // the system package is not disabled; we're parsing the system partition 10548 if (isProtectedAction(intent)) { 10549 if (mDeferProtectedFilters) { 10550 // We can't deal with these just yet. No component should ever obtain a 10551 // >0 priority for a protected actions, with ONE exception -- the setup 10552 // wizard. The setup wizard, however, cannot be known until we're able to 10553 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10554 // until all intent filters have been processed. Chicken, meet egg. 10555 // Let the filter temporarily have a high priority and rectify the 10556 // priorities after all system packages have been scanned. 10557 mProtectedFilters.add(intent); 10558 if (DEBUG_FILTERS) { 10559 Slog.i(TAG, "Protected action; save for later;" 10560 + " package: " + applicationInfo.packageName 10561 + " activity: " + intent.activity.className 10562 + " origPrio: " + intent.getPriority()); 10563 } 10564 return; 10565 } else { 10566 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10567 Slog.i(TAG, "No setup wizard;" 10568 + " All protected intents capped to priority 0"); 10569 } 10570 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10571 if (DEBUG_FILTERS) { 10572 Slog.i(TAG, "Found setup wizard;" 10573 + " allow priority " + intent.getPriority() + ";" 10574 + " package: " + intent.activity.info.packageName 10575 + " activity: " + intent.activity.className 10576 + " priority: " + intent.getPriority()); 10577 } 10578 // setup wizard gets whatever it wants 10579 return; 10580 } 10581 Slog.w(TAG, "Protected action; cap priority to 0;" 10582 + " package: " + intent.activity.info.packageName 10583 + " activity: " + intent.activity.className 10584 + " origPrio: " + intent.getPriority()); 10585 intent.setPriority(0); 10586 return; 10587 } 10588 } 10589 // privileged apps on the system image get whatever priority they request 10590 return; 10591 } 10592 10593 // privileged app unbundled update ... try to find the same activity 10594 final PackageParser.Activity foundActivity = 10595 findMatchingActivity(systemActivities, activityInfo); 10596 if (foundActivity == null) { 10597 // this is a new activity; it cannot obtain >0 priority 10598 if (DEBUG_FILTERS) { 10599 Slog.i(TAG, "New activity; cap priority to 0;" 10600 + " package: " + applicationInfo.packageName 10601 + " activity: " + intent.activity.className 10602 + " origPrio: " + intent.getPriority()); 10603 } 10604 intent.setPriority(0); 10605 return; 10606 } 10607 10608 // found activity, now check for filter equivalence 10609 10610 // a shallow copy is enough; we modify the list, not its contents 10611 final List<ActivityIntentInfo> intentListCopy = 10612 new ArrayList<>(foundActivity.intents); 10613 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10614 10615 // find matching action subsets 10616 final Iterator<String> actionsIterator = intent.actionsIterator(); 10617 if (actionsIterator != null) { 10618 getIntentListSubset( 10619 intentListCopy, new ActionIterGenerator(), actionsIterator); 10620 if (intentListCopy.size() == 0) { 10621 // no more intents to match; we're not equivalent 10622 if (DEBUG_FILTERS) { 10623 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10624 + " package: " + applicationInfo.packageName 10625 + " activity: " + intent.activity.className 10626 + " origPrio: " + intent.getPriority()); 10627 } 10628 intent.setPriority(0); 10629 return; 10630 } 10631 } 10632 10633 // find matching category subsets 10634 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10635 if (categoriesIterator != null) { 10636 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10637 categoriesIterator); 10638 if (intentListCopy.size() == 0) { 10639 // no more intents to match; we're not equivalent 10640 if (DEBUG_FILTERS) { 10641 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10642 + " package: " + applicationInfo.packageName 10643 + " activity: " + intent.activity.className 10644 + " origPrio: " + intent.getPriority()); 10645 } 10646 intent.setPriority(0); 10647 return; 10648 } 10649 } 10650 10651 // find matching schemes subsets 10652 final Iterator<String> schemesIterator = intent.schemesIterator(); 10653 if (schemesIterator != null) { 10654 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10655 schemesIterator); 10656 if (intentListCopy.size() == 0) { 10657 // no more intents to match; we're not equivalent 10658 if (DEBUG_FILTERS) { 10659 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10660 + " package: " + applicationInfo.packageName 10661 + " activity: " + intent.activity.className 10662 + " origPrio: " + intent.getPriority()); 10663 } 10664 intent.setPriority(0); 10665 return; 10666 } 10667 } 10668 10669 // find matching authorities subsets 10670 final Iterator<IntentFilter.AuthorityEntry> 10671 authoritiesIterator = intent.authoritiesIterator(); 10672 if (authoritiesIterator != null) { 10673 getIntentListSubset(intentListCopy, 10674 new AuthoritiesIterGenerator(), 10675 authoritiesIterator); 10676 if (intentListCopy.size() == 0) { 10677 // no more intents to match; we're not equivalent 10678 if (DEBUG_FILTERS) { 10679 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10680 + " package: " + applicationInfo.packageName 10681 + " activity: " + intent.activity.className 10682 + " origPrio: " + intent.getPriority()); 10683 } 10684 intent.setPriority(0); 10685 return; 10686 } 10687 } 10688 10689 // we found matching filter(s); app gets the max priority of all intents 10690 int cappedPriority = 0; 10691 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10692 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10693 } 10694 if (intent.getPriority() > cappedPriority) { 10695 if (DEBUG_FILTERS) { 10696 Slog.i(TAG, "Found matching filter(s);" 10697 + " cap priority to " + cappedPriority + ";" 10698 + " package: " + applicationInfo.packageName 10699 + " activity: " + intent.activity.className 10700 + " origPrio: " + intent.getPriority()); 10701 } 10702 intent.setPriority(cappedPriority); 10703 return; 10704 } 10705 // all this for nothing; the requested priority was <= what was on the system 10706 } 10707 10708 public final void addActivity(PackageParser.Activity a, String type) { 10709 mActivities.put(a.getComponentName(), a); 10710 if (DEBUG_SHOW_INFO) 10711 Log.v( 10712 TAG, " " + type + " " + 10713 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10714 if (DEBUG_SHOW_INFO) 10715 Log.v(TAG, " Class=" + a.info.name); 10716 final int NI = a.intents.size(); 10717 for (int j=0; j<NI; j++) { 10718 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10719 if ("activity".equals(type)) { 10720 final PackageSetting ps = 10721 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10722 final List<PackageParser.Activity> systemActivities = 10723 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10724 adjustPriority(systemActivities, intent); 10725 } 10726 if (DEBUG_SHOW_INFO) { 10727 Log.v(TAG, " IntentFilter:"); 10728 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10729 } 10730 if (!intent.debugCheck()) { 10731 Log.w(TAG, "==> For Activity " + a.info.name); 10732 } 10733 addFilter(intent); 10734 } 10735 } 10736 10737 public final void removeActivity(PackageParser.Activity a, String type) { 10738 mActivities.remove(a.getComponentName()); 10739 if (DEBUG_SHOW_INFO) { 10740 Log.v(TAG, " " + type + " " 10741 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10742 : a.info.name) + ":"); 10743 Log.v(TAG, " Class=" + a.info.name); 10744 } 10745 final int NI = a.intents.size(); 10746 for (int j=0; j<NI; j++) { 10747 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10748 if (DEBUG_SHOW_INFO) { 10749 Log.v(TAG, " IntentFilter:"); 10750 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10751 } 10752 removeFilter(intent); 10753 } 10754 } 10755 10756 @Override 10757 protected boolean allowFilterResult( 10758 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10759 ActivityInfo filterAi = filter.activity.info; 10760 for (int i=dest.size()-1; i>=0; i--) { 10761 ActivityInfo destAi = dest.get(i).activityInfo; 10762 if (destAi.name == filterAi.name 10763 && destAi.packageName == filterAi.packageName) { 10764 return false; 10765 } 10766 } 10767 return true; 10768 } 10769 10770 @Override 10771 protected ActivityIntentInfo[] newArray(int size) { 10772 return new ActivityIntentInfo[size]; 10773 } 10774 10775 @Override 10776 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10777 if (!sUserManager.exists(userId)) return true; 10778 PackageParser.Package p = filter.activity.owner; 10779 if (p != null) { 10780 PackageSetting ps = (PackageSetting)p.mExtras; 10781 if (ps != null) { 10782 // System apps are never considered stopped for purposes of 10783 // filtering, because there may be no way for the user to 10784 // actually re-launch them. 10785 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10786 && ps.getStopped(userId); 10787 } 10788 } 10789 return false; 10790 } 10791 10792 @Override 10793 protected boolean isPackageForFilter(String packageName, 10794 PackageParser.ActivityIntentInfo info) { 10795 return packageName.equals(info.activity.owner.packageName); 10796 } 10797 10798 @Override 10799 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10800 int match, int userId) { 10801 if (!sUserManager.exists(userId)) return null; 10802 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10803 return null; 10804 } 10805 final PackageParser.Activity activity = info.activity; 10806 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10807 if (ps == null) { 10808 return null; 10809 } 10810 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10811 ps.readUserState(userId), userId); 10812 if (ai == null) { 10813 return null; 10814 } 10815 final ResolveInfo res = new ResolveInfo(); 10816 res.activityInfo = ai; 10817 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10818 res.filter = info; 10819 } 10820 if (info != null) { 10821 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10822 } 10823 res.priority = info.getPriority(); 10824 res.preferredOrder = activity.owner.mPreferredOrder; 10825 //System.out.println("Result: " + res.activityInfo.className + 10826 // " = " + res.priority); 10827 res.match = match; 10828 res.isDefault = info.hasDefault; 10829 res.labelRes = info.labelRes; 10830 res.nonLocalizedLabel = info.nonLocalizedLabel; 10831 if (userNeedsBadging(userId)) { 10832 res.noResourceId = true; 10833 } else { 10834 res.icon = info.icon; 10835 } 10836 res.iconResourceId = info.icon; 10837 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10838 return res; 10839 } 10840 10841 @Override 10842 protected void sortResults(List<ResolveInfo> results) { 10843 Collections.sort(results, mResolvePrioritySorter); 10844 } 10845 10846 @Override 10847 protected void dumpFilter(PrintWriter out, String prefix, 10848 PackageParser.ActivityIntentInfo filter) { 10849 out.print(prefix); out.print( 10850 Integer.toHexString(System.identityHashCode(filter.activity))); 10851 out.print(' '); 10852 filter.activity.printComponentShortName(out); 10853 out.print(" filter "); 10854 out.println(Integer.toHexString(System.identityHashCode(filter))); 10855 } 10856 10857 @Override 10858 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10859 return filter.activity; 10860 } 10861 10862 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10863 PackageParser.Activity activity = (PackageParser.Activity)label; 10864 out.print(prefix); out.print( 10865 Integer.toHexString(System.identityHashCode(activity))); 10866 out.print(' '); 10867 activity.printComponentShortName(out); 10868 if (count > 1) { 10869 out.print(" ("); out.print(count); out.print(" filters)"); 10870 } 10871 out.println(); 10872 } 10873 10874 // Keys are String (activity class name), values are Activity. 10875 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10876 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10877 private int mFlags; 10878 } 10879 10880 private final class ServiceIntentResolver 10881 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10882 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10883 boolean defaultOnly, int userId) { 10884 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10885 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10886 } 10887 10888 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10889 int userId) { 10890 if (!sUserManager.exists(userId)) return null; 10891 mFlags = flags; 10892 return super.queryIntent(intent, resolvedType, 10893 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10894 } 10895 10896 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10897 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10898 if (!sUserManager.exists(userId)) return null; 10899 if (packageServices == null) { 10900 return null; 10901 } 10902 mFlags = flags; 10903 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10904 final int N = packageServices.size(); 10905 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10906 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10907 10908 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10909 for (int i = 0; i < N; ++i) { 10910 intentFilters = packageServices.get(i).intents; 10911 if (intentFilters != null && intentFilters.size() > 0) { 10912 PackageParser.ServiceIntentInfo[] array = 10913 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10914 intentFilters.toArray(array); 10915 listCut.add(array); 10916 } 10917 } 10918 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10919 } 10920 10921 public final void addService(PackageParser.Service s) { 10922 mServices.put(s.getComponentName(), s); 10923 if (DEBUG_SHOW_INFO) { 10924 Log.v(TAG, " " 10925 + (s.info.nonLocalizedLabel != null 10926 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10927 Log.v(TAG, " Class=" + s.info.name); 10928 } 10929 final int NI = s.intents.size(); 10930 int j; 10931 for (j=0; j<NI; j++) { 10932 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10933 if (DEBUG_SHOW_INFO) { 10934 Log.v(TAG, " IntentFilter:"); 10935 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10936 } 10937 if (!intent.debugCheck()) { 10938 Log.w(TAG, "==> For Service " + s.info.name); 10939 } 10940 addFilter(intent); 10941 } 10942 } 10943 10944 public final void removeService(PackageParser.Service s) { 10945 mServices.remove(s.getComponentName()); 10946 if (DEBUG_SHOW_INFO) { 10947 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10948 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10949 Log.v(TAG, " Class=" + s.info.name); 10950 } 10951 final int NI = s.intents.size(); 10952 int j; 10953 for (j=0; j<NI; j++) { 10954 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10955 if (DEBUG_SHOW_INFO) { 10956 Log.v(TAG, " IntentFilter:"); 10957 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10958 } 10959 removeFilter(intent); 10960 } 10961 } 10962 10963 @Override 10964 protected boolean allowFilterResult( 10965 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10966 ServiceInfo filterSi = filter.service.info; 10967 for (int i=dest.size()-1; i>=0; i--) { 10968 ServiceInfo destAi = dest.get(i).serviceInfo; 10969 if (destAi.name == filterSi.name 10970 && destAi.packageName == filterSi.packageName) { 10971 return false; 10972 } 10973 } 10974 return true; 10975 } 10976 10977 @Override 10978 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10979 return new PackageParser.ServiceIntentInfo[size]; 10980 } 10981 10982 @Override 10983 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10984 if (!sUserManager.exists(userId)) return true; 10985 PackageParser.Package p = filter.service.owner; 10986 if (p != null) { 10987 PackageSetting ps = (PackageSetting)p.mExtras; 10988 if (ps != null) { 10989 // System apps are never considered stopped for purposes of 10990 // filtering, because there may be no way for the user to 10991 // actually re-launch them. 10992 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10993 && ps.getStopped(userId); 10994 } 10995 } 10996 return false; 10997 } 10998 10999 @Override 11000 protected boolean isPackageForFilter(String packageName, 11001 PackageParser.ServiceIntentInfo info) { 11002 return packageName.equals(info.service.owner.packageName); 11003 } 11004 11005 @Override 11006 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11007 int match, int userId) { 11008 if (!sUserManager.exists(userId)) return null; 11009 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11010 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11011 return null; 11012 } 11013 final PackageParser.Service service = info.service; 11014 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11015 if (ps == null) { 11016 return null; 11017 } 11018 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11019 ps.readUserState(userId), userId); 11020 if (si == null) { 11021 return null; 11022 } 11023 final ResolveInfo res = new ResolveInfo(); 11024 res.serviceInfo = si; 11025 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11026 res.filter = filter; 11027 } 11028 res.priority = info.getPriority(); 11029 res.preferredOrder = service.owner.mPreferredOrder; 11030 res.match = match; 11031 res.isDefault = info.hasDefault; 11032 res.labelRes = info.labelRes; 11033 res.nonLocalizedLabel = info.nonLocalizedLabel; 11034 res.icon = info.icon; 11035 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11036 return res; 11037 } 11038 11039 @Override 11040 protected void sortResults(List<ResolveInfo> results) { 11041 Collections.sort(results, mResolvePrioritySorter); 11042 } 11043 11044 @Override 11045 protected void dumpFilter(PrintWriter out, String prefix, 11046 PackageParser.ServiceIntentInfo filter) { 11047 out.print(prefix); out.print( 11048 Integer.toHexString(System.identityHashCode(filter.service))); 11049 out.print(' '); 11050 filter.service.printComponentShortName(out); 11051 out.print(" filter "); 11052 out.println(Integer.toHexString(System.identityHashCode(filter))); 11053 } 11054 11055 @Override 11056 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11057 return filter.service; 11058 } 11059 11060 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11061 PackageParser.Service service = (PackageParser.Service)label; 11062 out.print(prefix); out.print( 11063 Integer.toHexString(System.identityHashCode(service))); 11064 out.print(' '); 11065 service.printComponentShortName(out); 11066 if (count > 1) { 11067 out.print(" ("); out.print(count); out.print(" filters)"); 11068 } 11069 out.println(); 11070 } 11071 11072// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11073// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11074// final List<ResolveInfo> retList = Lists.newArrayList(); 11075// while (i.hasNext()) { 11076// final ResolveInfo resolveInfo = (ResolveInfo) i; 11077// if (isEnabledLP(resolveInfo.serviceInfo)) { 11078// retList.add(resolveInfo); 11079// } 11080// } 11081// return retList; 11082// } 11083 11084 // Keys are String (activity class name), values are Activity. 11085 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11086 = new ArrayMap<ComponentName, PackageParser.Service>(); 11087 private int mFlags; 11088 }; 11089 11090 private final class ProviderIntentResolver 11091 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11092 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11093 boolean defaultOnly, int userId) { 11094 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11095 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11096 } 11097 11098 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11099 int userId) { 11100 if (!sUserManager.exists(userId)) 11101 return null; 11102 mFlags = flags; 11103 return super.queryIntent(intent, resolvedType, 11104 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11105 } 11106 11107 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11108 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11109 if (!sUserManager.exists(userId)) 11110 return null; 11111 if (packageProviders == null) { 11112 return null; 11113 } 11114 mFlags = flags; 11115 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11116 final int N = packageProviders.size(); 11117 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11118 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11119 11120 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11121 for (int i = 0; i < N; ++i) { 11122 intentFilters = packageProviders.get(i).intents; 11123 if (intentFilters != null && intentFilters.size() > 0) { 11124 PackageParser.ProviderIntentInfo[] array = 11125 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11126 intentFilters.toArray(array); 11127 listCut.add(array); 11128 } 11129 } 11130 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11131 } 11132 11133 public final void addProvider(PackageParser.Provider p) { 11134 if (mProviders.containsKey(p.getComponentName())) { 11135 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11136 return; 11137 } 11138 11139 mProviders.put(p.getComponentName(), p); 11140 if (DEBUG_SHOW_INFO) { 11141 Log.v(TAG, " " 11142 + (p.info.nonLocalizedLabel != null 11143 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11144 Log.v(TAG, " Class=" + p.info.name); 11145 } 11146 final int NI = p.intents.size(); 11147 int j; 11148 for (j = 0; j < NI; j++) { 11149 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11150 if (DEBUG_SHOW_INFO) { 11151 Log.v(TAG, " IntentFilter:"); 11152 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11153 } 11154 if (!intent.debugCheck()) { 11155 Log.w(TAG, "==> For Provider " + p.info.name); 11156 } 11157 addFilter(intent); 11158 } 11159 } 11160 11161 public final void removeProvider(PackageParser.Provider p) { 11162 mProviders.remove(p.getComponentName()); 11163 if (DEBUG_SHOW_INFO) { 11164 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11165 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11166 Log.v(TAG, " Class=" + p.info.name); 11167 } 11168 final int NI = p.intents.size(); 11169 int j; 11170 for (j = 0; j < NI; j++) { 11171 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11172 if (DEBUG_SHOW_INFO) { 11173 Log.v(TAG, " IntentFilter:"); 11174 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11175 } 11176 removeFilter(intent); 11177 } 11178 } 11179 11180 @Override 11181 protected boolean allowFilterResult( 11182 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11183 ProviderInfo filterPi = filter.provider.info; 11184 for (int i = dest.size() - 1; i >= 0; i--) { 11185 ProviderInfo destPi = dest.get(i).providerInfo; 11186 if (destPi.name == filterPi.name 11187 && destPi.packageName == filterPi.packageName) { 11188 return false; 11189 } 11190 } 11191 return true; 11192 } 11193 11194 @Override 11195 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11196 return new PackageParser.ProviderIntentInfo[size]; 11197 } 11198 11199 @Override 11200 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11201 if (!sUserManager.exists(userId)) 11202 return true; 11203 PackageParser.Package p = filter.provider.owner; 11204 if (p != null) { 11205 PackageSetting ps = (PackageSetting) p.mExtras; 11206 if (ps != null) { 11207 // System apps are never considered stopped for purposes of 11208 // filtering, because there may be no way for the user to 11209 // actually re-launch them. 11210 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11211 && ps.getStopped(userId); 11212 } 11213 } 11214 return false; 11215 } 11216 11217 @Override 11218 protected boolean isPackageForFilter(String packageName, 11219 PackageParser.ProviderIntentInfo info) { 11220 return packageName.equals(info.provider.owner.packageName); 11221 } 11222 11223 @Override 11224 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11225 int match, int userId) { 11226 if (!sUserManager.exists(userId)) 11227 return null; 11228 final PackageParser.ProviderIntentInfo info = filter; 11229 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11230 return null; 11231 } 11232 final PackageParser.Provider provider = info.provider; 11233 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11234 if (ps == null) { 11235 return null; 11236 } 11237 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11238 ps.readUserState(userId), userId); 11239 if (pi == null) { 11240 return null; 11241 } 11242 final ResolveInfo res = new ResolveInfo(); 11243 res.providerInfo = pi; 11244 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11245 res.filter = filter; 11246 } 11247 res.priority = info.getPriority(); 11248 res.preferredOrder = provider.owner.mPreferredOrder; 11249 res.match = match; 11250 res.isDefault = info.hasDefault; 11251 res.labelRes = info.labelRes; 11252 res.nonLocalizedLabel = info.nonLocalizedLabel; 11253 res.icon = info.icon; 11254 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11255 return res; 11256 } 11257 11258 @Override 11259 protected void sortResults(List<ResolveInfo> results) { 11260 Collections.sort(results, mResolvePrioritySorter); 11261 } 11262 11263 @Override 11264 protected void dumpFilter(PrintWriter out, String prefix, 11265 PackageParser.ProviderIntentInfo filter) { 11266 out.print(prefix); 11267 out.print( 11268 Integer.toHexString(System.identityHashCode(filter.provider))); 11269 out.print(' '); 11270 filter.provider.printComponentShortName(out); 11271 out.print(" filter "); 11272 out.println(Integer.toHexString(System.identityHashCode(filter))); 11273 } 11274 11275 @Override 11276 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11277 return filter.provider; 11278 } 11279 11280 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11281 PackageParser.Provider provider = (PackageParser.Provider)label; 11282 out.print(prefix); out.print( 11283 Integer.toHexString(System.identityHashCode(provider))); 11284 out.print(' '); 11285 provider.printComponentShortName(out); 11286 if (count > 1) { 11287 out.print(" ("); out.print(count); out.print(" filters)"); 11288 } 11289 out.println(); 11290 } 11291 11292 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11293 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11294 private int mFlags; 11295 } 11296 11297 private static final class EphemeralIntentResolver 11298 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11299 @Override 11300 protected EphemeralResolveIntentInfo[] newArray(int size) { 11301 return new EphemeralResolveIntentInfo[size]; 11302 } 11303 11304 @Override 11305 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11306 return true; 11307 } 11308 11309 @Override 11310 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11311 int userId) { 11312 if (!sUserManager.exists(userId)) { 11313 return null; 11314 } 11315 return info.getEphemeralResolveInfo(); 11316 } 11317 } 11318 11319 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11320 new Comparator<ResolveInfo>() { 11321 public int compare(ResolveInfo r1, ResolveInfo r2) { 11322 int v1 = r1.priority; 11323 int v2 = r2.priority; 11324 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11325 if (v1 != v2) { 11326 return (v1 > v2) ? -1 : 1; 11327 } 11328 v1 = r1.preferredOrder; 11329 v2 = r2.preferredOrder; 11330 if (v1 != v2) { 11331 return (v1 > v2) ? -1 : 1; 11332 } 11333 if (r1.isDefault != r2.isDefault) { 11334 return r1.isDefault ? -1 : 1; 11335 } 11336 v1 = r1.match; 11337 v2 = r2.match; 11338 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11339 if (v1 != v2) { 11340 return (v1 > v2) ? -1 : 1; 11341 } 11342 if (r1.system != r2.system) { 11343 return r1.system ? -1 : 1; 11344 } 11345 if (r1.activityInfo != null) { 11346 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11347 } 11348 if (r1.serviceInfo != null) { 11349 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11350 } 11351 if (r1.providerInfo != null) { 11352 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11353 } 11354 return 0; 11355 } 11356 }; 11357 11358 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11359 new Comparator<ProviderInfo>() { 11360 public int compare(ProviderInfo p1, ProviderInfo p2) { 11361 final int v1 = p1.initOrder; 11362 final int v2 = p2.initOrder; 11363 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11364 } 11365 }; 11366 11367 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11368 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11369 final int[] userIds) { 11370 mHandler.post(new Runnable() { 11371 @Override 11372 public void run() { 11373 try { 11374 final IActivityManager am = ActivityManagerNative.getDefault(); 11375 if (am == null) return; 11376 final int[] resolvedUserIds; 11377 if (userIds == null) { 11378 resolvedUserIds = am.getRunningUserIds(); 11379 } else { 11380 resolvedUserIds = userIds; 11381 } 11382 for (int id : resolvedUserIds) { 11383 final Intent intent = new Intent(action, 11384 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11385 if (extras != null) { 11386 intent.putExtras(extras); 11387 } 11388 if (targetPkg != null) { 11389 intent.setPackage(targetPkg); 11390 } 11391 // Modify the UID when posting to other users 11392 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11393 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11394 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11395 intent.putExtra(Intent.EXTRA_UID, uid); 11396 } 11397 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11398 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11399 if (DEBUG_BROADCASTS) { 11400 RuntimeException here = new RuntimeException("here"); 11401 here.fillInStackTrace(); 11402 Slog.d(TAG, "Sending to user " + id + ": " 11403 + intent.toShortString(false, true, false, false) 11404 + " " + intent.getExtras(), here); 11405 } 11406 am.broadcastIntent(null, intent, null, finishedReceiver, 11407 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11408 null, finishedReceiver != null, false, id); 11409 } 11410 } catch (RemoteException ex) { 11411 } 11412 } 11413 }); 11414 } 11415 11416 /** 11417 * Check if the external storage media is available. This is true if there 11418 * is a mounted external storage medium or if the external storage is 11419 * emulated. 11420 */ 11421 private boolean isExternalMediaAvailable() { 11422 return mMediaMounted || Environment.isExternalStorageEmulated(); 11423 } 11424 11425 @Override 11426 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11427 // writer 11428 synchronized (mPackages) { 11429 if (!isExternalMediaAvailable()) { 11430 // If the external storage is no longer mounted at this point, 11431 // the caller may not have been able to delete all of this 11432 // packages files and can not delete any more. Bail. 11433 return null; 11434 } 11435 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11436 if (lastPackage != null) { 11437 pkgs.remove(lastPackage); 11438 } 11439 if (pkgs.size() > 0) { 11440 return pkgs.get(0); 11441 } 11442 } 11443 return null; 11444 } 11445 11446 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11447 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11448 userId, andCode ? 1 : 0, packageName); 11449 if (mSystemReady) { 11450 msg.sendToTarget(); 11451 } else { 11452 if (mPostSystemReadyMessages == null) { 11453 mPostSystemReadyMessages = new ArrayList<>(); 11454 } 11455 mPostSystemReadyMessages.add(msg); 11456 } 11457 } 11458 11459 void startCleaningPackages() { 11460 // reader 11461 if (!isExternalMediaAvailable()) { 11462 return; 11463 } 11464 synchronized (mPackages) { 11465 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11466 return; 11467 } 11468 } 11469 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11470 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11471 IActivityManager am = ActivityManagerNative.getDefault(); 11472 if (am != null) { 11473 try { 11474 am.startService(null, intent, null, mContext.getOpPackageName(), 11475 UserHandle.USER_SYSTEM); 11476 } catch (RemoteException e) { 11477 } 11478 } 11479 } 11480 11481 @Override 11482 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11483 int installFlags, String installerPackageName, int userId) { 11484 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11485 11486 final int callingUid = Binder.getCallingUid(); 11487 enforceCrossUserPermission(callingUid, userId, 11488 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11489 11490 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11491 try { 11492 if (observer != null) { 11493 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11494 } 11495 } catch (RemoteException re) { 11496 } 11497 return; 11498 } 11499 11500 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11501 installFlags |= PackageManager.INSTALL_FROM_ADB; 11502 11503 } else { 11504 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11505 // about installerPackageName. 11506 11507 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11508 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11509 } 11510 11511 UserHandle user; 11512 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11513 user = UserHandle.ALL; 11514 } else { 11515 user = new UserHandle(userId); 11516 } 11517 11518 // Only system components can circumvent runtime permissions when installing. 11519 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11520 && mContext.checkCallingOrSelfPermission(Manifest.permission 11521 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11522 throw new SecurityException("You need the " 11523 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11524 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11525 } 11526 11527 final File originFile = new File(originPath); 11528 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11529 11530 final Message msg = mHandler.obtainMessage(INIT_COPY); 11531 final VerificationInfo verificationInfo = new VerificationInfo( 11532 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11533 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11534 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11535 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11536 null /*certificates*/); 11537 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11538 msg.obj = params; 11539 11540 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11541 System.identityHashCode(msg.obj)); 11542 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11543 System.identityHashCode(msg.obj)); 11544 11545 mHandler.sendMessage(msg); 11546 } 11547 11548 void installStage(String packageName, File stagedDir, String stagedCid, 11549 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11550 String installerPackageName, int installerUid, UserHandle user, 11551 Certificate[][] certificates) { 11552 if (DEBUG_EPHEMERAL) { 11553 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11554 Slog.d(TAG, "Ephemeral install of " + packageName); 11555 } 11556 } 11557 final VerificationInfo verificationInfo = new VerificationInfo( 11558 sessionParams.originatingUri, sessionParams.referrerUri, 11559 sessionParams.originatingUid, installerUid); 11560 11561 final OriginInfo origin; 11562 if (stagedDir != null) { 11563 origin = OriginInfo.fromStagedFile(stagedDir); 11564 } else { 11565 origin = OriginInfo.fromStagedContainer(stagedCid); 11566 } 11567 11568 final Message msg = mHandler.obtainMessage(INIT_COPY); 11569 final InstallParams params = new InstallParams(origin, null, observer, 11570 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11571 verificationInfo, user, sessionParams.abiOverride, 11572 sessionParams.grantedRuntimePermissions, certificates); 11573 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11574 msg.obj = params; 11575 11576 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11577 System.identityHashCode(msg.obj)); 11578 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11579 System.identityHashCode(msg.obj)); 11580 11581 mHandler.sendMessage(msg); 11582 } 11583 11584 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11585 int userId) { 11586 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11587 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11588 } 11589 11590 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11591 int appId, int userId) { 11592 Bundle extras = new Bundle(1); 11593 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11594 11595 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11596 packageName, extras, 0, null, null, new int[] {userId}); 11597 try { 11598 IActivityManager am = ActivityManagerNative.getDefault(); 11599 if (isSystem && am.isUserRunning(userId, 0)) { 11600 // The just-installed/enabled app is bundled on the system, so presumed 11601 // to be able to run automatically without needing an explicit launch. 11602 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11603 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11604 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11605 .setPackage(packageName); 11606 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11607 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11608 } 11609 } catch (RemoteException e) { 11610 // shouldn't happen 11611 Slog.w(TAG, "Unable to bootstrap installed package", e); 11612 } 11613 } 11614 11615 @Override 11616 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11617 int userId) { 11618 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11619 PackageSetting pkgSetting; 11620 final int uid = Binder.getCallingUid(); 11621 enforceCrossUserPermission(uid, userId, 11622 true /* requireFullPermission */, true /* checkShell */, 11623 "setApplicationHiddenSetting for user " + userId); 11624 11625 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11626 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11627 return false; 11628 } 11629 11630 long callingId = Binder.clearCallingIdentity(); 11631 try { 11632 boolean sendAdded = false; 11633 boolean sendRemoved = false; 11634 // writer 11635 synchronized (mPackages) { 11636 pkgSetting = mSettings.mPackages.get(packageName); 11637 if (pkgSetting == null) { 11638 return false; 11639 } 11640 if (pkgSetting.getHidden(userId) != hidden) { 11641 pkgSetting.setHidden(hidden, userId); 11642 mSettings.writePackageRestrictionsLPr(userId); 11643 if (hidden) { 11644 sendRemoved = true; 11645 } else { 11646 sendAdded = true; 11647 } 11648 } 11649 } 11650 if (sendAdded) { 11651 sendPackageAddedForUser(packageName, pkgSetting, userId); 11652 return true; 11653 } 11654 if (sendRemoved) { 11655 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11656 "hiding pkg"); 11657 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11658 return true; 11659 } 11660 } finally { 11661 Binder.restoreCallingIdentity(callingId); 11662 } 11663 return false; 11664 } 11665 11666 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11667 int userId) { 11668 final PackageRemovedInfo info = new PackageRemovedInfo(); 11669 info.removedPackage = packageName; 11670 info.removedUsers = new int[] {userId}; 11671 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11672 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11673 } 11674 11675 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11676 if (pkgList.length > 0) { 11677 Bundle extras = new Bundle(1); 11678 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11679 11680 sendPackageBroadcast( 11681 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11682 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11683 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11684 new int[] {userId}); 11685 } 11686 } 11687 11688 /** 11689 * Returns true if application is not found or there was an error. Otherwise it returns 11690 * the hidden state of the package for the given user. 11691 */ 11692 @Override 11693 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11694 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11695 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11696 true /* requireFullPermission */, false /* checkShell */, 11697 "getApplicationHidden for user " + userId); 11698 PackageSetting pkgSetting; 11699 long callingId = Binder.clearCallingIdentity(); 11700 try { 11701 // writer 11702 synchronized (mPackages) { 11703 pkgSetting = mSettings.mPackages.get(packageName); 11704 if (pkgSetting == null) { 11705 return true; 11706 } 11707 return pkgSetting.getHidden(userId); 11708 } 11709 } finally { 11710 Binder.restoreCallingIdentity(callingId); 11711 } 11712 } 11713 11714 /** 11715 * @hide 11716 */ 11717 @Override 11718 public int installExistingPackageAsUser(String packageName, int userId) { 11719 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11720 null); 11721 PackageSetting pkgSetting; 11722 final int uid = Binder.getCallingUid(); 11723 enforceCrossUserPermission(uid, userId, 11724 true /* requireFullPermission */, true /* checkShell */, 11725 "installExistingPackage for user " + userId); 11726 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11727 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11728 } 11729 11730 long callingId = Binder.clearCallingIdentity(); 11731 try { 11732 boolean installed = false; 11733 11734 // writer 11735 synchronized (mPackages) { 11736 pkgSetting = mSettings.mPackages.get(packageName); 11737 if (pkgSetting == null) { 11738 return PackageManager.INSTALL_FAILED_INVALID_URI; 11739 } 11740 if (!pkgSetting.getInstalled(userId)) { 11741 pkgSetting.setInstalled(true, userId); 11742 pkgSetting.setHidden(false, userId); 11743 mSettings.writePackageRestrictionsLPr(userId); 11744 installed = true; 11745 } 11746 } 11747 11748 if (installed) { 11749 if (pkgSetting.pkg != null) { 11750 synchronized (mInstallLock) { 11751 // We don't need to freeze for a brand new install 11752 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11753 } 11754 } 11755 sendPackageAddedForUser(packageName, pkgSetting, userId); 11756 } 11757 } finally { 11758 Binder.restoreCallingIdentity(callingId); 11759 } 11760 11761 return PackageManager.INSTALL_SUCCEEDED; 11762 } 11763 11764 boolean isUserRestricted(int userId, String restrictionKey) { 11765 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11766 if (restrictions.getBoolean(restrictionKey, false)) { 11767 Log.w(TAG, "User is restricted: " + restrictionKey); 11768 return true; 11769 } 11770 return false; 11771 } 11772 11773 @Override 11774 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11775 int userId) { 11776 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11777 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11778 true /* requireFullPermission */, true /* checkShell */, 11779 "setPackagesSuspended for user " + userId); 11780 11781 if (ArrayUtils.isEmpty(packageNames)) { 11782 return packageNames; 11783 } 11784 11785 // List of package names for whom the suspended state has changed. 11786 List<String> changedPackages = new ArrayList<>(packageNames.length); 11787 // List of package names for whom the suspended state is not set as requested in this 11788 // method. 11789 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11790 long callingId = Binder.clearCallingIdentity(); 11791 try { 11792 for (int i = 0; i < packageNames.length; i++) { 11793 String packageName = packageNames[i]; 11794 boolean changed = false; 11795 final int appId; 11796 synchronized (mPackages) { 11797 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11798 if (pkgSetting == null) { 11799 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11800 + "\". Skipping suspending/un-suspending."); 11801 unactionedPackages.add(packageName); 11802 continue; 11803 } 11804 appId = pkgSetting.appId; 11805 if (pkgSetting.getSuspended(userId) != suspended) { 11806 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11807 unactionedPackages.add(packageName); 11808 continue; 11809 } 11810 pkgSetting.setSuspended(suspended, userId); 11811 mSettings.writePackageRestrictionsLPr(userId); 11812 changed = true; 11813 changedPackages.add(packageName); 11814 } 11815 } 11816 11817 if (changed && suspended) { 11818 killApplication(packageName, UserHandle.getUid(userId, appId), 11819 "suspending package"); 11820 } 11821 } 11822 } finally { 11823 Binder.restoreCallingIdentity(callingId); 11824 } 11825 11826 if (!changedPackages.isEmpty()) { 11827 sendPackagesSuspendedForUser(changedPackages.toArray( 11828 new String[changedPackages.size()]), userId, suspended); 11829 } 11830 11831 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11832 } 11833 11834 @Override 11835 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11836 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11837 true /* requireFullPermission */, false /* checkShell */, 11838 "isPackageSuspendedForUser for user " + userId); 11839 synchronized (mPackages) { 11840 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11841 if (pkgSetting == null) { 11842 throw new IllegalArgumentException("Unknown target package: " + packageName); 11843 } 11844 return pkgSetting.getSuspended(userId); 11845 } 11846 } 11847 11848 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11849 if (isPackageDeviceAdmin(packageName, userId)) { 11850 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11851 + "\": has an active device admin"); 11852 return false; 11853 } 11854 11855 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11856 if (packageName.equals(activeLauncherPackageName)) { 11857 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11858 + "\": contains the active launcher"); 11859 return false; 11860 } 11861 11862 if (packageName.equals(mRequiredInstallerPackage)) { 11863 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11864 + "\": required for package installation"); 11865 return false; 11866 } 11867 11868 if (packageName.equals(mRequiredVerifierPackage)) { 11869 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11870 + "\": required for package verification"); 11871 return false; 11872 } 11873 11874 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11875 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11876 + "\": is the default dialer"); 11877 return false; 11878 } 11879 11880 return true; 11881 } 11882 11883 private String getActiveLauncherPackageName(int userId) { 11884 Intent intent = new Intent(Intent.ACTION_MAIN); 11885 intent.addCategory(Intent.CATEGORY_HOME); 11886 ResolveInfo resolveInfo = resolveIntent( 11887 intent, 11888 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11889 PackageManager.MATCH_DEFAULT_ONLY, 11890 userId); 11891 11892 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11893 } 11894 11895 private String getDefaultDialerPackageName(int userId) { 11896 synchronized (mPackages) { 11897 return mSettings.getDefaultDialerPackageNameLPw(userId); 11898 } 11899 } 11900 11901 @Override 11902 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11903 mContext.enforceCallingOrSelfPermission( 11904 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11905 "Only package verification agents can verify applications"); 11906 11907 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11908 final PackageVerificationResponse response = new PackageVerificationResponse( 11909 verificationCode, Binder.getCallingUid()); 11910 msg.arg1 = id; 11911 msg.obj = response; 11912 mHandler.sendMessage(msg); 11913 } 11914 11915 @Override 11916 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11917 long millisecondsToDelay) { 11918 mContext.enforceCallingOrSelfPermission( 11919 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11920 "Only package verification agents can extend verification timeouts"); 11921 11922 final PackageVerificationState state = mPendingVerification.get(id); 11923 final PackageVerificationResponse response = new PackageVerificationResponse( 11924 verificationCodeAtTimeout, Binder.getCallingUid()); 11925 11926 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11927 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11928 } 11929 if (millisecondsToDelay < 0) { 11930 millisecondsToDelay = 0; 11931 } 11932 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11933 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11934 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11935 } 11936 11937 if ((state != null) && !state.timeoutExtended()) { 11938 state.extendTimeout(); 11939 11940 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11941 msg.arg1 = id; 11942 msg.obj = response; 11943 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11944 } 11945 } 11946 11947 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11948 int verificationCode, UserHandle user) { 11949 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11950 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11951 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11952 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11953 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11954 11955 mContext.sendBroadcastAsUser(intent, user, 11956 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11957 } 11958 11959 private ComponentName matchComponentForVerifier(String packageName, 11960 List<ResolveInfo> receivers) { 11961 ActivityInfo targetReceiver = null; 11962 11963 final int NR = receivers.size(); 11964 for (int i = 0; i < NR; i++) { 11965 final ResolveInfo info = receivers.get(i); 11966 if (info.activityInfo == null) { 11967 continue; 11968 } 11969 11970 if (packageName.equals(info.activityInfo.packageName)) { 11971 targetReceiver = info.activityInfo; 11972 break; 11973 } 11974 } 11975 11976 if (targetReceiver == null) { 11977 return null; 11978 } 11979 11980 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11981 } 11982 11983 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11984 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11985 if (pkgInfo.verifiers.length == 0) { 11986 return null; 11987 } 11988 11989 final int N = pkgInfo.verifiers.length; 11990 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11991 for (int i = 0; i < N; i++) { 11992 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11993 11994 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11995 receivers); 11996 if (comp == null) { 11997 continue; 11998 } 11999 12000 final int verifierUid = getUidForVerifier(verifierInfo); 12001 if (verifierUid == -1) { 12002 continue; 12003 } 12004 12005 if (DEBUG_VERIFY) { 12006 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12007 + " with the correct signature"); 12008 } 12009 sufficientVerifiers.add(comp); 12010 verificationState.addSufficientVerifier(verifierUid); 12011 } 12012 12013 return sufficientVerifiers; 12014 } 12015 12016 private int getUidForVerifier(VerifierInfo verifierInfo) { 12017 synchronized (mPackages) { 12018 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12019 if (pkg == null) { 12020 return -1; 12021 } else if (pkg.mSignatures.length != 1) { 12022 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12023 + " has more than one signature; ignoring"); 12024 return -1; 12025 } 12026 12027 /* 12028 * If the public key of the package's signature does not match 12029 * our expected public key, then this is a different package and 12030 * we should skip. 12031 */ 12032 12033 final byte[] expectedPublicKey; 12034 try { 12035 final Signature verifierSig = pkg.mSignatures[0]; 12036 final PublicKey publicKey = verifierSig.getPublicKey(); 12037 expectedPublicKey = publicKey.getEncoded(); 12038 } catch (CertificateException e) { 12039 return -1; 12040 } 12041 12042 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12043 12044 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12045 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12046 + " does not have the expected public key; ignoring"); 12047 return -1; 12048 } 12049 12050 return pkg.applicationInfo.uid; 12051 } 12052 } 12053 12054 @Override 12055 public void finishPackageInstall(int token, boolean didLaunch) { 12056 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12057 12058 if (DEBUG_INSTALL) { 12059 Slog.v(TAG, "BM finishing package install for " + token); 12060 } 12061 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12062 12063 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12064 mHandler.sendMessage(msg); 12065 } 12066 12067 /** 12068 * Get the verification agent timeout. 12069 * 12070 * @return verification timeout in milliseconds 12071 */ 12072 private long getVerificationTimeout() { 12073 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12074 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12075 DEFAULT_VERIFICATION_TIMEOUT); 12076 } 12077 12078 /** 12079 * Get the default verification agent response code. 12080 * 12081 * @return default verification response code 12082 */ 12083 private int getDefaultVerificationResponse() { 12084 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12085 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12086 DEFAULT_VERIFICATION_RESPONSE); 12087 } 12088 12089 /** 12090 * Check whether or not package verification has been enabled. 12091 * 12092 * @return true if verification should be performed 12093 */ 12094 private boolean isVerificationEnabled(int userId, int installFlags) { 12095 if (!DEFAULT_VERIFY_ENABLE) { 12096 return false; 12097 } 12098 // Ephemeral apps don't get the full verification treatment 12099 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12100 if (DEBUG_EPHEMERAL) { 12101 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12102 } 12103 return false; 12104 } 12105 12106 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12107 12108 // Check if installing from ADB 12109 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12110 // Do not run verification in a test harness environment 12111 if (ActivityManager.isRunningInTestHarness()) { 12112 return false; 12113 } 12114 if (ensureVerifyAppsEnabled) { 12115 return true; 12116 } 12117 // Check if the developer does not want package verification for ADB installs 12118 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12119 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12120 return false; 12121 } 12122 } 12123 12124 if (ensureVerifyAppsEnabled) { 12125 return true; 12126 } 12127 12128 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12129 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12130 } 12131 12132 @Override 12133 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12134 throws RemoteException { 12135 mContext.enforceCallingOrSelfPermission( 12136 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12137 "Only intentfilter verification agents can verify applications"); 12138 12139 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12140 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12141 Binder.getCallingUid(), verificationCode, failedDomains); 12142 msg.arg1 = id; 12143 msg.obj = response; 12144 mHandler.sendMessage(msg); 12145 } 12146 12147 @Override 12148 public int getIntentVerificationStatus(String packageName, int userId) { 12149 synchronized (mPackages) { 12150 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12151 } 12152 } 12153 12154 @Override 12155 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12156 mContext.enforceCallingOrSelfPermission( 12157 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12158 12159 boolean result = false; 12160 synchronized (mPackages) { 12161 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12162 } 12163 if (result) { 12164 scheduleWritePackageRestrictionsLocked(userId); 12165 } 12166 return result; 12167 } 12168 12169 @Override 12170 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12171 String packageName) { 12172 synchronized (mPackages) { 12173 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12174 } 12175 } 12176 12177 @Override 12178 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12179 if (TextUtils.isEmpty(packageName)) { 12180 return ParceledListSlice.emptyList(); 12181 } 12182 synchronized (mPackages) { 12183 PackageParser.Package pkg = mPackages.get(packageName); 12184 if (pkg == null || pkg.activities == null) { 12185 return ParceledListSlice.emptyList(); 12186 } 12187 final int count = pkg.activities.size(); 12188 ArrayList<IntentFilter> result = new ArrayList<>(); 12189 for (int n=0; n<count; n++) { 12190 PackageParser.Activity activity = pkg.activities.get(n); 12191 if (activity.intents != null && activity.intents.size() > 0) { 12192 result.addAll(activity.intents); 12193 } 12194 } 12195 return new ParceledListSlice<>(result); 12196 } 12197 } 12198 12199 @Override 12200 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12201 mContext.enforceCallingOrSelfPermission( 12202 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12203 12204 synchronized (mPackages) { 12205 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12206 if (packageName != null) { 12207 result |= updateIntentVerificationStatus(packageName, 12208 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12209 userId); 12210 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12211 packageName, userId); 12212 } 12213 return result; 12214 } 12215 } 12216 12217 @Override 12218 public String getDefaultBrowserPackageName(int userId) { 12219 synchronized (mPackages) { 12220 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12221 } 12222 } 12223 12224 /** 12225 * Get the "allow unknown sources" setting. 12226 * 12227 * @return the current "allow unknown sources" setting 12228 */ 12229 private int getUnknownSourcesSettings() { 12230 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12231 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12232 -1); 12233 } 12234 12235 @Override 12236 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12237 final int uid = Binder.getCallingUid(); 12238 // writer 12239 synchronized (mPackages) { 12240 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12241 if (targetPackageSetting == null) { 12242 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12243 } 12244 12245 PackageSetting installerPackageSetting; 12246 if (installerPackageName != null) { 12247 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12248 if (installerPackageSetting == null) { 12249 throw new IllegalArgumentException("Unknown installer package: " 12250 + installerPackageName); 12251 } 12252 } else { 12253 installerPackageSetting = null; 12254 } 12255 12256 Signature[] callerSignature; 12257 Object obj = mSettings.getUserIdLPr(uid); 12258 if (obj != null) { 12259 if (obj instanceof SharedUserSetting) { 12260 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12261 } else if (obj instanceof PackageSetting) { 12262 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12263 } else { 12264 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12265 } 12266 } else { 12267 throw new SecurityException("Unknown calling UID: " + uid); 12268 } 12269 12270 // Verify: can't set installerPackageName to a package that is 12271 // not signed with the same cert as the caller. 12272 if (installerPackageSetting != null) { 12273 if (compareSignatures(callerSignature, 12274 installerPackageSetting.signatures.mSignatures) 12275 != PackageManager.SIGNATURE_MATCH) { 12276 throw new SecurityException( 12277 "Caller does not have same cert as new installer package " 12278 + installerPackageName); 12279 } 12280 } 12281 12282 // Verify: if target already has an installer package, it must 12283 // be signed with the same cert as the caller. 12284 if (targetPackageSetting.installerPackageName != null) { 12285 PackageSetting setting = mSettings.mPackages.get( 12286 targetPackageSetting.installerPackageName); 12287 // If the currently set package isn't valid, then it's always 12288 // okay to change it. 12289 if (setting != null) { 12290 if (compareSignatures(callerSignature, 12291 setting.signatures.mSignatures) 12292 != PackageManager.SIGNATURE_MATCH) { 12293 throw new SecurityException( 12294 "Caller does not have same cert as old installer package " 12295 + targetPackageSetting.installerPackageName); 12296 } 12297 } 12298 } 12299 12300 // Okay! 12301 targetPackageSetting.installerPackageName = installerPackageName; 12302 if (installerPackageName != null) { 12303 mSettings.mInstallerPackages.add(installerPackageName); 12304 } 12305 scheduleWriteSettingsLocked(); 12306 } 12307 } 12308 12309 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12310 // Queue up an async operation since the package installation may take a little while. 12311 mHandler.post(new Runnable() { 12312 public void run() { 12313 mHandler.removeCallbacks(this); 12314 // Result object to be returned 12315 PackageInstalledInfo res = new PackageInstalledInfo(); 12316 res.setReturnCode(currentStatus); 12317 res.uid = -1; 12318 res.pkg = null; 12319 res.removedInfo = null; 12320 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12321 args.doPreInstall(res.returnCode); 12322 synchronized (mInstallLock) { 12323 installPackageTracedLI(args, res); 12324 } 12325 args.doPostInstall(res.returnCode, res.uid); 12326 } 12327 12328 // A restore should be performed at this point if (a) the install 12329 // succeeded, (b) the operation is not an update, and (c) the new 12330 // package has not opted out of backup participation. 12331 final boolean update = res.removedInfo != null 12332 && res.removedInfo.removedPackage != null; 12333 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12334 boolean doRestore = !update 12335 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12336 12337 // Set up the post-install work request bookkeeping. This will be used 12338 // and cleaned up by the post-install event handling regardless of whether 12339 // there's a restore pass performed. Token values are >= 1. 12340 int token; 12341 if (mNextInstallToken < 0) mNextInstallToken = 1; 12342 token = mNextInstallToken++; 12343 12344 PostInstallData data = new PostInstallData(args, res); 12345 mRunningInstalls.put(token, data); 12346 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12347 12348 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12349 // Pass responsibility to the Backup Manager. It will perform a 12350 // restore if appropriate, then pass responsibility back to the 12351 // Package Manager to run the post-install observer callbacks 12352 // and broadcasts. 12353 IBackupManager bm = IBackupManager.Stub.asInterface( 12354 ServiceManager.getService(Context.BACKUP_SERVICE)); 12355 if (bm != null) { 12356 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12357 + " to BM for possible restore"); 12358 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12359 try { 12360 // TODO: http://b/22388012 12361 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12362 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12363 } else { 12364 doRestore = false; 12365 } 12366 } catch (RemoteException e) { 12367 // can't happen; the backup manager is local 12368 } catch (Exception e) { 12369 Slog.e(TAG, "Exception trying to enqueue restore", e); 12370 doRestore = false; 12371 } 12372 } else { 12373 Slog.e(TAG, "Backup Manager not found!"); 12374 doRestore = false; 12375 } 12376 } 12377 12378 if (!doRestore) { 12379 // No restore possible, or the Backup Manager was mysteriously not 12380 // available -- just fire the post-install work request directly. 12381 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12382 12383 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12384 12385 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12386 mHandler.sendMessage(msg); 12387 } 12388 } 12389 }); 12390 } 12391 12392 /** 12393 * Callback from PackageSettings whenever an app is first transitioned out of the 12394 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12395 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12396 * here whether the app is the target of an ongoing install, and only send the 12397 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12398 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12399 * handling. 12400 */ 12401 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12402 // Serialize this with the rest of the install-process message chain. In the 12403 // restore-at-install case, this Runnable will necessarily run before the 12404 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12405 // are coherent. In the non-restore case, the app has already completed install 12406 // and been launched through some other means, so it is not in a problematic 12407 // state for observers to see the FIRST_LAUNCH signal. 12408 mHandler.post(new Runnable() { 12409 @Override 12410 public void run() { 12411 for (int i = 0; i < mRunningInstalls.size(); i++) { 12412 final PostInstallData data = mRunningInstalls.valueAt(i); 12413 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12414 // right package; but is it for the right user? 12415 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12416 if (userId == data.res.newUsers[uIndex]) { 12417 if (DEBUG_BACKUP) { 12418 Slog.i(TAG, "Package " + pkgName 12419 + " being restored so deferring FIRST_LAUNCH"); 12420 } 12421 return; 12422 } 12423 } 12424 } 12425 } 12426 // didn't find it, so not being restored 12427 if (DEBUG_BACKUP) { 12428 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12429 } 12430 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12431 } 12432 }); 12433 } 12434 12435 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12436 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12437 installerPkg, null, userIds); 12438 } 12439 12440 private abstract class HandlerParams { 12441 private static final int MAX_RETRIES = 4; 12442 12443 /** 12444 * Number of times startCopy() has been attempted and had a non-fatal 12445 * error. 12446 */ 12447 private int mRetries = 0; 12448 12449 /** User handle for the user requesting the information or installation. */ 12450 private final UserHandle mUser; 12451 String traceMethod; 12452 int traceCookie; 12453 12454 HandlerParams(UserHandle user) { 12455 mUser = user; 12456 } 12457 12458 UserHandle getUser() { 12459 return mUser; 12460 } 12461 12462 HandlerParams setTraceMethod(String traceMethod) { 12463 this.traceMethod = traceMethod; 12464 return this; 12465 } 12466 12467 HandlerParams setTraceCookie(int traceCookie) { 12468 this.traceCookie = traceCookie; 12469 return this; 12470 } 12471 12472 final boolean startCopy() { 12473 boolean res; 12474 try { 12475 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12476 12477 if (++mRetries > MAX_RETRIES) { 12478 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12479 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12480 handleServiceError(); 12481 return false; 12482 } else { 12483 handleStartCopy(); 12484 res = true; 12485 } 12486 } catch (RemoteException e) { 12487 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12488 mHandler.sendEmptyMessage(MCS_RECONNECT); 12489 res = false; 12490 } 12491 handleReturnCode(); 12492 return res; 12493 } 12494 12495 final void serviceError() { 12496 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12497 handleServiceError(); 12498 handleReturnCode(); 12499 } 12500 12501 abstract void handleStartCopy() throws RemoteException; 12502 abstract void handleServiceError(); 12503 abstract void handleReturnCode(); 12504 } 12505 12506 class MeasureParams extends HandlerParams { 12507 private final PackageStats mStats; 12508 private boolean mSuccess; 12509 12510 private final IPackageStatsObserver mObserver; 12511 12512 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12513 super(new UserHandle(stats.userHandle)); 12514 mObserver = observer; 12515 mStats = stats; 12516 } 12517 12518 @Override 12519 public String toString() { 12520 return "MeasureParams{" 12521 + Integer.toHexString(System.identityHashCode(this)) 12522 + " " + mStats.packageName + "}"; 12523 } 12524 12525 @Override 12526 void handleStartCopy() throws RemoteException { 12527 synchronized (mInstallLock) { 12528 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12529 } 12530 12531 if (mSuccess) { 12532 final boolean mounted; 12533 if (Environment.isExternalStorageEmulated()) { 12534 mounted = true; 12535 } else { 12536 final String status = Environment.getExternalStorageState(); 12537 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12538 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12539 } 12540 12541 if (mounted) { 12542 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12543 12544 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12545 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12546 12547 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12548 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12549 12550 // Always subtract cache size, since it's a subdirectory 12551 mStats.externalDataSize -= mStats.externalCacheSize; 12552 12553 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12554 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12555 12556 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12557 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12558 } 12559 } 12560 } 12561 12562 @Override 12563 void handleReturnCode() { 12564 if (mObserver != null) { 12565 try { 12566 mObserver.onGetStatsCompleted(mStats, mSuccess); 12567 } catch (RemoteException e) { 12568 Slog.i(TAG, "Observer no longer exists."); 12569 } 12570 } 12571 } 12572 12573 @Override 12574 void handleServiceError() { 12575 Slog.e(TAG, "Could not measure application " + mStats.packageName 12576 + " external storage"); 12577 } 12578 } 12579 12580 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12581 throws RemoteException { 12582 long result = 0; 12583 for (File path : paths) { 12584 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12585 } 12586 return result; 12587 } 12588 12589 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12590 for (File path : paths) { 12591 try { 12592 mcs.clearDirectory(path.getAbsolutePath()); 12593 } catch (RemoteException e) { 12594 } 12595 } 12596 } 12597 12598 static class OriginInfo { 12599 /** 12600 * Location where install is coming from, before it has been 12601 * copied/renamed into place. This could be a single monolithic APK 12602 * file, or a cluster directory. This location may be untrusted. 12603 */ 12604 final File file; 12605 final String cid; 12606 12607 /** 12608 * Flag indicating that {@link #file} or {@link #cid} has already been 12609 * staged, meaning downstream users don't need to defensively copy the 12610 * contents. 12611 */ 12612 final boolean staged; 12613 12614 /** 12615 * Flag indicating that {@link #file} or {@link #cid} is an already 12616 * installed app that is being moved. 12617 */ 12618 final boolean existing; 12619 12620 final String resolvedPath; 12621 final File resolvedFile; 12622 12623 static OriginInfo fromNothing() { 12624 return new OriginInfo(null, null, false, false); 12625 } 12626 12627 static OriginInfo fromUntrustedFile(File file) { 12628 return new OriginInfo(file, null, false, false); 12629 } 12630 12631 static OriginInfo fromExistingFile(File file) { 12632 return new OriginInfo(file, null, false, true); 12633 } 12634 12635 static OriginInfo fromStagedFile(File file) { 12636 return new OriginInfo(file, null, true, false); 12637 } 12638 12639 static OriginInfo fromStagedContainer(String cid) { 12640 return new OriginInfo(null, cid, true, false); 12641 } 12642 12643 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12644 this.file = file; 12645 this.cid = cid; 12646 this.staged = staged; 12647 this.existing = existing; 12648 12649 if (cid != null) { 12650 resolvedPath = PackageHelper.getSdDir(cid); 12651 resolvedFile = new File(resolvedPath); 12652 } else if (file != null) { 12653 resolvedPath = file.getAbsolutePath(); 12654 resolvedFile = file; 12655 } else { 12656 resolvedPath = null; 12657 resolvedFile = null; 12658 } 12659 } 12660 } 12661 12662 static class MoveInfo { 12663 final int moveId; 12664 final String fromUuid; 12665 final String toUuid; 12666 final String packageName; 12667 final String dataAppName; 12668 final int appId; 12669 final String seinfo; 12670 final int targetSdkVersion; 12671 12672 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12673 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12674 this.moveId = moveId; 12675 this.fromUuid = fromUuid; 12676 this.toUuid = toUuid; 12677 this.packageName = packageName; 12678 this.dataAppName = dataAppName; 12679 this.appId = appId; 12680 this.seinfo = seinfo; 12681 this.targetSdkVersion = targetSdkVersion; 12682 } 12683 } 12684 12685 static class VerificationInfo { 12686 /** A constant used to indicate that a uid value is not present. */ 12687 public static final int NO_UID = -1; 12688 12689 /** URI referencing where the package was downloaded from. */ 12690 final Uri originatingUri; 12691 12692 /** HTTP referrer URI associated with the originatingURI. */ 12693 final Uri referrer; 12694 12695 /** UID of the application that the install request originated from. */ 12696 final int originatingUid; 12697 12698 /** UID of application requesting the install */ 12699 final int installerUid; 12700 12701 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12702 this.originatingUri = originatingUri; 12703 this.referrer = referrer; 12704 this.originatingUid = originatingUid; 12705 this.installerUid = installerUid; 12706 } 12707 } 12708 12709 class InstallParams extends HandlerParams { 12710 final OriginInfo origin; 12711 final MoveInfo move; 12712 final IPackageInstallObserver2 observer; 12713 int installFlags; 12714 final String installerPackageName; 12715 final String volumeUuid; 12716 private InstallArgs mArgs; 12717 private int mRet; 12718 final String packageAbiOverride; 12719 final String[] grantedRuntimePermissions; 12720 final VerificationInfo verificationInfo; 12721 final Certificate[][] certificates; 12722 12723 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12724 int installFlags, String installerPackageName, String volumeUuid, 12725 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12726 String[] grantedPermissions, Certificate[][] certificates) { 12727 super(user); 12728 this.origin = origin; 12729 this.move = move; 12730 this.observer = observer; 12731 this.installFlags = installFlags; 12732 this.installerPackageName = installerPackageName; 12733 this.volumeUuid = volumeUuid; 12734 this.verificationInfo = verificationInfo; 12735 this.packageAbiOverride = packageAbiOverride; 12736 this.grantedRuntimePermissions = grantedPermissions; 12737 this.certificates = certificates; 12738 } 12739 12740 @Override 12741 public String toString() { 12742 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12743 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12744 } 12745 12746 private int installLocationPolicy(PackageInfoLite pkgLite) { 12747 String packageName = pkgLite.packageName; 12748 int installLocation = pkgLite.installLocation; 12749 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12750 // reader 12751 synchronized (mPackages) { 12752 // Currently installed package which the new package is attempting to replace or 12753 // null if no such package is installed. 12754 PackageParser.Package installedPkg = mPackages.get(packageName); 12755 // Package which currently owns the data which the new package will own if installed. 12756 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12757 // will be null whereas dataOwnerPkg will contain information about the package 12758 // which was uninstalled while keeping its data. 12759 PackageParser.Package dataOwnerPkg = installedPkg; 12760 if (dataOwnerPkg == null) { 12761 PackageSetting ps = mSettings.mPackages.get(packageName); 12762 if (ps != null) { 12763 dataOwnerPkg = ps.pkg; 12764 } 12765 } 12766 12767 if (dataOwnerPkg != null) { 12768 // If installed, the package will get access to data left on the device by its 12769 // predecessor. As a security measure, this is permited only if this is not a 12770 // version downgrade or if the predecessor package is marked as debuggable and 12771 // a downgrade is explicitly requested. 12772 // 12773 // On debuggable platform builds, downgrades are permitted even for 12774 // non-debuggable packages to make testing easier. Debuggable platform builds do 12775 // not offer security guarantees and thus it's OK to disable some security 12776 // mechanisms to make debugging/testing easier on those builds. However, even on 12777 // debuggable builds downgrades of packages are permitted only if requested via 12778 // installFlags. This is because we aim to keep the behavior of debuggable 12779 // platform builds as close as possible to the behavior of non-debuggable 12780 // platform builds. 12781 final boolean downgradeRequested = 12782 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12783 final boolean packageDebuggable = 12784 (dataOwnerPkg.applicationInfo.flags 12785 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12786 final boolean downgradePermitted = 12787 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12788 if (!downgradePermitted) { 12789 try { 12790 checkDowngrade(dataOwnerPkg, pkgLite); 12791 } catch (PackageManagerException e) { 12792 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12793 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12794 } 12795 } 12796 } 12797 12798 if (installedPkg != null) { 12799 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12800 // Check for updated system application. 12801 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12802 if (onSd) { 12803 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12804 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12805 } 12806 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12807 } else { 12808 if (onSd) { 12809 // Install flag overrides everything. 12810 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12811 } 12812 // If current upgrade specifies particular preference 12813 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12814 // Application explicitly specified internal. 12815 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12816 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12817 // App explictly prefers external. Let policy decide 12818 } else { 12819 // Prefer previous location 12820 if (isExternal(installedPkg)) { 12821 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12822 } 12823 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12824 } 12825 } 12826 } else { 12827 // Invalid install. Return error code 12828 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12829 } 12830 } 12831 } 12832 // All the special cases have been taken care of. 12833 // Return result based on recommended install location. 12834 if (onSd) { 12835 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12836 } 12837 return pkgLite.recommendedInstallLocation; 12838 } 12839 12840 /* 12841 * Invoke remote method to get package information and install 12842 * location values. Override install location based on default 12843 * policy if needed and then create install arguments based 12844 * on the install location. 12845 */ 12846 public void handleStartCopy() throws RemoteException { 12847 int ret = PackageManager.INSTALL_SUCCEEDED; 12848 12849 // If we're already staged, we've firmly committed to an install location 12850 if (origin.staged) { 12851 if (origin.file != null) { 12852 installFlags |= PackageManager.INSTALL_INTERNAL; 12853 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12854 } else if (origin.cid != null) { 12855 installFlags |= PackageManager.INSTALL_EXTERNAL; 12856 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12857 } else { 12858 throw new IllegalStateException("Invalid stage location"); 12859 } 12860 } 12861 12862 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12863 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12864 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12865 PackageInfoLite pkgLite = null; 12866 12867 if (onInt && onSd) { 12868 // Check if both bits are set. 12869 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12870 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12871 } else if (onSd && ephemeral) { 12872 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12873 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12874 } else { 12875 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12876 packageAbiOverride); 12877 12878 if (DEBUG_EPHEMERAL && ephemeral) { 12879 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12880 } 12881 12882 /* 12883 * If we have too little free space, try to free cache 12884 * before giving up. 12885 */ 12886 if (!origin.staged && pkgLite.recommendedInstallLocation 12887 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12888 // TODO: focus freeing disk space on the target device 12889 final StorageManager storage = StorageManager.from(mContext); 12890 final long lowThreshold = storage.getStorageLowBytes( 12891 Environment.getDataDirectory()); 12892 12893 final long sizeBytes = mContainerService.calculateInstalledSize( 12894 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12895 12896 try { 12897 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12898 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12899 installFlags, packageAbiOverride); 12900 } catch (InstallerException e) { 12901 Slog.w(TAG, "Failed to free cache", e); 12902 } 12903 12904 /* 12905 * The cache free must have deleted the file we 12906 * downloaded to install. 12907 * 12908 * TODO: fix the "freeCache" call to not delete 12909 * the file we care about. 12910 */ 12911 if (pkgLite.recommendedInstallLocation 12912 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12913 pkgLite.recommendedInstallLocation 12914 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12915 } 12916 } 12917 } 12918 12919 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12920 int loc = pkgLite.recommendedInstallLocation; 12921 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12922 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12923 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12924 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12925 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12926 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12927 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12928 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12929 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12930 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12931 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12932 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12933 } else { 12934 // Override with defaults if needed. 12935 loc = installLocationPolicy(pkgLite); 12936 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12937 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12938 } else if (!onSd && !onInt) { 12939 // Override install location with flags 12940 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12941 // Set the flag to install on external media. 12942 installFlags |= PackageManager.INSTALL_EXTERNAL; 12943 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12944 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12945 if (DEBUG_EPHEMERAL) { 12946 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12947 } 12948 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12949 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12950 |PackageManager.INSTALL_INTERNAL); 12951 } else { 12952 // Make sure the flag for installing on external 12953 // media is unset 12954 installFlags |= PackageManager.INSTALL_INTERNAL; 12955 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12956 } 12957 } 12958 } 12959 } 12960 12961 final InstallArgs args = createInstallArgs(this); 12962 mArgs = args; 12963 12964 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12965 // TODO: http://b/22976637 12966 // Apps installed for "all" users use the device owner to verify the app 12967 UserHandle verifierUser = getUser(); 12968 if (verifierUser == UserHandle.ALL) { 12969 verifierUser = UserHandle.SYSTEM; 12970 } 12971 12972 /* 12973 * Determine if we have any installed package verifiers. If we 12974 * do, then we'll defer to them to verify the packages. 12975 */ 12976 final int requiredUid = mRequiredVerifierPackage == null ? -1 12977 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12978 verifierUser.getIdentifier()); 12979 if (!origin.existing && requiredUid != -1 12980 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12981 final Intent verification = new Intent( 12982 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12983 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12984 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12985 PACKAGE_MIME_TYPE); 12986 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12987 12988 // Query all live verifiers based on current user state 12989 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12990 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12991 12992 if (DEBUG_VERIFY) { 12993 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12994 + verification.toString() + " with " + pkgLite.verifiers.length 12995 + " optional verifiers"); 12996 } 12997 12998 final int verificationId = mPendingVerificationToken++; 12999 13000 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13001 13002 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13003 installerPackageName); 13004 13005 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13006 installFlags); 13007 13008 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13009 pkgLite.packageName); 13010 13011 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13012 pkgLite.versionCode); 13013 13014 if (verificationInfo != null) { 13015 if (verificationInfo.originatingUri != null) { 13016 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13017 verificationInfo.originatingUri); 13018 } 13019 if (verificationInfo.referrer != null) { 13020 verification.putExtra(Intent.EXTRA_REFERRER, 13021 verificationInfo.referrer); 13022 } 13023 if (verificationInfo.originatingUid >= 0) { 13024 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13025 verificationInfo.originatingUid); 13026 } 13027 if (verificationInfo.installerUid >= 0) { 13028 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13029 verificationInfo.installerUid); 13030 } 13031 } 13032 13033 final PackageVerificationState verificationState = new PackageVerificationState( 13034 requiredUid, args); 13035 13036 mPendingVerification.append(verificationId, verificationState); 13037 13038 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13039 receivers, verificationState); 13040 13041 /* 13042 * If any sufficient verifiers were listed in the package 13043 * manifest, attempt to ask them. 13044 */ 13045 if (sufficientVerifiers != null) { 13046 final int N = sufficientVerifiers.size(); 13047 if (N == 0) { 13048 Slog.i(TAG, "Additional verifiers required, but none installed."); 13049 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13050 } else { 13051 for (int i = 0; i < N; i++) { 13052 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13053 13054 final Intent sufficientIntent = new Intent(verification); 13055 sufficientIntent.setComponent(verifierComponent); 13056 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13057 } 13058 } 13059 } 13060 13061 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13062 mRequiredVerifierPackage, receivers); 13063 if (ret == PackageManager.INSTALL_SUCCEEDED 13064 && mRequiredVerifierPackage != null) { 13065 Trace.asyncTraceBegin( 13066 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13067 /* 13068 * Send the intent to the required verification agent, 13069 * but only start the verification timeout after the 13070 * target BroadcastReceivers have run. 13071 */ 13072 verification.setComponent(requiredVerifierComponent); 13073 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13074 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13075 new BroadcastReceiver() { 13076 @Override 13077 public void onReceive(Context context, Intent intent) { 13078 final Message msg = mHandler 13079 .obtainMessage(CHECK_PENDING_VERIFICATION); 13080 msg.arg1 = verificationId; 13081 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13082 } 13083 }, null, 0, null, null); 13084 13085 /* 13086 * We don't want the copy to proceed until verification 13087 * succeeds, so null out this field. 13088 */ 13089 mArgs = null; 13090 } 13091 } else { 13092 /* 13093 * No package verification is enabled, so immediately start 13094 * the remote call to initiate copy using temporary file. 13095 */ 13096 ret = args.copyApk(mContainerService, true); 13097 } 13098 } 13099 13100 mRet = ret; 13101 } 13102 13103 @Override 13104 void handleReturnCode() { 13105 // If mArgs is null, then MCS couldn't be reached. When it 13106 // reconnects, it will try again to install. At that point, this 13107 // will succeed. 13108 if (mArgs != null) { 13109 processPendingInstall(mArgs, mRet); 13110 } 13111 } 13112 13113 @Override 13114 void handleServiceError() { 13115 mArgs = createInstallArgs(this); 13116 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13117 } 13118 13119 public boolean isForwardLocked() { 13120 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13121 } 13122 } 13123 13124 /** 13125 * Used during creation of InstallArgs 13126 * 13127 * @param installFlags package installation flags 13128 * @return true if should be installed on external storage 13129 */ 13130 private static boolean installOnExternalAsec(int installFlags) { 13131 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13132 return false; 13133 } 13134 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13135 return true; 13136 } 13137 return false; 13138 } 13139 13140 /** 13141 * Used during creation of InstallArgs 13142 * 13143 * @param installFlags package installation flags 13144 * @return true if should be installed as forward locked 13145 */ 13146 private static boolean installForwardLocked(int installFlags) { 13147 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13148 } 13149 13150 private InstallArgs createInstallArgs(InstallParams params) { 13151 if (params.move != null) { 13152 return new MoveInstallArgs(params); 13153 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13154 return new AsecInstallArgs(params); 13155 } else { 13156 return new FileInstallArgs(params); 13157 } 13158 } 13159 13160 /** 13161 * Create args that describe an existing installed package. Typically used 13162 * when cleaning up old installs, or used as a move source. 13163 */ 13164 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13165 String resourcePath, String[] instructionSets) { 13166 final boolean isInAsec; 13167 if (installOnExternalAsec(installFlags)) { 13168 /* Apps on SD card are always in ASEC containers. */ 13169 isInAsec = true; 13170 } else if (installForwardLocked(installFlags) 13171 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13172 /* 13173 * Forward-locked apps are only in ASEC containers if they're the 13174 * new style 13175 */ 13176 isInAsec = true; 13177 } else { 13178 isInAsec = false; 13179 } 13180 13181 if (isInAsec) { 13182 return new AsecInstallArgs(codePath, instructionSets, 13183 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13184 } else { 13185 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13186 } 13187 } 13188 13189 static abstract class InstallArgs { 13190 /** @see InstallParams#origin */ 13191 final OriginInfo origin; 13192 /** @see InstallParams#move */ 13193 final MoveInfo move; 13194 13195 final IPackageInstallObserver2 observer; 13196 // Always refers to PackageManager flags only 13197 final int installFlags; 13198 final String installerPackageName; 13199 final String volumeUuid; 13200 final UserHandle user; 13201 final String abiOverride; 13202 final String[] installGrantPermissions; 13203 /** If non-null, drop an async trace when the install completes */ 13204 final String traceMethod; 13205 final int traceCookie; 13206 final Certificate[][] certificates; 13207 13208 // The list of instruction sets supported by this app. This is currently 13209 // only used during the rmdex() phase to clean up resources. We can get rid of this 13210 // if we move dex files under the common app path. 13211 /* nullable */ String[] instructionSets; 13212 13213 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13214 int installFlags, String installerPackageName, String volumeUuid, 13215 UserHandle user, String[] instructionSets, 13216 String abiOverride, String[] installGrantPermissions, 13217 String traceMethod, int traceCookie, Certificate[][] certificates) { 13218 this.origin = origin; 13219 this.move = move; 13220 this.installFlags = installFlags; 13221 this.observer = observer; 13222 this.installerPackageName = installerPackageName; 13223 this.volumeUuid = volumeUuid; 13224 this.user = user; 13225 this.instructionSets = instructionSets; 13226 this.abiOverride = abiOverride; 13227 this.installGrantPermissions = installGrantPermissions; 13228 this.traceMethod = traceMethod; 13229 this.traceCookie = traceCookie; 13230 this.certificates = certificates; 13231 } 13232 13233 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13234 abstract int doPreInstall(int status); 13235 13236 /** 13237 * Rename package into final resting place. All paths on the given 13238 * scanned package should be updated to reflect the rename. 13239 */ 13240 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13241 abstract int doPostInstall(int status, int uid); 13242 13243 /** @see PackageSettingBase#codePathString */ 13244 abstract String getCodePath(); 13245 /** @see PackageSettingBase#resourcePathString */ 13246 abstract String getResourcePath(); 13247 13248 // Need installer lock especially for dex file removal. 13249 abstract void cleanUpResourcesLI(); 13250 abstract boolean doPostDeleteLI(boolean delete); 13251 13252 /** 13253 * Called before the source arguments are copied. This is used mostly 13254 * for MoveParams when it needs to read the source file to put it in the 13255 * destination. 13256 */ 13257 int doPreCopy() { 13258 return PackageManager.INSTALL_SUCCEEDED; 13259 } 13260 13261 /** 13262 * Called after the source arguments are copied. This is used mostly for 13263 * MoveParams when it needs to read the source file to put it in the 13264 * destination. 13265 */ 13266 int doPostCopy(int uid) { 13267 return PackageManager.INSTALL_SUCCEEDED; 13268 } 13269 13270 protected boolean isFwdLocked() { 13271 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13272 } 13273 13274 protected boolean isExternalAsec() { 13275 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13276 } 13277 13278 protected boolean isEphemeral() { 13279 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13280 } 13281 13282 UserHandle getUser() { 13283 return user; 13284 } 13285 } 13286 13287 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13288 if (!allCodePaths.isEmpty()) { 13289 if (instructionSets == null) { 13290 throw new IllegalStateException("instructionSet == null"); 13291 } 13292 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13293 for (String codePath : allCodePaths) { 13294 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13295 try { 13296 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13297 } catch (InstallerException ignored) { 13298 } 13299 } 13300 } 13301 } 13302 } 13303 13304 /** 13305 * Logic to handle installation of non-ASEC applications, including copying 13306 * and renaming logic. 13307 */ 13308 class FileInstallArgs extends InstallArgs { 13309 private File codeFile; 13310 private File resourceFile; 13311 13312 // Example topology: 13313 // /data/app/com.example/base.apk 13314 // /data/app/com.example/split_foo.apk 13315 // /data/app/com.example/lib/arm/libfoo.so 13316 // /data/app/com.example/lib/arm64/libfoo.so 13317 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13318 13319 /** New install */ 13320 FileInstallArgs(InstallParams params) { 13321 super(params.origin, params.move, params.observer, params.installFlags, 13322 params.installerPackageName, params.volumeUuid, 13323 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13324 params.grantedRuntimePermissions, 13325 params.traceMethod, params.traceCookie, params.certificates); 13326 if (isFwdLocked()) { 13327 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13328 } 13329 } 13330 13331 /** Existing install */ 13332 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13333 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13334 null, null, null, 0, null /*certificates*/); 13335 this.codeFile = (codePath != null) ? new File(codePath) : null; 13336 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13337 } 13338 13339 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13340 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13341 try { 13342 return doCopyApk(imcs, temp); 13343 } finally { 13344 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13345 } 13346 } 13347 13348 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13349 if (origin.staged) { 13350 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13351 codeFile = origin.file; 13352 resourceFile = origin.file; 13353 return PackageManager.INSTALL_SUCCEEDED; 13354 } 13355 13356 try { 13357 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13358 final File tempDir = 13359 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13360 codeFile = tempDir; 13361 resourceFile = tempDir; 13362 } catch (IOException e) { 13363 Slog.w(TAG, "Failed to create copy file: " + e); 13364 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13365 } 13366 13367 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13368 @Override 13369 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13370 if (!FileUtils.isValidExtFilename(name)) { 13371 throw new IllegalArgumentException("Invalid filename: " + name); 13372 } 13373 try { 13374 final File file = new File(codeFile, name); 13375 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13376 O_RDWR | O_CREAT, 0644); 13377 Os.chmod(file.getAbsolutePath(), 0644); 13378 return new ParcelFileDescriptor(fd); 13379 } catch (ErrnoException e) { 13380 throw new RemoteException("Failed to open: " + e.getMessage()); 13381 } 13382 } 13383 }; 13384 13385 int ret = PackageManager.INSTALL_SUCCEEDED; 13386 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13387 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13388 Slog.e(TAG, "Failed to copy package"); 13389 return ret; 13390 } 13391 13392 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13393 NativeLibraryHelper.Handle handle = null; 13394 try { 13395 handle = NativeLibraryHelper.Handle.create(codeFile); 13396 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13397 abiOverride); 13398 } catch (IOException e) { 13399 Slog.e(TAG, "Copying native libraries failed", e); 13400 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13401 } finally { 13402 IoUtils.closeQuietly(handle); 13403 } 13404 13405 return ret; 13406 } 13407 13408 int doPreInstall(int status) { 13409 if (status != PackageManager.INSTALL_SUCCEEDED) { 13410 cleanUp(); 13411 } 13412 return status; 13413 } 13414 13415 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13416 if (status != PackageManager.INSTALL_SUCCEEDED) { 13417 cleanUp(); 13418 return false; 13419 } 13420 13421 final File targetDir = codeFile.getParentFile(); 13422 final File beforeCodeFile = codeFile; 13423 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13424 13425 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13426 try { 13427 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13428 } catch (ErrnoException e) { 13429 Slog.w(TAG, "Failed to rename", e); 13430 return false; 13431 } 13432 13433 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13434 Slog.w(TAG, "Failed to restorecon"); 13435 return false; 13436 } 13437 13438 // Reflect the rename internally 13439 codeFile = afterCodeFile; 13440 resourceFile = afterCodeFile; 13441 13442 // Reflect the rename in scanned details 13443 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13444 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13445 afterCodeFile, pkg.baseCodePath)); 13446 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13447 afterCodeFile, pkg.splitCodePaths)); 13448 13449 // Reflect the rename in app info 13450 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13451 pkg.setApplicationInfoCodePath(pkg.codePath); 13452 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13453 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13454 pkg.setApplicationInfoResourcePath(pkg.codePath); 13455 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13456 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13457 13458 return true; 13459 } 13460 13461 int doPostInstall(int status, int uid) { 13462 if (status != PackageManager.INSTALL_SUCCEEDED) { 13463 cleanUp(); 13464 } 13465 return status; 13466 } 13467 13468 @Override 13469 String getCodePath() { 13470 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13471 } 13472 13473 @Override 13474 String getResourcePath() { 13475 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13476 } 13477 13478 private boolean cleanUp() { 13479 if (codeFile == null || !codeFile.exists()) { 13480 return false; 13481 } 13482 13483 removeCodePathLI(codeFile); 13484 13485 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13486 resourceFile.delete(); 13487 } 13488 13489 return true; 13490 } 13491 13492 void cleanUpResourcesLI() { 13493 // Try enumerating all code paths before deleting 13494 List<String> allCodePaths = Collections.EMPTY_LIST; 13495 if (codeFile != null && codeFile.exists()) { 13496 try { 13497 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13498 allCodePaths = pkg.getAllCodePaths(); 13499 } catch (PackageParserException e) { 13500 // Ignored; we tried our best 13501 } 13502 } 13503 13504 cleanUp(); 13505 removeDexFiles(allCodePaths, instructionSets); 13506 } 13507 13508 boolean doPostDeleteLI(boolean delete) { 13509 // XXX err, shouldn't we respect the delete flag? 13510 cleanUpResourcesLI(); 13511 return true; 13512 } 13513 } 13514 13515 private boolean isAsecExternal(String cid) { 13516 final String asecPath = PackageHelper.getSdFilesystem(cid); 13517 return !asecPath.startsWith(mAsecInternalPath); 13518 } 13519 13520 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13521 PackageManagerException { 13522 if (copyRet < 0) { 13523 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13524 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13525 throw new PackageManagerException(copyRet, message); 13526 } 13527 } 13528 } 13529 13530 /** 13531 * Extract the MountService "container ID" from the full code path of an 13532 * .apk. 13533 */ 13534 static String cidFromCodePath(String fullCodePath) { 13535 int eidx = fullCodePath.lastIndexOf("/"); 13536 String subStr1 = fullCodePath.substring(0, eidx); 13537 int sidx = subStr1.lastIndexOf("/"); 13538 return subStr1.substring(sidx+1, eidx); 13539 } 13540 13541 /** 13542 * Logic to handle installation of ASEC applications, including copying and 13543 * renaming logic. 13544 */ 13545 class AsecInstallArgs extends InstallArgs { 13546 static final String RES_FILE_NAME = "pkg.apk"; 13547 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13548 13549 String cid; 13550 String packagePath; 13551 String resourcePath; 13552 13553 /** New install */ 13554 AsecInstallArgs(InstallParams params) { 13555 super(params.origin, params.move, params.observer, params.installFlags, 13556 params.installerPackageName, params.volumeUuid, 13557 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13558 params.grantedRuntimePermissions, 13559 params.traceMethod, params.traceCookie, params.certificates); 13560 } 13561 13562 /** Existing install */ 13563 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13564 boolean isExternal, boolean isForwardLocked) { 13565 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13566 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13567 instructionSets, null, null, null, 0, null /*certificates*/); 13568 // Hackily pretend we're still looking at a full code path 13569 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13570 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13571 } 13572 13573 // Extract cid from fullCodePath 13574 int eidx = fullCodePath.lastIndexOf("/"); 13575 String subStr1 = fullCodePath.substring(0, eidx); 13576 int sidx = subStr1.lastIndexOf("/"); 13577 cid = subStr1.substring(sidx+1, eidx); 13578 setMountPath(subStr1); 13579 } 13580 13581 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13582 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13583 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13584 instructionSets, null, null, null, 0, null /*certificates*/); 13585 this.cid = cid; 13586 setMountPath(PackageHelper.getSdDir(cid)); 13587 } 13588 13589 void createCopyFile() { 13590 cid = mInstallerService.allocateExternalStageCidLegacy(); 13591 } 13592 13593 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13594 if (origin.staged && origin.cid != null) { 13595 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13596 cid = origin.cid; 13597 setMountPath(PackageHelper.getSdDir(cid)); 13598 return PackageManager.INSTALL_SUCCEEDED; 13599 } 13600 13601 if (temp) { 13602 createCopyFile(); 13603 } else { 13604 /* 13605 * Pre-emptively destroy the container since it's destroyed if 13606 * copying fails due to it existing anyway. 13607 */ 13608 PackageHelper.destroySdDir(cid); 13609 } 13610 13611 final String newMountPath = imcs.copyPackageToContainer( 13612 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13613 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13614 13615 if (newMountPath != null) { 13616 setMountPath(newMountPath); 13617 return PackageManager.INSTALL_SUCCEEDED; 13618 } else { 13619 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13620 } 13621 } 13622 13623 @Override 13624 String getCodePath() { 13625 return packagePath; 13626 } 13627 13628 @Override 13629 String getResourcePath() { 13630 return resourcePath; 13631 } 13632 13633 int doPreInstall(int status) { 13634 if (status != PackageManager.INSTALL_SUCCEEDED) { 13635 // Destroy container 13636 PackageHelper.destroySdDir(cid); 13637 } else { 13638 boolean mounted = PackageHelper.isContainerMounted(cid); 13639 if (!mounted) { 13640 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13641 Process.SYSTEM_UID); 13642 if (newMountPath != null) { 13643 setMountPath(newMountPath); 13644 } else { 13645 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13646 } 13647 } 13648 } 13649 return status; 13650 } 13651 13652 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13653 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13654 String newMountPath = null; 13655 if (PackageHelper.isContainerMounted(cid)) { 13656 // Unmount the container 13657 if (!PackageHelper.unMountSdDir(cid)) { 13658 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13659 return false; 13660 } 13661 } 13662 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13663 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13664 " which might be stale. Will try to clean up."); 13665 // Clean up the stale container and proceed to recreate. 13666 if (!PackageHelper.destroySdDir(newCacheId)) { 13667 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13668 return false; 13669 } 13670 // Successfully cleaned up stale container. Try to rename again. 13671 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13672 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13673 + " inspite of cleaning it up."); 13674 return false; 13675 } 13676 } 13677 if (!PackageHelper.isContainerMounted(newCacheId)) { 13678 Slog.w(TAG, "Mounting container " + newCacheId); 13679 newMountPath = PackageHelper.mountSdDir(newCacheId, 13680 getEncryptKey(), Process.SYSTEM_UID); 13681 } else { 13682 newMountPath = PackageHelper.getSdDir(newCacheId); 13683 } 13684 if (newMountPath == null) { 13685 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13686 return false; 13687 } 13688 Log.i(TAG, "Succesfully renamed " + cid + 13689 " to " + newCacheId + 13690 " at new path: " + newMountPath); 13691 cid = newCacheId; 13692 13693 final File beforeCodeFile = new File(packagePath); 13694 setMountPath(newMountPath); 13695 final File afterCodeFile = new File(packagePath); 13696 13697 // Reflect the rename in scanned details 13698 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13699 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13700 afterCodeFile, pkg.baseCodePath)); 13701 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13702 afterCodeFile, pkg.splitCodePaths)); 13703 13704 // Reflect the rename in app info 13705 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13706 pkg.setApplicationInfoCodePath(pkg.codePath); 13707 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13708 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13709 pkg.setApplicationInfoResourcePath(pkg.codePath); 13710 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13711 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13712 13713 return true; 13714 } 13715 13716 private void setMountPath(String mountPath) { 13717 final File mountFile = new File(mountPath); 13718 13719 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13720 if (monolithicFile.exists()) { 13721 packagePath = monolithicFile.getAbsolutePath(); 13722 if (isFwdLocked()) { 13723 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13724 } else { 13725 resourcePath = packagePath; 13726 } 13727 } else { 13728 packagePath = mountFile.getAbsolutePath(); 13729 resourcePath = packagePath; 13730 } 13731 } 13732 13733 int doPostInstall(int status, int uid) { 13734 if (status != PackageManager.INSTALL_SUCCEEDED) { 13735 cleanUp(); 13736 } else { 13737 final int groupOwner; 13738 final String protectedFile; 13739 if (isFwdLocked()) { 13740 groupOwner = UserHandle.getSharedAppGid(uid); 13741 protectedFile = RES_FILE_NAME; 13742 } else { 13743 groupOwner = -1; 13744 protectedFile = null; 13745 } 13746 13747 if (uid < Process.FIRST_APPLICATION_UID 13748 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13749 Slog.e(TAG, "Failed to finalize " + cid); 13750 PackageHelper.destroySdDir(cid); 13751 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13752 } 13753 13754 boolean mounted = PackageHelper.isContainerMounted(cid); 13755 if (!mounted) { 13756 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13757 } 13758 } 13759 return status; 13760 } 13761 13762 private void cleanUp() { 13763 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13764 13765 // Destroy secure container 13766 PackageHelper.destroySdDir(cid); 13767 } 13768 13769 private List<String> getAllCodePaths() { 13770 final File codeFile = new File(getCodePath()); 13771 if (codeFile != null && codeFile.exists()) { 13772 try { 13773 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13774 return pkg.getAllCodePaths(); 13775 } catch (PackageParserException e) { 13776 // Ignored; we tried our best 13777 } 13778 } 13779 return Collections.EMPTY_LIST; 13780 } 13781 13782 void cleanUpResourcesLI() { 13783 // Enumerate all code paths before deleting 13784 cleanUpResourcesLI(getAllCodePaths()); 13785 } 13786 13787 private void cleanUpResourcesLI(List<String> allCodePaths) { 13788 cleanUp(); 13789 removeDexFiles(allCodePaths, instructionSets); 13790 } 13791 13792 String getPackageName() { 13793 return getAsecPackageName(cid); 13794 } 13795 13796 boolean doPostDeleteLI(boolean delete) { 13797 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13798 final List<String> allCodePaths = getAllCodePaths(); 13799 boolean mounted = PackageHelper.isContainerMounted(cid); 13800 if (mounted) { 13801 // Unmount first 13802 if (PackageHelper.unMountSdDir(cid)) { 13803 mounted = false; 13804 } 13805 } 13806 if (!mounted && delete) { 13807 cleanUpResourcesLI(allCodePaths); 13808 } 13809 return !mounted; 13810 } 13811 13812 @Override 13813 int doPreCopy() { 13814 if (isFwdLocked()) { 13815 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13816 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13817 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13818 } 13819 } 13820 13821 return PackageManager.INSTALL_SUCCEEDED; 13822 } 13823 13824 @Override 13825 int doPostCopy(int uid) { 13826 if (isFwdLocked()) { 13827 if (uid < Process.FIRST_APPLICATION_UID 13828 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13829 RES_FILE_NAME)) { 13830 Slog.e(TAG, "Failed to finalize " + cid); 13831 PackageHelper.destroySdDir(cid); 13832 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13833 } 13834 } 13835 13836 return PackageManager.INSTALL_SUCCEEDED; 13837 } 13838 } 13839 13840 /** 13841 * Logic to handle movement of existing installed applications. 13842 */ 13843 class MoveInstallArgs extends InstallArgs { 13844 private File codeFile; 13845 private File resourceFile; 13846 13847 /** New install */ 13848 MoveInstallArgs(InstallParams params) { 13849 super(params.origin, params.move, params.observer, params.installFlags, 13850 params.installerPackageName, params.volumeUuid, 13851 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13852 params.grantedRuntimePermissions, 13853 params.traceMethod, params.traceCookie, params.certificates); 13854 } 13855 13856 int copyApk(IMediaContainerService imcs, boolean temp) { 13857 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13858 + move.fromUuid + " to " + move.toUuid); 13859 synchronized (mInstaller) { 13860 try { 13861 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13862 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13863 } catch (InstallerException e) { 13864 Slog.w(TAG, "Failed to move app", e); 13865 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13866 } 13867 } 13868 13869 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13870 resourceFile = codeFile; 13871 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13872 13873 return PackageManager.INSTALL_SUCCEEDED; 13874 } 13875 13876 int doPreInstall(int status) { 13877 if (status != PackageManager.INSTALL_SUCCEEDED) { 13878 cleanUp(move.toUuid); 13879 } 13880 return status; 13881 } 13882 13883 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13884 if (status != PackageManager.INSTALL_SUCCEEDED) { 13885 cleanUp(move.toUuid); 13886 return false; 13887 } 13888 13889 // Reflect the move in app info 13890 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13891 pkg.setApplicationInfoCodePath(pkg.codePath); 13892 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13893 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13894 pkg.setApplicationInfoResourcePath(pkg.codePath); 13895 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13896 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13897 13898 return true; 13899 } 13900 13901 int doPostInstall(int status, int uid) { 13902 if (status == PackageManager.INSTALL_SUCCEEDED) { 13903 cleanUp(move.fromUuid); 13904 } else { 13905 cleanUp(move.toUuid); 13906 } 13907 return status; 13908 } 13909 13910 @Override 13911 String getCodePath() { 13912 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13913 } 13914 13915 @Override 13916 String getResourcePath() { 13917 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13918 } 13919 13920 private boolean cleanUp(String volumeUuid) { 13921 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13922 move.dataAppName); 13923 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13924 final int[] userIds = sUserManager.getUserIds(); 13925 synchronized (mInstallLock) { 13926 // Clean up both app data and code 13927 // All package moves are frozen until finished 13928 for (int userId : userIds) { 13929 try { 13930 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13931 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13932 } catch (InstallerException e) { 13933 Slog.w(TAG, String.valueOf(e)); 13934 } 13935 } 13936 removeCodePathLI(codeFile); 13937 } 13938 return true; 13939 } 13940 13941 void cleanUpResourcesLI() { 13942 throw new UnsupportedOperationException(); 13943 } 13944 13945 boolean doPostDeleteLI(boolean delete) { 13946 throw new UnsupportedOperationException(); 13947 } 13948 } 13949 13950 static String getAsecPackageName(String packageCid) { 13951 int idx = packageCid.lastIndexOf("-"); 13952 if (idx == -1) { 13953 return packageCid; 13954 } 13955 return packageCid.substring(0, idx); 13956 } 13957 13958 // Utility method used to create code paths based on package name and available index. 13959 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13960 String idxStr = ""; 13961 int idx = 1; 13962 // Fall back to default value of idx=1 if prefix is not 13963 // part of oldCodePath 13964 if (oldCodePath != null) { 13965 String subStr = oldCodePath; 13966 // Drop the suffix right away 13967 if (suffix != null && subStr.endsWith(suffix)) { 13968 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13969 } 13970 // If oldCodePath already contains prefix find out the 13971 // ending index to either increment or decrement. 13972 int sidx = subStr.lastIndexOf(prefix); 13973 if (sidx != -1) { 13974 subStr = subStr.substring(sidx + prefix.length()); 13975 if (subStr != null) { 13976 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13977 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13978 } 13979 try { 13980 idx = Integer.parseInt(subStr); 13981 if (idx <= 1) { 13982 idx++; 13983 } else { 13984 idx--; 13985 } 13986 } catch(NumberFormatException e) { 13987 } 13988 } 13989 } 13990 } 13991 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13992 return prefix + idxStr; 13993 } 13994 13995 private File getNextCodePath(File targetDir, String packageName) { 13996 int suffix = 1; 13997 File result; 13998 do { 13999 result = new File(targetDir, packageName + "-" + suffix); 14000 suffix++; 14001 } while (result.exists()); 14002 return result; 14003 } 14004 14005 // Utility method that returns the relative package path with respect 14006 // to the installation directory. Like say for /data/data/com.test-1.apk 14007 // string com.test-1 is returned. 14008 static String deriveCodePathName(String codePath) { 14009 if (codePath == null) { 14010 return null; 14011 } 14012 final File codeFile = new File(codePath); 14013 final String name = codeFile.getName(); 14014 if (codeFile.isDirectory()) { 14015 return name; 14016 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14017 final int lastDot = name.lastIndexOf('.'); 14018 return name.substring(0, lastDot); 14019 } else { 14020 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14021 return null; 14022 } 14023 } 14024 14025 static class PackageInstalledInfo { 14026 String name; 14027 int uid; 14028 // The set of users that originally had this package installed. 14029 int[] origUsers; 14030 // The set of users that now have this package installed. 14031 int[] newUsers; 14032 PackageParser.Package pkg; 14033 int returnCode; 14034 String returnMsg; 14035 PackageRemovedInfo removedInfo; 14036 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14037 14038 public void setError(int code, String msg) { 14039 setReturnCode(code); 14040 setReturnMessage(msg); 14041 Slog.w(TAG, msg); 14042 } 14043 14044 public void setError(String msg, PackageParserException e) { 14045 setReturnCode(e.error); 14046 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14047 Slog.w(TAG, msg, e); 14048 } 14049 14050 public void setError(String msg, PackageManagerException e) { 14051 returnCode = e.error; 14052 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14053 Slog.w(TAG, msg, e); 14054 } 14055 14056 public void setReturnCode(int returnCode) { 14057 this.returnCode = returnCode; 14058 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14059 for (int i = 0; i < childCount; i++) { 14060 addedChildPackages.valueAt(i).returnCode = returnCode; 14061 } 14062 } 14063 14064 private void setReturnMessage(String returnMsg) { 14065 this.returnMsg = returnMsg; 14066 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14067 for (int i = 0; i < childCount; i++) { 14068 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14069 } 14070 } 14071 14072 // In some error cases we want to convey more info back to the observer 14073 String origPackage; 14074 String origPermission; 14075 } 14076 14077 /* 14078 * Install a non-existing package. 14079 */ 14080 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14081 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14082 PackageInstalledInfo res) { 14083 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14084 14085 // Remember this for later, in case we need to rollback this install 14086 String pkgName = pkg.packageName; 14087 14088 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14089 14090 synchronized(mPackages) { 14091 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14092 // A package with the same name is already installed, though 14093 // it has been renamed to an older name. The package we 14094 // are trying to install should be installed as an update to 14095 // the existing one, but that has not been requested, so bail. 14096 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14097 + " without first uninstalling package running as " 14098 + mSettings.mRenamedPackages.get(pkgName)); 14099 return; 14100 } 14101 if (mPackages.containsKey(pkgName)) { 14102 // Don't allow installation over an existing package with the same name. 14103 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14104 + " without first uninstalling."); 14105 return; 14106 } 14107 } 14108 14109 try { 14110 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14111 System.currentTimeMillis(), user); 14112 14113 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14114 14115 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14116 prepareAppDataAfterInstallLIF(newPackage); 14117 14118 } else { 14119 // Remove package from internal structures, but keep around any 14120 // data that might have already existed 14121 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14122 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14123 } 14124 } catch (PackageManagerException e) { 14125 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14126 } 14127 14128 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14129 } 14130 14131 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14132 // Can't rotate keys during boot or if sharedUser. 14133 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14134 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14135 return false; 14136 } 14137 // app is using upgradeKeySets; make sure all are valid 14138 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14139 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14140 for (int i = 0; i < upgradeKeySets.length; i++) { 14141 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14142 Slog.wtf(TAG, "Package " 14143 + (oldPs.name != null ? oldPs.name : "<null>") 14144 + " contains upgrade-key-set reference to unknown key-set: " 14145 + upgradeKeySets[i] 14146 + " reverting to signatures check."); 14147 return false; 14148 } 14149 } 14150 return true; 14151 } 14152 14153 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14154 // Upgrade keysets are being used. Determine if new package has a superset of the 14155 // required keys. 14156 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14157 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14158 for (int i = 0; i < upgradeKeySets.length; i++) { 14159 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14160 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14161 return true; 14162 } 14163 } 14164 return false; 14165 } 14166 14167 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14168 try (DigestInputStream digestStream = 14169 new DigestInputStream(new FileInputStream(file), digest)) { 14170 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14171 } 14172 } 14173 14174 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14175 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14176 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14177 14178 final PackageParser.Package oldPackage; 14179 final String pkgName = pkg.packageName; 14180 final int[] allUsers; 14181 final int[] installedUsers; 14182 14183 synchronized(mPackages) { 14184 oldPackage = mPackages.get(pkgName); 14185 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14186 14187 // don't allow upgrade to target a release SDK from a pre-release SDK 14188 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14189 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14190 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14191 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14192 if (oldTargetsPreRelease 14193 && !newTargetsPreRelease 14194 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14195 Slog.w(TAG, "Can't install package targeting released sdk"); 14196 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14197 return; 14198 } 14199 14200 // don't allow an upgrade from full to ephemeral 14201 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14202 if (isEphemeral && !oldIsEphemeral) { 14203 // can't downgrade from full to ephemeral 14204 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14205 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14206 return; 14207 } 14208 14209 // verify signatures are valid 14210 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14211 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14212 if (!checkUpgradeKeySetLP(ps, pkg)) { 14213 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14214 "New package not signed by keys specified by upgrade-keysets: " 14215 + pkgName); 14216 return; 14217 } 14218 } else { 14219 // default to original signature matching 14220 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14221 != PackageManager.SIGNATURE_MATCH) { 14222 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14223 "New package has a different signature: " + pkgName); 14224 return; 14225 } 14226 } 14227 14228 // don't allow a system upgrade unless the upgrade hash matches 14229 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14230 byte[] digestBytes = null; 14231 try { 14232 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14233 updateDigest(digest, new File(pkg.baseCodePath)); 14234 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14235 for (String path : pkg.splitCodePaths) { 14236 updateDigest(digest, new File(path)); 14237 } 14238 } 14239 digestBytes = digest.digest(); 14240 } catch (NoSuchAlgorithmException | IOException e) { 14241 res.setError(INSTALL_FAILED_INVALID_APK, 14242 "Could not compute hash: " + pkgName); 14243 return; 14244 } 14245 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14246 res.setError(INSTALL_FAILED_INVALID_APK, 14247 "New package fails restrict-update check: " + pkgName); 14248 return; 14249 } 14250 // retain upgrade restriction 14251 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14252 } 14253 14254 // Check for shared user id changes 14255 String invalidPackageName = 14256 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14257 if (invalidPackageName != null) { 14258 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14259 "Package " + invalidPackageName + " tried to change user " 14260 + oldPackage.mSharedUserId); 14261 return; 14262 } 14263 14264 // In case of rollback, remember per-user/profile install state 14265 allUsers = sUserManager.getUserIds(); 14266 installedUsers = ps.queryInstalledUsers(allUsers, true); 14267 } 14268 14269 // Update what is removed 14270 res.removedInfo = new PackageRemovedInfo(); 14271 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14272 res.removedInfo.removedPackage = oldPackage.packageName; 14273 res.removedInfo.isUpdate = true; 14274 res.removedInfo.origUsers = installedUsers; 14275 final int childCount = (oldPackage.childPackages != null) 14276 ? oldPackage.childPackages.size() : 0; 14277 for (int i = 0; i < childCount; i++) { 14278 boolean childPackageUpdated = false; 14279 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14280 if (res.addedChildPackages != null) { 14281 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14282 if (childRes != null) { 14283 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14284 childRes.removedInfo.removedPackage = childPkg.packageName; 14285 childRes.removedInfo.isUpdate = true; 14286 childPackageUpdated = true; 14287 } 14288 } 14289 if (!childPackageUpdated) { 14290 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14291 childRemovedRes.removedPackage = childPkg.packageName; 14292 childRemovedRes.isUpdate = false; 14293 childRemovedRes.dataRemoved = true; 14294 synchronized (mPackages) { 14295 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14296 if (childPs != null) { 14297 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14298 } 14299 } 14300 if (res.removedInfo.removedChildPackages == null) { 14301 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14302 } 14303 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14304 } 14305 } 14306 14307 boolean sysPkg = (isSystemApp(oldPackage)); 14308 if (sysPkg) { 14309 // Set the system/privileged flags as needed 14310 final boolean privileged = 14311 (oldPackage.applicationInfo.privateFlags 14312 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14313 final int systemPolicyFlags = policyFlags 14314 | PackageParser.PARSE_IS_SYSTEM 14315 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14316 14317 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14318 user, allUsers, installerPackageName, res); 14319 } else { 14320 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14321 user, allUsers, installerPackageName, res); 14322 } 14323 } 14324 14325 public List<String> getPreviousCodePaths(String packageName) { 14326 final PackageSetting ps = mSettings.mPackages.get(packageName); 14327 final List<String> result = new ArrayList<String>(); 14328 if (ps != null && ps.oldCodePaths != null) { 14329 result.addAll(ps.oldCodePaths); 14330 } 14331 return result; 14332 } 14333 14334 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14335 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14336 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14337 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14338 + deletedPackage); 14339 14340 String pkgName = deletedPackage.packageName; 14341 boolean deletedPkg = true; 14342 boolean addedPkg = false; 14343 boolean updatedSettings = false; 14344 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14345 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14346 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14347 14348 final long origUpdateTime = (pkg.mExtras != null) 14349 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14350 14351 // First delete the existing package while retaining the data directory 14352 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14353 res.removedInfo, true, pkg)) { 14354 // If the existing package wasn't successfully deleted 14355 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14356 deletedPkg = false; 14357 } else { 14358 // Successfully deleted the old package; proceed with replace. 14359 14360 // If deleted package lived in a container, give users a chance to 14361 // relinquish resources before killing. 14362 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14363 if (DEBUG_INSTALL) { 14364 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14365 } 14366 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14367 final ArrayList<String> pkgList = new ArrayList<String>(1); 14368 pkgList.add(deletedPackage.applicationInfo.packageName); 14369 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14370 } 14371 14372 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14373 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14374 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14375 14376 try { 14377 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14378 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14379 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14380 14381 // Update the in-memory copy of the previous code paths. 14382 PackageSetting ps = mSettings.mPackages.get(pkgName); 14383 if (!killApp) { 14384 if (ps.oldCodePaths == null) { 14385 ps.oldCodePaths = new ArraySet<>(); 14386 } 14387 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14388 if (deletedPackage.splitCodePaths != null) { 14389 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14390 } 14391 } else { 14392 ps.oldCodePaths = null; 14393 } 14394 if (ps.childPackageNames != null) { 14395 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14396 final String childPkgName = ps.childPackageNames.get(i); 14397 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14398 childPs.oldCodePaths = ps.oldCodePaths; 14399 } 14400 } 14401 prepareAppDataAfterInstallLIF(newPackage); 14402 addedPkg = true; 14403 } catch (PackageManagerException e) { 14404 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14405 } 14406 } 14407 14408 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14409 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14410 14411 // Revert all internal state mutations and added folders for the failed install 14412 if (addedPkg) { 14413 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14414 res.removedInfo, true, null); 14415 } 14416 14417 // Restore the old package 14418 if (deletedPkg) { 14419 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14420 File restoreFile = new File(deletedPackage.codePath); 14421 // Parse old package 14422 boolean oldExternal = isExternal(deletedPackage); 14423 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14424 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14425 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14426 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14427 try { 14428 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14429 null); 14430 } catch (PackageManagerException e) { 14431 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14432 + e.getMessage()); 14433 return; 14434 } 14435 14436 synchronized (mPackages) { 14437 // Ensure the installer package name up to date 14438 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14439 14440 // Update permissions for restored package 14441 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14442 14443 mSettings.writeLPr(); 14444 } 14445 14446 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14447 } 14448 } else { 14449 synchronized (mPackages) { 14450 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14451 if (ps != null) { 14452 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14453 if (res.removedInfo.removedChildPackages != null) { 14454 final int childCount = res.removedInfo.removedChildPackages.size(); 14455 // Iterate in reverse as we may modify the collection 14456 for (int i = childCount - 1; i >= 0; i--) { 14457 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14458 if (res.addedChildPackages.containsKey(childPackageName)) { 14459 res.removedInfo.removedChildPackages.removeAt(i); 14460 } else { 14461 PackageRemovedInfo childInfo = res.removedInfo 14462 .removedChildPackages.valueAt(i); 14463 childInfo.removedForAllUsers = mPackages.get( 14464 childInfo.removedPackage) == null; 14465 } 14466 } 14467 } 14468 } 14469 } 14470 } 14471 } 14472 14473 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14474 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14475 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14476 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14477 + ", old=" + deletedPackage); 14478 14479 final boolean disabledSystem; 14480 14481 // Remove existing system package 14482 removePackageLI(deletedPackage, true); 14483 14484 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14485 if (!disabledSystem) { 14486 // We didn't need to disable the .apk as a current system package, 14487 // which means we are replacing another update that is already 14488 // installed. We need to make sure to delete the older one's .apk. 14489 res.removedInfo.args = createInstallArgsForExisting(0, 14490 deletedPackage.applicationInfo.getCodePath(), 14491 deletedPackage.applicationInfo.getResourcePath(), 14492 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14493 } else { 14494 res.removedInfo.args = null; 14495 } 14496 14497 // Successfully disabled the old package. Now proceed with re-installation 14498 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14499 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14500 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14501 14502 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14503 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14504 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14505 14506 PackageParser.Package newPackage = null; 14507 try { 14508 // Add the package to the internal data structures 14509 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14510 14511 // Set the update and install times 14512 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14513 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14514 System.currentTimeMillis()); 14515 14516 // Update the package dynamic state if succeeded 14517 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14518 // Now that the install succeeded make sure we remove data 14519 // directories for any child package the update removed. 14520 final int deletedChildCount = (deletedPackage.childPackages != null) 14521 ? deletedPackage.childPackages.size() : 0; 14522 final int newChildCount = (newPackage.childPackages != null) 14523 ? newPackage.childPackages.size() : 0; 14524 for (int i = 0; i < deletedChildCount; i++) { 14525 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14526 boolean childPackageDeleted = true; 14527 for (int j = 0; j < newChildCount; j++) { 14528 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14529 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14530 childPackageDeleted = false; 14531 break; 14532 } 14533 } 14534 if (childPackageDeleted) { 14535 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14536 deletedChildPkg.packageName); 14537 if (ps != null && res.removedInfo.removedChildPackages != null) { 14538 PackageRemovedInfo removedChildRes = res.removedInfo 14539 .removedChildPackages.get(deletedChildPkg.packageName); 14540 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14541 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14542 } 14543 } 14544 } 14545 14546 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14547 prepareAppDataAfterInstallLIF(newPackage); 14548 } 14549 } catch (PackageManagerException e) { 14550 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14551 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14552 } 14553 14554 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14555 // Re installation failed. Restore old information 14556 // Remove new pkg information 14557 if (newPackage != null) { 14558 removeInstalledPackageLI(newPackage, true); 14559 } 14560 // Add back the old system package 14561 try { 14562 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14563 } catch (PackageManagerException e) { 14564 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14565 } 14566 14567 synchronized (mPackages) { 14568 if (disabledSystem) { 14569 enableSystemPackageLPw(deletedPackage); 14570 } 14571 14572 // Ensure the installer package name up to date 14573 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14574 14575 // Update permissions for restored package 14576 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14577 14578 mSettings.writeLPr(); 14579 } 14580 14581 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14582 + " after failed upgrade"); 14583 } 14584 } 14585 14586 /** 14587 * Checks whether the parent or any of the child packages have a change shared 14588 * user. For a package to be a valid update the shred users of the parent and 14589 * the children should match. We may later support changing child shared users. 14590 * @param oldPkg The updated package. 14591 * @param newPkg The update package. 14592 * @return The shared user that change between the versions. 14593 */ 14594 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14595 PackageParser.Package newPkg) { 14596 // Check parent shared user 14597 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14598 return newPkg.packageName; 14599 } 14600 // Check child shared users 14601 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14602 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14603 for (int i = 0; i < newChildCount; i++) { 14604 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14605 // If this child was present, did it have the same shared user? 14606 for (int j = 0; j < oldChildCount; j++) { 14607 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14608 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14609 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14610 return newChildPkg.packageName; 14611 } 14612 } 14613 } 14614 return null; 14615 } 14616 14617 private void removeNativeBinariesLI(PackageSetting ps) { 14618 // Remove the lib path for the parent package 14619 if (ps != null) { 14620 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14621 // Remove the lib path for the child packages 14622 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14623 for (int i = 0; i < childCount; i++) { 14624 PackageSetting childPs = null; 14625 synchronized (mPackages) { 14626 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14627 } 14628 if (childPs != null) { 14629 NativeLibraryHelper.removeNativeBinariesLI(childPs 14630 .legacyNativeLibraryPathString); 14631 } 14632 } 14633 } 14634 } 14635 14636 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14637 // Enable the parent package 14638 mSettings.enableSystemPackageLPw(pkg.packageName); 14639 // Enable the child packages 14640 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14641 for (int i = 0; i < childCount; i++) { 14642 PackageParser.Package childPkg = pkg.childPackages.get(i); 14643 mSettings.enableSystemPackageLPw(childPkg.packageName); 14644 } 14645 } 14646 14647 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14648 PackageParser.Package newPkg) { 14649 // Disable the parent package (parent always replaced) 14650 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14651 // Disable the child packages 14652 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14653 for (int i = 0; i < childCount; i++) { 14654 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14655 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14656 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14657 } 14658 return disabled; 14659 } 14660 14661 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14662 String installerPackageName) { 14663 // Enable the parent package 14664 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14665 // Enable the child packages 14666 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14667 for (int i = 0; i < childCount; i++) { 14668 PackageParser.Package childPkg = pkg.childPackages.get(i); 14669 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14670 } 14671 } 14672 14673 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14674 // Collect all used permissions in the UID 14675 ArraySet<String> usedPermissions = new ArraySet<>(); 14676 final int packageCount = su.packages.size(); 14677 for (int i = 0; i < packageCount; i++) { 14678 PackageSetting ps = su.packages.valueAt(i); 14679 if (ps.pkg == null) { 14680 continue; 14681 } 14682 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14683 for (int j = 0; j < requestedPermCount; j++) { 14684 String permission = ps.pkg.requestedPermissions.get(j); 14685 BasePermission bp = mSettings.mPermissions.get(permission); 14686 if (bp != null) { 14687 usedPermissions.add(permission); 14688 } 14689 } 14690 } 14691 14692 PermissionsState permissionsState = su.getPermissionsState(); 14693 // Prune install permissions 14694 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14695 final int installPermCount = installPermStates.size(); 14696 for (int i = installPermCount - 1; i >= 0; i--) { 14697 PermissionState permissionState = installPermStates.get(i); 14698 if (!usedPermissions.contains(permissionState.getName())) { 14699 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14700 if (bp != null) { 14701 permissionsState.revokeInstallPermission(bp); 14702 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14703 PackageManager.MASK_PERMISSION_FLAGS, 0); 14704 } 14705 } 14706 } 14707 14708 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14709 14710 // Prune runtime permissions 14711 for (int userId : allUserIds) { 14712 List<PermissionState> runtimePermStates = permissionsState 14713 .getRuntimePermissionStates(userId); 14714 final int runtimePermCount = runtimePermStates.size(); 14715 for (int i = runtimePermCount - 1; i >= 0; i--) { 14716 PermissionState permissionState = runtimePermStates.get(i); 14717 if (!usedPermissions.contains(permissionState.getName())) { 14718 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14719 if (bp != null) { 14720 permissionsState.revokeRuntimePermission(bp, userId); 14721 permissionsState.updatePermissionFlags(bp, userId, 14722 PackageManager.MASK_PERMISSION_FLAGS, 0); 14723 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14724 runtimePermissionChangedUserIds, userId); 14725 } 14726 } 14727 } 14728 } 14729 14730 return runtimePermissionChangedUserIds; 14731 } 14732 14733 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14734 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14735 // Update the parent package setting 14736 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14737 res, user); 14738 // Update the child packages setting 14739 final int childCount = (newPackage.childPackages != null) 14740 ? newPackage.childPackages.size() : 0; 14741 for (int i = 0; i < childCount; i++) { 14742 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14743 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14744 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14745 childRes.origUsers, childRes, user); 14746 } 14747 } 14748 14749 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14750 String installerPackageName, int[] allUsers, int[] installedForUsers, 14751 PackageInstalledInfo res, UserHandle user) { 14752 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14753 14754 String pkgName = newPackage.packageName; 14755 synchronized (mPackages) { 14756 //write settings. the installStatus will be incomplete at this stage. 14757 //note that the new package setting would have already been 14758 //added to mPackages. It hasn't been persisted yet. 14759 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14760 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14761 mSettings.writeLPr(); 14762 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14763 } 14764 14765 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14766 synchronized (mPackages) { 14767 updatePermissionsLPw(newPackage.packageName, newPackage, 14768 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14769 ? UPDATE_PERMISSIONS_ALL : 0)); 14770 // For system-bundled packages, we assume that installing an upgraded version 14771 // of the package implies that the user actually wants to run that new code, 14772 // so we enable the package. 14773 PackageSetting ps = mSettings.mPackages.get(pkgName); 14774 final int userId = user.getIdentifier(); 14775 if (ps != null) { 14776 if (isSystemApp(newPackage)) { 14777 if (DEBUG_INSTALL) { 14778 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14779 } 14780 // Enable system package for requested users 14781 if (res.origUsers != null) { 14782 for (int origUserId : res.origUsers) { 14783 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14784 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14785 origUserId, installerPackageName); 14786 } 14787 } 14788 } 14789 // Also convey the prior install/uninstall state 14790 if (allUsers != null && installedForUsers != null) { 14791 for (int currentUserId : allUsers) { 14792 final boolean installed = ArrayUtils.contains( 14793 installedForUsers, currentUserId); 14794 if (DEBUG_INSTALL) { 14795 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14796 } 14797 ps.setInstalled(installed, currentUserId); 14798 } 14799 // these install state changes will be persisted in the 14800 // upcoming call to mSettings.writeLPr(). 14801 } 14802 } 14803 // It's implied that when a user requests installation, they want the app to be 14804 // installed and enabled. 14805 if (userId != UserHandle.USER_ALL) { 14806 ps.setInstalled(true, userId); 14807 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14808 } 14809 } 14810 res.name = pkgName; 14811 res.uid = newPackage.applicationInfo.uid; 14812 res.pkg = newPackage; 14813 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14814 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14815 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14816 //to update install status 14817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14818 mSettings.writeLPr(); 14819 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14820 } 14821 14822 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14823 } 14824 14825 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14826 try { 14827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14828 installPackageLI(args, res); 14829 } finally { 14830 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14831 } 14832 } 14833 14834 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14835 final int installFlags = args.installFlags; 14836 final String installerPackageName = args.installerPackageName; 14837 final String volumeUuid = args.volumeUuid; 14838 final File tmpPackageFile = new File(args.getCodePath()); 14839 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14840 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14841 || (args.volumeUuid != null)); 14842 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14843 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14844 boolean replace = false; 14845 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14846 if (args.move != null) { 14847 // moving a complete application; perform an initial scan on the new install location 14848 scanFlags |= SCAN_INITIAL; 14849 } 14850 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14851 scanFlags |= SCAN_DONT_KILL_APP; 14852 } 14853 14854 // Result object to be returned 14855 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14856 14857 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14858 14859 // Sanity check 14860 if (ephemeral && (forwardLocked || onExternal)) { 14861 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14862 + " external=" + onExternal); 14863 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14864 return; 14865 } 14866 14867 // Retrieve PackageSettings and parse package 14868 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14869 | PackageParser.PARSE_ENFORCE_CODE 14870 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14871 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14872 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14873 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14874 PackageParser pp = new PackageParser(); 14875 pp.setSeparateProcesses(mSeparateProcesses); 14876 pp.setDisplayMetrics(mMetrics); 14877 14878 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14879 final PackageParser.Package pkg; 14880 try { 14881 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14882 } catch (PackageParserException e) { 14883 res.setError("Failed parse during installPackageLI", e); 14884 return; 14885 } finally { 14886 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14887 } 14888 14889 // If we are installing a clustered package add results for the children 14890 if (pkg.childPackages != null) { 14891 synchronized (mPackages) { 14892 final int childCount = pkg.childPackages.size(); 14893 for (int i = 0; i < childCount; i++) { 14894 PackageParser.Package childPkg = pkg.childPackages.get(i); 14895 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14896 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14897 childRes.pkg = childPkg; 14898 childRes.name = childPkg.packageName; 14899 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14900 if (childPs != null) { 14901 childRes.origUsers = childPs.queryInstalledUsers( 14902 sUserManager.getUserIds(), true); 14903 } 14904 if ((mPackages.containsKey(childPkg.packageName))) { 14905 childRes.removedInfo = new PackageRemovedInfo(); 14906 childRes.removedInfo.removedPackage = childPkg.packageName; 14907 } 14908 if (res.addedChildPackages == null) { 14909 res.addedChildPackages = new ArrayMap<>(); 14910 } 14911 res.addedChildPackages.put(childPkg.packageName, childRes); 14912 } 14913 } 14914 } 14915 14916 // If package doesn't declare API override, mark that we have an install 14917 // time CPU ABI override. 14918 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14919 pkg.cpuAbiOverride = args.abiOverride; 14920 } 14921 14922 String pkgName = res.name = pkg.packageName; 14923 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14924 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14925 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14926 return; 14927 } 14928 } 14929 14930 try { 14931 // either use what we've been given or parse directly from the APK 14932 if (args.certificates != null) { 14933 try { 14934 PackageParser.populateCertificates(pkg, args.certificates); 14935 } catch (PackageParserException e) { 14936 // there was something wrong with the certificates we were given; 14937 // try to pull them from the APK 14938 PackageParser.collectCertificates(pkg, parseFlags); 14939 } 14940 } else { 14941 PackageParser.collectCertificates(pkg, parseFlags); 14942 } 14943 } catch (PackageParserException e) { 14944 res.setError("Failed collect during installPackageLI", e); 14945 return; 14946 } 14947 14948 // Get rid of all references to package scan path via parser. 14949 pp = null; 14950 String oldCodePath = null; 14951 boolean systemApp = false; 14952 synchronized (mPackages) { 14953 // Check if installing already existing package 14954 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14955 String oldName = mSettings.mRenamedPackages.get(pkgName); 14956 if (pkg.mOriginalPackages != null 14957 && pkg.mOriginalPackages.contains(oldName) 14958 && mPackages.containsKey(oldName)) { 14959 // This package is derived from an original package, 14960 // and this device has been updating from that original 14961 // name. We must continue using the original name, so 14962 // rename the new package here. 14963 pkg.setPackageName(oldName); 14964 pkgName = pkg.packageName; 14965 replace = true; 14966 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14967 + oldName + " pkgName=" + pkgName); 14968 } else if (mPackages.containsKey(pkgName)) { 14969 // This package, under its official name, already exists 14970 // on the device; we should replace it. 14971 replace = true; 14972 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14973 } 14974 14975 // Child packages are installed through the parent package 14976 if (pkg.parentPackage != null) { 14977 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14978 "Package " + pkg.packageName + " is child of package " 14979 + pkg.parentPackage.parentPackage + ". Child packages " 14980 + "can be updated only through the parent package."); 14981 return; 14982 } 14983 14984 if (replace) { 14985 // Prevent apps opting out from runtime permissions 14986 PackageParser.Package oldPackage = mPackages.get(pkgName); 14987 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14988 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14989 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14990 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14991 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14992 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14993 + " doesn't support runtime permissions but the old" 14994 + " target SDK " + oldTargetSdk + " does."); 14995 return; 14996 } 14997 14998 // Prevent installing of child packages 14999 if (oldPackage.parentPackage != null) { 15000 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15001 "Package " + pkg.packageName + " is child of package " 15002 + oldPackage.parentPackage + ". Child packages " 15003 + "can be updated only through the parent package."); 15004 return; 15005 } 15006 } 15007 } 15008 15009 PackageSetting ps = mSettings.mPackages.get(pkgName); 15010 if (ps != null) { 15011 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15012 15013 // Quick sanity check that we're signed correctly if updating; 15014 // we'll check this again later when scanning, but we want to 15015 // bail early here before tripping over redefined permissions. 15016 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15017 if (!checkUpgradeKeySetLP(ps, pkg)) { 15018 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15019 + pkg.packageName + " upgrade keys do not match the " 15020 + "previously installed version"); 15021 return; 15022 } 15023 } else { 15024 try { 15025 verifySignaturesLP(ps, pkg); 15026 } catch (PackageManagerException e) { 15027 res.setError(e.error, e.getMessage()); 15028 return; 15029 } 15030 } 15031 15032 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15033 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15034 systemApp = (ps.pkg.applicationInfo.flags & 15035 ApplicationInfo.FLAG_SYSTEM) != 0; 15036 } 15037 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15038 } 15039 15040 // Check whether the newly-scanned package wants to define an already-defined perm 15041 int N = pkg.permissions.size(); 15042 for (int i = N-1; i >= 0; i--) { 15043 PackageParser.Permission perm = pkg.permissions.get(i); 15044 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15045 if (bp != null) { 15046 // If the defining package is signed with our cert, it's okay. This 15047 // also includes the "updating the same package" case, of course. 15048 // "updating same package" could also involve key-rotation. 15049 final boolean sigsOk; 15050 if (bp.sourcePackage.equals(pkg.packageName) 15051 && (bp.packageSetting instanceof PackageSetting) 15052 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15053 scanFlags))) { 15054 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15055 } else { 15056 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15057 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15058 } 15059 if (!sigsOk) { 15060 // If the owning package is the system itself, we log but allow 15061 // install to proceed; we fail the install on all other permission 15062 // redefinitions. 15063 if (!bp.sourcePackage.equals("android")) { 15064 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15065 + pkg.packageName + " attempting to redeclare permission " 15066 + perm.info.name + " already owned by " + bp.sourcePackage); 15067 res.origPermission = perm.info.name; 15068 res.origPackage = bp.sourcePackage; 15069 return; 15070 } else { 15071 Slog.w(TAG, "Package " + pkg.packageName 15072 + " attempting to redeclare system permission " 15073 + perm.info.name + "; ignoring new declaration"); 15074 pkg.permissions.remove(i); 15075 } 15076 } 15077 } 15078 } 15079 } 15080 15081 if (systemApp) { 15082 if (onExternal) { 15083 // Abort update; system app can't be replaced with app on sdcard 15084 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15085 "Cannot install updates to system apps on sdcard"); 15086 return; 15087 } else if (ephemeral) { 15088 // Abort update; system app can't be replaced with an ephemeral app 15089 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15090 "Cannot update a system app with an ephemeral app"); 15091 return; 15092 } 15093 } 15094 15095 if (args.move != null) { 15096 // We did an in-place move, so dex is ready to roll 15097 scanFlags |= SCAN_NO_DEX; 15098 scanFlags |= SCAN_MOVE; 15099 15100 synchronized (mPackages) { 15101 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15102 if (ps == null) { 15103 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15104 "Missing settings for moved package " + pkgName); 15105 } 15106 15107 // We moved the entire application as-is, so bring over the 15108 // previously derived ABI information. 15109 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15110 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15111 } 15112 15113 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15114 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15115 scanFlags |= SCAN_NO_DEX; 15116 15117 try { 15118 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15119 args.abiOverride : pkg.cpuAbiOverride); 15120 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15121 true /* extract libs */); 15122 } catch (PackageManagerException pme) { 15123 Slog.e(TAG, "Error deriving application ABI", pme); 15124 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15125 return; 15126 } 15127 15128 // Shared libraries for the package need to be updated. 15129 synchronized (mPackages) { 15130 try { 15131 updateSharedLibrariesLPw(pkg, null); 15132 } catch (PackageManagerException e) { 15133 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15134 } 15135 } 15136 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15137 // Do not run PackageDexOptimizer through the local performDexOpt 15138 // method because `pkg` is not in `mPackages` yet. 15139 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15140 null /* instructionSets */, false /* checkProfiles */, 15141 getCompilerFilterForReason(REASON_INSTALL)); 15142 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15143 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 15144 String msg = "Extracting package failed for " + pkgName; 15145 res.setError(INSTALL_FAILED_DEXOPT, msg); 15146 return; 15147 } 15148 15149 // Notify BackgroundDexOptService that the package has been changed. 15150 // If this is an update of a package which used to fail to compile, 15151 // BDOS will remove it from its blacklist. 15152 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15153 } 15154 15155 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15156 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15157 return; 15158 } 15159 15160 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15161 15162 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15163 "installPackageLI")) { 15164 if (replace) { 15165 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15166 installerPackageName, res); 15167 } else { 15168 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15169 args.user, installerPackageName, volumeUuid, res); 15170 } 15171 } 15172 synchronized (mPackages) { 15173 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15174 if (ps != null) { 15175 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15176 } 15177 15178 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15179 for (int i = 0; i < childCount; i++) { 15180 PackageParser.Package childPkg = pkg.childPackages.get(i); 15181 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15182 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15183 if (childPs != null) { 15184 childRes.newUsers = childPs.queryInstalledUsers( 15185 sUserManager.getUserIds(), true); 15186 } 15187 } 15188 } 15189 } 15190 15191 private void startIntentFilterVerifications(int userId, boolean replacing, 15192 PackageParser.Package pkg) { 15193 if (mIntentFilterVerifierComponent == null) { 15194 Slog.w(TAG, "No IntentFilter verification will not be done as " 15195 + "there is no IntentFilterVerifier available!"); 15196 return; 15197 } 15198 15199 final int verifierUid = getPackageUid( 15200 mIntentFilterVerifierComponent.getPackageName(), 15201 MATCH_DEBUG_TRIAGED_MISSING, 15202 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15203 15204 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15205 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15206 mHandler.sendMessage(msg); 15207 15208 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15209 for (int i = 0; i < childCount; i++) { 15210 PackageParser.Package childPkg = pkg.childPackages.get(i); 15211 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15212 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15213 mHandler.sendMessage(msg); 15214 } 15215 } 15216 15217 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15218 PackageParser.Package pkg) { 15219 int size = pkg.activities.size(); 15220 if (size == 0) { 15221 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15222 "No activity, so no need to verify any IntentFilter!"); 15223 return; 15224 } 15225 15226 final boolean hasDomainURLs = hasDomainURLs(pkg); 15227 if (!hasDomainURLs) { 15228 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15229 "No domain URLs, so no need to verify any IntentFilter!"); 15230 return; 15231 } 15232 15233 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15234 + " if any IntentFilter from the " + size 15235 + " Activities needs verification ..."); 15236 15237 int count = 0; 15238 final String packageName = pkg.packageName; 15239 15240 synchronized (mPackages) { 15241 // If this is a new install and we see that we've already run verification for this 15242 // package, we have nothing to do: it means the state was restored from backup. 15243 if (!replacing) { 15244 IntentFilterVerificationInfo ivi = 15245 mSettings.getIntentFilterVerificationLPr(packageName); 15246 if (ivi != null) { 15247 if (DEBUG_DOMAIN_VERIFICATION) { 15248 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15249 + ivi.getStatusString()); 15250 } 15251 return; 15252 } 15253 } 15254 15255 // If any filters need to be verified, then all need to be. 15256 boolean needToVerify = false; 15257 for (PackageParser.Activity a : pkg.activities) { 15258 for (ActivityIntentInfo filter : a.intents) { 15259 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15260 if (DEBUG_DOMAIN_VERIFICATION) { 15261 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15262 } 15263 needToVerify = true; 15264 break; 15265 } 15266 } 15267 } 15268 15269 if (needToVerify) { 15270 final int verificationId = mIntentFilterVerificationToken++; 15271 for (PackageParser.Activity a : pkg.activities) { 15272 for (ActivityIntentInfo filter : a.intents) { 15273 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15274 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15275 "Verification needed for IntentFilter:" + filter.toString()); 15276 mIntentFilterVerifier.addOneIntentFilterVerification( 15277 verifierUid, userId, verificationId, filter, packageName); 15278 count++; 15279 } 15280 } 15281 } 15282 } 15283 } 15284 15285 if (count > 0) { 15286 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15287 + " IntentFilter verification" + (count > 1 ? "s" : "") 15288 + " for userId:" + userId); 15289 mIntentFilterVerifier.startVerifications(userId); 15290 } else { 15291 if (DEBUG_DOMAIN_VERIFICATION) { 15292 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15293 } 15294 } 15295 } 15296 15297 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15298 final ComponentName cn = filter.activity.getComponentName(); 15299 final String packageName = cn.getPackageName(); 15300 15301 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15302 packageName); 15303 if (ivi == null) { 15304 return true; 15305 } 15306 int status = ivi.getStatus(); 15307 switch (status) { 15308 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15309 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15310 return true; 15311 15312 default: 15313 // Nothing to do 15314 return false; 15315 } 15316 } 15317 15318 private static boolean isMultiArch(ApplicationInfo info) { 15319 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15320 } 15321 15322 private static boolean isExternal(PackageParser.Package pkg) { 15323 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15324 } 15325 15326 private static boolean isExternal(PackageSetting ps) { 15327 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15328 } 15329 15330 private static boolean isEphemeral(PackageParser.Package pkg) { 15331 return pkg.applicationInfo.isEphemeralApp(); 15332 } 15333 15334 private static boolean isEphemeral(PackageSetting ps) { 15335 return ps.pkg != null && isEphemeral(ps.pkg); 15336 } 15337 15338 private static boolean isSystemApp(PackageParser.Package pkg) { 15339 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15340 } 15341 15342 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15343 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15344 } 15345 15346 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15347 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15348 } 15349 15350 private static boolean isSystemApp(PackageSetting ps) { 15351 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15352 } 15353 15354 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15355 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15356 } 15357 15358 private int packageFlagsToInstallFlags(PackageSetting ps) { 15359 int installFlags = 0; 15360 if (isEphemeral(ps)) { 15361 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15362 } 15363 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15364 // This existing package was an external ASEC install when we have 15365 // the external flag without a UUID 15366 installFlags |= PackageManager.INSTALL_EXTERNAL; 15367 } 15368 if (ps.isForwardLocked()) { 15369 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15370 } 15371 return installFlags; 15372 } 15373 15374 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15375 if (isExternal(pkg)) { 15376 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15377 return StorageManager.UUID_PRIMARY_PHYSICAL; 15378 } else { 15379 return pkg.volumeUuid; 15380 } 15381 } else { 15382 return StorageManager.UUID_PRIVATE_INTERNAL; 15383 } 15384 } 15385 15386 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15387 if (isExternal(pkg)) { 15388 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15389 return mSettings.getExternalVersion(); 15390 } else { 15391 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15392 } 15393 } else { 15394 return mSettings.getInternalVersion(); 15395 } 15396 } 15397 15398 private void deleteTempPackageFiles() { 15399 final FilenameFilter filter = new FilenameFilter() { 15400 public boolean accept(File dir, String name) { 15401 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15402 } 15403 }; 15404 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15405 file.delete(); 15406 } 15407 } 15408 15409 @Override 15410 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15411 int flags) { 15412 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15413 flags); 15414 } 15415 15416 @Override 15417 public void deletePackage(final String packageName, 15418 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15419 mContext.enforceCallingOrSelfPermission( 15420 android.Manifest.permission.DELETE_PACKAGES, null); 15421 Preconditions.checkNotNull(packageName); 15422 Preconditions.checkNotNull(observer); 15423 final int uid = Binder.getCallingUid(); 15424 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15425 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15426 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15427 mContext.enforceCallingOrSelfPermission( 15428 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15429 "deletePackage for user " + userId); 15430 } 15431 15432 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15433 try { 15434 observer.onPackageDeleted(packageName, 15435 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15436 } catch (RemoteException re) { 15437 } 15438 return; 15439 } 15440 15441 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15442 try { 15443 observer.onPackageDeleted(packageName, 15444 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15445 } catch (RemoteException re) { 15446 } 15447 return; 15448 } 15449 15450 if (DEBUG_REMOVE) { 15451 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15452 + " deleteAllUsers: " + deleteAllUsers ); 15453 } 15454 // Queue up an async operation since the package deletion may take a little while. 15455 mHandler.post(new Runnable() { 15456 public void run() { 15457 mHandler.removeCallbacks(this); 15458 int returnCode; 15459 if (!deleteAllUsers) { 15460 returnCode = deletePackageX(packageName, userId, deleteFlags); 15461 } else { 15462 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15463 // If nobody is blocking uninstall, proceed with delete for all users 15464 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15465 returnCode = deletePackageX(packageName, userId, deleteFlags); 15466 } else { 15467 // Otherwise uninstall individually for users with blockUninstalls=false 15468 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15469 for (int userId : users) { 15470 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15471 returnCode = deletePackageX(packageName, userId, userFlags); 15472 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15473 Slog.w(TAG, "Package delete failed for user " + userId 15474 + ", returnCode " + returnCode); 15475 } 15476 } 15477 } 15478 // The app has only been marked uninstalled for certain users. 15479 // We still need to report that delete was blocked 15480 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15481 } 15482 } 15483 try { 15484 observer.onPackageDeleted(packageName, returnCode, null); 15485 } catch (RemoteException e) { 15486 Log.i(TAG, "Observer no longer exists."); 15487 } //end catch 15488 } //end run 15489 }); 15490 } 15491 15492 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15493 int[] result = EMPTY_INT_ARRAY; 15494 for (int userId : userIds) { 15495 if (getBlockUninstallForUser(packageName, userId)) { 15496 result = ArrayUtils.appendInt(result, userId); 15497 } 15498 } 15499 return result; 15500 } 15501 15502 @Override 15503 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15504 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15505 } 15506 15507 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15508 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15509 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15510 try { 15511 if (dpm != null) { 15512 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15513 /* callingUserOnly =*/ false); 15514 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15515 : deviceOwnerComponentName.getPackageName(); 15516 // Does the package contains the device owner? 15517 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15518 // this check is probably not needed, since DO should be registered as a device 15519 // admin on some user too. (Original bug for this: b/17657954) 15520 if (packageName.equals(deviceOwnerPackageName)) { 15521 return true; 15522 } 15523 // Does it contain a device admin for any user? 15524 int[] users; 15525 if (userId == UserHandle.USER_ALL) { 15526 users = sUserManager.getUserIds(); 15527 } else { 15528 users = new int[]{userId}; 15529 } 15530 for (int i = 0; i < users.length; ++i) { 15531 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15532 return true; 15533 } 15534 } 15535 } 15536 } catch (RemoteException e) { 15537 } 15538 return false; 15539 } 15540 15541 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15542 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15543 } 15544 15545 /** 15546 * This method is an internal method that could be get invoked either 15547 * to delete an installed package or to clean up a failed installation. 15548 * After deleting an installed package, a broadcast is sent to notify any 15549 * listeners that the package has been removed. For cleaning up a failed 15550 * installation, the broadcast is not necessary since the package's 15551 * installation wouldn't have sent the initial broadcast either 15552 * The key steps in deleting a package are 15553 * deleting the package information in internal structures like mPackages, 15554 * deleting the packages base directories through installd 15555 * updating mSettings to reflect current status 15556 * persisting settings for later use 15557 * sending a broadcast if necessary 15558 */ 15559 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15560 final PackageRemovedInfo info = new PackageRemovedInfo(); 15561 final boolean res; 15562 15563 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15564 ? UserHandle.ALL : new UserHandle(userId); 15565 15566 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15567 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15568 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15569 } 15570 15571 PackageSetting uninstalledPs = null; 15572 15573 // for the uninstall-updates case and restricted profiles, remember the per- 15574 // user handle installed state 15575 int[] allUsers; 15576 synchronized (mPackages) { 15577 uninstalledPs = mSettings.mPackages.get(packageName); 15578 if (uninstalledPs == null) { 15579 Slog.w(TAG, "Not removing non-existent package " + packageName); 15580 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15581 } 15582 allUsers = sUserManager.getUserIds(); 15583 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15584 } 15585 15586 synchronized (mInstallLock) { 15587 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15588 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15589 "deletePackageX")) { 15590 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15591 deleteFlags | REMOVE_CHATTY, info, true, null); 15592 } 15593 synchronized (mPackages) { 15594 if (res) { 15595 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15596 } 15597 } 15598 } 15599 15600 if (res) { 15601 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15602 info.sendPackageRemovedBroadcasts(killApp); 15603 info.sendSystemPackageUpdatedBroadcasts(); 15604 info.sendSystemPackageAppearedBroadcasts(); 15605 } 15606 // Force a gc here. 15607 Runtime.getRuntime().gc(); 15608 // Delete the resources here after sending the broadcast to let 15609 // other processes clean up before deleting resources. 15610 if (info.args != null) { 15611 synchronized (mInstallLock) { 15612 info.args.doPostDeleteLI(true); 15613 } 15614 } 15615 15616 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15617 } 15618 15619 class PackageRemovedInfo { 15620 String removedPackage; 15621 int uid = -1; 15622 int removedAppId = -1; 15623 int[] origUsers; 15624 int[] removedUsers = null; 15625 boolean isRemovedPackageSystemUpdate = false; 15626 boolean isUpdate; 15627 boolean dataRemoved; 15628 boolean removedForAllUsers; 15629 // Clean up resources deleted packages. 15630 InstallArgs args = null; 15631 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15632 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15633 15634 void sendPackageRemovedBroadcasts(boolean killApp) { 15635 sendPackageRemovedBroadcastInternal(killApp); 15636 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15637 for (int i = 0; i < childCount; i++) { 15638 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15639 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15640 } 15641 } 15642 15643 void sendSystemPackageUpdatedBroadcasts() { 15644 if (isRemovedPackageSystemUpdate) { 15645 sendSystemPackageUpdatedBroadcastsInternal(); 15646 final int childCount = (removedChildPackages != null) 15647 ? removedChildPackages.size() : 0; 15648 for (int i = 0; i < childCount; i++) { 15649 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15650 if (childInfo.isRemovedPackageSystemUpdate) { 15651 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15652 } 15653 } 15654 } 15655 } 15656 15657 void sendSystemPackageAppearedBroadcasts() { 15658 final int packageCount = (appearedChildPackages != null) 15659 ? appearedChildPackages.size() : 0; 15660 for (int i = 0; i < packageCount; i++) { 15661 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15662 for (int userId : installedInfo.newUsers) { 15663 sendPackageAddedForUser(installedInfo.name, true, 15664 UserHandle.getAppId(installedInfo.uid), userId); 15665 } 15666 } 15667 } 15668 15669 private void sendSystemPackageUpdatedBroadcastsInternal() { 15670 Bundle extras = new Bundle(2); 15671 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15672 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15673 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15674 extras, 0, null, null, null); 15675 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15676 extras, 0, null, null, null); 15677 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15678 null, 0, removedPackage, null, null); 15679 } 15680 15681 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15682 Bundle extras = new Bundle(2); 15683 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15684 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15685 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15686 if (isUpdate || isRemovedPackageSystemUpdate) { 15687 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15688 } 15689 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15690 if (removedPackage != null) { 15691 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15692 extras, 0, null, null, removedUsers); 15693 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15694 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15695 removedPackage, extras, 0, null, null, removedUsers); 15696 } 15697 } 15698 if (removedAppId >= 0) { 15699 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15700 removedUsers); 15701 } 15702 } 15703 } 15704 15705 /* 15706 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15707 * flag is not set, the data directory is removed as well. 15708 * make sure this flag is set for partially installed apps. If not its meaningless to 15709 * delete a partially installed application. 15710 */ 15711 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15712 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15713 String packageName = ps.name; 15714 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15715 // Retrieve object to delete permissions for shared user later on 15716 final PackageParser.Package deletedPkg; 15717 final PackageSetting deletedPs; 15718 // reader 15719 synchronized (mPackages) { 15720 deletedPkg = mPackages.get(packageName); 15721 deletedPs = mSettings.mPackages.get(packageName); 15722 if (outInfo != null) { 15723 outInfo.removedPackage = packageName; 15724 outInfo.removedUsers = deletedPs != null 15725 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15726 : null; 15727 } 15728 } 15729 15730 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15731 15732 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15733 final PackageParser.Package resolvedPkg; 15734 if (deletedPkg != null) { 15735 resolvedPkg = deletedPkg; 15736 } else { 15737 // We don't have a parsed package when it lives on an ejected 15738 // adopted storage device, so fake something together 15739 resolvedPkg = new PackageParser.Package(ps.name); 15740 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15741 } 15742 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15743 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15744 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15745 if (outInfo != null) { 15746 outInfo.dataRemoved = true; 15747 } 15748 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15749 } 15750 15751 // writer 15752 synchronized (mPackages) { 15753 if (deletedPs != null) { 15754 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15755 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15756 clearDefaultBrowserIfNeeded(packageName); 15757 if (outInfo != null) { 15758 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15759 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15760 } 15761 updatePermissionsLPw(deletedPs.name, null, 0); 15762 if (deletedPs.sharedUser != null) { 15763 // Remove permissions associated with package. Since runtime 15764 // permissions are per user we have to kill the removed package 15765 // or packages running under the shared user of the removed 15766 // package if revoking the permissions requested only by the removed 15767 // package is successful and this causes a change in gids. 15768 for (int userId : UserManagerService.getInstance().getUserIds()) { 15769 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15770 userId); 15771 if (userIdToKill == UserHandle.USER_ALL 15772 || userIdToKill >= UserHandle.USER_SYSTEM) { 15773 // If gids changed for this user, kill all affected packages. 15774 mHandler.post(new Runnable() { 15775 @Override 15776 public void run() { 15777 // This has to happen with no lock held. 15778 killApplication(deletedPs.name, deletedPs.appId, 15779 KILL_APP_REASON_GIDS_CHANGED); 15780 } 15781 }); 15782 break; 15783 } 15784 } 15785 } 15786 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15787 } 15788 // make sure to preserve per-user disabled state if this removal was just 15789 // a downgrade of a system app to the factory package 15790 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15791 if (DEBUG_REMOVE) { 15792 Slog.d(TAG, "Propagating install state across downgrade"); 15793 } 15794 for (int userId : allUserHandles) { 15795 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15796 if (DEBUG_REMOVE) { 15797 Slog.d(TAG, " user " + userId + " => " + installed); 15798 } 15799 ps.setInstalled(installed, userId); 15800 } 15801 } 15802 } 15803 // can downgrade to reader 15804 if (writeSettings) { 15805 // Save settings now 15806 mSettings.writeLPr(); 15807 } 15808 } 15809 if (outInfo != null) { 15810 // A user ID was deleted here. Go through all users and remove it 15811 // from KeyStore. 15812 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15813 } 15814 } 15815 15816 static boolean locationIsPrivileged(File path) { 15817 try { 15818 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15819 .getCanonicalPath(); 15820 return path.getCanonicalPath().startsWith(privilegedAppDir); 15821 } catch (IOException e) { 15822 Slog.e(TAG, "Unable to access code path " + path); 15823 } 15824 return false; 15825 } 15826 15827 /* 15828 * Tries to delete system package. 15829 */ 15830 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15831 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15832 boolean writeSettings) { 15833 if (deletedPs.parentPackageName != null) { 15834 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15835 return false; 15836 } 15837 15838 final boolean applyUserRestrictions 15839 = (allUserHandles != null) && (outInfo.origUsers != null); 15840 final PackageSetting disabledPs; 15841 // Confirm if the system package has been updated 15842 // An updated system app can be deleted. This will also have to restore 15843 // the system pkg from system partition 15844 // reader 15845 synchronized (mPackages) { 15846 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15847 } 15848 15849 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15850 + " disabledPs=" + disabledPs); 15851 15852 if (disabledPs == null) { 15853 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15854 return false; 15855 } else if (DEBUG_REMOVE) { 15856 Slog.d(TAG, "Deleting system pkg from data partition"); 15857 } 15858 15859 if (DEBUG_REMOVE) { 15860 if (applyUserRestrictions) { 15861 Slog.d(TAG, "Remembering install states:"); 15862 for (int userId : allUserHandles) { 15863 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15864 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15865 } 15866 } 15867 } 15868 15869 // Delete the updated package 15870 outInfo.isRemovedPackageSystemUpdate = true; 15871 if (outInfo.removedChildPackages != null) { 15872 final int childCount = (deletedPs.childPackageNames != null) 15873 ? deletedPs.childPackageNames.size() : 0; 15874 for (int i = 0; i < childCount; i++) { 15875 String childPackageName = deletedPs.childPackageNames.get(i); 15876 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15877 .contains(childPackageName)) { 15878 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15879 childPackageName); 15880 if (childInfo != null) { 15881 childInfo.isRemovedPackageSystemUpdate = true; 15882 } 15883 } 15884 } 15885 } 15886 15887 if (disabledPs.versionCode < deletedPs.versionCode) { 15888 // Delete data for downgrades 15889 flags &= ~PackageManager.DELETE_KEEP_DATA; 15890 } else { 15891 // Preserve data by setting flag 15892 flags |= PackageManager.DELETE_KEEP_DATA; 15893 } 15894 15895 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15896 outInfo, writeSettings, disabledPs.pkg); 15897 if (!ret) { 15898 return false; 15899 } 15900 15901 // writer 15902 synchronized (mPackages) { 15903 // Reinstate the old system package 15904 enableSystemPackageLPw(disabledPs.pkg); 15905 // Remove any native libraries from the upgraded package. 15906 removeNativeBinariesLI(deletedPs); 15907 } 15908 15909 // Install the system package 15910 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15911 int parseFlags = mDefParseFlags 15912 | PackageParser.PARSE_MUST_BE_APK 15913 | PackageParser.PARSE_IS_SYSTEM 15914 | PackageParser.PARSE_IS_SYSTEM_DIR; 15915 if (locationIsPrivileged(disabledPs.codePath)) { 15916 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15917 } 15918 15919 final PackageParser.Package newPkg; 15920 try { 15921 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15922 } catch (PackageManagerException e) { 15923 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15924 + e.getMessage()); 15925 return false; 15926 } 15927 15928 prepareAppDataAfterInstallLIF(newPkg); 15929 15930 // writer 15931 synchronized (mPackages) { 15932 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15933 15934 // Propagate the permissions state as we do not want to drop on the floor 15935 // runtime permissions. The update permissions method below will take 15936 // care of removing obsolete permissions and grant install permissions. 15937 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15938 updatePermissionsLPw(newPkg.packageName, newPkg, 15939 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15940 15941 if (applyUserRestrictions) { 15942 if (DEBUG_REMOVE) { 15943 Slog.d(TAG, "Propagating install state across reinstall"); 15944 } 15945 for (int userId : allUserHandles) { 15946 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15947 if (DEBUG_REMOVE) { 15948 Slog.d(TAG, " user " + userId + " => " + installed); 15949 } 15950 ps.setInstalled(installed, userId); 15951 15952 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15953 } 15954 // Regardless of writeSettings we need to ensure that this restriction 15955 // state propagation is persisted 15956 mSettings.writeAllUsersPackageRestrictionsLPr(); 15957 } 15958 // can downgrade to reader here 15959 if (writeSettings) { 15960 mSettings.writeLPr(); 15961 } 15962 } 15963 return true; 15964 } 15965 15966 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15967 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15968 PackageRemovedInfo outInfo, boolean writeSettings, 15969 PackageParser.Package replacingPackage) { 15970 synchronized (mPackages) { 15971 if (outInfo != null) { 15972 outInfo.uid = ps.appId; 15973 } 15974 15975 if (outInfo != null && outInfo.removedChildPackages != null) { 15976 final int childCount = (ps.childPackageNames != null) 15977 ? ps.childPackageNames.size() : 0; 15978 for (int i = 0; i < childCount; i++) { 15979 String childPackageName = ps.childPackageNames.get(i); 15980 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15981 if (childPs == null) { 15982 return false; 15983 } 15984 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15985 childPackageName); 15986 if (childInfo != null) { 15987 childInfo.uid = childPs.appId; 15988 } 15989 } 15990 } 15991 } 15992 15993 // Delete package data from internal structures and also remove data if flag is set 15994 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15995 15996 // Delete the child packages data 15997 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15998 for (int i = 0; i < childCount; i++) { 15999 PackageSetting childPs; 16000 synchronized (mPackages) { 16001 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16002 } 16003 if (childPs != null) { 16004 PackageRemovedInfo childOutInfo = (outInfo != null 16005 && outInfo.removedChildPackages != null) 16006 ? outInfo.removedChildPackages.get(childPs.name) : null; 16007 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16008 && (replacingPackage != null 16009 && !replacingPackage.hasChildPackage(childPs.name)) 16010 ? flags & ~DELETE_KEEP_DATA : flags; 16011 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16012 deleteFlags, writeSettings); 16013 } 16014 } 16015 16016 // Delete application code and resources only for parent packages 16017 if (ps.parentPackageName == null) { 16018 if (deleteCodeAndResources && (outInfo != null)) { 16019 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16020 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16021 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16022 } 16023 } 16024 16025 return true; 16026 } 16027 16028 @Override 16029 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16030 int userId) { 16031 mContext.enforceCallingOrSelfPermission( 16032 android.Manifest.permission.DELETE_PACKAGES, null); 16033 synchronized (mPackages) { 16034 PackageSetting ps = mSettings.mPackages.get(packageName); 16035 if (ps == null) { 16036 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16037 return false; 16038 } 16039 if (!ps.getInstalled(userId)) { 16040 // Can't block uninstall for an app that is not installed or enabled. 16041 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16042 return false; 16043 } 16044 ps.setBlockUninstall(blockUninstall, userId); 16045 mSettings.writePackageRestrictionsLPr(userId); 16046 } 16047 return true; 16048 } 16049 16050 @Override 16051 public boolean getBlockUninstallForUser(String packageName, int userId) { 16052 synchronized (mPackages) { 16053 PackageSetting ps = mSettings.mPackages.get(packageName); 16054 if (ps == null) { 16055 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16056 return false; 16057 } 16058 return ps.getBlockUninstall(userId); 16059 } 16060 } 16061 16062 @Override 16063 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16064 int callingUid = Binder.getCallingUid(); 16065 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16066 throw new SecurityException( 16067 "setRequiredForSystemUser can only be run by the system or root"); 16068 } 16069 synchronized (mPackages) { 16070 PackageSetting ps = mSettings.mPackages.get(packageName); 16071 if (ps == null) { 16072 Log.w(TAG, "Package doesn't exist: " + packageName); 16073 return false; 16074 } 16075 if (systemUserApp) { 16076 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16077 } else { 16078 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16079 } 16080 mSettings.writeLPr(); 16081 } 16082 return true; 16083 } 16084 16085 /* 16086 * This method handles package deletion in general 16087 */ 16088 private boolean deletePackageLIF(String packageName, UserHandle user, 16089 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16090 PackageRemovedInfo outInfo, boolean writeSettings, 16091 PackageParser.Package replacingPackage) { 16092 if (packageName == null) { 16093 Slog.w(TAG, "Attempt to delete null packageName."); 16094 return false; 16095 } 16096 16097 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16098 16099 PackageSetting ps; 16100 16101 synchronized (mPackages) { 16102 ps = mSettings.mPackages.get(packageName); 16103 if (ps == null) { 16104 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16105 return false; 16106 } 16107 16108 if (ps.parentPackageName != null && (!isSystemApp(ps) 16109 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16110 if (DEBUG_REMOVE) { 16111 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16112 + ((user == null) ? UserHandle.USER_ALL : user)); 16113 } 16114 final int removedUserId = (user != null) ? user.getIdentifier() 16115 : UserHandle.USER_ALL; 16116 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16117 return false; 16118 } 16119 markPackageUninstalledForUserLPw(ps, user); 16120 scheduleWritePackageRestrictionsLocked(user); 16121 return true; 16122 } 16123 } 16124 16125 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16126 && user.getIdentifier() != UserHandle.USER_ALL)) { 16127 // The caller is asking that the package only be deleted for a single 16128 // user. To do this, we just mark its uninstalled state and delete 16129 // its data. If this is a system app, we only allow this to happen if 16130 // they have set the special DELETE_SYSTEM_APP which requests different 16131 // semantics than normal for uninstalling system apps. 16132 markPackageUninstalledForUserLPw(ps, user); 16133 16134 if (!isSystemApp(ps)) { 16135 // Do not uninstall the APK if an app should be cached 16136 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16137 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16138 // Other user still have this package installed, so all 16139 // we need to do is clear this user's data and save that 16140 // it is uninstalled. 16141 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16142 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16143 return false; 16144 } 16145 scheduleWritePackageRestrictionsLocked(user); 16146 return true; 16147 } else { 16148 // We need to set it back to 'installed' so the uninstall 16149 // broadcasts will be sent correctly. 16150 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16151 ps.setInstalled(true, user.getIdentifier()); 16152 } 16153 } else { 16154 // This is a system app, so we assume that the 16155 // other users still have this package installed, so all 16156 // we need to do is clear this user's data and save that 16157 // it is uninstalled. 16158 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16159 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16160 return false; 16161 } 16162 scheduleWritePackageRestrictionsLocked(user); 16163 return true; 16164 } 16165 } 16166 16167 // If we are deleting a composite package for all users, keep track 16168 // of result for each child. 16169 if (ps.childPackageNames != null && outInfo != null) { 16170 synchronized (mPackages) { 16171 final int childCount = ps.childPackageNames.size(); 16172 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16173 for (int i = 0; i < childCount; i++) { 16174 String childPackageName = ps.childPackageNames.get(i); 16175 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16176 childInfo.removedPackage = childPackageName; 16177 outInfo.removedChildPackages.put(childPackageName, childInfo); 16178 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16179 if (childPs != null) { 16180 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16181 } 16182 } 16183 } 16184 } 16185 16186 boolean ret = false; 16187 if (isSystemApp(ps)) { 16188 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16189 // When an updated system application is deleted we delete the existing resources 16190 // as well and fall back to existing code in system partition 16191 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16192 } else { 16193 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16194 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16195 outInfo, writeSettings, replacingPackage); 16196 } 16197 16198 // Take a note whether we deleted the package for all users 16199 if (outInfo != null) { 16200 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16201 if (outInfo.removedChildPackages != null) { 16202 synchronized (mPackages) { 16203 final int childCount = outInfo.removedChildPackages.size(); 16204 for (int i = 0; i < childCount; i++) { 16205 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16206 if (childInfo != null) { 16207 childInfo.removedForAllUsers = mPackages.get( 16208 childInfo.removedPackage) == null; 16209 } 16210 } 16211 } 16212 } 16213 // If we uninstalled an update to a system app there may be some 16214 // child packages that appeared as they are declared in the system 16215 // app but were not declared in the update. 16216 if (isSystemApp(ps)) { 16217 synchronized (mPackages) { 16218 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16219 final int childCount = (updatedPs.childPackageNames != null) 16220 ? updatedPs.childPackageNames.size() : 0; 16221 for (int i = 0; i < childCount; i++) { 16222 String childPackageName = updatedPs.childPackageNames.get(i); 16223 if (outInfo.removedChildPackages == null 16224 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16225 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16226 if (childPs == null) { 16227 continue; 16228 } 16229 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16230 installRes.name = childPackageName; 16231 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16232 installRes.pkg = mPackages.get(childPackageName); 16233 installRes.uid = childPs.pkg.applicationInfo.uid; 16234 if (outInfo.appearedChildPackages == null) { 16235 outInfo.appearedChildPackages = new ArrayMap<>(); 16236 } 16237 outInfo.appearedChildPackages.put(childPackageName, installRes); 16238 } 16239 } 16240 } 16241 } 16242 } 16243 16244 return ret; 16245 } 16246 16247 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16248 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16249 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16250 for (int nextUserId : userIds) { 16251 if (DEBUG_REMOVE) { 16252 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16253 } 16254 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16255 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16256 false /*hidden*/, false /*suspended*/, null, null, null, 16257 false /*blockUninstall*/, 16258 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16259 } 16260 } 16261 16262 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16263 PackageRemovedInfo outInfo) { 16264 final PackageParser.Package pkg; 16265 synchronized (mPackages) { 16266 pkg = mPackages.get(ps.name); 16267 } 16268 16269 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16270 : new int[] {userId}; 16271 for (int nextUserId : userIds) { 16272 if (DEBUG_REMOVE) { 16273 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16274 + nextUserId); 16275 } 16276 16277 destroyAppDataLIF(pkg, userId, 16278 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16279 destroyAppProfilesLIF(pkg, userId); 16280 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16281 schedulePackageCleaning(ps.name, nextUserId, false); 16282 synchronized (mPackages) { 16283 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16284 scheduleWritePackageRestrictionsLocked(nextUserId); 16285 } 16286 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16287 } 16288 } 16289 16290 if (outInfo != null) { 16291 outInfo.removedPackage = ps.name; 16292 outInfo.removedAppId = ps.appId; 16293 outInfo.removedUsers = userIds; 16294 } 16295 16296 return true; 16297 } 16298 16299 private final class ClearStorageConnection implements ServiceConnection { 16300 IMediaContainerService mContainerService; 16301 16302 @Override 16303 public void onServiceConnected(ComponentName name, IBinder service) { 16304 synchronized (this) { 16305 mContainerService = IMediaContainerService.Stub.asInterface(service); 16306 notifyAll(); 16307 } 16308 } 16309 16310 @Override 16311 public void onServiceDisconnected(ComponentName name) { 16312 } 16313 } 16314 16315 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16316 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16317 16318 final boolean mounted; 16319 if (Environment.isExternalStorageEmulated()) { 16320 mounted = true; 16321 } else { 16322 final String status = Environment.getExternalStorageState(); 16323 16324 mounted = status.equals(Environment.MEDIA_MOUNTED) 16325 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16326 } 16327 16328 if (!mounted) { 16329 return; 16330 } 16331 16332 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16333 int[] users; 16334 if (userId == UserHandle.USER_ALL) { 16335 users = sUserManager.getUserIds(); 16336 } else { 16337 users = new int[] { userId }; 16338 } 16339 final ClearStorageConnection conn = new ClearStorageConnection(); 16340 if (mContext.bindServiceAsUser( 16341 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16342 try { 16343 for (int curUser : users) { 16344 long timeout = SystemClock.uptimeMillis() + 5000; 16345 synchronized (conn) { 16346 long now = SystemClock.uptimeMillis(); 16347 while (conn.mContainerService == null && now < timeout) { 16348 try { 16349 conn.wait(timeout - now); 16350 } catch (InterruptedException e) { 16351 } 16352 } 16353 } 16354 if (conn.mContainerService == null) { 16355 return; 16356 } 16357 16358 final UserEnvironment userEnv = new UserEnvironment(curUser); 16359 clearDirectory(conn.mContainerService, 16360 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16361 if (allData) { 16362 clearDirectory(conn.mContainerService, 16363 userEnv.buildExternalStorageAppDataDirs(packageName)); 16364 clearDirectory(conn.mContainerService, 16365 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16366 } 16367 } 16368 } finally { 16369 mContext.unbindService(conn); 16370 } 16371 } 16372 } 16373 16374 @Override 16375 public void clearApplicationProfileData(String packageName) { 16376 enforceSystemOrRoot("Only the system can clear all profile data"); 16377 16378 final PackageParser.Package pkg; 16379 synchronized (mPackages) { 16380 pkg = mPackages.get(packageName); 16381 } 16382 16383 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16384 synchronized (mInstallLock) { 16385 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16386 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16387 true /* removeBaseMarker */); 16388 } 16389 } 16390 } 16391 16392 @Override 16393 public void clearApplicationUserData(final String packageName, 16394 final IPackageDataObserver observer, final int userId) { 16395 mContext.enforceCallingOrSelfPermission( 16396 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16397 16398 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16399 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16400 16401 if (mProtectedPackages.canPackageBeWiped(userId, packageName)) { 16402 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16403 } 16404 // Queue up an async operation since the package deletion may take a little while. 16405 mHandler.post(new Runnable() { 16406 public void run() { 16407 mHandler.removeCallbacks(this); 16408 final boolean succeeded; 16409 try (PackageFreezer freezer = freezePackage(packageName, 16410 "clearApplicationUserData")) { 16411 synchronized (mInstallLock) { 16412 succeeded = clearApplicationUserDataLIF(packageName, userId); 16413 } 16414 clearExternalStorageDataSync(packageName, userId, true); 16415 } 16416 if (succeeded) { 16417 // invoke DeviceStorageMonitor's update method to clear any notifications 16418 DeviceStorageMonitorInternal dsm = LocalServices 16419 .getService(DeviceStorageMonitorInternal.class); 16420 if (dsm != null) { 16421 dsm.checkMemory(); 16422 } 16423 } 16424 if(observer != null) { 16425 try { 16426 observer.onRemoveCompleted(packageName, succeeded); 16427 } catch (RemoteException e) { 16428 Log.i(TAG, "Observer no longer exists."); 16429 } 16430 } //end if observer 16431 } //end run 16432 }); 16433 } 16434 16435 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16436 if (packageName == null) { 16437 Slog.w(TAG, "Attempt to delete null packageName."); 16438 return false; 16439 } 16440 16441 // Try finding details about the requested package 16442 PackageParser.Package pkg; 16443 synchronized (mPackages) { 16444 pkg = mPackages.get(packageName); 16445 if (pkg == null) { 16446 final PackageSetting ps = mSettings.mPackages.get(packageName); 16447 if (ps != null) { 16448 pkg = ps.pkg; 16449 } 16450 } 16451 16452 if (pkg == null) { 16453 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16454 return false; 16455 } 16456 16457 PackageSetting ps = (PackageSetting) pkg.mExtras; 16458 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16459 } 16460 16461 clearAppDataLIF(pkg, userId, 16462 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16463 16464 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16465 removeKeystoreDataIfNeeded(userId, appId); 16466 16467 UserManagerInternal umInternal = getUserManagerInternal(); 16468 final int flags; 16469 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16470 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16471 } else if (umInternal.isUserRunning(userId)) { 16472 flags = StorageManager.FLAG_STORAGE_DE; 16473 } else { 16474 flags = 0; 16475 } 16476 prepareAppDataContentsLIF(pkg, userId, flags); 16477 16478 return true; 16479 } 16480 16481 /** 16482 * Reverts user permission state changes (permissions and flags) in 16483 * all packages for a given user. 16484 * 16485 * @param userId The device user for which to do a reset. 16486 */ 16487 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16488 final int packageCount = mPackages.size(); 16489 for (int i = 0; i < packageCount; i++) { 16490 PackageParser.Package pkg = mPackages.valueAt(i); 16491 PackageSetting ps = (PackageSetting) pkg.mExtras; 16492 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16493 } 16494 } 16495 16496 private void resetNetworkPolicies(int userId) { 16497 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16498 } 16499 16500 /** 16501 * Reverts user permission state changes (permissions and flags). 16502 * 16503 * @param ps The package for which to reset. 16504 * @param userId The device user for which to do a reset. 16505 */ 16506 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16507 final PackageSetting ps, final int userId) { 16508 if (ps.pkg == null) { 16509 return; 16510 } 16511 16512 // These are flags that can change base on user actions. 16513 final int userSettableMask = FLAG_PERMISSION_USER_SET 16514 | FLAG_PERMISSION_USER_FIXED 16515 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16516 | FLAG_PERMISSION_REVIEW_REQUIRED; 16517 16518 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16519 | FLAG_PERMISSION_POLICY_FIXED; 16520 16521 boolean writeInstallPermissions = false; 16522 boolean writeRuntimePermissions = false; 16523 16524 final int permissionCount = ps.pkg.requestedPermissions.size(); 16525 for (int i = 0; i < permissionCount; i++) { 16526 String permission = ps.pkg.requestedPermissions.get(i); 16527 16528 BasePermission bp = mSettings.mPermissions.get(permission); 16529 if (bp == null) { 16530 continue; 16531 } 16532 16533 // If shared user we just reset the state to which only this app contributed. 16534 if (ps.sharedUser != null) { 16535 boolean used = false; 16536 final int packageCount = ps.sharedUser.packages.size(); 16537 for (int j = 0; j < packageCount; j++) { 16538 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16539 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16540 && pkg.pkg.requestedPermissions.contains(permission)) { 16541 used = true; 16542 break; 16543 } 16544 } 16545 if (used) { 16546 continue; 16547 } 16548 } 16549 16550 PermissionsState permissionsState = ps.getPermissionsState(); 16551 16552 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16553 16554 // Always clear the user settable flags. 16555 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16556 bp.name) != null; 16557 // If permission review is enabled and this is a legacy app, mark the 16558 // permission as requiring a review as this is the initial state. 16559 int flags = 0; 16560 if (Build.PERMISSIONS_REVIEW_REQUIRED 16561 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16562 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16563 } 16564 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16565 if (hasInstallState) { 16566 writeInstallPermissions = true; 16567 } else { 16568 writeRuntimePermissions = true; 16569 } 16570 } 16571 16572 // Below is only runtime permission handling. 16573 if (!bp.isRuntime()) { 16574 continue; 16575 } 16576 16577 // Never clobber system or policy. 16578 if ((oldFlags & policyOrSystemFlags) != 0) { 16579 continue; 16580 } 16581 16582 // If this permission was granted by default, make sure it is. 16583 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16584 if (permissionsState.grantRuntimePermission(bp, userId) 16585 != PERMISSION_OPERATION_FAILURE) { 16586 writeRuntimePermissions = true; 16587 } 16588 // If permission review is enabled the permissions for a legacy apps 16589 // are represented as constantly granted runtime ones, so don't revoke. 16590 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16591 // Otherwise, reset the permission. 16592 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16593 switch (revokeResult) { 16594 case PERMISSION_OPERATION_SUCCESS: 16595 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16596 writeRuntimePermissions = true; 16597 final int appId = ps.appId; 16598 mHandler.post(new Runnable() { 16599 @Override 16600 public void run() { 16601 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16602 } 16603 }); 16604 } break; 16605 } 16606 } 16607 } 16608 16609 // Synchronously write as we are taking permissions away. 16610 if (writeRuntimePermissions) { 16611 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16612 } 16613 16614 // Synchronously write as we are taking permissions away. 16615 if (writeInstallPermissions) { 16616 mSettings.writeLPr(); 16617 } 16618 } 16619 16620 /** 16621 * Remove entries from the keystore daemon. Will only remove it if the 16622 * {@code appId} is valid. 16623 */ 16624 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16625 if (appId < 0) { 16626 return; 16627 } 16628 16629 final KeyStore keyStore = KeyStore.getInstance(); 16630 if (keyStore != null) { 16631 if (userId == UserHandle.USER_ALL) { 16632 for (final int individual : sUserManager.getUserIds()) { 16633 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16634 } 16635 } else { 16636 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16637 } 16638 } else { 16639 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16640 } 16641 } 16642 16643 @Override 16644 public void deleteApplicationCacheFiles(final String packageName, 16645 final IPackageDataObserver observer) { 16646 final int userId = UserHandle.getCallingUserId(); 16647 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16648 } 16649 16650 @Override 16651 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16652 final IPackageDataObserver observer) { 16653 mContext.enforceCallingOrSelfPermission( 16654 android.Manifest.permission.DELETE_CACHE_FILES, null); 16655 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16656 /* requireFullPermission= */ true, /* checkShell= */ false, 16657 "delete application cache files"); 16658 16659 final PackageParser.Package pkg; 16660 synchronized (mPackages) { 16661 pkg = mPackages.get(packageName); 16662 } 16663 16664 // Queue up an async operation since the package deletion may take a little while. 16665 mHandler.post(new Runnable() { 16666 public void run() { 16667 synchronized (mInstallLock) { 16668 final int flags = StorageManager.FLAG_STORAGE_DE 16669 | StorageManager.FLAG_STORAGE_CE; 16670 // We're only clearing cache files, so we don't care if the 16671 // app is unfrozen and still able to run 16672 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16673 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16674 } 16675 clearExternalStorageDataSync(packageName, userId, false); 16676 if (observer != null) { 16677 try { 16678 observer.onRemoveCompleted(packageName, true); 16679 } catch (RemoteException e) { 16680 Log.i(TAG, "Observer no longer exists."); 16681 } 16682 } 16683 } 16684 }); 16685 } 16686 16687 @Override 16688 public void getPackageSizeInfo(final String packageName, int userHandle, 16689 final IPackageStatsObserver observer) { 16690 mContext.enforceCallingOrSelfPermission( 16691 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16692 if (packageName == null) { 16693 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16694 } 16695 16696 PackageStats stats = new PackageStats(packageName, userHandle); 16697 16698 /* 16699 * Queue up an async operation since the package measurement may take a 16700 * little while. 16701 */ 16702 Message msg = mHandler.obtainMessage(INIT_COPY); 16703 msg.obj = new MeasureParams(stats, observer); 16704 mHandler.sendMessage(msg); 16705 } 16706 16707 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16708 final PackageSetting ps; 16709 synchronized (mPackages) { 16710 ps = mSettings.mPackages.get(packageName); 16711 if (ps == null) { 16712 Slog.w(TAG, "Failed to find settings for " + packageName); 16713 return false; 16714 } 16715 } 16716 try { 16717 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16718 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16719 ps.getCeDataInode(userId), ps.codePathString, stats); 16720 } catch (InstallerException e) { 16721 Slog.w(TAG, String.valueOf(e)); 16722 return false; 16723 } 16724 16725 // For now, ignore code size of packages on system partition 16726 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16727 stats.codeSize = 0; 16728 } 16729 16730 return true; 16731 } 16732 16733 private int getUidTargetSdkVersionLockedLPr(int uid) { 16734 Object obj = mSettings.getUserIdLPr(uid); 16735 if (obj instanceof SharedUserSetting) { 16736 final SharedUserSetting sus = (SharedUserSetting) obj; 16737 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16738 final Iterator<PackageSetting> it = sus.packages.iterator(); 16739 while (it.hasNext()) { 16740 final PackageSetting ps = it.next(); 16741 if (ps.pkg != null) { 16742 int v = ps.pkg.applicationInfo.targetSdkVersion; 16743 if (v < vers) vers = v; 16744 } 16745 } 16746 return vers; 16747 } else if (obj instanceof PackageSetting) { 16748 final PackageSetting ps = (PackageSetting) obj; 16749 if (ps.pkg != null) { 16750 return ps.pkg.applicationInfo.targetSdkVersion; 16751 } 16752 } 16753 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16754 } 16755 16756 @Override 16757 public void addPreferredActivity(IntentFilter filter, int match, 16758 ComponentName[] set, ComponentName activity, int userId) { 16759 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16760 "Adding preferred"); 16761 } 16762 16763 private void addPreferredActivityInternal(IntentFilter filter, int match, 16764 ComponentName[] set, ComponentName activity, boolean always, int userId, 16765 String opname) { 16766 // writer 16767 int callingUid = Binder.getCallingUid(); 16768 enforceCrossUserPermission(callingUid, userId, 16769 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16770 if (filter.countActions() == 0) { 16771 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16772 return; 16773 } 16774 synchronized (mPackages) { 16775 if (mContext.checkCallingOrSelfPermission( 16776 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16777 != PackageManager.PERMISSION_GRANTED) { 16778 if (getUidTargetSdkVersionLockedLPr(callingUid) 16779 < Build.VERSION_CODES.FROYO) { 16780 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16781 + callingUid); 16782 return; 16783 } 16784 mContext.enforceCallingOrSelfPermission( 16785 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16786 } 16787 16788 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16789 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16790 + userId + ":"); 16791 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16792 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16793 scheduleWritePackageRestrictionsLocked(userId); 16794 } 16795 } 16796 16797 @Override 16798 public void replacePreferredActivity(IntentFilter filter, int match, 16799 ComponentName[] set, ComponentName activity, int userId) { 16800 if (filter.countActions() != 1) { 16801 throw new IllegalArgumentException( 16802 "replacePreferredActivity expects filter to have only 1 action."); 16803 } 16804 if (filter.countDataAuthorities() != 0 16805 || filter.countDataPaths() != 0 16806 || filter.countDataSchemes() > 1 16807 || filter.countDataTypes() != 0) { 16808 throw new IllegalArgumentException( 16809 "replacePreferredActivity expects filter to have no data authorities, " + 16810 "paths, or types; and at most one scheme."); 16811 } 16812 16813 final int callingUid = Binder.getCallingUid(); 16814 enforceCrossUserPermission(callingUid, userId, 16815 true /* requireFullPermission */, false /* checkShell */, 16816 "replace preferred activity"); 16817 synchronized (mPackages) { 16818 if (mContext.checkCallingOrSelfPermission( 16819 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16820 != PackageManager.PERMISSION_GRANTED) { 16821 if (getUidTargetSdkVersionLockedLPr(callingUid) 16822 < Build.VERSION_CODES.FROYO) { 16823 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16824 + Binder.getCallingUid()); 16825 return; 16826 } 16827 mContext.enforceCallingOrSelfPermission( 16828 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16829 } 16830 16831 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16832 if (pir != null) { 16833 // Get all of the existing entries that exactly match this filter. 16834 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16835 if (existing != null && existing.size() == 1) { 16836 PreferredActivity cur = existing.get(0); 16837 if (DEBUG_PREFERRED) { 16838 Slog.i(TAG, "Checking replace of preferred:"); 16839 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16840 if (!cur.mPref.mAlways) { 16841 Slog.i(TAG, " -- CUR; not mAlways!"); 16842 } else { 16843 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16844 Slog.i(TAG, " -- CUR: mSet=" 16845 + Arrays.toString(cur.mPref.mSetComponents)); 16846 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16847 Slog.i(TAG, " -- NEW: mMatch=" 16848 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16849 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16850 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16851 } 16852 } 16853 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16854 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16855 && cur.mPref.sameSet(set)) { 16856 // Setting the preferred activity to what it happens to be already 16857 if (DEBUG_PREFERRED) { 16858 Slog.i(TAG, "Replacing with same preferred activity " 16859 + cur.mPref.mShortComponent + " for user " 16860 + userId + ":"); 16861 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16862 } 16863 return; 16864 } 16865 } 16866 16867 if (existing != null) { 16868 if (DEBUG_PREFERRED) { 16869 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16870 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16871 } 16872 for (int i = 0; i < existing.size(); i++) { 16873 PreferredActivity pa = existing.get(i); 16874 if (DEBUG_PREFERRED) { 16875 Slog.i(TAG, "Removing existing preferred activity " 16876 + pa.mPref.mComponent + ":"); 16877 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16878 } 16879 pir.removeFilter(pa); 16880 } 16881 } 16882 } 16883 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16884 "Replacing preferred"); 16885 } 16886 } 16887 16888 @Override 16889 public void clearPackagePreferredActivities(String packageName) { 16890 final int uid = Binder.getCallingUid(); 16891 // writer 16892 synchronized (mPackages) { 16893 PackageParser.Package pkg = mPackages.get(packageName); 16894 if (pkg == null || pkg.applicationInfo.uid != uid) { 16895 if (mContext.checkCallingOrSelfPermission( 16896 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16897 != PackageManager.PERMISSION_GRANTED) { 16898 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16899 < Build.VERSION_CODES.FROYO) { 16900 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16901 + Binder.getCallingUid()); 16902 return; 16903 } 16904 mContext.enforceCallingOrSelfPermission( 16905 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16906 } 16907 } 16908 16909 int user = UserHandle.getCallingUserId(); 16910 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16911 scheduleWritePackageRestrictionsLocked(user); 16912 } 16913 } 16914 } 16915 16916 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16917 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16918 ArrayList<PreferredActivity> removed = null; 16919 boolean changed = false; 16920 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16921 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16922 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16923 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16924 continue; 16925 } 16926 Iterator<PreferredActivity> it = pir.filterIterator(); 16927 while (it.hasNext()) { 16928 PreferredActivity pa = it.next(); 16929 // Mark entry for removal only if it matches the package name 16930 // and the entry is of type "always". 16931 if (packageName == null || 16932 (pa.mPref.mComponent.getPackageName().equals(packageName) 16933 && pa.mPref.mAlways)) { 16934 if (removed == null) { 16935 removed = new ArrayList<PreferredActivity>(); 16936 } 16937 removed.add(pa); 16938 } 16939 } 16940 if (removed != null) { 16941 for (int j=0; j<removed.size(); j++) { 16942 PreferredActivity pa = removed.get(j); 16943 pir.removeFilter(pa); 16944 } 16945 changed = true; 16946 } 16947 } 16948 return changed; 16949 } 16950 16951 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16952 private void clearIntentFilterVerificationsLPw(int userId) { 16953 final int packageCount = mPackages.size(); 16954 for (int i = 0; i < packageCount; i++) { 16955 PackageParser.Package pkg = mPackages.valueAt(i); 16956 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16957 } 16958 } 16959 16960 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16961 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16962 if (userId == UserHandle.USER_ALL) { 16963 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16964 sUserManager.getUserIds())) { 16965 for (int oneUserId : sUserManager.getUserIds()) { 16966 scheduleWritePackageRestrictionsLocked(oneUserId); 16967 } 16968 } 16969 } else { 16970 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16971 scheduleWritePackageRestrictionsLocked(userId); 16972 } 16973 } 16974 } 16975 16976 void clearDefaultBrowserIfNeeded(String packageName) { 16977 for (int oneUserId : sUserManager.getUserIds()) { 16978 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16979 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16980 if (packageName.equals(defaultBrowserPackageName)) { 16981 setDefaultBrowserPackageName(null, oneUserId); 16982 } 16983 } 16984 } 16985 16986 @Override 16987 public void resetApplicationPreferences(int userId) { 16988 mContext.enforceCallingOrSelfPermission( 16989 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16990 final long identity = Binder.clearCallingIdentity(); 16991 // writer 16992 try { 16993 synchronized (mPackages) { 16994 clearPackagePreferredActivitiesLPw(null, userId); 16995 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16996 // TODO: We have to reset the default SMS and Phone. This requires 16997 // significant refactoring to keep all default apps in the package 16998 // manager (cleaner but more work) or have the services provide 16999 // callbacks to the package manager to request a default app reset. 17000 applyFactoryDefaultBrowserLPw(userId); 17001 clearIntentFilterVerificationsLPw(userId); 17002 primeDomainVerificationsLPw(userId); 17003 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17004 scheduleWritePackageRestrictionsLocked(userId); 17005 } 17006 resetNetworkPolicies(userId); 17007 } finally { 17008 Binder.restoreCallingIdentity(identity); 17009 } 17010 } 17011 17012 @Override 17013 public int getPreferredActivities(List<IntentFilter> outFilters, 17014 List<ComponentName> outActivities, String packageName) { 17015 17016 int num = 0; 17017 final int userId = UserHandle.getCallingUserId(); 17018 // reader 17019 synchronized (mPackages) { 17020 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17021 if (pir != null) { 17022 final Iterator<PreferredActivity> it = pir.filterIterator(); 17023 while (it.hasNext()) { 17024 final PreferredActivity pa = it.next(); 17025 if (packageName == null 17026 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17027 && pa.mPref.mAlways)) { 17028 if (outFilters != null) { 17029 outFilters.add(new IntentFilter(pa)); 17030 } 17031 if (outActivities != null) { 17032 outActivities.add(pa.mPref.mComponent); 17033 } 17034 } 17035 } 17036 } 17037 } 17038 17039 return num; 17040 } 17041 17042 @Override 17043 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17044 int userId) { 17045 int callingUid = Binder.getCallingUid(); 17046 if (callingUid != Process.SYSTEM_UID) { 17047 throw new SecurityException( 17048 "addPersistentPreferredActivity can only be run by the system"); 17049 } 17050 if (filter.countActions() == 0) { 17051 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17052 return; 17053 } 17054 synchronized (mPackages) { 17055 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17056 ":"); 17057 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17058 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17059 new PersistentPreferredActivity(filter, activity)); 17060 scheduleWritePackageRestrictionsLocked(userId); 17061 } 17062 } 17063 17064 @Override 17065 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17066 int callingUid = Binder.getCallingUid(); 17067 if (callingUid != Process.SYSTEM_UID) { 17068 throw new SecurityException( 17069 "clearPackagePersistentPreferredActivities can only be run by the system"); 17070 } 17071 ArrayList<PersistentPreferredActivity> removed = null; 17072 boolean changed = false; 17073 synchronized (mPackages) { 17074 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17075 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17076 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17077 .valueAt(i); 17078 if (userId != thisUserId) { 17079 continue; 17080 } 17081 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17082 while (it.hasNext()) { 17083 PersistentPreferredActivity ppa = it.next(); 17084 // Mark entry for removal only if it matches the package name. 17085 if (ppa.mComponent.getPackageName().equals(packageName)) { 17086 if (removed == null) { 17087 removed = new ArrayList<PersistentPreferredActivity>(); 17088 } 17089 removed.add(ppa); 17090 } 17091 } 17092 if (removed != null) { 17093 for (int j=0; j<removed.size(); j++) { 17094 PersistentPreferredActivity ppa = removed.get(j); 17095 ppir.removeFilter(ppa); 17096 } 17097 changed = true; 17098 } 17099 } 17100 17101 if (changed) { 17102 scheduleWritePackageRestrictionsLocked(userId); 17103 } 17104 } 17105 } 17106 17107 /** 17108 * Common machinery for picking apart a restored XML blob and passing 17109 * it to a caller-supplied functor to be applied to the running system. 17110 */ 17111 private void restoreFromXml(XmlPullParser parser, int userId, 17112 String expectedStartTag, BlobXmlRestorer functor) 17113 throws IOException, XmlPullParserException { 17114 int type; 17115 while ((type = parser.next()) != XmlPullParser.START_TAG 17116 && type != XmlPullParser.END_DOCUMENT) { 17117 } 17118 if (type != XmlPullParser.START_TAG) { 17119 // oops didn't find a start tag?! 17120 if (DEBUG_BACKUP) { 17121 Slog.e(TAG, "Didn't find start tag during restore"); 17122 } 17123 return; 17124 } 17125Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17126 // this is supposed to be TAG_PREFERRED_BACKUP 17127 if (!expectedStartTag.equals(parser.getName())) { 17128 if (DEBUG_BACKUP) { 17129 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17130 } 17131 return; 17132 } 17133 17134 // skip interfering stuff, then we're aligned with the backing implementation 17135 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17136Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17137 functor.apply(parser, userId); 17138 } 17139 17140 private interface BlobXmlRestorer { 17141 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17142 } 17143 17144 /** 17145 * Non-Binder method, support for the backup/restore mechanism: write the 17146 * full set of preferred activities in its canonical XML format. Returns the 17147 * XML output as a byte array, or null if there is none. 17148 */ 17149 @Override 17150 public byte[] getPreferredActivityBackup(int userId) { 17151 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17152 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17153 } 17154 17155 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17156 try { 17157 final XmlSerializer serializer = new FastXmlSerializer(); 17158 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17159 serializer.startDocument(null, true); 17160 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17161 17162 synchronized (mPackages) { 17163 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17164 } 17165 17166 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17167 serializer.endDocument(); 17168 serializer.flush(); 17169 } catch (Exception e) { 17170 if (DEBUG_BACKUP) { 17171 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17172 } 17173 return null; 17174 } 17175 17176 return dataStream.toByteArray(); 17177 } 17178 17179 @Override 17180 public void restorePreferredActivities(byte[] backup, int userId) { 17181 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17182 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17183 } 17184 17185 try { 17186 final XmlPullParser parser = Xml.newPullParser(); 17187 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17188 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17189 new BlobXmlRestorer() { 17190 @Override 17191 public void apply(XmlPullParser parser, int userId) 17192 throws XmlPullParserException, IOException { 17193 synchronized (mPackages) { 17194 mSettings.readPreferredActivitiesLPw(parser, userId); 17195 } 17196 } 17197 } ); 17198 } catch (Exception e) { 17199 if (DEBUG_BACKUP) { 17200 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17201 } 17202 } 17203 } 17204 17205 /** 17206 * Non-Binder method, support for the backup/restore mechanism: write the 17207 * default browser (etc) settings in its canonical XML format. Returns the default 17208 * browser XML representation as a byte array, or null if there is none. 17209 */ 17210 @Override 17211 public byte[] getDefaultAppsBackup(int userId) { 17212 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17213 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17214 } 17215 17216 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17217 try { 17218 final XmlSerializer serializer = new FastXmlSerializer(); 17219 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17220 serializer.startDocument(null, true); 17221 serializer.startTag(null, TAG_DEFAULT_APPS); 17222 17223 synchronized (mPackages) { 17224 mSettings.writeDefaultAppsLPr(serializer, userId); 17225 } 17226 17227 serializer.endTag(null, TAG_DEFAULT_APPS); 17228 serializer.endDocument(); 17229 serializer.flush(); 17230 } catch (Exception e) { 17231 if (DEBUG_BACKUP) { 17232 Slog.e(TAG, "Unable to write default apps for backup", e); 17233 } 17234 return null; 17235 } 17236 17237 return dataStream.toByteArray(); 17238 } 17239 17240 @Override 17241 public void restoreDefaultApps(byte[] backup, int userId) { 17242 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17243 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17244 } 17245 17246 try { 17247 final XmlPullParser parser = Xml.newPullParser(); 17248 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17249 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17250 new BlobXmlRestorer() { 17251 @Override 17252 public void apply(XmlPullParser parser, int userId) 17253 throws XmlPullParserException, IOException { 17254 synchronized (mPackages) { 17255 mSettings.readDefaultAppsLPw(parser, userId); 17256 } 17257 } 17258 } ); 17259 } catch (Exception e) { 17260 if (DEBUG_BACKUP) { 17261 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17262 } 17263 } 17264 } 17265 17266 @Override 17267 public byte[] getIntentFilterVerificationBackup(int userId) { 17268 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17269 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17270 } 17271 17272 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17273 try { 17274 final XmlSerializer serializer = new FastXmlSerializer(); 17275 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17276 serializer.startDocument(null, true); 17277 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17278 17279 synchronized (mPackages) { 17280 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17281 } 17282 17283 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17284 serializer.endDocument(); 17285 serializer.flush(); 17286 } catch (Exception e) { 17287 if (DEBUG_BACKUP) { 17288 Slog.e(TAG, "Unable to write default apps for backup", e); 17289 } 17290 return null; 17291 } 17292 17293 return dataStream.toByteArray(); 17294 } 17295 17296 @Override 17297 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17298 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17299 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17300 } 17301 17302 try { 17303 final XmlPullParser parser = Xml.newPullParser(); 17304 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17305 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17306 new BlobXmlRestorer() { 17307 @Override 17308 public void apply(XmlPullParser parser, int userId) 17309 throws XmlPullParserException, IOException { 17310 synchronized (mPackages) { 17311 mSettings.readAllDomainVerificationsLPr(parser, userId); 17312 mSettings.writeLPr(); 17313 } 17314 } 17315 } ); 17316 } catch (Exception e) { 17317 if (DEBUG_BACKUP) { 17318 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17319 } 17320 } 17321 } 17322 17323 @Override 17324 public byte[] getPermissionGrantBackup(int userId) { 17325 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17326 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17327 } 17328 17329 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17330 try { 17331 final XmlSerializer serializer = new FastXmlSerializer(); 17332 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17333 serializer.startDocument(null, true); 17334 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17335 17336 synchronized (mPackages) { 17337 serializeRuntimePermissionGrantsLPr(serializer, userId); 17338 } 17339 17340 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17341 serializer.endDocument(); 17342 serializer.flush(); 17343 } catch (Exception e) { 17344 if (DEBUG_BACKUP) { 17345 Slog.e(TAG, "Unable to write default apps for backup", e); 17346 } 17347 return null; 17348 } 17349 17350 return dataStream.toByteArray(); 17351 } 17352 17353 @Override 17354 public void restorePermissionGrants(byte[] backup, int userId) { 17355 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17356 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17357 } 17358 17359 try { 17360 final XmlPullParser parser = Xml.newPullParser(); 17361 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17362 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17363 new BlobXmlRestorer() { 17364 @Override 17365 public void apply(XmlPullParser parser, int userId) 17366 throws XmlPullParserException, IOException { 17367 synchronized (mPackages) { 17368 processRestoredPermissionGrantsLPr(parser, userId); 17369 } 17370 } 17371 } ); 17372 } catch (Exception e) { 17373 if (DEBUG_BACKUP) { 17374 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17375 } 17376 } 17377 } 17378 17379 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17380 throws IOException { 17381 serializer.startTag(null, TAG_ALL_GRANTS); 17382 17383 final int N = mSettings.mPackages.size(); 17384 for (int i = 0; i < N; i++) { 17385 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17386 boolean pkgGrantsKnown = false; 17387 17388 PermissionsState packagePerms = ps.getPermissionsState(); 17389 17390 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17391 final int grantFlags = state.getFlags(); 17392 // only look at grants that are not system/policy fixed 17393 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17394 final boolean isGranted = state.isGranted(); 17395 // And only back up the user-twiddled state bits 17396 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17397 final String packageName = mSettings.mPackages.keyAt(i); 17398 if (!pkgGrantsKnown) { 17399 serializer.startTag(null, TAG_GRANT); 17400 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17401 pkgGrantsKnown = true; 17402 } 17403 17404 final boolean userSet = 17405 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17406 final boolean userFixed = 17407 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17408 final boolean revoke = 17409 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17410 17411 serializer.startTag(null, TAG_PERMISSION); 17412 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17413 if (isGranted) { 17414 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17415 } 17416 if (userSet) { 17417 serializer.attribute(null, ATTR_USER_SET, "true"); 17418 } 17419 if (userFixed) { 17420 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17421 } 17422 if (revoke) { 17423 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17424 } 17425 serializer.endTag(null, TAG_PERMISSION); 17426 } 17427 } 17428 } 17429 17430 if (pkgGrantsKnown) { 17431 serializer.endTag(null, TAG_GRANT); 17432 } 17433 } 17434 17435 serializer.endTag(null, TAG_ALL_GRANTS); 17436 } 17437 17438 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17439 throws XmlPullParserException, IOException { 17440 String pkgName = null; 17441 int outerDepth = parser.getDepth(); 17442 int type; 17443 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17444 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17445 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17446 continue; 17447 } 17448 17449 final String tagName = parser.getName(); 17450 if (tagName.equals(TAG_GRANT)) { 17451 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17452 if (DEBUG_BACKUP) { 17453 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17454 } 17455 } else if (tagName.equals(TAG_PERMISSION)) { 17456 17457 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17458 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17459 17460 int newFlagSet = 0; 17461 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17462 newFlagSet |= FLAG_PERMISSION_USER_SET; 17463 } 17464 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17465 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17466 } 17467 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17468 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17469 } 17470 if (DEBUG_BACKUP) { 17471 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17472 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17473 } 17474 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17475 if (ps != null) { 17476 // Already installed so we apply the grant immediately 17477 if (DEBUG_BACKUP) { 17478 Slog.v(TAG, " + already installed; applying"); 17479 } 17480 PermissionsState perms = ps.getPermissionsState(); 17481 BasePermission bp = mSettings.mPermissions.get(permName); 17482 if (bp != null) { 17483 if (isGranted) { 17484 perms.grantRuntimePermission(bp, userId); 17485 } 17486 if (newFlagSet != 0) { 17487 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17488 } 17489 } 17490 } else { 17491 // Need to wait for post-restore install to apply the grant 17492 if (DEBUG_BACKUP) { 17493 Slog.v(TAG, " - not yet installed; saving for later"); 17494 } 17495 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17496 isGranted, newFlagSet, userId); 17497 } 17498 } else { 17499 PackageManagerService.reportSettingsProblem(Log.WARN, 17500 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17501 XmlUtils.skipCurrentTag(parser); 17502 } 17503 } 17504 17505 scheduleWriteSettingsLocked(); 17506 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17507 } 17508 17509 @Override 17510 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17511 int sourceUserId, int targetUserId, int flags) { 17512 mContext.enforceCallingOrSelfPermission( 17513 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17514 int callingUid = Binder.getCallingUid(); 17515 enforceOwnerRights(ownerPackage, callingUid); 17516 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17517 if (intentFilter.countActions() == 0) { 17518 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17519 return; 17520 } 17521 synchronized (mPackages) { 17522 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17523 ownerPackage, targetUserId, flags); 17524 CrossProfileIntentResolver resolver = 17525 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17526 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17527 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17528 if (existing != null) { 17529 int size = existing.size(); 17530 for (int i = 0; i < size; i++) { 17531 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17532 return; 17533 } 17534 } 17535 } 17536 resolver.addFilter(newFilter); 17537 scheduleWritePackageRestrictionsLocked(sourceUserId); 17538 } 17539 } 17540 17541 @Override 17542 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17543 mContext.enforceCallingOrSelfPermission( 17544 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17545 int callingUid = Binder.getCallingUid(); 17546 enforceOwnerRights(ownerPackage, callingUid); 17547 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17548 synchronized (mPackages) { 17549 CrossProfileIntentResolver resolver = 17550 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17551 ArraySet<CrossProfileIntentFilter> set = 17552 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17553 for (CrossProfileIntentFilter filter : set) { 17554 if (filter.getOwnerPackage().equals(ownerPackage)) { 17555 resolver.removeFilter(filter); 17556 } 17557 } 17558 scheduleWritePackageRestrictionsLocked(sourceUserId); 17559 } 17560 } 17561 17562 // Enforcing that callingUid is owning pkg on userId 17563 private void enforceOwnerRights(String pkg, int callingUid) { 17564 // The system owns everything. 17565 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17566 return; 17567 } 17568 int callingUserId = UserHandle.getUserId(callingUid); 17569 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17570 if (pi == null) { 17571 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17572 + callingUserId); 17573 } 17574 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17575 throw new SecurityException("Calling uid " + callingUid 17576 + " does not own package " + pkg); 17577 } 17578 } 17579 17580 @Override 17581 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17582 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17583 } 17584 17585 private Intent getHomeIntent() { 17586 Intent intent = new Intent(Intent.ACTION_MAIN); 17587 intent.addCategory(Intent.CATEGORY_HOME); 17588 return intent; 17589 } 17590 17591 private IntentFilter getHomeFilter() { 17592 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17593 filter.addCategory(Intent.CATEGORY_HOME); 17594 filter.addCategory(Intent.CATEGORY_DEFAULT); 17595 return filter; 17596 } 17597 17598 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17599 int userId) { 17600 Intent intent = getHomeIntent(); 17601 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17602 PackageManager.GET_META_DATA, userId); 17603 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17604 true, false, false, userId); 17605 17606 allHomeCandidates.clear(); 17607 if (list != null) { 17608 for (ResolveInfo ri : list) { 17609 allHomeCandidates.add(ri); 17610 } 17611 } 17612 return (preferred == null || preferred.activityInfo == null) 17613 ? null 17614 : new ComponentName(preferred.activityInfo.packageName, 17615 preferred.activityInfo.name); 17616 } 17617 17618 @Override 17619 public void setHomeActivity(ComponentName comp, int userId) { 17620 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17621 getHomeActivitiesAsUser(homeActivities, userId); 17622 17623 boolean found = false; 17624 17625 final int size = homeActivities.size(); 17626 final ComponentName[] set = new ComponentName[size]; 17627 for (int i = 0; i < size; i++) { 17628 final ResolveInfo candidate = homeActivities.get(i); 17629 final ActivityInfo info = candidate.activityInfo; 17630 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17631 set[i] = activityName; 17632 if (!found && activityName.equals(comp)) { 17633 found = true; 17634 } 17635 } 17636 if (!found) { 17637 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17638 + userId); 17639 } 17640 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17641 set, comp, userId); 17642 } 17643 17644 private @Nullable String getSetupWizardPackageName() { 17645 final Intent intent = new Intent(Intent.ACTION_MAIN); 17646 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17647 17648 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17649 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17650 | MATCH_DISABLED_COMPONENTS, 17651 UserHandle.myUserId()); 17652 if (matches.size() == 1) { 17653 return matches.get(0).getComponentInfo().packageName; 17654 } else { 17655 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17656 + ": matches=" + matches); 17657 return null; 17658 } 17659 } 17660 17661 @Override 17662 public void setApplicationEnabledSetting(String appPackageName, 17663 int newState, int flags, int userId, String callingPackage) { 17664 if (!sUserManager.exists(userId)) return; 17665 if (callingPackage == null) { 17666 callingPackage = Integer.toString(Binder.getCallingUid()); 17667 } 17668 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17669 } 17670 17671 @Override 17672 public void setComponentEnabledSetting(ComponentName componentName, 17673 int newState, int flags, int userId) { 17674 if (!sUserManager.exists(userId)) return; 17675 setEnabledSetting(componentName.getPackageName(), 17676 componentName.getClassName(), newState, flags, userId, null); 17677 } 17678 17679 private void setEnabledSetting(final String packageName, String className, int newState, 17680 final int flags, int userId, String callingPackage) { 17681 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17682 || newState == COMPONENT_ENABLED_STATE_ENABLED 17683 || newState == COMPONENT_ENABLED_STATE_DISABLED 17684 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17685 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17686 throw new IllegalArgumentException("Invalid new component state: " 17687 + newState); 17688 } 17689 PackageSetting pkgSetting; 17690 final int uid = Binder.getCallingUid(); 17691 final int permission; 17692 if (uid == Process.SYSTEM_UID) { 17693 permission = PackageManager.PERMISSION_GRANTED; 17694 } else { 17695 permission = mContext.checkCallingOrSelfPermission( 17696 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17697 } 17698 enforceCrossUserPermission(uid, userId, 17699 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17700 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17701 boolean sendNow = false; 17702 boolean isApp = (className == null); 17703 String componentName = isApp ? packageName : className; 17704 int packageUid = -1; 17705 ArrayList<String> components; 17706 17707 // writer 17708 synchronized (mPackages) { 17709 pkgSetting = mSettings.mPackages.get(packageName); 17710 if (pkgSetting == null) { 17711 if (className == null) { 17712 throw new IllegalArgumentException("Unknown package: " + packageName); 17713 } 17714 throw new IllegalArgumentException( 17715 "Unknown component: " + packageName + "/" + className); 17716 } 17717 } 17718 17719 // Limit who can change which apps 17720 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17721 // Don't allow apps that don't have permission to modify other apps 17722 if (!allowedByPermission) { 17723 throw new SecurityException( 17724 "Permission Denial: attempt to change component state from pid=" 17725 + Binder.getCallingPid() 17726 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17727 } 17728 // Don't allow changing profile and device owners. 17729 if (mProtectedPackages.canPackageStateBeChanged(userId, packageName)) { 17730 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17731 } 17732 } 17733 17734 synchronized (mPackages) { 17735 if (uid == Process.SHELL_UID) { 17736 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17737 int oldState = pkgSetting.getEnabled(userId); 17738 if (className == null 17739 && 17740 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17741 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17742 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17743 && 17744 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17745 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17746 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17747 // ok 17748 } else { 17749 throw new SecurityException( 17750 "Shell cannot change component state for " + packageName + "/" 17751 + className + " to " + newState); 17752 } 17753 } 17754 if (className == null) { 17755 // We're dealing with an application/package level state change 17756 if (pkgSetting.getEnabled(userId) == newState) { 17757 // Nothing to do 17758 return; 17759 } 17760 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17761 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17762 // Don't care about who enables an app. 17763 callingPackage = null; 17764 } 17765 pkgSetting.setEnabled(newState, userId, callingPackage); 17766 // pkgSetting.pkg.mSetEnabled = newState; 17767 } else { 17768 // We're dealing with a component level state change 17769 // First, verify that this is a valid class name. 17770 PackageParser.Package pkg = pkgSetting.pkg; 17771 if (pkg == null || !pkg.hasComponentClassName(className)) { 17772 if (pkg != null && 17773 pkg.applicationInfo.targetSdkVersion >= 17774 Build.VERSION_CODES.JELLY_BEAN) { 17775 throw new IllegalArgumentException("Component class " + className 17776 + " does not exist in " + packageName); 17777 } else { 17778 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17779 + className + " does not exist in " + packageName); 17780 } 17781 } 17782 switch (newState) { 17783 case COMPONENT_ENABLED_STATE_ENABLED: 17784 if (!pkgSetting.enableComponentLPw(className, userId)) { 17785 return; 17786 } 17787 break; 17788 case COMPONENT_ENABLED_STATE_DISABLED: 17789 if (!pkgSetting.disableComponentLPw(className, userId)) { 17790 return; 17791 } 17792 break; 17793 case COMPONENT_ENABLED_STATE_DEFAULT: 17794 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17795 return; 17796 } 17797 break; 17798 default: 17799 Slog.e(TAG, "Invalid new component state: " + newState); 17800 return; 17801 } 17802 } 17803 scheduleWritePackageRestrictionsLocked(userId); 17804 components = mPendingBroadcasts.get(userId, packageName); 17805 final boolean newPackage = components == null; 17806 if (newPackage) { 17807 components = new ArrayList<String>(); 17808 } 17809 if (!components.contains(componentName)) { 17810 components.add(componentName); 17811 } 17812 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17813 sendNow = true; 17814 // Purge entry from pending broadcast list if another one exists already 17815 // since we are sending one right away. 17816 mPendingBroadcasts.remove(userId, packageName); 17817 } else { 17818 if (newPackage) { 17819 mPendingBroadcasts.put(userId, packageName, components); 17820 } 17821 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17822 // Schedule a message 17823 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17824 } 17825 } 17826 } 17827 17828 long callingId = Binder.clearCallingIdentity(); 17829 try { 17830 if (sendNow) { 17831 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17832 sendPackageChangedBroadcast(packageName, 17833 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17834 } 17835 } finally { 17836 Binder.restoreCallingIdentity(callingId); 17837 } 17838 } 17839 17840 @Override 17841 public void flushPackageRestrictionsAsUser(int userId) { 17842 if (!sUserManager.exists(userId)) { 17843 return; 17844 } 17845 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17846 false /* checkShell */, "flushPackageRestrictions"); 17847 synchronized (mPackages) { 17848 mSettings.writePackageRestrictionsLPr(userId); 17849 mDirtyUsers.remove(userId); 17850 if (mDirtyUsers.isEmpty()) { 17851 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17852 } 17853 } 17854 } 17855 17856 private void sendPackageChangedBroadcast(String packageName, 17857 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17858 if (DEBUG_INSTALL) 17859 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17860 + componentNames); 17861 Bundle extras = new Bundle(4); 17862 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17863 String nameList[] = new String[componentNames.size()]; 17864 componentNames.toArray(nameList); 17865 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17866 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17867 extras.putInt(Intent.EXTRA_UID, packageUid); 17868 // If this is not reporting a change of the overall package, then only send it 17869 // to registered receivers. We don't want to launch a swath of apps for every 17870 // little component state change. 17871 final int flags = !componentNames.contains(packageName) 17872 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17873 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17874 new int[] {UserHandle.getUserId(packageUid)}); 17875 } 17876 17877 @Override 17878 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17879 if (!sUserManager.exists(userId)) return; 17880 final int uid = Binder.getCallingUid(); 17881 final int permission = mContext.checkCallingOrSelfPermission( 17882 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17883 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17884 enforceCrossUserPermission(uid, userId, 17885 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17886 // writer 17887 synchronized (mPackages) { 17888 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17889 allowedByPermission, uid, userId)) { 17890 scheduleWritePackageRestrictionsLocked(userId); 17891 } 17892 } 17893 } 17894 17895 @Override 17896 public String getInstallerPackageName(String packageName) { 17897 // reader 17898 synchronized (mPackages) { 17899 return mSettings.getInstallerPackageNameLPr(packageName); 17900 } 17901 } 17902 17903 public boolean isOrphaned(String packageName) { 17904 // reader 17905 synchronized (mPackages) { 17906 return mSettings.isOrphaned(packageName); 17907 } 17908 } 17909 17910 @Override 17911 public int getApplicationEnabledSetting(String packageName, int userId) { 17912 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17913 int uid = Binder.getCallingUid(); 17914 enforceCrossUserPermission(uid, userId, 17915 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17916 // reader 17917 synchronized (mPackages) { 17918 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17919 } 17920 } 17921 17922 @Override 17923 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17924 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17925 int uid = Binder.getCallingUid(); 17926 enforceCrossUserPermission(uid, userId, 17927 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17928 // reader 17929 synchronized (mPackages) { 17930 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17931 } 17932 } 17933 17934 @Override 17935 public void enterSafeMode() { 17936 enforceSystemOrRoot("Only the system can request entering safe mode"); 17937 17938 if (!mSystemReady) { 17939 mSafeMode = true; 17940 } 17941 } 17942 17943 @Override 17944 public void systemReady() { 17945 mSystemReady = true; 17946 17947 // Read the compatibilty setting when the system is ready. 17948 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17949 mContext.getContentResolver(), 17950 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17951 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17952 if (DEBUG_SETTINGS) { 17953 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17954 } 17955 17956 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17957 17958 synchronized (mPackages) { 17959 // Verify that all of the preferred activity components actually 17960 // exist. It is possible for applications to be updated and at 17961 // that point remove a previously declared activity component that 17962 // had been set as a preferred activity. We try to clean this up 17963 // the next time we encounter that preferred activity, but it is 17964 // possible for the user flow to never be able to return to that 17965 // situation so here we do a sanity check to make sure we haven't 17966 // left any junk around. 17967 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17968 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17969 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17970 removed.clear(); 17971 for (PreferredActivity pa : pir.filterSet()) { 17972 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17973 removed.add(pa); 17974 } 17975 } 17976 if (removed.size() > 0) { 17977 for (int r=0; r<removed.size(); r++) { 17978 PreferredActivity pa = removed.get(r); 17979 Slog.w(TAG, "Removing dangling preferred activity: " 17980 + pa.mPref.mComponent); 17981 pir.removeFilter(pa); 17982 } 17983 mSettings.writePackageRestrictionsLPr( 17984 mSettings.mPreferredActivities.keyAt(i)); 17985 } 17986 } 17987 17988 for (int userId : UserManagerService.getInstance().getUserIds()) { 17989 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17990 grantPermissionsUserIds = ArrayUtils.appendInt( 17991 grantPermissionsUserIds, userId); 17992 } 17993 } 17994 } 17995 sUserManager.systemReady(); 17996 17997 // If we upgraded grant all default permissions before kicking off. 17998 for (int userId : grantPermissionsUserIds) { 17999 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18000 } 18001 18002 // Kick off any messages waiting for system ready 18003 if (mPostSystemReadyMessages != null) { 18004 for (Message msg : mPostSystemReadyMessages) { 18005 msg.sendToTarget(); 18006 } 18007 mPostSystemReadyMessages = null; 18008 } 18009 18010 // Watch for external volumes that come and go over time 18011 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18012 storage.registerListener(mStorageListener); 18013 18014 mInstallerService.systemReady(); 18015 mPackageDexOptimizer.systemReady(); 18016 18017 MountServiceInternal mountServiceInternal = LocalServices.getService( 18018 MountServiceInternal.class); 18019 mountServiceInternal.addExternalStoragePolicy( 18020 new MountServiceInternal.ExternalStorageMountPolicy() { 18021 @Override 18022 public int getMountMode(int uid, String packageName) { 18023 if (Process.isIsolated(uid)) { 18024 return Zygote.MOUNT_EXTERNAL_NONE; 18025 } 18026 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18027 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18028 } 18029 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18030 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18031 } 18032 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18033 return Zygote.MOUNT_EXTERNAL_READ; 18034 } 18035 return Zygote.MOUNT_EXTERNAL_WRITE; 18036 } 18037 18038 @Override 18039 public boolean hasExternalStorage(int uid, String packageName) { 18040 return true; 18041 } 18042 }); 18043 18044 // Now that we're mostly running, clean up stale users and apps 18045 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18046 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18047 } 18048 18049 @Override 18050 public boolean isSafeMode() { 18051 return mSafeMode; 18052 } 18053 18054 @Override 18055 public boolean hasSystemUidErrors() { 18056 return mHasSystemUidErrors; 18057 } 18058 18059 static String arrayToString(int[] array) { 18060 StringBuffer buf = new StringBuffer(128); 18061 buf.append('['); 18062 if (array != null) { 18063 for (int i=0; i<array.length; i++) { 18064 if (i > 0) buf.append(", "); 18065 buf.append(array[i]); 18066 } 18067 } 18068 buf.append(']'); 18069 return buf.toString(); 18070 } 18071 18072 static class DumpState { 18073 public static final int DUMP_LIBS = 1 << 0; 18074 public static final int DUMP_FEATURES = 1 << 1; 18075 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18076 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18077 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18078 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18079 public static final int DUMP_PERMISSIONS = 1 << 6; 18080 public static final int DUMP_PACKAGES = 1 << 7; 18081 public static final int DUMP_SHARED_USERS = 1 << 8; 18082 public static final int DUMP_MESSAGES = 1 << 9; 18083 public static final int DUMP_PROVIDERS = 1 << 10; 18084 public static final int DUMP_VERIFIERS = 1 << 11; 18085 public static final int DUMP_PREFERRED = 1 << 12; 18086 public static final int DUMP_PREFERRED_XML = 1 << 13; 18087 public static final int DUMP_KEYSETS = 1 << 14; 18088 public static final int DUMP_VERSION = 1 << 15; 18089 public static final int DUMP_INSTALLS = 1 << 16; 18090 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18091 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18092 public static final int DUMP_FROZEN = 1 << 19; 18093 public static final int DUMP_DEXOPT = 1 << 20; 18094 18095 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18096 18097 private int mTypes; 18098 18099 private int mOptions; 18100 18101 private boolean mTitlePrinted; 18102 18103 private SharedUserSetting mSharedUser; 18104 18105 public boolean isDumping(int type) { 18106 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18107 return true; 18108 } 18109 18110 return (mTypes & type) != 0; 18111 } 18112 18113 public void setDump(int type) { 18114 mTypes |= type; 18115 } 18116 18117 public boolean isOptionEnabled(int option) { 18118 return (mOptions & option) != 0; 18119 } 18120 18121 public void setOptionEnabled(int option) { 18122 mOptions |= option; 18123 } 18124 18125 public boolean onTitlePrinted() { 18126 final boolean printed = mTitlePrinted; 18127 mTitlePrinted = true; 18128 return printed; 18129 } 18130 18131 public boolean getTitlePrinted() { 18132 return mTitlePrinted; 18133 } 18134 18135 public void setTitlePrinted(boolean enabled) { 18136 mTitlePrinted = enabled; 18137 } 18138 18139 public SharedUserSetting getSharedUser() { 18140 return mSharedUser; 18141 } 18142 18143 public void setSharedUser(SharedUserSetting user) { 18144 mSharedUser = user; 18145 } 18146 } 18147 18148 @Override 18149 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18150 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18151 (new PackageManagerShellCommand(this)).exec( 18152 this, in, out, err, args, resultReceiver); 18153 } 18154 18155 @Override 18156 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18157 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18158 != PackageManager.PERMISSION_GRANTED) { 18159 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18160 + Binder.getCallingPid() 18161 + ", uid=" + Binder.getCallingUid() 18162 + " without permission " 18163 + android.Manifest.permission.DUMP); 18164 return; 18165 } 18166 18167 DumpState dumpState = new DumpState(); 18168 boolean fullPreferred = false; 18169 boolean checkin = false; 18170 18171 String packageName = null; 18172 ArraySet<String> permissionNames = null; 18173 18174 int opti = 0; 18175 while (opti < args.length) { 18176 String opt = args[opti]; 18177 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18178 break; 18179 } 18180 opti++; 18181 18182 if ("-a".equals(opt)) { 18183 // Right now we only know how to print all. 18184 } else if ("-h".equals(opt)) { 18185 pw.println("Package manager dump options:"); 18186 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18187 pw.println(" --checkin: dump for a checkin"); 18188 pw.println(" -f: print details of intent filters"); 18189 pw.println(" -h: print this help"); 18190 pw.println(" cmd may be one of:"); 18191 pw.println(" l[ibraries]: list known shared libraries"); 18192 pw.println(" f[eatures]: list device features"); 18193 pw.println(" k[eysets]: print known keysets"); 18194 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18195 pw.println(" perm[issions]: dump permissions"); 18196 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18197 pw.println(" pref[erred]: print preferred package settings"); 18198 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18199 pw.println(" prov[iders]: dump content providers"); 18200 pw.println(" p[ackages]: dump installed packages"); 18201 pw.println(" s[hared-users]: dump shared user IDs"); 18202 pw.println(" m[essages]: print collected runtime messages"); 18203 pw.println(" v[erifiers]: print package verifier info"); 18204 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18205 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18206 pw.println(" version: print database version info"); 18207 pw.println(" write: write current settings now"); 18208 pw.println(" installs: details about install sessions"); 18209 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18210 pw.println(" dexopt: dump dexopt state"); 18211 pw.println(" <package.name>: info about given package"); 18212 return; 18213 } else if ("--checkin".equals(opt)) { 18214 checkin = true; 18215 } else if ("-f".equals(opt)) { 18216 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18217 } else { 18218 pw.println("Unknown argument: " + opt + "; use -h for help"); 18219 } 18220 } 18221 18222 // Is the caller requesting to dump a particular piece of data? 18223 if (opti < args.length) { 18224 String cmd = args[opti]; 18225 opti++; 18226 // Is this a package name? 18227 if ("android".equals(cmd) || cmd.contains(".")) { 18228 packageName = cmd; 18229 // When dumping a single package, we always dump all of its 18230 // filter information since the amount of data will be reasonable. 18231 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18232 } else if ("check-permission".equals(cmd)) { 18233 if (opti >= args.length) { 18234 pw.println("Error: check-permission missing permission argument"); 18235 return; 18236 } 18237 String perm = args[opti]; 18238 opti++; 18239 if (opti >= args.length) { 18240 pw.println("Error: check-permission missing package argument"); 18241 return; 18242 } 18243 String pkg = args[opti]; 18244 opti++; 18245 int user = UserHandle.getUserId(Binder.getCallingUid()); 18246 if (opti < args.length) { 18247 try { 18248 user = Integer.parseInt(args[opti]); 18249 } catch (NumberFormatException e) { 18250 pw.println("Error: check-permission user argument is not a number: " 18251 + args[opti]); 18252 return; 18253 } 18254 } 18255 pw.println(checkPermission(perm, pkg, user)); 18256 return; 18257 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18258 dumpState.setDump(DumpState.DUMP_LIBS); 18259 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18260 dumpState.setDump(DumpState.DUMP_FEATURES); 18261 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18262 if (opti >= args.length) { 18263 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18264 | DumpState.DUMP_SERVICE_RESOLVERS 18265 | DumpState.DUMP_RECEIVER_RESOLVERS 18266 | DumpState.DUMP_CONTENT_RESOLVERS); 18267 } else { 18268 while (opti < args.length) { 18269 String name = args[opti]; 18270 if ("a".equals(name) || "activity".equals(name)) { 18271 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18272 } else if ("s".equals(name) || "service".equals(name)) { 18273 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18274 } else if ("r".equals(name) || "receiver".equals(name)) { 18275 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18276 } else if ("c".equals(name) || "content".equals(name)) { 18277 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18278 } else { 18279 pw.println("Error: unknown resolver table type: " + name); 18280 return; 18281 } 18282 opti++; 18283 } 18284 } 18285 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18286 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18287 } else if ("permission".equals(cmd)) { 18288 if (opti >= args.length) { 18289 pw.println("Error: permission requires permission name"); 18290 return; 18291 } 18292 permissionNames = new ArraySet<>(); 18293 while (opti < args.length) { 18294 permissionNames.add(args[opti]); 18295 opti++; 18296 } 18297 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18298 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18299 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18300 dumpState.setDump(DumpState.DUMP_PREFERRED); 18301 } else if ("preferred-xml".equals(cmd)) { 18302 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18303 if (opti < args.length && "--full".equals(args[opti])) { 18304 fullPreferred = true; 18305 opti++; 18306 } 18307 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18308 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18309 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18310 dumpState.setDump(DumpState.DUMP_PACKAGES); 18311 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18312 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18313 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18314 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18315 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18316 dumpState.setDump(DumpState.DUMP_MESSAGES); 18317 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18318 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18319 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18320 || "intent-filter-verifiers".equals(cmd)) { 18321 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18322 } else if ("version".equals(cmd)) { 18323 dumpState.setDump(DumpState.DUMP_VERSION); 18324 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18325 dumpState.setDump(DumpState.DUMP_KEYSETS); 18326 } else if ("installs".equals(cmd)) { 18327 dumpState.setDump(DumpState.DUMP_INSTALLS); 18328 } else if ("frozen".equals(cmd)) { 18329 dumpState.setDump(DumpState.DUMP_FROZEN); 18330 } else if ("dexopt".equals(cmd)) { 18331 dumpState.setDump(DumpState.DUMP_DEXOPT); 18332 } else if ("write".equals(cmd)) { 18333 synchronized (mPackages) { 18334 mSettings.writeLPr(); 18335 pw.println("Settings written."); 18336 return; 18337 } 18338 } 18339 } 18340 18341 if (checkin) { 18342 pw.println("vers,1"); 18343 } 18344 18345 // reader 18346 synchronized (mPackages) { 18347 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18348 if (!checkin) { 18349 if (dumpState.onTitlePrinted()) 18350 pw.println(); 18351 pw.println("Database versions:"); 18352 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18353 } 18354 } 18355 18356 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18357 if (!checkin) { 18358 if (dumpState.onTitlePrinted()) 18359 pw.println(); 18360 pw.println("Verifiers:"); 18361 pw.print(" Required: "); 18362 pw.print(mRequiredVerifierPackage); 18363 pw.print(" (uid="); 18364 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18365 UserHandle.USER_SYSTEM)); 18366 pw.println(")"); 18367 } else if (mRequiredVerifierPackage != null) { 18368 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18369 pw.print(","); 18370 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18371 UserHandle.USER_SYSTEM)); 18372 } 18373 } 18374 18375 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18376 packageName == null) { 18377 if (mIntentFilterVerifierComponent != null) { 18378 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18379 if (!checkin) { 18380 if (dumpState.onTitlePrinted()) 18381 pw.println(); 18382 pw.println("Intent Filter Verifier:"); 18383 pw.print(" Using: "); 18384 pw.print(verifierPackageName); 18385 pw.print(" (uid="); 18386 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18387 UserHandle.USER_SYSTEM)); 18388 pw.println(")"); 18389 } else if (verifierPackageName != null) { 18390 pw.print("ifv,"); pw.print(verifierPackageName); 18391 pw.print(","); 18392 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18393 UserHandle.USER_SYSTEM)); 18394 } 18395 } else { 18396 pw.println(); 18397 pw.println("No Intent Filter Verifier available!"); 18398 } 18399 } 18400 18401 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18402 boolean printedHeader = false; 18403 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18404 while (it.hasNext()) { 18405 String name = it.next(); 18406 SharedLibraryEntry ent = mSharedLibraries.get(name); 18407 if (!checkin) { 18408 if (!printedHeader) { 18409 if (dumpState.onTitlePrinted()) 18410 pw.println(); 18411 pw.println("Libraries:"); 18412 printedHeader = true; 18413 } 18414 pw.print(" "); 18415 } else { 18416 pw.print("lib,"); 18417 } 18418 pw.print(name); 18419 if (!checkin) { 18420 pw.print(" -> "); 18421 } 18422 if (ent.path != null) { 18423 if (!checkin) { 18424 pw.print("(jar) "); 18425 pw.print(ent.path); 18426 } else { 18427 pw.print(",jar,"); 18428 pw.print(ent.path); 18429 } 18430 } else { 18431 if (!checkin) { 18432 pw.print("(apk) "); 18433 pw.print(ent.apk); 18434 } else { 18435 pw.print(",apk,"); 18436 pw.print(ent.apk); 18437 } 18438 } 18439 pw.println(); 18440 } 18441 } 18442 18443 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18444 if (dumpState.onTitlePrinted()) 18445 pw.println(); 18446 if (!checkin) { 18447 pw.println("Features:"); 18448 } 18449 18450 for (FeatureInfo feat : mAvailableFeatures.values()) { 18451 if (checkin) { 18452 pw.print("feat,"); 18453 pw.print(feat.name); 18454 pw.print(","); 18455 pw.println(feat.version); 18456 } else { 18457 pw.print(" "); 18458 pw.print(feat.name); 18459 if (feat.version > 0) { 18460 pw.print(" version="); 18461 pw.print(feat.version); 18462 } 18463 pw.println(); 18464 } 18465 } 18466 } 18467 18468 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18469 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18470 : "Activity Resolver Table:", " ", packageName, 18471 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18472 dumpState.setTitlePrinted(true); 18473 } 18474 } 18475 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18476 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18477 : "Receiver Resolver Table:", " ", packageName, 18478 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18479 dumpState.setTitlePrinted(true); 18480 } 18481 } 18482 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18483 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18484 : "Service Resolver Table:", " ", packageName, 18485 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18486 dumpState.setTitlePrinted(true); 18487 } 18488 } 18489 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18490 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18491 : "Provider Resolver Table:", " ", packageName, 18492 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18493 dumpState.setTitlePrinted(true); 18494 } 18495 } 18496 18497 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18498 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18499 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18500 int user = mSettings.mPreferredActivities.keyAt(i); 18501 if (pir.dump(pw, 18502 dumpState.getTitlePrinted() 18503 ? "\nPreferred Activities User " + user + ":" 18504 : "Preferred Activities User " + user + ":", " ", 18505 packageName, true, false)) { 18506 dumpState.setTitlePrinted(true); 18507 } 18508 } 18509 } 18510 18511 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18512 pw.flush(); 18513 FileOutputStream fout = new FileOutputStream(fd); 18514 BufferedOutputStream str = new BufferedOutputStream(fout); 18515 XmlSerializer serializer = new FastXmlSerializer(); 18516 try { 18517 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18518 serializer.startDocument(null, true); 18519 serializer.setFeature( 18520 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18521 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18522 serializer.endDocument(); 18523 serializer.flush(); 18524 } catch (IllegalArgumentException e) { 18525 pw.println("Failed writing: " + e); 18526 } catch (IllegalStateException e) { 18527 pw.println("Failed writing: " + e); 18528 } catch (IOException e) { 18529 pw.println("Failed writing: " + e); 18530 } 18531 } 18532 18533 if (!checkin 18534 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18535 && packageName == null) { 18536 pw.println(); 18537 int count = mSettings.mPackages.size(); 18538 if (count == 0) { 18539 pw.println("No applications!"); 18540 pw.println(); 18541 } else { 18542 final String prefix = " "; 18543 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18544 if (allPackageSettings.size() == 0) { 18545 pw.println("No domain preferred apps!"); 18546 pw.println(); 18547 } else { 18548 pw.println("App verification status:"); 18549 pw.println(); 18550 count = 0; 18551 for (PackageSetting ps : allPackageSettings) { 18552 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18553 if (ivi == null || ivi.getPackageName() == null) continue; 18554 pw.println(prefix + "Package: " + ivi.getPackageName()); 18555 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18556 pw.println(prefix + "Status: " + ivi.getStatusString()); 18557 pw.println(); 18558 count++; 18559 } 18560 if (count == 0) { 18561 pw.println(prefix + "No app verification established."); 18562 pw.println(); 18563 } 18564 for (int userId : sUserManager.getUserIds()) { 18565 pw.println("App linkages for user " + userId + ":"); 18566 pw.println(); 18567 count = 0; 18568 for (PackageSetting ps : allPackageSettings) { 18569 final long status = ps.getDomainVerificationStatusForUser(userId); 18570 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18571 continue; 18572 } 18573 pw.println(prefix + "Package: " + ps.name); 18574 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18575 String statusStr = IntentFilterVerificationInfo. 18576 getStatusStringFromValue(status); 18577 pw.println(prefix + "Status: " + statusStr); 18578 pw.println(); 18579 count++; 18580 } 18581 if (count == 0) { 18582 pw.println(prefix + "No configured app linkages."); 18583 pw.println(); 18584 } 18585 } 18586 } 18587 } 18588 } 18589 18590 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18591 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18592 if (packageName == null && permissionNames == null) { 18593 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18594 if (iperm == 0) { 18595 if (dumpState.onTitlePrinted()) 18596 pw.println(); 18597 pw.println("AppOp Permissions:"); 18598 } 18599 pw.print(" AppOp Permission "); 18600 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18601 pw.println(":"); 18602 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18603 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18604 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18605 } 18606 } 18607 } 18608 } 18609 18610 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18611 boolean printedSomething = false; 18612 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18613 if (packageName != null && !packageName.equals(p.info.packageName)) { 18614 continue; 18615 } 18616 if (!printedSomething) { 18617 if (dumpState.onTitlePrinted()) 18618 pw.println(); 18619 pw.println("Registered ContentProviders:"); 18620 printedSomething = true; 18621 } 18622 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18623 pw.print(" "); pw.println(p.toString()); 18624 } 18625 printedSomething = false; 18626 for (Map.Entry<String, PackageParser.Provider> entry : 18627 mProvidersByAuthority.entrySet()) { 18628 PackageParser.Provider p = entry.getValue(); 18629 if (packageName != null && !packageName.equals(p.info.packageName)) { 18630 continue; 18631 } 18632 if (!printedSomething) { 18633 if (dumpState.onTitlePrinted()) 18634 pw.println(); 18635 pw.println("ContentProvider Authorities:"); 18636 printedSomething = true; 18637 } 18638 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18639 pw.print(" "); pw.println(p.toString()); 18640 if (p.info != null && p.info.applicationInfo != null) { 18641 final String appInfo = p.info.applicationInfo.toString(); 18642 pw.print(" applicationInfo="); pw.println(appInfo); 18643 } 18644 } 18645 } 18646 18647 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18648 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18649 } 18650 18651 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18652 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18653 } 18654 18655 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18656 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18657 } 18658 18659 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18660 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18661 } 18662 18663 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18664 // XXX should handle packageName != null by dumping only install data that 18665 // the given package is involved with. 18666 if (dumpState.onTitlePrinted()) pw.println(); 18667 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18668 } 18669 18670 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18671 // XXX should handle packageName != null by dumping only install data that 18672 // the given package is involved with. 18673 if (dumpState.onTitlePrinted()) pw.println(); 18674 18675 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18676 ipw.println(); 18677 ipw.println("Frozen packages:"); 18678 ipw.increaseIndent(); 18679 if (mFrozenPackages.size() == 0) { 18680 ipw.println("(none)"); 18681 } else { 18682 for (int i = 0; i < mFrozenPackages.size(); i++) { 18683 ipw.println(mFrozenPackages.valueAt(i)); 18684 } 18685 } 18686 ipw.decreaseIndent(); 18687 } 18688 18689 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18690 if (dumpState.onTitlePrinted()) pw.println(); 18691 dumpDexoptStateLPr(pw, packageName); 18692 } 18693 18694 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18695 if (dumpState.onTitlePrinted()) pw.println(); 18696 mSettings.dumpReadMessagesLPr(pw, dumpState); 18697 18698 pw.println(); 18699 pw.println("Package warning messages:"); 18700 BufferedReader in = null; 18701 String line = null; 18702 try { 18703 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18704 while ((line = in.readLine()) != null) { 18705 if (line.contains("ignored: updated version")) continue; 18706 pw.println(line); 18707 } 18708 } catch (IOException ignored) { 18709 } finally { 18710 IoUtils.closeQuietly(in); 18711 } 18712 } 18713 18714 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18715 BufferedReader in = null; 18716 String line = null; 18717 try { 18718 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18719 while ((line = in.readLine()) != null) { 18720 if (line.contains("ignored: updated version")) continue; 18721 pw.print("msg,"); 18722 pw.println(line); 18723 } 18724 } catch (IOException ignored) { 18725 } finally { 18726 IoUtils.closeQuietly(in); 18727 } 18728 } 18729 } 18730 } 18731 18732 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18733 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18734 ipw.println(); 18735 ipw.println("Dexopt state:"); 18736 ipw.increaseIndent(); 18737 Collection<PackageParser.Package> packages = null; 18738 if (packageName != null) { 18739 PackageParser.Package targetPackage = mPackages.get(packageName); 18740 if (targetPackage != null) { 18741 packages = Collections.singletonList(targetPackage); 18742 } else { 18743 ipw.println("Unable to find package: " + packageName); 18744 return; 18745 } 18746 } else { 18747 packages = mPackages.values(); 18748 } 18749 18750 for (PackageParser.Package pkg : packages) { 18751 ipw.println("[" + pkg.packageName + "]"); 18752 ipw.increaseIndent(); 18753 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18754 ipw.decreaseIndent(); 18755 } 18756 } 18757 18758 private String dumpDomainString(String packageName) { 18759 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18760 .getList(); 18761 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18762 18763 ArraySet<String> result = new ArraySet<>(); 18764 if (iviList.size() > 0) { 18765 for (IntentFilterVerificationInfo ivi : iviList) { 18766 for (String host : ivi.getDomains()) { 18767 result.add(host); 18768 } 18769 } 18770 } 18771 if (filters != null && filters.size() > 0) { 18772 for (IntentFilter filter : filters) { 18773 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18774 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18775 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18776 result.addAll(filter.getHostsList()); 18777 } 18778 } 18779 } 18780 18781 StringBuilder sb = new StringBuilder(result.size() * 16); 18782 for (String domain : result) { 18783 if (sb.length() > 0) sb.append(" "); 18784 sb.append(domain); 18785 } 18786 return sb.toString(); 18787 } 18788 18789 // ------- apps on sdcard specific code ------- 18790 static final boolean DEBUG_SD_INSTALL = false; 18791 18792 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18793 18794 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18795 18796 private boolean mMediaMounted = false; 18797 18798 static String getEncryptKey() { 18799 try { 18800 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18801 SD_ENCRYPTION_KEYSTORE_NAME); 18802 if (sdEncKey == null) { 18803 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18804 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18805 if (sdEncKey == null) { 18806 Slog.e(TAG, "Failed to create encryption keys"); 18807 return null; 18808 } 18809 } 18810 return sdEncKey; 18811 } catch (NoSuchAlgorithmException nsae) { 18812 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18813 return null; 18814 } catch (IOException ioe) { 18815 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18816 return null; 18817 } 18818 } 18819 18820 /* 18821 * Update media status on PackageManager. 18822 */ 18823 @Override 18824 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18825 int callingUid = Binder.getCallingUid(); 18826 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18827 throw new SecurityException("Media status can only be updated by the system"); 18828 } 18829 // reader; this apparently protects mMediaMounted, but should probably 18830 // be a different lock in that case. 18831 synchronized (mPackages) { 18832 Log.i(TAG, "Updating external media status from " 18833 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18834 + (mediaStatus ? "mounted" : "unmounted")); 18835 if (DEBUG_SD_INSTALL) 18836 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18837 + ", mMediaMounted=" + mMediaMounted); 18838 if (mediaStatus == mMediaMounted) { 18839 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18840 : 0, -1); 18841 mHandler.sendMessage(msg); 18842 return; 18843 } 18844 mMediaMounted = mediaStatus; 18845 } 18846 // Queue up an async operation since the package installation may take a 18847 // little while. 18848 mHandler.post(new Runnable() { 18849 public void run() { 18850 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18851 } 18852 }); 18853 } 18854 18855 /** 18856 * Called by MountService when the initial ASECs to scan are available. 18857 * Should block until all the ASEC containers are finished being scanned. 18858 */ 18859 public void scanAvailableAsecs() { 18860 updateExternalMediaStatusInner(true, false, false); 18861 } 18862 18863 /* 18864 * Collect information of applications on external media, map them against 18865 * existing containers and update information based on current mount status. 18866 * Please note that we always have to report status if reportStatus has been 18867 * set to true especially when unloading packages. 18868 */ 18869 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18870 boolean externalStorage) { 18871 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18872 int[] uidArr = EmptyArray.INT; 18873 18874 final String[] list = PackageHelper.getSecureContainerList(); 18875 if (ArrayUtils.isEmpty(list)) { 18876 Log.i(TAG, "No secure containers found"); 18877 } else { 18878 // Process list of secure containers and categorize them 18879 // as active or stale based on their package internal state. 18880 18881 // reader 18882 synchronized (mPackages) { 18883 for (String cid : list) { 18884 // Leave stages untouched for now; installer service owns them 18885 if (PackageInstallerService.isStageName(cid)) continue; 18886 18887 if (DEBUG_SD_INSTALL) 18888 Log.i(TAG, "Processing container " + cid); 18889 String pkgName = getAsecPackageName(cid); 18890 if (pkgName == null) { 18891 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18892 continue; 18893 } 18894 if (DEBUG_SD_INSTALL) 18895 Log.i(TAG, "Looking for pkg : " + pkgName); 18896 18897 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18898 if (ps == null) { 18899 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18900 continue; 18901 } 18902 18903 /* 18904 * Skip packages that are not external if we're unmounting 18905 * external storage. 18906 */ 18907 if (externalStorage && !isMounted && !isExternal(ps)) { 18908 continue; 18909 } 18910 18911 final AsecInstallArgs args = new AsecInstallArgs(cid, 18912 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18913 // The package status is changed only if the code path 18914 // matches between settings and the container id. 18915 if (ps.codePathString != null 18916 && ps.codePathString.startsWith(args.getCodePath())) { 18917 if (DEBUG_SD_INSTALL) { 18918 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18919 + " at code path: " + ps.codePathString); 18920 } 18921 18922 // We do have a valid package installed on sdcard 18923 processCids.put(args, ps.codePathString); 18924 final int uid = ps.appId; 18925 if (uid != -1) { 18926 uidArr = ArrayUtils.appendInt(uidArr, uid); 18927 } 18928 } else { 18929 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18930 + ps.codePathString); 18931 } 18932 } 18933 } 18934 18935 Arrays.sort(uidArr); 18936 } 18937 18938 // Process packages with valid entries. 18939 if (isMounted) { 18940 if (DEBUG_SD_INSTALL) 18941 Log.i(TAG, "Loading packages"); 18942 loadMediaPackages(processCids, uidArr, externalStorage); 18943 startCleaningPackages(); 18944 mInstallerService.onSecureContainersAvailable(); 18945 } else { 18946 if (DEBUG_SD_INSTALL) 18947 Log.i(TAG, "Unloading packages"); 18948 unloadMediaPackages(processCids, uidArr, reportStatus); 18949 } 18950 } 18951 18952 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18953 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18954 final int size = infos.size(); 18955 final String[] packageNames = new String[size]; 18956 final int[] packageUids = new int[size]; 18957 for (int i = 0; i < size; i++) { 18958 final ApplicationInfo info = infos.get(i); 18959 packageNames[i] = info.packageName; 18960 packageUids[i] = info.uid; 18961 } 18962 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18963 finishedReceiver); 18964 } 18965 18966 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18967 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18968 sendResourcesChangedBroadcast(mediaStatus, replacing, 18969 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18970 } 18971 18972 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18973 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18974 int size = pkgList.length; 18975 if (size > 0) { 18976 // Send broadcasts here 18977 Bundle extras = new Bundle(); 18978 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18979 if (uidArr != null) { 18980 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18981 } 18982 if (replacing) { 18983 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18984 } 18985 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18986 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18987 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18988 } 18989 } 18990 18991 /* 18992 * Look at potentially valid container ids from processCids If package 18993 * information doesn't match the one on record or package scanning fails, 18994 * the cid is added to list of removeCids. We currently don't delete stale 18995 * containers. 18996 */ 18997 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18998 boolean externalStorage) { 18999 ArrayList<String> pkgList = new ArrayList<String>(); 19000 Set<AsecInstallArgs> keys = processCids.keySet(); 19001 19002 for (AsecInstallArgs args : keys) { 19003 String codePath = processCids.get(args); 19004 if (DEBUG_SD_INSTALL) 19005 Log.i(TAG, "Loading container : " + args.cid); 19006 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19007 try { 19008 // Make sure there are no container errors first. 19009 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19010 Slog.e(TAG, "Failed to mount cid : " + args.cid 19011 + " when installing from sdcard"); 19012 continue; 19013 } 19014 // Check code path here. 19015 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19016 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19017 + " does not match one in settings " + codePath); 19018 continue; 19019 } 19020 // Parse package 19021 int parseFlags = mDefParseFlags; 19022 if (args.isExternalAsec()) { 19023 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19024 } 19025 if (args.isFwdLocked()) { 19026 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19027 } 19028 19029 synchronized (mInstallLock) { 19030 PackageParser.Package pkg = null; 19031 try { 19032 // Sadly we don't know the package name yet to freeze it 19033 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19034 SCAN_IGNORE_FROZEN, 0, null); 19035 } catch (PackageManagerException e) { 19036 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19037 } 19038 // Scan the package 19039 if (pkg != null) { 19040 /* 19041 * TODO why is the lock being held? doPostInstall is 19042 * called in other places without the lock. This needs 19043 * to be straightened out. 19044 */ 19045 // writer 19046 synchronized (mPackages) { 19047 retCode = PackageManager.INSTALL_SUCCEEDED; 19048 pkgList.add(pkg.packageName); 19049 // Post process args 19050 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19051 pkg.applicationInfo.uid); 19052 } 19053 } else { 19054 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19055 } 19056 } 19057 19058 } finally { 19059 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19060 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19061 } 19062 } 19063 } 19064 // writer 19065 synchronized (mPackages) { 19066 // If the platform SDK has changed since the last time we booted, 19067 // we need to re-grant app permission to catch any new ones that 19068 // appear. This is really a hack, and means that apps can in some 19069 // cases get permissions that the user didn't initially explicitly 19070 // allow... it would be nice to have some better way to handle 19071 // this situation. 19072 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19073 : mSettings.getInternalVersion(); 19074 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19075 : StorageManager.UUID_PRIVATE_INTERNAL; 19076 19077 int updateFlags = UPDATE_PERMISSIONS_ALL; 19078 if (ver.sdkVersion != mSdkVersion) { 19079 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19080 + mSdkVersion + "; regranting permissions for external"); 19081 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19082 } 19083 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19084 19085 // Yay, everything is now upgraded 19086 ver.forceCurrent(); 19087 19088 // can downgrade to reader 19089 // Persist settings 19090 mSettings.writeLPr(); 19091 } 19092 // Send a broadcast to let everyone know we are done processing 19093 if (pkgList.size() > 0) { 19094 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19095 } 19096 } 19097 19098 /* 19099 * Utility method to unload a list of specified containers 19100 */ 19101 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19102 // Just unmount all valid containers. 19103 for (AsecInstallArgs arg : cidArgs) { 19104 synchronized (mInstallLock) { 19105 arg.doPostDeleteLI(false); 19106 } 19107 } 19108 } 19109 19110 /* 19111 * Unload packages mounted on external media. This involves deleting package 19112 * data from internal structures, sending broadcasts about disabled packages, 19113 * gc'ing to free up references, unmounting all secure containers 19114 * corresponding to packages on external media, and posting a 19115 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19116 * that we always have to post this message if status has been requested no 19117 * matter what. 19118 */ 19119 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19120 final boolean reportStatus) { 19121 if (DEBUG_SD_INSTALL) 19122 Log.i(TAG, "unloading media packages"); 19123 ArrayList<String> pkgList = new ArrayList<String>(); 19124 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19125 final Set<AsecInstallArgs> keys = processCids.keySet(); 19126 for (AsecInstallArgs args : keys) { 19127 String pkgName = args.getPackageName(); 19128 if (DEBUG_SD_INSTALL) 19129 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19130 // Delete package internally 19131 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19132 synchronized (mInstallLock) { 19133 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19134 final boolean res; 19135 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19136 "unloadMediaPackages")) { 19137 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19138 null); 19139 } 19140 if (res) { 19141 pkgList.add(pkgName); 19142 } else { 19143 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19144 failedList.add(args); 19145 } 19146 } 19147 } 19148 19149 // reader 19150 synchronized (mPackages) { 19151 // We didn't update the settings after removing each package; 19152 // write them now for all packages. 19153 mSettings.writeLPr(); 19154 } 19155 19156 // We have to absolutely send UPDATED_MEDIA_STATUS only 19157 // after confirming that all the receivers processed the ordered 19158 // broadcast when packages get disabled, force a gc to clean things up. 19159 // and unload all the containers. 19160 if (pkgList.size() > 0) { 19161 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19162 new IIntentReceiver.Stub() { 19163 public void performReceive(Intent intent, int resultCode, String data, 19164 Bundle extras, boolean ordered, boolean sticky, 19165 int sendingUser) throws RemoteException { 19166 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19167 reportStatus ? 1 : 0, 1, keys); 19168 mHandler.sendMessage(msg); 19169 } 19170 }); 19171 } else { 19172 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19173 keys); 19174 mHandler.sendMessage(msg); 19175 } 19176 } 19177 19178 private void loadPrivatePackages(final VolumeInfo vol) { 19179 mHandler.post(new Runnable() { 19180 @Override 19181 public void run() { 19182 loadPrivatePackagesInner(vol); 19183 } 19184 }); 19185 } 19186 19187 private void loadPrivatePackagesInner(VolumeInfo vol) { 19188 final String volumeUuid = vol.fsUuid; 19189 if (TextUtils.isEmpty(volumeUuid)) { 19190 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19191 return; 19192 } 19193 19194 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19195 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19196 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19197 19198 final VersionInfo ver; 19199 final List<PackageSetting> packages; 19200 synchronized (mPackages) { 19201 ver = mSettings.findOrCreateVersion(volumeUuid); 19202 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19203 } 19204 19205 for (PackageSetting ps : packages) { 19206 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19207 synchronized (mInstallLock) { 19208 final PackageParser.Package pkg; 19209 try { 19210 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19211 loaded.add(pkg.applicationInfo); 19212 19213 } catch (PackageManagerException e) { 19214 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19215 } 19216 19217 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19218 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19219 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19220 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19221 } 19222 } 19223 } 19224 19225 // Reconcile app data for all started/unlocked users 19226 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19227 final UserManager um = mContext.getSystemService(UserManager.class); 19228 UserManagerInternal umInternal = getUserManagerInternal(); 19229 for (UserInfo user : um.getUsers()) { 19230 final int flags; 19231 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19232 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19233 } else if (umInternal.isUserRunning(user.id)) { 19234 flags = StorageManager.FLAG_STORAGE_DE; 19235 } else { 19236 continue; 19237 } 19238 19239 try { 19240 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19241 synchronized (mInstallLock) { 19242 reconcileAppsDataLI(volumeUuid, user.id, flags); 19243 } 19244 } catch (IllegalStateException e) { 19245 // Device was probably ejected, and we'll process that event momentarily 19246 Slog.w(TAG, "Failed to prepare storage: " + e); 19247 } 19248 } 19249 19250 synchronized (mPackages) { 19251 int updateFlags = UPDATE_PERMISSIONS_ALL; 19252 if (ver.sdkVersion != mSdkVersion) { 19253 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19254 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19255 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19256 } 19257 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19258 19259 // Yay, everything is now upgraded 19260 ver.forceCurrent(); 19261 19262 mSettings.writeLPr(); 19263 } 19264 19265 for (PackageFreezer freezer : freezers) { 19266 freezer.close(); 19267 } 19268 19269 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19270 sendResourcesChangedBroadcast(true, false, loaded, null); 19271 } 19272 19273 private void unloadPrivatePackages(final VolumeInfo vol) { 19274 mHandler.post(new Runnable() { 19275 @Override 19276 public void run() { 19277 unloadPrivatePackagesInner(vol); 19278 } 19279 }); 19280 } 19281 19282 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19283 final String volumeUuid = vol.fsUuid; 19284 if (TextUtils.isEmpty(volumeUuid)) { 19285 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19286 return; 19287 } 19288 19289 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19290 synchronized (mInstallLock) { 19291 synchronized (mPackages) { 19292 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19293 for (PackageSetting ps : packages) { 19294 if (ps.pkg == null) continue; 19295 19296 final ApplicationInfo info = ps.pkg.applicationInfo; 19297 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19298 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19299 19300 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19301 "unloadPrivatePackagesInner")) { 19302 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19303 false, null)) { 19304 unloaded.add(info); 19305 } else { 19306 Slog.w(TAG, "Failed to unload " + ps.codePath); 19307 } 19308 } 19309 19310 // Try very hard to release any references to this package 19311 // so we don't risk the system server being killed due to 19312 // open FDs 19313 AttributeCache.instance().removePackage(ps.name); 19314 } 19315 19316 mSettings.writeLPr(); 19317 } 19318 } 19319 19320 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19321 sendResourcesChangedBroadcast(false, false, unloaded, null); 19322 19323 // Try very hard to release any references to this path so we don't risk 19324 // the system server being killed due to open FDs 19325 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19326 19327 for (int i = 0; i < 3; i++) { 19328 System.gc(); 19329 System.runFinalization(); 19330 } 19331 } 19332 19333 /** 19334 * Prepare storage areas for given user on all mounted devices. 19335 */ 19336 void prepareUserData(int userId, int userSerial, int flags) { 19337 synchronized (mInstallLock) { 19338 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19339 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19340 final String volumeUuid = vol.getFsUuid(); 19341 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19342 } 19343 } 19344 } 19345 19346 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19347 boolean allowRecover) { 19348 // Prepare storage and verify that serial numbers are consistent; if 19349 // there's a mismatch we need to destroy to avoid leaking data 19350 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19351 try { 19352 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19353 19354 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19355 UserManagerService.enforceSerialNumber( 19356 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19357 } 19358 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19359 UserManagerService.enforceSerialNumber( 19360 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19361 } 19362 19363 synchronized (mInstallLock) { 19364 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19365 } 19366 } catch (Exception e) { 19367 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19368 + " because we failed to prepare: " + e); 19369 destroyUserDataLI(volumeUuid, userId, 19370 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19371 19372 if (allowRecover) { 19373 // Try one last time; if we fail again we're really in trouble 19374 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19375 } 19376 } 19377 } 19378 19379 /** 19380 * Destroy storage areas for given user on all mounted devices. 19381 */ 19382 void destroyUserData(int userId, int flags) { 19383 synchronized (mInstallLock) { 19384 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19385 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19386 final String volumeUuid = vol.getFsUuid(); 19387 destroyUserDataLI(volumeUuid, userId, flags); 19388 } 19389 } 19390 } 19391 19392 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19393 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19394 try { 19395 // Clean up app data, profile data, and media data 19396 mInstaller.destroyUserData(volumeUuid, userId, flags); 19397 19398 // Clean up system data 19399 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19400 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19401 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19402 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19403 } 19404 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19405 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19406 } 19407 } 19408 19409 // Data with special labels is now gone, so finish the job 19410 storage.destroyUserStorage(volumeUuid, userId, flags); 19411 19412 } catch (Exception e) { 19413 logCriticalInfo(Log.WARN, 19414 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19415 } 19416 } 19417 19418 /** 19419 * Examine all users present on given mounted volume, and destroy data 19420 * belonging to users that are no longer valid, or whose user ID has been 19421 * recycled. 19422 */ 19423 private void reconcileUsers(String volumeUuid) { 19424 final List<File> files = new ArrayList<>(); 19425 Collections.addAll(files, FileUtils 19426 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19427 Collections.addAll(files, FileUtils 19428 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19429 for (File file : files) { 19430 if (!file.isDirectory()) continue; 19431 19432 final int userId; 19433 final UserInfo info; 19434 try { 19435 userId = Integer.parseInt(file.getName()); 19436 info = sUserManager.getUserInfo(userId); 19437 } catch (NumberFormatException e) { 19438 Slog.w(TAG, "Invalid user directory " + file); 19439 continue; 19440 } 19441 19442 boolean destroyUser = false; 19443 if (info == null) { 19444 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19445 + " because no matching user was found"); 19446 destroyUser = true; 19447 } else if (!mOnlyCore) { 19448 try { 19449 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19450 } catch (IOException e) { 19451 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19452 + " because we failed to enforce serial number: " + e); 19453 destroyUser = true; 19454 } 19455 } 19456 19457 if (destroyUser) { 19458 synchronized (mInstallLock) { 19459 destroyUserDataLI(volumeUuid, userId, 19460 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19461 } 19462 } 19463 } 19464 } 19465 19466 private void assertPackageKnown(String volumeUuid, String packageName) 19467 throws PackageManagerException { 19468 synchronized (mPackages) { 19469 final PackageSetting ps = mSettings.mPackages.get(packageName); 19470 if (ps == null) { 19471 throw new PackageManagerException("Package " + packageName + " is unknown"); 19472 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19473 throw new PackageManagerException( 19474 "Package " + packageName + " found on unknown volume " + volumeUuid 19475 + "; expected volume " + ps.volumeUuid); 19476 } 19477 } 19478 } 19479 19480 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19481 throws PackageManagerException { 19482 synchronized (mPackages) { 19483 final PackageSetting ps = mSettings.mPackages.get(packageName); 19484 if (ps == null) { 19485 throw new PackageManagerException("Package " + packageName + " is unknown"); 19486 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19487 throw new PackageManagerException( 19488 "Package " + packageName + " found on unknown volume " + volumeUuid 19489 + "; expected volume " + ps.volumeUuid); 19490 } else if (!ps.getInstalled(userId)) { 19491 throw new PackageManagerException( 19492 "Package " + packageName + " not installed for user " + userId); 19493 } 19494 } 19495 } 19496 19497 /** 19498 * Examine all apps present on given mounted volume, and destroy apps that 19499 * aren't expected, either due to uninstallation or reinstallation on 19500 * another volume. 19501 */ 19502 private void reconcileApps(String volumeUuid) { 19503 final File[] files = FileUtils 19504 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19505 for (File file : files) { 19506 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19507 && !PackageInstallerService.isStageName(file.getName()); 19508 if (!isPackage) { 19509 // Ignore entries which are not packages 19510 continue; 19511 } 19512 19513 try { 19514 final PackageLite pkg = PackageParser.parsePackageLite(file, 19515 PackageParser.PARSE_MUST_BE_APK); 19516 assertPackageKnown(volumeUuid, pkg.packageName); 19517 19518 } catch (PackageParserException | PackageManagerException e) { 19519 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19520 synchronized (mInstallLock) { 19521 removeCodePathLI(file); 19522 } 19523 } 19524 } 19525 } 19526 19527 /** 19528 * Reconcile all app data for the given user. 19529 * <p> 19530 * Verifies that directories exist and that ownership and labeling is 19531 * correct for all installed apps on all mounted volumes. 19532 */ 19533 void reconcileAppsData(int userId, int flags) { 19534 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19535 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19536 final String volumeUuid = vol.getFsUuid(); 19537 synchronized (mInstallLock) { 19538 reconcileAppsDataLI(volumeUuid, userId, flags); 19539 } 19540 } 19541 } 19542 19543 /** 19544 * Reconcile all app data on given mounted volume. 19545 * <p> 19546 * Destroys app data that isn't expected, either due to uninstallation or 19547 * reinstallation on another volume. 19548 * <p> 19549 * Verifies that directories exist and that ownership and labeling is 19550 * correct for all installed apps. 19551 */ 19552 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19553 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19554 + Integer.toHexString(flags)); 19555 19556 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19557 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19558 19559 boolean restoreconNeeded = false; 19560 19561 // First look for stale data that doesn't belong, and check if things 19562 // have changed since we did our last restorecon 19563 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19564 if (StorageManager.isFileEncryptedNativeOrEmulated() 19565 && !StorageManager.isUserKeyUnlocked(userId)) { 19566 throw new RuntimeException( 19567 "Yikes, someone asked us to reconcile CE storage while " + userId 19568 + " was still locked; this would have caused massive data loss!"); 19569 } 19570 19571 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19572 19573 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19574 for (File file : files) { 19575 final String packageName = file.getName(); 19576 try { 19577 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19578 } catch (PackageManagerException e) { 19579 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19580 try { 19581 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19582 StorageManager.FLAG_STORAGE_CE, 0); 19583 } catch (InstallerException e2) { 19584 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19585 } 19586 } 19587 } 19588 } 19589 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19590 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19591 19592 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19593 for (File file : files) { 19594 final String packageName = file.getName(); 19595 try { 19596 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19597 } catch (PackageManagerException e) { 19598 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19599 try { 19600 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19601 StorageManager.FLAG_STORAGE_DE, 0); 19602 } catch (InstallerException e2) { 19603 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19604 } 19605 } 19606 } 19607 } 19608 19609 // Ensure that data directories are ready to roll for all packages 19610 // installed for this volume and user 19611 final List<PackageSetting> packages; 19612 synchronized (mPackages) { 19613 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19614 } 19615 int preparedCount = 0; 19616 for (PackageSetting ps : packages) { 19617 final String packageName = ps.name; 19618 if (ps.pkg == null) { 19619 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19620 // TODO: might be due to legacy ASEC apps; we should circle back 19621 // and reconcile again once they're scanned 19622 continue; 19623 } 19624 19625 if (ps.getInstalled(userId)) { 19626 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19627 19628 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19629 // We may have just shuffled around app data directories, so 19630 // prepare them one more time 19631 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19632 } 19633 19634 preparedCount++; 19635 } 19636 } 19637 19638 if (restoreconNeeded) { 19639 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19640 SELinuxMMAC.setRestoreconDone(ceDir); 19641 } 19642 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19643 SELinuxMMAC.setRestoreconDone(deDir); 19644 } 19645 } 19646 19647 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19648 + " packages; restoreconNeeded was " + restoreconNeeded); 19649 } 19650 19651 /** 19652 * Prepare app data for the given app just after it was installed or 19653 * upgraded. This method carefully only touches users that it's installed 19654 * for, and it forces a restorecon to handle any seinfo changes. 19655 * <p> 19656 * Verifies that directories exist and that ownership and labeling is 19657 * correct for all installed apps. If there is an ownership mismatch, it 19658 * will try recovering system apps by wiping data; third-party app data is 19659 * left intact. 19660 * <p> 19661 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19662 */ 19663 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19664 final PackageSetting ps; 19665 synchronized (mPackages) { 19666 ps = mSettings.mPackages.get(pkg.packageName); 19667 mSettings.writeKernelMappingLPr(ps); 19668 } 19669 19670 final UserManager um = mContext.getSystemService(UserManager.class); 19671 UserManagerInternal umInternal = getUserManagerInternal(); 19672 for (UserInfo user : um.getUsers()) { 19673 final int flags; 19674 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19675 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19676 } else if (umInternal.isUserRunning(user.id)) { 19677 flags = StorageManager.FLAG_STORAGE_DE; 19678 } else { 19679 continue; 19680 } 19681 19682 if (ps.getInstalled(user.id)) { 19683 // Whenever an app changes, force a restorecon of its data 19684 // TODO: when user data is locked, mark that we're still dirty 19685 prepareAppDataLIF(pkg, user.id, flags, true); 19686 } 19687 } 19688 } 19689 19690 /** 19691 * Prepare app data for the given app. 19692 * <p> 19693 * Verifies that directories exist and that ownership and labeling is 19694 * correct for all installed apps. If there is an ownership mismatch, this 19695 * will try recovering system apps by wiping data; third-party app data is 19696 * left intact. 19697 */ 19698 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19699 boolean restoreconNeeded) { 19700 if (pkg == null) { 19701 Slog.wtf(TAG, "Package was null!", new Throwable()); 19702 return; 19703 } 19704 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19705 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19706 for (int i = 0; i < childCount; i++) { 19707 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19708 } 19709 } 19710 19711 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19712 boolean restoreconNeeded) { 19713 if (DEBUG_APP_DATA) { 19714 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19715 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19716 } 19717 19718 final String volumeUuid = pkg.volumeUuid; 19719 final String packageName = pkg.packageName; 19720 final ApplicationInfo app = pkg.applicationInfo; 19721 final int appId = UserHandle.getAppId(app.uid); 19722 19723 Preconditions.checkNotNull(app.seinfo); 19724 19725 try { 19726 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19727 appId, app.seinfo, app.targetSdkVersion); 19728 } catch (InstallerException e) { 19729 if (app.isSystemApp()) { 19730 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19731 + ", but trying to recover: " + e); 19732 destroyAppDataLeafLIF(pkg, userId, flags); 19733 try { 19734 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19735 appId, app.seinfo, app.targetSdkVersion); 19736 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19737 } catch (InstallerException e2) { 19738 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19739 } 19740 } else { 19741 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19742 } 19743 } 19744 19745 if (restoreconNeeded) { 19746 try { 19747 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19748 app.seinfo); 19749 } catch (InstallerException e) { 19750 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19751 } 19752 } 19753 19754 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19755 try { 19756 // CE storage is unlocked right now, so read out the inode and 19757 // remember for use later when it's locked 19758 // TODO: mark this structure as dirty so we persist it! 19759 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19760 StorageManager.FLAG_STORAGE_CE); 19761 synchronized (mPackages) { 19762 final PackageSetting ps = mSettings.mPackages.get(packageName); 19763 if (ps != null) { 19764 ps.setCeDataInode(ceDataInode, userId); 19765 } 19766 } 19767 } catch (InstallerException e) { 19768 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19769 } 19770 } 19771 19772 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19773 } 19774 19775 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19776 if (pkg == null) { 19777 Slog.wtf(TAG, "Package was null!", new Throwable()); 19778 return; 19779 } 19780 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19781 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19782 for (int i = 0; i < childCount; i++) { 19783 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19784 } 19785 } 19786 19787 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19788 final String volumeUuid = pkg.volumeUuid; 19789 final String packageName = pkg.packageName; 19790 final ApplicationInfo app = pkg.applicationInfo; 19791 19792 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19793 // Create a native library symlink only if we have native libraries 19794 // and if the native libraries are 32 bit libraries. We do not provide 19795 // this symlink for 64 bit libraries. 19796 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19797 final String nativeLibPath = app.nativeLibraryDir; 19798 try { 19799 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19800 nativeLibPath, userId); 19801 } catch (InstallerException e) { 19802 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19803 } 19804 } 19805 } 19806 } 19807 19808 /** 19809 * For system apps on non-FBE devices, this method migrates any existing 19810 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19811 * requested by the app. 19812 */ 19813 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19814 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19815 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19816 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19817 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19818 try { 19819 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19820 storageTarget); 19821 } catch (InstallerException e) { 19822 logCriticalInfo(Log.WARN, 19823 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19824 } 19825 return true; 19826 } else { 19827 return false; 19828 } 19829 } 19830 19831 public PackageFreezer freezePackage(String packageName, String killReason) { 19832 return new PackageFreezer(packageName, killReason); 19833 } 19834 19835 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19836 String killReason) { 19837 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19838 return new PackageFreezer(); 19839 } else { 19840 return freezePackage(packageName, killReason); 19841 } 19842 } 19843 19844 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19845 String killReason) { 19846 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19847 return new PackageFreezer(); 19848 } else { 19849 return freezePackage(packageName, killReason); 19850 } 19851 } 19852 19853 /** 19854 * Class that freezes and kills the given package upon creation, and 19855 * unfreezes it upon closing. This is typically used when doing surgery on 19856 * app code/data to prevent the app from running while you're working. 19857 */ 19858 private class PackageFreezer implements AutoCloseable { 19859 private final String mPackageName; 19860 private final PackageFreezer[] mChildren; 19861 19862 private final boolean mWeFroze; 19863 19864 private final AtomicBoolean mClosed = new AtomicBoolean(); 19865 private final CloseGuard mCloseGuard = CloseGuard.get(); 19866 19867 /** 19868 * Create and return a stub freezer that doesn't actually do anything, 19869 * typically used when someone requested 19870 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19871 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19872 */ 19873 public PackageFreezer() { 19874 mPackageName = null; 19875 mChildren = null; 19876 mWeFroze = false; 19877 mCloseGuard.open("close"); 19878 } 19879 19880 public PackageFreezer(String packageName, String killReason) { 19881 synchronized (mPackages) { 19882 mPackageName = packageName; 19883 mWeFroze = mFrozenPackages.add(mPackageName); 19884 19885 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19886 if (ps != null) { 19887 killApplication(ps.name, ps.appId, killReason); 19888 } 19889 19890 final PackageParser.Package p = mPackages.get(packageName); 19891 if (p != null && p.childPackages != null) { 19892 final int N = p.childPackages.size(); 19893 mChildren = new PackageFreezer[N]; 19894 for (int i = 0; i < N; i++) { 19895 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19896 killReason); 19897 } 19898 } else { 19899 mChildren = null; 19900 } 19901 } 19902 mCloseGuard.open("close"); 19903 } 19904 19905 @Override 19906 protected void finalize() throws Throwable { 19907 try { 19908 mCloseGuard.warnIfOpen(); 19909 close(); 19910 } finally { 19911 super.finalize(); 19912 } 19913 } 19914 19915 @Override 19916 public void close() { 19917 mCloseGuard.close(); 19918 if (mClosed.compareAndSet(false, true)) { 19919 synchronized (mPackages) { 19920 if (mWeFroze) { 19921 mFrozenPackages.remove(mPackageName); 19922 } 19923 19924 if (mChildren != null) { 19925 for (PackageFreezer freezer : mChildren) { 19926 freezer.close(); 19927 } 19928 } 19929 } 19930 } 19931 } 19932 } 19933 19934 /** 19935 * Verify that given package is currently frozen. 19936 */ 19937 private void checkPackageFrozen(String packageName) { 19938 synchronized (mPackages) { 19939 if (!mFrozenPackages.contains(packageName)) { 19940 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19941 } 19942 } 19943 } 19944 19945 @Override 19946 public int movePackage(final String packageName, final String volumeUuid) { 19947 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19948 19949 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19950 final int moveId = mNextMoveId.getAndIncrement(); 19951 mHandler.post(new Runnable() { 19952 @Override 19953 public void run() { 19954 try { 19955 movePackageInternal(packageName, volumeUuid, moveId, user); 19956 } catch (PackageManagerException e) { 19957 Slog.w(TAG, "Failed to move " + packageName, e); 19958 mMoveCallbacks.notifyStatusChanged(moveId, 19959 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19960 } 19961 } 19962 }); 19963 return moveId; 19964 } 19965 19966 private void movePackageInternal(final String packageName, final String volumeUuid, 19967 final int moveId, UserHandle user) throws PackageManagerException { 19968 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19969 final PackageManager pm = mContext.getPackageManager(); 19970 19971 final boolean currentAsec; 19972 final String currentVolumeUuid; 19973 final File codeFile; 19974 final String installerPackageName; 19975 final String packageAbiOverride; 19976 final int appId; 19977 final String seinfo; 19978 final String label; 19979 final int targetSdkVersion; 19980 final PackageFreezer freezer; 19981 final int[] installedUserIds; 19982 19983 // reader 19984 synchronized (mPackages) { 19985 final PackageParser.Package pkg = mPackages.get(packageName); 19986 final PackageSetting ps = mSettings.mPackages.get(packageName); 19987 if (pkg == null || ps == null) { 19988 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19989 } 19990 19991 if (pkg.applicationInfo.isSystemApp()) { 19992 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19993 "Cannot move system application"); 19994 } 19995 19996 if (pkg.applicationInfo.isExternalAsec()) { 19997 currentAsec = true; 19998 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19999 } else if (pkg.applicationInfo.isForwardLocked()) { 20000 currentAsec = true; 20001 currentVolumeUuid = "forward_locked"; 20002 } else { 20003 currentAsec = false; 20004 currentVolumeUuid = ps.volumeUuid; 20005 20006 final File probe = new File(pkg.codePath); 20007 final File probeOat = new File(probe, "oat"); 20008 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20009 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20010 "Move only supported for modern cluster style installs"); 20011 } 20012 } 20013 20014 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20015 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20016 "Package already moved to " + volumeUuid); 20017 } 20018 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20019 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20020 "Device admin cannot be moved"); 20021 } 20022 20023 if (mFrozenPackages.contains(packageName)) { 20024 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20025 "Failed to move already frozen package"); 20026 } 20027 20028 codeFile = new File(pkg.codePath); 20029 installerPackageName = ps.installerPackageName; 20030 packageAbiOverride = ps.cpuAbiOverrideString; 20031 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20032 seinfo = pkg.applicationInfo.seinfo; 20033 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20034 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20035 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20036 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20037 } 20038 20039 final Bundle extras = new Bundle(); 20040 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20041 extras.putString(Intent.EXTRA_TITLE, label); 20042 mMoveCallbacks.notifyCreated(moveId, extras); 20043 20044 int installFlags; 20045 final boolean moveCompleteApp; 20046 final File measurePath; 20047 20048 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20049 installFlags = INSTALL_INTERNAL; 20050 moveCompleteApp = !currentAsec; 20051 measurePath = Environment.getDataAppDirectory(volumeUuid); 20052 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20053 installFlags = INSTALL_EXTERNAL; 20054 moveCompleteApp = false; 20055 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20056 } else { 20057 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20058 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20059 || !volume.isMountedWritable()) { 20060 freezer.close(); 20061 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20062 "Move location not mounted private volume"); 20063 } 20064 20065 Preconditions.checkState(!currentAsec); 20066 20067 installFlags = INSTALL_INTERNAL; 20068 moveCompleteApp = true; 20069 measurePath = Environment.getDataAppDirectory(volumeUuid); 20070 } 20071 20072 final PackageStats stats = new PackageStats(null, -1); 20073 synchronized (mInstaller) { 20074 for (int userId : installedUserIds) { 20075 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20076 freezer.close(); 20077 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20078 "Failed to measure package size"); 20079 } 20080 } 20081 } 20082 20083 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20084 + stats.dataSize); 20085 20086 final long startFreeBytes = measurePath.getFreeSpace(); 20087 final long sizeBytes; 20088 if (moveCompleteApp) { 20089 sizeBytes = stats.codeSize + stats.dataSize; 20090 } else { 20091 sizeBytes = stats.codeSize; 20092 } 20093 20094 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20095 freezer.close(); 20096 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20097 "Not enough free space to move"); 20098 } 20099 20100 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20101 20102 final CountDownLatch installedLatch = new CountDownLatch(1); 20103 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20104 @Override 20105 public void onUserActionRequired(Intent intent) throws RemoteException { 20106 throw new IllegalStateException(); 20107 } 20108 20109 @Override 20110 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20111 Bundle extras) throws RemoteException { 20112 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20113 + PackageManager.installStatusToString(returnCode, msg)); 20114 20115 installedLatch.countDown(); 20116 freezer.close(); 20117 20118 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20119 switch (status) { 20120 case PackageInstaller.STATUS_SUCCESS: 20121 mMoveCallbacks.notifyStatusChanged(moveId, 20122 PackageManager.MOVE_SUCCEEDED); 20123 break; 20124 case PackageInstaller.STATUS_FAILURE_STORAGE: 20125 mMoveCallbacks.notifyStatusChanged(moveId, 20126 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20127 break; 20128 default: 20129 mMoveCallbacks.notifyStatusChanged(moveId, 20130 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20131 break; 20132 } 20133 } 20134 }; 20135 20136 final MoveInfo move; 20137 if (moveCompleteApp) { 20138 // Kick off a thread to report progress estimates 20139 new Thread() { 20140 @Override 20141 public void run() { 20142 while (true) { 20143 try { 20144 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20145 break; 20146 } 20147 } catch (InterruptedException ignored) { 20148 } 20149 20150 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20151 final int progress = 10 + (int) MathUtils.constrain( 20152 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20153 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20154 } 20155 } 20156 }.start(); 20157 20158 final String dataAppName = codeFile.getName(); 20159 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20160 dataAppName, appId, seinfo, targetSdkVersion); 20161 } else { 20162 move = null; 20163 } 20164 20165 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20166 20167 final Message msg = mHandler.obtainMessage(INIT_COPY); 20168 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20169 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20170 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20171 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20172 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20173 msg.obj = params; 20174 20175 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20176 System.identityHashCode(msg.obj)); 20177 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20178 System.identityHashCode(msg.obj)); 20179 20180 mHandler.sendMessage(msg); 20181 } 20182 20183 @Override 20184 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20185 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20186 20187 final int realMoveId = mNextMoveId.getAndIncrement(); 20188 final Bundle extras = new Bundle(); 20189 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20190 mMoveCallbacks.notifyCreated(realMoveId, extras); 20191 20192 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20193 @Override 20194 public void onCreated(int moveId, Bundle extras) { 20195 // Ignored 20196 } 20197 20198 @Override 20199 public void onStatusChanged(int moveId, int status, long estMillis) { 20200 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20201 } 20202 }; 20203 20204 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20205 storage.setPrimaryStorageUuid(volumeUuid, callback); 20206 return realMoveId; 20207 } 20208 20209 @Override 20210 public int getMoveStatus(int moveId) { 20211 mContext.enforceCallingOrSelfPermission( 20212 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20213 return mMoveCallbacks.mLastStatus.get(moveId); 20214 } 20215 20216 @Override 20217 public void registerMoveCallback(IPackageMoveObserver callback) { 20218 mContext.enforceCallingOrSelfPermission( 20219 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20220 mMoveCallbacks.register(callback); 20221 } 20222 20223 @Override 20224 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20225 mContext.enforceCallingOrSelfPermission( 20226 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20227 mMoveCallbacks.unregister(callback); 20228 } 20229 20230 @Override 20231 public boolean setInstallLocation(int loc) { 20232 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20233 null); 20234 if (getInstallLocation() == loc) { 20235 return true; 20236 } 20237 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20238 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20239 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20240 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20241 return true; 20242 } 20243 return false; 20244 } 20245 20246 @Override 20247 public int getInstallLocation() { 20248 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20249 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20250 PackageHelper.APP_INSTALL_AUTO); 20251 } 20252 20253 /** Called by UserManagerService */ 20254 void cleanUpUser(UserManagerService userManager, int userHandle) { 20255 synchronized (mPackages) { 20256 mDirtyUsers.remove(userHandle); 20257 mUserNeedsBadging.delete(userHandle); 20258 mSettings.removeUserLPw(userHandle); 20259 mPendingBroadcasts.remove(userHandle); 20260 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20261 removeUnusedPackagesLPw(userManager, userHandle); 20262 } 20263 } 20264 20265 /** 20266 * We're removing userHandle and would like to remove any downloaded packages 20267 * that are no longer in use by any other user. 20268 * @param userHandle the user being removed 20269 */ 20270 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20271 final boolean DEBUG_CLEAN_APKS = false; 20272 int [] users = userManager.getUserIds(); 20273 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20274 while (psit.hasNext()) { 20275 PackageSetting ps = psit.next(); 20276 if (ps.pkg == null) { 20277 continue; 20278 } 20279 final String packageName = ps.pkg.packageName; 20280 // Skip over if system app 20281 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20282 continue; 20283 } 20284 if (DEBUG_CLEAN_APKS) { 20285 Slog.i(TAG, "Checking package " + packageName); 20286 } 20287 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20288 if (keep) { 20289 if (DEBUG_CLEAN_APKS) { 20290 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20291 } 20292 } else { 20293 for (int i = 0; i < users.length; i++) { 20294 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20295 keep = true; 20296 if (DEBUG_CLEAN_APKS) { 20297 Slog.i(TAG, " Keeping package " + packageName + " for user " 20298 + users[i]); 20299 } 20300 break; 20301 } 20302 } 20303 } 20304 if (!keep) { 20305 if (DEBUG_CLEAN_APKS) { 20306 Slog.i(TAG, " Removing package " + packageName); 20307 } 20308 mHandler.post(new Runnable() { 20309 public void run() { 20310 deletePackageX(packageName, userHandle, 0); 20311 } //end run 20312 }); 20313 } 20314 } 20315 } 20316 20317 /** Called by UserManagerService */ 20318 void createNewUser(int userId) { 20319 synchronized (mInstallLock) { 20320 mSettings.createNewUserLI(this, mInstaller, userId); 20321 } 20322 synchronized (mPackages) { 20323 scheduleWritePackageRestrictionsLocked(userId); 20324 scheduleWritePackageListLocked(userId); 20325 applyFactoryDefaultBrowserLPw(userId); 20326 primeDomainVerificationsLPw(userId); 20327 } 20328 } 20329 20330 void onBeforeUserStartUninitialized(final int userId) { 20331 synchronized (mPackages) { 20332 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20333 return; 20334 } 20335 } 20336 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20337 // If permission review for legacy apps is required, we represent 20338 // dagerous permissions for such apps as always granted runtime 20339 // permissions to keep per user flag state whether review is needed. 20340 // Hence, if a new user is added we have to propagate dangerous 20341 // permission grants for these legacy apps. 20342 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20343 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20344 | UPDATE_PERMISSIONS_REPLACE_ALL); 20345 } 20346 } 20347 20348 @Override 20349 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20350 mContext.enforceCallingOrSelfPermission( 20351 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20352 "Only package verification agents can read the verifier device identity"); 20353 20354 synchronized (mPackages) { 20355 return mSettings.getVerifierDeviceIdentityLPw(); 20356 } 20357 } 20358 20359 @Override 20360 public void setPermissionEnforced(String permission, boolean enforced) { 20361 // TODO: Now that we no longer change GID for storage, this should to away. 20362 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20363 "setPermissionEnforced"); 20364 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20365 synchronized (mPackages) { 20366 if (mSettings.mReadExternalStorageEnforced == null 20367 || mSettings.mReadExternalStorageEnforced != enforced) { 20368 mSettings.mReadExternalStorageEnforced = enforced; 20369 mSettings.writeLPr(); 20370 } 20371 } 20372 // kill any non-foreground processes so we restart them and 20373 // grant/revoke the GID. 20374 final IActivityManager am = ActivityManagerNative.getDefault(); 20375 if (am != null) { 20376 final long token = Binder.clearCallingIdentity(); 20377 try { 20378 am.killProcessesBelowForeground("setPermissionEnforcement"); 20379 } catch (RemoteException e) { 20380 } finally { 20381 Binder.restoreCallingIdentity(token); 20382 } 20383 } 20384 } else { 20385 throw new IllegalArgumentException("No selective enforcement for " + permission); 20386 } 20387 } 20388 20389 @Override 20390 @Deprecated 20391 public boolean isPermissionEnforced(String permission) { 20392 return true; 20393 } 20394 20395 @Override 20396 public boolean isStorageLow() { 20397 final long token = Binder.clearCallingIdentity(); 20398 try { 20399 final DeviceStorageMonitorInternal 20400 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20401 if (dsm != null) { 20402 return dsm.isMemoryLow(); 20403 } else { 20404 return false; 20405 } 20406 } finally { 20407 Binder.restoreCallingIdentity(token); 20408 } 20409 } 20410 20411 @Override 20412 public IPackageInstaller getPackageInstaller() { 20413 return mInstallerService; 20414 } 20415 20416 private boolean userNeedsBadging(int userId) { 20417 int index = mUserNeedsBadging.indexOfKey(userId); 20418 if (index < 0) { 20419 final UserInfo userInfo; 20420 final long token = Binder.clearCallingIdentity(); 20421 try { 20422 userInfo = sUserManager.getUserInfo(userId); 20423 } finally { 20424 Binder.restoreCallingIdentity(token); 20425 } 20426 final boolean b; 20427 if (userInfo != null && userInfo.isManagedProfile()) { 20428 b = true; 20429 } else { 20430 b = false; 20431 } 20432 mUserNeedsBadging.put(userId, b); 20433 return b; 20434 } 20435 return mUserNeedsBadging.valueAt(index); 20436 } 20437 20438 @Override 20439 public KeySet getKeySetByAlias(String packageName, String alias) { 20440 if (packageName == null || alias == null) { 20441 return null; 20442 } 20443 synchronized(mPackages) { 20444 final PackageParser.Package pkg = mPackages.get(packageName); 20445 if (pkg == null) { 20446 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20447 throw new IllegalArgumentException("Unknown package: " + packageName); 20448 } 20449 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20450 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20451 } 20452 } 20453 20454 @Override 20455 public KeySet getSigningKeySet(String packageName) { 20456 if (packageName == null) { 20457 return null; 20458 } 20459 synchronized(mPackages) { 20460 final PackageParser.Package pkg = mPackages.get(packageName); 20461 if (pkg == null) { 20462 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20463 throw new IllegalArgumentException("Unknown package: " + packageName); 20464 } 20465 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20466 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20467 throw new SecurityException("May not access signing KeySet of other apps."); 20468 } 20469 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20470 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20471 } 20472 } 20473 20474 @Override 20475 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20476 if (packageName == null || ks == null) { 20477 return false; 20478 } 20479 synchronized(mPackages) { 20480 final PackageParser.Package pkg = mPackages.get(packageName); 20481 if (pkg == null) { 20482 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20483 throw new IllegalArgumentException("Unknown package: " + packageName); 20484 } 20485 IBinder ksh = ks.getToken(); 20486 if (ksh instanceof KeySetHandle) { 20487 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20488 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20489 } 20490 return false; 20491 } 20492 } 20493 20494 @Override 20495 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20496 if (packageName == null || ks == null) { 20497 return false; 20498 } 20499 synchronized(mPackages) { 20500 final PackageParser.Package pkg = mPackages.get(packageName); 20501 if (pkg == null) { 20502 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20503 throw new IllegalArgumentException("Unknown package: " + packageName); 20504 } 20505 IBinder ksh = ks.getToken(); 20506 if (ksh instanceof KeySetHandle) { 20507 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20508 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20509 } 20510 return false; 20511 } 20512 } 20513 20514 private void deletePackageIfUnusedLPr(final String packageName) { 20515 PackageSetting ps = mSettings.mPackages.get(packageName); 20516 if (ps == null) { 20517 return; 20518 } 20519 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20520 // TODO Implement atomic delete if package is unused 20521 // It is currently possible that the package will be deleted even if it is installed 20522 // after this method returns. 20523 mHandler.post(new Runnable() { 20524 public void run() { 20525 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20526 } 20527 }); 20528 } 20529 } 20530 20531 /** 20532 * Check and throw if the given before/after packages would be considered a 20533 * downgrade. 20534 */ 20535 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20536 throws PackageManagerException { 20537 if (after.versionCode < before.mVersionCode) { 20538 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20539 "Update version code " + after.versionCode + " is older than current " 20540 + before.mVersionCode); 20541 } else if (after.versionCode == before.mVersionCode) { 20542 if (after.baseRevisionCode < before.baseRevisionCode) { 20543 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20544 "Update base revision code " + after.baseRevisionCode 20545 + " is older than current " + before.baseRevisionCode); 20546 } 20547 20548 if (!ArrayUtils.isEmpty(after.splitNames)) { 20549 for (int i = 0; i < after.splitNames.length; i++) { 20550 final String splitName = after.splitNames[i]; 20551 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20552 if (j != -1) { 20553 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20554 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20555 "Update split " + splitName + " revision code " 20556 + after.splitRevisionCodes[i] + " is older than current " 20557 + before.splitRevisionCodes[j]); 20558 } 20559 } 20560 } 20561 } 20562 } 20563 } 20564 20565 private static class MoveCallbacks extends Handler { 20566 private static final int MSG_CREATED = 1; 20567 private static final int MSG_STATUS_CHANGED = 2; 20568 20569 private final RemoteCallbackList<IPackageMoveObserver> 20570 mCallbacks = new RemoteCallbackList<>(); 20571 20572 private final SparseIntArray mLastStatus = new SparseIntArray(); 20573 20574 public MoveCallbacks(Looper looper) { 20575 super(looper); 20576 } 20577 20578 public void register(IPackageMoveObserver callback) { 20579 mCallbacks.register(callback); 20580 } 20581 20582 public void unregister(IPackageMoveObserver callback) { 20583 mCallbacks.unregister(callback); 20584 } 20585 20586 @Override 20587 public void handleMessage(Message msg) { 20588 final SomeArgs args = (SomeArgs) msg.obj; 20589 final int n = mCallbacks.beginBroadcast(); 20590 for (int i = 0; i < n; i++) { 20591 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20592 try { 20593 invokeCallback(callback, msg.what, args); 20594 } catch (RemoteException ignored) { 20595 } 20596 } 20597 mCallbacks.finishBroadcast(); 20598 args.recycle(); 20599 } 20600 20601 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20602 throws RemoteException { 20603 switch (what) { 20604 case MSG_CREATED: { 20605 callback.onCreated(args.argi1, (Bundle) args.arg2); 20606 break; 20607 } 20608 case MSG_STATUS_CHANGED: { 20609 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20610 break; 20611 } 20612 } 20613 } 20614 20615 private void notifyCreated(int moveId, Bundle extras) { 20616 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20617 20618 final SomeArgs args = SomeArgs.obtain(); 20619 args.argi1 = moveId; 20620 args.arg2 = extras; 20621 obtainMessage(MSG_CREATED, args).sendToTarget(); 20622 } 20623 20624 private void notifyStatusChanged(int moveId, int status) { 20625 notifyStatusChanged(moveId, status, -1); 20626 } 20627 20628 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20629 Slog.v(TAG, "Move " + moveId + " status " + status); 20630 20631 final SomeArgs args = SomeArgs.obtain(); 20632 args.argi1 = moveId; 20633 args.argi2 = status; 20634 args.arg3 = estMillis; 20635 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20636 20637 synchronized (mLastStatus) { 20638 mLastStatus.put(moveId, status); 20639 } 20640 } 20641 } 20642 20643 private final static class OnPermissionChangeListeners extends Handler { 20644 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20645 20646 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20647 new RemoteCallbackList<>(); 20648 20649 public OnPermissionChangeListeners(Looper looper) { 20650 super(looper); 20651 } 20652 20653 @Override 20654 public void handleMessage(Message msg) { 20655 switch (msg.what) { 20656 case MSG_ON_PERMISSIONS_CHANGED: { 20657 final int uid = msg.arg1; 20658 handleOnPermissionsChanged(uid); 20659 } break; 20660 } 20661 } 20662 20663 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20664 mPermissionListeners.register(listener); 20665 20666 } 20667 20668 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20669 mPermissionListeners.unregister(listener); 20670 } 20671 20672 public void onPermissionsChanged(int uid) { 20673 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20674 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20675 } 20676 } 20677 20678 private void handleOnPermissionsChanged(int uid) { 20679 final int count = mPermissionListeners.beginBroadcast(); 20680 try { 20681 for (int i = 0; i < count; i++) { 20682 IOnPermissionsChangeListener callback = mPermissionListeners 20683 .getBroadcastItem(i); 20684 try { 20685 callback.onPermissionsChanged(uid); 20686 } catch (RemoteException e) { 20687 Log.e(TAG, "Permission listener is dead", e); 20688 } 20689 } 20690 } finally { 20691 mPermissionListeners.finishBroadcast(); 20692 } 20693 } 20694 } 20695 20696 private class PackageManagerInternalImpl extends PackageManagerInternal { 20697 @Override 20698 public void setLocationPackagesProvider(PackagesProvider provider) { 20699 synchronized (mPackages) { 20700 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20701 } 20702 } 20703 20704 @Override 20705 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20706 synchronized (mPackages) { 20707 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20708 } 20709 } 20710 20711 @Override 20712 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20713 synchronized (mPackages) { 20714 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20715 } 20716 } 20717 20718 @Override 20719 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20720 synchronized (mPackages) { 20721 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20722 } 20723 } 20724 20725 @Override 20726 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20727 synchronized (mPackages) { 20728 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20729 } 20730 } 20731 20732 @Override 20733 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20734 synchronized (mPackages) { 20735 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20736 } 20737 } 20738 20739 @Override 20740 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20741 synchronized (mPackages) { 20742 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20743 packageName, userId); 20744 } 20745 } 20746 20747 @Override 20748 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20749 synchronized (mPackages) { 20750 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20751 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20752 packageName, userId); 20753 } 20754 } 20755 20756 @Override 20757 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20758 synchronized (mPackages) { 20759 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20760 packageName, userId); 20761 } 20762 } 20763 20764 @Override 20765 public void setKeepUninstalledPackages(final List<String> packageList) { 20766 Preconditions.checkNotNull(packageList); 20767 List<String> removedFromList = null; 20768 synchronized (mPackages) { 20769 if (mKeepUninstalledPackages != null) { 20770 final int packagesCount = mKeepUninstalledPackages.size(); 20771 for (int i = 0; i < packagesCount; i++) { 20772 String oldPackage = mKeepUninstalledPackages.get(i); 20773 if (packageList != null && packageList.contains(oldPackage)) { 20774 continue; 20775 } 20776 if (removedFromList == null) { 20777 removedFromList = new ArrayList<>(); 20778 } 20779 removedFromList.add(oldPackage); 20780 } 20781 } 20782 mKeepUninstalledPackages = new ArrayList<>(packageList); 20783 if (removedFromList != null) { 20784 final int removedCount = removedFromList.size(); 20785 for (int i = 0; i < removedCount; i++) { 20786 deletePackageIfUnusedLPr(removedFromList.get(i)); 20787 } 20788 } 20789 } 20790 } 20791 20792 @Override 20793 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20794 synchronized (mPackages) { 20795 // If we do not support permission review, done. 20796 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20797 return false; 20798 } 20799 20800 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20801 if (packageSetting == null) { 20802 return false; 20803 } 20804 20805 // Permission review applies only to apps not supporting the new permission model. 20806 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20807 return false; 20808 } 20809 20810 // Legacy apps have the permission and get user consent on launch. 20811 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20812 return permissionsState.isPermissionReviewRequired(userId); 20813 } 20814 } 20815 20816 @Override 20817 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20818 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20819 } 20820 20821 @Override 20822 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20823 int userId) { 20824 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20825 } 20826 20827 @Override 20828 public void setDeviceAndProfileOwnerPackages( 20829 int deviceOwnerUserId, String deviceOwnerPackage, 20830 SparseArray<String> profileOwnerPackages) { 20831 mProtectedPackages.setDeviceAndProfileOwnerPackages( 20832 deviceOwnerUserId, deviceOwnerPackage, profileOwnerPackages); 20833 } 20834 20835 @Override 20836 public boolean canPackageBeWiped(int userId, String packageName) { 20837 return mProtectedPackages.canPackageBeWiped(userId, 20838 packageName); 20839 } 20840 } 20841 20842 @Override 20843 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20844 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20845 synchronized (mPackages) { 20846 final long identity = Binder.clearCallingIdentity(); 20847 try { 20848 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20849 packageNames, userId); 20850 } finally { 20851 Binder.restoreCallingIdentity(identity); 20852 } 20853 } 20854 } 20855 20856 private static void enforceSystemOrPhoneCaller(String tag) { 20857 int callingUid = Binder.getCallingUid(); 20858 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20859 throw new SecurityException( 20860 "Cannot call " + tag + " from UID " + callingUid); 20861 } 20862 } 20863 20864 boolean isHistoricalPackageUsageAvailable() { 20865 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20866 } 20867 20868 /** 20869 * Return a <b>copy</b> of the collection of packages known to the package manager. 20870 * @return A copy of the values of mPackages. 20871 */ 20872 Collection<PackageParser.Package> getPackages() { 20873 synchronized (mPackages) { 20874 return new ArrayList<>(mPackages.values()); 20875 } 20876 } 20877 20878 /** 20879 * Logs process start information (including base APK hash) to the security log. 20880 * @hide 20881 */ 20882 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20883 String apkFile, int pid) { 20884 if (!SecurityLog.isLoggingEnabled()) { 20885 return; 20886 } 20887 Bundle data = new Bundle(); 20888 data.putLong("startTimestamp", System.currentTimeMillis()); 20889 data.putString("processName", processName); 20890 data.putInt("uid", uid); 20891 data.putString("seinfo", seinfo); 20892 data.putString("apkFile", apkFile); 20893 data.putInt("pid", pid); 20894 Message msg = mProcessLoggingHandler.obtainMessage( 20895 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20896 msg.setData(data); 20897 mProcessLoggingHandler.sendMessage(msg); 20898 } 20899} 20900