PackageManagerService.java revision e2e1ef0581c188014a0b11bbf46325b82d959720
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.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.ResourcesManager; 109import android.app.admin.DevicePolicyManagerInternal; 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 = Build.IS_DEBUGGABLE; 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 = !Build.IS_DEBUGGABLE; 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 boolean mRestoredSettings; 626 627 // System configuration read by SystemConfig. 628 final int[] mGlobalGids; 629 final SparseArray<ArraySet<String>> mSystemPermissions; 630 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 631 632 // If mac_permissions.xml was found for seinfo labeling. 633 boolean mFoundPolicyFile; 634 635 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 636 637 public static final class SharedLibraryEntry { 638 public final String path; 639 public final String apk; 640 641 SharedLibraryEntry(String _path, String _apk) { 642 path = _path; 643 apk = _apk; 644 } 645 } 646 647 // Currently known shared libraries. 648 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 649 new ArrayMap<String, SharedLibraryEntry>(); 650 651 // All available activities, for your resolving pleasure. 652 final ActivityIntentResolver mActivities = 653 new ActivityIntentResolver(); 654 655 // All available receivers, for your resolving pleasure. 656 final ActivityIntentResolver mReceivers = 657 new ActivityIntentResolver(); 658 659 // All available services, for your resolving pleasure. 660 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 661 662 // All available providers, for your resolving pleasure. 663 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 664 665 // Mapping from provider base names (first directory in content URI codePath) 666 // to the provider information. 667 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 668 new ArrayMap<String, PackageParser.Provider>(); 669 670 // Mapping from instrumentation class names to info about them. 671 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 672 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 673 674 // Mapping from permission names to info about them. 675 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 676 new ArrayMap<String, PackageParser.PermissionGroup>(); 677 678 // Packages whose data we have transfered into another package, thus 679 // should no longer exist. 680 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 681 682 // Broadcast actions that are only available to the system. 683 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 684 685 /** List of packages waiting for verification. */ 686 final SparseArray<PackageVerificationState> mPendingVerification 687 = new SparseArray<PackageVerificationState>(); 688 689 /** Set of packages associated with each app op permission. */ 690 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 691 692 final PackageInstallerService mInstallerService; 693 694 private final PackageDexOptimizer mPackageDexOptimizer; 695 696 private AtomicInteger mNextMoveId = new AtomicInteger(); 697 private final MoveCallbacks mMoveCallbacks; 698 699 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 700 701 // Cache of users who need badging. 702 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 703 704 /** Token for keys in mPendingVerification. */ 705 private int mPendingVerificationToken = 0; 706 707 volatile boolean mSystemReady; 708 volatile boolean mSafeMode; 709 volatile boolean mHasSystemUidErrors; 710 711 ApplicationInfo mAndroidApplication; 712 final ActivityInfo mResolveActivity = new ActivityInfo(); 713 final ResolveInfo mResolveInfo = new ResolveInfo(); 714 ComponentName mResolveComponentName; 715 PackageParser.Package mPlatformPackage; 716 ComponentName mCustomResolverComponentName; 717 718 boolean mResolverReplaced = false; 719 720 private final @Nullable ComponentName mIntentFilterVerifierComponent; 721 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 722 723 private int mIntentFilterVerificationToken = 0; 724 725 /** Component that knows whether or not an ephemeral application exists */ 726 final ComponentName mEphemeralResolverComponent; 727 /** The service connection to the ephemeral resolver */ 728 final EphemeralResolverConnection mEphemeralResolverConnection; 729 730 /** Component used to install ephemeral applications */ 731 final ComponentName mEphemeralInstallerComponent; 732 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 733 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 734 735 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 736 = new SparseArray<IntentFilterVerificationState>(); 737 738 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 739 new DefaultPermissionGrantPolicy(this); 740 741 // List of packages names to keep cached, even if they are uninstalled for all users 742 private List<String> mKeepUninstalledPackages; 743 744 private UserManagerInternal mUserManagerInternal; 745 746 private static class IFVerificationParams { 747 PackageParser.Package pkg; 748 boolean replacing; 749 int userId; 750 int verifierUid; 751 752 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 753 int _userId, int _verifierUid) { 754 pkg = _pkg; 755 replacing = _replacing; 756 userId = _userId; 757 replacing = _replacing; 758 verifierUid = _verifierUid; 759 } 760 } 761 762 private interface IntentFilterVerifier<T extends IntentFilter> { 763 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 764 T filter, String packageName); 765 void startVerifications(int userId); 766 void receiveVerificationResponse(int verificationId); 767 } 768 769 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 770 private Context mContext; 771 private ComponentName mIntentFilterVerifierComponent; 772 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 773 774 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 775 mContext = context; 776 mIntentFilterVerifierComponent = verifierComponent; 777 } 778 779 private String getDefaultScheme() { 780 return IntentFilter.SCHEME_HTTPS; 781 } 782 783 @Override 784 public void startVerifications(int userId) { 785 // Launch verifications requests 786 int count = mCurrentIntentFilterVerifications.size(); 787 for (int n=0; n<count; n++) { 788 int verificationId = mCurrentIntentFilterVerifications.get(n); 789 final IntentFilterVerificationState ivs = 790 mIntentFilterVerificationStates.get(verificationId); 791 792 String packageName = ivs.getPackageName(); 793 794 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 795 final int filterCount = filters.size(); 796 ArraySet<String> domainsSet = new ArraySet<>(); 797 for (int m=0; m<filterCount; m++) { 798 PackageParser.ActivityIntentInfo filter = filters.get(m); 799 domainsSet.addAll(filter.getHostsList()); 800 } 801 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 802 synchronized (mPackages) { 803 if (mSettings.createIntentFilterVerificationIfNeededLPw( 804 packageName, domainsList) != null) { 805 scheduleWriteSettingsLocked(); 806 } 807 } 808 sendVerificationRequest(userId, verificationId, ivs); 809 } 810 mCurrentIntentFilterVerifications.clear(); 811 } 812 813 private void sendVerificationRequest(int userId, int verificationId, 814 IntentFilterVerificationState ivs) { 815 816 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 817 verificationIntent.putExtra( 818 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 819 verificationId); 820 verificationIntent.putExtra( 821 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 822 getDefaultScheme()); 823 verificationIntent.putExtra( 824 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 825 ivs.getHostsString()); 826 verificationIntent.putExtra( 827 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 828 ivs.getPackageName()); 829 verificationIntent.setComponent(mIntentFilterVerifierComponent); 830 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 831 832 UserHandle user = new UserHandle(userId); 833 mContext.sendBroadcastAsUser(verificationIntent, user); 834 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 835 "Sending IntentFilter verification broadcast"); 836 } 837 838 public void receiveVerificationResponse(int verificationId) { 839 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 840 841 final boolean verified = ivs.isVerified(); 842 843 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 844 final int count = filters.size(); 845 if (DEBUG_DOMAIN_VERIFICATION) { 846 Slog.i(TAG, "Received verification response " + verificationId 847 + " for " + count + " filters, verified=" + verified); 848 } 849 for (int n=0; n<count; n++) { 850 PackageParser.ActivityIntentInfo filter = filters.get(n); 851 filter.setVerified(verified); 852 853 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 854 + " verified with result:" + verified + " and hosts:" 855 + ivs.getHostsString()); 856 } 857 858 mIntentFilterVerificationStates.remove(verificationId); 859 860 final String packageName = ivs.getPackageName(); 861 IntentFilterVerificationInfo ivi = null; 862 863 synchronized (mPackages) { 864 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 865 } 866 if (ivi == null) { 867 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 868 + verificationId + " packageName:" + packageName); 869 return; 870 } 871 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 872 "Updating IntentFilterVerificationInfo for package " + packageName 873 +" verificationId:" + verificationId); 874 875 synchronized (mPackages) { 876 if (verified) { 877 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 878 } else { 879 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 880 } 881 scheduleWriteSettingsLocked(); 882 883 final int userId = ivs.getUserId(); 884 if (userId != UserHandle.USER_ALL) { 885 final int userStatus = 886 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 887 888 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 889 boolean needUpdate = false; 890 891 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 892 // already been set by the User thru the Disambiguation dialog 893 switch (userStatus) { 894 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 895 if (verified) { 896 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 897 } else { 898 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 899 } 900 needUpdate = true; 901 break; 902 903 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 904 if (verified) { 905 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 906 needUpdate = true; 907 } 908 break; 909 910 default: 911 // Nothing to do 912 } 913 914 if (needUpdate) { 915 mSettings.updateIntentFilterVerificationStatusLPw( 916 packageName, updatedStatus, userId); 917 scheduleWritePackageRestrictionsLocked(userId); 918 } 919 } 920 } 921 } 922 923 @Override 924 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 925 ActivityIntentInfo filter, String packageName) { 926 if (!hasValidDomains(filter)) { 927 return false; 928 } 929 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 930 if (ivs == null) { 931 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 932 packageName); 933 } 934 if (DEBUG_DOMAIN_VERIFICATION) { 935 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 936 } 937 ivs.addFilter(filter); 938 return true; 939 } 940 941 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 942 int userId, int verificationId, String packageName) { 943 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 944 verifierUid, userId, packageName); 945 ivs.setPendingState(); 946 synchronized (mPackages) { 947 mIntentFilterVerificationStates.append(verificationId, ivs); 948 mCurrentIntentFilterVerifications.add(verificationId); 949 } 950 return ivs; 951 } 952 } 953 954 private static boolean hasValidDomains(ActivityIntentInfo filter) { 955 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 956 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 957 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 958 } 959 960 // Set of pending broadcasts for aggregating enable/disable of components. 961 static class PendingPackageBroadcasts { 962 // for each user id, a map of <package name -> components within that package> 963 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 964 965 public PendingPackageBroadcasts() { 966 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 967 } 968 969 public ArrayList<String> get(int userId, String packageName) { 970 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 971 return packages.get(packageName); 972 } 973 974 public void put(int userId, String packageName, ArrayList<String> components) { 975 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 976 packages.put(packageName, components); 977 } 978 979 public void remove(int userId, String packageName) { 980 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 981 if (packages != null) { 982 packages.remove(packageName); 983 } 984 } 985 986 public void remove(int userId) { 987 mUidMap.remove(userId); 988 } 989 990 public int userIdCount() { 991 return mUidMap.size(); 992 } 993 994 public int userIdAt(int n) { 995 return mUidMap.keyAt(n); 996 } 997 998 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 999 return mUidMap.get(userId); 1000 } 1001 1002 public int size() { 1003 // total number of pending broadcast entries across all userIds 1004 int num = 0; 1005 for (int i = 0; i< mUidMap.size(); i++) { 1006 num += mUidMap.valueAt(i).size(); 1007 } 1008 return num; 1009 } 1010 1011 public void clear() { 1012 mUidMap.clear(); 1013 } 1014 1015 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1016 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1017 if (map == null) { 1018 map = new ArrayMap<String, ArrayList<String>>(); 1019 mUidMap.put(userId, map); 1020 } 1021 return map; 1022 } 1023 } 1024 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1025 1026 // Service Connection to remote media container service to copy 1027 // package uri's from external media onto secure containers 1028 // or internal storage. 1029 private IMediaContainerService mContainerService = null; 1030 1031 static final int SEND_PENDING_BROADCAST = 1; 1032 static final int MCS_BOUND = 3; 1033 static final int END_COPY = 4; 1034 static final int INIT_COPY = 5; 1035 static final int MCS_UNBIND = 6; 1036 static final int START_CLEANING_PACKAGE = 7; 1037 static final int FIND_INSTALL_LOC = 8; 1038 static final int POST_INSTALL = 9; 1039 static final int MCS_RECONNECT = 10; 1040 static final int MCS_GIVE_UP = 11; 1041 static final int UPDATED_MEDIA_STATUS = 12; 1042 static final int WRITE_SETTINGS = 13; 1043 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1044 static final int PACKAGE_VERIFIED = 15; 1045 static final int CHECK_PENDING_VERIFICATION = 16; 1046 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1047 static final int INTENT_FILTER_VERIFIED = 18; 1048 static final int WRITE_PACKAGE_LIST = 19; 1049 1050 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1051 1052 // Delay time in millisecs 1053 static final int BROADCAST_DELAY = 10 * 1000; 1054 1055 static UserManagerService sUserManager; 1056 1057 // Stores a list of users whose package restrictions file needs to be updated 1058 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1059 1060 final private DefaultContainerConnection mDefContainerConn = 1061 new DefaultContainerConnection(); 1062 class DefaultContainerConnection implements ServiceConnection { 1063 public void onServiceConnected(ComponentName name, IBinder service) { 1064 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1065 IMediaContainerService imcs = 1066 IMediaContainerService.Stub.asInterface(service); 1067 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1068 } 1069 1070 public void onServiceDisconnected(ComponentName name) { 1071 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1072 } 1073 } 1074 1075 // Recordkeeping of restore-after-install operations that are currently in flight 1076 // between the Package Manager and the Backup Manager 1077 static class PostInstallData { 1078 public InstallArgs args; 1079 public PackageInstalledInfo res; 1080 1081 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1082 args = _a; 1083 res = _r; 1084 } 1085 } 1086 1087 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1088 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1089 1090 // XML tags for backup/restore of various bits of state 1091 private static final String TAG_PREFERRED_BACKUP = "pa"; 1092 private static final String TAG_DEFAULT_APPS = "da"; 1093 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1094 1095 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1096 private static final String TAG_ALL_GRANTS = "rt-grants"; 1097 private static final String TAG_GRANT = "grant"; 1098 private static final String ATTR_PACKAGE_NAME = "pkg"; 1099 1100 private static final String TAG_PERMISSION = "perm"; 1101 private static final String ATTR_PERMISSION_NAME = "name"; 1102 private static final String ATTR_IS_GRANTED = "g"; 1103 private static final String ATTR_USER_SET = "set"; 1104 private static final String ATTR_USER_FIXED = "fixed"; 1105 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1106 1107 // System/policy permission grants are not backed up 1108 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1109 FLAG_PERMISSION_POLICY_FIXED 1110 | FLAG_PERMISSION_SYSTEM_FIXED 1111 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1112 1113 // And we back up these user-adjusted states 1114 private static final int USER_RUNTIME_GRANT_MASK = 1115 FLAG_PERMISSION_USER_SET 1116 | FLAG_PERMISSION_USER_FIXED 1117 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1118 1119 final @Nullable String mRequiredVerifierPackage; 1120 final @NonNull String mRequiredInstallerPackage; 1121 final @Nullable String mSetupWizardPackage; 1122 final @NonNull String mServicesSystemSharedLibraryPackageName; 1123 final @NonNull String mSharedSystemSharedLibraryPackageName; 1124 1125 private final PackageUsage mPackageUsage = new PackageUsage(); 1126 1127 private class PackageUsage { 1128 private static final int WRITE_INTERVAL 1129 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1130 1131 private final Object mFileLock = new Object(); 1132 private final AtomicLong mLastWritten = new AtomicLong(0); 1133 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1134 1135 private boolean mIsHistoricalPackageUsageAvailable = true; 1136 1137 boolean isHistoricalPackageUsageAvailable() { 1138 return mIsHistoricalPackageUsageAvailable; 1139 } 1140 1141 void write(boolean force) { 1142 if (force) { 1143 writeInternal(); 1144 return; 1145 } 1146 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1147 && !DEBUG_DEXOPT) { 1148 return; 1149 } 1150 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1151 new Thread("PackageUsage_DiskWriter") { 1152 @Override 1153 public void run() { 1154 try { 1155 writeInternal(); 1156 } finally { 1157 mBackgroundWriteRunning.set(false); 1158 } 1159 } 1160 }.start(); 1161 } 1162 } 1163 1164 private void writeInternal() { 1165 synchronized (mPackages) { 1166 synchronized (mFileLock) { 1167 AtomicFile file = getFile(); 1168 FileOutputStream f = null; 1169 try { 1170 f = file.startWrite(); 1171 BufferedOutputStream out = new BufferedOutputStream(f); 1172 FileUtils.setPermissions(file.getBaseFile().getPath(), 1173 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1174 StringBuilder sb = new StringBuilder(); 1175 1176 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1177 sb.append('\n'); 1178 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1179 1180 for (PackageParser.Package pkg : mPackages.values()) { 1181 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1182 continue; 1183 } 1184 sb.setLength(0); 1185 sb.append(pkg.packageName); 1186 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1187 sb.append(' '); 1188 sb.append(usageTimeInMillis); 1189 } 1190 sb.append('\n'); 1191 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1192 } 1193 out.flush(); 1194 file.finishWrite(f); 1195 } catch (IOException e) { 1196 if (f != null) { 1197 file.failWrite(f); 1198 } 1199 Log.e(TAG, "Failed to write package usage times", e); 1200 } 1201 } 1202 } 1203 mLastWritten.set(SystemClock.elapsedRealtime()); 1204 } 1205 1206 void readLP() { 1207 synchronized (mFileLock) { 1208 AtomicFile file = getFile(); 1209 BufferedInputStream in = null; 1210 try { 1211 in = new BufferedInputStream(file.openRead()); 1212 StringBuffer sb = new StringBuffer(); 1213 1214 String firstLine = readLine(in, sb); 1215 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1216 readVersion1LP(in, sb); 1217 } else { 1218 readVersion0LP(in, sb, firstLine); 1219 } 1220 } catch (FileNotFoundException expected) { 1221 mIsHistoricalPackageUsageAvailable = false; 1222 } catch (IOException e) { 1223 Log.w(TAG, "Failed to read package usage times", e); 1224 } finally { 1225 IoUtils.closeQuietly(in); 1226 } 1227 } 1228 mLastWritten.set(SystemClock.elapsedRealtime()); 1229 } 1230 1231 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1232 throws IOException { 1233 // Initial version of the file had no version number and stored one 1234 // package-timestamp pair per line. 1235 // Note that the first line has already been read from the InputStream. 1236 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1237 String[] tokens = line.split(" "); 1238 if (tokens.length != 2) { 1239 throw new IOException("Failed to parse " + line + 1240 " as package-timestamp pair."); 1241 } 1242 1243 String packageName = tokens[0]; 1244 PackageParser.Package pkg = mPackages.get(packageName); 1245 if (pkg == null) { 1246 continue; 1247 } 1248 1249 long timestamp = parseAsLong(tokens[1]); 1250 for (int reason = 0; 1251 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1252 reason++) { 1253 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1254 } 1255 } 1256 } 1257 1258 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1259 // Version 1 of the file started with the corresponding version 1260 // number and then stored a package name and eight timestamps per line. 1261 String line; 1262 while ((line = readLine(in, sb)) != null) { 1263 String[] tokens = line.split(" "); 1264 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1265 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1266 } 1267 1268 String packageName = tokens[0]; 1269 PackageParser.Package pkg = mPackages.get(packageName); 1270 if (pkg == null) { 1271 continue; 1272 } 1273 1274 for (int reason = 0; 1275 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1276 reason++) { 1277 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1278 } 1279 } 1280 } 1281 1282 private long parseAsLong(String token) throws IOException { 1283 try { 1284 return Long.parseLong(token); 1285 } catch (NumberFormatException e) { 1286 throw new IOException("Failed to parse " + token + " as a long.", e); 1287 } 1288 } 1289 1290 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1291 return readToken(in, sb, '\n'); 1292 } 1293 1294 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1295 throws IOException { 1296 sb.setLength(0); 1297 while (true) { 1298 int ch = in.read(); 1299 if (ch == -1) { 1300 if (sb.length() == 0) { 1301 return null; 1302 } 1303 throw new IOException("Unexpected EOF"); 1304 } 1305 if (ch == endOfToken) { 1306 return sb.toString(); 1307 } 1308 sb.append((char)ch); 1309 } 1310 } 1311 1312 private AtomicFile getFile() { 1313 File dataDir = Environment.getDataDirectory(); 1314 File systemDir = new File(dataDir, "system"); 1315 File fname = new File(systemDir, "package-usage.list"); 1316 return new AtomicFile(fname); 1317 } 1318 1319 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1320 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1321 } 1322 1323 class PackageHandler extends Handler { 1324 private boolean mBound = false; 1325 final ArrayList<HandlerParams> mPendingInstalls = 1326 new ArrayList<HandlerParams>(); 1327 1328 private boolean connectToService() { 1329 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1330 " DefaultContainerService"); 1331 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1333 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1334 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1335 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1336 mBound = true; 1337 return true; 1338 } 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1340 return false; 1341 } 1342 1343 private void disconnectService() { 1344 mContainerService = null; 1345 mBound = false; 1346 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1347 mContext.unbindService(mDefContainerConn); 1348 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1349 } 1350 1351 PackageHandler(Looper looper) { 1352 super(looper); 1353 } 1354 1355 public void handleMessage(Message msg) { 1356 try { 1357 doHandleMessage(msg); 1358 } finally { 1359 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1360 } 1361 } 1362 1363 void doHandleMessage(Message msg) { 1364 switch (msg.what) { 1365 case INIT_COPY: { 1366 HandlerParams params = (HandlerParams) msg.obj; 1367 int idx = mPendingInstalls.size(); 1368 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1369 // If a bind was already initiated we dont really 1370 // need to do anything. The pending install 1371 // will be processed later on. 1372 if (!mBound) { 1373 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1374 System.identityHashCode(mHandler)); 1375 // If this is the only one pending we might 1376 // have to bind to the service again. 1377 if (!connectToService()) { 1378 Slog.e(TAG, "Failed to bind to media container service"); 1379 params.serviceError(); 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1381 System.identityHashCode(mHandler)); 1382 if (params.traceMethod != null) { 1383 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1384 params.traceCookie); 1385 } 1386 return; 1387 } else { 1388 // Once we bind to the service, the first 1389 // pending request will be processed. 1390 mPendingInstalls.add(idx, params); 1391 } 1392 } else { 1393 mPendingInstalls.add(idx, params); 1394 // Already bound to the service. Just make 1395 // sure we trigger off processing the first request. 1396 if (idx == 0) { 1397 mHandler.sendEmptyMessage(MCS_BOUND); 1398 } 1399 } 1400 break; 1401 } 1402 case MCS_BOUND: { 1403 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1404 if (msg.obj != null) { 1405 mContainerService = (IMediaContainerService) msg.obj; 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1407 System.identityHashCode(mHandler)); 1408 } 1409 if (mContainerService == null) { 1410 if (!mBound) { 1411 // Something seriously wrong since we are not bound and we are not 1412 // waiting for connection. Bail out. 1413 Slog.e(TAG, "Cannot bind to media container service"); 1414 for (HandlerParams params : mPendingInstalls) { 1415 // Indicate service bind error 1416 params.serviceError(); 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1418 System.identityHashCode(params)); 1419 if (params.traceMethod != null) { 1420 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1421 params.traceMethod, params.traceCookie); 1422 } 1423 return; 1424 } 1425 mPendingInstalls.clear(); 1426 } else { 1427 Slog.w(TAG, "Waiting to connect to media container service"); 1428 } 1429 } else if (mPendingInstalls.size() > 0) { 1430 HandlerParams params = mPendingInstalls.get(0); 1431 if (params != null) { 1432 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1433 System.identityHashCode(params)); 1434 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1435 if (params.startCopy()) { 1436 // We are done... look for more work or to 1437 // go idle. 1438 if (DEBUG_SD_INSTALL) Log.i(TAG, 1439 "Checking for more work or unbind..."); 1440 // Delete pending install 1441 if (mPendingInstalls.size() > 0) { 1442 mPendingInstalls.remove(0); 1443 } 1444 if (mPendingInstalls.size() == 0) { 1445 if (mBound) { 1446 if (DEBUG_SD_INSTALL) Log.i(TAG, 1447 "Posting delayed MCS_UNBIND"); 1448 removeMessages(MCS_UNBIND); 1449 Message ubmsg = obtainMessage(MCS_UNBIND); 1450 // Unbind after a little delay, to avoid 1451 // continual thrashing. 1452 sendMessageDelayed(ubmsg, 10000); 1453 } 1454 } else { 1455 // There are more pending requests in queue. 1456 // Just post MCS_BOUND message to trigger processing 1457 // of next pending install. 1458 if (DEBUG_SD_INSTALL) Log.i(TAG, 1459 "Posting MCS_BOUND for next work"); 1460 mHandler.sendEmptyMessage(MCS_BOUND); 1461 } 1462 } 1463 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1464 } 1465 } else { 1466 // Should never happen ideally. 1467 Slog.w(TAG, "Empty queue"); 1468 } 1469 break; 1470 } 1471 case MCS_RECONNECT: { 1472 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1473 if (mPendingInstalls.size() > 0) { 1474 if (mBound) { 1475 disconnectService(); 1476 } 1477 if (!connectToService()) { 1478 Slog.e(TAG, "Failed to bind to media container service"); 1479 for (HandlerParams params : mPendingInstalls) { 1480 // Indicate service bind error 1481 params.serviceError(); 1482 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1483 System.identityHashCode(params)); 1484 } 1485 mPendingInstalls.clear(); 1486 } 1487 } 1488 break; 1489 } 1490 case MCS_UNBIND: { 1491 // If there is no actual work left, then time to unbind. 1492 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1493 1494 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1495 if (mBound) { 1496 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1497 1498 disconnectService(); 1499 } 1500 } else if (mPendingInstalls.size() > 0) { 1501 // There are more pending requests in queue. 1502 // Just post MCS_BOUND message to trigger processing 1503 // of next pending install. 1504 mHandler.sendEmptyMessage(MCS_BOUND); 1505 } 1506 1507 break; 1508 } 1509 case MCS_GIVE_UP: { 1510 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1511 HandlerParams params = mPendingInstalls.remove(0); 1512 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1513 System.identityHashCode(params)); 1514 break; 1515 } 1516 case SEND_PENDING_BROADCAST: { 1517 String packages[]; 1518 ArrayList<String> components[]; 1519 int size = 0; 1520 int uids[]; 1521 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1522 synchronized (mPackages) { 1523 if (mPendingBroadcasts == null) { 1524 return; 1525 } 1526 size = mPendingBroadcasts.size(); 1527 if (size <= 0) { 1528 // Nothing to be done. Just return 1529 return; 1530 } 1531 packages = new String[size]; 1532 components = new ArrayList[size]; 1533 uids = new int[size]; 1534 int i = 0; // filling out the above arrays 1535 1536 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1537 int packageUserId = mPendingBroadcasts.userIdAt(n); 1538 Iterator<Map.Entry<String, ArrayList<String>>> it 1539 = mPendingBroadcasts.packagesForUserId(packageUserId) 1540 .entrySet().iterator(); 1541 while (it.hasNext() && i < size) { 1542 Map.Entry<String, ArrayList<String>> ent = it.next(); 1543 packages[i] = ent.getKey(); 1544 components[i] = ent.getValue(); 1545 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1546 uids[i] = (ps != null) 1547 ? UserHandle.getUid(packageUserId, ps.appId) 1548 : -1; 1549 i++; 1550 } 1551 } 1552 size = i; 1553 mPendingBroadcasts.clear(); 1554 } 1555 // Send broadcasts 1556 for (int i = 0; i < size; i++) { 1557 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1558 } 1559 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1560 break; 1561 } 1562 case START_CLEANING_PACKAGE: { 1563 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1564 final String packageName = (String)msg.obj; 1565 final int userId = msg.arg1; 1566 final boolean andCode = msg.arg2 != 0; 1567 synchronized (mPackages) { 1568 if (userId == UserHandle.USER_ALL) { 1569 int[] users = sUserManager.getUserIds(); 1570 for (int user : users) { 1571 mSettings.addPackageToCleanLPw( 1572 new PackageCleanItem(user, packageName, andCode)); 1573 } 1574 } else { 1575 mSettings.addPackageToCleanLPw( 1576 new PackageCleanItem(userId, packageName, andCode)); 1577 } 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 startCleaningPackages(); 1581 } break; 1582 case POST_INSTALL: { 1583 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1584 1585 PostInstallData data = mRunningInstalls.get(msg.arg1); 1586 final boolean didRestore = (msg.arg2 != 0); 1587 mRunningInstalls.delete(msg.arg1); 1588 1589 if (data != null) { 1590 InstallArgs args = data.args; 1591 PackageInstalledInfo parentRes = data.res; 1592 1593 final boolean grantPermissions = (args.installFlags 1594 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1595 final boolean killApp = (args.installFlags 1596 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1597 final String[] grantedPermissions = args.installGrantPermissions; 1598 1599 // Handle the parent package 1600 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1601 grantedPermissions, didRestore, args.installerPackageName, 1602 args.observer); 1603 1604 // Handle the child packages 1605 final int childCount = (parentRes.addedChildPackages != null) 1606 ? parentRes.addedChildPackages.size() : 0; 1607 for (int i = 0; i < childCount; i++) { 1608 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1609 handlePackagePostInstall(childRes, grantPermissions, killApp, 1610 grantedPermissions, false, args.installerPackageName, 1611 args.observer); 1612 } 1613 1614 // Log tracing if needed 1615 if (args.traceMethod != null) { 1616 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1617 args.traceCookie); 1618 } 1619 } else { 1620 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1621 } 1622 1623 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1624 } break; 1625 case UPDATED_MEDIA_STATUS: { 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1627 boolean reportStatus = msg.arg1 == 1; 1628 boolean doGc = msg.arg2 == 1; 1629 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1630 if (doGc) { 1631 // Force a gc to clear up stale containers. 1632 Runtime.getRuntime().gc(); 1633 } 1634 if (msg.obj != null) { 1635 @SuppressWarnings("unchecked") 1636 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1638 // Unload containers 1639 unloadAllContainers(args); 1640 } 1641 if (reportStatus) { 1642 try { 1643 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1644 PackageHelper.getMountService().finishMediaUpdate(); 1645 } catch (RemoteException e) { 1646 Log.e(TAG, "MountService not running?"); 1647 } 1648 } 1649 } break; 1650 case WRITE_SETTINGS: { 1651 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1652 synchronized (mPackages) { 1653 removeMessages(WRITE_SETTINGS); 1654 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1655 mSettings.writeLPr(); 1656 mDirtyUsers.clear(); 1657 } 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1659 } break; 1660 case WRITE_PACKAGE_RESTRICTIONS: { 1661 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1662 synchronized (mPackages) { 1663 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1664 for (int userId : mDirtyUsers) { 1665 mSettings.writePackageRestrictionsLPr(userId); 1666 } 1667 mDirtyUsers.clear(); 1668 } 1669 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1670 } break; 1671 case WRITE_PACKAGE_LIST: { 1672 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1673 synchronized (mPackages) { 1674 removeMessages(WRITE_PACKAGE_LIST); 1675 mSettings.writePackageListLPr(msg.arg1); 1676 } 1677 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1678 } break; 1679 case CHECK_PENDING_VERIFICATION: { 1680 final int verificationId = msg.arg1; 1681 final PackageVerificationState state = mPendingVerification.get(verificationId); 1682 1683 if ((state != null) && !state.timeoutExtended()) { 1684 final InstallArgs args = state.getInstallArgs(); 1685 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1686 1687 Slog.i(TAG, "Verification timed out for " + originUri); 1688 mPendingVerification.remove(verificationId); 1689 1690 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1691 1692 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1693 Slog.i(TAG, "Continuing with installation of " + originUri); 1694 state.setVerifierResponse(Binder.getCallingUid(), 1695 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1696 broadcastPackageVerified(verificationId, originUri, 1697 PackageManager.VERIFICATION_ALLOW, 1698 state.getInstallArgs().getUser()); 1699 try { 1700 ret = args.copyApk(mContainerService, true); 1701 } catch (RemoteException e) { 1702 Slog.e(TAG, "Could not contact the ContainerService"); 1703 } 1704 } else { 1705 broadcastPackageVerified(verificationId, originUri, 1706 PackageManager.VERIFICATION_REJECT, 1707 state.getInstallArgs().getUser()); 1708 } 1709 1710 Trace.asyncTraceEnd( 1711 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1712 1713 processPendingInstall(args, ret); 1714 mHandler.sendEmptyMessage(MCS_UNBIND); 1715 } 1716 break; 1717 } 1718 case PACKAGE_VERIFIED: { 1719 final int verificationId = msg.arg1; 1720 1721 final PackageVerificationState state = mPendingVerification.get(verificationId); 1722 if (state == null) { 1723 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1724 break; 1725 } 1726 1727 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1728 1729 state.setVerifierResponse(response.callerUid, response.code); 1730 1731 if (state.isVerificationComplete()) { 1732 mPendingVerification.remove(verificationId); 1733 1734 final InstallArgs args = state.getInstallArgs(); 1735 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1736 1737 int ret; 1738 if (state.isInstallAllowed()) { 1739 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1740 broadcastPackageVerified(verificationId, originUri, 1741 response.code, state.getInstallArgs().getUser()); 1742 try { 1743 ret = args.copyApk(mContainerService, true); 1744 } catch (RemoteException e) { 1745 Slog.e(TAG, "Could not contact the ContainerService"); 1746 } 1747 } else { 1748 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1749 } 1750 1751 Trace.asyncTraceEnd( 1752 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1753 1754 processPendingInstall(args, ret); 1755 mHandler.sendEmptyMessage(MCS_UNBIND); 1756 } 1757 1758 break; 1759 } 1760 case START_INTENT_FILTER_VERIFICATIONS: { 1761 IFVerificationParams params = (IFVerificationParams) msg.obj; 1762 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1763 params.replacing, params.pkg); 1764 break; 1765 } 1766 case INTENT_FILTER_VERIFIED: { 1767 final int verificationId = msg.arg1; 1768 1769 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1770 verificationId); 1771 if (state == null) { 1772 Slog.w(TAG, "Invalid IntentFilter verification token " 1773 + verificationId + " received"); 1774 break; 1775 } 1776 1777 final int userId = state.getUserId(); 1778 1779 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1780 "Processing IntentFilter verification with token:" 1781 + verificationId + " and userId:" + userId); 1782 1783 final IntentFilterVerificationResponse response = 1784 (IntentFilterVerificationResponse) msg.obj; 1785 1786 state.setVerifierResponse(response.callerUid, response.code); 1787 1788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1789 "IntentFilter verification with token:" + verificationId 1790 + " and userId:" + userId 1791 + " is settings verifier response with response code:" 1792 + response.code); 1793 1794 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1795 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1796 + response.getFailedDomainsString()); 1797 } 1798 1799 if (state.isVerificationComplete()) { 1800 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1801 } else { 1802 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1803 "IntentFilter verification with token:" + verificationId 1804 + " was not said to be complete"); 1805 } 1806 1807 break; 1808 } 1809 } 1810 } 1811 } 1812 1813 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1814 boolean killApp, String[] grantedPermissions, 1815 boolean launchedForRestore, String installerPackage, 1816 IPackageInstallObserver2 installObserver) { 1817 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1818 // Send the removed broadcasts 1819 if (res.removedInfo != null) { 1820 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1821 } 1822 1823 // Now that we successfully installed the package, grant runtime 1824 // permissions if requested before broadcasting the install. 1825 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1826 >= Build.VERSION_CODES.M) { 1827 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1828 } 1829 1830 final boolean update = res.removedInfo != null 1831 && res.removedInfo.removedPackage != null; 1832 1833 // If this is the first time we have child packages for a disabled privileged 1834 // app that had no children, we grant requested runtime permissions to the new 1835 // children if the parent on the system image had them already granted. 1836 if (res.pkg.parentPackage != null) { 1837 synchronized (mPackages) { 1838 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1839 } 1840 } 1841 1842 synchronized (mPackages) { 1843 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1844 } 1845 1846 final String packageName = res.pkg.applicationInfo.packageName; 1847 Bundle extras = new Bundle(1); 1848 extras.putInt(Intent.EXTRA_UID, res.uid); 1849 1850 // Determine the set of users who are adding this package for 1851 // the first time vs. those who are seeing an update. 1852 int[] firstUsers = EMPTY_INT_ARRAY; 1853 int[] updateUsers = EMPTY_INT_ARRAY; 1854 if (res.origUsers == null || res.origUsers.length == 0) { 1855 firstUsers = res.newUsers; 1856 } else { 1857 for (int newUser : res.newUsers) { 1858 boolean isNew = true; 1859 for (int origUser : res.origUsers) { 1860 if (origUser == newUser) { 1861 isNew = false; 1862 break; 1863 } 1864 } 1865 if (isNew) { 1866 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1867 } else { 1868 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1869 } 1870 } 1871 } 1872 1873 // Send installed broadcasts if the install/update is not ephemeral 1874 if (!isEphemeral(res.pkg)) { 1875 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1876 1877 // Send added for users that see the package for the first time 1878 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1879 extras, 0 /*flags*/, null /*targetPackage*/, 1880 null /*finishedReceiver*/, firstUsers); 1881 1882 // Send added for users that don't see the package for the first time 1883 if (update) { 1884 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1885 } 1886 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1887 extras, 0 /*flags*/, null /*targetPackage*/, 1888 null /*finishedReceiver*/, updateUsers); 1889 1890 // Send replaced for users that don't see the package for the first time 1891 if (update) { 1892 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1893 packageName, extras, 0 /*flags*/, 1894 null /*targetPackage*/, null /*finishedReceiver*/, 1895 updateUsers); 1896 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1897 null /*package*/, null /*extras*/, 0 /*flags*/, 1898 packageName /*targetPackage*/, 1899 null /*finishedReceiver*/, updateUsers); 1900 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1901 // First-install and we did a restore, so we're responsible for the 1902 // first-launch broadcast. 1903 if (DEBUG_BACKUP) { 1904 Slog.i(TAG, "Post-restore of " + packageName 1905 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1906 } 1907 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1908 } 1909 1910 // Send broadcast package appeared if forward locked/external for all users 1911 // treat asec-hosted packages like removable media on upgrade 1912 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1913 if (DEBUG_INSTALL) { 1914 Slog.i(TAG, "upgrading pkg " + res.pkg 1915 + " is ASEC-hosted -> AVAILABLE"); 1916 } 1917 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1918 ArrayList<String> pkgList = new ArrayList<>(1); 1919 pkgList.add(packageName); 1920 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1921 } 1922 } 1923 1924 // Work that needs to happen on first install within each user 1925 if (firstUsers != null && firstUsers.length > 0) { 1926 synchronized (mPackages) { 1927 for (int userId : firstUsers) { 1928 // If this app is a browser and it's newly-installed for some 1929 // users, clear any default-browser state in those users. The 1930 // app's nature doesn't depend on the user, so we can just check 1931 // its browser nature in any user and generalize. 1932 if (packageIsBrowser(packageName, userId)) { 1933 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1934 } 1935 1936 // We may also need to apply pending (restored) runtime 1937 // permission grants within these users. 1938 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1939 } 1940 } 1941 } 1942 1943 // Log current value of "unknown sources" setting 1944 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1945 getUnknownSourcesSettings()); 1946 1947 // Force a gc to clear up things 1948 Runtime.getRuntime().gc(); 1949 1950 // Remove the replaced package's older resources safely now 1951 // We delete after a gc for applications on sdcard. 1952 if (res.removedInfo != null && res.removedInfo.args != null) { 1953 synchronized (mInstallLock) { 1954 res.removedInfo.args.doPostDeleteLI(true); 1955 } 1956 } 1957 } 1958 1959 // If someone is watching installs - notify them 1960 if (installObserver != null) { 1961 try { 1962 Bundle extras = extrasForInstallResult(res); 1963 installObserver.onPackageInstalled(res.name, res.returnCode, 1964 res.returnMsg, extras); 1965 } catch (RemoteException e) { 1966 Slog.i(TAG, "Observer no longer exists."); 1967 } 1968 } 1969 } 1970 1971 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1972 PackageParser.Package pkg) { 1973 if (pkg.parentPackage == null) { 1974 return; 1975 } 1976 if (pkg.requestedPermissions == null) { 1977 return; 1978 } 1979 final PackageSetting disabledSysParentPs = mSettings 1980 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1981 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1982 || !disabledSysParentPs.isPrivileged() 1983 || (disabledSysParentPs.childPackageNames != null 1984 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1985 return; 1986 } 1987 final int[] allUserIds = sUserManager.getUserIds(); 1988 final int permCount = pkg.requestedPermissions.size(); 1989 for (int i = 0; i < permCount; i++) { 1990 String permission = pkg.requestedPermissions.get(i); 1991 BasePermission bp = mSettings.mPermissions.get(permission); 1992 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1993 continue; 1994 } 1995 for (int userId : allUserIds) { 1996 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1997 permission, userId)) { 1998 grantRuntimePermission(pkg.packageName, permission, userId); 1999 } 2000 } 2001 } 2002 } 2003 2004 private StorageEventListener mStorageListener = new StorageEventListener() { 2005 @Override 2006 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 2007 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 2008 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2009 final String volumeUuid = vol.getFsUuid(); 2010 2011 // Clean up any users or apps that were removed or recreated 2012 // while this volume was missing 2013 reconcileUsers(volumeUuid); 2014 reconcileApps(volumeUuid); 2015 2016 // Clean up any install sessions that expired or were 2017 // cancelled while this volume was missing 2018 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2019 2020 loadPrivatePackages(vol); 2021 2022 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2023 unloadPrivatePackages(vol); 2024 } 2025 } 2026 2027 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2028 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2029 updateExternalMediaStatus(true, false); 2030 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2031 updateExternalMediaStatus(false, false); 2032 } 2033 } 2034 } 2035 2036 @Override 2037 public void onVolumeForgotten(String fsUuid) { 2038 if (TextUtils.isEmpty(fsUuid)) { 2039 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2040 return; 2041 } 2042 2043 // Remove any apps installed on the forgotten volume 2044 synchronized (mPackages) { 2045 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2046 for (PackageSetting ps : packages) { 2047 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2048 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2049 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2050 } 2051 2052 mSettings.onVolumeForgotten(fsUuid); 2053 mSettings.writeLPr(); 2054 } 2055 } 2056 }; 2057 2058 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2059 String[] grantedPermissions) { 2060 for (int userId : userIds) { 2061 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2062 } 2063 2064 // We could have touched GID membership, so flush out packages.list 2065 synchronized (mPackages) { 2066 mSettings.writePackageListLPr(); 2067 } 2068 } 2069 2070 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2071 String[] grantedPermissions) { 2072 SettingBase sb = (SettingBase) pkg.mExtras; 2073 if (sb == null) { 2074 return; 2075 } 2076 2077 PermissionsState permissionsState = sb.getPermissionsState(); 2078 2079 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2080 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2081 2082 for (String permission : pkg.requestedPermissions) { 2083 final BasePermission bp; 2084 synchronized (mPackages) { 2085 bp = mSettings.mPermissions.get(permission); 2086 } 2087 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2088 && (grantedPermissions == null 2089 || ArrayUtils.contains(grantedPermissions, permission))) { 2090 final int flags = permissionsState.getPermissionFlags(permission, userId); 2091 // Installer cannot change immutable permissions. 2092 if ((flags & immutableFlags) == 0) { 2093 grantRuntimePermission(pkg.packageName, permission, userId); 2094 } 2095 } 2096 } 2097 } 2098 2099 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2100 Bundle extras = null; 2101 switch (res.returnCode) { 2102 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2103 extras = new Bundle(); 2104 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2105 res.origPermission); 2106 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2107 res.origPackage); 2108 break; 2109 } 2110 case PackageManager.INSTALL_SUCCEEDED: { 2111 extras = new Bundle(); 2112 extras.putBoolean(Intent.EXTRA_REPLACING, 2113 res.removedInfo != null && res.removedInfo.removedPackage != null); 2114 break; 2115 } 2116 } 2117 return extras; 2118 } 2119 2120 void scheduleWriteSettingsLocked() { 2121 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2122 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2123 } 2124 } 2125 2126 void scheduleWritePackageListLocked(int userId) { 2127 if (!mHandler.hasMessages(WRITE_PACKAGE_LIST)) { 2128 Message msg = mHandler.obtainMessage(WRITE_PACKAGE_LIST); 2129 msg.arg1 = userId; 2130 mHandler.sendMessageDelayed(msg, WRITE_SETTINGS_DELAY); 2131 } 2132 } 2133 2134 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2135 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2136 scheduleWritePackageRestrictionsLocked(userId); 2137 } 2138 2139 void scheduleWritePackageRestrictionsLocked(int userId) { 2140 final int[] userIds = (userId == UserHandle.USER_ALL) 2141 ? sUserManager.getUserIds() : new int[]{userId}; 2142 for (int nextUserId : userIds) { 2143 if (!sUserManager.exists(nextUserId)) return; 2144 mDirtyUsers.add(nextUserId); 2145 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2146 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2147 } 2148 } 2149 } 2150 2151 public static PackageManagerService main(Context context, Installer installer, 2152 boolean factoryTest, boolean onlyCore) { 2153 // Self-check for initial settings. 2154 PackageManagerServiceCompilerMapping.checkProperties(); 2155 2156 PackageManagerService m = new PackageManagerService(context, installer, 2157 factoryTest, onlyCore); 2158 m.enableSystemUserPackages(); 2159 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2160 // disabled after already being started. 2161 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2162 UserHandle.USER_SYSTEM); 2163 ServiceManager.addService("package", m); 2164 return m; 2165 } 2166 2167 private void enableSystemUserPackages() { 2168 if (!UserManager.isSplitSystemUser()) { 2169 return; 2170 } 2171 // For system user, enable apps based on the following conditions: 2172 // - app is whitelisted or belong to one of these groups: 2173 // -- system app which has no launcher icons 2174 // -- system app which has INTERACT_ACROSS_USERS permission 2175 // -- system IME app 2176 // - app is not in the blacklist 2177 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2178 Set<String> enableApps = new ArraySet<>(); 2179 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2180 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2181 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2182 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2183 enableApps.addAll(wlApps); 2184 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2185 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2186 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2187 enableApps.removeAll(blApps); 2188 Log.i(TAG, "Applications installed for system user: " + enableApps); 2189 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2190 UserHandle.SYSTEM); 2191 final int allAppsSize = allAps.size(); 2192 synchronized (mPackages) { 2193 for (int i = 0; i < allAppsSize; i++) { 2194 String pName = allAps.get(i); 2195 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2196 // Should not happen, but we shouldn't be failing if it does 2197 if (pkgSetting == null) { 2198 continue; 2199 } 2200 boolean install = enableApps.contains(pName); 2201 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2202 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2203 + " for system user"); 2204 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2205 } 2206 } 2207 } 2208 } 2209 2210 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2211 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2212 Context.DISPLAY_SERVICE); 2213 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2214 } 2215 2216 public PackageManagerService(Context context, Installer installer, 2217 boolean factoryTest, boolean onlyCore) { 2218 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2219 SystemClock.uptimeMillis()); 2220 2221 if (mSdkVersion <= 0) { 2222 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2223 } 2224 2225 mContext = context; 2226 mFactoryTest = factoryTest; 2227 mOnlyCore = onlyCore; 2228 mMetrics = new DisplayMetrics(); 2229 mSettings = new Settings(mPackages); 2230 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2231 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2232 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2233 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2234 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2235 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2236 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2237 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2238 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2239 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2240 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2241 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2242 2243 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2244 if (separateProcesses != null && separateProcesses.length() > 0) { 2245 if ("*".equals(separateProcesses)) { 2246 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2247 mSeparateProcesses = null; 2248 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2249 } else { 2250 mDefParseFlags = 0; 2251 mSeparateProcesses = separateProcesses.split(","); 2252 Slog.w(TAG, "Running with debug.separate_processes: " 2253 + separateProcesses); 2254 } 2255 } else { 2256 mDefParseFlags = 0; 2257 mSeparateProcesses = null; 2258 } 2259 2260 mInstaller = installer; 2261 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2262 "*dexopt*"); 2263 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2264 2265 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2266 FgThread.get().getLooper()); 2267 2268 getDefaultDisplayMetrics(context, mMetrics); 2269 2270 SystemConfig systemConfig = SystemConfig.getInstance(); 2271 mGlobalGids = systemConfig.getGlobalGids(); 2272 mSystemPermissions = systemConfig.getSystemPermissions(); 2273 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2274 2275 synchronized (mInstallLock) { 2276 // writer 2277 synchronized (mPackages) { 2278 mHandlerThread = new ServiceThread(TAG, 2279 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2280 mHandlerThread.start(); 2281 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2282 mProcessLoggingHandler = new ProcessLoggingHandler(); 2283 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2284 2285 File dataDir = Environment.getDataDirectory(); 2286 mAppInstallDir = new File(dataDir, "app"); 2287 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2288 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2289 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2290 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2291 2292 sUserManager = new UserManagerService(context, this, mPackages); 2293 2294 // Propagate permission configuration in to package manager. 2295 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2296 = systemConfig.getPermissions(); 2297 for (int i=0; i<permConfig.size(); i++) { 2298 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2299 BasePermission bp = mSettings.mPermissions.get(perm.name); 2300 if (bp == null) { 2301 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2302 mSettings.mPermissions.put(perm.name, bp); 2303 } 2304 if (perm.gids != null) { 2305 bp.setGids(perm.gids, perm.perUser); 2306 } 2307 } 2308 2309 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2310 for (int i=0; i<libConfig.size(); i++) { 2311 mSharedLibraries.put(libConfig.keyAt(i), 2312 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2313 } 2314 2315 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2316 2317 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2318 2319 String customResolverActivity = Resources.getSystem().getString( 2320 R.string.config_customResolverActivity); 2321 if (TextUtils.isEmpty(customResolverActivity)) { 2322 customResolverActivity = null; 2323 } else { 2324 mCustomResolverComponentName = ComponentName.unflattenFromString( 2325 customResolverActivity); 2326 } 2327 2328 long startTime = SystemClock.uptimeMillis(); 2329 2330 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2331 startTime); 2332 2333 // Set flag to monitor and not change apk file paths when 2334 // scanning install directories. 2335 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2336 2337 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2338 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2339 2340 if (bootClassPath == null) { 2341 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2342 } 2343 2344 if (systemServerClassPath == null) { 2345 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2346 } 2347 2348 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2349 final String[] dexCodeInstructionSets = 2350 getDexCodeInstructionSets( 2351 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2352 2353 /** 2354 * Ensure all external libraries have had dexopt run on them. 2355 */ 2356 if (mSharedLibraries.size() > 0) { 2357 // NOTE: For now, we're compiling these system "shared libraries" 2358 // (and framework jars) into all available architectures. It's possible 2359 // to compile them only when we come across an app that uses them (there's 2360 // already logic for that in scanPackageLI) but that adds some complexity. 2361 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2362 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2363 final String lib = libEntry.path; 2364 if (lib == null) { 2365 continue; 2366 } 2367 2368 try { 2369 // Shared libraries do not have profiles so we perform a full 2370 // AOT compilation (if needed). 2371 int dexoptNeeded = DexFile.getDexOptNeeded( 2372 lib, dexCodeInstructionSet, 2373 getCompilerFilterForReason(REASON_SHARED_APK), 2374 false /* newProfile */); 2375 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2376 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2377 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2378 getCompilerFilterForReason(REASON_SHARED_APK), 2379 StorageManager.UUID_PRIVATE_INTERNAL, 2380 SKIP_SHARED_LIBRARY_CHECK); 2381 } 2382 } catch (FileNotFoundException e) { 2383 Slog.w(TAG, "Library not found: " + lib); 2384 } catch (IOException | InstallerException e) { 2385 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2386 + e.getMessage()); 2387 } 2388 } 2389 } 2390 } 2391 2392 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2393 2394 final VersionInfo ver = mSettings.getInternalVersion(); 2395 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2396 2397 // when upgrading from pre-M, promote system app permissions from install to runtime 2398 mPromoteSystemApps = 2399 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2400 2401 // When upgrading from pre-N, we need to handle package extraction like first boot, 2402 // as there is no profiling data available. 2403 mIsPreNUpgrade = mIsUpgrade && ver.sdkVersion < Build.VERSION_CODES.N; 2404 2405 // save off the names of pre-existing system packages prior to scanning; we don't 2406 // want to automatically grant runtime permissions for new system apps 2407 if (mPromoteSystemApps) { 2408 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2409 while (pkgSettingIter.hasNext()) { 2410 PackageSetting ps = pkgSettingIter.next(); 2411 if (isSystemApp(ps)) { 2412 mExistingSystemPackages.add(ps.name); 2413 } 2414 } 2415 } 2416 2417 // Collect vendor overlay packages. 2418 // (Do this before scanning any apps.) 2419 // For security and version matching reason, only consider 2420 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2421 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2422 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2423 | PackageParser.PARSE_IS_SYSTEM 2424 | PackageParser.PARSE_IS_SYSTEM_DIR 2425 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2426 2427 // Find base frameworks (resource packages without code). 2428 scanDirTracedLI(frameworkDir, mDefParseFlags 2429 | PackageParser.PARSE_IS_SYSTEM 2430 | PackageParser.PARSE_IS_SYSTEM_DIR 2431 | PackageParser.PARSE_IS_PRIVILEGED, 2432 scanFlags | SCAN_NO_DEX, 0); 2433 2434 // Collected privileged system packages. 2435 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2436 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR 2439 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2440 2441 // Collect ordinary system packages. 2442 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2443 scanDirTracedLI(systemAppDir, mDefParseFlags 2444 | PackageParser.PARSE_IS_SYSTEM 2445 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2446 2447 // Collect all vendor packages. 2448 File vendorAppDir = new File("/vendor/app"); 2449 try { 2450 vendorAppDir = vendorAppDir.getCanonicalFile(); 2451 } catch (IOException e) { 2452 // failed to look up canonical path, continue with original one 2453 } 2454 scanDirTracedLI(vendorAppDir, mDefParseFlags 2455 | PackageParser.PARSE_IS_SYSTEM 2456 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2457 2458 // Collect all OEM packages. 2459 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2460 scanDirTracedLI(oemAppDir, mDefParseFlags 2461 | PackageParser.PARSE_IS_SYSTEM 2462 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2463 2464 // Prune any system packages that no longer exist. 2465 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2466 if (!mOnlyCore) { 2467 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2468 while (psit.hasNext()) { 2469 PackageSetting ps = psit.next(); 2470 2471 /* 2472 * If this is not a system app, it can't be a 2473 * disable system app. 2474 */ 2475 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2476 continue; 2477 } 2478 2479 /* 2480 * If the package is scanned, it's not erased. 2481 */ 2482 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2483 if (scannedPkg != null) { 2484 /* 2485 * If the system app is both scanned and in the 2486 * disabled packages list, then it must have been 2487 * added via OTA. Remove it from the currently 2488 * scanned package so the previously user-installed 2489 * application can be scanned. 2490 */ 2491 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2492 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2493 + ps.name + "; removing system app. Last known codePath=" 2494 + ps.codePathString + ", installStatus=" + ps.installStatus 2495 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2496 + scannedPkg.mVersionCode); 2497 removePackageLI(scannedPkg, true); 2498 mExpectingBetter.put(ps.name, ps.codePath); 2499 } 2500 2501 continue; 2502 } 2503 2504 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2505 psit.remove(); 2506 logCriticalInfo(Log.WARN, "System package " + ps.name 2507 + " no longer exists; it's data will be wiped"); 2508 // Actual deletion of code and data will be handled by later 2509 // reconciliation step 2510 } else { 2511 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2512 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2513 possiblyDeletedUpdatedSystemApps.add(ps.name); 2514 } 2515 } 2516 } 2517 } 2518 2519 //look for any incomplete package installations 2520 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2521 for (int i = 0; i < deletePkgsList.size(); i++) { 2522 // Actual deletion of code and data will be handled by later 2523 // reconciliation step 2524 final String packageName = deletePkgsList.get(i).name; 2525 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2526 synchronized (mPackages) { 2527 mSettings.removePackageLPw(packageName); 2528 } 2529 } 2530 2531 //delete tmp files 2532 deleteTempPackageFiles(); 2533 2534 // Remove any shared userIDs that have no associated packages 2535 mSettings.pruneSharedUsersLPw(); 2536 2537 if (!mOnlyCore) { 2538 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2539 SystemClock.uptimeMillis()); 2540 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2541 2542 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2543 | PackageParser.PARSE_FORWARD_LOCK, 2544 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2545 2546 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2547 | PackageParser.PARSE_IS_EPHEMERAL, 2548 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2549 2550 /** 2551 * Remove disable package settings for any updated system 2552 * apps that were removed via an OTA. If they're not a 2553 * previously-updated app, remove them completely. 2554 * Otherwise, just revoke their system-level permissions. 2555 */ 2556 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2557 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2558 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2559 2560 String msg; 2561 if (deletedPkg == null) { 2562 msg = "Updated system package " + deletedAppName 2563 + " no longer exists; it's data will be wiped"; 2564 // Actual deletion of code and data will be handled by later 2565 // reconciliation step 2566 } else { 2567 msg = "Updated system app + " + deletedAppName 2568 + " no longer present; removing system privileges for " 2569 + deletedAppName; 2570 2571 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2572 2573 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2574 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2575 } 2576 logCriticalInfo(Log.WARN, msg); 2577 } 2578 2579 /** 2580 * Make sure all system apps that we expected to appear on 2581 * the userdata partition actually showed up. If they never 2582 * appeared, crawl back and revive the system version. 2583 */ 2584 for (int i = 0; i < mExpectingBetter.size(); i++) { 2585 final String packageName = mExpectingBetter.keyAt(i); 2586 if (!mPackages.containsKey(packageName)) { 2587 final File scanFile = mExpectingBetter.valueAt(i); 2588 2589 logCriticalInfo(Log.WARN, "Expected better " + packageName 2590 + " but never showed up; reverting to system"); 2591 2592 int reparseFlags = mDefParseFlags; 2593 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2594 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2595 | PackageParser.PARSE_IS_SYSTEM_DIR 2596 | PackageParser.PARSE_IS_PRIVILEGED; 2597 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2598 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2599 | PackageParser.PARSE_IS_SYSTEM_DIR; 2600 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2601 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2602 | PackageParser.PARSE_IS_SYSTEM_DIR; 2603 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2604 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2605 | PackageParser.PARSE_IS_SYSTEM_DIR; 2606 } else { 2607 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2608 continue; 2609 } 2610 2611 mSettings.enableSystemPackageLPw(packageName); 2612 2613 try { 2614 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2615 } catch (PackageManagerException e) { 2616 Slog.e(TAG, "Failed to parse original system package: " 2617 + e.getMessage()); 2618 } 2619 } 2620 } 2621 } 2622 mExpectingBetter.clear(); 2623 2624 // Resolve protected action filters. Only the setup wizard is allowed to 2625 // have a high priority filter for these actions. 2626 mSetupWizardPackage = getSetupWizardPackageName(); 2627 if (mProtectedFilters.size() > 0) { 2628 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2629 Slog.i(TAG, "No setup wizard;" 2630 + " All protected intents capped to priority 0"); 2631 } 2632 for (ActivityIntentInfo filter : mProtectedFilters) { 2633 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2634 if (DEBUG_FILTERS) { 2635 Slog.i(TAG, "Found setup wizard;" 2636 + " allow priority " + filter.getPriority() + ";" 2637 + " package: " + filter.activity.info.packageName 2638 + " activity: " + filter.activity.className 2639 + " priority: " + filter.getPriority()); 2640 } 2641 // skip setup wizard; allow it to keep the high priority filter 2642 continue; 2643 } 2644 Slog.w(TAG, "Protected action; cap priority to 0;" 2645 + " package: " + filter.activity.info.packageName 2646 + " activity: " + filter.activity.className 2647 + " origPrio: " + filter.getPriority()); 2648 filter.setPriority(0); 2649 } 2650 } 2651 mDeferProtectedFilters = false; 2652 mProtectedFilters.clear(); 2653 2654 // Now that we know all of the shared libraries, update all clients to have 2655 // the correct library paths. 2656 updateAllSharedLibrariesLPw(); 2657 2658 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2659 // NOTE: We ignore potential failures here during a system scan (like 2660 // the rest of the commands above) because there's precious little we 2661 // can do about it. A settings error is reported, though. 2662 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2663 false /* boot complete */); 2664 } 2665 2666 // Now that we know all the packages we are keeping, 2667 // read and update their last usage times. 2668 mPackageUsage.readLP(); 2669 2670 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2671 SystemClock.uptimeMillis()); 2672 Slog.i(TAG, "Time to scan packages: " 2673 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2674 + " seconds"); 2675 2676 // If the platform SDK has changed since the last time we booted, 2677 // we need to re-grant app permission to catch any new ones that 2678 // appear. This is really a hack, and means that apps can in some 2679 // cases get permissions that the user didn't initially explicitly 2680 // allow... it would be nice to have some better way to handle 2681 // this situation. 2682 int updateFlags = UPDATE_PERMISSIONS_ALL; 2683 if (ver.sdkVersion != mSdkVersion) { 2684 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2685 + mSdkVersion + "; regranting permissions for internal storage"); 2686 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2687 } 2688 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2689 ver.sdkVersion = mSdkVersion; 2690 2691 // If this is the first boot or an update from pre-M, and it is a normal 2692 // boot, then we need to initialize the default preferred apps across 2693 // all defined users. 2694 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2695 for (UserInfo user : sUserManager.getUsers(true)) { 2696 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2697 applyFactoryDefaultBrowserLPw(user.id); 2698 primeDomainVerificationsLPw(user.id); 2699 } 2700 } 2701 2702 // Prepare storage for system user really early during boot, 2703 // since core system apps like SettingsProvider and SystemUI 2704 // can't wait for user to start 2705 final int storageFlags; 2706 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2707 storageFlags = StorageManager.FLAG_STORAGE_DE; 2708 } else { 2709 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2710 } 2711 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2712 storageFlags); 2713 2714 // If this is first boot after an OTA, and a normal boot, then 2715 // we need to clear code cache directories. 2716 // Note that we do *not* clear the application profiles. These remain valid 2717 // across OTAs and are used to drive profile verification (post OTA) and 2718 // profile compilation (without waiting to collect a fresh set of profiles). 2719 if (mIsUpgrade && !onlyCore) { 2720 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2721 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2722 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2723 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2724 // No apps are running this early, so no need to freeze 2725 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2726 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2727 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2728 } 2729 } 2730 ver.fingerprint = Build.FINGERPRINT; 2731 } 2732 2733 checkDefaultBrowser(); 2734 2735 // clear only after permissions and other defaults have been updated 2736 mExistingSystemPackages.clear(); 2737 mPromoteSystemApps = false; 2738 2739 // All the changes are done during package scanning. 2740 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2741 2742 // can downgrade to reader 2743 mSettings.writeLPr(); 2744 2745 // Perform dexopt on all apps that mark themselves as coreApps. We do this pretty 2746 // early on (before the package manager declares itself as early) because other 2747 // components in the system server might ask for package contexts for these apps. 2748 // 2749 // Note that "onlyCore" in this context means the system is encrypted or encrypting 2750 // (i.e, that the data partition is unavailable). 2751 if ((isFirstBoot() || isUpgrade() || VMRuntime.didPruneDalvikCache()) && !onlyCore) { 2752 long start = System.nanoTime(); 2753 List<PackageParser.Package> coreApps = new ArrayList<>(); 2754 for (PackageParser.Package pkg : mPackages.values()) { 2755 if (pkg.coreApp) { 2756 coreApps.add(pkg); 2757 } 2758 } 2759 2760 int[] stats = performDexOpt(coreApps, false, 2761 getCompilerFilterForReason(REASON_CORE_APP)); 2762 2763 final int elapsedTimeSeconds = 2764 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - start); 2765 MetricsLogger.histogram(mContext, "opt_coreapps_time_s", elapsedTimeSeconds); 2766 2767 if (DEBUG_DEXOPT) { 2768 Slog.i(TAG, "Dex-opt core apps took : " + elapsedTimeSeconds + " seconds (" + 2769 stats[0] + ", " + stats[1] + ", " + stats[2] + ")"); 2770 } 2771 2772 2773 // TODO: Should we log these stats to tron too ? 2774 // MetricsLogger.histogram(mContext, "opt_coreapps_num_dexopted", stats[0]); 2775 // MetricsLogger.histogram(mContext, "opt_coreapps_num_skipped", stats[1]); 2776 // MetricsLogger.histogram(mContext, "opt_coreapps_num_failed", stats[2]); 2777 // MetricsLogger.histogram(mContext, "opt_coreapps_num_total", coreApps.size()); 2778 } 2779 2780 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2781 SystemClock.uptimeMillis()); 2782 2783 if (!mOnlyCore) { 2784 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2785 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2786 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2787 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2788 mIntentFilterVerifierComponent); 2789 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2790 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2791 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2792 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2793 } else { 2794 mRequiredVerifierPackage = null; 2795 mRequiredInstallerPackage = null; 2796 mIntentFilterVerifierComponent = null; 2797 mIntentFilterVerifier = null; 2798 mServicesSystemSharedLibraryPackageName = null; 2799 mSharedSystemSharedLibraryPackageName = null; 2800 } 2801 2802 mInstallerService = new PackageInstallerService(context, this); 2803 2804 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2805 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2806 // both the installer and resolver must be present to enable ephemeral 2807 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2808 if (DEBUG_EPHEMERAL) { 2809 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2810 + " installer:" + ephemeralInstallerComponent); 2811 } 2812 mEphemeralResolverComponent = ephemeralResolverComponent; 2813 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2814 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2815 mEphemeralResolverConnection = 2816 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2817 } else { 2818 if (DEBUG_EPHEMERAL) { 2819 final String missingComponent = 2820 (ephemeralResolverComponent == null) 2821 ? (ephemeralInstallerComponent == null) 2822 ? "resolver and installer" 2823 : "resolver" 2824 : "installer"; 2825 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2826 } 2827 mEphemeralResolverComponent = null; 2828 mEphemeralInstallerComponent = null; 2829 mEphemeralResolverConnection = null; 2830 } 2831 2832 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2833 } // synchronized (mPackages) 2834 } // synchronized (mInstallLock) 2835 2836 // Now after opening every single application zip, make sure they 2837 // are all flushed. Not really needed, but keeps things nice and 2838 // tidy. 2839 Runtime.getRuntime().gc(); 2840 2841 // The initial scanning above does many calls into installd while 2842 // holding the mPackages lock, but we're mostly interested in yelling 2843 // once we have a booted system. 2844 mInstaller.setWarnIfHeld(mPackages); 2845 2846 // Expose private service for system components to use. 2847 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2848 } 2849 2850 @Override 2851 public boolean isFirstBoot() { 2852 return !mRestoredSettings; 2853 } 2854 2855 @Override 2856 public boolean isOnlyCoreApps() { 2857 return mOnlyCore; 2858 } 2859 2860 @Override 2861 public boolean isUpgrade() { 2862 return mIsUpgrade; 2863 } 2864 2865 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2866 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2867 2868 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2869 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2870 UserHandle.USER_SYSTEM); 2871 if (matches.size() == 1) { 2872 return matches.get(0).getComponentInfo().packageName; 2873 } else { 2874 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2875 return null; 2876 } 2877 } 2878 2879 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2880 synchronized (mPackages) { 2881 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2882 if (libraryEntry == null) { 2883 throw new IllegalStateException("Missing required shared library:" + libraryName); 2884 } 2885 return libraryEntry.apk; 2886 } 2887 } 2888 2889 private @NonNull String getRequiredInstallerLPr() { 2890 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2891 intent.addCategory(Intent.CATEGORY_DEFAULT); 2892 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2893 2894 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2895 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2896 UserHandle.USER_SYSTEM); 2897 if (matches.size() == 1) { 2898 ResolveInfo resolveInfo = matches.get(0); 2899 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2900 throw new RuntimeException("The installer must be a privileged app"); 2901 } 2902 return matches.get(0).getComponentInfo().packageName; 2903 } else { 2904 throw new RuntimeException("There must be exactly one installer; found " + matches); 2905 } 2906 } 2907 2908 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2909 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2910 2911 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2912 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2913 UserHandle.USER_SYSTEM); 2914 ResolveInfo best = null; 2915 final int N = matches.size(); 2916 for (int i = 0; i < N; i++) { 2917 final ResolveInfo cur = matches.get(i); 2918 final String packageName = cur.getComponentInfo().packageName; 2919 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2920 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2921 continue; 2922 } 2923 2924 if (best == null || cur.priority > best.priority) { 2925 best = cur; 2926 } 2927 } 2928 2929 if (best != null) { 2930 return best.getComponentInfo().getComponentName(); 2931 } else { 2932 throw new RuntimeException("There must be at least one intent filter verifier"); 2933 } 2934 } 2935 2936 private @Nullable ComponentName getEphemeralResolverLPr() { 2937 final String[] packageArray = 2938 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2939 if (packageArray.length == 0 && !Build.IS_DEBUGGABLE) { 2940 if (DEBUG_EPHEMERAL) { 2941 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2942 } 2943 return null; 2944 } 2945 2946 final int resolveFlags = 2947 MATCH_DIRECT_BOOT_AWARE 2948 | MATCH_DIRECT_BOOT_UNAWARE 2949 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 2950 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2951 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2952 resolveFlags, UserHandle.USER_SYSTEM); 2953 2954 final int N = resolvers.size(); 2955 if (N == 0) { 2956 if (DEBUG_EPHEMERAL) { 2957 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2958 } 2959 return null; 2960 } 2961 2962 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2963 for (int i = 0; i < N; i++) { 2964 final ResolveInfo info = resolvers.get(i); 2965 2966 if (info.serviceInfo == null) { 2967 continue; 2968 } 2969 2970 final String packageName = info.serviceInfo.packageName; 2971 if (!possiblePackages.contains(packageName) && !Build.IS_DEBUGGABLE) { 2972 if (DEBUG_EPHEMERAL) { 2973 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2974 + " pkg: " + packageName + ", info:" + info); 2975 } 2976 continue; 2977 } 2978 2979 if (DEBUG_EPHEMERAL) { 2980 Slog.v(TAG, "Ephemeral resolver found;" 2981 + " pkg: " + packageName + ", info:" + info); 2982 } 2983 return new ComponentName(packageName, info.serviceInfo.name); 2984 } 2985 if (DEBUG_EPHEMERAL) { 2986 Slog.v(TAG, "Ephemeral resolver NOT found"); 2987 } 2988 return null; 2989 } 2990 2991 private @Nullable ComponentName getEphemeralInstallerLPr() { 2992 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2993 intent.addCategory(Intent.CATEGORY_DEFAULT); 2994 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2995 2996 final int resolveFlags = 2997 MATCH_DIRECT_BOOT_AWARE 2998 | MATCH_DIRECT_BOOT_UNAWARE 2999 | (!Build.IS_DEBUGGABLE ? MATCH_SYSTEM_ONLY : 0); 3000 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 3001 resolveFlags, UserHandle.USER_SYSTEM); 3002 if (matches.size() == 0) { 3003 return null; 3004 } else if (matches.size() == 1) { 3005 return matches.get(0).getComponentInfo().getComponentName(); 3006 } else { 3007 throw new RuntimeException( 3008 "There must be at most one ephemeral installer; found " + matches); 3009 } 3010 } 3011 3012 private void primeDomainVerificationsLPw(int userId) { 3013 if (DEBUG_DOMAIN_VERIFICATION) { 3014 Slog.d(TAG, "Priming domain verifications in user " + userId); 3015 } 3016 3017 SystemConfig systemConfig = SystemConfig.getInstance(); 3018 ArraySet<String> packages = systemConfig.getLinkedApps(); 3019 ArraySet<String> domains = new ArraySet<String>(); 3020 3021 for (String packageName : packages) { 3022 PackageParser.Package pkg = mPackages.get(packageName); 3023 if (pkg != null) { 3024 if (!pkg.isSystemApp()) { 3025 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 3026 continue; 3027 } 3028 3029 domains.clear(); 3030 for (PackageParser.Activity a : pkg.activities) { 3031 for (ActivityIntentInfo filter : a.intents) { 3032 if (hasValidDomains(filter)) { 3033 domains.addAll(filter.getHostsList()); 3034 } 3035 } 3036 } 3037 3038 if (domains.size() > 0) { 3039 if (DEBUG_DOMAIN_VERIFICATION) { 3040 Slog.v(TAG, " + " + packageName); 3041 } 3042 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 3043 // state w.r.t. the formal app-linkage "no verification attempted" state; 3044 // and then 'always' in the per-user state actually used for intent resolution. 3045 final IntentFilterVerificationInfo ivi; 3046 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 3047 new ArrayList<String>(domains)); 3048 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 3049 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 3050 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 3051 } else { 3052 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 3053 + "' does not handle web links"); 3054 } 3055 } else { 3056 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 3057 } 3058 } 3059 3060 scheduleWritePackageRestrictionsLocked(userId); 3061 scheduleWriteSettingsLocked(); 3062 } 3063 3064 private void applyFactoryDefaultBrowserLPw(int userId) { 3065 // The default browser app's package name is stored in a string resource, 3066 // with a product-specific overlay used for vendor customization. 3067 String browserPkg = mContext.getResources().getString( 3068 com.android.internal.R.string.default_browser); 3069 if (!TextUtils.isEmpty(browserPkg)) { 3070 // non-empty string => required to be a known package 3071 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3072 if (ps == null) { 3073 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3074 browserPkg = null; 3075 } else { 3076 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3077 } 3078 } 3079 3080 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3081 // default. If there's more than one, just leave everything alone. 3082 if (browserPkg == null) { 3083 calculateDefaultBrowserLPw(userId); 3084 } 3085 } 3086 3087 private void calculateDefaultBrowserLPw(int userId) { 3088 List<String> allBrowsers = resolveAllBrowserApps(userId); 3089 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3090 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3091 } 3092 3093 private List<String> resolveAllBrowserApps(int userId) { 3094 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3095 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3096 PackageManager.MATCH_ALL, userId); 3097 3098 final int count = list.size(); 3099 List<String> result = new ArrayList<String>(count); 3100 for (int i=0; i<count; i++) { 3101 ResolveInfo info = list.get(i); 3102 if (info.activityInfo == null 3103 || !info.handleAllWebDataURI 3104 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3105 || result.contains(info.activityInfo.packageName)) { 3106 continue; 3107 } 3108 result.add(info.activityInfo.packageName); 3109 } 3110 3111 return result; 3112 } 3113 3114 private boolean packageIsBrowser(String packageName, int userId) { 3115 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3116 PackageManager.MATCH_ALL, userId); 3117 final int N = list.size(); 3118 for (int i = 0; i < N; i++) { 3119 ResolveInfo info = list.get(i); 3120 if (packageName.equals(info.activityInfo.packageName)) { 3121 return true; 3122 } 3123 } 3124 return false; 3125 } 3126 3127 private void checkDefaultBrowser() { 3128 final int myUserId = UserHandle.myUserId(); 3129 final String packageName = getDefaultBrowserPackageName(myUserId); 3130 if (packageName != null) { 3131 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3132 if (info == null) { 3133 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3134 synchronized (mPackages) { 3135 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3136 } 3137 } 3138 } 3139 } 3140 3141 @Override 3142 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3143 throws RemoteException { 3144 try { 3145 return super.onTransact(code, data, reply, flags); 3146 } catch (RuntimeException e) { 3147 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3148 Slog.wtf(TAG, "Package Manager Crash", e); 3149 } 3150 throw e; 3151 } 3152 } 3153 3154 static int[] appendInts(int[] cur, int[] add) { 3155 if (add == null) return cur; 3156 if (cur == null) return add; 3157 final int N = add.length; 3158 for (int i=0; i<N; i++) { 3159 cur = appendInt(cur, add[i]); 3160 } 3161 return cur; 3162 } 3163 3164 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3165 if (!sUserManager.exists(userId)) return null; 3166 if (ps == null) { 3167 return null; 3168 } 3169 final PackageParser.Package p = ps.pkg; 3170 if (p == null) { 3171 return null; 3172 } 3173 3174 final PermissionsState permissionsState = ps.getPermissionsState(); 3175 3176 final int[] gids = permissionsState.computeGids(userId); 3177 final Set<String> permissions = permissionsState.getPermissions(userId); 3178 final PackageUserState state = ps.readUserState(userId); 3179 3180 return PackageParser.generatePackageInfo(p, gids, flags, 3181 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3182 } 3183 3184 @Override 3185 public void checkPackageStartable(String packageName, int userId) { 3186 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3187 3188 synchronized (mPackages) { 3189 final PackageSetting ps = mSettings.mPackages.get(packageName); 3190 if (ps == null) { 3191 throw new SecurityException("Package " + packageName + " was not found!"); 3192 } 3193 3194 if (!ps.getInstalled(userId)) { 3195 throw new SecurityException( 3196 "Package " + packageName + " was not installed for user " + userId + "!"); 3197 } 3198 3199 if (mSafeMode && !ps.isSystem()) { 3200 throw new SecurityException("Package " + packageName + " not a system app!"); 3201 } 3202 3203 if (mFrozenPackages.contains(packageName)) { 3204 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3205 } 3206 3207 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3208 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3209 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3210 } 3211 } 3212 } 3213 3214 @Override 3215 public boolean isPackageAvailable(String packageName, int userId) { 3216 if (!sUserManager.exists(userId)) return false; 3217 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3218 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3219 synchronized (mPackages) { 3220 PackageParser.Package p = mPackages.get(packageName); 3221 if (p != null) { 3222 final PackageSetting ps = (PackageSetting) p.mExtras; 3223 if (ps != null) { 3224 final PackageUserState state = ps.readUserState(userId); 3225 if (state != null) { 3226 return PackageParser.isAvailable(state); 3227 } 3228 } 3229 } 3230 } 3231 return false; 3232 } 3233 3234 @Override 3235 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3236 if (!sUserManager.exists(userId)) return null; 3237 flags = updateFlagsForPackage(flags, userId, packageName); 3238 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3239 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3240 // reader 3241 synchronized (mPackages) { 3242 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3243 PackageParser.Package p = null; 3244 if (matchFactoryOnly) { 3245 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3246 if (ps != null) { 3247 return generatePackageInfo(ps, flags, userId); 3248 } 3249 } 3250 if (p == null) { 3251 p = mPackages.get(packageName); 3252 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3253 return null; 3254 } 3255 } 3256 if (DEBUG_PACKAGE_INFO) 3257 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3258 if (p != null) { 3259 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3260 } 3261 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3262 final PackageSetting ps = mSettings.mPackages.get(packageName); 3263 return generatePackageInfo(ps, flags, userId); 3264 } 3265 } 3266 return null; 3267 } 3268 3269 @Override 3270 public String[] currentToCanonicalPackageNames(String[] names) { 3271 String[] out = new String[names.length]; 3272 // reader 3273 synchronized (mPackages) { 3274 for (int i=names.length-1; i>=0; i--) { 3275 PackageSetting ps = mSettings.mPackages.get(names[i]); 3276 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3277 } 3278 } 3279 return out; 3280 } 3281 3282 @Override 3283 public String[] canonicalToCurrentPackageNames(String[] names) { 3284 String[] out = new String[names.length]; 3285 // reader 3286 synchronized (mPackages) { 3287 for (int i=names.length-1; i>=0; i--) { 3288 String cur = mSettings.mRenamedPackages.get(names[i]); 3289 out[i] = cur != null ? cur : names[i]; 3290 } 3291 } 3292 return out; 3293 } 3294 3295 @Override 3296 public int getPackageUid(String packageName, int flags, int userId) { 3297 if (!sUserManager.exists(userId)) return -1; 3298 flags = updateFlagsForPackage(flags, userId, packageName); 3299 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3300 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3301 3302 // reader 3303 synchronized (mPackages) { 3304 final PackageParser.Package p = mPackages.get(packageName); 3305 if (p != null && p.isMatch(flags)) { 3306 return UserHandle.getUid(userId, p.applicationInfo.uid); 3307 } 3308 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3309 final PackageSetting ps = mSettings.mPackages.get(packageName); 3310 if (ps != null && ps.isMatch(flags)) { 3311 return UserHandle.getUid(userId, ps.appId); 3312 } 3313 } 3314 } 3315 3316 return -1; 3317 } 3318 3319 @Override 3320 public int[] getPackageGids(String packageName, int flags, int userId) { 3321 if (!sUserManager.exists(userId)) return null; 3322 flags = updateFlagsForPackage(flags, userId, packageName); 3323 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3324 false /* requireFullPermission */, false /* checkShell */, 3325 "getPackageGids"); 3326 3327 // reader 3328 synchronized (mPackages) { 3329 final PackageParser.Package p = mPackages.get(packageName); 3330 if (p != null && p.isMatch(flags)) { 3331 PackageSetting ps = (PackageSetting) p.mExtras; 3332 return ps.getPermissionsState().computeGids(userId); 3333 } 3334 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3335 final PackageSetting ps = mSettings.mPackages.get(packageName); 3336 if (ps != null && ps.isMatch(flags)) { 3337 return ps.getPermissionsState().computeGids(userId); 3338 } 3339 } 3340 } 3341 3342 return null; 3343 } 3344 3345 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3346 if (bp.perm != null) { 3347 return PackageParser.generatePermissionInfo(bp.perm, flags); 3348 } 3349 PermissionInfo pi = new PermissionInfo(); 3350 pi.name = bp.name; 3351 pi.packageName = bp.sourcePackage; 3352 pi.nonLocalizedLabel = bp.name; 3353 pi.protectionLevel = bp.protectionLevel; 3354 return pi; 3355 } 3356 3357 @Override 3358 public PermissionInfo getPermissionInfo(String name, int flags) { 3359 // reader 3360 synchronized (mPackages) { 3361 final BasePermission p = mSettings.mPermissions.get(name); 3362 if (p != null) { 3363 return generatePermissionInfo(p, flags); 3364 } 3365 return null; 3366 } 3367 } 3368 3369 @Override 3370 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3371 int flags) { 3372 // reader 3373 synchronized (mPackages) { 3374 if (group != null && !mPermissionGroups.containsKey(group)) { 3375 // This is thrown as NameNotFoundException 3376 return null; 3377 } 3378 3379 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3380 for (BasePermission p : mSettings.mPermissions.values()) { 3381 if (group == null) { 3382 if (p.perm == null || p.perm.info.group == null) { 3383 out.add(generatePermissionInfo(p, flags)); 3384 } 3385 } else { 3386 if (p.perm != null && group.equals(p.perm.info.group)) { 3387 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3388 } 3389 } 3390 } 3391 return new ParceledListSlice<>(out); 3392 } 3393 } 3394 3395 @Override 3396 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3397 // reader 3398 synchronized (mPackages) { 3399 return PackageParser.generatePermissionGroupInfo( 3400 mPermissionGroups.get(name), flags); 3401 } 3402 } 3403 3404 @Override 3405 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3406 // reader 3407 synchronized (mPackages) { 3408 final int N = mPermissionGroups.size(); 3409 ArrayList<PermissionGroupInfo> out 3410 = new ArrayList<PermissionGroupInfo>(N); 3411 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3412 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3413 } 3414 return new ParceledListSlice<>(out); 3415 } 3416 } 3417 3418 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3419 int userId) { 3420 if (!sUserManager.exists(userId)) return null; 3421 PackageSetting ps = mSettings.mPackages.get(packageName); 3422 if (ps != null) { 3423 if (ps.pkg == null) { 3424 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3425 if (pInfo != null) { 3426 return pInfo.applicationInfo; 3427 } 3428 return null; 3429 } 3430 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3431 ps.readUserState(userId), userId); 3432 } 3433 return null; 3434 } 3435 3436 @Override 3437 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3438 if (!sUserManager.exists(userId)) return null; 3439 flags = updateFlagsForApplication(flags, userId, packageName); 3440 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3441 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3442 // writer 3443 synchronized (mPackages) { 3444 PackageParser.Package p = mPackages.get(packageName); 3445 if (DEBUG_PACKAGE_INFO) Log.v( 3446 TAG, "getApplicationInfo " + packageName 3447 + ": " + p); 3448 if (p != null) { 3449 PackageSetting ps = mSettings.mPackages.get(packageName); 3450 if (ps == null) return null; 3451 // Note: isEnabledLP() does not apply here - always return info 3452 return PackageParser.generateApplicationInfo( 3453 p, flags, ps.readUserState(userId), userId); 3454 } 3455 if ("android".equals(packageName)||"system".equals(packageName)) { 3456 return mAndroidApplication; 3457 } 3458 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3459 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3460 } 3461 } 3462 return null; 3463 } 3464 3465 @Override 3466 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3467 final IPackageDataObserver observer) { 3468 mContext.enforceCallingOrSelfPermission( 3469 android.Manifest.permission.CLEAR_APP_CACHE, null); 3470 // Queue up an async operation since clearing cache may take a little while. 3471 mHandler.post(new Runnable() { 3472 public void run() { 3473 mHandler.removeCallbacks(this); 3474 boolean success = true; 3475 synchronized (mInstallLock) { 3476 try { 3477 mInstaller.freeCache(volumeUuid, freeStorageSize); 3478 } catch (InstallerException e) { 3479 Slog.w(TAG, "Couldn't clear application caches: " + e); 3480 success = false; 3481 } 3482 } 3483 if (observer != null) { 3484 try { 3485 observer.onRemoveCompleted(null, success); 3486 } catch (RemoteException e) { 3487 Slog.w(TAG, "RemoveException when invoking call back"); 3488 } 3489 } 3490 } 3491 }); 3492 } 3493 3494 @Override 3495 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3496 final IntentSender pi) { 3497 mContext.enforceCallingOrSelfPermission( 3498 android.Manifest.permission.CLEAR_APP_CACHE, null); 3499 // Queue up an async operation since clearing cache may take a little while. 3500 mHandler.post(new Runnable() { 3501 public void run() { 3502 mHandler.removeCallbacks(this); 3503 boolean success = true; 3504 synchronized (mInstallLock) { 3505 try { 3506 mInstaller.freeCache(volumeUuid, freeStorageSize); 3507 } catch (InstallerException e) { 3508 Slog.w(TAG, "Couldn't clear application caches: " + e); 3509 success = false; 3510 } 3511 } 3512 if(pi != null) { 3513 try { 3514 // Callback via pending intent 3515 int code = success ? 1 : 0; 3516 pi.sendIntent(null, code, null, 3517 null, null); 3518 } catch (SendIntentException e1) { 3519 Slog.i(TAG, "Failed to send pending intent"); 3520 } 3521 } 3522 } 3523 }); 3524 } 3525 3526 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3527 synchronized (mInstallLock) { 3528 try { 3529 mInstaller.freeCache(volumeUuid, freeStorageSize); 3530 } catch (InstallerException e) { 3531 throw new IOException("Failed to free enough space", e); 3532 } 3533 } 3534 } 3535 3536 /** 3537 * Update given flags based on encryption status of current user. 3538 */ 3539 private int updateFlags(int flags, int userId) { 3540 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3541 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3542 // Caller expressed an explicit opinion about what encryption 3543 // aware/unaware components they want to see, so fall through and 3544 // give them what they want 3545 } else { 3546 // Caller expressed no opinion, so match based on user state 3547 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3548 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3549 } else { 3550 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3551 } 3552 } 3553 return flags; 3554 } 3555 3556 private UserManagerInternal getUserManagerInternal() { 3557 if (mUserManagerInternal == null) { 3558 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3559 } 3560 return mUserManagerInternal; 3561 } 3562 3563 /** 3564 * Update given flags when being used to request {@link PackageInfo}. 3565 */ 3566 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3567 boolean triaged = true; 3568 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3569 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3570 // Caller is asking for component details, so they'd better be 3571 // asking for specific encryption matching behavior, or be triaged 3572 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3573 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3574 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3575 triaged = false; 3576 } 3577 } 3578 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3579 | PackageManager.MATCH_SYSTEM_ONLY 3580 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3581 triaged = false; 3582 } 3583 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3584 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3585 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3586 } 3587 return updateFlags(flags, userId); 3588 } 3589 3590 /** 3591 * Update given flags when being used to request {@link ApplicationInfo}. 3592 */ 3593 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3594 return updateFlagsForPackage(flags, userId, cookie); 3595 } 3596 3597 /** 3598 * Update given flags when being used to request {@link ComponentInfo}. 3599 */ 3600 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3601 if (cookie instanceof Intent) { 3602 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3603 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3604 } 3605 } 3606 3607 boolean triaged = true; 3608 // Caller is asking for component details, so they'd better be 3609 // asking for specific encryption matching behavior, or be triaged 3610 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3611 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3612 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3613 triaged = false; 3614 } 3615 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3616 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3617 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3618 } 3619 3620 return updateFlags(flags, userId); 3621 } 3622 3623 /** 3624 * Update given flags when being used to request {@link ResolveInfo}. 3625 */ 3626 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3627 // Safe mode means we shouldn't match any third-party components 3628 if (mSafeMode) { 3629 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3630 } 3631 3632 return updateFlagsForComponent(flags, userId, cookie); 3633 } 3634 3635 @Override 3636 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3637 if (!sUserManager.exists(userId)) return null; 3638 flags = updateFlagsForComponent(flags, userId, component); 3639 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3640 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3641 synchronized (mPackages) { 3642 PackageParser.Activity a = mActivities.mActivities.get(component); 3643 3644 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3645 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3646 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3647 if (ps == null) return null; 3648 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3649 userId); 3650 } 3651 if (mResolveComponentName.equals(component)) { 3652 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3653 new PackageUserState(), userId); 3654 } 3655 } 3656 return null; 3657 } 3658 3659 @Override 3660 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3661 String resolvedType) { 3662 synchronized (mPackages) { 3663 if (component.equals(mResolveComponentName)) { 3664 // The resolver supports EVERYTHING! 3665 return true; 3666 } 3667 PackageParser.Activity a = mActivities.mActivities.get(component); 3668 if (a == null) { 3669 return false; 3670 } 3671 for (int i=0; i<a.intents.size(); i++) { 3672 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3673 intent.getData(), intent.getCategories(), TAG) >= 0) { 3674 return true; 3675 } 3676 } 3677 return false; 3678 } 3679 } 3680 3681 @Override 3682 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3683 if (!sUserManager.exists(userId)) return null; 3684 flags = updateFlagsForComponent(flags, userId, component); 3685 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3686 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3687 synchronized (mPackages) { 3688 PackageParser.Activity a = mReceivers.mActivities.get(component); 3689 if (DEBUG_PACKAGE_INFO) Log.v( 3690 TAG, "getReceiverInfo " + component + ": " + a); 3691 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3692 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3693 if (ps == null) return null; 3694 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3695 userId); 3696 } 3697 } 3698 return null; 3699 } 3700 3701 @Override 3702 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3703 if (!sUserManager.exists(userId)) return null; 3704 flags = updateFlagsForComponent(flags, userId, component); 3705 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3706 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3707 synchronized (mPackages) { 3708 PackageParser.Service s = mServices.mServices.get(component); 3709 if (DEBUG_PACKAGE_INFO) Log.v( 3710 TAG, "getServiceInfo " + component + ": " + s); 3711 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3712 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3713 if (ps == null) return null; 3714 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3715 userId); 3716 } 3717 } 3718 return null; 3719 } 3720 3721 @Override 3722 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3723 if (!sUserManager.exists(userId)) return null; 3724 flags = updateFlagsForComponent(flags, userId, component); 3725 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3726 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3727 synchronized (mPackages) { 3728 PackageParser.Provider p = mProviders.mProviders.get(component); 3729 if (DEBUG_PACKAGE_INFO) Log.v( 3730 TAG, "getProviderInfo " + component + ": " + p); 3731 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3732 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3733 if (ps == null) return null; 3734 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3735 userId); 3736 } 3737 } 3738 return null; 3739 } 3740 3741 @Override 3742 public String[] getSystemSharedLibraryNames() { 3743 Set<String> libSet; 3744 synchronized (mPackages) { 3745 libSet = mSharedLibraries.keySet(); 3746 int size = libSet.size(); 3747 if (size > 0) { 3748 String[] libs = new String[size]; 3749 libSet.toArray(libs); 3750 return libs; 3751 } 3752 } 3753 return null; 3754 } 3755 3756 @Override 3757 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3758 synchronized (mPackages) { 3759 return mServicesSystemSharedLibraryPackageName; 3760 } 3761 } 3762 3763 @Override 3764 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3765 synchronized (mPackages) { 3766 return mSharedSystemSharedLibraryPackageName; 3767 } 3768 } 3769 3770 @Override 3771 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3772 synchronized (mPackages) { 3773 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3774 3775 final FeatureInfo fi = new FeatureInfo(); 3776 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3777 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3778 res.add(fi); 3779 3780 return new ParceledListSlice<>(res); 3781 } 3782 } 3783 3784 @Override 3785 public boolean hasSystemFeature(String name, int version) { 3786 synchronized (mPackages) { 3787 final FeatureInfo feat = mAvailableFeatures.get(name); 3788 if (feat == null) { 3789 return false; 3790 } else { 3791 return feat.version >= version; 3792 } 3793 } 3794 } 3795 3796 @Override 3797 public int checkPermission(String permName, String pkgName, int userId) { 3798 if (!sUserManager.exists(userId)) { 3799 return PackageManager.PERMISSION_DENIED; 3800 } 3801 3802 synchronized (mPackages) { 3803 final PackageParser.Package p = mPackages.get(pkgName); 3804 if (p != null && p.mExtras != null) { 3805 final PackageSetting ps = (PackageSetting) p.mExtras; 3806 final PermissionsState permissionsState = ps.getPermissionsState(); 3807 if (permissionsState.hasPermission(permName, userId)) { 3808 return PackageManager.PERMISSION_GRANTED; 3809 } 3810 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3811 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3812 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3813 return PackageManager.PERMISSION_GRANTED; 3814 } 3815 } 3816 } 3817 3818 return PackageManager.PERMISSION_DENIED; 3819 } 3820 3821 @Override 3822 public int checkUidPermission(String permName, int uid) { 3823 final int userId = UserHandle.getUserId(uid); 3824 3825 if (!sUserManager.exists(userId)) { 3826 return PackageManager.PERMISSION_DENIED; 3827 } 3828 3829 synchronized (mPackages) { 3830 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3831 if (obj != null) { 3832 final SettingBase ps = (SettingBase) obj; 3833 final PermissionsState permissionsState = ps.getPermissionsState(); 3834 if (permissionsState.hasPermission(permName, userId)) { 3835 return PackageManager.PERMISSION_GRANTED; 3836 } 3837 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3838 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3839 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3840 return PackageManager.PERMISSION_GRANTED; 3841 } 3842 } else { 3843 ArraySet<String> perms = mSystemPermissions.get(uid); 3844 if (perms != null) { 3845 if (perms.contains(permName)) { 3846 return PackageManager.PERMISSION_GRANTED; 3847 } 3848 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3849 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3850 return PackageManager.PERMISSION_GRANTED; 3851 } 3852 } 3853 } 3854 } 3855 3856 return PackageManager.PERMISSION_DENIED; 3857 } 3858 3859 @Override 3860 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3861 if (UserHandle.getCallingUserId() != userId) { 3862 mContext.enforceCallingPermission( 3863 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3864 "isPermissionRevokedByPolicy for user " + userId); 3865 } 3866 3867 if (checkPermission(permission, packageName, userId) 3868 == PackageManager.PERMISSION_GRANTED) { 3869 return false; 3870 } 3871 3872 final long identity = Binder.clearCallingIdentity(); 3873 try { 3874 final int flags = getPermissionFlags(permission, packageName, userId); 3875 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3876 } finally { 3877 Binder.restoreCallingIdentity(identity); 3878 } 3879 } 3880 3881 @Override 3882 public String getPermissionControllerPackageName() { 3883 synchronized (mPackages) { 3884 return mRequiredInstallerPackage; 3885 } 3886 } 3887 3888 /** 3889 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3890 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3891 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3892 * @param message the message to log on security exception 3893 */ 3894 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3895 boolean checkShell, String message) { 3896 if (userId < 0) { 3897 throw new IllegalArgumentException("Invalid userId " + userId); 3898 } 3899 if (checkShell) { 3900 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3901 } 3902 if (userId == UserHandle.getUserId(callingUid)) return; 3903 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3904 if (requireFullPermission) { 3905 mContext.enforceCallingOrSelfPermission( 3906 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3907 } else { 3908 try { 3909 mContext.enforceCallingOrSelfPermission( 3910 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3911 } catch (SecurityException se) { 3912 mContext.enforceCallingOrSelfPermission( 3913 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3914 } 3915 } 3916 } 3917 } 3918 3919 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3920 if (callingUid == Process.SHELL_UID) { 3921 if (userHandle >= 0 3922 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3923 throw new SecurityException("Shell does not have permission to access user " 3924 + userHandle); 3925 } else if (userHandle < 0) { 3926 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3927 + Debug.getCallers(3)); 3928 } 3929 } 3930 } 3931 3932 private BasePermission findPermissionTreeLP(String permName) { 3933 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3934 if (permName.startsWith(bp.name) && 3935 permName.length() > bp.name.length() && 3936 permName.charAt(bp.name.length()) == '.') { 3937 return bp; 3938 } 3939 } 3940 return null; 3941 } 3942 3943 private BasePermission checkPermissionTreeLP(String permName) { 3944 if (permName != null) { 3945 BasePermission bp = findPermissionTreeLP(permName); 3946 if (bp != null) { 3947 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3948 return bp; 3949 } 3950 throw new SecurityException("Calling uid " 3951 + Binder.getCallingUid() 3952 + " is not allowed to add to permission tree " 3953 + bp.name + " owned by uid " + bp.uid); 3954 } 3955 } 3956 throw new SecurityException("No permission tree found for " + permName); 3957 } 3958 3959 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3960 if (s1 == null) { 3961 return s2 == null; 3962 } 3963 if (s2 == null) { 3964 return false; 3965 } 3966 if (s1.getClass() != s2.getClass()) { 3967 return false; 3968 } 3969 return s1.equals(s2); 3970 } 3971 3972 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3973 if (pi1.icon != pi2.icon) return false; 3974 if (pi1.logo != pi2.logo) return false; 3975 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3976 if (!compareStrings(pi1.name, pi2.name)) return false; 3977 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3978 // We'll take care of setting this one. 3979 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3980 // These are not currently stored in settings. 3981 //if (!compareStrings(pi1.group, pi2.group)) return false; 3982 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3983 //if (pi1.labelRes != pi2.labelRes) return false; 3984 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3985 return true; 3986 } 3987 3988 int permissionInfoFootprint(PermissionInfo info) { 3989 int size = info.name.length(); 3990 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3991 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3992 return size; 3993 } 3994 3995 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3996 int size = 0; 3997 for (BasePermission perm : mSettings.mPermissions.values()) { 3998 if (perm.uid == tree.uid) { 3999 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 4000 } 4001 } 4002 return size; 4003 } 4004 4005 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 4006 // We calculate the max size of permissions defined by this uid and throw 4007 // if that plus the size of 'info' would exceed our stated maximum. 4008 if (tree.uid != Process.SYSTEM_UID) { 4009 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 4010 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 4011 throw new SecurityException("Permission tree size cap exceeded"); 4012 } 4013 } 4014 } 4015 4016 boolean addPermissionLocked(PermissionInfo info, boolean async) { 4017 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 4018 throw new SecurityException("Label must be specified in permission"); 4019 } 4020 BasePermission tree = checkPermissionTreeLP(info.name); 4021 BasePermission bp = mSettings.mPermissions.get(info.name); 4022 boolean added = bp == null; 4023 boolean changed = true; 4024 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 4025 if (added) { 4026 enforcePermissionCapLocked(info, tree); 4027 bp = new BasePermission(info.name, tree.sourcePackage, 4028 BasePermission.TYPE_DYNAMIC); 4029 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 4030 throw new SecurityException( 4031 "Not allowed to modify non-dynamic permission " 4032 + info.name); 4033 } else { 4034 if (bp.protectionLevel == fixedLevel 4035 && bp.perm.owner.equals(tree.perm.owner) 4036 && bp.uid == tree.uid 4037 && comparePermissionInfos(bp.perm.info, info)) { 4038 changed = false; 4039 } 4040 } 4041 bp.protectionLevel = fixedLevel; 4042 info = new PermissionInfo(info); 4043 info.protectionLevel = fixedLevel; 4044 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 4045 bp.perm.info.packageName = tree.perm.info.packageName; 4046 bp.uid = tree.uid; 4047 if (added) { 4048 mSettings.mPermissions.put(info.name, bp); 4049 } 4050 if (changed) { 4051 if (!async) { 4052 mSettings.writeLPr(); 4053 } else { 4054 scheduleWriteSettingsLocked(); 4055 } 4056 } 4057 return added; 4058 } 4059 4060 @Override 4061 public boolean addPermission(PermissionInfo info) { 4062 synchronized (mPackages) { 4063 return addPermissionLocked(info, false); 4064 } 4065 } 4066 4067 @Override 4068 public boolean addPermissionAsync(PermissionInfo info) { 4069 synchronized (mPackages) { 4070 return addPermissionLocked(info, true); 4071 } 4072 } 4073 4074 @Override 4075 public void removePermission(String name) { 4076 synchronized (mPackages) { 4077 checkPermissionTreeLP(name); 4078 BasePermission bp = mSettings.mPermissions.get(name); 4079 if (bp != null) { 4080 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4081 throw new SecurityException( 4082 "Not allowed to modify non-dynamic permission " 4083 + name); 4084 } 4085 mSettings.mPermissions.remove(name); 4086 mSettings.writeLPr(); 4087 } 4088 } 4089 } 4090 4091 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4092 BasePermission bp) { 4093 int index = pkg.requestedPermissions.indexOf(bp.name); 4094 if (index == -1) { 4095 throw new SecurityException("Package " + pkg.packageName 4096 + " has not requested permission " + bp.name); 4097 } 4098 if (!bp.isRuntime() && !bp.isDevelopment()) { 4099 throw new SecurityException("Permission " + bp.name 4100 + " is not a changeable permission type"); 4101 } 4102 } 4103 4104 @Override 4105 public void grantRuntimePermission(String packageName, String name, final int userId) { 4106 if (!sUserManager.exists(userId)) { 4107 Log.e(TAG, "No such user:" + userId); 4108 return; 4109 } 4110 4111 mContext.enforceCallingOrSelfPermission( 4112 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4113 "grantRuntimePermission"); 4114 4115 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4116 true /* requireFullPermission */, true /* checkShell */, 4117 "grantRuntimePermission"); 4118 4119 final int uid; 4120 final SettingBase sb; 4121 4122 synchronized (mPackages) { 4123 final PackageParser.Package pkg = mPackages.get(packageName); 4124 if (pkg == null) { 4125 throw new IllegalArgumentException("Unknown package: " + packageName); 4126 } 4127 4128 final BasePermission bp = mSettings.mPermissions.get(name); 4129 if (bp == null) { 4130 throw new IllegalArgumentException("Unknown permission: " + name); 4131 } 4132 4133 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4134 4135 // If a permission review is required for legacy apps we represent 4136 // their permissions as always granted runtime ones since we need 4137 // to keep the review required permission flag per user while an 4138 // install permission's state is shared across all users. 4139 if (Build.PERMISSIONS_REVIEW_REQUIRED 4140 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4141 && bp.isRuntime()) { 4142 return; 4143 } 4144 4145 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4146 sb = (SettingBase) pkg.mExtras; 4147 if (sb == null) { 4148 throw new IllegalArgumentException("Unknown package: " + packageName); 4149 } 4150 4151 final PermissionsState permissionsState = sb.getPermissionsState(); 4152 4153 final int flags = permissionsState.getPermissionFlags(name, userId); 4154 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4155 throw new SecurityException("Cannot grant system fixed permission " 4156 + name + " for package " + packageName); 4157 } 4158 4159 if (bp.isDevelopment()) { 4160 // Development permissions must be handled specially, since they are not 4161 // normal runtime permissions. For now they apply to all users. 4162 if (permissionsState.grantInstallPermission(bp) != 4163 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4164 scheduleWriteSettingsLocked(); 4165 } 4166 return; 4167 } 4168 4169 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4170 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4171 return; 4172 } 4173 4174 final int result = permissionsState.grantRuntimePermission(bp, userId); 4175 switch (result) { 4176 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4177 return; 4178 } 4179 4180 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4181 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4182 mHandler.post(new Runnable() { 4183 @Override 4184 public void run() { 4185 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4186 } 4187 }); 4188 } 4189 break; 4190 } 4191 4192 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4193 4194 // Not critical if that is lost - app has to request again. 4195 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4196 } 4197 4198 // Only need to do this if user is initialized. Otherwise it's a new user 4199 // and there are no processes running as the user yet and there's no need 4200 // to make an expensive call to remount processes for the changed permissions. 4201 if (READ_EXTERNAL_STORAGE.equals(name) 4202 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4203 final long token = Binder.clearCallingIdentity(); 4204 try { 4205 if (sUserManager.isInitialized(userId)) { 4206 MountServiceInternal mountServiceInternal = LocalServices.getService( 4207 MountServiceInternal.class); 4208 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4209 } 4210 } finally { 4211 Binder.restoreCallingIdentity(token); 4212 } 4213 } 4214 } 4215 4216 @Override 4217 public void revokeRuntimePermission(String packageName, String name, int userId) { 4218 if (!sUserManager.exists(userId)) { 4219 Log.e(TAG, "No such user:" + userId); 4220 return; 4221 } 4222 4223 mContext.enforceCallingOrSelfPermission( 4224 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4225 "revokeRuntimePermission"); 4226 4227 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4228 true /* requireFullPermission */, true /* checkShell */, 4229 "revokeRuntimePermission"); 4230 4231 final int appId; 4232 4233 synchronized (mPackages) { 4234 final PackageParser.Package pkg = mPackages.get(packageName); 4235 if (pkg == null) { 4236 throw new IllegalArgumentException("Unknown package: " + packageName); 4237 } 4238 4239 final BasePermission bp = mSettings.mPermissions.get(name); 4240 if (bp == null) { 4241 throw new IllegalArgumentException("Unknown permission: " + name); 4242 } 4243 4244 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4245 4246 // If a permission review is required for legacy apps we represent 4247 // their permissions as always granted runtime ones since we need 4248 // to keep the review required permission flag per user while an 4249 // install permission's state is shared across all users. 4250 if (Build.PERMISSIONS_REVIEW_REQUIRED 4251 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4252 && bp.isRuntime()) { 4253 return; 4254 } 4255 4256 SettingBase sb = (SettingBase) pkg.mExtras; 4257 if (sb == null) { 4258 throw new IllegalArgumentException("Unknown package: " + packageName); 4259 } 4260 4261 final PermissionsState permissionsState = sb.getPermissionsState(); 4262 4263 final int flags = permissionsState.getPermissionFlags(name, userId); 4264 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4265 throw new SecurityException("Cannot revoke system fixed permission " 4266 + name + " for package " + packageName); 4267 } 4268 4269 if (bp.isDevelopment()) { 4270 // Development permissions must be handled specially, since they are not 4271 // normal runtime permissions. For now they apply to all users. 4272 if (permissionsState.revokeInstallPermission(bp) != 4273 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4274 scheduleWriteSettingsLocked(); 4275 } 4276 return; 4277 } 4278 4279 if (permissionsState.revokeRuntimePermission(bp, userId) == 4280 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4281 return; 4282 } 4283 4284 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4285 4286 // Critical, after this call app should never have the permission. 4287 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4288 4289 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4290 } 4291 4292 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4293 } 4294 4295 @Override 4296 public void resetRuntimePermissions() { 4297 mContext.enforceCallingOrSelfPermission( 4298 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4299 "revokeRuntimePermission"); 4300 4301 int callingUid = Binder.getCallingUid(); 4302 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4303 mContext.enforceCallingOrSelfPermission( 4304 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4305 "resetRuntimePermissions"); 4306 } 4307 4308 synchronized (mPackages) { 4309 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4310 for (int userId : UserManagerService.getInstance().getUserIds()) { 4311 final int packageCount = mPackages.size(); 4312 for (int i = 0; i < packageCount; i++) { 4313 PackageParser.Package pkg = mPackages.valueAt(i); 4314 if (!(pkg.mExtras instanceof PackageSetting)) { 4315 continue; 4316 } 4317 PackageSetting ps = (PackageSetting) pkg.mExtras; 4318 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4319 } 4320 } 4321 } 4322 } 4323 4324 @Override 4325 public int getPermissionFlags(String name, String packageName, int userId) { 4326 if (!sUserManager.exists(userId)) { 4327 return 0; 4328 } 4329 4330 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4331 4332 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4333 true /* requireFullPermission */, false /* checkShell */, 4334 "getPermissionFlags"); 4335 4336 synchronized (mPackages) { 4337 final PackageParser.Package pkg = mPackages.get(packageName); 4338 if (pkg == null) { 4339 return 0; 4340 } 4341 4342 final BasePermission bp = mSettings.mPermissions.get(name); 4343 if (bp == null) { 4344 return 0; 4345 } 4346 4347 SettingBase sb = (SettingBase) pkg.mExtras; 4348 if (sb == null) { 4349 return 0; 4350 } 4351 4352 PermissionsState permissionsState = sb.getPermissionsState(); 4353 return permissionsState.getPermissionFlags(name, userId); 4354 } 4355 } 4356 4357 @Override 4358 public void updatePermissionFlags(String name, String packageName, int flagMask, 4359 int flagValues, int userId) { 4360 if (!sUserManager.exists(userId)) { 4361 return; 4362 } 4363 4364 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4365 4366 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4367 true /* requireFullPermission */, true /* checkShell */, 4368 "updatePermissionFlags"); 4369 4370 // Only the system can change these flags and nothing else. 4371 if (getCallingUid() != Process.SYSTEM_UID) { 4372 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4373 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4374 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4375 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4376 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4377 } 4378 4379 synchronized (mPackages) { 4380 final PackageParser.Package pkg = mPackages.get(packageName); 4381 if (pkg == null) { 4382 throw new IllegalArgumentException("Unknown package: " + packageName); 4383 } 4384 4385 final BasePermission bp = mSettings.mPermissions.get(name); 4386 if (bp == null) { 4387 throw new IllegalArgumentException("Unknown permission: " + name); 4388 } 4389 4390 SettingBase sb = (SettingBase) pkg.mExtras; 4391 if (sb == null) { 4392 throw new IllegalArgumentException("Unknown package: " + packageName); 4393 } 4394 4395 PermissionsState permissionsState = sb.getPermissionsState(); 4396 4397 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4398 4399 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4400 // Install and runtime permissions are stored in different places, 4401 // so figure out what permission changed and persist the change. 4402 if (permissionsState.getInstallPermissionState(name) != null) { 4403 scheduleWriteSettingsLocked(); 4404 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4405 || hadState) { 4406 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4407 } 4408 } 4409 } 4410 } 4411 4412 /** 4413 * Update the permission flags for all packages and runtime permissions of a user in order 4414 * to allow device or profile owner to remove POLICY_FIXED. 4415 */ 4416 @Override 4417 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4418 if (!sUserManager.exists(userId)) { 4419 return; 4420 } 4421 4422 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4423 4424 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4425 true /* requireFullPermission */, true /* checkShell */, 4426 "updatePermissionFlagsForAllApps"); 4427 4428 // Only the system can change system fixed flags. 4429 if (getCallingUid() != Process.SYSTEM_UID) { 4430 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4431 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4432 } 4433 4434 synchronized (mPackages) { 4435 boolean changed = false; 4436 final int packageCount = mPackages.size(); 4437 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4438 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4439 SettingBase sb = (SettingBase) pkg.mExtras; 4440 if (sb == null) { 4441 continue; 4442 } 4443 PermissionsState permissionsState = sb.getPermissionsState(); 4444 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4445 userId, flagMask, flagValues); 4446 } 4447 if (changed) { 4448 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4449 } 4450 } 4451 } 4452 4453 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4454 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4455 != PackageManager.PERMISSION_GRANTED 4456 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4457 != PackageManager.PERMISSION_GRANTED) { 4458 throw new SecurityException(message + " requires " 4459 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4460 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4461 } 4462 } 4463 4464 @Override 4465 public boolean shouldShowRequestPermissionRationale(String permissionName, 4466 String packageName, int userId) { 4467 if (UserHandle.getCallingUserId() != userId) { 4468 mContext.enforceCallingPermission( 4469 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4470 "canShowRequestPermissionRationale for user " + userId); 4471 } 4472 4473 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4474 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4475 return false; 4476 } 4477 4478 if (checkPermission(permissionName, packageName, userId) 4479 == PackageManager.PERMISSION_GRANTED) { 4480 return false; 4481 } 4482 4483 final int flags; 4484 4485 final long identity = Binder.clearCallingIdentity(); 4486 try { 4487 flags = getPermissionFlags(permissionName, 4488 packageName, userId); 4489 } finally { 4490 Binder.restoreCallingIdentity(identity); 4491 } 4492 4493 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4494 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4495 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4496 4497 if ((flags & fixedFlags) != 0) { 4498 return false; 4499 } 4500 4501 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4502 } 4503 4504 @Override 4505 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4506 mContext.enforceCallingOrSelfPermission( 4507 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4508 "addOnPermissionsChangeListener"); 4509 4510 synchronized (mPackages) { 4511 mOnPermissionChangeListeners.addListenerLocked(listener); 4512 } 4513 } 4514 4515 @Override 4516 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4517 synchronized (mPackages) { 4518 mOnPermissionChangeListeners.removeListenerLocked(listener); 4519 } 4520 } 4521 4522 @Override 4523 public boolean isProtectedBroadcast(String actionName) { 4524 synchronized (mPackages) { 4525 if (mProtectedBroadcasts.contains(actionName)) { 4526 return true; 4527 } else if (actionName != null) { 4528 // TODO: remove these terrible hacks 4529 if (actionName.startsWith("android.net.netmon.lingerExpired") 4530 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4531 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4532 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4533 return true; 4534 } 4535 } 4536 } 4537 return false; 4538 } 4539 4540 @Override 4541 public int checkSignatures(String pkg1, String pkg2) { 4542 synchronized (mPackages) { 4543 final PackageParser.Package p1 = mPackages.get(pkg1); 4544 final PackageParser.Package p2 = mPackages.get(pkg2); 4545 if (p1 == null || p1.mExtras == null 4546 || p2 == null || p2.mExtras == null) { 4547 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4548 } 4549 return compareSignatures(p1.mSignatures, p2.mSignatures); 4550 } 4551 } 4552 4553 @Override 4554 public int checkUidSignatures(int uid1, int uid2) { 4555 // Map to base uids. 4556 uid1 = UserHandle.getAppId(uid1); 4557 uid2 = UserHandle.getAppId(uid2); 4558 // reader 4559 synchronized (mPackages) { 4560 Signature[] s1; 4561 Signature[] s2; 4562 Object obj = mSettings.getUserIdLPr(uid1); 4563 if (obj != null) { 4564 if (obj instanceof SharedUserSetting) { 4565 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4566 } else if (obj instanceof PackageSetting) { 4567 s1 = ((PackageSetting)obj).signatures.mSignatures; 4568 } else { 4569 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4570 } 4571 } else { 4572 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4573 } 4574 obj = mSettings.getUserIdLPr(uid2); 4575 if (obj != null) { 4576 if (obj instanceof SharedUserSetting) { 4577 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4578 } else if (obj instanceof PackageSetting) { 4579 s2 = ((PackageSetting)obj).signatures.mSignatures; 4580 } else { 4581 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4582 } 4583 } else { 4584 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4585 } 4586 return compareSignatures(s1, s2); 4587 } 4588 } 4589 4590 /** 4591 * This method should typically only be used when granting or revoking 4592 * permissions, since the app may immediately restart after this call. 4593 * <p> 4594 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4595 * guard your work against the app being relaunched. 4596 */ 4597 private void killUid(int appId, int userId, String reason) { 4598 final long identity = Binder.clearCallingIdentity(); 4599 try { 4600 IActivityManager am = ActivityManagerNative.getDefault(); 4601 if (am != null) { 4602 try { 4603 am.killUid(appId, userId, reason); 4604 } catch (RemoteException e) { 4605 /* ignore - same process */ 4606 } 4607 } 4608 } finally { 4609 Binder.restoreCallingIdentity(identity); 4610 } 4611 } 4612 4613 /** 4614 * Compares two sets of signatures. Returns: 4615 * <br /> 4616 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4617 * <br /> 4618 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4619 * <br /> 4620 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4621 * <br /> 4622 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4623 * <br /> 4624 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4625 */ 4626 static int compareSignatures(Signature[] s1, Signature[] s2) { 4627 if (s1 == null) { 4628 return s2 == null 4629 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4630 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4631 } 4632 4633 if (s2 == null) { 4634 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4635 } 4636 4637 if (s1.length != s2.length) { 4638 return PackageManager.SIGNATURE_NO_MATCH; 4639 } 4640 4641 // Since both signature sets are of size 1, we can compare without HashSets. 4642 if (s1.length == 1) { 4643 return s1[0].equals(s2[0]) ? 4644 PackageManager.SIGNATURE_MATCH : 4645 PackageManager.SIGNATURE_NO_MATCH; 4646 } 4647 4648 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4649 for (Signature sig : s1) { 4650 set1.add(sig); 4651 } 4652 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4653 for (Signature sig : s2) { 4654 set2.add(sig); 4655 } 4656 // Make sure s2 contains all signatures in s1. 4657 if (set1.equals(set2)) { 4658 return PackageManager.SIGNATURE_MATCH; 4659 } 4660 return PackageManager.SIGNATURE_NO_MATCH; 4661 } 4662 4663 /** 4664 * If the database version for this type of package (internal storage or 4665 * external storage) is less than the version where package signatures 4666 * were updated, return true. 4667 */ 4668 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4669 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4670 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4671 } 4672 4673 /** 4674 * Used for backward compatibility to make sure any packages with 4675 * certificate chains get upgraded to the new style. {@code existingSigs} 4676 * will be in the old format (since they were stored on disk from before the 4677 * system upgrade) and {@code scannedSigs} will be in the newer format. 4678 */ 4679 private int compareSignaturesCompat(PackageSignatures existingSigs, 4680 PackageParser.Package scannedPkg) { 4681 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4682 return PackageManager.SIGNATURE_NO_MATCH; 4683 } 4684 4685 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4686 for (Signature sig : existingSigs.mSignatures) { 4687 existingSet.add(sig); 4688 } 4689 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4690 for (Signature sig : scannedPkg.mSignatures) { 4691 try { 4692 Signature[] chainSignatures = sig.getChainSignatures(); 4693 for (Signature chainSig : chainSignatures) { 4694 scannedCompatSet.add(chainSig); 4695 } 4696 } catch (CertificateEncodingException e) { 4697 scannedCompatSet.add(sig); 4698 } 4699 } 4700 /* 4701 * Make sure the expanded scanned set contains all signatures in the 4702 * existing one. 4703 */ 4704 if (scannedCompatSet.equals(existingSet)) { 4705 // Migrate the old signatures to the new scheme. 4706 existingSigs.assignSignatures(scannedPkg.mSignatures); 4707 // The new KeySets will be re-added later in the scanning process. 4708 synchronized (mPackages) { 4709 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4710 } 4711 return PackageManager.SIGNATURE_MATCH; 4712 } 4713 return PackageManager.SIGNATURE_NO_MATCH; 4714 } 4715 4716 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4717 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4718 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4719 } 4720 4721 private int compareSignaturesRecover(PackageSignatures existingSigs, 4722 PackageParser.Package scannedPkg) { 4723 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4724 return PackageManager.SIGNATURE_NO_MATCH; 4725 } 4726 4727 String msg = null; 4728 try { 4729 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4730 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4731 + scannedPkg.packageName); 4732 return PackageManager.SIGNATURE_MATCH; 4733 } 4734 } catch (CertificateException e) { 4735 msg = e.getMessage(); 4736 } 4737 4738 logCriticalInfo(Log.INFO, 4739 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4740 return PackageManager.SIGNATURE_NO_MATCH; 4741 } 4742 4743 @Override 4744 public List<String> getAllPackages() { 4745 synchronized (mPackages) { 4746 return new ArrayList<String>(mPackages.keySet()); 4747 } 4748 } 4749 4750 @Override 4751 public String[] getPackagesForUid(int uid) { 4752 uid = UserHandle.getAppId(uid); 4753 // reader 4754 synchronized (mPackages) { 4755 Object obj = mSettings.getUserIdLPr(uid); 4756 if (obj instanceof SharedUserSetting) { 4757 final SharedUserSetting sus = (SharedUserSetting) obj; 4758 final int N = sus.packages.size(); 4759 final String[] res = new String[N]; 4760 final Iterator<PackageSetting> it = sus.packages.iterator(); 4761 int i = 0; 4762 while (it.hasNext()) { 4763 res[i++] = it.next().name; 4764 } 4765 return res; 4766 } else if (obj instanceof PackageSetting) { 4767 final PackageSetting ps = (PackageSetting) obj; 4768 return new String[] { ps.name }; 4769 } 4770 } 4771 return null; 4772 } 4773 4774 @Override 4775 public String getNameForUid(int uid) { 4776 // reader 4777 synchronized (mPackages) { 4778 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4779 if (obj instanceof SharedUserSetting) { 4780 final SharedUserSetting sus = (SharedUserSetting) obj; 4781 return sus.name + ":" + sus.userId; 4782 } else if (obj instanceof PackageSetting) { 4783 final PackageSetting ps = (PackageSetting) obj; 4784 return ps.name; 4785 } 4786 } 4787 return null; 4788 } 4789 4790 @Override 4791 public int getUidForSharedUser(String sharedUserName) { 4792 if(sharedUserName == null) { 4793 return -1; 4794 } 4795 // reader 4796 synchronized (mPackages) { 4797 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4798 if (suid == null) { 4799 return -1; 4800 } 4801 return suid.userId; 4802 } 4803 } 4804 4805 @Override 4806 public int getFlagsForUid(int uid) { 4807 synchronized (mPackages) { 4808 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4809 if (obj instanceof SharedUserSetting) { 4810 final SharedUserSetting sus = (SharedUserSetting) obj; 4811 return sus.pkgFlags; 4812 } else if (obj instanceof PackageSetting) { 4813 final PackageSetting ps = (PackageSetting) obj; 4814 return ps.pkgFlags; 4815 } 4816 } 4817 return 0; 4818 } 4819 4820 @Override 4821 public int getPrivateFlagsForUid(int uid) { 4822 synchronized (mPackages) { 4823 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4824 if (obj instanceof SharedUserSetting) { 4825 final SharedUserSetting sus = (SharedUserSetting) obj; 4826 return sus.pkgPrivateFlags; 4827 } else if (obj instanceof PackageSetting) { 4828 final PackageSetting ps = (PackageSetting) obj; 4829 return ps.pkgPrivateFlags; 4830 } 4831 } 4832 return 0; 4833 } 4834 4835 @Override 4836 public boolean isUidPrivileged(int uid) { 4837 uid = UserHandle.getAppId(uid); 4838 // reader 4839 synchronized (mPackages) { 4840 Object obj = mSettings.getUserIdLPr(uid); 4841 if (obj instanceof SharedUserSetting) { 4842 final SharedUserSetting sus = (SharedUserSetting) obj; 4843 final Iterator<PackageSetting> it = sus.packages.iterator(); 4844 while (it.hasNext()) { 4845 if (it.next().isPrivileged()) { 4846 return true; 4847 } 4848 } 4849 } else if (obj instanceof PackageSetting) { 4850 final PackageSetting ps = (PackageSetting) obj; 4851 return ps.isPrivileged(); 4852 } 4853 } 4854 return false; 4855 } 4856 4857 @Override 4858 public String[] getAppOpPermissionPackages(String permissionName) { 4859 synchronized (mPackages) { 4860 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4861 if (pkgs == null) { 4862 return null; 4863 } 4864 return pkgs.toArray(new String[pkgs.size()]); 4865 } 4866 } 4867 4868 @Override 4869 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4870 int flags, int userId) { 4871 try { 4872 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4873 4874 if (!sUserManager.exists(userId)) return null; 4875 flags = updateFlagsForResolve(flags, userId, intent); 4876 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4877 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4878 4879 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4880 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4881 flags, userId); 4882 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4883 4884 final ResolveInfo bestChoice = 4885 chooseBestActivity(intent, resolvedType, flags, query, userId); 4886 4887 if (isEphemeralAllowed(intent, query, userId)) { 4888 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4889 final EphemeralResolveInfo ai = 4890 getEphemeralResolveInfo(intent, resolvedType, userId); 4891 if (ai != null) { 4892 if (DEBUG_EPHEMERAL) { 4893 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4894 } 4895 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4896 bestChoice.ephemeralResolveInfo = ai; 4897 } 4898 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4899 } 4900 return bestChoice; 4901 } finally { 4902 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4903 } 4904 } 4905 4906 @Override 4907 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4908 IntentFilter filter, int match, ComponentName activity) { 4909 final int userId = UserHandle.getCallingUserId(); 4910 if (DEBUG_PREFERRED) { 4911 Log.v(TAG, "setLastChosenActivity intent=" + intent 4912 + " resolvedType=" + resolvedType 4913 + " flags=" + flags 4914 + " filter=" + filter 4915 + " match=" + match 4916 + " activity=" + activity); 4917 filter.dump(new PrintStreamPrinter(System.out), " "); 4918 } 4919 intent.setComponent(null); 4920 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4921 userId); 4922 // Find any earlier preferred or last chosen entries and nuke them 4923 findPreferredActivity(intent, resolvedType, 4924 flags, query, 0, false, true, false, userId); 4925 // Add the new activity as the last chosen for this filter 4926 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4927 "Setting last chosen"); 4928 } 4929 4930 @Override 4931 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4932 final int userId = UserHandle.getCallingUserId(); 4933 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4934 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4935 userId); 4936 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4937 false, false, false, userId); 4938 } 4939 4940 4941 private boolean isEphemeralAllowed( 4942 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4943 // Short circuit and return early if possible. 4944 if (DISABLE_EPHEMERAL_APPS) { 4945 return false; 4946 } 4947 final int callingUser = UserHandle.getCallingUserId(); 4948 if (callingUser != UserHandle.USER_SYSTEM) { 4949 return false; 4950 } 4951 if (mEphemeralResolverConnection == null) { 4952 return false; 4953 } 4954 if (intent.getComponent() != null) { 4955 return false; 4956 } 4957 if (intent.getPackage() != null) { 4958 return false; 4959 } 4960 final boolean isWebUri = hasWebURI(intent); 4961 if (!isWebUri) { 4962 return false; 4963 } 4964 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4965 synchronized (mPackages) { 4966 final int count = resolvedActivites.size(); 4967 for (int n = 0; n < count; n++) { 4968 ResolveInfo info = resolvedActivites.get(n); 4969 String packageName = info.activityInfo.packageName; 4970 PackageSetting ps = mSettings.mPackages.get(packageName); 4971 if (ps != null) { 4972 // Try to get the status from User settings first 4973 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4974 int status = (int) (packedStatus >> 32); 4975 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4976 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4977 if (DEBUG_EPHEMERAL) { 4978 Slog.v(TAG, "DENY ephemeral apps;" 4979 + " pkg: " + packageName + ", status: " + status); 4980 } 4981 return false; 4982 } 4983 } 4984 } 4985 } 4986 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4987 return true; 4988 } 4989 4990 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4991 int userId) { 4992 MessageDigest digest = null; 4993 try { 4994 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4995 } catch (NoSuchAlgorithmException e) { 4996 // If we can't create a digest, ignore ephemeral apps. 4997 return null; 4998 } 4999 5000 final byte[] hostBytes = intent.getData().getHost().getBytes(); 5001 final byte[] digestBytes = digest.digest(hostBytes); 5002 int shaPrefix = 5003 (digestBytes[0] & 0xFF) << 24 5004 | (digestBytes[1] & 0xFF) << 16 5005 | (digestBytes[2] & 0xFF) << 8 5006 | (digestBytes[3] & 0xFF) << 0; 5007 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 5008 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 5009 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 5010 // No hash prefix match; there are no ephemeral apps for this domain. 5011 return null; 5012 } 5013 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 5014 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 5015 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 5016 continue; 5017 } 5018 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 5019 // No filters; this should never happen. 5020 if (filters.isEmpty()) { 5021 continue; 5022 } 5023 // We have a domain match; resolve the filters to see if anything matches. 5024 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 5025 for (int j = filters.size() - 1; j >= 0; --j) { 5026 final EphemeralResolveIntentInfo intentInfo = 5027 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 5028 ephemeralResolver.addFilter(intentInfo); 5029 } 5030 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 5031 intent, resolvedType, false /*defaultOnly*/, userId); 5032 if (!matchedResolveInfoList.isEmpty()) { 5033 return matchedResolveInfoList.get(0); 5034 } 5035 } 5036 // Hash or filter mis-match; no ephemeral apps for this domain. 5037 return null; 5038 } 5039 5040 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 5041 int flags, List<ResolveInfo> query, int userId) { 5042 if (query != null) { 5043 final int N = query.size(); 5044 if (N == 1) { 5045 return query.get(0); 5046 } else if (N > 1) { 5047 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 5048 // If there is more than one activity with the same priority, 5049 // then let the user decide between them. 5050 ResolveInfo r0 = query.get(0); 5051 ResolveInfo r1 = query.get(1); 5052 if (DEBUG_INTENT_MATCHING || debug) { 5053 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 5054 + r1.activityInfo.name + "=" + r1.priority); 5055 } 5056 // If the first activity has a higher priority, or a different 5057 // default, then it is always desirable to pick it. 5058 if (r0.priority != r1.priority 5059 || r0.preferredOrder != r1.preferredOrder 5060 || r0.isDefault != r1.isDefault) { 5061 return query.get(0); 5062 } 5063 // If we have saved a preference for a preferred activity for 5064 // this Intent, use that. 5065 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5066 flags, query, r0.priority, true, false, debug, userId); 5067 if (ri != null) { 5068 return ri; 5069 } 5070 ri = new ResolveInfo(mResolveInfo); 5071 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5072 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5073 // If all of the options come from the same package, show the application's 5074 // label and icon instead of the generic resolver's. 5075 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5076 // and then throw away the ResolveInfo itself, meaning that the caller loses 5077 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5078 // a fallback for this case; we only set the target package's resources on 5079 // the ResolveInfo, not the ActivityInfo. 5080 final String intentPackage = intent.getPackage(); 5081 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5082 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5083 ri.resolvePackageName = intentPackage; 5084 if (userNeedsBadging(userId)) { 5085 ri.noResourceId = true; 5086 } else { 5087 ri.icon = appi.icon; 5088 } 5089 ri.iconResourceId = appi.icon; 5090 ri.labelRes = appi.labelRes; 5091 } 5092 ri.activityInfo.applicationInfo = new ApplicationInfo( 5093 ri.activityInfo.applicationInfo); 5094 if (userId != 0) { 5095 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5096 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5097 } 5098 // Make sure that the resolver is displayable in car mode 5099 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5100 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5101 return ri; 5102 } 5103 } 5104 return null; 5105 } 5106 5107 /** 5108 * Return true if the given list is not empty and all of its contents have 5109 * an activityInfo with the given package name. 5110 */ 5111 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5112 if (ArrayUtils.isEmpty(list)) { 5113 return false; 5114 } 5115 for (int i = 0, N = list.size(); i < N; i++) { 5116 final ResolveInfo ri = list.get(i); 5117 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5118 if (ai == null || !packageName.equals(ai.packageName)) { 5119 return false; 5120 } 5121 } 5122 return true; 5123 } 5124 5125 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5126 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5127 final int N = query.size(); 5128 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5129 .get(userId); 5130 // Get the list of persistent preferred activities that handle the intent 5131 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5132 List<PersistentPreferredActivity> pprefs = ppir != null 5133 ? ppir.queryIntent(intent, resolvedType, 5134 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5135 : null; 5136 if (pprefs != null && pprefs.size() > 0) { 5137 final int M = pprefs.size(); 5138 for (int i=0; i<M; i++) { 5139 final PersistentPreferredActivity ppa = pprefs.get(i); 5140 if (DEBUG_PREFERRED || debug) { 5141 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5142 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5143 + "\n component=" + ppa.mComponent); 5144 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5145 } 5146 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5147 flags | MATCH_DISABLED_COMPONENTS, userId); 5148 if (DEBUG_PREFERRED || debug) { 5149 Slog.v(TAG, "Found persistent preferred activity:"); 5150 if (ai != null) { 5151 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5152 } else { 5153 Slog.v(TAG, " null"); 5154 } 5155 } 5156 if (ai == null) { 5157 // This previously registered persistent preferred activity 5158 // component is no longer known. Ignore it and do NOT remove it. 5159 continue; 5160 } 5161 for (int j=0; j<N; j++) { 5162 final ResolveInfo ri = query.get(j); 5163 if (!ri.activityInfo.applicationInfo.packageName 5164 .equals(ai.applicationInfo.packageName)) { 5165 continue; 5166 } 5167 if (!ri.activityInfo.name.equals(ai.name)) { 5168 continue; 5169 } 5170 // Found a persistent preference that can handle the intent. 5171 if (DEBUG_PREFERRED || debug) { 5172 Slog.v(TAG, "Returning persistent preferred activity: " + 5173 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5174 } 5175 return ri; 5176 } 5177 } 5178 } 5179 return null; 5180 } 5181 5182 // TODO: handle preferred activities missing while user has amnesia 5183 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5184 List<ResolveInfo> query, int priority, boolean always, 5185 boolean removeMatches, boolean debug, int userId) { 5186 if (!sUserManager.exists(userId)) return null; 5187 flags = updateFlagsForResolve(flags, userId, intent); 5188 // writer 5189 synchronized (mPackages) { 5190 if (intent.getSelector() != null) { 5191 intent = intent.getSelector(); 5192 } 5193 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5194 5195 // Try to find a matching persistent preferred activity. 5196 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5197 debug, userId); 5198 5199 // If a persistent preferred activity matched, use it. 5200 if (pri != null) { 5201 return pri; 5202 } 5203 5204 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5205 // Get the list of preferred activities that handle the intent 5206 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5207 List<PreferredActivity> prefs = pir != null 5208 ? pir.queryIntent(intent, resolvedType, 5209 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5210 : null; 5211 if (prefs != null && prefs.size() > 0) { 5212 boolean changed = false; 5213 try { 5214 // First figure out how good the original match set is. 5215 // We will only allow preferred activities that came 5216 // from the same match quality. 5217 int match = 0; 5218 5219 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5220 5221 final int N = query.size(); 5222 for (int j=0; j<N; j++) { 5223 final ResolveInfo ri = query.get(j); 5224 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5225 + ": 0x" + Integer.toHexString(match)); 5226 if (ri.match > match) { 5227 match = ri.match; 5228 } 5229 } 5230 5231 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5232 + Integer.toHexString(match)); 5233 5234 match &= IntentFilter.MATCH_CATEGORY_MASK; 5235 final int M = prefs.size(); 5236 for (int i=0; i<M; i++) { 5237 final PreferredActivity pa = prefs.get(i); 5238 if (DEBUG_PREFERRED || debug) { 5239 Slog.v(TAG, "Checking PreferredActivity ds=" 5240 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5241 + "\n component=" + pa.mPref.mComponent); 5242 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5243 } 5244 if (pa.mPref.mMatch != match) { 5245 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5246 + Integer.toHexString(pa.mPref.mMatch)); 5247 continue; 5248 } 5249 // If it's not an "always" type preferred activity and that's what we're 5250 // looking for, skip it. 5251 if (always && !pa.mPref.mAlways) { 5252 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5253 continue; 5254 } 5255 final ActivityInfo ai = getActivityInfo( 5256 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5257 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5258 userId); 5259 if (DEBUG_PREFERRED || debug) { 5260 Slog.v(TAG, "Found preferred activity:"); 5261 if (ai != null) { 5262 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5263 } else { 5264 Slog.v(TAG, " null"); 5265 } 5266 } 5267 if (ai == null) { 5268 // This previously registered preferred activity 5269 // component is no longer known. Most likely an update 5270 // to the app was installed and in the new version this 5271 // component no longer exists. Clean it up by removing 5272 // it from the preferred activities list, and skip it. 5273 Slog.w(TAG, "Removing dangling preferred activity: " 5274 + pa.mPref.mComponent); 5275 pir.removeFilter(pa); 5276 changed = true; 5277 continue; 5278 } 5279 for (int j=0; j<N; j++) { 5280 final ResolveInfo ri = query.get(j); 5281 if (!ri.activityInfo.applicationInfo.packageName 5282 .equals(ai.applicationInfo.packageName)) { 5283 continue; 5284 } 5285 if (!ri.activityInfo.name.equals(ai.name)) { 5286 continue; 5287 } 5288 5289 if (removeMatches) { 5290 pir.removeFilter(pa); 5291 changed = true; 5292 if (DEBUG_PREFERRED) { 5293 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5294 } 5295 break; 5296 } 5297 5298 // Okay we found a previously set preferred or last chosen app. 5299 // If the result set is different from when this 5300 // was created, we need to clear it and re-ask the 5301 // user their preference, if we're looking for an "always" type entry. 5302 if (always && !pa.mPref.sameSet(query)) { 5303 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5304 + intent + " type " + resolvedType); 5305 if (DEBUG_PREFERRED) { 5306 Slog.v(TAG, "Removing preferred activity since set changed " 5307 + pa.mPref.mComponent); 5308 } 5309 pir.removeFilter(pa); 5310 // Re-add the filter as a "last chosen" entry (!always) 5311 PreferredActivity lastChosen = new PreferredActivity( 5312 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5313 pir.addFilter(lastChosen); 5314 changed = true; 5315 return null; 5316 } 5317 5318 // Yay! Either the set matched or we're looking for the last chosen 5319 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5320 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5321 return ri; 5322 } 5323 } 5324 } finally { 5325 if (changed) { 5326 if (DEBUG_PREFERRED) { 5327 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5328 } 5329 scheduleWritePackageRestrictionsLocked(userId); 5330 } 5331 } 5332 } 5333 } 5334 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5335 return null; 5336 } 5337 5338 /* 5339 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5340 */ 5341 @Override 5342 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5343 int targetUserId) { 5344 mContext.enforceCallingOrSelfPermission( 5345 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5346 List<CrossProfileIntentFilter> matches = 5347 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5348 if (matches != null) { 5349 int size = matches.size(); 5350 for (int i = 0; i < size; i++) { 5351 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5352 } 5353 } 5354 if (hasWebURI(intent)) { 5355 // cross-profile app linking works only towards the parent. 5356 final UserInfo parent = getProfileParent(sourceUserId); 5357 synchronized(mPackages) { 5358 int flags = updateFlagsForResolve(0, parent.id, intent); 5359 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5360 intent, resolvedType, flags, sourceUserId, parent.id); 5361 return xpDomainInfo != null; 5362 } 5363 } 5364 return false; 5365 } 5366 5367 private UserInfo getProfileParent(int userId) { 5368 final long identity = Binder.clearCallingIdentity(); 5369 try { 5370 return sUserManager.getProfileParent(userId); 5371 } finally { 5372 Binder.restoreCallingIdentity(identity); 5373 } 5374 } 5375 5376 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5377 String resolvedType, int userId) { 5378 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5379 if (resolver != null) { 5380 return resolver.queryIntent(intent, resolvedType, false, userId); 5381 } 5382 return null; 5383 } 5384 5385 @Override 5386 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5387 String resolvedType, int flags, int userId) { 5388 try { 5389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5390 5391 return new ParceledListSlice<>( 5392 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5393 } finally { 5394 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5395 } 5396 } 5397 5398 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5399 String resolvedType, int flags, int userId) { 5400 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5401 flags = updateFlagsForResolve(flags, userId, intent); 5402 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5403 false /* requireFullPermission */, false /* checkShell */, 5404 "query intent activities"); 5405 ComponentName comp = intent.getComponent(); 5406 if (comp == null) { 5407 if (intent.getSelector() != null) { 5408 intent = intent.getSelector(); 5409 comp = intent.getComponent(); 5410 } 5411 } 5412 5413 if (comp != null) { 5414 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5415 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5416 if (ai != null) { 5417 final ResolveInfo ri = new ResolveInfo(); 5418 ri.activityInfo = ai; 5419 list.add(ri); 5420 } 5421 return list; 5422 } 5423 5424 // reader 5425 synchronized (mPackages) { 5426 final String pkgName = intent.getPackage(); 5427 if (pkgName == null) { 5428 List<CrossProfileIntentFilter> matchingFilters = 5429 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5430 // Check for results that need to skip the current profile. 5431 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5432 resolvedType, flags, userId); 5433 if (xpResolveInfo != null) { 5434 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5435 result.add(xpResolveInfo); 5436 return filterIfNotSystemUser(result, userId); 5437 } 5438 5439 // Check for results in the current profile. 5440 List<ResolveInfo> result = mActivities.queryIntent( 5441 intent, resolvedType, flags, userId); 5442 result = filterIfNotSystemUser(result, userId); 5443 5444 // Check for cross profile results. 5445 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5446 xpResolveInfo = queryCrossProfileIntents( 5447 matchingFilters, intent, resolvedType, flags, userId, 5448 hasNonNegativePriorityResult); 5449 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5450 boolean isVisibleToUser = filterIfNotSystemUser( 5451 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5452 if (isVisibleToUser) { 5453 result.add(xpResolveInfo); 5454 Collections.sort(result, mResolvePrioritySorter); 5455 } 5456 } 5457 if (hasWebURI(intent)) { 5458 CrossProfileDomainInfo xpDomainInfo = null; 5459 final UserInfo parent = getProfileParent(userId); 5460 if (parent != null) { 5461 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5462 flags, userId, parent.id); 5463 } 5464 if (xpDomainInfo != null) { 5465 if (xpResolveInfo != null) { 5466 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5467 // in the result. 5468 result.remove(xpResolveInfo); 5469 } 5470 if (result.size() == 0) { 5471 result.add(xpDomainInfo.resolveInfo); 5472 return result; 5473 } 5474 } else if (result.size() <= 1) { 5475 return result; 5476 } 5477 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5478 xpDomainInfo, userId); 5479 Collections.sort(result, mResolvePrioritySorter); 5480 } 5481 return result; 5482 } 5483 final PackageParser.Package pkg = mPackages.get(pkgName); 5484 if (pkg != null) { 5485 return filterIfNotSystemUser( 5486 mActivities.queryIntentForPackage( 5487 intent, resolvedType, flags, pkg.activities, userId), 5488 userId); 5489 } 5490 return new ArrayList<ResolveInfo>(); 5491 } 5492 } 5493 5494 private static class CrossProfileDomainInfo { 5495 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5496 ResolveInfo resolveInfo; 5497 /* Best domain verification status of the activities found in the other profile */ 5498 int bestDomainVerificationStatus; 5499 } 5500 5501 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5502 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5503 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5504 sourceUserId)) { 5505 return null; 5506 } 5507 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5508 resolvedType, flags, parentUserId); 5509 5510 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5511 return null; 5512 } 5513 CrossProfileDomainInfo result = null; 5514 int size = resultTargetUser.size(); 5515 for (int i = 0; i < size; i++) { 5516 ResolveInfo riTargetUser = resultTargetUser.get(i); 5517 // Intent filter verification is only for filters that specify a host. So don't return 5518 // those that handle all web uris. 5519 if (riTargetUser.handleAllWebDataURI) { 5520 continue; 5521 } 5522 String packageName = riTargetUser.activityInfo.packageName; 5523 PackageSetting ps = mSettings.mPackages.get(packageName); 5524 if (ps == null) { 5525 continue; 5526 } 5527 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5528 int status = (int)(verificationState >> 32); 5529 if (result == null) { 5530 result = new CrossProfileDomainInfo(); 5531 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5532 sourceUserId, parentUserId); 5533 result.bestDomainVerificationStatus = status; 5534 } else { 5535 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5536 result.bestDomainVerificationStatus); 5537 } 5538 } 5539 // Don't consider matches with status NEVER across profiles. 5540 if (result != null && result.bestDomainVerificationStatus 5541 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5542 return null; 5543 } 5544 return result; 5545 } 5546 5547 /** 5548 * Verification statuses are ordered from the worse to the best, except for 5549 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5550 */ 5551 private int bestDomainVerificationStatus(int status1, int status2) { 5552 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5553 return status2; 5554 } 5555 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5556 return status1; 5557 } 5558 return (int) MathUtils.max(status1, status2); 5559 } 5560 5561 private boolean isUserEnabled(int userId) { 5562 long callingId = Binder.clearCallingIdentity(); 5563 try { 5564 UserInfo userInfo = sUserManager.getUserInfo(userId); 5565 return userInfo != null && userInfo.isEnabled(); 5566 } finally { 5567 Binder.restoreCallingIdentity(callingId); 5568 } 5569 } 5570 5571 /** 5572 * Filter out activities with systemUserOnly flag set, when current user is not System. 5573 * 5574 * @return filtered list 5575 */ 5576 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5577 if (userId == UserHandle.USER_SYSTEM) { 5578 return resolveInfos; 5579 } 5580 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5581 ResolveInfo info = resolveInfos.get(i); 5582 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5583 resolveInfos.remove(i); 5584 } 5585 } 5586 return resolveInfos; 5587 } 5588 5589 /** 5590 * @param resolveInfos list of resolve infos in descending priority order 5591 * @return if the list contains a resolve info with non-negative priority 5592 */ 5593 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5594 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5595 } 5596 5597 private static boolean hasWebURI(Intent intent) { 5598 if (intent.getData() == null) { 5599 return false; 5600 } 5601 final String scheme = intent.getScheme(); 5602 if (TextUtils.isEmpty(scheme)) { 5603 return false; 5604 } 5605 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5606 } 5607 5608 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5609 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5610 int userId) { 5611 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5612 5613 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5614 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5615 candidates.size()); 5616 } 5617 5618 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5619 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5620 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5621 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5622 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5623 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5624 5625 synchronized (mPackages) { 5626 final int count = candidates.size(); 5627 // First, try to use linked apps. Partition the candidates into four lists: 5628 // one for the final results, one for the "do not use ever", one for "undefined status" 5629 // and finally one for "browser app type". 5630 for (int n=0; n<count; n++) { 5631 ResolveInfo info = candidates.get(n); 5632 String packageName = info.activityInfo.packageName; 5633 PackageSetting ps = mSettings.mPackages.get(packageName); 5634 if (ps != null) { 5635 // Add to the special match all list (Browser use case) 5636 if (info.handleAllWebDataURI) { 5637 matchAllList.add(info); 5638 continue; 5639 } 5640 // Try to get the status from User settings first 5641 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5642 int status = (int)(packedStatus >> 32); 5643 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5644 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5645 if (DEBUG_DOMAIN_VERIFICATION) { 5646 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5647 + " : linkgen=" + linkGeneration); 5648 } 5649 // Use link-enabled generation as preferredOrder, i.e. 5650 // prefer newly-enabled over earlier-enabled. 5651 info.preferredOrder = linkGeneration; 5652 alwaysList.add(info); 5653 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5654 if (DEBUG_DOMAIN_VERIFICATION) { 5655 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5656 } 5657 neverList.add(info); 5658 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5659 if (DEBUG_DOMAIN_VERIFICATION) { 5660 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5661 } 5662 alwaysAskList.add(info); 5663 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5664 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5665 if (DEBUG_DOMAIN_VERIFICATION) { 5666 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5667 } 5668 undefinedList.add(info); 5669 } 5670 } 5671 } 5672 5673 // We'll want to include browser possibilities in a few cases 5674 boolean includeBrowser = false; 5675 5676 // First try to add the "always" resolution(s) for the current user, if any 5677 if (alwaysList.size() > 0) { 5678 result.addAll(alwaysList); 5679 } else { 5680 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5681 result.addAll(undefinedList); 5682 // Maybe add one for the other profile. 5683 if (xpDomainInfo != null && ( 5684 xpDomainInfo.bestDomainVerificationStatus 5685 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5686 result.add(xpDomainInfo.resolveInfo); 5687 } 5688 includeBrowser = true; 5689 } 5690 5691 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5692 // If there were 'always' entries their preferred order has been set, so we also 5693 // back that off to make the alternatives equivalent 5694 if (alwaysAskList.size() > 0) { 5695 for (ResolveInfo i : result) { 5696 i.preferredOrder = 0; 5697 } 5698 result.addAll(alwaysAskList); 5699 includeBrowser = true; 5700 } 5701 5702 if (includeBrowser) { 5703 // Also add browsers (all of them or only the default one) 5704 if (DEBUG_DOMAIN_VERIFICATION) { 5705 Slog.v(TAG, " ...including browsers in candidate set"); 5706 } 5707 if ((matchFlags & MATCH_ALL) != 0) { 5708 result.addAll(matchAllList); 5709 } else { 5710 // Browser/generic handling case. If there's a default browser, go straight 5711 // to that (but only if there is no other higher-priority match). 5712 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5713 int maxMatchPrio = 0; 5714 ResolveInfo defaultBrowserMatch = null; 5715 final int numCandidates = matchAllList.size(); 5716 for (int n = 0; n < numCandidates; n++) { 5717 ResolveInfo info = matchAllList.get(n); 5718 // track the highest overall match priority... 5719 if (info.priority > maxMatchPrio) { 5720 maxMatchPrio = info.priority; 5721 } 5722 // ...and the highest-priority default browser match 5723 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5724 if (defaultBrowserMatch == null 5725 || (defaultBrowserMatch.priority < info.priority)) { 5726 if (debug) { 5727 Slog.v(TAG, "Considering default browser match " + info); 5728 } 5729 defaultBrowserMatch = info; 5730 } 5731 } 5732 } 5733 if (defaultBrowserMatch != null 5734 && defaultBrowserMatch.priority >= maxMatchPrio 5735 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5736 { 5737 if (debug) { 5738 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5739 } 5740 result.add(defaultBrowserMatch); 5741 } else { 5742 result.addAll(matchAllList); 5743 } 5744 } 5745 5746 // If there is nothing selected, add all candidates and remove the ones that the user 5747 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5748 if (result.size() == 0) { 5749 result.addAll(candidates); 5750 result.removeAll(neverList); 5751 } 5752 } 5753 } 5754 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5755 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5756 result.size()); 5757 for (ResolveInfo info : result) { 5758 Slog.v(TAG, " + " + info.activityInfo); 5759 } 5760 } 5761 return result; 5762 } 5763 5764 // Returns a packed value as a long: 5765 // 5766 // high 'int'-sized word: link status: undefined/ask/never/always. 5767 // low 'int'-sized word: relative priority among 'always' results. 5768 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5769 long result = ps.getDomainVerificationStatusForUser(userId); 5770 // if none available, get the master status 5771 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5772 if (ps.getIntentFilterVerificationInfo() != null) { 5773 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5774 } 5775 } 5776 return result; 5777 } 5778 5779 private ResolveInfo querySkipCurrentProfileIntents( 5780 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5781 int flags, int sourceUserId) { 5782 if (matchingFilters != null) { 5783 int size = matchingFilters.size(); 5784 for (int i = 0; i < size; i ++) { 5785 CrossProfileIntentFilter filter = matchingFilters.get(i); 5786 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5787 // Checking if there are activities in the target user that can handle the 5788 // intent. 5789 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5790 resolvedType, flags, sourceUserId); 5791 if (resolveInfo != null) { 5792 return resolveInfo; 5793 } 5794 } 5795 } 5796 } 5797 return null; 5798 } 5799 5800 // Return matching ResolveInfo in target user if any. 5801 private ResolveInfo queryCrossProfileIntents( 5802 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5803 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5804 if (matchingFilters != null) { 5805 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5806 // match the same intent. For performance reasons, it is better not to 5807 // run queryIntent twice for the same userId 5808 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5809 int size = matchingFilters.size(); 5810 for (int i = 0; i < size; i++) { 5811 CrossProfileIntentFilter filter = matchingFilters.get(i); 5812 int targetUserId = filter.getTargetUserId(); 5813 boolean skipCurrentProfile = 5814 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5815 boolean skipCurrentProfileIfNoMatchFound = 5816 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5817 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5818 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5819 // Checking if there are activities in the target user that can handle the 5820 // intent. 5821 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5822 resolvedType, flags, sourceUserId); 5823 if (resolveInfo != null) return resolveInfo; 5824 alreadyTriedUserIds.put(targetUserId, true); 5825 } 5826 } 5827 } 5828 return null; 5829 } 5830 5831 /** 5832 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5833 * will forward the intent to the filter's target user. 5834 * Otherwise, returns null. 5835 */ 5836 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5837 String resolvedType, int flags, int sourceUserId) { 5838 int targetUserId = filter.getTargetUserId(); 5839 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5840 resolvedType, flags, targetUserId); 5841 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5842 // If all the matches in the target profile are suspended, return null. 5843 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5844 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5845 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5846 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5847 targetUserId); 5848 } 5849 } 5850 } 5851 return null; 5852 } 5853 5854 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5855 int sourceUserId, int targetUserId) { 5856 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5857 long ident = Binder.clearCallingIdentity(); 5858 boolean targetIsProfile; 5859 try { 5860 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5861 } finally { 5862 Binder.restoreCallingIdentity(ident); 5863 } 5864 String className; 5865 if (targetIsProfile) { 5866 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5867 } else { 5868 className = FORWARD_INTENT_TO_PARENT; 5869 } 5870 ComponentName forwardingActivityComponentName = new ComponentName( 5871 mAndroidApplication.packageName, className); 5872 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5873 sourceUserId); 5874 if (!targetIsProfile) { 5875 forwardingActivityInfo.showUserIcon = targetUserId; 5876 forwardingResolveInfo.noResourceId = true; 5877 } 5878 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5879 forwardingResolveInfo.priority = 0; 5880 forwardingResolveInfo.preferredOrder = 0; 5881 forwardingResolveInfo.match = 0; 5882 forwardingResolveInfo.isDefault = true; 5883 forwardingResolveInfo.filter = filter; 5884 forwardingResolveInfo.targetUserId = targetUserId; 5885 return forwardingResolveInfo; 5886 } 5887 5888 @Override 5889 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5890 Intent[] specifics, String[] specificTypes, Intent intent, 5891 String resolvedType, int flags, int userId) { 5892 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5893 specificTypes, intent, resolvedType, flags, userId)); 5894 } 5895 5896 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5897 Intent[] specifics, String[] specificTypes, Intent intent, 5898 String resolvedType, int flags, int userId) { 5899 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5900 flags = updateFlagsForResolve(flags, userId, intent); 5901 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5902 false /* requireFullPermission */, false /* checkShell */, 5903 "query intent activity options"); 5904 final String resultsAction = intent.getAction(); 5905 5906 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5907 | PackageManager.GET_RESOLVED_FILTER, userId); 5908 5909 if (DEBUG_INTENT_MATCHING) { 5910 Log.v(TAG, "Query " + intent + ": " + results); 5911 } 5912 5913 int specificsPos = 0; 5914 int N; 5915 5916 // todo: note that the algorithm used here is O(N^2). This 5917 // isn't a problem in our current environment, but if we start running 5918 // into situations where we have more than 5 or 10 matches then this 5919 // should probably be changed to something smarter... 5920 5921 // First we go through and resolve each of the specific items 5922 // that were supplied, taking care of removing any corresponding 5923 // duplicate items in the generic resolve list. 5924 if (specifics != null) { 5925 for (int i=0; i<specifics.length; i++) { 5926 final Intent sintent = specifics[i]; 5927 if (sintent == null) { 5928 continue; 5929 } 5930 5931 if (DEBUG_INTENT_MATCHING) { 5932 Log.v(TAG, "Specific #" + i + ": " + sintent); 5933 } 5934 5935 String action = sintent.getAction(); 5936 if (resultsAction != null && resultsAction.equals(action)) { 5937 // If this action was explicitly requested, then don't 5938 // remove things that have it. 5939 action = null; 5940 } 5941 5942 ResolveInfo ri = null; 5943 ActivityInfo ai = null; 5944 5945 ComponentName comp = sintent.getComponent(); 5946 if (comp == null) { 5947 ri = resolveIntent( 5948 sintent, 5949 specificTypes != null ? specificTypes[i] : null, 5950 flags, userId); 5951 if (ri == null) { 5952 continue; 5953 } 5954 if (ri == mResolveInfo) { 5955 // ACK! Must do something better with this. 5956 } 5957 ai = ri.activityInfo; 5958 comp = new ComponentName(ai.applicationInfo.packageName, 5959 ai.name); 5960 } else { 5961 ai = getActivityInfo(comp, flags, userId); 5962 if (ai == null) { 5963 continue; 5964 } 5965 } 5966 5967 // Look for any generic query activities that are duplicates 5968 // of this specific one, and remove them from the results. 5969 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5970 N = results.size(); 5971 int j; 5972 for (j=specificsPos; j<N; j++) { 5973 ResolveInfo sri = results.get(j); 5974 if ((sri.activityInfo.name.equals(comp.getClassName()) 5975 && sri.activityInfo.applicationInfo.packageName.equals( 5976 comp.getPackageName())) 5977 || (action != null && sri.filter.matchAction(action))) { 5978 results.remove(j); 5979 if (DEBUG_INTENT_MATCHING) Log.v( 5980 TAG, "Removing duplicate item from " + j 5981 + " due to specific " + specificsPos); 5982 if (ri == null) { 5983 ri = sri; 5984 } 5985 j--; 5986 N--; 5987 } 5988 } 5989 5990 // Add this specific item to its proper place. 5991 if (ri == null) { 5992 ri = new ResolveInfo(); 5993 ri.activityInfo = ai; 5994 } 5995 results.add(specificsPos, ri); 5996 ri.specificIndex = i; 5997 specificsPos++; 5998 } 5999 } 6000 6001 // Now we go through the remaining generic results and remove any 6002 // duplicate actions that are found here. 6003 N = results.size(); 6004 for (int i=specificsPos; i<N-1; i++) { 6005 final ResolveInfo rii = results.get(i); 6006 if (rii.filter == null) { 6007 continue; 6008 } 6009 6010 // Iterate over all of the actions of this result's intent 6011 // filter... typically this should be just one. 6012 final Iterator<String> it = rii.filter.actionsIterator(); 6013 if (it == null) { 6014 continue; 6015 } 6016 while (it.hasNext()) { 6017 final String action = it.next(); 6018 if (resultsAction != null && resultsAction.equals(action)) { 6019 // If this action was explicitly requested, then don't 6020 // remove things that have it. 6021 continue; 6022 } 6023 for (int j=i+1; j<N; j++) { 6024 final ResolveInfo rij = results.get(j); 6025 if (rij.filter != null && rij.filter.hasAction(action)) { 6026 results.remove(j); 6027 if (DEBUG_INTENT_MATCHING) Log.v( 6028 TAG, "Removing duplicate item from " + j 6029 + " due to action " + action + " at " + i); 6030 j--; 6031 N--; 6032 } 6033 } 6034 } 6035 6036 // If the caller didn't request filter information, drop it now 6037 // so we don't have to marshall/unmarshall it. 6038 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6039 rii.filter = null; 6040 } 6041 } 6042 6043 // Filter out the caller activity if so requested. 6044 if (caller != null) { 6045 N = results.size(); 6046 for (int i=0; i<N; i++) { 6047 ActivityInfo ainfo = results.get(i).activityInfo; 6048 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 6049 && caller.getClassName().equals(ainfo.name)) { 6050 results.remove(i); 6051 break; 6052 } 6053 } 6054 } 6055 6056 // If the caller didn't request filter information, 6057 // drop them now so we don't have to 6058 // marshall/unmarshall it. 6059 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 6060 N = results.size(); 6061 for (int i=0; i<N; i++) { 6062 results.get(i).filter = null; 6063 } 6064 } 6065 6066 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6067 return results; 6068 } 6069 6070 @Override 6071 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6072 String resolvedType, int flags, int userId) { 6073 return new ParceledListSlice<>( 6074 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6075 } 6076 6077 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6078 String resolvedType, int flags, int userId) { 6079 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6080 flags = updateFlagsForResolve(flags, userId, intent); 6081 ComponentName comp = intent.getComponent(); 6082 if (comp == null) { 6083 if (intent.getSelector() != null) { 6084 intent = intent.getSelector(); 6085 comp = intent.getComponent(); 6086 } 6087 } 6088 if (comp != null) { 6089 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6090 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6091 if (ai != null) { 6092 ResolveInfo ri = new ResolveInfo(); 6093 ri.activityInfo = ai; 6094 list.add(ri); 6095 } 6096 return list; 6097 } 6098 6099 // reader 6100 synchronized (mPackages) { 6101 String pkgName = intent.getPackage(); 6102 if (pkgName == null) { 6103 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6104 } 6105 final PackageParser.Package pkg = mPackages.get(pkgName); 6106 if (pkg != null) { 6107 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6108 userId); 6109 } 6110 return Collections.emptyList(); 6111 } 6112 } 6113 6114 @Override 6115 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6116 if (!sUserManager.exists(userId)) return null; 6117 flags = updateFlagsForResolve(flags, userId, intent); 6118 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6119 if (query != null) { 6120 if (query.size() >= 1) { 6121 // If there is more than one service with the same priority, 6122 // just arbitrarily pick the first one. 6123 return query.get(0); 6124 } 6125 } 6126 return null; 6127 } 6128 6129 @Override 6130 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6131 String resolvedType, int flags, int userId) { 6132 return new ParceledListSlice<>( 6133 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6134 } 6135 6136 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6137 String resolvedType, int flags, int userId) { 6138 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6139 flags = updateFlagsForResolve(flags, userId, intent); 6140 ComponentName comp = intent.getComponent(); 6141 if (comp == null) { 6142 if (intent.getSelector() != null) { 6143 intent = intent.getSelector(); 6144 comp = intent.getComponent(); 6145 } 6146 } 6147 if (comp != null) { 6148 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6149 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6150 if (si != null) { 6151 final ResolveInfo ri = new ResolveInfo(); 6152 ri.serviceInfo = si; 6153 list.add(ri); 6154 } 6155 return list; 6156 } 6157 6158 // reader 6159 synchronized (mPackages) { 6160 String pkgName = intent.getPackage(); 6161 if (pkgName == null) { 6162 return mServices.queryIntent(intent, resolvedType, flags, userId); 6163 } 6164 final PackageParser.Package pkg = mPackages.get(pkgName); 6165 if (pkg != null) { 6166 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6167 userId); 6168 } 6169 return Collections.emptyList(); 6170 } 6171 } 6172 6173 @Override 6174 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6175 String resolvedType, int flags, int userId) { 6176 return new ParceledListSlice<>( 6177 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6178 } 6179 6180 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6181 Intent intent, String resolvedType, int flags, int userId) { 6182 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6183 flags = updateFlagsForResolve(flags, userId, intent); 6184 ComponentName comp = intent.getComponent(); 6185 if (comp == null) { 6186 if (intent.getSelector() != null) { 6187 intent = intent.getSelector(); 6188 comp = intent.getComponent(); 6189 } 6190 } 6191 if (comp != null) { 6192 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6193 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6194 if (pi != null) { 6195 final ResolveInfo ri = new ResolveInfo(); 6196 ri.providerInfo = pi; 6197 list.add(ri); 6198 } 6199 return list; 6200 } 6201 6202 // reader 6203 synchronized (mPackages) { 6204 String pkgName = intent.getPackage(); 6205 if (pkgName == null) { 6206 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6207 } 6208 final PackageParser.Package pkg = mPackages.get(pkgName); 6209 if (pkg != null) { 6210 return mProviders.queryIntentForPackage( 6211 intent, resolvedType, flags, pkg.providers, userId); 6212 } 6213 return Collections.emptyList(); 6214 } 6215 } 6216 6217 @Override 6218 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6219 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6220 flags = updateFlagsForPackage(flags, userId, null); 6221 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6222 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6223 true /* requireFullPermission */, false /* checkShell */, 6224 "get installed packages"); 6225 6226 // writer 6227 synchronized (mPackages) { 6228 ArrayList<PackageInfo> list; 6229 if (listUninstalled) { 6230 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6231 for (PackageSetting ps : mSettings.mPackages.values()) { 6232 final PackageInfo pi; 6233 if (ps.pkg != null) { 6234 pi = generatePackageInfo(ps, flags, userId); 6235 } else { 6236 pi = generatePackageInfo(ps, flags, userId); 6237 } 6238 if (pi != null) { 6239 list.add(pi); 6240 } 6241 } 6242 } else { 6243 list = new ArrayList<PackageInfo>(mPackages.size()); 6244 for (PackageParser.Package p : mPackages.values()) { 6245 final PackageInfo pi = 6246 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6247 if (pi != null) { 6248 list.add(pi); 6249 } 6250 } 6251 } 6252 6253 return new ParceledListSlice<PackageInfo>(list); 6254 } 6255 } 6256 6257 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6258 String[] permissions, boolean[] tmp, int flags, int userId) { 6259 int numMatch = 0; 6260 final PermissionsState permissionsState = ps.getPermissionsState(); 6261 for (int i=0; i<permissions.length; i++) { 6262 final String permission = permissions[i]; 6263 if (permissionsState.hasPermission(permission, userId)) { 6264 tmp[i] = true; 6265 numMatch++; 6266 } else { 6267 tmp[i] = false; 6268 } 6269 } 6270 if (numMatch == 0) { 6271 return; 6272 } 6273 final PackageInfo pi; 6274 if (ps.pkg != null) { 6275 pi = generatePackageInfo(ps, flags, userId); 6276 } else { 6277 pi = generatePackageInfo(ps, flags, userId); 6278 } 6279 // The above might return null in cases of uninstalled apps or install-state 6280 // skew across users/profiles. 6281 if (pi != null) { 6282 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6283 if (numMatch == permissions.length) { 6284 pi.requestedPermissions = permissions; 6285 } else { 6286 pi.requestedPermissions = new String[numMatch]; 6287 numMatch = 0; 6288 for (int i=0; i<permissions.length; i++) { 6289 if (tmp[i]) { 6290 pi.requestedPermissions[numMatch] = permissions[i]; 6291 numMatch++; 6292 } 6293 } 6294 } 6295 } 6296 list.add(pi); 6297 } 6298 } 6299 6300 @Override 6301 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6302 String[] permissions, int flags, int userId) { 6303 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6304 flags = updateFlagsForPackage(flags, userId, permissions); 6305 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6306 6307 // writer 6308 synchronized (mPackages) { 6309 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6310 boolean[] tmpBools = new boolean[permissions.length]; 6311 if (listUninstalled) { 6312 for (PackageSetting ps : mSettings.mPackages.values()) { 6313 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6314 } 6315 } else { 6316 for (PackageParser.Package pkg : mPackages.values()) { 6317 PackageSetting ps = (PackageSetting)pkg.mExtras; 6318 if (ps != null) { 6319 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6320 userId); 6321 } 6322 } 6323 } 6324 6325 return new ParceledListSlice<PackageInfo>(list); 6326 } 6327 } 6328 6329 @Override 6330 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6331 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6332 flags = updateFlagsForApplication(flags, userId, null); 6333 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6334 6335 // writer 6336 synchronized (mPackages) { 6337 ArrayList<ApplicationInfo> list; 6338 if (listUninstalled) { 6339 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6340 for (PackageSetting ps : mSettings.mPackages.values()) { 6341 ApplicationInfo ai; 6342 if (ps.pkg != null) { 6343 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6344 ps.readUserState(userId), userId); 6345 } else { 6346 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6347 } 6348 if (ai != null) { 6349 list.add(ai); 6350 } 6351 } 6352 } else { 6353 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6354 for (PackageParser.Package p : mPackages.values()) { 6355 if (p.mExtras != null) { 6356 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6357 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6358 if (ai != null) { 6359 list.add(ai); 6360 } 6361 } 6362 } 6363 } 6364 6365 return new ParceledListSlice<ApplicationInfo>(list); 6366 } 6367 } 6368 6369 @Override 6370 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6371 if (DISABLE_EPHEMERAL_APPS) { 6372 return null; 6373 } 6374 6375 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6376 "getEphemeralApplications"); 6377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6378 true /* requireFullPermission */, false /* checkShell */, 6379 "getEphemeralApplications"); 6380 synchronized (mPackages) { 6381 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6382 .getEphemeralApplicationsLPw(userId); 6383 if (ephemeralApps != null) { 6384 return new ParceledListSlice<>(ephemeralApps); 6385 } 6386 } 6387 return null; 6388 } 6389 6390 @Override 6391 public boolean isEphemeralApplication(String packageName, int userId) { 6392 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6393 true /* requireFullPermission */, false /* checkShell */, 6394 "isEphemeral"); 6395 if (DISABLE_EPHEMERAL_APPS) { 6396 return false; 6397 } 6398 6399 if (!isCallerSameApp(packageName)) { 6400 return false; 6401 } 6402 synchronized (mPackages) { 6403 PackageParser.Package pkg = mPackages.get(packageName); 6404 if (pkg != null) { 6405 return pkg.applicationInfo.isEphemeralApp(); 6406 } 6407 } 6408 return false; 6409 } 6410 6411 @Override 6412 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6413 if (DISABLE_EPHEMERAL_APPS) { 6414 return null; 6415 } 6416 6417 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6418 true /* requireFullPermission */, false /* checkShell */, 6419 "getCookie"); 6420 if (!isCallerSameApp(packageName)) { 6421 return null; 6422 } 6423 synchronized (mPackages) { 6424 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6425 packageName, userId); 6426 } 6427 } 6428 6429 @Override 6430 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6431 if (DISABLE_EPHEMERAL_APPS) { 6432 return true; 6433 } 6434 6435 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6436 true /* requireFullPermission */, true /* checkShell */, 6437 "setCookie"); 6438 if (!isCallerSameApp(packageName)) { 6439 return false; 6440 } 6441 synchronized (mPackages) { 6442 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6443 packageName, cookie, userId); 6444 } 6445 } 6446 6447 @Override 6448 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6449 if (DISABLE_EPHEMERAL_APPS) { 6450 return null; 6451 } 6452 6453 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6454 "getEphemeralApplicationIcon"); 6455 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6456 true /* requireFullPermission */, false /* checkShell */, 6457 "getEphemeralApplicationIcon"); 6458 synchronized (mPackages) { 6459 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6460 packageName, userId); 6461 } 6462 } 6463 6464 private boolean isCallerSameApp(String packageName) { 6465 PackageParser.Package pkg = mPackages.get(packageName); 6466 return pkg != null 6467 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6468 } 6469 6470 @Override 6471 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6472 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6473 } 6474 6475 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6476 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6477 6478 // reader 6479 synchronized (mPackages) { 6480 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6481 final int userId = UserHandle.getCallingUserId(); 6482 while (i.hasNext()) { 6483 final PackageParser.Package p = i.next(); 6484 if (p.applicationInfo == null) continue; 6485 6486 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6487 && !p.applicationInfo.isDirectBootAware(); 6488 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6489 && p.applicationInfo.isDirectBootAware(); 6490 6491 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6492 && (!mSafeMode || isSystemApp(p)) 6493 && (matchesUnaware || matchesAware)) { 6494 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6495 if (ps != null) { 6496 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6497 ps.readUserState(userId), userId); 6498 if (ai != null) { 6499 finalList.add(ai); 6500 } 6501 } 6502 } 6503 } 6504 } 6505 6506 return finalList; 6507 } 6508 6509 @Override 6510 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6511 if (!sUserManager.exists(userId)) return null; 6512 flags = updateFlagsForComponent(flags, userId, name); 6513 // reader 6514 synchronized (mPackages) { 6515 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6516 PackageSetting ps = provider != null 6517 ? mSettings.mPackages.get(provider.owner.packageName) 6518 : null; 6519 return ps != null 6520 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6521 ? PackageParser.generateProviderInfo(provider, flags, 6522 ps.readUserState(userId), userId) 6523 : null; 6524 } 6525 } 6526 6527 /** 6528 * @deprecated 6529 */ 6530 @Deprecated 6531 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6532 // reader 6533 synchronized (mPackages) { 6534 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6535 .entrySet().iterator(); 6536 final int userId = UserHandle.getCallingUserId(); 6537 while (i.hasNext()) { 6538 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6539 PackageParser.Provider p = entry.getValue(); 6540 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6541 6542 if (ps != null && p.syncable 6543 && (!mSafeMode || (p.info.applicationInfo.flags 6544 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6545 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6546 ps.readUserState(userId), userId); 6547 if (info != null) { 6548 outNames.add(entry.getKey()); 6549 outInfo.add(info); 6550 } 6551 } 6552 } 6553 } 6554 } 6555 6556 @Override 6557 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6558 int uid, int flags) { 6559 final int userId = processName != null ? UserHandle.getUserId(uid) 6560 : UserHandle.getCallingUserId(); 6561 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6562 flags = updateFlagsForComponent(flags, userId, processName); 6563 6564 ArrayList<ProviderInfo> finalList = null; 6565 // reader 6566 synchronized (mPackages) { 6567 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6568 while (i.hasNext()) { 6569 final PackageParser.Provider p = i.next(); 6570 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6571 if (ps != null && p.info.authority != null 6572 && (processName == null 6573 || (p.info.processName.equals(processName) 6574 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6575 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6576 if (finalList == null) { 6577 finalList = new ArrayList<ProviderInfo>(3); 6578 } 6579 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6580 ps.readUserState(userId), userId); 6581 if (info != null) { 6582 finalList.add(info); 6583 } 6584 } 6585 } 6586 } 6587 6588 if (finalList != null) { 6589 Collections.sort(finalList, mProviderInitOrderSorter); 6590 return new ParceledListSlice<ProviderInfo>(finalList); 6591 } 6592 6593 return ParceledListSlice.emptyList(); 6594 } 6595 6596 @Override 6597 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6598 // reader 6599 synchronized (mPackages) { 6600 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6601 return PackageParser.generateInstrumentationInfo(i, flags); 6602 } 6603 } 6604 6605 @Override 6606 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6607 String targetPackage, int flags) { 6608 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6609 } 6610 6611 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6612 int flags) { 6613 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6614 6615 // reader 6616 synchronized (mPackages) { 6617 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6618 while (i.hasNext()) { 6619 final PackageParser.Instrumentation p = i.next(); 6620 if (targetPackage == null 6621 || targetPackage.equals(p.info.targetPackage)) { 6622 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6623 flags); 6624 if (ii != null) { 6625 finalList.add(ii); 6626 } 6627 } 6628 } 6629 } 6630 6631 return finalList; 6632 } 6633 6634 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6635 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6636 if (overlays == null) { 6637 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6638 return; 6639 } 6640 for (PackageParser.Package opkg : overlays.values()) { 6641 // Not much to do if idmap fails: we already logged the error 6642 // and we certainly don't want to abort installation of pkg simply 6643 // because an overlay didn't fit properly. For these reasons, 6644 // ignore the return value of createIdmapForPackagePairLI. 6645 createIdmapForPackagePairLI(pkg, opkg); 6646 } 6647 } 6648 6649 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6650 PackageParser.Package opkg) { 6651 if (!opkg.mTrustedOverlay) { 6652 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6653 opkg.baseCodePath + ": overlay not trusted"); 6654 return false; 6655 } 6656 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6657 if (overlaySet == null) { 6658 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6659 opkg.baseCodePath + " but target package has no known overlays"); 6660 return false; 6661 } 6662 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6663 // TODO: generate idmap for split APKs 6664 try { 6665 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6666 } catch (InstallerException e) { 6667 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6668 + opkg.baseCodePath); 6669 return false; 6670 } 6671 PackageParser.Package[] overlayArray = 6672 overlaySet.values().toArray(new PackageParser.Package[0]); 6673 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6674 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6675 return p1.mOverlayPriority - p2.mOverlayPriority; 6676 } 6677 }; 6678 Arrays.sort(overlayArray, cmp); 6679 6680 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6681 int i = 0; 6682 for (PackageParser.Package p : overlayArray) { 6683 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6684 } 6685 return true; 6686 } 6687 6688 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6689 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6690 try { 6691 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6692 } finally { 6693 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6694 } 6695 } 6696 6697 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6698 final File[] files = dir.listFiles(); 6699 if (ArrayUtils.isEmpty(files)) { 6700 Log.d(TAG, "No files in app dir " + dir); 6701 return; 6702 } 6703 6704 if (DEBUG_PACKAGE_SCANNING) { 6705 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6706 + " flags=0x" + Integer.toHexString(parseFlags)); 6707 } 6708 6709 for (File file : files) { 6710 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6711 && !PackageInstallerService.isStageName(file.getName()); 6712 if (!isPackage) { 6713 // Ignore entries which are not packages 6714 continue; 6715 } 6716 try { 6717 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6718 scanFlags, currentTime, null); 6719 } catch (PackageManagerException e) { 6720 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6721 6722 // Delete invalid userdata apps 6723 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6724 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6725 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6726 removeCodePathLI(file); 6727 } 6728 } 6729 } 6730 } 6731 6732 private static File getSettingsProblemFile() { 6733 File dataDir = Environment.getDataDirectory(); 6734 File systemDir = new File(dataDir, "system"); 6735 File fname = new File(systemDir, "uiderrors.txt"); 6736 return fname; 6737 } 6738 6739 static void reportSettingsProblem(int priority, String msg) { 6740 logCriticalInfo(priority, msg); 6741 } 6742 6743 static void logCriticalInfo(int priority, String msg) { 6744 Slog.println(priority, TAG, msg); 6745 EventLogTags.writePmCriticalInfo(msg); 6746 try { 6747 File fname = getSettingsProblemFile(); 6748 FileOutputStream out = new FileOutputStream(fname, true); 6749 PrintWriter pw = new FastPrintWriter(out); 6750 SimpleDateFormat formatter = new SimpleDateFormat(); 6751 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6752 pw.println(dateString + ": " + msg); 6753 pw.close(); 6754 FileUtils.setPermissions( 6755 fname.toString(), 6756 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6757 -1, -1); 6758 } catch (java.io.IOException e) { 6759 } 6760 } 6761 6762 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6763 final int policyFlags) throws PackageManagerException { 6764 if (ps != null 6765 && ps.codePath.equals(srcFile) 6766 && ps.timeStamp == srcFile.lastModified() 6767 && !isCompatSignatureUpdateNeeded(pkg) 6768 && !isRecoverSignatureUpdateNeeded(pkg)) { 6769 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6770 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6771 ArraySet<PublicKey> signingKs; 6772 synchronized (mPackages) { 6773 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6774 } 6775 if (ps.signatures.mSignatures != null 6776 && ps.signatures.mSignatures.length != 0 6777 && signingKs != null) { 6778 // Optimization: reuse the existing cached certificates 6779 // if the package appears to be unchanged. 6780 pkg.mSignatures = ps.signatures.mSignatures; 6781 pkg.mSigningKeys = signingKs; 6782 return; 6783 } 6784 6785 Slog.w(TAG, "PackageSetting for " + ps.name 6786 + " is missing signatures. Collecting certs again to recover them."); 6787 } else { 6788 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6789 } 6790 6791 try { 6792 PackageParser.collectCertificates(pkg, policyFlags); 6793 } catch (PackageParserException e) { 6794 throw PackageManagerException.from(e); 6795 } 6796 } 6797 6798 /** 6799 * Traces a package scan. 6800 * @see #scanPackageLI(File, int, int, long, UserHandle) 6801 */ 6802 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6803 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6804 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6805 try { 6806 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6807 } finally { 6808 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6809 } 6810 } 6811 6812 /** 6813 * Scans a package and returns the newly parsed package. 6814 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6815 */ 6816 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6817 long currentTime, UserHandle user) throws PackageManagerException { 6818 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6819 PackageParser pp = new PackageParser(); 6820 pp.setSeparateProcesses(mSeparateProcesses); 6821 pp.setOnlyCoreApps(mOnlyCore); 6822 pp.setDisplayMetrics(mMetrics); 6823 6824 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6825 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6826 } 6827 6828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6829 final PackageParser.Package pkg; 6830 try { 6831 pkg = pp.parsePackage(scanFile, parseFlags); 6832 } catch (PackageParserException e) { 6833 throw PackageManagerException.from(e); 6834 } finally { 6835 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6836 } 6837 6838 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6839 } 6840 6841 /** 6842 * Scans a package and returns the newly parsed package. 6843 * @throws PackageManagerException on a parse error. 6844 */ 6845 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6846 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6847 throws PackageManagerException { 6848 // If the package has children and this is the first dive in the function 6849 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6850 // packages (parent and children) would be successfully scanned before the 6851 // actual scan since scanning mutates internal state and we want to atomically 6852 // install the package and its children. 6853 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6854 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6855 scanFlags |= SCAN_CHECK_ONLY; 6856 } 6857 } else { 6858 scanFlags &= ~SCAN_CHECK_ONLY; 6859 } 6860 6861 // Scan the parent 6862 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6863 scanFlags, currentTime, user); 6864 6865 // Scan the children 6866 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6867 for (int i = 0; i < childCount; i++) { 6868 PackageParser.Package childPackage = pkg.childPackages.get(i); 6869 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6870 currentTime, user); 6871 } 6872 6873 6874 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6875 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6876 } 6877 6878 return scannedPkg; 6879 } 6880 6881 /** 6882 * Scans a package and returns the newly parsed package. 6883 * @throws PackageManagerException on a parse error. 6884 */ 6885 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6886 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6887 throws PackageManagerException { 6888 PackageSetting ps = null; 6889 PackageSetting updatedPkg; 6890 // reader 6891 synchronized (mPackages) { 6892 // Look to see if we already know about this package. 6893 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6894 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6895 // This package has been renamed to its original name. Let's 6896 // use that. 6897 ps = mSettings.peekPackageLPr(oldName); 6898 } 6899 // If there was no original package, see one for the real package name. 6900 if (ps == null) { 6901 ps = mSettings.peekPackageLPr(pkg.packageName); 6902 } 6903 // Check to see if this package could be hiding/updating a system 6904 // package. Must look for it either under the original or real 6905 // package name depending on our state. 6906 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6907 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6908 6909 // If this is a package we don't know about on the system partition, we 6910 // may need to remove disabled child packages on the system partition 6911 // or may need to not add child packages if the parent apk is updated 6912 // on the data partition and no longer defines this child package. 6913 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6914 // If this is a parent package for an updated system app and this system 6915 // app got an OTA update which no longer defines some of the child packages 6916 // we have to prune them from the disabled system packages. 6917 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6918 if (disabledPs != null) { 6919 final int scannedChildCount = (pkg.childPackages != null) 6920 ? pkg.childPackages.size() : 0; 6921 final int disabledChildCount = disabledPs.childPackageNames != null 6922 ? disabledPs.childPackageNames.size() : 0; 6923 for (int i = 0; i < disabledChildCount; i++) { 6924 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6925 boolean disabledPackageAvailable = false; 6926 for (int j = 0; j < scannedChildCount; j++) { 6927 PackageParser.Package childPkg = pkg.childPackages.get(j); 6928 if (childPkg.packageName.equals(disabledChildPackageName)) { 6929 disabledPackageAvailable = true; 6930 break; 6931 } 6932 } 6933 if (!disabledPackageAvailable) { 6934 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6935 } 6936 } 6937 } 6938 } 6939 } 6940 6941 boolean updatedPkgBetter = false; 6942 // First check if this is a system package that may involve an update 6943 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6944 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6945 // it needs to drop FLAG_PRIVILEGED. 6946 if (locationIsPrivileged(scanFile)) { 6947 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6948 } else { 6949 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6950 } 6951 6952 if (ps != null && !ps.codePath.equals(scanFile)) { 6953 // The path has changed from what was last scanned... check the 6954 // version of the new path against what we have stored to determine 6955 // what to do. 6956 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6957 if (pkg.mVersionCode <= ps.versionCode) { 6958 // The system package has been updated and the code path does not match 6959 // Ignore entry. Skip it. 6960 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6961 + " ignored: updated version " + ps.versionCode 6962 + " better than this " + pkg.mVersionCode); 6963 if (!updatedPkg.codePath.equals(scanFile)) { 6964 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6965 + ps.name + " changing from " + updatedPkg.codePathString 6966 + " to " + scanFile); 6967 updatedPkg.codePath = scanFile; 6968 updatedPkg.codePathString = scanFile.toString(); 6969 updatedPkg.resourcePath = scanFile; 6970 updatedPkg.resourcePathString = scanFile.toString(); 6971 } 6972 updatedPkg.pkg = pkg; 6973 updatedPkg.versionCode = pkg.mVersionCode; 6974 6975 // Update the disabled system child packages to point to the package too. 6976 final int childCount = updatedPkg.childPackageNames != null 6977 ? updatedPkg.childPackageNames.size() : 0; 6978 for (int i = 0; i < childCount; i++) { 6979 String childPackageName = updatedPkg.childPackageNames.get(i); 6980 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6981 childPackageName); 6982 if (updatedChildPkg != null) { 6983 updatedChildPkg.pkg = pkg; 6984 updatedChildPkg.versionCode = pkg.mVersionCode; 6985 } 6986 } 6987 6988 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6989 + scanFile + " ignored: updated version " + ps.versionCode 6990 + " better than this " + pkg.mVersionCode); 6991 } else { 6992 // The current app on the system partition is better than 6993 // what we have updated to on the data partition; switch 6994 // back to the system partition version. 6995 // At this point, its safely assumed that package installation for 6996 // apps in system partition will go through. If not there won't be a working 6997 // version of the app 6998 // writer 6999 synchronized (mPackages) { 7000 // Just remove the loaded entries from package lists. 7001 mPackages.remove(ps.name); 7002 } 7003 7004 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7005 + " reverting from " + ps.codePathString 7006 + ": new version " + pkg.mVersionCode 7007 + " better than installed " + ps.versionCode); 7008 7009 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7010 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7011 synchronized (mInstallLock) { 7012 args.cleanUpResourcesLI(); 7013 } 7014 synchronized (mPackages) { 7015 mSettings.enableSystemPackageLPw(ps.name); 7016 } 7017 updatedPkgBetter = true; 7018 } 7019 } 7020 } 7021 7022 if (updatedPkg != null) { 7023 // An updated system app will not have the PARSE_IS_SYSTEM flag set 7024 // initially 7025 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 7026 7027 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 7028 // flag set initially 7029 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 7030 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 7031 } 7032 } 7033 7034 // Verify certificates against what was last scanned 7035 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 7036 7037 /* 7038 * A new system app appeared, but we already had a non-system one of the 7039 * same name installed earlier. 7040 */ 7041 boolean shouldHideSystemApp = false; 7042 if (updatedPkg == null && ps != null 7043 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 7044 /* 7045 * Check to make sure the signatures match first. If they don't, 7046 * wipe the installed application and its data. 7047 */ 7048 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 7049 != PackageManager.SIGNATURE_MATCH) { 7050 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 7051 + " signatures don't match existing userdata copy; removing"); 7052 try (PackageFreezer freezer = freezePackage(pkg.packageName, 7053 "scanPackageInternalLI")) { 7054 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 7055 } 7056 ps = null; 7057 } else { 7058 /* 7059 * If the newly-added system app is an older version than the 7060 * already installed version, hide it. It will be scanned later 7061 * and re-added like an update. 7062 */ 7063 if (pkg.mVersionCode <= ps.versionCode) { 7064 shouldHideSystemApp = true; 7065 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7066 + " but new version " + pkg.mVersionCode + " better than installed " 7067 + ps.versionCode + "; hiding system"); 7068 } else { 7069 /* 7070 * The newly found system app is a newer version that the 7071 * one previously installed. Simply remove the 7072 * already-installed application and replace it with our own 7073 * while keeping the application data. 7074 */ 7075 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7076 + " reverting from " + ps.codePathString + ": new version " 7077 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7078 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7079 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7080 synchronized (mInstallLock) { 7081 args.cleanUpResourcesLI(); 7082 } 7083 } 7084 } 7085 } 7086 7087 // The apk is forward locked (not public) if its code and resources 7088 // are kept in different files. (except for app in either system or 7089 // vendor path). 7090 // TODO grab this value from PackageSettings 7091 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7092 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7093 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7094 } 7095 } 7096 7097 // TODO: extend to support forward-locked splits 7098 String resourcePath = null; 7099 String baseResourcePath = null; 7100 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7101 if (ps != null && ps.resourcePathString != null) { 7102 resourcePath = ps.resourcePathString; 7103 baseResourcePath = ps.resourcePathString; 7104 } else { 7105 // Should not happen at all. Just log an error. 7106 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7107 } 7108 } else { 7109 resourcePath = pkg.codePath; 7110 baseResourcePath = pkg.baseCodePath; 7111 } 7112 7113 // Set application objects path explicitly. 7114 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7115 pkg.setApplicationInfoCodePath(pkg.codePath); 7116 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7117 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7118 pkg.setApplicationInfoResourcePath(resourcePath); 7119 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7120 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7121 7122 // Note that we invoke the following method only if we are about to unpack an application 7123 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7124 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7125 7126 /* 7127 * If the system app should be overridden by a previously installed 7128 * data, hide the system app now and let the /data/app scan pick it up 7129 * again. 7130 */ 7131 if (shouldHideSystemApp) { 7132 synchronized (mPackages) { 7133 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7134 } 7135 } 7136 7137 return scannedPkg; 7138 } 7139 7140 private static String fixProcessName(String defProcessName, 7141 String processName, int uid) { 7142 if (processName == null) { 7143 return defProcessName; 7144 } 7145 return processName; 7146 } 7147 7148 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7149 throws PackageManagerException { 7150 if (pkgSetting.signatures.mSignatures != null) { 7151 // Already existing package. Make sure signatures match 7152 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7153 == PackageManager.SIGNATURE_MATCH; 7154 if (!match) { 7155 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7156 == PackageManager.SIGNATURE_MATCH; 7157 } 7158 if (!match) { 7159 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7160 == PackageManager.SIGNATURE_MATCH; 7161 } 7162 if (!match) { 7163 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7164 + pkg.packageName + " signatures do not match the " 7165 + "previously installed version; ignoring!"); 7166 } 7167 } 7168 7169 // Check for shared user signatures 7170 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7171 // Already existing package. Make sure signatures match 7172 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7173 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7174 if (!match) { 7175 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7176 == PackageManager.SIGNATURE_MATCH; 7177 } 7178 if (!match) { 7179 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7180 == PackageManager.SIGNATURE_MATCH; 7181 } 7182 if (!match) { 7183 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7184 "Package " + pkg.packageName 7185 + " has no signatures that match those in shared user " 7186 + pkgSetting.sharedUser.name + "; ignoring!"); 7187 } 7188 } 7189 } 7190 7191 /** 7192 * Enforces that only the system UID or root's UID can call a method exposed 7193 * via Binder. 7194 * 7195 * @param message used as message if SecurityException is thrown 7196 * @throws SecurityException if the caller is not system or root 7197 */ 7198 private static final void enforceSystemOrRoot(String message) { 7199 final int uid = Binder.getCallingUid(); 7200 if (uid != Process.SYSTEM_UID && uid != 0) { 7201 throw new SecurityException(message); 7202 } 7203 } 7204 7205 @Override 7206 public void performFstrimIfNeeded() { 7207 enforceSystemOrRoot("Only the system can request fstrim"); 7208 7209 // Before everything else, see whether we need to fstrim. 7210 try { 7211 IMountService ms = PackageHelper.getMountService(); 7212 if (ms != null) { 7213 final boolean isUpgrade = isUpgrade(); 7214 boolean doTrim = isUpgrade; 7215 if (doTrim) { 7216 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7217 } else { 7218 final long interval = android.provider.Settings.Global.getLong( 7219 mContext.getContentResolver(), 7220 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7221 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7222 if (interval > 0) { 7223 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7224 if (timeSinceLast > interval) { 7225 doTrim = true; 7226 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7227 + "; running immediately"); 7228 } 7229 } 7230 } 7231 if (doTrim) { 7232 if (!isFirstBoot()) { 7233 try { 7234 ActivityManagerNative.getDefault().showBootMessage( 7235 mContext.getResources().getString( 7236 R.string.android_upgrading_fstrim), true); 7237 } catch (RemoteException e) { 7238 } 7239 } 7240 ms.runMaintenance(); 7241 } 7242 } else { 7243 Slog.e(TAG, "Mount service unavailable!"); 7244 } 7245 } catch (RemoteException e) { 7246 // Can't happen; MountService is local 7247 } 7248 } 7249 7250 @Override 7251 public void updatePackagesIfNeeded() { 7252 enforceSystemOrRoot("Only the system can request package update"); 7253 7254 // We need to re-extract after an OTA. 7255 boolean causeUpgrade = isUpgrade(); 7256 7257 // First boot or factory reset. 7258 // Note: we also handle devices that are upgrading to N right now as if it is their 7259 // first boot, as they do not have profile data. 7260 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7261 7262 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7263 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7264 7265 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7266 return; 7267 } 7268 7269 List<PackageParser.Package> pkgs; 7270 synchronized (mPackages) { 7271 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7272 } 7273 7274 final long startTime = System.nanoTime(); 7275 final int[] stats = performDexOpt(pkgs, mIsPreNUpgrade /* showDialog */, 7276 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT)); 7277 7278 final int elapsedTimeSeconds = 7279 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7280 7281 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", stats[0]); 7282 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", stats[1]); 7283 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", stats[2]); 7284 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7285 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7286 } 7287 7288 /** 7289 * Performs dexopt on the set of packages in {@code packages} and returns an int array 7290 * containing statistics about the invocation. The array consists of three elements, 7291 * which are (in order) {@code numberOfPackagesOptimized}, {@code numberOfPackagesSkipped} 7292 * and {@code numberOfPackagesFailed}. 7293 */ 7294 private int[] performDexOpt(List<PackageParser.Package> pkgs, boolean showDialog, 7295 String compilerFilter) { 7296 7297 int numberOfPackagesVisited = 0; 7298 int numberOfPackagesOptimized = 0; 7299 int numberOfPackagesSkipped = 0; 7300 int numberOfPackagesFailed = 0; 7301 final int numberOfPackagesToDexopt = pkgs.size(); 7302 7303 for (PackageParser.Package pkg : pkgs) { 7304 numberOfPackagesVisited++; 7305 7306 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7307 if (DEBUG_DEXOPT) { 7308 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7309 } 7310 numberOfPackagesSkipped++; 7311 continue; 7312 } 7313 7314 if (DEBUG_DEXOPT) { 7315 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7316 numberOfPackagesToDexopt + ": " + pkg.packageName); 7317 } 7318 7319 if (showDialog) { 7320 try { 7321 ActivityManagerNative.getDefault().showBootMessage( 7322 mContext.getResources().getString(R.string.android_upgrading_apk, 7323 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7324 } catch (RemoteException e) { 7325 } 7326 } 7327 7328 // checkProfiles is false to avoid merging profiles during boot which 7329 // might interfere with background compilation (b/28612421). 7330 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7331 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7332 // trade-off worth doing to save boot time work. 7333 int dexOptStatus = performDexOptTraced(pkg.packageName, 7334 false /* checkProfiles */, 7335 compilerFilter, 7336 false /* force */); 7337 switch (dexOptStatus) { 7338 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7339 numberOfPackagesOptimized++; 7340 break; 7341 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7342 numberOfPackagesSkipped++; 7343 break; 7344 case PackageDexOptimizer.DEX_OPT_FAILED: 7345 numberOfPackagesFailed++; 7346 break; 7347 default: 7348 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7349 break; 7350 } 7351 } 7352 7353 return new int[] { numberOfPackagesOptimized, numberOfPackagesSkipped, 7354 numberOfPackagesFailed }; 7355 } 7356 7357 @Override 7358 public void notifyPackageUse(String packageName, int reason) { 7359 synchronized (mPackages) { 7360 PackageParser.Package p = mPackages.get(packageName); 7361 if (p == null) { 7362 return; 7363 } 7364 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7365 } 7366 } 7367 7368 // TODO: this is not used nor needed. Delete it. 7369 @Override 7370 public boolean performDexOptIfNeeded(String packageName) { 7371 int dexOptStatus = performDexOptTraced(packageName, 7372 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7373 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7374 } 7375 7376 @Override 7377 public boolean performDexOpt(String packageName, 7378 boolean checkProfiles, int compileReason, boolean force) { 7379 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7380 getCompilerFilterForReason(compileReason), force); 7381 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7382 } 7383 7384 @Override 7385 public boolean performDexOptMode(String packageName, 7386 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7387 int dexOptStatus = performDexOptTraced(packageName, checkProfiles, 7388 targetCompilerFilter, force); 7389 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7390 } 7391 7392 private int performDexOptTraced(String packageName, 7393 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7394 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7395 try { 7396 return performDexOptInternal(packageName, checkProfiles, 7397 targetCompilerFilter, force); 7398 } finally { 7399 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7400 } 7401 } 7402 7403 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7404 // if the package can now be considered up to date for the given filter. 7405 private int performDexOptInternal(String packageName, 7406 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7407 PackageParser.Package p; 7408 synchronized (mPackages) { 7409 p = mPackages.get(packageName); 7410 if (p == null) { 7411 // Package could not be found. Report failure. 7412 return PackageDexOptimizer.DEX_OPT_FAILED; 7413 } 7414 mPackageUsage.write(false); 7415 } 7416 long callingId = Binder.clearCallingIdentity(); 7417 try { 7418 synchronized (mInstallLock) { 7419 return performDexOptInternalWithDependenciesLI(p, checkProfiles, 7420 targetCompilerFilter, force); 7421 } 7422 } finally { 7423 Binder.restoreCallingIdentity(callingId); 7424 } 7425 } 7426 7427 public ArraySet<String> getOptimizablePackages() { 7428 ArraySet<String> pkgs = new ArraySet<String>(); 7429 synchronized (mPackages) { 7430 for (PackageParser.Package p : mPackages.values()) { 7431 if (PackageDexOptimizer.canOptimizePackage(p)) { 7432 pkgs.add(p.packageName); 7433 } 7434 } 7435 } 7436 return pkgs; 7437 } 7438 7439 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7440 boolean checkProfiles, String targetCompilerFilter, 7441 boolean force) { 7442 // Select the dex optimizer based on the force parameter. 7443 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7444 // allocate an object here. 7445 PackageDexOptimizer pdo = force 7446 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7447 : mPackageDexOptimizer; 7448 7449 // Optimize all dependencies first. Note: we ignore the return value and march on 7450 // on errors. 7451 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7452 final String[] instructionSets = getAppDexInstructionSets(p.applicationInfo); 7453 if (!deps.isEmpty()) { 7454 for (PackageParser.Package depPackage : deps) { 7455 // TODO: Analyze and investigate if we (should) profile libraries. 7456 // Currently this will do a full compilation of the library by default. 7457 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7458 false /* checkProfiles */, 7459 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7460 } 7461 } 7462 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7463 targetCompilerFilter); 7464 } 7465 7466 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7467 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7468 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7469 Set<String> collectedNames = new HashSet<>(); 7470 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7471 7472 retValue.remove(p); 7473 7474 return retValue; 7475 } else { 7476 return Collections.emptyList(); 7477 } 7478 } 7479 7480 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7481 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7482 if (!collectedNames.contains(p.packageName)) { 7483 collectedNames.add(p.packageName); 7484 collected.add(p); 7485 7486 if (p.usesLibraries != null) { 7487 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7488 } 7489 if (p.usesOptionalLibraries != null) { 7490 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7491 collectedNames); 7492 } 7493 } 7494 } 7495 7496 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7497 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7498 for (String libName : libs) { 7499 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7500 if (libPkg != null) { 7501 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7502 } 7503 } 7504 } 7505 7506 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7507 synchronized (mPackages) { 7508 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7509 if (lib != null && lib.apk != null) { 7510 return mPackages.get(lib.apk); 7511 } 7512 } 7513 return null; 7514 } 7515 7516 public void shutdown() { 7517 mPackageUsage.write(true); 7518 } 7519 7520 @Override 7521 public void dumpProfiles(String packageName) { 7522 PackageParser.Package pkg; 7523 synchronized (mPackages) { 7524 pkg = mPackages.get(packageName); 7525 if (pkg == null) { 7526 throw new IllegalArgumentException("Unknown package: " + packageName); 7527 } 7528 } 7529 /* Only the shell, root, or the app user should be able to dump profiles. */ 7530 int callingUid = Binder.getCallingUid(); 7531 if (callingUid != Process.SHELL_UID && 7532 callingUid != Process.ROOT_UID && 7533 callingUid != pkg.applicationInfo.uid) { 7534 throw new SecurityException("dumpProfiles"); 7535 } 7536 7537 synchronized (mInstallLock) { 7538 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dump profiles"); 7539 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 7540 try { 7541 List<String> allCodePaths = pkg.getAllCodePathsExcludingResourceOnly(); 7542 String gid = Integer.toString(sharedGid); 7543 String codePaths = TextUtils.join(";", allCodePaths); 7544 mInstaller.dumpProfiles(gid, packageName, codePaths); 7545 } catch (InstallerException e) { 7546 Slog.w(TAG, "Failed to dump profiles", e); 7547 } 7548 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7549 } 7550 } 7551 7552 @Override 7553 public void forceDexOpt(String packageName) { 7554 enforceSystemOrRoot("forceDexOpt"); 7555 7556 PackageParser.Package pkg; 7557 synchronized (mPackages) { 7558 pkg = mPackages.get(packageName); 7559 if (pkg == null) { 7560 throw new IllegalArgumentException("Unknown package: " + packageName); 7561 } 7562 } 7563 7564 synchronized (mInstallLock) { 7565 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7566 7567 // Whoever is calling forceDexOpt wants a fully compiled package. 7568 // Don't use profiles since that may cause compilation to be skipped. 7569 final int res = performDexOptInternalWithDependenciesLI(pkg, 7570 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7571 true /* force */); 7572 7573 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7574 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7575 throw new IllegalStateException("Failed to dexopt: " + res); 7576 } 7577 } 7578 } 7579 7580 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7581 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7582 Slog.w(TAG, "Unable to update from " + oldPkg.name 7583 + " to " + newPkg.packageName 7584 + ": old package not in system partition"); 7585 return false; 7586 } else if (mPackages.get(oldPkg.name) != null) { 7587 Slog.w(TAG, "Unable to update from " + oldPkg.name 7588 + " to " + newPkg.packageName 7589 + ": old package still exists"); 7590 return false; 7591 } 7592 return true; 7593 } 7594 7595 void removeCodePathLI(File codePath) { 7596 if (codePath.isDirectory()) { 7597 try { 7598 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7599 } catch (InstallerException e) { 7600 Slog.w(TAG, "Failed to remove code path", e); 7601 } 7602 } else { 7603 codePath.delete(); 7604 } 7605 } 7606 7607 private int[] resolveUserIds(int userId) { 7608 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7609 } 7610 7611 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7612 if (pkg == null) { 7613 Slog.wtf(TAG, "Package was null!", new Throwable()); 7614 return; 7615 } 7616 clearAppDataLeafLIF(pkg, userId, flags); 7617 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7618 for (int i = 0; i < childCount; i++) { 7619 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7620 } 7621 } 7622 7623 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7624 final PackageSetting ps; 7625 synchronized (mPackages) { 7626 ps = mSettings.mPackages.get(pkg.packageName); 7627 } 7628 for (int realUserId : resolveUserIds(userId)) { 7629 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7630 try { 7631 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7632 ceDataInode); 7633 } catch (InstallerException e) { 7634 Slog.w(TAG, String.valueOf(e)); 7635 } 7636 } 7637 } 7638 7639 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7640 if (pkg == null) { 7641 Slog.wtf(TAG, "Package was null!", new Throwable()); 7642 return; 7643 } 7644 destroyAppDataLeafLIF(pkg, userId, flags); 7645 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7646 for (int i = 0; i < childCount; i++) { 7647 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7648 } 7649 } 7650 7651 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7652 final PackageSetting ps; 7653 synchronized (mPackages) { 7654 ps = mSettings.mPackages.get(pkg.packageName); 7655 } 7656 for (int realUserId : resolveUserIds(userId)) { 7657 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7658 try { 7659 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7660 ceDataInode); 7661 } catch (InstallerException e) { 7662 Slog.w(TAG, String.valueOf(e)); 7663 } 7664 } 7665 } 7666 7667 private void destroyAppProfilesLIF(PackageParser.Package pkg, int userId) { 7668 if (pkg == null) { 7669 Slog.wtf(TAG, "Package was null!", new Throwable()); 7670 return; 7671 } 7672 destroyAppProfilesLeafLIF(pkg); 7673 destroyAppReferenceProfileLeafLIF(pkg, userId, true /* removeBaseMarker */); 7674 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7675 for (int i = 0; i < childCount; i++) { 7676 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7677 destroyAppReferenceProfileLeafLIF(pkg.childPackages.get(i), userId, 7678 true /* removeBaseMarker */); 7679 } 7680 } 7681 7682 private void destroyAppReferenceProfileLeafLIF(PackageParser.Package pkg, int userId, 7683 boolean removeBaseMarker) { 7684 if (pkg.isForwardLocked()) { 7685 return; 7686 } 7687 7688 for (String path : pkg.getAllCodePathsExcludingResourceOnly()) { 7689 try { 7690 path = PackageManagerServiceUtils.realpath(new File(path)); 7691 } catch (IOException e) { 7692 // TODO: Should we return early here ? 7693 Slog.w(TAG, "Failed to get canonical path", e); 7694 continue; 7695 } 7696 7697 final String useMarker = path.replace('/', '@'); 7698 for (int realUserId : resolveUserIds(userId)) { 7699 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(realUserId); 7700 if (removeBaseMarker) { 7701 File foreignUseMark = new File(profileDir, useMarker); 7702 if (foreignUseMark.exists()) { 7703 if (!foreignUseMark.delete()) { 7704 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7705 + pkg.packageName); 7706 } 7707 } 7708 } 7709 7710 File[] markers = profileDir.listFiles(); 7711 if (markers != null) { 7712 final String searchString = "@" + pkg.packageName + "@"; 7713 // We also delete all markers that contain the package name we're 7714 // uninstalling. These are associated with secondary dex-files belonging 7715 // to the package. Reconstructing the path of these dex files is messy 7716 // in general. 7717 for (File marker : markers) { 7718 if (marker.getName().indexOf(searchString) > 0) { 7719 if (!marker.delete()) { 7720 Slog.w(TAG, "Unable to delete foreign user mark for package: " 7721 + pkg.packageName); 7722 } 7723 } 7724 } 7725 } 7726 } 7727 } 7728 } 7729 7730 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7731 try { 7732 mInstaller.destroyAppProfiles(pkg.packageName); 7733 } catch (InstallerException e) { 7734 Slog.w(TAG, String.valueOf(e)); 7735 } 7736 } 7737 7738 private void clearAppProfilesLIF(PackageParser.Package pkg, int userId) { 7739 if (pkg == null) { 7740 Slog.wtf(TAG, "Package was null!", new Throwable()); 7741 return; 7742 } 7743 clearAppProfilesLeafLIF(pkg); 7744 // We don't remove the base foreign use marker when clearing profiles because 7745 // we will rename it when the app is updated. Unlike the actual profile contents, 7746 // the foreign use marker is good across installs. 7747 destroyAppReferenceProfileLeafLIF(pkg, userId, false /* removeBaseMarker */); 7748 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7749 for (int i = 0; i < childCount; i++) { 7750 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7751 } 7752 } 7753 7754 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7755 try { 7756 mInstaller.clearAppProfiles(pkg.packageName); 7757 } catch (InstallerException e) { 7758 Slog.w(TAG, String.valueOf(e)); 7759 } 7760 } 7761 7762 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7763 long lastUpdateTime) { 7764 // Set parent install/update time 7765 PackageSetting ps = (PackageSetting) pkg.mExtras; 7766 if (ps != null) { 7767 ps.firstInstallTime = firstInstallTime; 7768 ps.lastUpdateTime = lastUpdateTime; 7769 } 7770 // Set children install/update time 7771 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7772 for (int i = 0; i < childCount; i++) { 7773 PackageParser.Package childPkg = pkg.childPackages.get(i); 7774 ps = (PackageSetting) childPkg.mExtras; 7775 if (ps != null) { 7776 ps.firstInstallTime = firstInstallTime; 7777 ps.lastUpdateTime = lastUpdateTime; 7778 } 7779 } 7780 } 7781 7782 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7783 PackageParser.Package changingLib) { 7784 if (file.path != null) { 7785 usesLibraryFiles.add(file.path); 7786 return; 7787 } 7788 PackageParser.Package p = mPackages.get(file.apk); 7789 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7790 // If we are doing this while in the middle of updating a library apk, 7791 // then we need to make sure to use that new apk for determining the 7792 // dependencies here. (We haven't yet finished committing the new apk 7793 // to the package manager state.) 7794 if (p == null || p.packageName.equals(changingLib.packageName)) { 7795 p = changingLib; 7796 } 7797 } 7798 if (p != null) { 7799 usesLibraryFiles.addAll(p.getAllCodePaths()); 7800 } 7801 } 7802 7803 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7804 PackageParser.Package changingLib) throws PackageManagerException { 7805 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7806 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7807 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7808 for (int i=0; i<N; i++) { 7809 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7810 if (file == null) { 7811 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7812 "Package " + pkg.packageName + " requires unavailable shared library " 7813 + pkg.usesLibraries.get(i) + "; failing!"); 7814 } 7815 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7816 } 7817 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7818 for (int i=0; i<N; i++) { 7819 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7820 if (file == null) { 7821 Slog.w(TAG, "Package " + pkg.packageName 7822 + " desires unavailable shared library " 7823 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7824 } else { 7825 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7826 } 7827 } 7828 N = usesLibraryFiles.size(); 7829 if (N > 0) { 7830 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7831 } else { 7832 pkg.usesLibraryFiles = null; 7833 } 7834 } 7835 } 7836 7837 private static boolean hasString(List<String> list, List<String> which) { 7838 if (list == null) { 7839 return false; 7840 } 7841 for (int i=list.size()-1; i>=0; i--) { 7842 for (int j=which.size()-1; j>=0; j--) { 7843 if (which.get(j).equals(list.get(i))) { 7844 return true; 7845 } 7846 } 7847 } 7848 return false; 7849 } 7850 7851 private void updateAllSharedLibrariesLPw() { 7852 for (PackageParser.Package pkg : mPackages.values()) { 7853 try { 7854 updateSharedLibrariesLPw(pkg, null); 7855 } catch (PackageManagerException e) { 7856 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7857 } 7858 } 7859 } 7860 7861 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7862 PackageParser.Package changingPkg) { 7863 ArrayList<PackageParser.Package> res = null; 7864 for (PackageParser.Package pkg : mPackages.values()) { 7865 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7866 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7867 if (res == null) { 7868 res = new ArrayList<PackageParser.Package>(); 7869 } 7870 res.add(pkg); 7871 try { 7872 updateSharedLibrariesLPw(pkg, changingPkg); 7873 } catch (PackageManagerException e) { 7874 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7875 } 7876 } 7877 } 7878 return res; 7879 } 7880 7881 /** 7882 * Derive the value of the {@code cpuAbiOverride} based on the provided 7883 * value and an optional stored value from the package settings. 7884 */ 7885 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7886 String cpuAbiOverride = null; 7887 7888 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7889 cpuAbiOverride = null; 7890 } else if (abiOverride != null) { 7891 cpuAbiOverride = abiOverride; 7892 } else if (settings != null) { 7893 cpuAbiOverride = settings.cpuAbiOverrideString; 7894 } 7895 7896 return cpuAbiOverride; 7897 } 7898 7899 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7900 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7901 throws PackageManagerException { 7902 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7903 // If the package has children and this is the first dive in the function 7904 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7905 // whether all packages (parent and children) would be successfully scanned 7906 // before the actual scan since scanning mutates internal state and we want 7907 // to atomically install the package and its children. 7908 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7909 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7910 scanFlags |= SCAN_CHECK_ONLY; 7911 } 7912 } else { 7913 scanFlags &= ~SCAN_CHECK_ONLY; 7914 } 7915 7916 final PackageParser.Package scannedPkg; 7917 try { 7918 // Scan the parent 7919 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7920 // Scan the children 7921 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7922 for (int i = 0; i < childCount; i++) { 7923 PackageParser.Package childPkg = pkg.childPackages.get(i); 7924 scanPackageLI(childPkg, policyFlags, 7925 scanFlags, currentTime, user); 7926 } 7927 } finally { 7928 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7929 } 7930 7931 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7932 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7933 } 7934 7935 return scannedPkg; 7936 } 7937 7938 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7939 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7940 boolean success = false; 7941 try { 7942 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7943 currentTime, user); 7944 success = true; 7945 return res; 7946 } finally { 7947 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7948 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7949 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7950 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7951 destroyAppProfilesLIF(pkg, UserHandle.USER_ALL); 7952 } 7953 } 7954 } 7955 7956 /** 7957 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7958 */ 7959 private static boolean apkHasCode(String fileName) { 7960 StrictJarFile jarFile = null; 7961 try { 7962 jarFile = new StrictJarFile(fileName, 7963 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7964 return jarFile.findEntry("classes.dex") != null; 7965 } catch (IOException ignore) { 7966 } finally { 7967 try { 7968 jarFile.close(); 7969 } catch (IOException ignore) {} 7970 } 7971 return false; 7972 } 7973 7974 /** 7975 * Enforces code policy for the package. This ensures that if an APK has 7976 * declared hasCode="true" in its manifest that the APK actually contains 7977 * code. 7978 * 7979 * @throws PackageManagerException If bytecode could not be found when it should exist 7980 */ 7981 private static void enforceCodePolicy(PackageParser.Package pkg) 7982 throws PackageManagerException { 7983 final boolean shouldHaveCode = 7984 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7985 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7986 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7987 "Package " + pkg.baseCodePath + " code is missing"); 7988 } 7989 7990 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7991 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7992 final boolean splitShouldHaveCode = 7993 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7994 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7995 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7996 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7997 } 7998 } 7999 } 8000 } 8001 8002 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 8003 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 8004 throws PackageManagerException { 8005 final File scanFile = new File(pkg.codePath); 8006 if (pkg.applicationInfo.getCodePath() == null || 8007 pkg.applicationInfo.getResourcePath() == null) { 8008 // Bail out. The resource and code paths haven't been set. 8009 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 8010 "Code and resource paths haven't been set correctly"); 8011 } 8012 8013 // Apply policy 8014 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 8015 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 8016 if (pkg.applicationInfo.isDirectBootAware()) { 8017 // we're direct boot aware; set for all components 8018 for (PackageParser.Service s : pkg.services) { 8019 s.info.encryptionAware = s.info.directBootAware = true; 8020 } 8021 for (PackageParser.Provider p : pkg.providers) { 8022 p.info.encryptionAware = p.info.directBootAware = true; 8023 } 8024 for (PackageParser.Activity a : pkg.activities) { 8025 a.info.encryptionAware = a.info.directBootAware = true; 8026 } 8027 for (PackageParser.Activity r : pkg.receivers) { 8028 r.info.encryptionAware = r.info.directBootAware = true; 8029 } 8030 } 8031 } else { 8032 // Only allow system apps to be flagged as core apps. 8033 pkg.coreApp = false; 8034 // clear flags not applicable to regular apps 8035 pkg.applicationInfo.privateFlags &= 8036 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 8037 pkg.applicationInfo.privateFlags &= 8038 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 8039 } 8040 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 8041 8042 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 8043 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 8044 } 8045 8046 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 8047 enforceCodePolicy(pkg); 8048 } 8049 8050 if (mCustomResolverComponentName != null && 8051 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 8052 setUpCustomResolverActivity(pkg); 8053 } 8054 8055 if (pkg.packageName.equals("android")) { 8056 synchronized (mPackages) { 8057 if (mAndroidApplication != null) { 8058 Slog.w(TAG, "*************************************************"); 8059 Slog.w(TAG, "Core android package being redefined. Skipping."); 8060 Slog.w(TAG, " file=" + scanFile); 8061 Slog.w(TAG, "*************************************************"); 8062 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8063 "Core android package being redefined. Skipping."); 8064 } 8065 8066 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8067 // Set up information for our fall-back user intent resolution activity. 8068 mPlatformPackage = pkg; 8069 pkg.mVersionCode = mSdkVersion; 8070 mAndroidApplication = pkg.applicationInfo; 8071 8072 if (!mResolverReplaced) { 8073 mResolveActivity.applicationInfo = mAndroidApplication; 8074 mResolveActivity.name = ResolverActivity.class.getName(); 8075 mResolveActivity.packageName = mAndroidApplication.packageName; 8076 mResolveActivity.processName = "system:ui"; 8077 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8078 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 8079 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 8080 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 8081 mResolveActivity.exported = true; 8082 mResolveActivity.enabled = true; 8083 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 8084 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 8085 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 8086 | ActivityInfo.CONFIG_SCREEN_LAYOUT 8087 | ActivityInfo.CONFIG_ORIENTATION 8088 | ActivityInfo.CONFIG_KEYBOARD 8089 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 8090 mResolveInfo.activityInfo = mResolveActivity; 8091 mResolveInfo.priority = 0; 8092 mResolveInfo.preferredOrder = 0; 8093 mResolveInfo.match = 0; 8094 mResolveComponentName = new ComponentName( 8095 mAndroidApplication.packageName, mResolveActivity.name); 8096 } 8097 } 8098 } 8099 } 8100 8101 if (DEBUG_PACKAGE_SCANNING) { 8102 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8103 Log.d(TAG, "Scanning package " + pkg.packageName); 8104 } 8105 8106 synchronized (mPackages) { 8107 if (mPackages.containsKey(pkg.packageName) 8108 || mSharedLibraries.containsKey(pkg.packageName)) { 8109 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 8110 "Application package " + pkg.packageName 8111 + " already installed. Skipping duplicate."); 8112 } 8113 8114 // If we're only installing presumed-existing packages, require that the 8115 // scanned APK is both already known and at the path previously established 8116 // for it. Previously unknown packages we pick up normally, but if we have an 8117 // a priori expectation about this package's install presence, enforce it. 8118 // With a singular exception for new system packages. When an OTA contains 8119 // a new system package, we allow the codepath to change from a system location 8120 // to the user-installed location. If we don't allow this change, any newer, 8121 // user-installed version of the application will be ignored. 8122 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 8123 if (mExpectingBetter.containsKey(pkg.packageName)) { 8124 logCriticalInfo(Log.WARN, 8125 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 8126 } else { 8127 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 8128 if (known != null) { 8129 if (DEBUG_PACKAGE_SCANNING) { 8130 Log.d(TAG, "Examining " + pkg.codePath 8131 + " and requiring known paths " + known.codePathString 8132 + " & " + known.resourcePathString); 8133 } 8134 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 8135 || !pkg.applicationInfo.getResourcePath().equals( 8136 known.resourcePathString)) { 8137 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 8138 "Application package " + pkg.packageName 8139 + " found at " + pkg.applicationInfo.getCodePath() 8140 + " but expected at " + known.codePathString 8141 + "; ignoring."); 8142 } 8143 } 8144 } 8145 } 8146 } 8147 8148 // Initialize package source and resource directories 8149 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 8150 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 8151 8152 SharedUserSetting suid = null; 8153 PackageSetting pkgSetting = null; 8154 8155 if (!isSystemApp(pkg)) { 8156 // Only system apps can use these features. 8157 pkg.mOriginalPackages = null; 8158 pkg.mRealPackage = null; 8159 pkg.mAdoptPermissions = null; 8160 } 8161 8162 // Getting the package setting may have a side-effect, so if we 8163 // are only checking if scan would succeed, stash a copy of the 8164 // old setting to restore at the end. 8165 PackageSetting nonMutatedPs = null; 8166 8167 // writer 8168 synchronized (mPackages) { 8169 if (pkg.mSharedUserId != null) { 8170 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8171 if (suid == null) { 8172 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8173 "Creating application package " + pkg.packageName 8174 + " for shared user failed"); 8175 } 8176 if (DEBUG_PACKAGE_SCANNING) { 8177 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8178 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8179 + "): packages=" + suid.packages); 8180 } 8181 } 8182 8183 // Check if we are renaming from an original package name. 8184 PackageSetting origPackage = null; 8185 String realName = null; 8186 if (pkg.mOriginalPackages != null) { 8187 // This package may need to be renamed to a previously 8188 // installed name. Let's check on that... 8189 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8190 if (pkg.mOriginalPackages.contains(renamed)) { 8191 // This package had originally been installed as the 8192 // original name, and we have already taken care of 8193 // transitioning to the new one. Just update the new 8194 // one to continue using the old name. 8195 realName = pkg.mRealPackage; 8196 if (!pkg.packageName.equals(renamed)) { 8197 // Callers into this function may have already taken 8198 // care of renaming the package; only do it here if 8199 // it is not already done. 8200 pkg.setPackageName(renamed); 8201 } 8202 8203 } else { 8204 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8205 if ((origPackage = mSettings.peekPackageLPr( 8206 pkg.mOriginalPackages.get(i))) != null) { 8207 // We do have the package already installed under its 8208 // original name... should we use it? 8209 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8210 // New package is not compatible with original. 8211 origPackage = null; 8212 continue; 8213 } else if (origPackage.sharedUser != null) { 8214 // Make sure uid is compatible between packages. 8215 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8216 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8217 + " to " + pkg.packageName + ": old uid " 8218 + origPackage.sharedUser.name 8219 + " differs from " + pkg.mSharedUserId); 8220 origPackage = null; 8221 continue; 8222 } 8223 // TODO: Add case when shared user id is added [b/28144775] 8224 } else { 8225 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8226 + pkg.packageName + " to old name " + origPackage.name); 8227 } 8228 break; 8229 } 8230 } 8231 } 8232 } 8233 8234 if (mTransferedPackages.contains(pkg.packageName)) { 8235 Slog.w(TAG, "Package " + pkg.packageName 8236 + " was transferred to another, but its .apk remains"); 8237 } 8238 8239 // See comments in nonMutatedPs declaration 8240 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8241 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8242 if (foundPs != null) { 8243 nonMutatedPs = new PackageSetting(foundPs); 8244 } 8245 } 8246 8247 // Just create the setting, don't add it yet. For already existing packages 8248 // the PkgSetting exists already and doesn't have to be created. 8249 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8250 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8251 pkg.applicationInfo.primaryCpuAbi, 8252 pkg.applicationInfo.secondaryCpuAbi, 8253 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8254 user, false); 8255 if (pkgSetting == null) { 8256 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8257 "Creating application package " + pkg.packageName + " failed"); 8258 } 8259 8260 if (pkgSetting.origPackage != null) { 8261 // If we are first transitioning from an original package, 8262 // fix up the new package's name now. We need to do this after 8263 // looking up the package under its new name, so getPackageLP 8264 // can take care of fiddling things correctly. 8265 pkg.setPackageName(origPackage.name); 8266 8267 // File a report about this. 8268 String msg = "New package " + pkgSetting.realName 8269 + " renamed to replace old package " + pkgSetting.name; 8270 reportSettingsProblem(Log.WARN, msg); 8271 8272 // Make a note of it. 8273 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8274 mTransferedPackages.add(origPackage.name); 8275 } 8276 8277 // No longer need to retain this. 8278 pkgSetting.origPackage = null; 8279 } 8280 8281 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8282 // Make a note of it. 8283 mTransferedPackages.add(pkg.packageName); 8284 } 8285 8286 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8287 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8288 } 8289 8290 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8291 // Check all shared libraries and map to their actual file path. 8292 // We only do this here for apps not on a system dir, because those 8293 // are the only ones that can fail an install due to this. We 8294 // will take care of the system apps by updating all of their 8295 // library paths after the scan is done. 8296 updateSharedLibrariesLPw(pkg, null); 8297 } 8298 8299 if (mFoundPolicyFile) { 8300 SELinuxMMAC.assignSeinfoValue(pkg); 8301 } 8302 8303 pkg.applicationInfo.uid = pkgSetting.appId; 8304 pkg.mExtras = pkgSetting; 8305 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8306 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8307 // We just determined the app is signed correctly, so bring 8308 // over the latest parsed certs. 8309 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8310 } else { 8311 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8312 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8313 "Package " + pkg.packageName + " upgrade keys do not match the " 8314 + "previously installed version"); 8315 } else { 8316 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8317 String msg = "System package " + pkg.packageName 8318 + " signature changed; retaining data."; 8319 reportSettingsProblem(Log.WARN, msg); 8320 } 8321 } 8322 } else { 8323 try { 8324 verifySignaturesLP(pkgSetting, pkg); 8325 // We just determined the app is signed correctly, so bring 8326 // over the latest parsed certs. 8327 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8328 } catch (PackageManagerException e) { 8329 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8330 throw e; 8331 } 8332 // The signature has changed, but this package is in the system 8333 // image... let's recover! 8334 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8335 // However... if this package is part of a shared user, but it 8336 // doesn't match the signature of the shared user, let's fail. 8337 // What this means is that you can't change the signatures 8338 // associated with an overall shared user, which doesn't seem all 8339 // that unreasonable. 8340 if (pkgSetting.sharedUser != null) { 8341 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8342 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8343 throw new PackageManagerException( 8344 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8345 "Signature mismatch for shared user: " 8346 + pkgSetting.sharedUser); 8347 } 8348 } 8349 // File a report about this. 8350 String msg = "System package " + pkg.packageName 8351 + " signature changed; retaining data."; 8352 reportSettingsProblem(Log.WARN, msg); 8353 } 8354 } 8355 // Verify that this new package doesn't have any content providers 8356 // that conflict with existing packages. Only do this if the 8357 // package isn't already installed, since we don't want to break 8358 // things that are installed. 8359 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8360 final int N = pkg.providers.size(); 8361 int i; 8362 for (i=0; i<N; i++) { 8363 PackageParser.Provider p = pkg.providers.get(i); 8364 if (p.info.authority != null) { 8365 String names[] = p.info.authority.split(";"); 8366 for (int j = 0; j < names.length; j++) { 8367 if (mProvidersByAuthority.containsKey(names[j])) { 8368 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8369 final String otherPackageName = 8370 ((other != null && other.getComponentName() != null) ? 8371 other.getComponentName().getPackageName() : "?"); 8372 throw new PackageManagerException( 8373 INSTALL_FAILED_CONFLICTING_PROVIDER, 8374 "Can't install because provider name " + names[j] 8375 + " (in package " + pkg.applicationInfo.packageName 8376 + ") is already used by " + otherPackageName); 8377 } 8378 } 8379 } 8380 } 8381 } 8382 8383 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8384 // This package wants to adopt ownership of permissions from 8385 // another package. 8386 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8387 final String origName = pkg.mAdoptPermissions.get(i); 8388 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8389 if (orig != null) { 8390 if (verifyPackageUpdateLPr(orig, pkg)) { 8391 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8392 + pkg.packageName); 8393 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8394 } 8395 } 8396 } 8397 } 8398 } 8399 8400 final String pkgName = pkg.packageName; 8401 8402 final long scanFileTime = scanFile.lastModified(); 8403 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8404 pkg.applicationInfo.processName = fixProcessName( 8405 pkg.applicationInfo.packageName, 8406 pkg.applicationInfo.processName, 8407 pkg.applicationInfo.uid); 8408 8409 if (pkg != mPlatformPackage) { 8410 // Get all of our default paths setup 8411 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8412 } 8413 8414 final String path = scanFile.getPath(); 8415 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8416 8417 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8418 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8419 8420 // Some system apps still use directory structure for native libraries 8421 // in which case we might end up not detecting abi solely based on apk 8422 // structure. Try to detect abi based on directory structure. 8423 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8424 pkg.applicationInfo.primaryCpuAbi == null) { 8425 setBundledAppAbisAndRoots(pkg, pkgSetting); 8426 setNativeLibraryPaths(pkg); 8427 } 8428 8429 } else { 8430 if ((scanFlags & SCAN_MOVE) != 0) { 8431 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8432 // but we already have this packages package info in the PackageSetting. We just 8433 // use that and derive the native library path based on the new codepath. 8434 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8435 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8436 } 8437 8438 // Set native library paths again. For moves, the path will be updated based on the 8439 // ABIs we've determined above. For non-moves, the path will be updated based on the 8440 // ABIs we determined during compilation, but the path will depend on the final 8441 // package path (after the rename away from the stage path). 8442 setNativeLibraryPaths(pkg); 8443 } 8444 8445 // This is a special case for the "system" package, where the ABI is 8446 // dictated by the zygote configuration (and init.rc). We should keep track 8447 // of this ABI so that we can deal with "normal" applications that run under 8448 // the same UID correctly. 8449 if (mPlatformPackage == pkg) { 8450 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8451 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8452 } 8453 8454 // If there's a mismatch between the abi-override in the package setting 8455 // and the abiOverride specified for the install. Warn about this because we 8456 // would've already compiled the app without taking the package setting into 8457 // account. 8458 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8459 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8460 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8461 " for package " + pkg.packageName); 8462 } 8463 } 8464 8465 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8466 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8467 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8468 8469 // Copy the derived override back to the parsed package, so that we can 8470 // update the package settings accordingly. 8471 pkg.cpuAbiOverride = cpuAbiOverride; 8472 8473 if (DEBUG_ABI_SELECTION) { 8474 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8475 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8476 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8477 } 8478 8479 // Push the derived path down into PackageSettings so we know what to 8480 // clean up at uninstall time. 8481 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8482 8483 if (DEBUG_ABI_SELECTION) { 8484 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8485 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8486 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8487 } 8488 8489 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8490 // We don't do this here during boot because we can do it all 8491 // at once after scanning all existing packages. 8492 // 8493 // We also do this *before* we perform dexopt on this package, so that 8494 // we can avoid redundant dexopts, and also to make sure we've got the 8495 // code and package path correct. 8496 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8497 pkg, true /* boot complete */); 8498 } 8499 8500 if (mFactoryTest && pkg.requestedPermissions.contains( 8501 android.Manifest.permission.FACTORY_TEST)) { 8502 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8503 } 8504 8505 ArrayList<PackageParser.Package> clientLibPkgs = null; 8506 8507 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8508 if (nonMutatedPs != null) { 8509 synchronized (mPackages) { 8510 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8511 } 8512 } 8513 return pkg; 8514 } 8515 8516 // Only privileged apps and updated privileged apps can add child packages. 8517 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8518 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8519 throw new PackageManagerException("Only privileged apps and updated " 8520 + "privileged apps can add child packages. Ignoring package " 8521 + pkg.packageName); 8522 } 8523 final int childCount = pkg.childPackages.size(); 8524 for (int i = 0; i < childCount; i++) { 8525 PackageParser.Package childPkg = pkg.childPackages.get(i); 8526 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8527 childPkg.packageName)) { 8528 throw new PackageManagerException("Cannot override a child package of " 8529 + "another disabled system app. Ignoring package " + pkg.packageName); 8530 } 8531 } 8532 } 8533 8534 // writer 8535 synchronized (mPackages) { 8536 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8537 // Only system apps can add new shared libraries. 8538 if (pkg.libraryNames != null) { 8539 for (int i=0; i<pkg.libraryNames.size(); i++) { 8540 String name = pkg.libraryNames.get(i); 8541 boolean allowed = false; 8542 if (pkg.isUpdatedSystemApp()) { 8543 // New library entries can only be added through the 8544 // system image. This is important to get rid of a lot 8545 // of nasty edge cases: for example if we allowed a non- 8546 // system update of the app to add a library, then uninstalling 8547 // the update would make the library go away, and assumptions 8548 // we made such as through app install filtering would now 8549 // have allowed apps on the device which aren't compatible 8550 // with it. Better to just have the restriction here, be 8551 // conservative, and create many fewer cases that can negatively 8552 // impact the user experience. 8553 final PackageSetting sysPs = mSettings 8554 .getDisabledSystemPkgLPr(pkg.packageName); 8555 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8556 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8557 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8558 allowed = true; 8559 break; 8560 } 8561 } 8562 } 8563 } else { 8564 allowed = true; 8565 } 8566 if (allowed) { 8567 if (!mSharedLibraries.containsKey(name)) { 8568 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8569 } else if (!name.equals(pkg.packageName)) { 8570 Slog.w(TAG, "Package " + pkg.packageName + " library " 8571 + name + " already exists; skipping"); 8572 } 8573 } else { 8574 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8575 + name + " that is not declared on system image; skipping"); 8576 } 8577 } 8578 if ((scanFlags & SCAN_BOOTING) == 0) { 8579 // If we are not booting, we need to update any applications 8580 // that are clients of our shared library. If we are booting, 8581 // this will all be done once the scan is complete. 8582 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8583 } 8584 } 8585 } 8586 } 8587 8588 if ((scanFlags & SCAN_BOOTING) != 0) { 8589 // No apps can run during boot scan, so they don't need to be frozen 8590 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8591 // Caller asked to not kill app, so it's probably not frozen 8592 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8593 // Caller asked us to ignore frozen check for some reason; they 8594 // probably didn't know the package name 8595 } else { 8596 // We're doing major surgery on this package, so it better be frozen 8597 // right now to keep it from launching 8598 checkPackageFrozen(pkgName); 8599 } 8600 8601 // Also need to kill any apps that are dependent on the library. 8602 if (clientLibPkgs != null) { 8603 for (int i=0; i<clientLibPkgs.size(); i++) { 8604 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8605 killApplication(clientPkg.applicationInfo.packageName, 8606 clientPkg.applicationInfo.uid, "update lib"); 8607 } 8608 } 8609 8610 // Make sure we're not adding any bogus keyset info 8611 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8612 ksms.assertScannedPackageValid(pkg); 8613 8614 // writer 8615 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8616 8617 boolean createIdmapFailed = false; 8618 synchronized (mPackages) { 8619 // We don't expect installation to fail beyond this point 8620 8621 if (pkgSetting.pkg != null) { 8622 // Note that |user| might be null during the initial boot scan. If a codePath 8623 // for an app has changed during a boot scan, it's due to an app update that's 8624 // part of the system partition and marker changes must be applied to all users. 8625 maybeRenameForeignDexMarkers(pkgSetting.pkg, pkg, 8626 (user != null) ? user : UserHandle.ALL); 8627 } 8628 8629 // Add the new setting to mSettings 8630 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8631 // Add the new setting to mPackages 8632 mPackages.put(pkg.applicationInfo.packageName, pkg); 8633 // Make sure we don't accidentally delete its data. 8634 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8635 while (iter.hasNext()) { 8636 PackageCleanItem item = iter.next(); 8637 if (pkgName.equals(item.packageName)) { 8638 iter.remove(); 8639 } 8640 } 8641 8642 // Take care of first install / last update times. 8643 if (currentTime != 0) { 8644 if (pkgSetting.firstInstallTime == 0) { 8645 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8646 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8647 pkgSetting.lastUpdateTime = currentTime; 8648 } 8649 } else if (pkgSetting.firstInstallTime == 0) { 8650 // We need *something*. Take time time stamp of the file. 8651 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8652 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8653 if (scanFileTime != pkgSetting.timeStamp) { 8654 // A package on the system image has changed; consider this 8655 // to be an update. 8656 pkgSetting.lastUpdateTime = scanFileTime; 8657 } 8658 } 8659 8660 // Add the package's KeySets to the global KeySetManagerService 8661 ksms.addScannedPackageLPw(pkg); 8662 8663 int N = pkg.providers.size(); 8664 StringBuilder r = null; 8665 int i; 8666 for (i=0; i<N; i++) { 8667 PackageParser.Provider p = pkg.providers.get(i); 8668 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8669 p.info.processName, pkg.applicationInfo.uid); 8670 mProviders.addProvider(p); 8671 p.syncable = p.info.isSyncable; 8672 if (p.info.authority != null) { 8673 String names[] = p.info.authority.split(";"); 8674 p.info.authority = null; 8675 for (int j = 0; j < names.length; j++) { 8676 if (j == 1 && p.syncable) { 8677 // We only want the first authority for a provider to possibly be 8678 // syncable, so if we already added this provider using a different 8679 // authority clear the syncable flag. We copy the provider before 8680 // changing it because the mProviders object contains a reference 8681 // to a provider that we don't want to change. 8682 // Only do this for the second authority since the resulting provider 8683 // object can be the same for all future authorities for this provider. 8684 p = new PackageParser.Provider(p); 8685 p.syncable = false; 8686 } 8687 if (!mProvidersByAuthority.containsKey(names[j])) { 8688 mProvidersByAuthority.put(names[j], p); 8689 if (p.info.authority == null) { 8690 p.info.authority = names[j]; 8691 } else { 8692 p.info.authority = p.info.authority + ";" + names[j]; 8693 } 8694 if (DEBUG_PACKAGE_SCANNING) { 8695 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8696 Log.d(TAG, "Registered content provider: " + names[j] 8697 + ", className = " + p.info.name + ", isSyncable = " 8698 + p.info.isSyncable); 8699 } 8700 } else { 8701 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8702 Slog.w(TAG, "Skipping provider name " + names[j] + 8703 " (in package " + pkg.applicationInfo.packageName + 8704 "): name already used by " 8705 + ((other != null && other.getComponentName() != null) 8706 ? other.getComponentName().getPackageName() : "?")); 8707 } 8708 } 8709 } 8710 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8711 if (r == null) { 8712 r = new StringBuilder(256); 8713 } else { 8714 r.append(' '); 8715 } 8716 r.append(p.info.name); 8717 } 8718 } 8719 if (r != null) { 8720 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8721 } 8722 8723 N = pkg.services.size(); 8724 r = null; 8725 for (i=0; i<N; i++) { 8726 PackageParser.Service s = pkg.services.get(i); 8727 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8728 s.info.processName, pkg.applicationInfo.uid); 8729 mServices.addService(s); 8730 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8731 if (r == null) { 8732 r = new StringBuilder(256); 8733 } else { 8734 r.append(' '); 8735 } 8736 r.append(s.info.name); 8737 } 8738 } 8739 if (r != null) { 8740 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8741 } 8742 8743 N = pkg.receivers.size(); 8744 r = null; 8745 for (i=0; i<N; i++) { 8746 PackageParser.Activity a = pkg.receivers.get(i); 8747 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8748 a.info.processName, pkg.applicationInfo.uid); 8749 mReceivers.addActivity(a, "receiver"); 8750 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8751 if (r == null) { 8752 r = new StringBuilder(256); 8753 } else { 8754 r.append(' '); 8755 } 8756 r.append(a.info.name); 8757 } 8758 } 8759 if (r != null) { 8760 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8761 } 8762 8763 N = pkg.activities.size(); 8764 r = null; 8765 for (i=0; i<N; i++) { 8766 PackageParser.Activity a = pkg.activities.get(i); 8767 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8768 a.info.processName, pkg.applicationInfo.uid); 8769 mActivities.addActivity(a, "activity"); 8770 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8771 if (r == null) { 8772 r = new StringBuilder(256); 8773 } else { 8774 r.append(' '); 8775 } 8776 r.append(a.info.name); 8777 } 8778 } 8779 if (r != null) { 8780 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8781 } 8782 8783 N = pkg.permissionGroups.size(); 8784 r = null; 8785 for (i=0; i<N; i++) { 8786 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8787 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8788 if (cur == null) { 8789 mPermissionGroups.put(pg.info.name, pg); 8790 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8791 if (r == null) { 8792 r = new StringBuilder(256); 8793 } else { 8794 r.append(' '); 8795 } 8796 r.append(pg.info.name); 8797 } 8798 } else { 8799 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8800 + pg.info.packageName + " ignored: original from " 8801 + cur.info.packageName); 8802 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8803 if (r == null) { 8804 r = new StringBuilder(256); 8805 } else { 8806 r.append(' '); 8807 } 8808 r.append("DUP:"); 8809 r.append(pg.info.name); 8810 } 8811 } 8812 } 8813 if (r != null) { 8814 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8815 } 8816 8817 N = pkg.permissions.size(); 8818 r = null; 8819 for (i=0; i<N; i++) { 8820 PackageParser.Permission p = pkg.permissions.get(i); 8821 8822 // Assume by default that we did not install this permission into the system. 8823 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8824 8825 // Now that permission groups have a special meaning, we ignore permission 8826 // groups for legacy apps to prevent unexpected behavior. In particular, 8827 // permissions for one app being granted to someone just becase they happen 8828 // to be in a group defined by another app (before this had no implications). 8829 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8830 p.group = mPermissionGroups.get(p.info.group); 8831 // Warn for a permission in an unknown group. 8832 if (p.info.group != null && p.group == null) { 8833 Slog.w(TAG, "Permission " + p.info.name + " from package " 8834 + p.info.packageName + " in an unknown group " + p.info.group); 8835 } 8836 } 8837 8838 ArrayMap<String, BasePermission> permissionMap = 8839 p.tree ? mSettings.mPermissionTrees 8840 : mSettings.mPermissions; 8841 BasePermission bp = permissionMap.get(p.info.name); 8842 8843 // Allow system apps to redefine non-system permissions 8844 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8845 final boolean currentOwnerIsSystem = (bp.perm != null 8846 && isSystemApp(bp.perm.owner)); 8847 if (isSystemApp(p.owner)) { 8848 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8849 // It's a built-in permission and no owner, take ownership now 8850 bp.packageSetting = pkgSetting; 8851 bp.perm = p; 8852 bp.uid = pkg.applicationInfo.uid; 8853 bp.sourcePackage = p.info.packageName; 8854 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8855 } else if (!currentOwnerIsSystem) { 8856 String msg = "New decl " + p.owner + " of permission " 8857 + p.info.name + " is system; overriding " + bp.sourcePackage; 8858 reportSettingsProblem(Log.WARN, msg); 8859 bp = null; 8860 } 8861 } 8862 } 8863 8864 if (bp == null) { 8865 bp = new BasePermission(p.info.name, p.info.packageName, 8866 BasePermission.TYPE_NORMAL); 8867 permissionMap.put(p.info.name, bp); 8868 } 8869 8870 if (bp.perm == null) { 8871 if (bp.sourcePackage == null 8872 || bp.sourcePackage.equals(p.info.packageName)) { 8873 BasePermission tree = findPermissionTreeLP(p.info.name); 8874 if (tree == null 8875 || tree.sourcePackage.equals(p.info.packageName)) { 8876 bp.packageSetting = pkgSetting; 8877 bp.perm = p; 8878 bp.uid = pkg.applicationInfo.uid; 8879 bp.sourcePackage = p.info.packageName; 8880 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8881 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8882 if (r == null) { 8883 r = new StringBuilder(256); 8884 } else { 8885 r.append(' '); 8886 } 8887 r.append(p.info.name); 8888 } 8889 } else { 8890 Slog.w(TAG, "Permission " + p.info.name + " from package " 8891 + p.info.packageName + " ignored: base tree " 8892 + tree.name + " is from package " 8893 + tree.sourcePackage); 8894 } 8895 } else { 8896 Slog.w(TAG, "Permission " + p.info.name + " from package " 8897 + p.info.packageName + " ignored: original from " 8898 + bp.sourcePackage); 8899 } 8900 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8901 if (r == null) { 8902 r = new StringBuilder(256); 8903 } else { 8904 r.append(' '); 8905 } 8906 r.append("DUP:"); 8907 r.append(p.info.name); 8908 } 8909 if (bp.perm == p) { 8910 bp.protectionLevel = p.info.protectionLevel; 8911 } 8912 } 8913 8914 if (r != null) { 8915 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8916 } 8917 8918 N = pkg.instrumentation.size(); 8919 r = null; 8920 for (i=0; i<N; i++) { 8921 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8922 a.info.packageName = pkg.applicationInfo.packageName; 8923 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8924 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8925 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8926 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8927 a.info.dataDir = pkg.applicationInfo.dataDir; 8928 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8929 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8930 8931 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8932 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8933 mInstrumentation.put(a.getComponentName(), a); 8934 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8935 if (r == null) { 8936 r = new StringBuilder(256); 8937 } else { 8938 r.append(' '); 8939 } 8940 r.append(a.info.name); 8941 } 8942 } 8943 if (r != null) { 8944 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8945 } 8946 8947 if (pkg.protectedBroadcasts != null) { 8948 N = pkg.protectedBroadcasts.size(); 8949 for (i=0; i<N; i++) { 8950 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8951 } 8952 } 8953 8954 pkgSetting.setTimeStamp(scanFileTime); 8955 8956 // Create idmap files for pairs of (packages, overlay packages). 8957 // Note: "android", ie framework-res.apk, is handled by native layers. 8958 if (pkg.mOverlayTarget != null) { 8959 // This is an overlay package. 8960 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8961 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8962 mOverlays.put(pkg.mOverlayTarget, 8963 new ArrayMap<String, PackageParser.Package>()); 8964 } 8965 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8966 map.put(pkg.packageName, pkg); 8967 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8968 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8969 createIdmapFailed = true; 8970 } 8971 } 8972 } else if (mOverlays.containsKey(pkg.packageName) && 8973 !pkg.packageName.equals("android")) { 8974 // This is a regular package, with one or more known overlay packages. 8975 createIdmapsForPackageLI(pkg); 8976 } 8977 } 8978 8979 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8980 8981 if (createIdmapFailed) { 8982 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8983 "scanPackageLI failed to createIdmap"); 8984 } 8985 return pkg; 8986 } 8987 8988 private void maybeRenameForeignDexMarkers(PackageParser.Package existing, 8989 PackageParser.Package update, UserHandle user) { 8990 if (existing.applicationInfo == null || update.applicationInfo == null) { 8991 // This isn't due to an app installation. 8992 return; 8993 } 8994 8995 final File oldCodePath = new File(existing.applicationInfo.getCodePath()); 8996 final File newCodePath = new File(update.applicationInfo.getCodePath()); 8997 8998 // The codePath hasn't changed, so there's nothing for us to do. 8999 if (Objects.equals(oldCodePath, newCodePath)) { 9000 return; 9001 } 9002 9003 File canonicalNewCodePath; 9004 try { 9005 canonicalNewCodePath = new File(PackageManagerServiceUtils.realpath(newCodePath)); 9006 } catch (IOException e) { 9007 Slog.w(TAG, "Failed to get canonical path.", e); 9008 return; 9009 } 9010 9011 // This is a bit of a hack. The oldCodePath doesn't exist at this point (because 9012 // we've already renamed / deleted it) so we cannot call realpath on it. Here we assume 9013 // that the last component of the path (i.e, the name) doesn't need canonicalization 9014 // (i.e, that it isn't ".", ".." or a symbolic link). This is a valid assumption for now 9015 // but may change in the future. Hopefully this function won't exist at that point. 9016 final File canonicalOldCodePath = new File(canonicalNewCodePath.getParentFile(), 9017 oldCodePath.getName()); 9018 9019 // Calculate the prefixes of the markers. These are just the paths with "/" replaced 9020 // with "@". 9021 String oldMarkerPrefix = canonicalOldCodePath.getAbsolutePath().replace('/', '@'); 9022 if (!oldMarkerPrefix.endsWith("@")) { 9023 oldMarkerPrefix += "@"; 9024 } 9025 String newMarkerPrefix = canonicalNewCodePath.getAbsolutePath().replace('/', '@'); 9026 if (!newMarkerPrefix.endsWith("@")) { 9027 newMarkerPrefix += "@"; 9028 } 9029 9030 List<String> updatedPaths = update.getAllCodePathsExcludingResourceOnly(); 9031 List<String> markerSuffixes = new ArrayList<String>(updatedPaths.size()); 9032 for (String updatedPath : updatedPaths) { 9033 String updatedPathName = new File(updatedPath).getName(); 9034 markerSuffixes.add(updatedPathName.replace('/', '@')); 9035 } 9036 9037 for (int userId : resolveUserIds(user.getIdentifier())) { 9038 File profileDir = Environment.getDataProfilesDeForeignDexDirectory(userId); 9039 9040 for (String markerSuffix : markerSuffixes) { 9041 File oldForeignUseMark = new File(profileDir, oldMarkerPrefix + markerSuffix); 9042 File newForeignUseMark = new File(profileDir, newMarkerPrefix + markerSuffix); 9043 if (oldForeignUseMark.exists()) { 9044 try { 9045 Os.rename(oldForeignUseMark.getAbsolutePath(), 9046 newForeignUseMark.getAbsolutePath()); 9047 } catch (ErrnoException e) { 9048 Slog.w(TAG, "Failed to rename foreign use marker", e); 9049 oldForeignUseMark.delete(); 9050 } 9051 } 9052 } 9053 } 9054 } 9055 9056 /** 9057 * Derive the ABI of a non-system package located at {@code scanFile}. This information 9058 * is derived purely on the basis of the contents of {@code scanFile} and 9059 * {@code cpuAbiOverride}. 9060 * 9061 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 9062 */ 9063 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 9064 String cpuAbiOverride, boolean extractLibs) 9065 throws PackageManagerException { 9066 // TODO: We can probably be smarter about this stuff. For installed apps, 9067 // we can calculate this information at install time once and for all. For 9068 // system apps, we can probably assume that this information doesn't change 9069 // after the first boot scan. As things stand, we do lots of unnecessary work. 9070 9071 // Give ourselves some initial paths; we'll come back for another 9072 // pass once we've determined ABI below. 9073 setNativeLibraryPaths(pkg); 9074 9075 // We would never need to extract libs for forward-locked and external packages, 9076 // since the container service will do it for us. We shouldn't attempt to 9077 // extract libs from system app when it was not updated. 9078 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 9079 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 9080 extractLibs = false; 9081 } 9082 9083 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 9084 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 9085 9086 NativeLibraryHelper.Handle handle = null; 9087 try { 9088 handle = NativeLibraryHelper.Handle.create(pkg); 9089 // TODO(multiArch): This can be null for apps that didn't go through the 9090 // usual installation process. We can calculate it again, like we 9091 // do during install time. 9092 // 9093 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 9094 // unnecessary. 9095 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 9096 9097 // Null out the abis so that they can be recalculated. 9098 pkg.applicationInfo.primaryCpuAbi = null; 9099 pkg.applicationInfo.secondaryCpuAbi = null; 9100 if (isMultiArch(pkg.applicationInfo)) { 9101 // Warn if we've set an abiOverride for multi-lib packages.. 9102 // By definition, we need to copy both 32 and 64 bit libraries for 9103 // such packages. 9104 if (pkg.cpuAbiOverride != null 9105 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 9106 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 9107 } 9108 9109 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 9110 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 9111 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 9112 if (extractLibs) { 9113 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9114 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 9115 useIsaSpecificSubdirs); 9116 } else { 9117 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 9118 } 9119 } 9120 9121 maybeThrowExceptionForMultiArchCopy( 9122 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 9123 9124 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 9125 if (extractLibs) { 9126 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9127 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 9128 useIsaSpecificSubdirs); 9129 } else { 9130 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 9131 } 9132 } 9133 9134 maybeThrowExceptionForMultiArchCopy( 9135 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 9136 9137 if (abi64 >= 0) { 9138 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 9139 } 9140 9141 if (abi32 >= 0) { 9142 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 9143 if (abi64 >= 0) { 9144 if (pkg.use32bitAbi) { 9145 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 9146 pkg.applicationInfo.primaryCpuAbi = abi; 9147 } else { 9148 pkg.applicationInfo.secondaryCpuAbi = abi; 9149 } 9150 } else { 9151 pkg.applicationInfo.primaryCpuAbi = abi; 9152 } 9153 } 9154 9155 } else { 9156 String[] abiList = (cpuAbiOverride != null) ? 9157 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 9158 9159 // Enable gross and lame hacks for apps that are built with old 9160 // SDK tools. We must scan their APKs for renderscript bitcode and 9161 // not launch them if it's present. Don't bother checking on devices 9162 // that don't have 64 bit support. 9163 boolean needsRenderScriptOverride = false; 9164 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 9165 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 9166 abiList = Build.SUPPORTED_32_BIT_ABIS; 9167 needsRenderScriptOverride = true; 9168 } 9169 9170 final int copyRet; 9171 if (extractLibs) { 9172 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 9173 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 9174 } else { 9175 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 9176 } 9177 9178 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 9179 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 9180 "Error unpackaging native libs for app, errorCode=" + copyRet); 9181 } 9182 9183 if (copyRet >= 0) { 9184 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 9185 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 9186 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 9187 } else if (needsRenderScriptOverride) { 9188 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 9189 } 9190 } 9191 } catch (IOException ioe) { 9192 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 9193 } finally { 9194 IoUtils.closeQuietly(handle); 9195 } 9196 9197 // Now that we've calculated the ABIs and determined if it's an internal app, 9198 // we will go ahead and populate the nativeLibraryPath. 9199 setNativeLibraryPaths(pkg); 9200 } 9201 9202 /** 9203 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 9204 * i.e, so that all packages can be run inside a single process if required. 9205 * 9206 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 9207 * this function will either try and make the ABI for all packages in {@code packagesForUser} 9208 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 9209 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 9210 * updating a package that belongs to a shared user. 9211 * 9212 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 9213 * adds unnecessary complexity. 9214 */ 9215 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 9216 PackageParser.Package scannedPackage, boolean bootComplete) { 9217 String requiredInstructionSet = null; 9218 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 9219 requiredInstructionSet = VMRuntime.getInstructionSet( 9220 scannedPackage.applicationInfo.primaryCpuAbi); 9221 } 9222 9223 PackageSetting requirer = null; 9224 for (PackageSetting ps : packagesForUser) { 9225 // If packagesForUser contains scannedPackage, we skip it. This will happen 9226 // when scannedPackage is an update of an existing package. Without this check, 9227 // we will never be able to change the ABI of any package belonging to a shared 9228 // user, even if it's compatible with other packages. 9229 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9230 if (ps.primaryCpuAbiString == null) { 9231 continue; 9232 } 9233 9234 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9235 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9236 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9237 // this but there's not much we can do. 9238 String errorMessage = "Instruction set mismatch, " 9239 + ((requirer == null) ? "[caller]" : requirer) 9240 + " requires " + requiredInstructionSet + " whereas " + ps 9241 + " requires " + instructionSet; 9242 Slog.w(TAG, errorMessage); 9243 } 9244 9245 if (requiredInstructionSet == null) { 9246 requiredInstructionSet = instructionSet; 9247 requirer = ps; 9248 } 9249 } 9250 } 9251 9252 if (requiredInstructionSet != null) { 9253 String adjustedAbi; 9254 if (requirer != null) { 9255 // requirer != null implies that either scannedPackage was null or that scannedPackage 9256 // did not require an ABI, in which case we have to adjust scannedPackage to match 9257 // the ABI of the set (which is the same as requirer's ABI) 9258 adjustedAbi = requirer.primaryCpuAbiString; 9259 if (scannedPackage != null) { 9260 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9261 } 9262 } else { 9263 // requirer == null implies that we're updating all ABIs in the set to 9264 // match scannedPackage. 9265 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9266 } 9267 9268 for (PackageSetting ps : packagesForUser) { 9269 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9270 if (ps.primaryCpuAbiString != null) { 9271 continue; 9272 } 9273 9274 ps.primaryCpuAbiString = adjustedAbi; 9275 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9276 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9277 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9278 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9279 + " (requirer=" 9280 + (requirer == null ? "null" : requirer.pkg.packageName) 9281 + ", scannedPackage=" 9282 + (scannedPackage != null ? scannedPackage.packageName : "null") 9283 + ")"); 9284 try { 9285 mInstaller.rmdex(ps.codePathString, 9286 getDexCodeInstructionSet(getPreferredInstructionSet())); 9287 } catch (InstallerException ignored) { 9288 } 9289 } 9290 } 9291 } 9292 } 9293 } 9294 9295 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9296 synchronized (mPackages) { 9297 mResolverReplaced = true; 9298 // Set up information for custom user intent resolution activity. 9299 mResolveActivity.applicationInfo = pkg.applicationInfo; 9300 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9301 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9302 mResolveActivity.processName = pkg.applicationInfo.packageName; 9303 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9304 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9305 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9306 mResolveActivity.theme = 0; 9307 mResolveActivity.exported = true; 9308 mResolveActivity.enabled = true; 9309 mResolveInfo.activityInfo = mResolveActivity; 9310 mResolveInfo.priority = 0; 9311 mResolveInfo.preferredOrder = 0; 9312 mResolveInfo.match = 0; 9313 mResolveComponentName = mCustomResolverComponentName; 9314 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9315 mResolveComponentName); 9316 } 9317 } 9318 9319 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9320 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9321 9322 // Set up information for ephemeral installer activity 9323 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9324 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9325 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9326 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9327 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9328 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9329 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9330 mEphemeralInstallerActivity.theme = 0; 9331 mEphemeralInstallerActivity.exported = true; 9332 mEphemeralInstallerActivity.enabled = true; 9333 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9334 mEphemeralInstallerInfo.priority = 0; 9335 mEphemeralInstallerInfo.preferredOrder = 0; 9336 mEphemeralInstallerInfo.match = 0; 9337 9338 if (DEBUG_EPHEMERAL) { 9339 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9340 } 9341 } 9342 9343 private static String calculateBundledApkRoot(final String codePathString) { 9344 final File codePath = new File(codePathString); 9345 final File codeRoot; 9346 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9347 codeRoot = Environment.getRootDirectory(); 9348 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9349 codeRoot = Environment.getOemDirectory(); 9350 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9351 codeRoot = Environment.getVendorDirectory(); 9352 } else { 9353 // Unrecognized code path; take its top real segment as the apk root: 9354 // e.g. /something/app/blah.apk => /something 9355 try { 9356 File f = codePath.getCanonicalFile(); 9357 File parent = f.getParentFile(); // non-null because codePath is a file 9358 File tmp; 9359 while ((tmp = parent.getParentFile()) != null) { 9360 f = parent; 9361 parent = tmp; 9362 } 9363 codeRoot = f; 9364 Slog.w(TAG, "Unrecognized code path " 9365 + codePath + " - using " + codeRoot); 9366 } catch (IOException e) { 9367 // Can't canonicalize the code path -- shenanigans? 9368 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9369 return Environment.getRootDirectory().getPath(); 9370 } 9371 } 9372 return codeRoot.getPath(); 9373 } 9374 9375 /** 9376 * Derive and set the location of native libraries for the given package, 9377 * which varies depending on where and how the package was installed. 9378 */ 9379 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9380 final ApplicationInfo info = pkg.applicationInfo; 9381 final String codePath = pkg.codePath; 9382 final File codeFile = new File(codePath); 9383 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9384 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9385 9386 info.nativeLibraryRootDir = null; 9387 info.nativeLibraryRootRequiresIsa = false; 9388 info.nativeLibraryDir = null; 9389 info.secondaryNativeLibraryDir = null; 9390 9391 if (isApkFile(codeFile)) { 9392 // Monolithic install 9393 if (bundledApp) { 9394 // If "/system/lib64/apkname" exists, assume that is the per-package 9395 // native library directory to use; otherwise use "/system/lib/apkname". 9396 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9397 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9398 getPrimaryInstructionSet(info)); 9399 9400 // This is a bundled system app so choose the path based on the ABI. 9401 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9402 // is just the default path. 9403 final String apkName = deriveCodePathName(codePath); 9404 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9405 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9406 apkName).getAbsolutePath(); 9407 9408 if (info.secondaryCpuAbi != null) { 9409 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9410 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9411 secondaryLibDir, apkName).getAbsolutePath(); 9412 } 9413 } else if (asecApp) { 9414 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9415 .getAbsolutePath(); 9416 } else { 9417 final String apkName = deriveCodePathName(codePath); 9418 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9419 .getAbsolutePath(); 9420 } 9421 9422 info.nativeLibraryRootRequiresIsa = false; 9423 info.nativeLibraryDir = info.nativeLibraryRootDir; 9424 } else { 9425 // Cluster install 9426 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9427 info.nativeLibraryRootRequiresIsa = true; 9428 9429 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9430 getPrimaryInstructionSet(info)).getAbsolutePath(); 9431 9432 if (info.secondaryCpuAbi != null) { 9433 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9434 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9435 } 9436 } 9437 } 9438 9439 /** 9440 * Calculate the abis and roots for a bundled app. These can uniquely 9441 * be determined from the contents of the system partition, i.e whether 9442 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9443 * of this information, and instead assume that the system was built 9444 * sensibly. 9445 */ 9446 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9447 PackageSetting pkgSetting) { 9448 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9449 9450 // If "/system/lib64/apkname" exists, assume that is the per-package 9451 // native library directory to use; otherwise use "/system/lib/apkname". 9452 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9453 setBundledAppAbi(pkg, apkRoot, apkName); 9454 // pkgSetting might be null during rescan following uninstall of updates 9455 // to a bundled app, so accommodate that possibility. The settings in 9456 // that case will be established later from the parsed package. 9457 // 9458 // If the settings aren't null, sync them up with what we've just derived. 9459 // note that apkRoot isn't stored in the package settings. 9460 if (pkgSetting != null) { 9461 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9462 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9463 } 9464 } 9465 9466 /** 9467 * Deduces the ABI of a bundled app and sets the relevant fields on the 9468 * parsed pkg object. 9469 * 9470 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9471 * under which system libraries are installed. 9472 * @param apkName the name of the installed package. 9473 */ 9474 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9475 final File codeFile = new File(pkg.codePath); 9476 9477 final boolean has64BitLibs; 9478 final boolean has32BitLibs; 9479 if (isApkFile(codeFile)) { 9480 // Monolithic install 9481 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9482 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9483 } else { 9484 // Cluster install 9485 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9486 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9487 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9488 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9489 has64BitLibs = (new File(rootDir, isa)).exists(); 9490 } else { 9491 has64BitLibs = false; 9492 } 9493 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9494 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9495 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9496 has32BitLibs = (new File(rootDir, isa)).exists(); 9497 } else { 9498 has32BitLibs = false; 9499 } 9500 } 9501 9502 if (has64BitLibs && !has32BitLibs) { 9503 // The package has 64 bit libs, but not 32 bit libs. Its primary 9504 // ABI should be 64 bit. We can safely assume here that the bundled 9505 // native libraries correspond to the most preferred ABI in the list. 9506 9507 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9508 pkg.applicationInfo.secondaryCpuAbi = null; 9509 } else if (has32BitLibs && !has64BitLibs) { 9510 // The package has 32 bit libs but not 64 bit libs. Its primary 9511 // ABI should be 32 bit. 9512 9513 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9514 pkg.applicationInfo.secondaryCpuAbi = null; 9515 } else if (has32BitLibs && has64BitLibs) { 9516 // The application has both 64 and 32 bit bundled libraries. We check 9517 // here that the app declares multiArch support, and warn if it doesn't. 9518 // 9519 // We will be lenient here and record both ABIs. The primary will be the 9520 // ABI that's higher on the list, i.e, a device that's configured to prefer 9521 // 64 bit apps will see a 64 bit primary ABI, 9522 9523 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9524 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9525 } 9526 9527 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9528 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9529 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9530 } else { 9531 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9532 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9533 } 9534 } else { 9535 pkg.applicationInfo.primaryCpuAbi = null; 9536 pkg.applicationInfo.secondaryCpuAbi = null; 9537 } 9538 } 9539 9540 private void killApplication(String pkgName, int appId, String reason) { 9541 // Request the ActivityManager to kill the process(only for existing packages) 9542 // so that we do not end up in a confused state while the user is still using the older 9543 // version of the application while the new one gets installed. 9544 final long token = Binder.clearCallingIdentity(); 9545 try { 9546 IActivityManager am = ActivityManagerNative.getDefault(); 9547 if (am != null) { 9548 try { 9549 am.killApplicationWithAppId(pkgName, appId, reason); 9550 } catch (RemoteException e) { 9551 } 9552 } 9553 } finally { 9554 Binder.restoreCallingIdentity(token); 9555 } 9556 } 9557 9558 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9559 // Remove the parent package setting 9560 PackageSetting ps = (PackageSetting) pkg.mExtras; 9561 if (ps != null) { 9562 removePackageLI(ps, chatty); 9563 } 9564 // Remove the child package setting 9565 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9566 for (int i = 0; i < childCount; i++) { 9567 PackageParser.Package childPkg = pkg.childPackages.get(i); 9568 ps = (PackageSetting) childPkg.mExtras; 9569 if (ps != null) { 9570 removePackageLI(ps, chatty); 9571 } 9572 } 9573 } 9574 9575 void removePackageLI(PackageSetting ps, boolean chatty) { 9576 if (DEBUG_INSTALL) { 9577 if (chatty) 9578 Log.d(TAG, "Removing package " + ps.name); 9579 } 9580 9581 // writer 9582 synchronized (mPackages) { 9583 mPackages.remove(ps.name); 9584 final PackageParser.Package pkg = ps.pkg; 9585 if (pkg != null) { 9586 cleanPackageDataStructuresLILPw(pkg, chatty); 9587 } 9588 } 9589 } 9590 9591 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9592 if (DEBUG_INSTALL) { 9593 if (chatty) 9594 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9595 } 9596 9597 // writer 9598 synchronized (mPackages) { 9599 // Remove the parent package 9600 mPackages.remove(pkg.applicationInfo.packageName); 9601 cleanPackageDataStructuresLILPw(pkg, chatty); 9602 9603 // Remove the child packages 9604 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9605 for (int i = 0; i < childCount; i++) { 9606 PackageParser.Package childPkg = pkg.childPackages.get(i); 9607 mPackages.remove(childPkg.applicationInfo.packageName); 9608 cleanPackageDataStructuresLILPw(childPkg, chatty); 9609 } 9610 } 9611 } 9612 9613 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9614 int N = pkg.providers.size(); 9615 StringBuilder r = null; 9616 int i; 9617 for (i=0; i<N; i++) { 9618 PackageParser.Provider p = pkg.providers.get(i); 9619 mProviders.removeProvider(p); 9620 if (p.info.authority == null) { 9621 9622 /* There was another ContentProvider with this authority when 9623 * this app was installed so this authority is null, 9624 * Ignore it as we don't have to unregister the provider. 9625 */ 9626 continue; 9627 } 9628 String names[] = p.info.authority.split(";"); 9629 for (int j = 0; j < names.length; j++) { 9630 if (mProvidersByAuthority.get(names[j]) == p) { 9631 mProvidersByAuthority.remove(names[j]); 9632 if (DEBUG_REMOVE) { 9633 if (chatty) 9634 Log.d(TAG, "Unregistered content provider: " + names[j] 9635 + ", className = " + p.info.name + ", isSyncable = " 9636 + p.info.isSyncable); 9637 } 9638 } 9639 } 9640 if (DEBUG_REMOVE && chatty) { 9641 if (r == null) { 9642 r = new StringBuilder(256); 9643 } else { 9644 r.append(' '); 9645 } 9646 r.append(p.info.name); 9647 } 9648 } 9649 if (r != null) { 9650 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9651 } 9652 9653 N = pkg.services.size(); 9654 r = null; 9655 for (i=0; i<N; i++) { 9656 PackageParser.Service s = pkg.services.get(i); 9657 mServices.removeService(s); 9658 if (chatty) { 9659 if (r == null) { 9660 r = new StringBuilder(256); 9661 } else { 9662 r.append(' '); 9663 } 9664 r.append(s.info.name); 9665 } 9666 } 9667 if (r != null) { 9668 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9669 } 9670 9671 N = pkg.receivers.size(); 9672 r = null; 9673 for (i=0; i<N; i++) { 9674 PackageParser.Activity a = pkg.receivers.get(i); 9675 mReceivers.removeActivity(a, "receiver"); 9676 if (DEBUG_REMOVE && chatty) { 9677 if (r == null) { 9678 r = new StringBuilder(256); 9679 } else { 9680 r.append(' '); 9681 } 9682 r.append(a.info.name); 9683 } 9684 } 9685 if (r != null) { 9686 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9687 } 9688 9689 N = pkg.activities.size(); 9690 r = null; 9691 for (i=0; i<N; i++) { 9692 PackageParser.Activity a = pkg.activities.get(i); 9693 mActivities.removeActivity(a, "activity"); 9694 if (DEBUG_REMOVE && chatty) { 9695 if (r == null) { 9696 r = new StringBuilder(256); 9697 } else { 9698 r.append(' '); 9699 } 9700 r.append(a.info.name); 9701 } 9702 } 9703 if (r != null) { 9704 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9705 } 9706 9707 N = pkg.permissions.size(); 9708 r = null; 9709 for (i=0; i<N; i++) { 9710 PackageParser.Permission p = pkg.permissions.get(i); 9711 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9712 if (bp == null) { 9713 bp = mSettings.mPermissionTrees.get(p.info.name); 9714 } 9715 if (bp != null && bp.perm == p) { 9716 bp.perm = null; 9717 if (DEBUG_REMOVE && chatty) { 9718 if (r == null) { 9719 r = new StringBuilder(256); 9720 } else { 9721 r.append(' '); 9722 } 9723 r.append(p.info.name); 9724 } 9725 } 9726 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9727 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9728 if (appOpPkgs != null) { 9729 appOpPkgs.remove(pkg.packageName); 9730 } 9731 } 9732 } 9733 if (r != null) { 9734 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9735 } 9736 9737 N = pkg.requestedPermissions.size(); 9738 r = null; 9739 for (i=0; i<N; i++) { 9740 String perm = pkg.requestedPermissions.get(i); 9741 BasePermission bp = mSettings.mPermissions.get(perm); 9742 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9743 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9744 if (appOpPkgs != null) { 9745 appOpPkgs.remove(pkg.packageName); 9746 if (appOpPkgs.isEmpty()) { 9747 mAppOpPermissionPackages.remove(perm); 9748 } 9749 } 9750 } 9751 } 9752 if (r != null) { 9753 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9754 } 9755 9756 N = pkg.instrumentation.size(); 9757 r = null; 9758 for (i=0; i<N; i++) { 9759 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9760 mInstrumentation.remove(a.getComponentName()); 9761 if (DEBUG_REMOVE && chatty) { 9762 if (r == null) { 9763 r = new StringBuilder(256); 9764 } else { 9765 r.append(' '); 9766 } 9767 r.append(a.info.name); 9768 } 9769 } 9770 if (r != null) { 9771 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9772 } 9773 9774 r = null; 9775 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9776 // Only system apps can hold shared libraries. 9777 if (pkg.libraryNames != null) { 9778 for (i=0; i<pkg.libraryNames.size(); i++) { 9779 String name = pkg.libraryNames.get(i); 9780 SharedLibraryEntry cur = mSharedLibraries.get(name); 9781 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9782 mSharedLibraries.remove(name); 9783 if (DEBUG_REMOVE && chatty) { 9784 if (r == null) { 9785 r = new StringBuilder(256); 9786 } else { 9787 r.append(' '); 9788 } 9789 r.append(name); 9790 } 9791 } 9792 } 9793 } 9794 } 9795 if (r != null) { 9796 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9797 } 9798 } 9799 9800 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9801 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9802 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9803 return true; 9804 } 9805 } 9806 return false; 9807 } 9808 9809 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9810 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9811 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9812 9813 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9814 // Update the parent permissions 9815 updatePermissionsLPw(pkg.packageName, pkg, flags); 9816 // Update the child permissions 9817 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9818 for (int i = 0; i < childCount; i++) { 9819 PackageParser.Package childPkg = pkg.childPackages.get(i); 9820 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9821 } 9822 } 9823 9824 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9825 int flags) { 9826 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9827 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9828 } 9829 9830 private void updatePermissionsLPw(String changingPkg, 9831 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9832 // Make sure there are no dangling permission trees. 9833 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9834 while (it.hasNext()) { 9835 final BasePermission bp = it.next(); 9836 if (bp.packageSetting == null) { 9837 // We may not yet have parsed the package, so just see if 9838 // we still know about its settings. 9839 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9840 } 9841 if (bp.packageSetting == null) { 9842 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9843 + " from package " + bp.sourcePackage); 9844 it.remove(); 9845 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9846 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9847 Slog.i(TAG, "Removing old permission tree: " + bp.name 9848 + " from package " + bp.sourcePackage); 9849 flags |= UPDATE_PERMISSIONS_ALL; 9850 it.remove(); 9851 } 9852 } 9853 } 9854 9855 // Make sure all dynamic permissions have been assigned to a package, 9856 // and make sure there are no dangling permissions. 9857 it = mSettings.mPermissions.values().iterator(); 9858 while (it.hasNext()) { 9859 final BasePermission bp = it.next(); 9860 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9861 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9862 + bp.name + " pkg=" + bp.sourcePackage 9863 + " info=" + bp.pendingInfo); 9864 if (bp.packageSetting == null && bp.pendingInfo != null) { 9865 final BasePermission tree = findPermissionTreeLP(bp.name); 9866 if (tree != null && tree.perm != null) { 9867 bp.packageSetting = tree.packageSetting; 9868 bp.perm = new PackageParser.Permission(tree.perm.owner, 9869 new PermissionInfo(bp.pendingInfo)); 9870 bp.perm.info.packageName = tree.perm.info.packageName; 9871 bp.perm.info.name = bp.name; 9872 bp.uid = tree.uid; 9873 } 9874 } 9875 } 9876 if (bp.packageSetting == null) { 9877 // We may not yet have parsed the package, so just see if 9878 // we still know about its settings. 9879 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9880 } 9881 if (bp.packageSetting == null) { 9882 Slog.w(TAG, "Removing dangling permission: " + bp.name 9883 + " from package " + bp.sourcePackage); 9884 it.remove(); 9885 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9886 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9887 Slog.i(TAG, "Removing old permission: " + bp.name 9888 + " from package " + bp.sourcePackage); 9889 flags |= UPDATE_PERMISSIONS_ALL; 9890 it.remove(); 9891 } 9892 } 9893 } 9894 9895 // Now update the permissions for all packages, in particular 9896 // replace the granted permissions of the system packages. 9897 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9898 for (PackageParser.Package pkg : mPackages.values()) { 9899 if (pkg != pkgInfo) { 9900 // Only replace for packages on requested volume 9901 final String volumeUuid = getVolumeUuidForPackage(pkg); 9902 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9903 && Objects.equals(replaceVolumeUuid, volumeUuid); 9904 grantPermissionsLPw(pkg, replace, changingPkg); 9905 } 9906 } 9907 } 9908 9909 if (pkgInfo != null) { 9910 // Only replace for packages on requested volume 9911 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9912 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9913 && Objects.equals(replaceVolumeUuid, volumeUuid); 9914 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9915 } 9916 } 9917 9918 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9919 String packageOfInterest) { 9920 // IMPORTANT: There are two types of permissions: install and runtime. 9921 // Install time permissions are granted when the app is installed to 9922 // all device users and users added in the future. Runtime permissions 9923 // are granted at runtime explicitly to specific users. Normal and signature 9924 // protected permissions are install time permissions. Dangerous permissions 9925 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9926 // otherwise they are runtime permissions. This function does not manage 9927 // runtime permissions except for the case an app targeting Lollipop MR1 9928 // being upgraded to target a newer SDK, in which case dangerous permissions 9929 // are transformed from install time to runtime ones. 9930 9931 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9932 if (ps == null) { 9933 return; 9934 } 9935 9936 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9937 9938 PermissionsState permissionsState = ps.getPermissionsState(); 9939 PermissionsState origPermissions = permissionsState; 9940 9941 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9942 9943 boolean runtimePermissionsRevoked = false; 9944 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9945 9946 boolean changedInstallPermission = false; 9947 9948 if (replace) { 9949 ps.installPermissionsFixed = false; 9950 if (!ps.isSharedUser()) { 9951 origPermissions = new PermissionsState(permissionsState); 9952 permissionsState.reset(); 9953 } else { 9954 // We need to know only about runtime permission changes since the 9955 // calling code always writes the install permissions state but 9956 // the runtime ones are written only if changed. The only cases of 9957 // changed runtime permissions here are promotion of an install to 9958 // runtime and revocation of a runtime from a shared user. 9959 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9960 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9961 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9962 runtimePermissionsRevoked = true; 9963 } 9964 } 9965 } 9966 9967 permissionsState.setGlobalGids(mGlobalGids); 9968 9969 final int N = pkg.requestedPermissions.size(); 9970 for (int i=0; i<N; i++) { 9971 final String name = pkg.requestedPermissions.get(i); 9972 final BasePermission bp = mSettings.mPermissions.get(name); 9973 9974 if (DEBUG_INSTALL) { 9975 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9976 } 9977 9978 if (bp == null || bp.packageSetting == null) { 9979 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9980 Slog.w(TAG, "Unknown permission " + name 9981 + " in package " + pkg.packageName); 9982 } 9983 continue; 9984 } 9985 9986 final String perm = bp.name; 9987 boolean allowedSig = false; 9988 int grant = GRANT_DENIED; 9989 9990 // Keep track of app op permissions. 9991 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9992 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9993 if (pkgs == null) { 9994 pkgs = new ArraySet<>(); 9995 mAppOpPermissionPackages.put(bp.name, pkgs); 9996 } 9997 pkgs.add(pkg.packageName); 9998 } 9999 10000 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 10001 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 10002 >= Build.VERSION_CODES.M; 10003 switch (level) { 10004 case PermissionInfo.PROTECTION_NORMAL: { 10005 // For all apps normal permissions are install time ones. 10006 grant = GRANT_INSTALL; 10007 } break; 10008 10009 case PermissionInfo.PROTECTION_DANGEROUS: { 10010 // If a permission review is required for legacy apps we represent 10011 // their permissions as always granted runtime ones since we need 10012 // to keep the review required permission flag per user while an 10013 // install permission's state is shared across all users. 10014 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 10015 // For legacy apps dangerous permissions are install time ones. 10016 grant = GRANT_INSTALL; 10017 } else if (origPermissions.hasInstallPermission(bp.name)) { 10018 // For legacy apps that became modern, install becomes runtime. 10019 grant = GRANT_UPGRADE; 10020 } else if (mPromoteSystemApps 10021 && isSystemApp(ps) 10022 && mExistingSystemPackages.contains(ps.name)) { 10023 // For legacy system apps, install becomes runtime. 10024 // We cannot check hasInstallPermission() for system apps since those 10025 // permissions were granted implicitly and not persisted pre-M. 10026 grant = GRANT_UPGRADE; 10027 } else { 10028 // For modern apps keep runtime permissions unchanged. 10029 grant = GRANT_RUNTIME; 10030 } 10031 } break; 10032 10033 case PermissionInfo.PROTECTION_SIGNATURE: { 10034 // For all apps signature permissions are install time ones. 10035 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 10036 if (allowedSig) { 10037 grant = GRANT_INSTALL; 10038 } 10039 } break; 10040 } 10041 10042 if (DEBUG_INSTALL) { 10043 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 10044 } 10045 10046 if (grant != GRANT_DENIED) { 10047 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 10048 // If this is an existing, non-system package, then 10049 // we can't add any new permissions to it. 10050 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 10051 // Except... if this is a permission that was added 10052 // to the platform (note: need to only do this when 10053 // updating the platform). 10054 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 10055 grant = GRANT_DENIED; 10056 } 10057 } 10058 } 10059 10060 switch (grant) { 10061 case GRANT_INSTALL: { 10062 // Revoke this as runtime permission to handle the case of 10063 // a runtime permission being downgraded to an install one. 10064 // Also in permission review mode we keep dangerous permissions 10065 // for legacy apps 10066 for (int userId : UserManagerService.getInstance().getUserIds()) { 10067 if (origPermissions.getRuntimePermissionState( 10068 bp.name, userId) != null) { 10069 // Revoke the runtime permission and clear the flags. 10070 origPermissions.revokeRuntimePermission(bp, userId); 10071 origPermissions.updatePermissionFlags(bp, userId, 10072 PackageManager.MASK_PERMISSION_FLAGS, 0); 10073 // If we revoked a permission permission, we have to write. 10074 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10075 changedRuntimePermissionUserIds, userId); 10076 } 10077 } 10078 // Grant an install permission. 10079 if (permissionsState.grantInstallPermission(bp) != 10080 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10081 changedInstallPermission = true; 10082 } 10083 } break; 10084 10085 case GRANT_RUNTIME: { 10086 // Grant previously granted runtime permissions. 10087 for (int userId : UserManagerService.getInstance().getUserIds()) { 10088 PermissionState permissionState = origPermissions 10089 .getRuntimePermissionState(bp.name, userId); 10090 int flags = permissionState != null 10091 ? permissionState.getFlags() : 0; 10092 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 10093 if (permissionsState.grantRuntimePermission(bp, userId) == 10094 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10095 // If we cannot put the permission as it was, we have to write. 10096 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10097 changedRuntimePermissionUserIds, userId); 10098 } 10099 // If the app supports runtime permissions no need for a review. 10100 if (Build.PERMISSIONS_REVIEW_REQUIRED 10101 && appSupportsRuntimePermissions 10102 && (flags & PackageManager 10103 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 10104 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 10105 // Since we changed the flags, we have to write. 10106 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10107 changedRuntimePermissionUserIds, userId); 10108 } 10109 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 10110 && !appSupportsRuntimePermissions) { 10111 // For legacy apps that need a permission review, every new 10112 // runtime permission is granted but it is pending a review. 10113 // We also need to review only platform defined runtime 10114 // permissions as these are the only ones the platform knows 10115 // how to disable the API to simulate revocation as legacy 10116 // apps don't expect to run with revoked permissions. 10117 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 10118 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 10119 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 10120 // We changed the flags, hence have to write. 10121 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10122 changedRuntimePermissionUserIds, userId); 10123 } 10124 } 10125 if (permissionsState.grantRuntimePermission(bp, userId) 10126 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10127 // We changed the permission, hence have to write. 10128 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10129 changedRuntimePermissionUserIds, userId); 10130 } 10131 } 10132 // Propagate the permission flags. 10133 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 10134 } 10135 } break; 10136 10137 case GRANT_UPGRADE: { 10138 // Grant runtime permissions for a previously held install permission. 10139 PermissionState permissionState = origPermissions 10140 .getInstallPermissionState(bp.name); 10141 final int flags = permissionState != null ? permissionState.getFlags() : 0; 10142 10143 if (origPermissions.revokeInstallPermission(bp) 10144 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 10145 // We will be transferring the permission flags, so clear them. 10146 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 10147 PackageManager.MASK_PERMISSION_FLAGS, 0); 10148 changedInstallPermission = true; 10149 } 10150 10151 // If the permission is not to be promoted to runtime we ignore it and 10152 // also its other flags as they are not applicable to install permissions. 10153 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 10154 for (int userId : currentUserIds) { 10155 if (permissionsState.grantRuntimePermission(bp, userId) != 10156 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10157 // Transfer the permission flags. 10158 permissionsState.updatePermissionFlags(bp, userId, 10159 flags, flags); 10160 // If we granted the permission, we have to write. 10161 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 10162 changedRuntimePermissionUserIds, userId); 10163 } 10164 } 10165 } 10166 } break; 10167 10168 default: { 10169 if (packageOfInterest == null 10170 || packageOfInterest.equals(pkg.packageName)) { 10171 Slog.w(TAG, "Not granting permission " + perm 10172 + " to package " + pkg.packageName 10173 + " because it was previously installed without"); 10174 } 10175 } break; 10176 } 10177 } else { 10178 if (permissionsState.revokeInstallPermission(bp) != 10179 PermissionsState.PERMISSION_OPERATION_FAILURE) { 10180 // Also drop the permission flags. 10181 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 10182 PackageManager.MASK_PERMISSION_FLAGS, 0); 10183 changedInstallPermission = true; 10184 Slog.i(TAG, "Un-granting permission " + perm 10185 + " from package " + pkg.packageName 10186 + " (protectionLevel=" + bp.protectionLevel 10187 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10188 + ")"); 10189 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 10190 // Don't print warning for app op permissions, since it is fine for them 10191 // not to be granted, there is a UI for the user to decide. 10192 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 10193 Slog.w(TAG, "Not granting permission " + perm 10194 + " to package " + pkg.packageName 10195 + " (protectionLevel=" + bp.protectionLevel 10196 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 10197 + ")"); 10198 } 10199 } 10200 } 10201 } 10202 10203 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 10204 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 10205 // This is the first that we have heard about this package, so the 10206 // permissions we have now selected are fixed until explicitly 10207 // changed. 10208 ps.installPermissionsFixed = true; 10209 } 10210 10211 // Persist the runtime permissions state for users with changes. If permissions 10212 // were revoked because no app in the shared user declares them we have to 10213 // write synchronously to avoid losing runtime permissions state. 10214 for (int userId : changedRuntimePermissionUserIds) { 10215 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 10216 } 10217 10218 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 10219 } 10220 10221 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 10222 boolean allowed = false; 10223 final int NP = PackageParser.NEW_PERMISSIONS.length; 10224 for (int ip=0; ip<NP; ip++) { 10225 final PackageParser.NewPermissionInfo npi 10226 = PackageParser.NEW_PERMISSIONS[ip]; 10227 if (npi.name.equals(perm) 10228 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 10229 allowed = true; 10230 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 10231 + pkg.packageName); 10232 break; 10233 } 10234 } 10235 return allowed; 10236 } 10237 10238 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10239 BasePermission bp, PermissionsState origPermissions) { 10240 boolean allowed; 10241 allowed = (compareSignatures( 10242 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10243 == PackageManager.SIGNATURE_MATCH) 10244 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10245 == PackageManager.SIGNATURE_MATCH); 10246 if (!allowed && (bp.protectionLevel 10247 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10248 if (isSystemApp(pkg)) { 10249 // For updated system applications, a system permission 10250 // is granted only if it had been defined by the original application. 10251 if (pkg.isUpdatedSystemApp()) { 10252 final PackageSetting sysPs = mSettings 10253 .getDisabledSystemPkgLPr(pkg.packageName); 10254 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10255 // If the original was granted this permission, we take 10256 // that grant decision as read and propagate it to the 10257 // update. 10258 if (sysPs.isPrivileged()) { 10259 allowed = true; 10260 } 10261 } else { 10262 // The system apk may have been updated with an older 10263 // version of the one on the data partition, but which 10264 // granted a new system permission that it didn't have 10265 // before. In this case we do want to allow the app to 10266 // now get the new permission if the ancestral apk is 10267 // privileged to get it. 10268 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10269 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10270 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10271 allowed = true; 10272 break; 10273 } 10274 } 10275 } 10276 // Also if a privileged parent package on the system image or any of 10277 // its children requested a privileged permission, the updated child 10278 // packages can also get the permission. 10279 if (pkg.parentPackage != null) { 10280 final PackageSetting disabledSysParentPs = mSettings 10281 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10282 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10283 && disabledSysParentPs.isPrivileged()) { 10284 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10285 allowed = true; 10286 } else if (disabledSysParentPs.pkg.childPackages != null) { 10287 final int count = disabledSysParentPs.pkg.childPackages.size(); 10288 for (int i = 0; i < count; i++) { 10289 PackageParser.Package disabledSysChildPkg = 10290 disabledSysParentPs.pkg.childPackages.get(i); 10291 if (isPackageRequestingPermission(disabledSysChildPkg, 10292 perm)) { 10293 allowed = true; 10294 break; 10295 } 10296 } 10297 } 10298 } 10299 } 10300 } 10301 } else { 10302 allowed = isPrivilegedApp(pkg); 10303 } 10304 } 10305 } 10306 if (!allowed) { 10307 if (!allowed && (bp.protectionLevel 10308 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10309 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10310 // If this was a previously normal/dangerous permission that got moved 10311 // to a system permission as part of the runtime permission redesign, then 10312 // we still want to blindly grant it to old apps. 10313 allowed = true; 10314 } 10315 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10316 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10317 // If this permission is to be granted to the system installer and 10318 // this app is an installer, then it gets the permission. 10319 allowed = true; 10320 } 10321 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10322 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10323 // If this permission is to be granted to the system verifier and 10324 // this app is a verifier, then it gets the permission. 10325 allowed = true; 10326 } 10327 if (!allowed && (bp.protectionLevel 10328 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10329 && isSystemApp(pkg)) { 10330 // Any pre-installed system app is allowed to get this permission. 10331 allowed = true; 10332 } 10333 if (!allowed && (bp.protectionLevel 10334 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10335 // For development permissions, a development permission 10336 // is granted only if it was already granted. 10337 allowed = origPermissions.hasInstallPermission(perm); 10338 } 10339 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10340 && pkg.packageName.equals(mSetupWizardPackage)) { 10341 // If this permission is to be granted to the system setup wizard and 10342 // this app is a setup wizard, then it gets the permission. 10343 allowed = true; 10344 } 10345 } 10346 return allowed; 10347 } 10348 10349 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10350 final int permCount = pkg.requestedPermissions.size(); 10351 for (int j = 0; j < permCount; j++) { 10352 String requestedPermission = pkg.requestedPermissions.get(j); 10353 if (permission.equals(requestedPermission)) { 10354 return true; 10355 } 10356 } 10357 return false; 10358 } 10359 10360 final class ActivityIntentResolver 10361 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10362 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10363 boolean defaultOnly, int userId) { 10364 if (!sUserManager.exists(userId)) return null; 10365 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10366 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10367 } 10368 10369 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10370 int userId) { 10371 if (!sUserManager.exists(userId)) return null; 10372 mFlags = flags; 10373 return super.queryIntent(intent, resolvedType, 10374 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10375 } 10376 10377 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10378 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10379 if (!sUserManager.exists(userId)) return null; 10380 if (packageActivities == null) { 10381 return null; 10382 } 10383 mFlags = flags; 10384 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10385 final int N = packageActivities.size(); 10386 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10387 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10388 10389 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10390 for (int i = 0; i < N; ++i) { 10391 intentFilters = packageActivities.get(i).intents; 10392 if (intentFilters != null && intentFilters.size() > 0) { 10393 PackageParser.ActivityIntentInfo[] array = 10394 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10395 intentFilters.toArray(array); 10396 listCut.add(array); 10397 } 10398 } 10399 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10400 } 10401 10402 /** 10403 * Finds a privileged activity that matches the specified activity names. 10404 */ 10405 private PackageParser.Activity findMatchingActivity( 10406 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10407 for (PackageParser.Activity sysActivity : activityList) { 10408 if (sysActivity.info.name.equals(activityInfo.name)) { 10409 return sysActivity; 10410 } 10411 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10412 return sysActivity; 10413 } 10414 if (sysActivity.info.targetActivity != null) { 10415 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10416 return sysActivity; 10417 } 10418 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10419 return sysActivity; 10420 } 10421 } 10422 } 10423 return null; 10424 } 10425 10426 public class IterGenerator<E> { 10427 public Iterator<E> generate(ActivityIntentInfo info) { 10428 return null; 10429 } 10430 } 10431 10432 public class ActionIterGenerator extends IterGenerator<String> { 10433 @Override 10434 public Iterator<String> generate(ActivityIntentInfo info) { 10435 return info.actionsIterator(); 10436 } 10437 } 10438 10439 public class CategoriesIterGenerator extends IterGenerator<String> { 10440 @Override 10441 public Iterator<String> generate(ActivityIntentInfo info) { 10442 return info.categoriesIterator(); 10443 } 10444 } 10445 10446 public class SchemesIterGenerator extends IterGenerator<String> { 10447 @Override 10448 public Iterator<String> generate(ActivityIntentInfo info) { 10449 return info.schemesIterator(); 10450 } 10451 } 10452 10453 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10454 @Override 10455 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10456 return info.authoritiesIterator(); 10457 } 10458 } 10459 10460 /** 10461 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10462 * MODIFIED. Do not pass in a list that should not be changed. 10463 */ 10464 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10465 IterGenerator<T> generator, Iterator<T> searchIterator) { 10466 // loop through the set of actions; every one must be found in the intent filter 10467 while (searchIterator.hasNext()) { 10468 // we must have at least one filter in the list to consider a match 10469 if (intentList.size() == 0) { 10470 break; 10471 } 10472 10473 final T searchAction = searchIterator.next(); 10474 10475 // loop through the set of intent filters 10476 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10477 while (intentIter.hasNext()) { 10478 final ActivityIntentInfo intentInfo = intentIter.next(); 10479 boolean selectionFound = false; 10480 10481 // loop through the intent filter's selection criteria; at least one 10482 // of them must match the searched criteria 10483 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10484 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10485 final T intentSelection = intentSelectionIter.next(); 10486 if (intentSelection != null && intentSelection.equals(searchAction)) { 10487 selectionFound = true; 10488 break; 10489 } 10490 } 10491 10492 // the selection criteria wasn't found in this filter's set; this filter 10493 // is not a potential match 10494 if (!selectionFound) { 10495 intentIter.remove(); 10496 } 10497 } 10498 } 10499 } 10500 10501 private boolean isProtectedAction(ActivityIntentInfo filter) { 10502 final Iterator<String> actionsIter = filter.actionsIterator(); 10503 while (actionsIter != null && actionsIter.hasNext()) { 10504 final String filterAction = actionsIter.next(); 10505 if (PROTECTED_ACTIONS.contains(filterAction)) { 10506 return true; 10507 } 10508 } 10509 return false; 10510 } 10511 10512 /** 10513 * Adjusts the priority of the given intent filter according to policy. 10514 * <p> 10515 * <ul> 10516 * <li>The priority for non privileged applications is capped to '0'</li> 10517 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10518 * <li>The priority for unbundled updates to privileged applications is capped to the 10519 * priority defined on the system partition</li> 10520 * </ul> 10521 * <p> 10522 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10523 * allowed to obtain any priority on any action. 10524 */ 10525 private void adjustPriority( 10526 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10527 // nothing to do; priority is fine as-is 10528 if (intent.getPriority() <= 0) { 10529 return; 10530 } 10531 10532 final ActivityInfo activityInfo = intent.activity.info; 10533 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10534 10535 final boolean privilegedApp = 10536 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10537 if (!privilegedApp) { 10538 // non-privileged applications can never define a priority >0 10539 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10540 + " package: " + applicationInfo.packageName 10541 + " activity: " + intent.activity.className 10542 + " origPrio: " + intent.getPriority()); 10543 intent.setPriority(0); 10544 return; 10545 } 10546 10547 if (systemActivities == null) { 10548 // the system package is not disabled; we're parsing the system partition 10549 if (isProtectedAction(intent)) { 10550 if (mDeferProtectedFilters) { 10551 // We can't deal with these just yet. No component should ever obtain a 10552 // >0 priority for a protected actions, with ONE exception -- the setup 10553 // wizard. The setup wizard, however, cannot be known until we're able to 10554 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10555 // until all intent filters have been processed. Chicken, meet egg. 10556 // Let the filter temporarily have a high priority and rectify the 10557 // priorities after all system packages have been scanned. 10558 mProtectedFilters.add(intent); 10559 if (DEBUG_FILTERS) { 10560 Slog.i(TAG, "Protected action; save for later;" 10561 + " package: " + applicationInfo.packageName 10562 + " activity: " + intent.activity.className 10563 + " origPrio: " + intent.getPriority()); 10564 } 10565 return; 10566 } else { 10567 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10568 Slog.i(TAG, "No setup wizard;" 10569 + " All protected intents capped to priority 0"); 10570 } 10571 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10572 if (DEBUG_FILTERS) { 10573 Slog.i(TAG, "Found setup wizard;" 10574 + " allow priority " + intent.getPriority() + ";" 10575 + " package: " + intent.activity.info.packageName 10576 + " activity: " + intent.activity.className 10577 + " priority: " + intent.getPriority()); 10578 } 10579 // setup wizard gets whatever it wants 10580 return; 10581 } 10582 Slog.w(TAG, "Protected action; cap priority to 0;" 10583 + " package: " + intent.activity.info.packageName 10584 + " activity: " + intent.activity.className 10585 + " origPrio: " + intent.getPriority()); 10586 intent.setPriority(0); 10587 return; 10588 } 10589 } 10590 // privileged apps on the system image get whatever priority they request 10591 return; 10592 } 10593 10594 // privileged app unbundled update ... try to find the same activity 10595 final PackageParser.Activity foundActivity = 10596 findMatchingActivity(systemActivities, activityInfo); 10597 if (foundActivity == null) { 10598 // this is a new activity; it cannot obtain >0 priority 10599 if (DEBUG_FILTERS) { 10600 Slog.i(TAG, "New activity; cap priority to 0;" 10601 + " package: " + applicationInfo.packageName 10602 + " activity: " + intent.activity.className 10603 + " origPrio: " + intent.getPriority()); 10604 } 10605 intent.setPriority(0); 10606 return; 10607 } 10608 10609 // found activity, now check for filter equivalence 10610 10611 // a shallow copy is enough; we modify the list, not its contents 10612 final List<ActivityIntentInfo> intentListCopy = 10613 new ArrayList<>(foundActivity.intents); 10614 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10615 10616 // find matching action subsets 10617 final Iterator<String> actionsIterator = intent.actionsIterator(); 10618 if (actionsIterator != null) { 10619 getIntentListSubset( 10620 intentListCopy, new ActionIterGenerator(), actionsIterator); 10621 if (intentListCopy.size() == 0) { 10622 // no more intents to match; we're not equivalent 10623 if (DEBUG_FILTERS) { 10624 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10625 + " package: " + applicationInfo.packageName 10626 + " activity: " + intent.activity.className 10627 + " origPrio: " + intent.getPriority()); 10628 } 10629 intent.setPriority(0); 10630 return; 10631 } 10632 } 10633 10634 // find matching category subsets 10635 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10636 if (categoriesIterator != null) { 10637 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10638 categoriesIterator); 10639 if (intentListCopy.size() == 0) { 10640 // no more intents to match; we're not equivalent 10641 if (DEBUG_FILTERS) { 10642 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10643 + " package: " + applicationInfo.packageName 10644 + " activity: " + intent.activity.className 10645 + " origPrio: " + intent.getPriority()); 10646 } 10647 intent.setPriority(0); 10648 return; 10649 } 10650 } 10651 10652 // find matching schemes subsets 10653 final Iterator<String> schemesIterator = intent.schemesIterator(); 10654 if (schemesIterator != null) { 10655 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10656 schemesIterator); 10657 if (intentListCopy.size() == 0) { 10658 // no more intents to match; we're not equivalent 10659 if (DEBUG_FILTERS) { 10660 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10661 + " package: " + applicationInfo.packageName 10662 + " activity: " + intent.activity.className 10663 + " origPrio: " + intent.getPriority()); 10664 } 10665 intent.setPriority(0); 10666 return; 10667 } 10668 } 10669 10670 // find matching authorities subsets 10671 final Iterator<IntentFilter.AuthorityEntry> 10672 authoritiesIterator = intent.authoritiesIterator(); 10673 if (authoritiesIterator != null) { 10674 getIntentListSubset(intentListCopy, 10675 new AuthoritiesIterGenerator(), 10676 authoritiesIterator); 10677 if (intentListCopy.size() == 0) { 10678 // no more intents to match; we're not equivalent 10679 if (DEBUG_FILTERS) { 10680 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10681 + " package: " + applicationInfo.packageName 10682 + " activity: " + intent.activity.className 10683 + " origPrio: " + intent.getPriority()); 10684 } 10685 intent.setPriority(0); 10686 return; 10687 } 10688 } 10689 10690 // we found matching filter(s); app gets the max priority of all intents 10691 int cappedPriority = 0; 10692 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10693 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10694 } 10695 if (intent.getPriority() > cappedPriority) { 10696 if (DEBUG_FILTERS) { 10697 Slog.i(TAG, "Found matching filter(s);" 10698 + " cap priority to " + cappedPriority + ";" 10699 + " package: " + applicationInfo.packageName 10700 + " activity: " + intent.activity.className 10701 + " origPrio: " + intent.getPriority()); 10702 } 10703 intent.setPriority(cappedPriority); 10704 return; 10705 } 10706 // all this for nothing; the requested priority was <= what was on the system 10707 } 10708 10709 public final void addActivity(PackageParser.Activity a, String type) { 10710 mActivities.put(a.getComponentName(), a); 10711 if (DEBUG_SHOW_INFO) 10712 Log.v( 10713 TAG, " " + type + " " + 10714 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10715 if (DEBUG_SHOW_INFO) 10716 Log.v(TAG, " Class=" + a.info.name); 10717 final int NI = a.intents.size(); 10718 for (int j=0; j<NI; j++) { 10719 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10720 if ("activity".equals(type)) { 10721 final PackageSetting ps = 10722 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10723 final List<PackageParser.Activity> systemActivities = 10724 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10725 adjustPriority(systemActivities, intent); 10726 } 10727 if (DEBUG_SHOW_INFO) { 10728 Log.v(TAG, " IntentFilter:"); 10729 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10730 } 10731 if (!intent.debugCheck()) { 10732 Log.w(TAG, "==> For Activity " + a.info.name); 10733 } 10734 addFilter(intent); 10735 } 10736 } 10737 10738 public final void removeActivity(PackageParser.Activity a, String type) { 10739 mActivities.remove(a.getComponentName()); 10740 if (DEBUG_SHOW_INFO) { 10741 Log.v(TAG, " " + type + " " 10742 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10743 : a.info.name) + ":"); 10744 Log.v(TAG, " Class=" + a.info.name); 10745 } 10746 final int NI = a.intents.size(); 10747 for (int j=0; j<NI; j++) { 10748 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10749 if (DEBUG_SHOW_INFO) { 10750 Log.v(TAG, " IntentFilter:"); 10751 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10752 } 10753 removeFilter(intent); 10754 } 10755 } 10756 10757 @Override 10758 protected boolean allowFilterResult( 10759 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10760 ActivityInfo filterAi = filter.activity.info; 10761 for (int i=dest.size()-1; i>=0; i--) { 10762 ActivityInfo destAi = dest.get(i).activityInfo; 10763 if (destAi.name == filterAi.name 10764 && destAi.packageName == filterAi.packageName) { 10765 return false; 10766 } 10767 } 10768 return true; 10769 } 10770 10771 @Override 10772 protected ActivityIntentInfo[] newArray(int size) { 10773 return new ActivityIntentInfo[size]; 10774 } 10775 10776 @Override 10777 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10778 if (!sUserManager.exists(userId)) return true; 10779 PackageParser.Package p = filter.activity.owner; 10780 if (p != null) { 10781 PackageSetting ps = (PackageSetting)p.mExtras; 10782 if (ps != null) { 10783 // System apps are never considered stopped for purposes of 10784 // filtering, because there may be no way for the user to 10785 // actually re-launch them. 10786 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10787 && ps.getStopped(userId); 10788 } 10789 } 10790 return false; 10791 } 10792 10793 @Override 10794 protected boolean isPackageForFilter(String packageName, 10795 PackageParser.ActivityIntentInfo info) { 10796 return packageName.equals(info.activity.owner.packageName); 10797 } 10798 10799 @Override 10800 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10801 int match, int userId) { 10802 if (!sUserManager.exists(userId)) return null; 10803 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10804 return null; 10805 } 10806 final PackageParser.Activity activity = info.activity; 10807 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10808 if (ps == null) { 10809 return null; 10810 } 10811 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10812 ps.readUserState(userId), userId); 10813 if (ai == null) { 10814 return null; 10815 } 10816 final ResolveInfo res = new ResolveInfo(); 10817 res.activityInfo = ai; 10818 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10819 res.filter = info; 10820 } 10821 if (info != null) { 10822 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10823 } 10824 res.priority = info.getPriority(); 10825 res.preferredOrder = activity.owner.mPreferredOrder; 10826 //System.out.println("Result: " + res.activityInfo.className + 10827 // " = " + res.priority); 10828 res.match = match; 10829 res.isDefault = info.hasDefault; 10830 res.labelRes = info.labelRes; 10831 res.nonLocalizedLabel = info.nonLocalizedLabel; 10832 if (userNeedsBadging(userId)) { 10833 res.noResourceId = true; 10834 } else { 10835 res.icon = info.icon; 10836 } 10837 res.iconResourceId = info.icon; 10838 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10839 return res; 10840 } 10841 10842 @Override 10843 protected void sortResults(List<ResolveInfo> results) { 10844 Collections.sort(results, mResolvePrioritySorter); 10845 } 10846 10847 @Override 10848 protected void dumpFilter(PrintWriter out, String prefix, 10849 PackageParser.ActivityIntentInfo filter) { 10850 out.print(prefix); out.print( 10851 Integer.toHexString(System.identityHashCode(filter.activity))); 10852 out.print(' '); 10853 filter.activity.printComponentShortName(out); 10854 out.print(" filter "); 10855 out.println(Integer.toHexString(System.identityHashCode(filter))); 10856 } 10857 10858 @Override 10859 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10860 return filter.activity; 10861 } 10862 10863 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10864 PackageParser.Activity activity = (PackageParser.Activity)label; 10865 out.print(prefix); out.print( 10866 Integer.toHexString(System.identityHashCode(activity))); 10867 out.print(' '); 10868 activity.printComponentShortName(out); 10869 if (count > 1) { 10870 out.print(" ("); out.print(count); out.print(" filters)"); 10871 } 10872 out.println(); 10873 } 10874 10875 // Keys are String (activity class name), values are Activity. 10876 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10877 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10878 private int mFlags; 10879 } 10880 10881 private final class ServiceIntentResolver 10882 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10883 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10884 boolean defaultOnly, int userId) { 10885 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10886 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10887 } 10888 10889 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10890 int userId) { 10891 if (!sUserManager.exists(userId)) return null; 10892 mFlags = flags; 10893 return super.queryIntent(intent, resolvedType, 10894 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10895 } 10896 10897 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10898 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10899 if (!sUserManager.exists(userId)) return null; 10900 if (packageServices == null) { 10901 return null; 10902 } 10903 mFlags = flags; 10904 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10905 final int N = packageServices.size(); 10906 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10907 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10908 10909 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10910 for (int i = 0; i < N; ++i) { 10911 intentFilters = packageServices.get(i).intents; 10912 if (intentFilters != null && intentFilters.size() > 0) { 10913 PackageParser.ServiceIntentInfo[] array = 10914 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10915 intentFilters.toArray(array); 10916 listCut.add(array); 10917 } 10918 } 10919 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10920 } 10921 10922 public final void addService(PackageParser.Service s) { 10923 mServices.put(s.getComponentName(), s); 10924 if (DEBUG_SHOW_INFO) { 10925 Log.v(TAG, " " 10926 + (s.info.nonLocalizedLabel != null 10927 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10928 Log.v(TAG, " Class=" + s.info.name); 10929 } 10930 final int NI = s.intents.size(); 10931 int j; 10932 for (j=0; j<NI; j++) { 10933 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10934 if (DEBUG_SHOW_INFO) { 10935 Log.v(TAG, " IntentFilter:"); 10936 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10937 } 10938 if (!intent.debugCheck()) { 10939 Log.w(TAG, "==> For Service " + s.info.name); 10940 } 10941 addFilter(intent); 10942 } 10943 } 10944 10945 public final void removeService(PackageParser.Service s) { 10946 mServices.remove(s.getComponentName()); 10947 if (DEBUG_SHOW_INFO) { 10948 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10949 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10950 Log.v(TAG, " Class=" + s.info.name); 10951 } 10952 final int NI = s.intents.size(); 10953 int j; 10954 for (j=0; j<NI; j++) { 10955 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10956 if (DEBUG_SHOW_INFO) { 10957 Log.v(TAG, " IntentFilter:"); 10958 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10959 } 10960 removeFilter(intent); 10961 } 10962 } 10963 10964 @Override 10965 protected boolean allowFilterResult( 10966 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10967 ServiceInfo filterSi = filter.service.info; 10968 for (int i=dest.size()-1; i>=0; i--) { 10969 ServiceInfo destAi = dest.get(i).serviceInfo; 10970 if (destAi.name == filterSi.name 10971 && destAi.packageName == filterSi.packageName) { 10972 return false; 10973 } 10974 } 10975 return true; 10976 } 10977 10978 @Override 10979 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10980 return new PackageParser.ServiceIntentInfo[size]; 10981 } 10982 10983 @Override 10984 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10985 if (!sUserManager.exists(userId)) return true; 10986 PackageParser.Package p = filter.service.owner; 10987 if (p != null) { 10988 PackageSetting ps = (PackageSetting)p.mExtras; 10989 if (ps != null) { 10990 // System apps are never considered stopped for purposes of 10991 // filtering, because there may be no way for the user to 10992 // actually re-launch them. 10993 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10994 && ps.getStopped(userId); 10995 } 10996 } 10997 return false; 10998 } 10999 11000 @Override 11001 protected boolean isPackageForFilter(String packageName, 11002 PackageParser.ServiceIntentInfo info) { 11003 return packageName.equals(info.service.owner.packageName); 11004 } 11005 11006 @Override 11007 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 11008 int match, int userId) { 11009 if (!sUserManager.exists(userId)) return null; 11010 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 11011 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 11012 return null; 11013 } 11014 final PackageParser.Service service = info.service; 11015 PackageSetting ps = (PackageSetting) service.owner.mExtras; 11016 if (ps == null) { 11017 return null; 11018 } 11019 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 11020 ps.readUserState(userId), userId); 11021 if (si == null) { 11022 return null; 11023 } 11024 final ResolveInfo res = new ResolveInfo(); 11025 res.serviceInfo = si; 11026 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 11027 res.filter = filter; 11028 } 11029 res.priority = info.getPriority(); 11030 res.preferredOrder = service.owner.mPreferredOrder; 11031 res.match = match; 11032 res.isDefault = info.hasDefault; 11033 res.labelRes = info.labelRes; 11034 res.nonLocalizedLabel = info.nonLocalizedLabel; 11035 res.icon = info.icon; 11036 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 11037 return res; 11038 } 11039 11040 @Override 11041 protected void sortResults(List<ResolveInfo> results) { 11042 Collections.sort(results, mResolvePrioritySorter); 11043 } 11044 11045 @Override 11046 protected void dumpFilter(PrintWriter out, String prefix, 11047 PackageParser.ServiceIntentInfo filter) { 11048 out.print(prefix); out.print( 11049 Integer.toHexString(System.identityHashCode(filter.service))); 11050 out.print(' '); 11051 filter.service.printComponentShortName(out); 11052 out.print(" filter "); 11053 out.println(Integer.toHexString(System.identityHashCode(filter))); 11054 } 11055 11056 @Override 11057 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 11058 return filter.service; 11059 } 11060 11061 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11062 PackageParser.Service service = (PackageParser.Service)label; 11063 out.print(prefix); out.print( 11064 Integer.toHexString(System.identityHashCode(service))); 11065 out.print(' '); 11066 service.printComponentShortName(out); 11067 if (count > 1) { 11068 out.print(" ("); out.print(count); out.print(" filters)"); 11069 } 11070 out.println(); 11071 } 11072 11073// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 11074// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 11075// final List<ResolveInfo> retList = Lists.newArrayList(); 11076// while (i.hasNext()) { 11077// final ResolveInfo resolveInfo = (ResolveInfo) i; 11078// if (isEnabledLP(resolveInfo.serviceInfo)) { 11079// retList.add(resolveInfo); 11080// } 11081// } 11082// return retList; 11083// } 11084 11085 // Keys are String (activity class name), values are Activity. 11086 private final ArrayMap<ComponentName, PackageParser.Service> mServices 11087 = new ArrayMap<ComponentName, PackageParser.Service>(); 11088 private int mFlags; 11089 }; 11090 11091 private final class ProviderIntentResolver 11092 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 11093 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 11094 boolean defaultOnly, int userId) { 11095 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 11096 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 11097 } 11098 11099 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 11100 int userId) { 11101 if (!sUserManager.exists(userId)) 11102 return null; 11103 mFlags = flags; 11104 return super.queryIntent(intent, resolvedType, 11105 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 11106 } 11107 11108 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 11109 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 11110 if (!sUserManager.exists(userId)) 11111 return null; 11112 if (packageProviders == null) { 11113 return null; 11114 } 11115 mFlags = flags; 11116 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 11117 final int N = packageProviders.size(); 11118 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 11119 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 11120 11121 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 11122 for (int i = 0; i < N; ++i) { 11123 intentFilters = packageProviders.get(i).intents; 11124 if (intentFilters != null && intentFilters.size() > 0) { 11125 PackageParser.ProviderIntentInfo[] array = 11126 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 11127 intentFilters.toArray(array); 11128 listCut.add(array); 11129 } 11130 } 11131 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 11132 } 11133 11134 public final void addProvider(PackageParser.Provider p) { 11135 if (mProviders.containsKey(p.getComponentName())) { 11136 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 11137 return; 11138 } 11139 11140 mProviders.put(p.getComponentName(), p); 11141 if (DEBUG_SHOW_INFO) { 11142 Log.v(TAG, " " 11143 + (p.info.nonLocalizedLabel != null 11144 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11145 Log.v(TAG, " Class=" + p.info.name); 11146 } 11147 final int NI = p.intents.size(); 11148 int j; 11149 for (j = 0; j < NI; j++) { 11150 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11151 if (DEBUG_SHOW_INFO) { 11152 Log.v(TAG, " IntentFilter:"); 11153 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11154 } 11155 if (!intent.debugCheck()) { 11156 Log.w(TAG, "==> For Provider " + p.info.name); 11157 } 11158 addFilter(intent); 11159 } 11160 } 11161 11162 public final void removeProvider(PackageParser.Provider p) { 11163 mProviders.remove(p.getComponentName()); 11164 if (DEBUG_SHOW_INFO) { 11165 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 11166 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 11167 Log.v(TAG, " Class=" + p.info.name); 11168 } 11169 final int NI = p.intents.size(); 11170 int j; 11171 for (j = 0; j < NI; j++) { 11172 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 11173 if (DEBUG_SHOW_INFO) { 11174 Log.v(TAG, " IntentFilter:"); 11175 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 11176 } 11177 removeFilter(intent); 11178 } 11179 } 11180 11181 @Override 11182 protected boolean allowFilterResult( 11183 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 11184 ProviderInfo filterPi = filter.provider.info; 11185 for (int i = dest.size() - 1; i >= 0; i--) { 11186 ProviderInfo destPi = dest.get(i).providerInfo; 11187 if (destPi.name == filterPi.name 11188 && destPi.packageName == filterPi.packageName) { 11189 return false; 11190 } 11191 } 11192 return true; 11193 } 11194 11195 @Override 11196 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 11197 return new PackageParser.ProviderIntentInfo[size]; 11198 } 11199 11200 @Override 11201 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 11202 if (!sUserManager.exists(userId)) 11203 return true; 11204 PackageParser.Package p = filter.provider.owner; 11205 if (p != null) { 11206 PackageSetting ps = (PackageSetting) p.mExtras; 11207 if (ps != null) { 11208 // System apps are never considered stopped for purposes of 11209 // filtering, because there may be no way for the user to 11210 // actually re-launch them. 11211 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 11212 && ps.getStopped(userId); 11213 } 11214 } 11215 return false; 11216 } 11217 11218 @Override 11219 protected boolean isPackageForFilter(String packageName, 11220 PackageParser.ProviderIntentInfo info) { 11221 return packageName.equals(info.provider.owner.packageName); 11222 } 11223 11224 @Override 11225 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 11226 int match, int userId) { 11227 if (!sUserManager.exists(userId)) 11228 return null; 11229 final PackageParser.ProviderIntentInfo info = filter; 11230 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 11231 return null; 11232 } 11233 final PackageParser.Provider provider = info.provider; 11234 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11235 if (ps == null) { 11236 return null; 11237 } 11238 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11239 ps.readUserState(userId), userId); 11240 if (pi == null) { 11241 return null; 11242 } 11243 final ResolveInfo res = new ResolveInfo(); 11244 res.providerInfo = pi; 11245 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11246 res.filter = filter; 11247 } 11248 res.priority = info.getPriority(); 11249 res.preferredOrder = provider.owner.mPreferredOrder; 11250 res.match = match; 11251 res.isDefault = info.hasDefault; 11252 res.labelRes = info.labelRes; 11253 res.nonLocalizedLabel = info.nonLocalizedLabel; 11254 res.icon = info.icon; 11255 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11256 return res; 11257 } 11258 11259 @Override 11260 protected void sortResults(List<ResolveInfo> results) { 11261 Collections.sort(results, mResolvePrioritySorter); 11262 } 11263 11264 @Override 11265 protected void dumpFilter(PrintWriter out, String prefix, 11266 PackageParser.ProviderIntentInfo filter) { 11267 out.print(prefix); 11268 out.print( 11269 Integer.toHexString(System.identityHashCode(filter.provider))); 11270 out.print(' '); 11271 filter.provider.printComponentShortName(out); 11272 out.print(" filter "); 11273 out.println(Integer.toHexString(System.identityHashCode(filter))); 11274 } 11275 11276 @Override 11277 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11278 return filter.provider; 11279 } 11280 11281 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11282 PackageParser.Provider provider = (PackageParser.Provider)label; 11283 out.print(prefix); out.print( 11284 Integer.toHexString(System.identityHashCode(provider))); 11285 out.print(' '); 11286 provider.printComponentShortName(out); 11287 if (count > 1) { 11288 out.print(" ("); out.print(count); out.print(" filters)"); 11289 } 11290 out.println(); 11291 } 11292 11293 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11294 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11295 private int mFlags; 11296 } 11297 11298 private static final class EphemeralIntentResolver 11299 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11300 @Override 11301 protected EphemeralResolveIntentInfo[] newArray(int size) { 11302 return new EphemeralResolveIntentInfo[size]; 11303 } 11304 11305 @Override 11306 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11307 return true; 11308 } 11309 11310 @Override 11311 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11312 int userId) { 11313 if (!sUserManager.exists(userId)) { 11314 return null; 11315 } 11316 return info.getEphemeralResolveInfo(); 11317 } 11318 } 11319 11320 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11321 new Comparator<ResolveInfo>() { 11322 public int compare(ResolveInfo r1, ResolveInfo r2) { 11323 int v1 = r1.priority; 11324 int v2 = r2.priority; 11325 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11326 if (v1 != v2) { 11327 return (v1 > v2) ? -1 : 1; 11328 } 11329 v1 = r1.preferredOrder; 11330 v2 = r2.preferredOrder; 11331 if (v1 != v2) { 11332 return (v1 > v2) ? -1 : 1; 11333 } 11334 if (r1.isDefault != r2.isDefault) { 11335 return r1.isDefault ? -1 : 1; 11336 } 11337 v1 = r1.match; 11338 v2 = r2.match; 11339 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11340 if (v1 != v2) { 11341 return (v1 > v2) ? -1 : 1; 11342 } 11343 if (r1.system != r2.system) { 11344 return r1.system ? -1 : 1; 11345 } 11346 if (r1.activityInfo != null) { 11347 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11348 } 11349 if (r1.serviceInfo != null) { 11350 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11351 } 11352 if (r1.providerInfo != null) { 11353 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11354 } 11355 return 0; 11356 } 11357 }; 11358 11359 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11360 new Comparator<ProviderInfo>() { 11361 public int compare(ProviderInfo p1, ProviderInfo p2) { 11362 final int v1 = p1.initOrder; 11363 final int v2 = p2.initOrder; 11364 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11365 } 11366 }; 11367 11368 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11369 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11370 final int[] userIds) { 11371 mHandler.post(new Runnable() { 11372 @Override 11373 public void run() { 11374 try { 11375 final IActivityManager am = ActivityManagerNative.getDefault(); 11376 if (am == null) return; 11377 final int[] resolvedUserIds; 11378 if (userIds == null) { 11379 resolvedUserIds = am.getRunningUserIds(); 11380 } else { 11381 resolvedUserIds = userIds; 11382 } 11383 for (int id : resolvedUserIds) { 11384 final Intent intent = new Intent(action, 11385 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11386 if (extras != null) { 11387 intent.putExtras(extras); 11388 } 11389 if (targetPkg != null) { 11390 intent.setPackage(targetPkg); 11391 } 11392 // Modify the UID when posting to other users 11393 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11394 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11395 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11396 intent.putExtra(Intent.EXTRA_UID, uid); 11397 } 11398 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11399 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11400 if (DEBUG_BROADCASTS) { 11401 RuntimeException here = new RuntimeException("here"); 11402 here.fillInStackTrace(); 11403 Slog.d(TAG, "Sending to user " + id + ": " 11404 + intent.toShortString(false, true, false, false) 11405 + " " + intent.getExtras(), here); 11406 } 11407 am.broadcastIntent(null, intent, null, finishedReceiver, 11408 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11409 null, finishedReceiver != null, false, id); 11410 } 11411 } catch (RemoteException ex) { 11412 } 11413 } 11414 }); 11415 } 11416 11417 /** 11418 * Check if the external storage media is available. This is true if there 11419 * is a mounted external storage medium or if the external storage is 11420 * emulated. 11421 */ 11422 private boolean isExternalMediaAvailable() { 11423 return mMediaMounted || Environment.isExternalStorageEmulated(); 11424 } 11425 11426 @Override 11427 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11428 // writer 11429 synchronized (mPackages) { 11430 if (!isExternalMediaAvailable()) { 11431 // If the external storage is no longer mounted at this point, 11432 // the caller may not have been able to delete all of this 11433 // packages files and can not delete any more. Bail. 11434 return null; 11435 } 11436 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11437 if (lastPackage != null) { 11438 pkgs.remove(lastPackage); 11439 } 11440 if (pkgs.size() > 0) { 11441 return pkgs.get(0); 11442 } 11443 } 11444 return null; 11445 } 11446 11447 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11448 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11449 userId, andCode ? 1 : 0, packageName); 11450 if (mSystemReady) { 11451 msg.sendToTarget(); 11452 } else { 11453 if (mPostSystemReadyMessages == null) { 11454 mPostSystemReadyMessages = new ArrayList<>(); 11455 } 11456 mPostSystemReadyMessages.add(msg); 11457 } 11458 } 11459 11460 void startCleaningPackages() { 11461 // reader 11462 if (!isExternalMediaAvailable()) { 11463 return; 11464 } 11465 synchronized (mPackages) { 11466 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11467 return; 11468 } 11469 } 11470 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11471 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11472 IActivityManager am = ActivityManagerNative.getDefault(); 11473 if (am != null) { 11474 try { 11475 am.startService(null, intent, null, mContext.getOpPackageName(), 11476 UserHandle.USER_SYSTEM); 11477 } catch (RemoteException e) { 11478 } 11479 } 11480 } 11481 11482 @Override 11483 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11484 int installFlags, String installerPackageName, int userId) { 11485 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11486 11487 final int callingUid = Binder.getCallingUid(); 11488 enforceCrossUserPermission(callingUid, userId, 11489 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11490 11491 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11492 try { 11493 if (observer != null) { 11494 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11495 } 11496 } catch (RemoteException re) { 11497 } 11498 return; 11499 } 11500 11501 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11502 installFlags |= PackageManager.INSTALL_FROM_ADB; 11503 11504 } else { 11505 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11506 // about installerPackageName. 11507 11508 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11509 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11510 } 11511 11512 UserHandle user; 11513 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11514 user = UserHandle.ALL; 11515 } else { 11516 user = new UserHandle(userId); 11517 } 11518 11519 // Only system components can circumvent runtime permissions when installing. 11520 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11521 && mContext.checkCallingOrSelfPermission(Manifest.permission 11522 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11523 throw new SecurityException("You need the " 11524 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11525 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11526 } 11527 11528 final File originFile = new File(originPath); 11529 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11530 11531 final Message msg = mHandler.obtainMessage(INIT_COPY); 11532 final VerificationInfo verificationInfo = new VerificationInfo( 11533 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11534 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11535 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11536 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11537 null /*certificates*/); 11538 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11539 msg.obj = params; 11540 11541 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11542 System.identityHashCode(msg.obj)); 11543 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11544 System.identityHashCode(msg.obj)); 11545 11546 mHandler.sendMessage(msg); 11547 } 11548 11549 void installStage(String packageName, File stagedDir, String stagedCid, 11550 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11551 String installerPackageName, int installerUid, UserHandle user, 11552 Certificate[][] certificates) { 11553 if (DEBUG_EPHEMERAL) { 11554 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11555 Slog.d(TAG, "Ephemeral install of " + packageName); 11556 } 11557 } 11558 final VerificationInfo verificationInfo = new VerificationInfo( 11559 sessionParams.originatingUri, sessionParams.referrerUri, 11560 sessionParams.originatingUid, installerUid); 11561 11562 final OriginInfo origin; 11563 if (stagedDir != null) { 11564 origin = OriginInfo.fromStagedFile(stagedDir); 11565 } else { 11566 origin = OriginInfo.fromStagedContainer(stagedCid); 11567 } 11568 11569 final Message msg = mHandler.obtainMessage(INIT_COPY); 11570 final InstallParams params = new InstallParams(origin, null, observer, 11571 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11572 verificationInfo, user, sessionParams.abiOverride, 11573 sessionParams.grantedRuntimePermissions, certificates); 11574 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11575 msg.obj = params; 11576 11577 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11578 System.identityHashCode(msg.obj)); 11579 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11580 System.identityHashCode(msg.obj)); 11581 11582 mHandler.sendMessage(msg); 11583 } 11584 11585 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11586 int userId) { 11587 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11588 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11589 } 11590 11591 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11592 int appId, int userId) { 11593 Bundle extras = new Bundle(1); 11594 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11595 11596 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11597 packageName, extras, 0, null, null, new int[] {userId}); 11598 try { 11599 IActivityManager am = ActivityManagerNative.getDefault(); 11600 if (isSystem && am.isUserRunning(userId, 0)) { 11601 // The just-installed/enabled app is bundled on the system, so presumed 11602 // to be able to run automatically without needing an explicit launch. 11603 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11604 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11605 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11606 .setPackage(packageName); 11607 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11608 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11609 } 11610 } catch (RemoteException e) { 11611 // shouldn't happen 11612 Slog.w(TAG, "Unable to bootstrap installed package", e); 11613 } 11614 } 11615 11616 @Override 11617 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11618 int userId) { 11619 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11620 PackageSetting pkgSetting; 11621 final int uid = Binder.getCallingUid(); 11622 enforceCrossUserPermission(uid, userId, 11623 true /* requireFullPermission */, true /* checkShell */, 11624 "setApplicationHiddenSetting for user " + userId); 11625 11626 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11627 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11628 return false; 11629 } 11630 11631 long callingId = Binder.clearCallingIdentity(); 11632 try { 11633 boolean sendAdded = false; 11634 boolean sendRemoved = false; 11635 // writer 11636 synchronized (mPackages) { 11637 pkgSetting = mSettings.mPackages.get(packageName); 11638 if (pkgSetting == null) { 11639 return false; 11640 } 11641 if (pkgSetting.getHidden(userId) != hidden) { 11642 pkgSetting.setHidden(hidden, userId); 11643 mSettings.writePackageRestrictionsLPr(userId); 11644 if (hidden) { 11645 sendRemoved = true; 11646 } else { 11647 sendAdded = true; 11648 } 11649 } 11650 } 11651 if (sendAdded) { 11652 sendPackageAddedForUser(packageName, pkgSetting, userId); 11653 return true; 11654 } 11655 if (sendRemoved) { 11656 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11657 "hiding pkg"); 11658 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11659 return true; 11660 } 11661 } finally { 11662 Binder.restoreCallingIdentity(callingId); 11663 } 11664 return false; 11665 } 11666 11667 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11668 int userId) { 11669 final PackageRemovedInfo info = new PackageRemovedInfo(); 11670 info.removedPackage = packageName; 11671 info.removedUsers = new int[] {userId}; 11672 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11673 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11674 } 11675 11676 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11677 if (pkgList.length > 0) { 11678 Bundle extras = new Bundle(1); 11679 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11680 11681 sendPackageBroadcast( 11682 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11683 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11684 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11685 new int[] {userId}); 11686 } 11687 } 11688 11689 /** 11690 * Returns true if application is not found or there was an error. Otherwise it returns 11691 * the hidden state of the package for the given user. 11692 */ 11693 @Override 11694 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11695 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11696 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11697 true /* requireFullPermission */, false /* checkShell */, 11698 "getApplicationHidden for user " + userId); 11699 PackageSetting pkgSetting; 11700 long callingId = Binder.clearCallingIdentity(); 11701 try { 11702 // writer 11703 synchronized (mPackages) { 11704 pkgSetting = mSettings.mPackages.get(packageName); 11705 if (pkgSetting == null) { 11706 return true; 11707 } 11708 return pkgSetting.getHidden(userId); 11709 } 11710 } finally { 11711 Binder.restoreCallingIdentity(callingId); 11712 } 11713 } 11714 11715 /** 11716 * @hide 11717 */ 11718 @Override 11719 public int installExistingPackageAsUser(String packageName, int userId) { 11720 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11721 null); 11722 PackageSetting pkgSetting; 11723 final int uid = Binder.getCallingUid(); 11724 enforceCrossUserPermission(uid, userId, 11725 true /* requireFullPermission */, true /* checkShell */, 11726 "installExistingPackage for user " + userId); 11727 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11728 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11729 } 11730 11731 long callingId = Binder.clearCallingIdentity(); 11732 try { 11733 boolean installed = false; 11734 11735 // writer 11736 synchronized (mPackages) { 11737 pkgSetting = mSettings.mPackages.get(packageName); 11738 if (pkgSetting == null) { 11739 return PackageManager.INSTALL_FAILED_INVALID_URI; 11740 } 11741 if (!pkgSetting.getInstalled(userId)) { 11742 pkgSetting.setInstalled(true, userId); 11743 pkgSetting.setHidden(false, userId); 11744 mSettings.writePackageRestrictionsLPr(userId); 11745 installed = true; 11746 } 11747 } 11748 11749 if (installed) { 11750 if (pkgSetting.pkg != null) { 11751 synchronized (mInstallLock) { 11752 // We don't need to freeze for a brand new install 11753 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11754 } 11755 } 11756 sendPackageAddedForUser(packageName, pkgSetting, userId); 11757 } 11758 } finally { 11759 Binder.restoreCallingIdentity(callingId); 11760 } 11761 11762 return PackageManager.INSTALL_SUCCEEDED; 11763 } 11764 11765 boolean isUserRestricted(int userId, String restrictionKey) { 11766 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11767 if (restrictions.getBoolean(restrictionKey, false)) { 11768 Log.w(TAG, "User is restricted: " + restrictionKey); 11769 return true; 11770 } 11771 return false; 11772 } 11773 11774 @Override 11775 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11776 int userId) { 11777 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11778 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11779 true /* requireFullPermission */, true /* checkShell */, 11780 "setPackagesSuspended for user " + userId); 11781 11782 if (ArrayUtils.isEmpty(packageNames)) { 11783 return packageNames; 11784 } 11785 11786 // List of package names for whom the suspended state has changed. 11787 List<String> changedPackages = new ArrayList<>(packageNames.length); 11788 // List of package names for whom the suspended state is not set as requested in this 11789 // method. 11790 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11791 long callingId = Binder.clearCallingIdentity(); 11792 try { 11793 for (int i = 0; i < packageNames.length; i++) { 11794 String packageName = packageNames[i]; 11795 boolean changed = false; 11796 final int appId; 11797 synchronized (mPackages) { 11798 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11799 if (pkgSetting == null) { 11800 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11801 + "\". Skipping suspending/un-suspending."); 11802 unactionedPackages.add(packageName); 11803 continue; 11804 } 11805 appId = pkgSetting.appId; 11806 if (pkgSetting.getSuspended(userId) != suspended) { 11807 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11808 unactionedPackages.add(packageName); 11809 continue; 11810 } 11811 pkgSetting.setSuspended(suspended, userId); 11812 mSettings.writePackageRestrictionsLPr(userId); 11813 changed = true; 11814 changedPackages.add(packageName); 11815 } 11816 } 11817 11818 if (changed && suspended) { 11819 killApplication(packageName, UserHandle.getUid(userId, appId), 11820 "suspending package"); 11821 } 11822 } 11823 } finally { 11824 Binder.restoreCallingIdentity(callingId); 11825 } 11826 11827 if (!changedPackages.isEmpty()) { 11828 sendPackagesSuspendedForUser(changedPackages.toArray( 11829 new String[changedPackages.size()]), userId, suspended); 11830 } 11831 11832 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11833 } 11834 11835 @Override 11836 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11837 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11838 true /* requireFullPermission */, false /* checkShell */, 11839 "isPackageSuspendedForUser for user " + userId); 11840 synchronized (mPackages) { 11841 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11842 if (pkgSetting == null) { 11843 throw new IllegalArgumentException("Unknown target package: " + packageName); 11844 } 11845 return pkgSetting.getSuspended(userId); 11846 } 11847 } 11848 11849 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11850 if (isPackageDeviceAdmin(packageName, userId)) { 11851 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11852 + "\": has an active device admin"); 11853 return false; 11854 } 11855 11856 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11857 if (packageName.equals(activeLauncherPackageName)) { 11858 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11859 + "\": contains the active launcher"); 11860 return false; 11861 } 11862 11863 if (packageName.equals(mRequiredInstallerPackage)) { 11864 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11865 + "\": required for package installation"); 11866 return false; 11867 } 11868 11869 if (packageName.equals(mRequiredVerifierPackage)) { 11870 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11871 + "\": required for package verification"); 11872 return false; 11873 } 11874 11875 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11876 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11877 + "\": is the default dialer"); 11878 return false; 11879 } 11880 11881 return true; 11882 } 11883 11884 private String getActiveLauncherPackageName(int userId) { 11885 Intent intent = new Intent(Intent.ACTION_MAIN); 11886 intent.addCategory(Intent.CATEGORY_HOME); 11887 ResolveInfo resolveInfo = resolveIntent( 11888 intent, 11889 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11890 PackageManager.MATCH_DEFAULT_ONLY, 11891 userId); 11892 11893 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11894 } 11895 11896 private String getDefaultDialerPackageName(int userId) { 11897 synchronized (mPackages) { 11898 return mSettings.getDefaultDialerPackageNameLPw(userId); 11899 } 11900 } 11901 11902 @Override 11903 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11904 mContext.enforceCallingOrSelfPermission( 11905 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11906 "Only package verification agents can verify applications"); 11907 11908 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11909 final PackageVerificationResponse response = new PackageVerificationResponse( 11910 verificationCode, Binder.getCallingUid()); 11911 msg.arg1 = id; 11912 msg.obj = response; 11913 mHandler.sendMessage(msg); 11914 } 11915 11916 @Override 11917 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11918 long millisecondsToDelay) { 11919 mContext.enforceCallingOrSelfPermission( 11920 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11921 "Only package verification agents can extend verification timeouts"); 11922 11923 final PackageVerificationState state = mPendingVerification.get(id); 11924 final PackageVerificationResponse response = new PackageVerificationResponse( 11925 verificationCodeAtTimeout, Binder.getCallingUid()); 11926 11927 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11928 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11929 } 11930 if (millisecondsToDelay < 0) { 11931 millisecondsToDelay = 0; 11932 } 11933 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11934 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11935 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11936 } 11937 11938 if ((state != null) && !state.timeoutExtended()) { 11939 state.extendTimeout(); 11940 11941 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11942 msg.arg1 = id; 11943 msg.obj = response; 11944 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11945 } 11946 } 11947 11948 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11949 int verificationCode, UserHandle user) { 11950 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11951 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11952 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11953 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11954 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11955 11956 mContext.sendBroadcastAsUser(intent, user, 11957 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11958 } 11959 11960 private ComponentName matchComponentForVerifier(String packageName, 11961 List<ResolveInfo> receivers) { 11962 ActivityInfo targetReceiver = null; 11963 11964 final int NR = receivers.size(); 11965 for (int i = 0; i < NR; i++) { 11966 final ResolveInfo info = receivers.get(i); 11967 if (info.activityInfo == null) { 11968 continue; 11969 } 11970 11971 if (packageName.equals(info.activityInfo.packageName)) { 11972 targetReceiver = info.activityInfo; 11973 break; 11974 } 11975 } 11976 11977 if (targetReceiver == null) { 11978 return null; 11979 } 11980 11981 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11982 } 11983 11984 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11985 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11986 if (pkgInfo.verifiers.length == 0) { 11987 return null; 11988 } 11989 11990 final int N = pkgInfo.verifiers.length; 11991 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11992 for (int i = 0; i < N; i++) { 11993 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11994 11995 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11996 receivers); 11997 if (comp == null) { 11998 continue; 11999 } 12000 12001 final int verifierUid = getUidForVerifier(verifierInfo); 12002 if (verifierUid == -1) { 12003 continue; 12004 } 12005 12006 if (DEBUG_VERIFY) { 12007 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 12008 + " with the correct signature"); 12009 } 12010 sufficientVerifiers.add(comp); 12011 verificationState.addSufficientVerifier(verifierUid); 12012 } 12013 12014 return sufficientVerifiers; 12015 } 12016 12017 private int getUidForVerifier(VerifierInfo verifierInfo) { 12018 synchronized (mPackages) { 12019 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 12020 if (pkg == null) { 12021 return -1; 12022 } else if (pkg.mSignatures.length != 1) { 12023 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12024 + " has more than one signature; ignoring"); 12025 return -1; 12026 } 12027 12028 /* 12029 * If the public key of the package's signature does not match 12030 * our expected public key, then this is a different package and 12031 * we should skip. 12032 */ 12033 12034 final byte[] expectedPublicKey; 12035 try { 12036 final Signature verifierSig = pkg.mSignatures[0]; 12037 final PublicKey publicKey = verifierSig.getPublicKey(); 12038 expectedPublicKey = publicKey.getEncoded(); 12039 } catch (CertificateException e) { 12040 return -1; 12041 } 12042 12043 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 12044 12045 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 12046 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 12047 + " does not have the expected public key; ignoring"); 12048 return -1; 12049 } 12050 12051 return pkg.applicationInfo.uid; 12052 } 12053 } 12054 12055 @Override 12056 public void finishPackageInstall(int token, boolean didLaunch) { 12057 enforceSystemOrRoot("Only the system is allowed to finish installs"); 12058 12059 if (DEBUG_INSTALL) { 12060 Slog.v(TAG, "BM finishing package install for " + token); 12061 } 12062 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12063 12064 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 12065 mHandler.sendMessage(msg); 12066 } 12067 12068 /** 12069 * Get the verification agent timeout. 12070 * 12071 * @return verification timeout in milliseconds 12072 */ 12073 private long getVerificationTimeout() { 12074 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 12075 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 12076 DEFAULT_VERIFICATION_TIMEOUT); 12077 } 12078 12079 /** 12080 * Get the default verification agent response code. 12081 * 12082 * @return default verification response code 12083 */ 12084 private int getDefaultVerificationResponse() { 12085 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12086 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 12087 DEFAULT_VERIFICATION_RESPONSE); 12088 } 12089 12090 /** 12091 * Check whether or not package verification has been enabled. 12092 * 12093 * @return true if verification should be performed 12094 */ 12095 private boolean isVerificationEnabled(int userId, int installFlags) { 12096 if (!DEFAULT_VERIFY_ENABLE) { 12097 return false; 12098 } 12099 // Ephemeral apps don't get the full verification treatment 12100 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 12101 if (DEBUG_EPHEMERAL) { 12102 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 12103 } 12104 return false; 12105 } 12106 12107 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 12108 12109 // Check if installing from ADB 12110 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 12111 // Do not run verification in a test harness environment 12112 if (ActivityManager.isRunningInTestHarness()) { 12113 return false; 12114 } 12115 if (ensureVerifyAppsEnabled) { 12116 return true; 12117 } 12118 // Check if the developer does not want package verification for ADB installs 12119 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12120 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 12121 return false; 12122 } 12123 } 12124 12125 if (ensureVerifyAppsEnabled) { 12126 return true; 12127 } 12128 12129 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 12130 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 12131 } 12132 12133 @Override 12134 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 12135 throws RemoteException { 12136 mContext.enforceCallingOrSelfPermission( 12137 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 12138 "Only intentfilter verification agents can verify applications"); 12139 12140 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 12141 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 12142 Binder.getCallingUid(), verificationCode, failedDomains); 12143 msg.arg1 = id; 12144 msg.obj = response; 12145 mHandler.sendMessage(msg); 12146 } 12147 12148 @Override 12149 public int getIntentVerificationStatus(String packageName, int userId) { 12150 synchronized (mPackages) { 12151 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 12152 } 12153 } 12154 12155 @Override 12156 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 12157 mContext.enforceCallingOrSelfPermission( 12158 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12159 12160 boolean result = false; 12161 synchronized (mPackages) { 12162 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 12163 } 12164 if (result) { 12165 scheduleWritePackageRestrictionsLocked(userId); 12166 } 12167 return result; 12168 } 12169 12170 @Override 12171 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 12172 String packageName) { 12173 synchronized (mPackages) { 12174 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 12175 } 12176 } 12177 12178 @Override 12179 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 12180 if (TextUtils.isEmpty(packageName)) { 12181 return ParceledListSlice.emptyList(); 12182 } 12183 synchronized (mPackages) { 12184 PackageParser.Package pkg = mPackages.get(packageName); 12185 if (pkg == null || pkg.activities == null) { 12186 return ParceledListSlice.emptyList(); 12187 } 12188 final int count = pkg.activities.size(); 12189 ArrayList<IntentFilter> result = new ArrayList<>(); 12190 for (int n=0; n<count; n++) { 12191 PackageParser.Activity activity = pkg.activities.get(n); 12192 if (activity.intents != null && activity.intents.size() > 0) { 12193 result.addAll(activity.intents); 12194 } 12195 } 12196 return new ParceledListSlice<>(result); 12197 } 12198 } 12199 12200 @Override 12201 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 12202 mContext.enforceCallingOrSelfPermission( 12203 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 12204 12205 synchronized (mPackages) { 12206 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 12207 if (packageName != null) { 12208 result |= updateIntentVerificationStatus(packageName, 12209 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 12210 userId); 12211 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 12212 packageName, userId); 12213 } 12214 return result; 12215 } 12216 } 12217 12218 @Override 12219 public String getDefaultBrowserPackageName(int userId) { 12220 synchronized (mPackages) { 12221 return mSettings.getDefaultBrowserPackageNameLPw(userId); 12222 } 12223 } 12224 12225 /** 12226 * Get the "allow unknown sources" setting. 12227 * 12228 * @return the current "allow unknown sources" setting 12229 */ 12230 private int getUnknownSourcesSettings() { 12231 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12232 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12233 -1); 12234 } 12235 12236 @Override 12237 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12238 final int uid = Binder.getCallingUid(); 12239 // writer 12240 synchronized (mPackages) { 12241 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12242 if (targetPackageSetting == null) { 12243 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12244 } 12245 12246 PackageSetting installerPackageSetting; 12247 if (installerPackageName != null) { 12248 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12249 if (installerPackageSetting == null) { 12250 throw new IllegalArgumentException("Unknown installer package: " 12251 + installerPackageName); 12252 } 12253 } else { 12254 installerPackageSetting = null; 12255 } 12256 12257 Signature[] callerSignature; 12258 Object obj = mSettings.getUserIdLPr(uid); 12259 if (obj != null) { 12260 if (obj instanceof SharedUserSetting) { 12261 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12262 } else if (obj instanceof PackageSetting) { 12263 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12264 } else { 12265 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12266 } 12267 } else { 12268 throw new SecurityException("Unknown calling UID: " + uid); 12269 } 12270 12271 // Verify: can't set installerPackageName to a package that is 12272 // not signed with the same cert as the caller. 12273 if (installerPackageSetting != null) { 12274 if (compareSignatures(callerSignature, 12275 installerPackageSetting.signatures.mSignatures) 12276 != PackageManager.SIGNATURE_MATCH) { 12277 throw new SecurityException( 12278 "Caller does not have same cert as new installer package " 12279 + installerPackageName); 12280 } 12281 } 12282 12283 // Verify: if target already has an installer package, it must 12284 // be signed with the same cert as the caller. 12285 if (targetPackageSetting.installerPackageName != null) { 12286 PackageSetting setting = mSettings.mPackages.get( 12287 targetPackageSetting.installerPackageName); 12288 // If the currently set package isn't valid, then it's always 12289 // okay to change it. 12290 if (setting != null) { 12291 if (compareSignatures(callerSignature, 12292 setting.signatures.mSignatures) 12293 != PackageManager.SIGNATURE_MATCH) { 12294 throw new SecurityException( 12295 "Caller does not have same cert as old installer package " 12296 + targetPackageSetting.installerPackageName); 12297 } 12298 } 12299 } 12300 12301 // Okay! 12302 targetPackageSetting.installerPackageName = installerPackageName; 12303 if (installerPackageName != null) { 12304 mSettings.mInstallerPackages.add(installerPackageName); 12305 } 12306 scheduleWriteSettingsLocked(); 12307 } 12308 } 12309 12310 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12311 // Queue up an async operation since the package installation may take a little while. 12312 mHandler.post(new Runnable() { 12313 public void run() { 12314 mHandler.removeCallbacks(this); 12315 // Result object to be returned 12316 PackageInstalledInfo res = new PackageInstalledInfo(); 12317 res.setReturnCode(currentStatus); 12318 res.uid = -1; 12319 res.pkg = null; 12320 res.removedInfo = null; 12321 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12322 args.doPreInstall(res.returnCode); 12323 synchronized (mInstallLock) { 12324 installPackageTracedLI(args, res); 12325 } 12326 args.doPostInstall(res.returnCode, res.uid); 12327 } 12328 12329 // A restore should be performed at this point if (a) the install 12330 // succeeded, (b) the operation is not an update, and (c) the new 12331 // package has not opted out of backup participation. 12332 final boolean update = res.removedInfo != null 12333 && res.removedInfo.removedPackage != null; 12334 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12335 boolean doRestore = !update 12336 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12337 12338 // Set up the post-install work request bookkeeping. This will be used 12339 // and cleaned up by the post-install event handling regardless of whether 12340 // there's a restore pass performed. Token values are >= 1. 12341 int token; 12342 if (mNextInstallToken < 0) mNextInstallToken = 1; 12343 token = mNextInstallToken++; 12344 12345 PostInstallData data = new PostInstallData(args, res); 12346 mRunningInstalls.put(token, data); 12347 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12348 12349 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12350 // Pass responsibility to the Backup Manager. It will perform a 12351 // restore if appropriate, then pass responsibility back to the 12352 // Package Manager to run the post-install observer callbacks 12353 // and broadcasts. 12354 IBackupManager bm = IBackupManager.Stub.asInterface( 12355 ServiceManager.getService(Context.BACKUP_SERVICE)); 12356 if (bm != null) { 12357 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12358 + " to BM for possible restore"); 12359 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12360 try { 12361 // TODO: http://b/22388012 12362 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12363 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12364 } else { 12365 doRestore = false; 12366 } 12367 } catch (RemoteException e) { 12368 // can't happen; the backup manager is local 12369 } catch (Exception e) { 12370 Slog.e(TAG, "Exception trying to enqueue restore", e); 12371 doRestore = false; 12372 } 12373 } else { 12374 Slog.e(TAG, "Backup Manager not found!"); 12375 doRestore = false; 12376 } 12377 } 12378 12379 if (!doRestore) { 12380 // No restore possible, or the Backup Manager was mysteriously not 12381 // available -- just fire the post-install work request directly. 12382 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12383 12384 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12385 12386 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12387 mHandler.sendMessage(msg); 12388 } 12389 } 12390 }); 12391 } 12392 12393 /** 12394 * Callback from PackageSettings whenever an app is first transitioned out of the 12395 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12396 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12397 * here whether the app is the target of an ongoing install, and only send the 12398 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12399 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12400 * handling. 12401 */ 12402 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12403 // Serialize this with the rest of the install-process message chain. In the 12404 // restore-at-install case, this Runnable will necessarily run before the 12405 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12406 // are coherent. In the non-restore case, the app has already completed install 12407 // and been launched through some other means, so it is not in a problematic 12408 // state for observers to see the FIRST_LAUNCH signal. 12409 mHandler.post(new Runnable() { 12410 @Override 12411 public void run() { 12412 for (int i = 0; i < mRunningInstalls.size(); i++) { 12413 final PostInstallData data = mRunningInstalls.valueAt(i); 12414 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12415 // right package; but is it for the right user? 12416 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12417 if (userId == data.res.newUsers[uIndex]) { 12418 if (DEBUG_BACKUP) { 12419 Slog.i(TAG, "Package " + pkgName 12420 + " being restored so deferring FIRST_LAUNCH"); 12421 } 12422 return; 12423 } 12424 } 12425 } 12426 } 12427 // didn't find it, so not being restored 12428 if (DEBUG_BACKUP) { 12429 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12430 } 12431 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12432 } 12433 }); 12434 } 12435 12436 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12437 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12438 installerPkg, null, userIds); 12439 } 12440 12441 private abstract class HandlerParams { 12442 private static final int MAX_RETRIES = 4; 12443 12444 /** 12445 * Number of times startCopy() has been attempted and had a non-fatal 12446 * error. 12447 */ 12448 private int mRetries = 0; 12449 12450 /** User handle for the user requesting the information or installation. */ 12451 private final UserHandle mUser; 12452 String traceMethod; 12453 int traceCookie; 12454 12455 HandlerParams(UserHandle user) { 12456 mUser = user; 12457 } 12458 12459 UserHandle getUser() { 12460 return mUser; 12461 } 12462 12463 HandlerParams setTraceMethod(String traceMethod) { 12464 this.traceMethod = traceMethod; 12465 return this; 12466 } 12467 12468 HandlerParams setTraceCookie(int traceCookie) { 12469 this.traceCookie = traceCookie; 12470 return this; 12471 } 12472 12473 final boolean startCopy() { 12474 boolean res; 12475 try { 12476 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12477 12478 if (++mRetries > MAX_RETRIES) { 12479 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12480 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12481 handleServiceError(); 12482 return false; 12483 } else { 12484 handleStartCopy(); 12485 res = true; 12486 } 12487 } catch (RemoteException e) { 12488 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12489 mHandler.sendEmptyMessage(MCS_RECONNECT); 12490 res = false; 12491 } 12492 handleReturnCode(); 12493 return res; 12494 } 12495 12496 final void serviceError() { 12497 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12498 handleServiceError(); 12499 handleReturnCode(); 12500 } 12501 12502 abstract void handleStartCopy() throws RemoteException; 12503 abstract void handleServiceError(); 12504 abstract void handleReturnCode(); 12505 } 12506 12507 class MeasureParams extends HandlerParams { 12508 private final PackageStats mStats; 12509 private boolean mSuccess; 12510 12511 private final IPackageStatsObserver mObserver; 12512 12513 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12514 super(new UserHandle(stats.userHandle)); 12515 mObserver = observer; 12516 mStats = stats; 12517 } 12518 12519 @Override 12520 public String toString() { 12521 return "MeasureParams{" 12522 + Integer.toHexString(System.identityHashCode(this)) 12523 + " " + mStats.packageName + "}"; 12524 } 12525 12526 @Override 12527 void handleStartCopy() throws RemoteException { 12528 synchronized (mInstallLock) { 12529 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12530 } 12531 12532 if (mSuccess) { 12533 final boolean mounted; 12534 if (Environment.isExternalStorageEmulated()) { 12535 mounted = true; 12536 } else { 12537 final String status = Environment.getExternalStorageState(); 12538 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12539 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12540 } 12541 12542 if (mounted) { 12543 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12544 12545 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12546 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12547 12548 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12549 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12550 12551 // Always subtract cache size, since it's a subdirectory 12552 mStats.externalDataSize -= mStats.externalCacheSize; 12553 12554 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12555 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12556 12557 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12558 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12559 } 12560 } 12561 } 12562 12563 @Override 12564 void handleReturnCode() { 12565 if (mObserver != null) { 12566 try { 12567 mObserver.onGetStatsCompleted(mStats, mSuccess); 12568 } catch (RemoteException e) { 12569 Slog.i(TAG, "Observer no longer exists."); 12570 } 12571 } 12572 } 12573 12574 @Override 12575 void handleServiceError() { 12576 Slog.e(TAG, "Could not measure application " + mStats.packageName 12577 + " external storage"); 12578 } 12579 } 12580 12581 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12582 throws RemoteException { 12583 long result = 0; 12584 for (File path : paths) { 12585 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12586 } 12587 return result; 12588 } 12589 12590 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12591 for (File path : paths) { 12592 try { 12593 mcs.clearDirectory(path.getAbsolutePath()); 12594 } catch (RemoteException e) { 12595 } 12596 } 12597 } 12598 12599 static class OriginInfo { 12600 /** 12601 * Location where install is coming from, before it has been 12602 * copied/renamed into place. This could be a single monolithic APK 12603 * file, or a cluster directory. This location may be untrusted. 12604 */ 12605 final File file; 12606 final String cid; 12607 12608 /** 12609 * Flag indicating that {@link #file} or {@link #cid} has already been 12610 * staged, meaning downstream users don't need to defensively copy the 12611 * contents. 12612 */ 12613 final boolean staged; 12614 12615 /** 12616 * Flag indicating that {@link #file} or {@link #cid} is an already 12617 * installed app that is being moved. 12618 */ 12619 final boolean existing; 12620 12621 final String resolvedPath; 12622 final File resolvedFile; 12623 12624 static OriginInfo fromNothing() { 12625 return new OriginInfo(null, null, false, false); 12626 } 12627 12628 static OriginInfo fromUntrustedFile(File file) { 12629 return new OriginInfo(file, null, false, false); 12630 } 12631 12632 static OriginInfo fromExistingFile(File file) { 12633 return new OriginInfo(file, null, false, true); 12634 } 12635 12636 static OriginInfo fromStagedFile(File file) { 12637 return new OriginInfo(file, null, true, false); 12638 } 12639 12640 static OriginInfo fromStagedContainer(String cid) { 12641 return new OriginInfo(null, cid, true, false); 12642 } 12643 12644 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12645 this.file = file; 12646 this.cid = cid; 12647 this.staged = staged; 12648 this.existing = existing; 12649 12650 if (cid != null) { 12651 resolvedPath = PackageHelper.getSdDir(cid); 12652 resolvedFile = new File(resolvedPath); 12653 } else if (file != null) { 12654 resolvedPath = file.getAbsolutePath(); 12655 resolvedFile = file; 12656 } else { 12657 resolvedPath = null; 12658 resolvedFile = null; 12659 } 12660 } 12661 } 12662 12663 static class MoveInfo { 12664 final int moveId; 12665 final String fromUuid; 12666 final String toUuid; 12667 final String packageName; 12668 final String dataAppName; 12669 final int appId; 12670 final String seinfo; 12671 final int targetSdkVersion; 12672 12673 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12674 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12675 this.moveId = moveId; 12676 this.fromUuid = fromUuid; 12677 this.toUuid = toUuid; 12678 this.packageName = packageName; 12679 this.dataAppName = dataAppName; 12680 this.appId = appId; 12681 this.seinfo = seinfo; 12682 this.targetSdkVersion = targetSdkVersion; 12683 } 12684 } 12685 12686 static class VerificationInfo { 12687 /** A constant used to indicate that a uid value is not present. */ 12688 public static final int NO_UID = -1; 12689 12690 /** URI referencing where the package was downloaded from. */ 12691 final Uri originatingUri; 12692 12693 /** HTTP referrer URI associated with the originatingURI. */ 12694 final Uri referrer; 12695 12696 /** UID of the application that the install request originated from. */ 12697 final int originatingUid; 12698 12699 /** UID of application requesting the install */ 12700 final int installerUid; 12701 12702 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12703 this.originatingUri = originatingUri; 12704 this.referrer = referrer; 12705 this.originatingUid = originatingUid; 12706 this.installerUid = installerUid; 12707 } 12708 } 12709 12710 class InstallParams extends HandlerParams { 12711 final OriginInfo origin; 12712 final MoveInfo move; 12713 final IPackageInstallObserver2 observer; 12714 int installFlags; 12715 final String installerPackageName; 12716 final String volumeUuid; 12717 private InstallArgs mArgs; 12718 private int mRet; 12719 final String packageAbiOverride; 12720 final String[] grantedRuntimePermissions; 12721 final VerificationInfo verificationInfo; 12722 final Certificate[][] certificates; 12723 12724 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12725 int installFlags, String installerPackageName, String volumeUuid, 12726 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12727 String[] grantedPermissions, Certificate[][] certificates) { 12728 super(user); 12729 this.origin = origin; 12730 this.move = move; 12731 this.observer = observer; 12732 this.installFlags = installFlags; 12733 this.installerPackageName = installerPackageName; 12734 this.volumeUuid = volumeUuid; 12735 this.verificationInfo = verificationInfo; 12736 this.packageAbiOverride = packageAbiOverride; 12737 this.grantedRuntimePermissions = grantedPermissions; 12738 this.certificates = certificates; 12739 } 12740 12741 @Override 12742 public String toString() { 12743 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12744 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12745 } 12746 12747 private int installLocationPolicy(PackageInfoLite pkgLite) { 12748 String packageName = pkgLite.packageName; 12749 int installLocation = pkgLite.installLocation; 12750 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12751 // reader 12752 synchronized (mPackages) { 12753 // Currently installed package which the new package is attempting to replace or 12754 // null if no such package is installed. 12755 PackageParser.Package installedPkg = mPackages.get(packageName); 12756 // Package which currently owns the data which the new package will own if installed. 12757 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12758 // will be null whereas dataOwnerPkg will contain information about the package 12759 // which was uninstalled while keeping its data. 12760 PackageParser.Package dataOwnerPkg = installedPkg; 12761 if (dataOwnerPkg == null) { 12762 PackageSetting ps = mSettings.mPackages.get(packageName); 12763 if (ps != null) { 12764 dataOwnerPkg = ps.pkg; 12765 } 12766 } 12767 12768 if (dataOwnerPkg != null) { 12769 // If installed, the package will get access to data left on the device by its 12770 // predecessor. As a security measure, this is permited only if this is not a 12771 // version downgrade or if the predecessor package is marked as debuggable and 12772 // a downgrade is explicitly requested. 12773 // 12774 // On debuggable platform builds, downgrades are permitted even for 12775 // non-debuggable packages to make testing easier. Debuggable platform builds do 12776 // not offer security guarantees and thus it's OK to disable some security 12777 // mechanisms to make debugging/testing easier on those builds. However, even on 12778 // debuggable builds downgrades of packages are permitted only if requested via 12779 // installFlags. This is because we aim to keep the behavior of debuggable 12780 // platform builds as close as possible to the behavior of non-debuggable 12781 // platform builds. 12782 final boolean downgradeRequested = 12783 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12784 final boolean packageDebuggable = 12785 (dataOwnerPkg.applicationInfo.flags 12786 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12787 final boolean downgradePermitted = 12788 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12789 if (!downgradePermitted) { 12790 try { 12791 checkDowngrade(dataOwnerPkg, pkgLite); 12792 } catch (PackageManagerException e) { 12793 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12794 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12795 } 12796 } 12797 } 12798 12799 if (installedPkg != null) { 12800 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12801 // Check for updated system application. 12802 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12803 if (onSd) { 12804 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12805 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12806 } 12807 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12808 } else { 12809 if (onSd) { 12810 // Install flag overrides everything. 12811 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12812 } 12813 // If current upgrade specifies particular preference 12814 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12815 // Application explicitly specified internal. 12816 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12817 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12818 // App explictly prefers external. Let policy decide 12819 } else { 12820 // Prefer previous location 12821 if (isExternal(installedPkg)) { 12822 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12823 } 12824 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12825 } 12826 } 12827 } else { 12828 // Invalid install. Return error code 12829 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12830 } 12831 } 12832 } 12833 // All the special cases have been taken care of. 12834 // Return result based on recommended install location. 12835 if (onSd) { 12836 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12837 } 12838 return pkgLite.recommendedInstallLocation; 12839 } 12840 12841 /* 12842 * Invoke remote method to get package information and install 12843 * location values. Override install location based on default 12844 * policy if needed and then create install arguments based 12845 * on the install location. 12846 */ 12847 public void handleStartCopy() throws RemoteException { 12848 int ret = PackageManager.INSTALL_SUCCEEDED; 12849 12850 // If we're already staged, we've firmly committed to an install location 12851 if (origin.staged) { 12852 if (origin.file != null) { 12853 installFlags |= PackageManager.INSTALL_INTERNAL; 12854 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12855 } else if (origin.cid != null) { 12856 installFlags |= PackageManager.INSTALL_EXTERNAL; 12857 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12858 } else { 12859 throw new IllegalStateException("Invalid stage location"); 12860 } 12861 } 12862 12863 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12864 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12865 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12866 PackageInfoLite pkgLite = null; 12867 12868 if (onInt && onSd) { 12869 // Check if both bits are set. 12870 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12871 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12872 } else if (onSd && ephemeral) { 12873 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12874 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12875 } else { 12876 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12877 packageAbiOverride); 12878 12879 if (DEBUG_EPHEMERAL && ephemeral) { 12880 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12881 } 12882 12883 /* 12884 * If we have too little free space, try to free cache 12885 * before giving up. 12886 */ 12887 if (!origin.staged && pkgLite.recommendedInstallLocation 12888 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12889 // TODO: focus freeing disk space on the target device 12890 final StorageManager storage = StorageManager.from(mContext); 12891 final long lowThreshold = storage.getStorageLowBytes( 12892 Environment.getDataDirectory()); 12893 12894 final long sizeBytes = mContainerService.calculateInstalledSize( 12895 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12896 12897 try { 12898 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12899 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12900 installFlags, packageAbiOverride); 12901 } catch (InstallerException e) { 12902 Slog.w(TAG, "Failed to free cache", e); 12903 } 12904 12905 /* 12906 * The cache free must have deleted the file we 12907 * downloaded to install. 12908 * 12909 * TODO: fix the "freeCache" call to not delete 12910 * the file we care about. 12911 */ 12912 if (pkgLite.recommendedInstallLocation 12913 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12914 pkgLite.recommendedInstallLocation 12915 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12916 } 12917 } 12918 } 12919 12920 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12921 int loc = pkgLite.recommendedInstallLocation; 12922 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12923 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12924 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12925 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12926 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12927 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12928 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12929 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12930 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12931 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12932 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12933 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12934 } else { 12935 // Override with defaults if needed. 12936 loc = installLocationPolicy(pkgLite); 12937 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12938 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12939 } else if (!onSd && !onInt) { 12940 // Override install location with flags 12941 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12942 // Set the flag to install on external media. 12943 installFlags |= PackageManager.INSTALL_EXTERNAL; 12944 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12945 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12946 if (DEBUG_EPHEMERAL) { 12947 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12948 } 12949 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12950 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12951 |PackageManager.INSTALL_INTERNAL); 12952 } else { 12953 // Make sure the flag for installing on external 12954 // media is unset 12955 installFlags |= PackageManager.INSTALL_INTERNAL; 12956 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12957 } 12958 } 12959 } 12960 } 12961 12962 final InstallArgs args = createInstallArgs(this); 12963 mArgs = args; 12964 12965 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12966 // TODO: http://b/22976637 12967 // Apps installed for "all" users use the device owner to verify the app 12968 UserHandle verifierUser = getUser(); 12969 if (verifierUser == UserHandle.ALL) { 12970 verifierUser = UserHandle.SYSTEM; 12971 } 12972 12973 /* 12974 * Determine if we have any installed package verifiers. If we 12975 * do, then we'll defer to them to verify the packages. 12976 */ 12977 final int requiredUid = mRequiredVerifierPackage == null ? -1 12978 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12979 verifierUser.getIdentifier()); 12980 if (!origin.existing && requiredUid != -1 12981 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12982 final Intent verification = new Intent( 12983 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12984 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12985 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12986 PACKAGE_MIME_TYPE); 12987 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12988 12989 // Query all live verifiers based on current user state 12990 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12991 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12992 12993 if (DEBUG_VERIFY) { 12994 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12995 + verification.toString() + " with " + pkgLite.verifiers.length 12996 + " optional verifiers"); 12997 } 12998 12999 final int verificationId = mPendingVerificationToken++; 13000 13001 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 13002 13003 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 13004 installerPackageName); 13005 13006 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 13007 installFlags); 13008 13009 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 13010 pkgLite.packageName); 13011 13012 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 13013 pkgLite.versionCode); 13014 13015 if (verificationInfo != null) { 13016 if (verificationInfo.originatingUri != null) { 13017 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 13018 verificationInfo.originatingUri); 13019 } 13020 if (verificationInfo.referrer != null) { 13021 verification.putExtra(Intent.EXTRA_REFERRER, 13022 verificationInfo.referrer); 13023 } 13024 if (verificationInfo.originatingUid >= 0) { 13025 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 13026 verificationInfo.originatingUid); 13027 } 13028 if (verificationInfo.installerUid >= 0) { 13029 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 13030 verificationInfo.installerUid); 13031 } 13032 } 13033 13034 final PackageVerificationState verificationState = new PackageVerificationState( 13035 requiredUid, args); 13036 13037 mPendingVerification.append(verificationId, verificationState); 13038 13039 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 13040 receivers, verificationState); 13041 13042 /* 13043 * If any sufficient verifiers were listed in the package 13044 * manifest, attempt to ask them. 13045 */ 13046 if (sufficientVerifiers != null) { 13047 final int N = sufficientVerifiers.size(); 13048 if (N == 0) { 13049 Slog.i(TAG, "Additional verifiers required, but none installed."); 13050 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 13051 } else { 13052 for (int i = 0; i < N; i++) { 13053 final ComponentName verifierComponent = sufficientVerifiers.get(i); 13054 13055 final Intent sufficientIntent = new Intent(verification); 13056 sufficientIntent.setComponent(verifierComponent); 13057 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 13058 } 13059 } 13060 } 13061 13062 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 13063 mRequiredVerifierPackage, receivers); 13064 if (ret == PackageManager.INSTALL_SUCCEEDED 13065 && mRequiredVerifierPackage != null) { 13066 Trace.asyncTraceBegin( 13067 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 13068 /* 13069 * Send the intent to the required verification agent, 13070 * but only start the verification timeout after the 13071 * target BroadcastReceivers have run. 13072 */ 13073 verification.setComponent(requiredVerifierComponent); 13074 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 13075 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 13076 new BroadcastReceiver() { 13077 @Override 13078 public void onReceive(Context context, Intent intent) { 13079 final Message msg = mHandler 13080 .obtainMessage(CHECK_PENDING_VERIFICATION); 13081 msg.arg1 = verificationId; 13082 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 13083 } 13084 }, null, 0, null, null); 13085 13086 /* 13087 * We don't want the copy to proceed until verification 13088 * succeeds, so null out this field. 13089 */ 13090 mArgs = null; 13091 } 13092 } else { 13093 /* 13094 * No package verification is enabled, so immediately start 13095 * the remote call to initiate copy using temporary file. 13096 */ 13097 ret = args.copyApk(mContainerService, true); 13098 } 13099 } 13100 13101 mRet = ret; 13102 } 13103 13104 @Override 13105 void handleReturnCode() { 13106 // If mArgs is null, then MCS couldn't be reached. When it 13107 // reconnects, it will try again to install. At that point, this 13108 // will succeed. 13109 if (mArgs != null) { 13110 processPendingInstall(mArgs, mRet); 13111 } 13112 } 13113 13114 @Override 13115 void handleServiceError() { 13116 mArgs = createInstallArgs(this); 13117 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13118 } 13119 13120 public boolean isForwardLocked() { 13121 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13122 } 13123 } 13124 13125 /** 13126 * Used during creation of InstallArgs 13127 * 13128 * @param installFlags package installation flags 13129 * @return true if should be installed on external storage 13130 */ 13131 private static boolean installOnExternalAsec(int installFlags) { 13132 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 13133 return false; 13134 } 13135 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 13136 return true; 13137 } 13138 return false; 13139 } 13140 13141 /** 13142 * Used during creation of InstallArgs 13143 * 13144 * @param installFlags package installation flags 13145 * @return true if should be installed as forward locked 13146 */ 13147 private static boolean installForwardLocked(int installFlags) { 13148 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13149 } 13150 13151 private InstallArgs createInstallArgs(InstallParams params) { 13152 if (params.move != null) { 13153 return new MoveInstallArgs(params); 13154 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 13155 return new AsecInstallArgs(params); 13156 } else { 13157 return new FileInstallArgs(params); 13158 } 13159 } 13160 13161 /** 13162 * Create args that describe an existing installed package. Typically used 13163 * when cleaning up old installs, or used as a move source. 13164 */ 13165 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 13166 String resourcePath, String[] instructionSets) { 13167 final boolean isInAsec; 13168 if (installOnExternalAsec(installFlags)) { 13169 /* Apps on SD card are always in ASEC containers. */ 13170 isInAsec = true; 13171 } else if (installForwardLocked(installFlags) 13172 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 13173 /* 13174 * Forward-locked apps are only in ASEC containers if they're the 13175 * new style 13176 */ 13177 isInAsec = true; 13178 } else { 13179 isInAsec = false; 13180 } 13181 13182 if (isInAsec) { 13183 return new AsecInstallArgs(codePath, instructionSets, 13184 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 13185 } else { 13186 return new FileInstallArgs(codePath, resourcePath, instructionSets); 13187 } 13188 } 13189 13190 static abstract class InstallArgs { 13191 /** @see InstallParams#origin */ 13192 final OriginInfo origin; 13193 /** @see InstallParams#move */ 13194 final MoveInfo move; 13195 13196 final IPackageInstallObserver2 observer; 13197 // Always refers to PackageManager flags only 13198 final int installFlags; 13199 final String installerPackageName; 13200 final String volumeUuid; 13201 final UserHandle user; 13202 final String abiOverride; 13203 final String[] installGrantPermissions; 13204 /** If non-null, drop an async trace when the install completes */ 13205 final String traceMethod; 13206 final int traceCookie; 13207 final Certificate[][] certificates; 13208 13209 // The list of instruction sets supported by this app. This is currently 13210 // only used during the rmdex() phase to clean up resources. We can get rid of this 13211 // if we move dex files under the common app path. 13212 /* nullable */ String[] instructionSets; 13213 13214 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 13215 int installFlags, String installerPackageName, String volumeUuid, 13216 UserHandle user, String[] instructionSets, 13217 String abiOverride, String[] installGrantPermissions, 13218 String traceMethod, int traceCookie, Certificate[][] certificates) { 13219 this.origin = origin; 13220 this.move = move; 13221 this.installFlags = installFlags; 13222 this.observer = observer; 13223 this.installerPackageName = installerPackageName; 13224 this.volumeUuid = volumeUuid; 13225 this.user = user; 13226 this.instructionSets = instructionSets; 13227 this.abiOverride = abiOverride; 13228 this.installGrantPermissions = installGrantPermissions; 13229 this.traceMethod = traceMethod; 13230 this.traceCookie = traceCookie; 13231 this.certificates = certificates; 13232 } 13233 13234 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13235 abstract int doPreInstall(int status); 13236 13237 /** 13238 * Rename package into final resting place. All paths on the given 13239 * scanned package should be updated to reflect the rename. 13240 */ 13241 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13242 abstract int doPostInstall(int status, int uid); 13243 13244 /** @see PackageSettingBase#codePathString */ 13245 abstract String getCodePath(); 13246 /** @see PackageSettingBase#resourcePathString */ 13247 abstract String getResourcePath(); 13248 13249 // Need installer lock especially for dex file removal. 13250 abstract void cleanUpResourcesLI(); 13251 abstract boolean doPostDeleteLI(boolean delete); 13252 13253 /** 13254 * Called before the source arguments are copied. This is used mostly 13255 * for MoveParams when it needs to read the source file to put it in the 13256 * destination. 13257 */ 13258 int doPreCopy() { 13259 return PackageManager.INSTALL_SUCCEEDED; 13260 } 13261 13262 /** 13263 * Called after the source arguments are copied. This is used mostly for 13264 * MoveParams when it needs to read the source file to put it in the 13265 * destination. 13266 */ 13267 int doPostCopy(int uid) { 13268 return PackageManager.INSTALL_SUCCEEDED; 13269 } 13270 13271 protected boolean isFwdLocked() { 13272 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13273 } 13274 13275 protected boolean isExternalAsec() { 13276 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13277 } 13278 13279 protected boolean isEphemeral() { 13280 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13281 } 13282 13283 UserHandle getUser() { 13284 return user; 13285 } 13286 } 13287 13288 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13289 if (!allCodePaths.isEmpty()) { 13290 if (instructionSets == null) { 13291 throw new IllegalStateException("instructionSet == null"); 13292 } 13293 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13294 for (String codePath : allCodePaths) { 13295 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13296 try { 13297 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13298 } catch (InstallerException ignored) { 13299 } 13300 } 13301 } 13302 } 13303 } 13304 13305 /** 13306 * Logic to handle installation of non-ASEC applications, including copying 13307 * and renaming logic. 13308 */ 13309 class FileInstallArgs extends InstallArgs { 13310 private File codeFile; 13311 private File resourceFile; 13312 13313 // Example topology: 13314 // /data/app/com.example/base.apk 13315 // /data/app/com.example/split_foo.apk 13316 // /data/app/com.example/lib/arm/libfoo.so 13317 // /data/app/com.example/lib/arm64/libfoo.so 13318 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13319 13320 /** New install */ 13321 FileInstallArgs(InstallParams params) { 13322 super(params.origin, params.move, params.observer, params.installFlags, 13323 params.installerPackageName, params.volumeUuid, 13324 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13325 params.grantedRuntimePermissions, 13326 params.traceMethod, params.traceCookie, params.certificates); 13327 if (isFwdLocked()) { 13328 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13329 } 13330 } 13331 13332 /** Existing install */ 13333 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13334 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13335 null, null, null, 0, null /*certificates*/); 13336 this.codeFile = (codePath != null) ? new File(codePath) : null; 13337 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13338 } 13339 13340 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13341 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13342 try { 13343 return doCopyApk(imcs, temp); 13344 } finally { 13345 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13346 } 13347 } 13348 13349 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13350 if (origin.staged) { 13351 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13352 codeFile = origin.file; 13353 resourceFile = origin.file; 13354 return PackageManager.INSTALL_SUCCEEDED; 13355 } 13356 13357 try { 13358 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13359 final File tempDir = 13360 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13361 codeFile = tempDir; 13362 resourceFile = tempDir; 13363 } catch (IOException e) { 13364 Slog.w(TAG, "Failed to create copy file: " + e); 13365 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13366 } 13367 13368 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13369 @Override 13370 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13371 if (!FileUtils.isValidExtFilename(name)) { 13372 throw new IllegalArgumentException("Invalid filename: " + name); 13373 } 13374 try { 13375 final File file = new File(codeFile, name); 13376 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13377 O_RDWR | O_CREAT, 0644); 13378 Os.chmod(file.getAbsolutePath(), 0644); 13379 return new ParcelFileDescriptor(fd); 13380 } catch (ErrnoException e) { 13381 throw new RemoteException("Failed to open: " + e.getMessage()); 13382 } 13383 } 13384 }; 13385 13386 int ret = PackageManager.INSTALL_SUCCEEDED; 13387 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13388 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13389 Slog.e(TAG, "Failed to copy package"); 13390 return ret; 13391 } 13392 13393 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13394 NativeLibraryHelper.Handle handle = null; 13395 try { 13396 handle = NativeLibraryHelper.Handle.create(codeFile); 13397 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13398 abiOverride); 13399 } catch (IOException e) { 13400 Slog.e(TAG, "Copying native libraries failed", e); 13401 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13402 } finally { 13403 IoUtils.closeQuietly(handle); 13404 } 13405 13406 return ret; 13407 } 13408 13409 int doPreInstall(int status) { 13410 if (status != PackageManager.INSTALL_SUCCEEDED) { 13411 cleanUp(); 13412 } 13413 return status; 13414 } 13415 13416 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13417 if (status != PackageManager.INSTALL_SUCCEEDED) { 13418 cleanUp(); 13419 return false; 13420 } 13421 13422 final File targetDir = codeFile.getParentFile(); 13423 final File beforeCodeFile = codeFile; 13424 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13425 13426 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13427 try { 13428 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13429 } catch (ErrnoException e) { 13430 Slog.w(TAG, "Failed to rename", e); 13431 return false; 13432 } 13433 13434 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13435 Slog.w(TAG, "Failed to restorecon"); 13436 return false; 13437 } 13438 13439 // Reflect the rename internally 13440 codeFile = afterCodeFile; 13441 resourceFile = afterCodeFile; 13442 13443 // Reflect the rename in scanned details 13444 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13445 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13446 afterCodeFile, pkg.baseCodePath)); 13447 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13448 afterCodeFile, pkg.splitCodePaths)); 13449 13450 // Reflect the rename in app info 13451 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13452 pkg.setApplicationInfoCodePath(pkg.codePath); 13453 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13454 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13455 pkg.setApplicationInfoResourcePath(pkg.codePath); 13456 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13457 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13458 13459 return true; 13460 } 13461 13462 int doPostInstall(int status, int uid) { 13463 if (status != PackageManager.INSTALL_SUCCEEDED) { 13464 cleanUp(); 13465 } 13466 return status; 13467 } 13468 13469 @Override 13470 String getCodePath() { 13471 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13472 } 13473 13474 @Override 13475 String getResourcePath() { 13476 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13477 } 13478 13479 private boolean cleanUp() { 13480 if (codeFile == null || !codeFile.exists()) { 13481 return false; 13482 } 13483 13484 removeCodePathLI(codeFile); 13485 13486 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13487 resourceFile.delete(); 13488 } 13489 13490 return true; 13491 } 13492 13493 void cleanUpResourcesLI() { 13494 // Try enumerating all code paths before deleting 13495 List<String> allCodePaths = Collections.EMPTY_LIST; 13496 if (codeFile != null && codeFile.exists()) { 13497 try { 13498 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13499 allCodePaths = pkg.getAllCodePaths(); 13500 } catch (PackageParserException e) { 13501 // Ignored; we tried our best 13502 } 13503 } 13504 13505 cleanUp(); 13506 removeDexFiles(allCodePaths, instructionSets); 13507 } 13508 13509 boolean doPostDeleteLI(boolean delete) { 13510 // XXX err, shouldn't we respect the delete flag? 13511 cleanUpResourcesLI(); 13512 return true; 13513 } 13514 } 13515 13516 private boolean isAsecExternal(String cid) { 13517 final String asecPath = PackageHelper.getSdFilesystem(cid); 13518 return !asecPath.startsWith(mAsecInternalPath); 13519 } 13520 13521 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13522 PackageManagerException { 13523 if (copyRet < 0) { 13524 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13525 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13526 throw new PackageManagerException(copyRet, message); 13527 } 13528 } 13529 } 13530 13531 /** 13532 * Extract the MountService "container ID" from the full code path of an 13533 * .apk. 13534 */ 13535 static String cidFromCodePath(String fullCodePath) { 13536 int eidx = fullCodePath.lastIndexOf("/"); 13537 String subStr1 = fullCodePath.substring(0, eidx); 13538 int sidx = subStr1.lastIndexOf("/"); 13539 return subStr1.substring(sidx+1, eidx); 13540 } 13541 13542 /** 13543 * Logic to handle installation of ASEC applications, including copying and 13544 * renaming logic. 13545 */ 13546 class AsecInstallArgs extends InstallArgs { 13547 static final String RES_FILE_NAME = "pkg.apk"; 13548 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13549 13550 String cid; 13551 String packagePath; 13552 String resourcePath; 13553 13554 /** New install */ 13555 AsecInstallArgs(InstallParams params) { 13556 super(params.origin, params.move, params.observer, params.installFlags, 13557 params.installerPackageName, params.volumeUuid, 13558 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13559 params.grantedRuntimePermissions, 13560 params.traceMethod, params.traceCookie, params.certificates); 13561 } 13562 13563 /** Existing install */ 13564 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13565 boolean isExternal, boolean isForwardLocked) { 13566 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13567 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13568 instructionSets, null, null, null, 0, null /*certificates*/); 13569 // Hackily pretend we're still looking at a full code path 13570 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13571 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13572 } 13573 13574 // Extract cid from fullCodePath 13575 int eidx = fullCodePath.lastIndexOf("/"); 13576 String subStr1 = fullCodePath.substring(0, eidx); 13577 int sidx = subStr1.lastIndexOf("/"); 13578 cid = subStr1.substring(sidx+1, eidx); 13579 setMountPath(subStr1); 13580 } 13581 13582 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13583 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13584 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13585 instructionSets, null, null, null, 0, null /*certificates*/); 13586 this.cid = cid; 13587 setMountPath(PackageHelper.getSdDir(cid)); 13588 } 13589 13590 void createCopyFile() { 13591 cid = mInstallerService.allocateExternalStageCidLegacy(); 13592 } 13593 13594 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13595 if (origin.staged && origin.cid != null) { 13596 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13597 cid = origin.cid; 13598 setMountPath(PackageHelper.getSdDir(cid)); 13599 return PackageManager.INSTALL_SUCCEEDED; 13600 } 13601 13602 if (temp) { 13603 createCopyFile(); 13604 } else { 13605 /* 13606 * Pre-emptively destroy the container since it's destroyed if 13607 * copying fails due to it existing anyway. 13608 */ 13609 PackageHelper.destroySdDir(cid); 13610 } 13611 13612 final String newMountPath = imcs.copyPackageToContainer( 13613 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13614 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13615 13616 if (newMountPath != null) { 13617 setMountPath(newMountPath); 13618 return PackageManager.INSTALL_SUCCEEDED; 13619 } else { 13620 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13621 } 13622 } 13623 13624 @Override 13625 String getCodePath() { 13626 return packagePath; 13627 } 13628 13629 @Override 13630 String getResourcePath() { 13631 return resourcePath; 13632 } 13633 13634 int doPreInstall(int status) { 13635 if (status != PackageManager.INSTALL_SUCCEEDED) { 13636 // Destroy container 13637 PackageHelper.destroySdDir(cid); 13638 } else { 13639 boolean mounted = PackageHelper.isContainerMounted(cid); 13640 if (!mounted) { 13641 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13642 Process.SYSTEM_UID); 13643 if (newMountPath != null) { 13644 setMountPath(newMountPath); 13645 } else { 13646 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13647 } 13648 } 13649 } 13650 return status; 13651 } 13652 13653 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13654 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13655 String newMountPath = null; 13656 if (PackageHelper.isContainerMounted(cid)) { 13657 // Unmount the container 13658 if (!PackageHelper.unMountSdDir(cid)) { 13659 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13660 return false; 13661 } 13662 } 13663 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13664 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13665 " which might be stale. Will try to clean up."); 13666 // Clean up the stale container and proceed to recreate. 13667 if (!PackageHelper.destroySdDir(newCacheId)) { 13668 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13669 return false; 13670 } 13671 // Successfully cleaned up stale container. Try to rename again. 13672 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13673 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13674 + " inspite of cleaning it up."); 13675 return false; 13676 } 13677 } 13678 if (!PackageHelper.isContainerMounted(newCacheId)) { 13679 Slog.w(TAG, "Mounting container " + newCacheId); 13680 newMountPath = PackageHelper.mountSdDir(newCacheId, 13681 getEncryptKey(), Process.SYSTEM_UID); 13682 } else { 13683 newMountPath = PackageHelper.getSdDir(newCacheId); 13684 } 13685 if (newMountPath == null) { 13686 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13687 return false; 13688 } 13689 Log.i(TAG, "Succesfully renamed " + cid + 13690 " to " + newCacheId + 13691 " at new path: " + newMountPath); 13692 cid = newCacheId; 13693 13694 final File beforeCodeFile = new File(packagePath); 13695 setMountPath(newMountPath); 13696 final File afterCodeFile = new File(packagePath); 13697 13698 // Reflect the rename in scanned details 13699 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13700 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13701 afterCodeFile, pkg.baseCodePath)); 13702 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13703 afterCodeFile, pkg.splitCodePaths)); 13704 13705 // Reflect the rename in app info 13706 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13707 pkg.setApplicationInfoCodePath(pkg.codePath); 13708 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13709 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13710 pkg.setApplicationInfoResourcePath(pkg.codePath); 13711 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13712 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13713 13714 return true; 13715 } 13716 13717 private void setMountPath(String mountPath) { 13718 final File mountFile = new File(mountPath); 13719 13720 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13721 if (monolithicFile.exists()) { 13722 packagePath = monolithicFile.getAbsolutePath(); 13723 if (isFwdLocked()) { 13724 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13725 } else { 13726 resourcePath = packagePath; 13727 } 13728 } else { 13729 packagePath = mountFile.getAbsolutePath(); 13730 resourcePath = packagePath; 13731 } 13732 } 13733 13734 int doPostInstall(int status, int uid) { 13735 if (status != PackageManager.INSTALL_SUCCEEDED) { 13736 cleanUp(); 13737 } else { 13738 final int groupOwner; 13739 final String protectedFile; 13740 if (isFwdLocked()) { 13741 groupOwner = UserHandle.getSharedAppGid(uid); 13742 protectedFile = RES_FILE_NAME; 13743 } else { 13744 groupOwner = -1; 13745 protectedFile = null; 13746 } 13747 13748 if (uid < Process.FIRST_APPLICATION_UID 13749 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13750 Slog.e(TAG, "Failed to finalize " + cid); 13751 PackageHelper.destroySdDir(cid); 13752 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13753 } 13754 13755 boolean mounted = PackageHelper.isContainerMounted(cid); 13756 if (!mounted) { 13757 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13758 } 13759 } 13760 return status; 13761 } 13762 13763 private void cleanUp() { 13764 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13765 13766 // Destroy secure container 13767 PackageHelper.destroySdDir(cid); 13768 } 13769 13770 private List<String> getAllCodePaths() { 13771 final File codeFile = new File(getCodePath()); 13772 if (codeFile != null && codeFile.exists()) { 13773 try { 13774 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13775 return pkg.getAllCodePaths(); 13776 } catch (PackageParserException e) { 13777 // Ignored; we tried our best 13778 } 13779 } 13780 return Collections.EMPTY_LIST; 13781 } 13782 13783 void cleanUpResourcesLI() { 13784 // Enumerate all code paths before deleting 13785 cleanUpResourcesLI(getAllCodePaths()); 13786 } 13787 13788 private void cleanUpResourcesLI(List<String> allCodePaths) { 13789 cleanUp(); 13790 removeDexFiles(allCodePaths, instructionSets); 13791 } 13792 13793 String getPackageName() { 13794 return getAsecPackageName(cid); 13795 } 13796 13797 boolean doPostDeleteLI(boolean delete) { 13798 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13799 final List<String> allCodePaths = getAllCodePaths(); 13800 boolean mounted = PackageHelper.isContainerMounted(cid); 13801 if (mounted) { 13802 // Unmount first 13803 if (PackageHelper.unMountSdDir(cid)) { 13804 mounted = false; 13805 } 13806 } 13807 if (!mounted && delete) { 13808 cleanUpResourcesLI(allCodePaths); 13809 } 13810 return !mounted; 13811 } 13812 13813 @Override 13814 int doPreCopy() { 13815 if (isFwdLocked()) { 13816 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13817 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13818 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13819 } 13820 } 13821 13822 return PackageManager.INSTALL_SUCCEEDED; 13823 } 13824 13825 @Override 13826 int doPostCopy(int uid) { 13827 if (isFwdLocked()) { 13828 if (uid < Process.FIRST_APPLICATION_UID 13829 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13830 RES_FILE_NAME)) { 13831 Slog.e(TAG, "Failed to finalize " + cid); 13832 PackageHelper.destroySdDir(cid); 13833 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13834 } 13835 } 13836 13837 return PackageManager.INSTALL_SUCCEEDED; 13838 } 13839 } 13840 13841 /** 13842 * Logic to handle movement of existing installed applications. 13843 */ 13844 class MoveInstallArgs extends InstallArgs { 13845 private File codeFile; 13846 private File resourceFile; 13847 13848 /** New install */ 13849 MoveInstallArgs(InstallParams params) { 13850 super(params.origin, params.move, params.observer, params.installFlags, 13851 params.installerPackageName, params.volumeUuid, 13852 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13853 params.grantedRuntimePermissions, 13854 params.traceMethod, params.traceCookie, params.certificates); 13855 } 13856 13857 int copyApk(IMediaContainerService imcs, boolean temp) { 13858 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13859 + move.fromUuid + " to " + move.toUuid); 13860 synchronized (mInstaller) { 13861 try { 13862 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13863 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13864 } catch (InstallerException e) { 13865 Slog.w(TAG, "Failed to move app", e); 13866 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13867 } 13868 } 13869 13870 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13871 resourceFile = codeFile; 13872 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13873 13874 return PackageManager.INSTALL_SUCCEEDED; 13875 } 13876 13877 int doPreInstall(int status) { 13878 if (status != PackageManager.INSTALL_SUCCEEDED) { 13879 cleanUp(move.toUuid); 13880 } 13881 return status; 13882 } 13883 13884 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13885 if (status != PackageManager.INSTALL_SUCCEEDED) { 13886 cleanUp(move.toUuid); 13887 return false; 13888 } 13889 13890 // Reflect the move in app info 13891 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13892 pkg.setApplicationInfoCodePath(pkg.codePath); 13893 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13894 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13895 pkg.setApplicationInfoResourcePath(pkg.codePath); 13896 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13897 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13898 13899 return true; 13900 } 13901 13902 int doPostInstall(int status, int uid) { 13903 if (status == PackageManager.INSTALL_SUCCEEDED) { 13904 cleanUp(move.fromUuid); 13905 } else { 13906 cleanUp(move.toUuid); 13907 } 13908 return status; 13909 } 13910 13911 @Override 13912 String getCodePath() { 13913 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13914 } 13915 13916 @Override 13917 String getResourcePath() { 13918 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13919 } 13920 13921 private boolean cleanUp(String volumeUuid) { 13922 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13923 move.dataAppName); 13924 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13925 final int[] userIds = sUserManager.getUserIds(); 13926 synchronized (mInstallLock) { 13927 // Clean up both app data and code 13928 // All package moves are frozen until finished 13929 for (int userId : userIds) { 13930 try { 13931 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13932 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13933 } catch (InstallerException e) { 13934 Slog.w(TAG, String.valueOf(e)); 13935 } 13936 } 13937 removeCodePathLI(codeFile); 13938 } 13939 return true; 13940 } 13941 13942 void cleanUpResourcesLI() { 13943 throw new UnsupportedOperationException(); 13944 } 13945 13946 boolean doPostDeleteLI(boolean delete) { 13947 throw new UnsupportedOperationException(); 13948 } 13949 } 13950 13951 static String getAsecPackageName(String packageCid) { 13952 int idx = packageCid.lastIndexOf("-"); 13953 if (idx == -1) { 13954 return packageCid; 13955 } 13956 return packageCid.substring(0, idx); 13957 } 13958 13959 // Utility method used to create code paths based on package name and available index. 13960 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13961 String idxStr = ""; 13962 int idx = 1; 13963 // Fall back to default value of idx=1 if prefix is not 13964 // part of oldCodePath 13965 if (oldCodePath != null) { 13966 String subStr = oldCodePath; 13967 // Drop the suffix right away 13968 if (suffix != null && subStr.endsWith(suffix)) { 13969 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13970 } 13971 // If oldCodePath already contains prefix find out the 13972 // ending index to either increment or decrement. 13973 int sidx = subStr.lastIndexOf(prefix); 13974 if (sidx != -1) { 13975 subStr = subStr.substring(sidx + prefix.length()); 13976 if (subStr != null) { 13977 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13978 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13979 } 13980 try { 13981 idx = Integer.parseInt(subStr); 13982 if (idx <= 1) { 13983 idx++; 13984 } else { 13985 idx--; 13986 } 13987 } catch(NumberFormatException e) { 13988 } 13989 } 13990 } 13991 } 13992 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13993 return prefix + idxStr; 13994 } 13995 13996 private File getNextCodePath(File targetDir, String packageName) { 13997 int suffix = 1; 13998 File result; 13999 do { 14000 result = new File(targetDir, packageName + "-" + suffix); 14001 suffix++; 14002 } while (result.exists()); 14003 return result; 14004 } 14005 14006 // Utility method that returns the relative package path with respect 14007 // to the installation directory. Like say for /data/data/com.test-1.apk 14008 // string com.test-1 is returned. 14009 static String deriveCodePathName(String codePath) { 14010 if (codePath == null) { 14011 return null; 14012 } 14013 final File codeFile = new File(codePath); 14014 final String name = codeFile.getName(); 14015 if (codeFile.isDirectory()) { 14016 return name; 14017 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 14018 final int lastDot = name.lastIndexOf('.'); 14019 return name.substring(0, lastDot); 14020 } else { 14021 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 14022 return null; 14023 } 14024 } 14025 14026 static class PackageInstalledInfo { 14027 String name; 14028 int uid; 14029 // The set of users that originally had this package installed. 14030 int[] origUsers; 14031 // The set of users that now have this package installed. 14032 int[] newUsers; 14033 PackageParser.Package pkg; 14034 int returnCode; 14035 String returnMsg; 14036 PackageRemovedInfo removedInfo; 14037 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 14038 14039 public void setError(int code, String msg) { 14040 setReturnCode(code); 14041 setReturnMessage(msg); 14042 Slog.w(TAG, msg); 14043 } 14044 14045 public void setError(String msg, PackageParserException e) { 14046 setReturnCode(e.error); 14047 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14048 Slog.w(TAG, msg, e); 14049 } 14050 14051 public void setError(String msg, PackageManagerException e) { 14052 returnCode = e.error; 14053 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 14054 Slog.w(TAG, msg, e); 14055 } 14056 14057 public void setReturnCode(int returnCode) { 14058 this.returnCode = returnCode; 14059 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14060 for (int i = 0; i < childCount; i++) { 14061 addedChildPackages.valueAt(i).returnCode = returnCode; 14062 } 14063 } 14064 14065 private void setReturnMessage(String returnMsg) { 14066 this.returnMsg = returnMsg; 14067 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 14068 for (int i = 0; i < childCount; i++) { 14069 addedChildPackages.valueAt(i).returnMsg = returnMsg; 14070 } 14071 } 14072 14073 // In some error cases we want to convey more info back to the observer 14074 String origPackage; 14075 String origPermission; 14076 } 14077 14078 /* 14079 * Install a non-existing package. 14080 */ 14081 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 14082 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 14083 PackageInstalledInfo res) { 14084 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 14085 14086 // Remember this for later, in case we need to rollback this install 14087 String pkgName = pkg.packageName; 14088 14089 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 14090 14091 synchronized(mPackages) { 14092 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 14093 // A package with the same name is already installed, though 14094 // it has been renamed to an older name. The package we 14095 // are trying to install should be installed as an update to 14096 // the existing one, but that has not been requested, so bail. 14097 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14098 + " without first uninstalling package running as " 14099 + mSettings.mRenamedPackages.get(pkgName)); 14100 return; 14101 } 14102 if (mPackages.containsKey(pkgName)) { 14103 // Don't allow installation over an existing package with the same name. 14104 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 14105 + " without first uninstalling."); 14106 return; 14107 } 14108 } 14109 14110 try { 14111 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 14112 System.currentTimeMillis(), user); 14113 14114 updateSettingsLI(newPackage, installerPackageName, null, res, user); 14115 14116 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14117 prepareAppDataAfterInstallLIF(newPackage); 14118 14119 } else { 14120 // Remove package from internal structures, but keep around any 14121 // data that might have already existed 14122 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 14123 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 14124 } 14125 } catch (PackageManagerException e) { 14126 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14127 } 14128 14129 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14130 } 14131 14132 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 14133 // Can't rotate keys during boot or if sharedUser. 14134 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 14135 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 14136 return false; 14137 } 14138 // app is using upgradeKeySets; make sure all are valid 14139 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14140 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 14141 for (int i = 0; i < upgradeKeySets.length; i++) { 14142 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 14143 Slog.wtf(TAG, "Package " 14144 + (oldPs.name != null ? oldPs.name : "<null>") 14145 + " contains upgrade-key-set reference to unknown key-set: " 14146 + upgradeKeySets[i] 14147 + " reverting to signatures check."); 14148 return false; 14149 } 14150 } 14151 return true; 14152 } 14153 14154 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 14155 // Upgrade keysets are being used. Determine if new package has a superset of the 14156 // required keys. 14157 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 14158 KeySetManagerService ksms = mSettings.mKeySetManagerService; 14159 for (int i = 0; i < upgradeKeySets.length; i++) { 14160 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 14161 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 14162 return true; 14163 } 14164 } 14165 return false; 14166 } 14167 14168 private static void updateDigest(MessageDigest digest, File file) throws IOException { 14169 try (DigestInputStream digestStream = 14170 new DigestInputStream(new FileInputStream(file), digest)) { 14171 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 14172 } 14173 } 14174 14175 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 14176 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 14177 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 14178 14179 final PackageParser.Package oldPackage; 14180 final String pkgName = pkg.packageName; 14181 final int[] allUsers; 14182 final int[] installedUsers; 14183 14184 synchronized(mPackages) { 14185 oldPackage = mPackages.get(pkgName); 14186 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 14187 14188 // don't allow upgrade to target a release SDK from a pre-release SDK 14189 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 14190 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14191 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 14192 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 14193 if (oldTargetsPreRelease 14194 && !newTargetsPreRelease 14195 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 14196 Slog.w(TAG, "Can't install package targeting released sdk"); 14197 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 14198 return; 14199 } 14200 14201 // don't allow an upgrade from full to ephemeral 14202 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 14203 if (isEphemeral && !oldIsEphemeral) { 14204 // can't downgrade from full to ephemeral 14205 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 14206 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14207 return; 14208 } 14209 14210 // verify signatures are valid 14211 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14212 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14213 if (!checkUpgradeKeySetLP(ps, pkg)) { 14214 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14215 "New package not signed by keys specified by upgrade-keysets: " 14216 + pkgName); 14217 return; 14218 } 14219 } else { 14220 // default to original signature matching 14221 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 14222 != PackageManager.SIGNATURE_MATCH) { 14223 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 14224 "New package has a different signature: " + pkgName); 14225 return; 14226 } 14227 } 14228 14229 // don't allow a system upgrade unless the upgrade hash matches 14230 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 14231 byte[] digestBytes = null; 14232 try { 14233 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14234 updateDigest(digest, new File(pkg.baseCodePath)); 14235 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14236 for (String path : pkg.splitCodePaths) { 14237 updateDigest(digest, new File(path)); 14238 } 14239 } 14240 digestBytes = digest.digest(); 14241 } catch (NoSuchAlgorithmException | IOException e) { 14242 res.setError(INSTALL_FAILED_INVALID_APK, 14243 "Could not compute hash: " + pkgName); 14244 return; 14245 } 14246 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14247 res.setError(INSTALL_FAILED_INVALID_APK, 14248 "New package fails restrict-update check: " + pkgName); 14249 return; 14250 } 14251 // retain upgrade restriction 14252 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14253 } 14254 14255 // Check for shared user id changes 14256 String invalidPackageName = 14257 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14258 if (invalidPackageName != null) { 14259 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14260 "Package " + invalidPackageName + " tried to change user " 14261 + oldPackage.mSharedUserId); 14262 return; 14263 } 14264 14265 // In case of rollback, remember per-user/profile install state 14266 allUsers = sUserManager.getUserIds(); 14267 installedUsers = ps.queryInstalledUsers(allUsers, true); 14268 } 14269 14270 // Update what is removed 14271 res.removedInfo = new PackageRemovedInfo(); 14272 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14273 res.removedInfo.removedPackage = oldPackage.packageName; 14274 res.removedInfo.isUpdate = true; 14275 res.removedInfo.origUsers = installedUsers; 14276 final int childCount = (oldPackage.childPackages != null) 14277 ? oldPackage.childPackages.size() : 0; 14278 for (int i = 0; i < childCount; i++) { 14279 boolean childPackageUpdated = false; 14280 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14281 if (res.addedChildPackages != null) { 14282 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14283 if (childRes != null) { 14284 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14285 childRes.removedInfo.removedPackage = childPkg.packageName; 14286 childRes.removedInfo.isUpdate = true; 14287 childPackageUpdated = true; 14288 } 14289 } 14290 if (!childPackageUpdated) { 14291 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14292 childRemovedRes.removedPackage = childPkg.packageName; 14293 childRemovedRes.isUpdate = false; 14294 childRemovedRes.dataRemoved = true; 14295 synchronized (mPackages) { 14296 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14297 if (childPs != null) { 14298 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14299 } 14300 } 14301 if (res.removedInfo.removedChildPackages == null) { 14302 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14303 } 14304 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14305 } 14306 } 14307 14308 boolean sysPkg = (isSystemApp(oldPackage)); 14309 if (sysPkg) { 14310 // Set the system/privileged flags as needed 14311 final boolean privileged = 14312 (oldPackage.applicationInfo.privateFlags 14313 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14314 final int systemPolicyFlags = policyFlags 14315 | PackageParser.PARSE_IS_SYSTEM 14316 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14317 14318 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14319 user, allUsers, installerPackageName, res); 14320 } else { 14321 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14322 user, allUsers, installerPackageName, res); 14323 } 14324 } 14325 14326 public List<String> getPreviousCodePaths(String packageName) { 14327 final PackageSetting ps = mSettings.mPackages.get(packageName); 14328 final List<String> result = new ArrayList<String>(); 14329 if (ps != null && ps.oldCodePaths != null) { 14330 result.addAll(ps.oldCodePaths); 14331 } 14332 return result; 14333 } 14334 14335 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14336 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14337 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14338 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14339 + deletedPackage); 14340 14341 String pkgName = deletedPackage.packageName; 14342 boolean deletedPkg = true; 14343 boolean addedPkg = false; 14344 boolean updatedSettings = false; 14345 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14346 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14347 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14348 14349 final long origUpdateTime = (pkg.mExtras != null) 14350 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14351 14352 // First delete the existing package while retaining the data directory 14353 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14354 res.removedInfo, true, pkg)) { 14355 // If the existing package wasn't successfully deleted 14356 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14357 deletedPkg = false; 14358 } else { 14359 // Successfully deleted the old package; proceed with replace. 14360 14361 // If deleted package lived in a container, give users a chance to 14362 // relinquish resources before killing. 14363 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14364 if (DEBUG_INSTALL) { 14365 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14366 } 14367 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14368 final ArrayList<String> pkgList = new ArrayList<String>(1); 14369 pkgList.add(deletedPackage.applicationInfo.packageName); 14370 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14371 } 14372 14373 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14374 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14375 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14376 14377 try { 14378 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14379 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14380 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14381 14382 // Update the in-memory copy of the previous code paths. 14383 PackageSetting ps = mSettings.mPackages.get(pkgName); 14384 if (!killApp) { 14385 if (ps.oldCodePaths == null) { 14386 ps.oldCodePaths = new ArraySet<>(); 14387 } 14388 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14389 if (deletedPackage.splitCodePaths != null) { 14390 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14391 } 14392 } else { 14393 ps.oldCodePaths = null; 14394 } 14395 if (ps.childPackageNames != null) { 14396 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14397 final String childPkgName = ps.childPackageNames.get(i); 14398 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14399 childPs.oldCodePaths = ps.oldCodePaths; 14400 } 14401 } 14402 prepareAppDataAfterInstallLIF(newPackage); 14403 addedPkg = true; 14404 } catch (PackageManagerException e) { 14405 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14406 } 14407 } 14408 14409 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14410 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14411 14412 // Revert all internal state mutations and added folders for the failed install 14413 if (addedPkg) { 14414 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14415 res.removedInfo, true, null); 14416 } 14417 14418 // Restore the old package 14419 if (deletedPkg) { 14420 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14421 File restoreFile = new File(deletedPackage.codePath); 14422 // Parse old package 14423 boolean oldExternal = isExternal(deletedPackage); 14424 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14425 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14426 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14427 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14428 try { 14429 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14430 null); 14431 } catch (PackageManagerException e) { 14432 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14433 + e.getMessage()); 14434 return; 14435 } 14436 14437 synchronized (mPackages) { 14438 // Ensure the installer package name up to date 14439 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14440 14441 // Update permissions for restored package 14442 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14443 14444 mSettings.writeLPr(); 14445 } 14446 14447 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14448 } 14449 } else { 14450 synchronized (mPackages) { 14451 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14452 if (ps != null) { 14453 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14454 if (res.removedInfo.removedChildPackages != null) { 14455 final int childCount = res.removedInfo.removedChildPackages.size(); 14456 // Iterate in reverse as we may modify the collection 14457 for (int i = childCount - 1; i >= 0; i--) { 14458 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14459 if (res.addedChildPackages.containsKey(childPackageName)) { 14460 res.removedInfo.removedChildPackages.removeAt(i); 14461 } else { 14462 PackageRemovedInfo childInfo = res.removedInfo 14463 .removedChildPackages.valueAt(i); 14464 childInfo.removedForAllUsers = mPackages.get( 14465 childInfo.removedPackage) == null; 14466 } 14467 } 14468 } 14469 } 14470 } 14471 } 14472 } 14473 14474 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14475 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14476 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14477 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14478 + ", old=" + deletedPackage); 14479 14480 final boolean disabledSystem; 14481 14482 // Remove existing system package 14483 removePackageLI(deletedPackage, true); 14484 14485 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14486 if (!disabledSystem) { 14487 // We didn't need to disable the .apk as a current system package, 14488 // which means we are replacing another update that is already 14489 // installed. We need to make sure to delete the older one's .apk. 14490 res.removedInfo.args = createInstallArgsForExisting(0, 14491 deletedPackage.applicationInfo.getCodePath(), 14492 deletedPackage.applicationInfo.getResourcePath(), 14493 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14494 } else { 14495 res.removedInfo.args = null; 14496 } 14497 14498 // Successfully disabled the old package. Now proceed with re-installation 14499 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14500 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14501 clearAppProfilesLIF(deletedPackage, UserHandle.USER_ALL); 14502 14503 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14504 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14505 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14506 14507 PackageParser.Package newPackage = null; 14508 try { 14509 // Add the package to the internal data structures 14510 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14511 14512 // Set the update and install times 14513 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14514 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14515 System.currentTimeMillis()); 14516 14517 // Update the package dynamic state if succeeded 14518 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14519 // Now that the install succeeded make sure we remove data 14520 // directories for any child package the update removed. 14521 final int deletedChildCount = (deletedPackage.childPackages != null) 14522 ? deletedPackage.childPackages.size() : 0; 14523 final int newChildCount = (newPackage.childPackages != null) 14524 ? newPackage.childPackages.size() : 0; 14525 for (int i = 0; i < deletedChildCount; i++) { 14526 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14527 boolean childPackageDeleted = true; 14528 for (int j = 0; j < newChildCount; j++) { 14529 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14530 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14531 childPackageDeleted = false; 14532 break; 14533 } 14534 } 14535 if (childPackageDeleted) { 14536 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14537 deletedChildPkg.packageName); 14538 if (ps != null && res.removedInfo.removedChildPackages != null) { 14539 PackageRemovedInfo removedChildRes = res.removedInfo 14540 .removedChildPackages.get(deletedChildPkg.packageName); 14541 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14542 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14543 } 14544 } 14545 } 14546 14547 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14548 prepareAppDataAfterInstallLIF(newPackage); 14549 } 14550 } catch (PackageManagerException e) { 14551 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14552 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14553 } 14554 14555 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14556 // Re installation failed. Restore old information 14557 // Remove new pkg information 14558 if (newPackage != null) { 14559 removeInstalledPackageLI(newPackage, true); 14560 } 14561 // Add back the old system package 14562 try { 14563 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14564 } catch (PackageManagerException e) { 14565 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14566 } 14567 14568 synchronized (mPackages) { 14569 if (disabledSystem) { 14570 enableSystemPackageLPw(deletedPackage); 14571 } 14572 14573 // Ensure the installer package name up to date 14574 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14575 14576 // Update permissions for restored package 14577 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14578 14579 mSettings.writeLPr(); 14580 } 14581 14582 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14583 + " after failed upgrade"); 14584 } 14585 } 14586 14587 /** 14588 * Checks whether the parent or any of the child packages have a change shared 14589 * user. For a package to be a valid update the shred users of the parent and 14590 * the children should match. We may later support changing child shared users. 14591 * @param oldPkg The updated package. 14592 * @param newPkg The update package. 14593 * @return The shared user that change between the versions. 14594 */ 14595 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14596 PackageParser.Package newPkg) { 14597 // Check parent shared user 14598 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14599 return newPkg.packageName; 14600 } 14601 // Check child shared users 14602 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14603 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14604 for (int i = 0; i < newChildCount; i++) { 14605 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14606 // If this child was present, did it have the same shared user? 14607 for (int j = 0; j < oldChildCount; j++) { 14608 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14609 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14610 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14611 return newChildPkg.packageName; 14612 } 14613 } 14614 } 14615 return null; 14616 } 14617 14618 private void removeNativeBinariesLI(PackageSetting ps) { 14619 // Remove the lib path for the parent package 14620 if (ps != null) { 14621 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14622 // Remove the lib path for the child packages 14623 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14624 for (int i = 0; i < childCount; i++) { 14625 PackageSetting childPs = null; 14626 synchronized (mPackages) { 14627 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14628 } 14629 if (childPs != null) { 14630 NativeLibraryHelper.removeNativeBinariesLI(childPs 14631 .legacyNativeLibraryPathString); 14632 } 14633 } 14634 } 14635 } 14636 14637 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14638 // Enable the parent package 14639 mSettings.enableSystemPackageLPw(pkg.packageName); 14640 // Enable the child packages 14641 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14642 for (int i = 0; i < childCount; i++) { 14643 PackageParser.Package childPkg = pkg.childPackages.get(i); 14644 mSettings.enableSystemPackageLPw(childPkg.packageName); 14645 } 14646 } 14647 14648 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14649 PackageParser.Package newPkg) { 14650 // Disable the parent package (parent always replaced) 14651 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14652 // Disable the child packages 14653 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14654 for (int i = 0; i < childCount; i++) { 14655 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14656 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14657 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14658 } 14659 return disabled; 14660 } 14661 14662 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14663 String installerPackageName) { 14664 // Enable the parent package 14665 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14666 // Enable the child packages 14667 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14668 for (int i = 0; i < childCount; i++) { 14669 PackageParser.Package childPkg = pkg.childPackages.get(i); 14670 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14671 } 14672 } 14673 14674 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14675 // Collect all used permissions in the UID 14676 ArraySet<String> usedPermissions = new ArraySet<>(); 14677 final int packageCount = su.packages.size(); 14678 for (int i = 0; i < packageCount; i++) { 14679 PackageSetting ps = su.packages.valueAt(i); 14680 if (ps.pkg == null) { 14681 continue; 14682 } 14683 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14684 for (int j = 0; j < requestedPermCount; j++) { 14685 String permission = ps.pkg.requestedPermissions.get(j); 14686 BasePermission bp = mSettings.mPermissions.get(permission); 14687 if (bp != null) { 14688 usedPermissions.add(permission); 14689 } 14690 } 14691 } 14692 14693 PermissionsState permissionsState = su.getPermissionsState(); 14694 // Prune install permissions 14695 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14696 final int installPermCount = installPermStates.size(); 14697 for (int i = installPermCount - 1; i >= 0; i--) { 14698 PermissionState permissionState = installPermStates.get(i); 14699 if (!usedPermissions.contains(permissionState.getName())) { 14700 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14701 if (bp != null) { 14702 permissionsState.revokeInstallPermission(bp); 14703 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14704 PackageManager.MASK_PERMISSION_FLAGS, 0); 14705 } 14706 } 14707 } 14708 14709 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14710 14711 // Prune runtime permissions 14712 for (int userId : allUserIds) { 14713 List<PermissionState> runtimePermStates = permissionsState 14714 .getRuntimePermissionStates(userId); 14715 final int runtimePermCount = runtimePermStates.size(); 14716 for (int i = runtimePermCount - 1; i >= 0; i--) { 14717 PermissionState permissionState = runtimePermStates.get(i); 14718 if (!usedPermissions.contains(permissionState.getName())) { 14719 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14720 if (bp != null) { 14721 permissionsState.revokeRuntimePermission(bp, userId); 14722 permissionsState.updatePermissionFlags(bp, userId, 14723 PackageManager.MASK_PERMISSION_FLAGS, 0); 14724 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14725 runtimePermissionChangedUserIds, userId); 14726 } 14727 } 14728 } 14729 } 14730 14731 return runtimePermissionChangedUserIds; 14732 } 14733 14734 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14735 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14736 // Update the parent package setting 14737 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14738 res, user); 14739 // Update the child packages setting 14740 final int childCount = (newPackage.childPackages != null) 14741 ? newPackage.childPackages.size() : 0; 14742 for (int i = 0; i < childCount; i++) { 14743 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14744 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14745 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14746 childRes.origUsers, childRes, user); 14747 } 14748 } 14749 14750 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14751 String installerPackageName, int[] allUsers, int[] installedForUsers, 14752 PackageInstalledInfo res, UserHandle user) { 14753 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14754 14755 String pkgName = newPackage.packageName; 14756 synchronized (mPackages) { 14757 //write settings. the installStatus will be incomplete at this stage. 14758 //note that the new package setting would have already been 14759 //added to mPackages. It hasn't been persisted yet. 14760 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14761 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14762 mSettings.writeLPr(); 14763 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14764 } 14765 14766 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14767 synchronized (mPackages) { 14768 updatePermissionsLPw(newPackage.packageName, newPackage, 14769 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14770 ? UPDATE_PERMISSIONS_ALL : 0)); 14771 // For system-bundled packages, we assume that installing an upgraded version 14772 // of the package implies that the user actually wants to run that new code, 14773 // so we enable the package. 14774 PackageSetting ps = mSettings.mPackages.get(pkgName); 14775 final int userId = user.getIdentifier(); 14776 if (ps != null) { 14777 if (isSystemApp(newPackage)) { 14778 if (DEBUG_INSTALL) { 14779 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14780 } 14781 // Enable system package for requested users 14782 if (res.origUsers != null) { 14783 for (int origUserId : res.origUsers) { 14784 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14785 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14786 origUserId, installerPackageName); 14787 } 14788 } 14789 } 14790 // Also convey the prior install/uninstall state 14791 if (allUsers != null && installedForUsers != null) { 14792 for (int currentUserId : allUsers) { 14793 final boolean installed = ArrayUtils.contains( 14794 installedForUsers, currentUserId); 14795 if (DEBUG_INSTALL) { 14796 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14797 } 14798 ps.setInstalled(installed, currentUserId); 14799 } 14800 // these install state changes will be persisted in the 14801 // upcoming call to mSettings.writeLPr(). 14802 } 14803 } 14804 // It's implied that when a user requests installation, they want the app to be 14805 // installed and enabled. 14806 if (userId != UserHandle.USER_ALL) { 14807 ps.setInstalled(true, userId); 14808 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14809 } 14810 } 14811 res.name = pkgName; 14812 res.uid = newPackage.applicationInfo.uid; 14813 res.pkg = newPackage; 14814 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14815 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14816 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14817 //to update install status 14818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14819 mSettings.writeLPr(); 14820 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14821 } 14822 14823 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14824 } 14825 14826 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14827 try { 14828 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14829 installPackageLI(args, res); 14830 } finally { 14831 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14832 } 14833 } 14834 14835 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14836 final int installFlags = args.installFlags; 14837 final String installerPackageName = args.installerPackageName; 14838 final String volumeUuid = args.volumeUuid; 14839 final File tmpPackageFile = new File(args.getCodePath()); 14840 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14841 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14842 || (args.volumeUuid != null)); 14843 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14844 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14845 boolean replace = false; 14846 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14847 if (args.move != null) { 14848 // moving a complete application; perform an initial scan on the new install location 14849 scanFlags |= SCAN_INITIAL; 14850 } 14851 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14852 scanFlags |= SCAN_DONT_KILL_APP; 14853 } 14854 14855 // Result object to be returned 14856 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14857 14858 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14859 14860 // Sanity check 14861 if (ephemeral && (forwardLocked || onExternal)) { 14862 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14863 + " external=" + onExternal); 14864 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14865 return; 14866 } 14867 14868 // Retrieve PackageSettings and parse package 14869 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14870 | PackageParser.PARSE_ENFORCE_CODE 14871 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14872 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14873 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14874 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14875 PackageParser pp = new PackageParser(); 14876 pp.setSeparateProcesses(mSeparateProcesses); 14877 pp.setDisplayMetrics(mMetrics); 14878 14879 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14880 final PackageParser.Package pkg; 14881 try { 14882 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14883 } catch (PackageParserException e) { 14884 res.setError("Failed parse during installPackageLI", e); 14885 return; 14886 } finally { 14887 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14888 } 14889 14890 // If we are installing a clustered package add results for the children 14891 if (pkg.childPackages != null) { 14892 synchronized (mPackages) { 14893 final int childCount = pkg.childPackages.size(); 14894 for (int i = 0; i < childCount; i++) { 14895 PackageParser.Package childPkg = pkg.childPackages.get(i); 14896 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14897 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14898 childRes.pkg = childPkg; 14899 childRes.name = childPkg.packageName; 14900 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14901 if (childPs != null) { 14902 childRes.origUsers = childPs.queryInstalledUsers( 14903 sUserManager.getUserIds(), true); 14904 } 14905 if ((mPackages.containsKey(childPkg.packageName))) { 14906 childRes.removedInfo = new PackageRemovedInfo(); 14907 childRes.removedInfo.removedPackage = childPkg.packageName; 14908 } 14909 if (res.addedChildPackages == null) { 14910 res.addedChildPackages = new ArrayMap<>(); 14911 } 14912 res.addedChildPackages.put(childPkg.packageName, childRes); 14913 } 14914 } 14915 } 14916 14917 // If package doesn't declare API override, mark that we have an install 14918 // time CPU ABI override. 14919 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14920 pkg.cpuAbiOverride = args.abiOverride; 14921 } 14922 14923 String pkgName = res.name = pkg.packageName; 14924 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14925 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14926 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14927 return; 14928 } 14929 } 14930 14931 try { 14932 // either use what we've been given or parse directly from the APK 14933 if (args.certificates != null) { 14934 try { 14935 PackageParser.populateCertificates(pkg, args.certificates); 14936 } catch (PackageParserException e) { 14937 // there was something wrong with the certificates we were given; 14938 // try to pull them from the APK 14939 PackageParser.collectCertificates(pkg, parseFlags); 14940 } 14941 } else { 14942 PackageParser.collectCertificates(pkg, parseFlags); 14943 } 14944 } catch (PackageParserException e) { 14945 res.setError("Failed collect during installPackageLI", e); 14946 return; 14947 } 14948 14949 // Get rid of all references to package scan path via parser. 14950 pp = null; 14951 String oldCodePath = null; 14952 boolean systemApp = false; 14953 synchronized (mPackages) { 14954 // Check if installing already existing package 14955 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14956 String oldName = mSettings.mRenamedPackages.get(pkgName); 14957 if (pkg.mOriginalPackages != null 14958 && pkg.mOriginalPackages.contains(oldName) 14959 && mPackages.containsKey(oldName)) { 14960 // This package is derived from an original package, 14961 // and this device has been updating from that original 14962 // name. We must continue using the original name, so 14963 // rename the new package here. 14964 pkg.setPackageName(oldName); 14965 pkgName = pkg.packageName; 14966 replace = true; 14967 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14968 + oldName + " pkgName=" + pkgName); 14969 } else if (mPackages.containsKey(pkgName)) { 14970 // This package, under its official name, already exists 14971 // on the device; we should replace it. 14972 replace = true; 14973 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14974 } 14975 14976 // Child packages are installed through the parent package 14977 if (pkg.parentPackage != null) { 14978 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14979 "Package " + pkg.packageName + " is child of package " 14980 + pkg.parentPackage.parentPackage + ". Child packages " 14981 + "can be updated only through the parent package."); 14982 return; 14983 } 14984 14985 if (replace) { 14986 // Prevent apps opting out from runtime permissions 14987 PackageParser.Package oldPackage = mPackages.get(pkgName); 14988 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14989 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14990 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14991 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14992 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14993 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14994 + " doesn't support runtime permissions but the old" 14995 + " target SDK " + oldTargetSdk + " does."); 14996 return; 14997 } 14998 14999 // Prevent installing of child packages 15000 if (oldPackage.parentPackage != null) { 15001 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 15002 "Package " + pkg.packageName + " is child of package " 15003 + oldPackage.parentPackage + ". Child packages " 15004 + "can be updated only through the parent package."); 15005 return; 15006 } 15007 } 15008 } 15009 15010 PackageSetting ps = mSettings.mPackages.get(pkgName); 15011 if (ps != null) { 15012 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 15013 15014 // Quick sanity check that we're signed correctly if updating; 15015 // we'll check this again later when scanning, but we want to 15016 // bail early here before tripping over redefined permissions. 15017 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 15018 if (!checkUpgradeKeySetLP(ps, pkg)) { 15019 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 15020 + pkg.packageName + " upgrade keys do not match the " 15021 + "previously installed version"); 15022 return; 15023 } 15024 } else { 15025 try { 15026 verifySignaturesLP(ps, pkg); 15027 } catch (PackageManagerException e) { 15028 res.setError(e.error, e.getMessage()); 15029 return; 15030 } 15031 } 15032 15033 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 15034 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 15035 systemApp = (ps.pkg.applicationInfo.flags & 15036 ApplicationInfo.FLAG_SYSTEM) != 0; 15037 } 15038 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15039 } 15040 15041 // Check whether the newly-scanned package wants to define an already-defined perm 15042 int N = pkg.permissions.size(); 15043 for (int i = N-1; i >= 0; i--) { 15044 PackageParser.Permission perm = pkg.permissions.get(i); 15045 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 15046 if (bp != null) { 15047 // If the defining package is signed with our cert, it's okay. This 15048 // also includes the "updating the same package" case, of course. 15049 // "updating same package" could also involve key-rotation. 15050 final boolean sigsOk; 15051 if (bp.sourcePackage.equals(pkg.packageName) 15052 && (bp.packageSetting instanceof PackageSetting) 15053 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 15054 scanFlags))) { 15055 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 15056 } else { 15057 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 15058 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 15059 } 15060 if (!sigsOk) { 15061 // If the owning package is the system itself, we log but allow 15062 // install to proceed; we fail the install on all other permission 15063 // redefinitions. 15064 if (!bp.sourcePackage.equals("android")) { 15065 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 15066 + pkg.packageName + " attempting to redeclare permission " 15067 + perm.info.name + " already owned by " + bp.sourcePackage); 15068 res.origPermission = perm.info.name; 15069 res.origPackage = bp.sourcePackage; 15070 return; 15071 } else { 15072 Slog.w(TAG, "Package " + pkg.packageName 15073 + " attempting to redeclare system permission " 15074 + perm.info.name + "; ignoring new declaration"); 15075 pkg.permissions.remove(i); 15076 } 15077 } 15078 } 15079 } 15080 } 15081 15082 if (systemApp) { 15083 if (onExternal) { 15084 // Abort update; system app can't be replaced with app on sdcard 15085 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 15086 "Cannot install updates to system apps on sdcard"); 15087 return; 15088 } else if (ephemeral) { 15089 // Abort update; system app can't be replaced with an ephemeral app 15090 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 15091 "Cannot update a system app with an ephemeral app"); 15092 return; 15093 } 15094 } 15095 15096 if (args.move != null) { 15097 // We did an in-place move, so dex is ready to roll 15098 scanFlags |= SCAN_NO_DEX; 15099 scanFlags |= SCAN_MOVE; 15100 15101 synchronized (mPackages) { 15102 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15103 if (ps == null) { 15104 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 15105 "Missing settings for moved package " + pkgName); 15106 } 15107 15108 // We moved the entire application as-is, so bring over the 15109 // previously derived ABI information. 15110 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 15111 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 15112 } 15113 15114 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 15115 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 15116 scanFlags |= SCAN_NO_DEX; 15117 15118 try { 15119 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 15120 args.abiOverride : pkg.cpuAbiOverride); 15121 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 15122 true /* extract libs */); 15123 } catch (PackageManagerException pme) { 15124 Slog.e(TAG, "Error deriving application ABI", pme); 15125 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 15126 return; 15127 } 15128 15129 // Shared libraries for the package need to be updated. 15130 synchronized (mPackages) { 15131 try { 15132 updateSharedLibrariesLPw(pkg, null); 15133 } catch (PackageManagerException e) { 15134 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 15135 } 15136 } 15137 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 15138 // Do not run PackageDexOptimizer through the local performDexOpt 15139 // method because `pkg` is not in `mPackages` yet. 15140 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 15141 null /* instructionSets */, false /* checkProfiles */, 15142 getCompilerFilterForReason(REASON_INSTALL)); 15143 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 15144 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 15145 String msg = "Extracting package failed for " + pkgName; 15146 res.setError(INSTALL_FAILED_DEXOPT, msg); 15147 return; 15148 } 15149 15150 // Notify BackgroundDexOptService that the package has been changed. 15151 // If this is an update of a package which used to fail to compile, 15152 // BDOS will remove it from its blacklist. 15153 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 15154 } 15155 15156 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 15157 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 15158 return; 15159 } 15160 15161 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 15162 15163 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 15164 "installPackageLI")) { 15165 if (replace) { 15166 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 15167 installerPackageName, res); 15168 } else { 15169 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 15170 args.user, installerPackageName, volumeUuid, res); 15171 } 15172 } 15173 synchronized (mPackages) { 15174 final PackageSetting ps = mSettings.mPackages.get(pkgName); 15175 if (ps != null) { 15176 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 15177 } 15178 15179 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15180 for (int i = 0; i < childCount; i++) { 15181 PackageParser.Package childPkg = pkg.childPackages.get(i); 15182 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 15183 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 15184 if (childPs != null) { 15185 childRes.newUsers = childPs.queryInstalledUsers( 15186 sUserManager.getUserIds(), true); 15187 } 15188 } 15189 } 15190 } 15191 15192 private void startIntentFilterVerifications(int userId, boolean replacing, 15193 PackageParser.Package pkg) { 15194 if (mIntentFilterVerifierComponent == null) { 15195 Slog.w(TAG, "No IntentFilter verification will not be done as " 15196 + "there is no IntentFilterVerifier available!"); 15197 return; 15198 } 15199 15200 final int verifierUid = getPackageUid( 15201 mIntentFilterVerifierComponent.getPackageName(), 15202 MATCH_DEBUG_TRIAGED_MISSING, 15203 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 15204 15205 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15206 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 15207 mHandler.sendMessage(msg); 15208 15209 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 15210 for (int i = 0; i < childCount; i++) { 15211 PackageParser.Package childPkg = pkg.childPackages.get(i); 15212 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 15213 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 15214 mHandler.sendMessage(msg); 15215 } 15216 } 15217 15218 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 15219 PackageParser.Package pkg) { 15220 int size = pkg.activities.size(); 15221 if (size == 0) { 15222 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15223 "No activity, so no need to verify any IntentFilter!"); 15224 return; 15225 } 15226 15227 final boolean hasDomainURLs = hasDomainURLs(pkg); 15228 if (!hasDomainURLs) { 15229 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15230 "No domain URLs, so no need to verify any IntentFilter!"); 15231 return; 15232 } 15233 15234 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15235 + " if any IntentFilter from the " + size 15236 + " Activities needs verification ..."); 15237 15238 int count = 0; 15239 final String packageName = pkg.packageName; 15240 15241 synchronized (mPackages) { 15242 // If this is a new install and we see that we've already run verification for this 15243 // package, we have nothing to do: it means the state was restored from backup. 15244 if (!replacing) { 15245 IntentFilterVerificationInfo ivi = 15246 mSettings.getIntentFilterVerificationLPr(packageName); 15247 if (ivi != null) { 15248 if (DEBUG_DOMAIN_VERIFICATION) { 15249 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15250 + ivi.getStatusString()); 15251 } 15252 return; 15253 } 15254 } 15255 15256 // If any filters need to be verified, then all need to be. 15257 boolean needToVerify = false; 15258 for (PackageParser.Activity a : pkg.activities) { 15259 for (ActivityIntentInfo filter : a.intents) { 15260 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15261 if (DEBUG_DOMAIN_VERIFICATION) { 15262 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15263 } 15264 needToVerify = true; 15265 break; 15266 } 15267 } 15268 } 15269 15270 if (needToVerify) { 15271 final int verificationId = mIntentFilterVerificationToken++; 15272 for (PackageParser.Activity a : pkg.activities) { 15273 for (ActivityIntentInfo filter : a.intents) { 15274 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15275 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15276 "Verification needed for IntentFilter:" + filter.toString()); 15277 mIntentFilterVerifier.addOneIntentFilterVerification( 15278 verifierUid, userId, verificationId, filter, packageName); 15279 count++; 15280 } 15281 } 15282 } 15283 } 15284 } 15285 15286 if (count > 0) { 15287 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15288 + " IntentFilter verification" + (count > 1 ? "s" : "") 15289 + " for userId:" + userId); 15290 mIntentFilterVerifier.startVerifications(userId); 15291 } else { 15292 if (DEBUG_DOMAIN_VERIFICATION) { 15293 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15294 } 15295 } 15296 } 15297 15298 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15299 final ComponentName cn = filter.activity.getComponentName(); 15300 final String packageName = cn.getPackageName(); 15301 15302 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15303 packageName); 15304 if (ivi == null) { 15305 return true; 15306 } 15307 int status = ivi.getStatus(); 15308 switch (status) { 15309 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15310 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15311 return true; 15312 15313 default: 15314 // Nothing to do 15315 return false; 15316 } 15317 } 15318 15319 private static boolean isMultiArch(ApplicationInfo info) { 15320 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15321 } 15322 15323 private static boolean isExternal(PackageParser.Package pkg) { 15324 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15325 } 15326 15327 private static boolean isExternal(PackageSetting ps) { 15328 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15329 } 15330 15331 private static boolean isEphemeral(PackageParser.Package pkg) { 15332 return pkg.applicationInfo.isEphemeralApp(); 15333 } 15334 15335 private static boolean isEphemeral(PackageSetting ps) { 15336 return ps.pkg != null && isEphemeral(ps.pkg); 15337 } 15338 15339 private static boolean isSystemApp(PackageParser.Package pkg) { 15340 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15341 } 15342 15343 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15344 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15345 } 15346 15347 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15348 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15349 } 15350 15351 private static boolean isSystemApp(PackageSetting ps) { 15352 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15353 } 15354 15355 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15356 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15357 } 15358 15359 private int packageFlagsToInstallFlags(PackageSetting ps) { 15360 int installFlags = 0; 15361 if (isEphemeral(ps)) { 15362 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15363 } 15364 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15365 // This existing package was an external ASEC install when we have 15366 // the external flag without a UUID 15367 installFlags |= PackageManager.INSTALL_EXTERNAL; 15368 } 15369 if (ps.isForwardLocked()) { 15370 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15371 } 15372 return installFlags; 15373 } 15374 15375 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15376 if (isExternal(pkg)) { 15377 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15378 return StorageManager.UUID_PRIMARY_PHYSICAL; 15379 } else { 15380 return pkg.volumeUuid; 15381 } 15382 } else { 15383 return StorageManager.UUID_PRIVATE_INTERNAL; 15384 } 15385 } 15386 15387 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15388 if (isExternal(pkg)) { 15389 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15390 return mSettings.getExternalVersion(); 15391 } else { 15392 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15393 } 15394 } else { 15395 return mSettings.getInternalVersion(); 15396 } 15397 } 15398 15399 private void deleteTempPackageFiles() { 15400 final FilenameFilter filter = new FilenameFilter() { 15401 public boolean accept(File dir, String name) { 15402 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15403 } 15404 }; 15405 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15406 file.delete(); 15407 } 15408 } 15409 15410 @Override 15411 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15412 int flags) { 15413 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15414 flags); 15415 } 15416 15417 @Override 15418 public void deletePackage(final String packageName, 15419 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15420 mContext.enforceCallingOrSelfPermission( 15421 android.Manifest.permission.DELETE_PACKAGES, null); 15422 Preconditions.checkNotNull(packageName); 15423 Preconditions.checkNotNull(observer); 15424 final int uid = Binder.getCallingUid(); 15425 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15426 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15427 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15428 mContext.enforceCallingOrSelfPermission( 15429 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15430 "deletePackage for user " + userId); 15431 } 15432 15433 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15434 try { 15435 observer.onPackageDeleted(packageName, 15436 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15437 } catch (RemoteException re) { 15438 } 15439 return; 15440 } 15441 15442 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15443 try { 15444 observer.onPackageDeleted(packageName, 15445 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15446 } catch (RemoteException re) { 15447 } 15448 return; 15449 } 15450 15451 if (DEBUG_REMOVE) { 15452 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15453 + " deleteAllUsers: " + deleteAllUsers ); 15454 } 15455 // Queue up an async operation since the package deletion may take a little while. 15456 mHandler.post(new Runnable() { 15457 public void run() { 15458 mHandler.removeCallbacks(this); 15459 int returnCode; 15460 if (!deleteAllUsers) { 15461 returnCode = deletePackageX(packageName, userId, deleteFlags); 15462 } else { 15463 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15464 // If nobody is blocking uninstall, proceed with delete for all users 15465 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15466 returnCode = deletePackageX(packageName, userId, deleteFlags); 15467 } else { 15468 // Otherwise uninstall individually for users with blockUninstalls=false 15469 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15470 for (int userId : users) { 15471 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15472 returnCode = deletePackageX(packageName, userId, userFlags); 15473 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15474 Slog.w(TAG, "Package delete failed for user " + userId 15475 + ", returnCode " + returnCode); 15476 } 15477 } 15478 } 15479 // The app has only been marked uninstalled for certain users. 15480 // We still need to report that delete was blocked 15481 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15482 } 15483 } 15484 try { 15485 observer.onPackageDeleted(packageName, returnCode, null); 15486 } catch (RemoteException e) { 15487 Log.i(TAG, "Observer no longer exists."); 15488 } //end catch 15489 } //end run 15490 }); 15491 } 15492 15493 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15494 int[] result = EMPTY_INT_ARRAY; 15495 for (int userId : userIds) { 15496 if (getBlockUninstallForUser(packageName, userId)) { 15497 result = ArrayUtils.appendInt(result, userId); 15498 } 15499 } 15500 return result; 15501 } 15502 15503 @Override 15504 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15505 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15506 } 15507 15508 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15509 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15510 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15511 try { 15512 if (dpm != null) { 15513 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15514 /* callingUserOnly =*/ false); 15515 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15516 : deviceOwnerComponentName.getPackageName(); 15517 // Does the package contains the device owner? 15518 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15519 // this check is probably not needed, since DO should be registered as a device 15520 // admin on some user too. (Original bug for this: b/17657954) 15521 if (packageName.equals(deviceOwnerPackageName)) { 15522 return true; 15523 } 15524 // Does it contain a device admin for any user? 15525 int[] users; 15526 if (userId == UserHandle.USER_ALL) { 15527 users = sUserManager.getUserIds(); 15528 } else { 15529 users = new int[]{userId}; 15530 } 15531 for (int i = 0; i < users.length; ++i) { 15532 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15533 return true; 15534 } 15535 } 15536 } 15537 } catch (RemoteException e) { 15538 } 15539 return false; 15540 } 15541 15542 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15543 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15544 } 15545 15546 /** 15547 * This method is an internal method that could be get invoked either 15548 * to delete an installed package or to clean up a failed installation. 15549 * After deleting an installed package, a broadcast is sent to notify any 15550 * listeners that the package has been removed. For cleaning up a failed 15551 * installation, the broadcast is not necessary since the package's 15552 * installation wouldn't have sent the initial broadcast either 15553 * The key steps in deleting a package are 15554 * deleting the package information in internal structures like mPackages, 15555 * deleting the packages base directories through installd 15556 * updating mSettings to reflect current status 15557 * persisting settings for later use 15558 * sending a broadcast if necessary 15559 */ 15560 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15561 final PackageRemovedInfo info = new PackageRemovedInfo(); 15562 final boolean res; 15563 15564 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15565 ? UserHandle.ALL : new UserHandle(userId); 15566 15567 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15568 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15569 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15570 } 15571 15572 PackageSetting uninstalledPs = null; 15573 15574 // for the uninstall-updates case and restricted profiles, remember the per- 15575 // user handle installed state 15576 int[] allUsers; 15577 synchronized (mPackages) { 15578 uninstalledPs = mSettings.mPackages.get(packageName); 15579 if (uninstalledPs == null) { 15580 Slog.w(TAG, "Not removing non-existent package " + packageName); 15581 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15582 } 15583 allUsers = sUserManager.getUserIds(); 15584 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15585 } 15586 15587 synchronized (mInstallLock) { 15588 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15589 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15590 "deletePackageX")) { 15591 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15592 deleteFlags | REMOVE_CHATTY, info, true, null); 15593 } 15594 synchronized (mPackages) { 15595 if (res) { 15596 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15597 } 15598 } 15599 } 15600 15601 if (res) { 15602 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15603 info.sendPackageRemovedBroadcasts(killApp); 15604 info.sendSystemPackageUpdatedBroadcasts(); 15605 info.sendSystemPackageAppearedBroadcasts(); 15606 } 15607 // Force a gc here. 15608 Runtime.getRuntime().gc(); 15609 // Delete the resources here after sending the broadcast to let 15610 // other processes clean up before deleting resources. 15611 if (info.args != null) { 15612 synchronized (mInstallLock) { 15613 info.args.doPostDeleteLI(true); 15614 } 15615 } 15616 15617 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15618 } 15619 15620 class PackageRemovedInfo { 15621 String removedPackage; 15622 int uid = -1; 15623 int removedAppId = -1; 15624 int[] origUsers; 15625 int[] removedUsers = null; 15626 boolean isRemovedPackageSystemUpdate = false; 15627 boolean isUpdate; 15628 boolean dataRemoved; 15629 boolean removedForAllUsers; 15630 // Clean up resources deleted packages. 15631 InstallArgs args = null; 15632 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15633 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15634 15635 void sendPackageRemovedBroadcasts(boolean killApp) { 15636 sendPackageRemovedBroadcastInternal(killApp); 15637 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15638 for (int i = 0; i < childCount; i++) { 15639 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15640 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15641 } 15642 } 15643 15644 void sendSystemPackageUpdatedBroadcasts() { 15645 if (isRemovedPackageSystemUpdate) { 15646 sendSystemPackageUpdatedBroadcastsInternal(); 15647 final int childCount = (removedChildPackages != null) 15648 ? removedChildPackages.size() : 0; 15649 for (int i = 0; i < childCount; i++) { 15650 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15651 if (childInfo.isRemovedPackageSystemUpdate) { 15652 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15653 } 15654 } 15655 } 15656 } 15657 15658 void sendSystemPackageAppearedBroadcasts() { 15659 final int packageCount = (appearedChildPackages != null) 15660 ? appearedChildPackages.size() : 0; 15661 for (int i = 0; i < packageCount; i++) { 15662 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15663 for (int userId : installedInfo.newUsers) { 15664 sendPackageAddedForUser(installedInfo.name, true, 15665 UserHandle.getAppId(installedInfo.uid), userId); 15666 } 15667 } 15668 } 15669 15670 private void sendSystemPackageUpdatedBroadcastsInternal() { 15671 Bundle extras = new Bundle(2); 15672 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15673 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15674 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15675 extras, 0, null, null, null); 15676 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15677 extras, 0, null, null, null); 15678 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15679 null, 0, removedPackage, null, null); 15680 } 15681 15682 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15683 Bundle extras = new Bundle(2); 15684 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15685 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15686 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15687 if (isUpdate || isRemovedPackageSystemUpdate) { 15688 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15689 } 15690 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15691 if (removedPackage != null) { 15692 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15693 extras, 0, null, null, removedUsers); 15694 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15695 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15696 removedPackage, extras, 0, null, null, removedUsers); 15697 } 15698 } 15699 if (removedAppId >= 0) { 15700 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15701 removedUsers); 15702 } 15703 } 15704 } 15705 15706 /* 15707 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15708 * flag is not set, the data directory is removed as well. 15709 * make sure this flag is set for partially installed apps. If not its meaningless to 15710 * delete a partially installed application. 15711 */ 15712 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15713 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15714 String packageName = ps.name; 15715 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15716 // Retrieve object to delete permissions for shared user later on 15717 final PackageParser.Package deletedPkg; 15718 final PackageSetting deletedPs; 15719 // reader 15720 synchronized (mPackages) { 15721 deletedPkg = mPackages.get(packageName); 15722 deletedPs = mSettings.mPackages.get(packageName); 15723 if (outInfo != null) { 15724 outInfo.removedPackage = packageName; 15725 outInfo.removedUsers = deletedPs != null 15726 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15727 : null; 15728 } 15729 } 15730 15731 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15732 15733 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15734 final PackageParser.Package resolvedPkg; 15735 if (deletedPkg != null) { 15736 resolvedPkg = deletedPkg; 15737 } else { 15738 // We don't have a parsed package when it lives on an ejected 15739 // adopted storage device, so fake something together 15740 resolvedPkg = new PackageParser.Package(ps.name); 15741 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15742 } 15743 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15744 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15745 destroyAppProfilesLIF(resolvedPkg, UserHandle.USER_ALL); 15746 if (outInfo != null) { 15747 outInfo.dataRemoved = true; 15748 } 15749 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15750 } 15751 15752 // writer 15753 synchronized (mPackages) { 15754 if (deletedPs != null) { 15755 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15756 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15757 clearDefaultBrowserIfNeeded(packageName); 15758 if (outInfo != null) { 15759 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15760 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15761 } 15762 updatePermissionsLPw(deletedPs.name, null, 0); 15763 if (deletedPs.sharedUser != null) { 15764 // Remove permissions associated with package. Since runtime 15765 // permissions are per user we have to kill the removed package 15766 // or packages running under the shared user of the removed 15767 // package if revoking the permissions requested only by the removed 15768 // package is successful and this causes a change in gids. 15769 for (int userId : UserManagerService.getInstance().getUserIds()) { 15770 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15771 userId); 15772 if (userIdToKill == UserHandle.USER_ALL 15773 || userIdToKill >= UserHandle.USER_SYSTEM) { 15774 // If gids changed for this user, kill all affected packages. 15775 mHandler.post(new Runnable() { 15776 @Override 15777 public void run() { 15778 // This has to happen with no lock held. 15779 killApplication(deletedPs.name, deletedPs.appId, 15780 KILL_APP_REASON_GIDS_CHANGED); 15781 } 15782 }); 15783 break; 15784 } 15785 } 15786 } 15787 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15788 } 15789 // make sure to preserve per-user disabled state if this removal was just 15790 // a downgrade of a system app to the factory package 15791 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15792 if (DEBUG_REMOVE) { 15793 Slog.d(TAG, "Propagating install state across downgrade"); 15794 } 15795 for (int userId : allUserHandles) { 15796 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15797 if (DEBUG_REMOVE) { 15798 Slog.d(TAG, " user " + userId + " => " + installed); 15799 } 15800 ps.setInstalled(installed, userId); 15801 } 15802 } 15803 } 15804 // can downgrade to reader 15805 if (writeSettings) { 15806 // Save settings now 15807 mSettings.writeLPr(); 15808 } 15809 } 15810 if (outInfo != null) { 15811 // A user ID was deleted here. Go through all users and remove it 15812 // from KeyStore. 15813 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15814 } 15815 } 15816 15817 static boolean locationIsPrivileged(File path) { 15818 try { 15819 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15820 .getCanonicalPath(); 15821 return path.getCanonicalPath().startsWith(privilegedAppDir); 15822 } catch (IOException e) { 15823 Slog.e(TAG, "Unable to access code path " + path); 15824 } 15825 return false; 15826 } 15827 15828 /* 15829 * Tries to delete system package. 15830 */ 15831 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15832 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15833 boolean writeSettings) { 15834 if (deletedPs.parentPackageName != null) { 15835 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15836 return false; 15837 } 15838 15839 final boolean applyUserRestrictions 15840 = (allUserHandles != null) && (outInfo.origUsers != null); 15841 final PackageSetting disabledPs; 15842 // Confirm if the system package has been updated 15843 // An updated system app can be deleted. This will also have to restore 15844 // the system pkg from system partition 15845 // reader 15846 synchronized (mPackages) { 15847 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15848 } 15849 15850 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15851 + " disabledPs=" + disabledPs); 15852 15853 if (disabledPs == null) { 15854 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15855 return false; 15856 } else if (DEBUG_REMOVE) { 15857 Slog.d(TAG, "Deleting system pkg from data partition"); 15858 } 15859 15860 if (DEBUG_REMOVE) { 15861 if (applyUserRestrictions) { 15862 Slog.d(TAG, "Remembering install states:"); 15863 for (int userId : allUserHandles) { 15864 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15865 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15866 } 15867 } 15868 } 15869 15870 // Delete the updated package 15871 outInfo.isRemovedPackageSystemUpdate = true; 15872 if (outInfo.removedChildPackages != null) { 15873 final int childCount = (deletedPs.childPackageNames != null) 15874 ? deletedPs.childPackageNames.size() : 0; 15875 for (int i = 0; i < childCount; i++) { 15876 String childPackageName = deletedPs.childPackageNames.get(i); 15877 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15878 .contains(childPackageName)) { 15879 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15880 childPackageName); 15881 if (childInfo != null) { 15882 childInfo.isRemovedPackageSystemUpdate = true; 15883 } 15884 } 15885 } 15886 } 15887 15888 if (disabledPs.versionCode < deletedPs.versionCode) { 15889 // Delete data for downgrades 15890 flags &= ~PackageManager.DELETE_KEEP_DATA; 15891 } else { 15892 // Preserve data by setting flag 15893 flags |= PackageManager.DELETE_KEEP_DATA; 15894 } 15895 15896 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15897 outInfo, writeSettings, disabledPs.pkg); 15898 if (!ret) { 15899 return false; 15900 } 15901 15902 // writer 15903 synchronized (mPackages) { 15904 // Reinstate the old system package 15905 enableSystemPackageLPw(disabledPs.pkg); 15906 // Remove any native libraries from the upgraded package. 15907 removeNativeBinariesLI(deletedPs); 15908 } 15909 15910 // Install the system package 15911 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15912 int parseFlags = mDefParseFlags 15913 | PackageParser.PARSE_MUST_BE_APK 15914 | PackageParser.PARSE_IS_SYSTEM 15915 | PackageParser.PARSE_IS_SYSTEM_DIR; 15916 if (locationIsPrivileged(disabledPs.codePath)) { 15917 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15918 } 15919 15920 final PackageParser.Package newPkg; 15921 try { 15922 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15923 } catch (PackageManagerException e) { 15924 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15925 + e.getMessage()); 15926 return false; 15927 } 15928 15929 prepareAppDataAfterInstallLIF(newPkg); 15930 15931 // writer 15932 synchronized (mPackages) { 15933 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15934 15935 // Propagate the permissions state as we do not want to drop on the floor 15936 // runtime permissions. The update permissions method below will take 15937 // care of removing obsolete permissions and grant install permissions. 15938 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15939 updatePermissionsLPw(newPkg.packageName, newPkg, 15940 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15941 15942 if (applyUserRestrictions) { 15943 if (DEBUG_REMOVE) { 15944 Slog.d(TAG, "Propagating install state across reinstall"); 15945 } 15946 for (int userId : allUserHandles) { 15947 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15948 if (DEBUG_REMOVE) { 15949 Slog.d(TAG, " user " + userId + " => " + installed); 15950 } 15951 ps.setInstalled(installed, userId); 15952 15953 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15954 } 15955 // Regardless of writeSettings we need to ensure that this restriction 15956 // state propagation is persisted 15957 mSettings.writeAllUsersPackageRestrictionsLPr(); 15958 } 15959 // can downgrade to reader here 15960 if (writeSettings) { 15961 mSettings.writeLPr(); 15962 } 15963 } 15964 return true; 15965 } 15966 15967 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15968 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15969 PackageRemovedInfo outInfo, boolean writeSettings, 15970 PackageParser.Package replacingPackage) { 15971 synchronized (mPackages) { 15972 if (outInfo != null) { 15973 outInfo.uid = ps.appId; 15974 } 15975 15976 if (outInfo != null && outInfo.removedChildPackages != null) { 15977 final int childCount = (ps.childPackageNames != null) 15978 ? ps.childPackageNames.size() : 0; 15979 for (int i = 0; i < childCount; i++) { 15980 String childPackageName = ps.childPackageNames.get(i); 15981 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15982 if (childPs == null) { 15983 return false; 15984 } 15985 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15986 childPackageName); 15987 if (childInfo != null) { 15988 childInfo.uid = childPs.appId; 15989 } 15990 } 15991 } 15992 } 15993 15994 // Delete package data from internal structures and also remove data if flag is set 15995 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15996 15997 // Delete the child packages data 15998 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15999 for (int i = 0; i < childCount; i++) { 16000 PackageSetting childPs; 16001 synchronized (mPackages) { 16002 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 16003 } 16004 if (childPs != null) { 16005 PackageRemovedInfo childOutInfo = (outInfo != null 16006 && outInfo.removedChildPackages != null) 16007 ? outInfo.removedChildPackages.get(childPs.name) : null; 16008 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 16009 && (replacingPackage != null 16010 && !replacingPackage.hasChildPackage(childPs.name)) 16011 ? flags & ~DELETE_KEEP_DATA : flags; 16012 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 16013 deleteFlags, writeSettings); 16014 } 16015 } 16016 16017 // Delete application code and resources only for parent packages 16018 if (ps.parentPackageName == null) { 16019 if (deleteCodeAndResources && (outInfo != null)) { 16020 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 16021 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 16022 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 16023 } 16024 } 16025 16026 return true; 16027 } 16028 16029 @Override 16030 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 16031 int userId) { 16032 mContext.enforceCallingOrSelfPermission( 16033 android.Manifest.permission.DELETE_PACKAGES, null); 16034 synchronized (mPackages) { 16035 PackageSetting ps = mSettings.mPackages.get(packageName); 16036 if (ps == null) { 16037 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 16038 return false; 16039 } 16040 if (!ps.getInstalled(userId)) { 16041 // Can't block uninstall for an app that is not installed or enabled. 16042 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 16043 return false; 16044 } 16045 ps.setBlockUninstall(blockUninstall, userId); 16046 mSettings.writePackageRestrictionsLPr(userId); 16047 } 16048 return true; 16049 } 16050 16051 @Override 16052 public boolean getBlockUninstallForUser(String packageName, int userId) { 16053 synchronized (mPackages) { 16054 PackageSetting ps = mSettings.mPackages.get(packageName); 16055 if (ps == null) { 16056 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 16057 return false; 16058 } 16059 return ps.getBlockUninstall(userId); 16060 } 16061 } 16062 16063 @Override 16064 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 16065 int callingUid = Binder.getCallingUid(); 16066 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 16067 throw new SecurityException( 16068 "setRequiredForSystemUser can only be run by the system or root"); 16069 } 16070 synchronized (mPackages) { 16071 PackageSetting ps = mSettings.mPackages.get(packageName); 16072 if (ps == null) { 16073 Log.w(TAG, "Package doesn't exist: " + packageName); 16074 return false; 16075 } 16076 if (systemUserApp) { 16077 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16078 } else { 16079 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 16080 } 16081 mSettings.writeLPr(); 16082 } 16083 return true; 16084 } 16085 16086 /* 16087 * This method handles package deletion in general 16088 */ 16089 private boolean deletePackageLIF(String packageName, UserHandle user, 16090 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 16091 PackageRemovedInfo outInfo, boolean writeSettings, 16092 PackageParser.Package replacingPackage) { 16093 if (packageName == null) { 16094 Slog.w(TAG, "Attempt to delete null packageName."); 16095 return false; 16096 } 16097 16098 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 16099 16100 PackageSetting ps; 16101 16102 synchronized (mPackages) { 16103 ps = mSettings.mPackages.get(packageName); 16104 if (ps == null) { 16105 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16106 return false; 16107 } 16108 16109 if (ps.parentPackageName != null && (!isSystemApp(ps) 16110 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 16111 if (DEBUG_REMOVE) { 16112 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 16113 + ((user == null) ? UserHandle.USER_ALL : user)); 16114 } 16115 final int removedUserId = (user != null) ? user.getIdentifier() 16116 : UserHandle.USER_ALL; 16117 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 16118 return false; 16119 } 16120 markPackageUninstalledForUserLPw(ps, user); 16121 scheduleWritePackageRestrictionsLocked(user); 16122 return true; 16123 } 16124 } 16125 16126 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 16127 && user.getIdentifier() != UserHandle.USER_ALL)) { 16128 // The caller is asking that the package only be deleted for a single 16129 // user. To do this, we just mark its uninstalled state and delete 16130 // its data. If this is a system app, we only allow this to happen if 16131 // they have set the special DELETE_SYSTEM_APP which requests different 16132 // semantics than normal for uninstalling system apps. 16133 markPackageUninstalledForUserLPw(ps, user); 16134 16135 if (!isSystemApp(ps)) { 16136 // Do not uninstall the APK if an app should be cached 16137 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 16138 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 16139 // Other user still have this package installed, so all 16140 // we need to do is clear this user's data and save that 16141 // it is uninstalled. 16142 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 16143 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16144 return false; 16145 } 16146 scheduleWritePackageRestrictionsLocked(user); 16147 return true; 16148 } else { 16149 // We need to set it back to 'installed' so the uninstall 16150 // broadcasts will be sent correctly. 16151 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 16152 ps.setInstalled(true, user.getIdentifier()); 16153 } 16154 } else { 16155 // This is a system app, so we assume that the 16156 // other users still have this package installed, so all 16157 // we need to do is clear this user's data and save that 16158 // it is uninstalled. 16159 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 16160 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 16161 return false; 16162 } 16163 scheduleWritePackageRestrictionsLocked(user); 16164 return true; 16165 } 16166 } 16167 16168 // If we are deleting a composite package for all users, keep track 16169 // of result for each child. 16170 if (ps.childPackageNames != null && outInfo != null) { 16171 synchronized (mPackages) { 16172 final int childCount = ps.childPackageNames.size(); 16173 outInfo.removedChildPackages = new ArrayMap<>(childCount); 16174 for (int i = 0; i < childCount; i++) { 16175 String childPackageName = ps.childPackageNames.get(i); 16176 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 16177 childInfo.removedPackage = childPackageName; 16178 outInfo.removedChildPackages.put(childPackageName, childInfo); 16179 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16180 if (childPs != null) { 16181 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 16182 } 16183 } 16184 } 16185 } 16186 16187 boolean ret = false; 16188 if (isSystemApp(ps)) { 16189 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 16190 // When an updated system application is deleted we delete the existing resources 16191 // as well and fall back to existing code in system partition 16192 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 16193 } else { 16194 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 16195 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 16196 outInfo, writeSettings, replacingPackage); 16197 } 16198 16199 // Take a note whether we deleted the package for all users 16200 if (outInfo != null) { 16201 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 16202 if (outInfo.removedChildPackages != null) { 16203 synchronized (mPackages) { 16204 final int childCount = outInfo.removedChildPackages.size(); 16205 for (int i = 0; i < childCount; i++) { 16206 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 16207 if (childInfo != null) { 16208 childInfo.removedForAllUsers = mPackages.get( 16209 childInfo.removedPackage) == null; 16210 } 16211 } 16212 } 16213 } 16214 // If we uninstalled an update to a system app there may be some 16215 // child packages that appeared as they are declared in the system 16216 // app but were not declared in the update. 16217 if (isSystemApp(ps)) { 16218 synchronized (mPackages) { 16219 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 16220 final int childCount = (updatedPs.childPackageNames != null) 16221 ? updatedPs.childPackageNames.size() : 0; 16222 for (int i = 0; i < childCount; i++) { 16223 String childPackageName = updatedPs.childPackageNames.get(i); 16224 if (outInfo.removedChildPackages == null 16225 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 16226 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 16227 if (childPs == null) { 16228 continue; 16229 } 16230 PackageInstalledInfo installRes = new PackageInstalledInfo(); 16231 installRes.name = childPackageName; 16232 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16233 installRes.pkg = mPackages.get(childPackageName); 16234 installRes.uid = childPs.pkg.applicationInfo.uid; 16235 if (outInfo.appearedChildPackages == null) { 16236 outInfo.appearedChildPackages = new ArrayMap<>(); 16237 } 16238 outInfo.appearedChildPackages.put(childPackageName, installRes); 16239 } 16240 } 16241 } 16242 } 16243 } 16244 16245 return ret; 16246 } 16247 16248 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16249 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16250 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16251 for (int nextUserId : userIds) { 16252 if (DEBUG_REMOVE) { 16253 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16254 } 16255 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16256 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16257 false /*hidden*/, false /*suspended*/, null, null, null, 16258 false /*blockUninstall*/, 16259 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16260 } 16261 } 16262 16263 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16264 PackageRemovedInfo outInfo) { 16265 final PackageParser.Package pkg; 16266 synchronized (mPackages) { 16267 pkg = mPackages.get(ps.name); 16268 } 16269 16270 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16271 : new int[] {userId}; 16272 for (int nextUserId : userIds) { 16273 if (DEBUG_REMOVE) { 16274 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16275 + nextUserId); 16276 } 16277 16278 destroyAppDataLIF(pkg, userId, 16279 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16280 destroyAppProfilesLIF(pkg, userId); 16281 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16282 schedulePackageCleaning(ps.name, nextUserId, false); 16283 synchronized (mPackages) { 16284 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16285 scheduleWritePackageRestrictionsLocked(nextUserId); 16286 } 16287 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16288 } 16289 } 16290 16291 if (outInfo != null) { 16292 outInfo.removedPackage = ps.name; 16293 outInfo.removedAppId = ps.appId; 16294 outInfo.removedUsers = userIds; 16295 } 16296 16297 return true; 16298 } 16299 16300 private final class ClearStorageConnection implements ServiceConnection { 16301 IMediaContainerService mContainerService; 16302 16303 @Override 16304 public void onServiceConnected(ComponentName name, IBinder service) { 16305 synchronized (this) { 16306 mContainerService = IMediaContainerService.Stub.asInterface(service); 16307 notifyAll(); 16308 } 16309 } 16310 16311 @Override 16312 public void onServiceDisconnected(ComponentName name) { 16313 } 16314 } 16315 16316 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16317 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16318 16319 final boolean mounted; 16320 if (Environment.isExternalStorageEmulated()) { 16321 mounted = true; 16322 } else { 16323 final String status = Environment.getExternalStorageState(); 16324 16325 mounted = status.equals(Environment.MEDIA_MOUNTED) 16326 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16327 } 16328 16329 if (!mounted) { 16330 return; 16331 } 16332 16333 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16334 int[] users; 16335 if (userId == UserHandle.USER_ALL) { 16336 users = sUserManager.getUserIds(); 16337 } else { 16338 users = new int[] { userId }; 16339 } 16340 final ClearStorageConnection conn = new ClearStorageConnection(); 16341 if (mContext.bindServiceAsUser( 16342 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16343 try { 16344 for (int curUser : users) { 16345 long timeout = SystemClock.uptimeMillis() + 5000; 16346 synchronized (conn) { 16347 long now = SystemClock.uptimeMillis(); 16348 while (conn.mContainerService == null && now < timeout) { 16349 try { 16350 conn.wait(timeout - now); 16351 } catch (InterruptedException e) { 16352 } 16353 } 16354 } 16355 if (conn.mContainerService == null) { 16356 return; 16357 } 16358 16359 final UserEnvironment userEnv = new UserEnvironment(curUser); 16360 clearDirectory(conn.mContainerService, 16361 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16362 if (allData) { 16363 clearDirectory(conn.mContainerService, 16364 userEnv.buildExternalStorageAppDataDirs(packageName)); 16365 clearDirectory(conn.mContainerService, 16366 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16367 } 16368 } 16369 } finally { 16370 mContext.unbindService(conn); 16371 } 16372 } 16373 } 16374 16375 @Override 16376 public void clearApplicationProfileData(String packageName) { 16377 enforceSystemOrRoot("Only the system can clear all profile data"); 16378 16379 final PackageParser.Package pkg; 16380 synchronized (mPackages) { 16381 pkg = mPackages.get(packageName); 16382 } 16383 16384 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16385 synchronized (mInstallLock) { 16386 clearAppProfilesLIF(pkg, UserHandle.USER_ALL); 16387 destroyAppReferenceProfileLeafLIF(pkg, UserHandle.USER_ALL, 16388 true /* removeBaseMarker */); 16389 } 16390 } 16391 } 16392 16393 @Override 16394 public void clearApplicationUserData(final String packageName, 16395 final IPackageDataObserver observer, final int userId) { 16396 mContext.enforceCallingOrSelfPermission( 16397 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16398 16399 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16400 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16401 16402 final DevicePolicyManagerInternal dpmi = LocalServices 16403 .getService(DevicePolicyManagerInternal.class); 16404 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16405 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16406 } 16407 // Queue up an async operation since the package deletion may take a little while. 16408 mHandler.post(new Runnable() { 16409 public void run() { 16410 mHandler.removeCallbacks(this); 16411 final boolean succeeded; 16412 try (PackageFreezer freezer = freezePackage(packageName, 16413 "clearApplicationUserData")) { 16414 synchronized (mInstallLock) { 16415 succeeded = clearApplicationUserDataLIF(packageName, userId); 16416 } 16417 clearExternalStorageDataSync(packageName, userId, true); 16418 } 16419 if (succeeded) { 16420 // invoke DeviceStorageMonitor's update method to clear any notifications 16421 DeviceStorageMonitorInternal dsm = LocalServices 16422 .getService(DeviceStorageMonitorInternal.class); 16423 if (dsm != null) { 16424 dsm.checkMemory(); 16425 } 16426 } 16427 if(observer != null) { 16428 try { 16429 observer.onRemoveCompleted(packageName, succeeded); 16430 } catch (RemoteException e) { 16431 Log.i(TAG, "Observer no longer exists."); 16432 } 16433 } //end if observer 16434 } //end run 16435 }); 16436 } 16437 16438 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16439 if (packageName == null) { 16440 Slog.w(TAG, "Attempt to delete null packageName."); 16441 return false; 16442 } 16443 16444 // Try finding details about the requested package 16445 PackageParser.Package pkg; 16446 synchronized (mPackages) { 16447 pkg = mPackages.get(packageName); 16448 if (pkg == null) { 16449 final PackageSetting ps = mSettings.mPackages.get(packageName); 16450 if (ps != null) { 16451 pkg = ps.pkg; 16452 } 16453 } 16454 16455 if (pkg == null) { 16456 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16457 return false; 16458 } 16459 16460 PackageSetting ps = (PackageSetting) pkg.mExtras; 16461 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16462 } 16463 16464 clearAppDataLIF(pkg, userId, 16465 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16466 16467 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16468 removeKeystoreDataIfNeeded(userId, appId); 16469 16470 UserManagerInternal umInternal = getUserManagerInternal(); 16471 final int flags; 16472 if (umInternal.isUserUnlockingOrUnlocked(userId)) { 16473 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16474 } else if (umInternal.isUserRunning(userId)) { 16475 flags = StorageManager.FLAG_STORAGE_DE; 16476 } else { 16477 flags = 0; 16478 } 16479 prepareAppDataContentsLIF(pkg, userId, flags); 16480 16481 return true; 16482 } 16483 16484 /** 16485 * Reverts user permission state changes (permissions and flags) in 16486 * all packages for a given user. 16487 * 16488 * @param userId The device user for which to do a reset. 16489 */ 16490 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16491 final int packageCount = mPackages.size(); 16492 for (int i = 0; i < packageCount; i++) { 16493 PackageParser.Package pkg = mPackages.valueAt(i); 16494 PackageSetting ps = (PackageSetting) pkg.mExtras; 16495 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16496 } 16497 } 16498 16499 private void resetNetworkPolicies(int userId) { 16500 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16501 } 16502 16503 /** 16504 * Reverts user permission state changes (permissions and flags). 16505 * 16506 * @param ps The package for which to reset. 16507 * @param userId The device user for which to do a reset. 16508 */ 16509 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16510 final PackageSetting ps, final int userId) { 16511 if (ps.pkg == null) { 16512 return; 16513 } 16514 16515 // These are flags that can change base on user actions. 16516 final int userSettableMask = FLAG_PERMISSION_USER_SET 16517 | FLAG_PERMISSION_USER_FIXED 16518 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16519 | FLAG_PERMISSION_REVIEW_REQUIRED; 16520 16521 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16522 | FLAG_PERMISSION_POLICY_FIXED; 16523 16524 boolean writeInstallPermissions = false; 16525 boolean writeRuntimePermissions = false; 16526 16527 final int permissionCount = ps.pkg.requestedPermissions.size(); 16528 for (int i = 0; i < permissionCount; i++) { 16529 String permission = ps.pkg.requestedPermissions.get(i); 16530 16531 BasePermission bp = mSettings.mPermissions.get(permission); 16532 if (bp == null) { 16533 continue; 16534 } 16535 16536 // If shared user we just reset the state to which only this app contributed. 16537 if (ps.sharedUser != null) { 16538 boolean used = false; 16539 final int packageCount = ps.sharedUser.packages.size(); 16540 for (int j = 0; j < packageCount; j++) { 16541 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16542 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16543 && pkg.pkg.requestedPermissions.contains(permission)) { 16544 used = true; 16545 break; 16546 } 16547 } 16548 if (used) { 16549 continue; 16550 } 16551 } 16552 16553 PermissionsState permissionsState = ps.getPermissionsState(); 16554 16555 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16556 16557 // Always clear the user settable flags. 16558 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16559 bp.name) != null; 16560 // If permission review is enabled and this is a legacy app, mark the 16561 // permission as requiring a review as this is the initial state. 16562 int flags = 0; 16563 if (Build.PERMISSIONS_REVIEW_REQUIRED 16564 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16565 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16566 } 16567 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16568 if (hasInstallState) { 16569 writeInstallPermissions = true; 16570 } else { 16571 writeRuntimePermissions = true; 16572 } 16573 } 16574 16575 // Below is only runtime permission handling. 16576 if (!bp.isRuntime()) { 16577 continue; 16578 } 16579 16580 // Never clobber system or policy. 16581 if ((oldFlags & policyOrSystemFlags) != 0) { 16582 continue; 16583 } 16584 16585 // If this permission was granted by default, make sure it is. 16586 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16587 if (permissionsState.grantRuntimePermission(bp, userId) 16588 != PERMISSION_OPERATION_FAILURE) { 16589 writeRuntimePermissions = true; 16590 } 16591 // If permission review is enabled the permissions for a legacy apps 16592 // are represented as constantly granted runtime ones, so don't revoke. 16593 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16594 // Otherwise, reset the permission. 16595 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16596 switch (revokeResult) { 16597 case PERMISSION_OPERATION_SUCCESS: 16598 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16599 writeRuntimePermissions = true; 16600 final int appId = ps.appId; 16601 mHandler.post(new Runnable() { 16602 @Override 16603 public void run() { 16604 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16605 } 16606 }); 16607 } break; 16608 } 16609 } 16610 } 16611 16612 // Synchronously write as we are taking permissions away. 16613 if (writeRuntimePermissions) { 16614 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16615 } 16616 16617 // Synchronously write as we are taking permissions away. 16618 if (writeInstallPermissions) { 16619 mSettings.writeLPr(); 16620 } 16621 } 16622 16623 /** 16624 * Remove entries from the keystore daemon. Will only remove it if the 16625 * {@code appId} is valid. 16626 */ 16627 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16628 if (appId < 0) { 16629 return; 16630 } 16631 16632 final KeyStore keyStore = KeyStore.getInstance(); 16633 if (keyStore != null) { 16634 if (userId == UserHandle.USER_ALL) { 16635 for (final int individual : sUserManager.getUserIds()) { 16636 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16637 } 16638 } else { 16639 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16640 } 16641 } else { 16642 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16643 } 16644 } 16645 16646 @Override 16647 public void deleteApplicationCacheFiles(final String packageName, 16648 final IPackageDataObserver observer) { 16649 final int userId = UserHandle.getCallingUserId(); 16650 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16651 } 16652 16653 @Override 16654 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16655 final IPackageDataObserver observer) { 16656 mContext.enforceCallingOrSelfPermission( 16657 android.Manifest.permission.DELETE_CACHE_FILES, null); 16658 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16659 /* requireFullPermission= */ true, /* checkShell= */ false, 16660 "delete application cache files"); 16661 16662 final PackageParser.Package pkg; 16663 synchronized (mPackages) { 16664 pkg = mPackages.get(packageName); 16665 } 16666 16667 // Queue up an async operation since the package deletion may take a little while. 16668 mHandler.post(new Runnable() { 16669 public void run() { 16670 synchronized (mInstallLock) { 16671 final int flags = StorageManager.FLAG_STORAGE_DE 16672 | StorageManager.FLAG_STORAGE_CE; 16673 // We're only clearing cache files, so we don't care if the 16674 // app is unfrozen and still able to run 16675 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16676 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16677 } 16678 clearExternalStorageDataSync(packageName, userId, false); 16679 if (observer != null) { 16680 try { 16681 observer.onRemoveCompleted(packageName, true); 16682 } catch (RemoteException e) { 16683 Log.i(TAG, "Observer no longer exists."); 16684 } 16685 } 16686 } 16687 }); 16688 } 16689 16690 @Override 16691 public void getPackageSizeInfo(final String packageName, int userHandle, 16692 final IPackageStatsObserver observer) { 16693 mContext.enforceCallingOrSelfPermission( 16694 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16695 if (packageName == null) { 16696 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16697 } 16698 16699 PackageStats stats = new PackageStats(packageName, userHandle); 16700 16701 /* 16702 * Queue up an async operation since the package measurement may take a 16703 * little while. 16704 */ 16705 Message msg = mHandler.obtainMessage(INIT_COPY); 16706 msg.obj = new MeasureParams(stats, observer); 16707 mHandler.sendMessage(msg); 16708 } 16709 16710 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16711 final PackageSetting ps; 16712 synchronized (mPackages) { 16713 ps = mSettings.mPackages.get(packageName); 16714 if (ps == null) { 16715 Slog.w(TAG, "Failed to find settings for " + packageName); 16716 return false; 16717 } 16718 } 16719 try { 16720 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16721 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16722 ps.getCeDataInode(userId), ps.codePathString, stats); 16723 } catch (InstallerException e) { 16724 Slog.w(TAG, String.valueOf(e)); 16725 return false; 16726 } 16727 16728 // For now, ignore code size of packages on system partition 16729 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16730 stats.codeSize = 0; 16731 } 16732 16733 return true; 16734 } 16735 16736 private int getUidTargetSdkVersionLockedLPr(int uid) { 16737 Object obj = mSettings.getUserIdLPr(uid); 16738 if (obj instanceof SharedUserSetting) { 16739 final SharedUserSetting sus = (SharedUserSetting) obj; 16740 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16741 final Iterator<PackageSetting> it = sus.packages.iterator(); 16742 while (it.hasNext()) { 16743 final PackageSetting ps = it.next(); 16744 if (ps.pkg != null) { 16745 int v = ps.pkg.applicationInfo.targetSdkVersion; 16746 if (v < vers) vers = v; 16747 } 16748 } 16749 return vers; 16750 } else if (obj instanceof PackageSetting) { 16751 final PackageSetting ps = (PackageSetting) obj; 16752 if (ps.pkg != null) { 16753 return ps.pkg.applicationInfo.targetSdkVersion; 16754 } 16755 } 16756 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16757 } 16758 16759 @Override 16760 public void addPreferredActivity(IntentFilter filter, int match, 16761 ComponentName[] set, ComponentName activity, int userId) { 16762 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16763 "Adding preferred"); 16764 } 16765 16766 private void addPreferredActivityInternal(IntentFilter filter, int match, 16767 ComponentName[] set, ComponentName activity, boolean always, int userId, 16768 String opname) { 16769 // writer 16770 int callingUid = Binder.getCallingUid(); 16771 enforceCrossUserPermission(callingUid, userId, 16772 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16773 if (filter.countActions() == 0) { 16774 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16775 return; 16776 } 16777 synchronized (mPackages) { 16778 if (mContext.checkCallingOrSelfPermission( 16779 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16780 != PackageManager.PERMISSION_GRANTED) { 16781 if (getUidTargetSdkVersionLockedLPr(callingUid) 16782 < Build.VERSION_CODES.FROYO) { 16783 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16784 + callingUid); 16785 return; 16786 } 16787 mContext.enforceCallingOrSelfPermission( 16788 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16789 } 16790 16791 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16792 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16793 + userId + ":"); 16794 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16795 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16796 scheduleWritePackageRestrictionsLocked(userId); 16797 } 16798 } 16799 16800 @Override 16801 public void replacePreferredActivity(IntentFilter filter, int match, 16802 ComponentName[] set, ComponentName activity, int userId) { 16803 if (filter.countActions() != 1) { 16804 throw new IllegalArgumentException( 16805 "replacePreferredActivity expects filter to have only 1 action."); 16806 } 16807 if (filter.countDataAuthorities() != 0 16808 || filter.countDataPaths() != 0 16809 || filter.countDataSchemes() > 1 16810 || filter.countDataTypes() != 0) { 16811 throw new IllegalArgumentException( 16812 "replacePreferredActivity expects filter to have no data authorities, " + 16813 "paths, or types; and at most one scheme."); 16814 } 16815 16816 final int callingUid = Binder.getCallingUid(); 16817 enforceCrossUserPermission(callingUid, userId, 16818 true /* requireFullPermission */, false /* checkShell */, 16819 "replace preferred activity"); 16820 synchronized (mPackages) { 16821 if (mContext.checkCallingOrSelfPermission( 16822 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16823 != PackageManager.PERMISSION_GRANTED) { 16824 if (getUidTargetSdkVersionLockedLPr(callingUid) 16825 < Build.VERSION_CODES.FROYO) { 16826 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16827 + Binder.getCallingUid()); 16828 return; 16829 } 16830 mContext.enforceCallingOrSelfPermission( 16831 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16832 } 16833 16834 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16835 if (pir != null) { 16836 // Get all of the existing entries that exactly match this filter. 16837 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16838 if (existing != null && existing.size() == 1) { 16839 PreferredActivity cur = existing.get(0); 16840 if (DEBUG_PREFERRED) { 16841 Slog.i(TAG, "Checking replace of preferred:"); 16842 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16843 if (!cur.mPref.mAlways) { 16844 Slog.i(TAG, " -- CUR; not mAlways!"); 16845 } else { 16846 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16847 Slog.i(TAG, " -- CUR: mSet=" 16848 + Arrays.toString(cur.mPref.mSetComponents)); 16849 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16850 Slog.i(TAG, " -- NEW: mMatch=" 16851 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16852 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16853 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16854 } 16855 } 16856 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16857 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16858 && cur.mPref.sameSet(set)) { 16859 // Setting the preferred activity to what it happens to be already 16860 if (DEBUG_PREFERRED) { 16861 Slog.i(TAG, "Replacing with same preferred activity " 16862 + cur.mPref.mShortComponent + " for user " 16863 + userId + ":"); 16864 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16865 } 16866 return; 16867 } 16868 } 16869 16870 if (existing != null) { 16871 if (DEBUG_PREFERRED) { 16872 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16873 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16874 } 16875 for (int i = 0; i < existing.size(); i++) { 16876 PreferredActivity pa = existing.get(i); 16877 if (DEBUG_PREFERRED) { 16878 Slog.i(TAG, "Removing existing preferred activity " 16879 + pa.mPref.mComponent + ":"); 16880 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16881 } 16882 pir.removeFilter(pa); 16883 } 16884 } 16885 } 16886 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16887 "Replacing preferred"); 16888 } 16889 } 16890 16891 @Override 16892 public void clearPackagePreferredActivities(String packageName) { 16893 final int uid = Binder.getCallingUid(); 16894 // writer 16895 synchronized (mPackages) { 16896 PackageParser.Package pkg = mPackages.get(packageName); 16897 if (pkg == null || pkg.applicationInfo.uid != uid) { 16898 if (mContext.checkCallingOrSelfPermission( 16899 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16900 != PackageManager.PERMISSION_GRANTED) { 16901 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16902 < Build.VERSION_CODES.FROYO) { 16903 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16904 + Binder.getCallingUid()); 16905 return; 16906 } 16907 mContext.enforceCallingOrSelfPermission( 16908 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16909 } 16910 } 16911 16912 int user = UserHandle.getCallingUserId(); 16913 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16914 scheduleWritePackageRestrictionsLocked(user); 16915 } 16916 } 16917 } 16918 16919 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16920 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16921 ArrayList<PreferredActivity> removed = null; 16922 boolean changed = false; 16923 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16924 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16925 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16926 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16927 continue; 16928 } 16929 Iterator<PreferredActivity> it = pir.filterIterator(); 16930 while (it.hasNext()) { 16931 PreferredActivity pa = it.next(); 16932 // Mark entry for removal only if it matches the package name 16933 // and the entry is of type "always". 16934 if (packageName == null || 16935 (pa.mPref.mComponent.getPackageName().equals(packageName) 16936 && pa.mPref.mAlways)) { 16937 if (removed == null) { 16938 removed = new ArrayList<PreferredActivity>(); 16939 } 16940 removed.add(pa); 16941 } 16942 } 16943 if (removed != null) { 16944 for (int j=0; j<removed.size(); j++) { 16945 PreferredActivity pa = removed.get(j); 16946 pir.removeFilter(pa); 16947 } 16948 changed = true; 16949 } 16950 } 16951 return changed; 16952 } 16953 16954 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16955 private void clearIntentFilterVerificationsLPw(int userId) { 16956 final int packageCount = mPackages.size(); 16957 for (int i = 0; i < packageCount; i++) { 16958 PackageParser.Package pkg = mPackages.valueAt(i); 16959 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16960 } 16961 } 16962 16963 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16964 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16965 if (userId == UserHandle.USER_ALL) { 16966 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16967 sUserManager.getUserIds())) { 16968 for (int oneUserId : sUserManager.getUserIds()) { 16969 scheduleWritePackageRestrictionsLocked(oneUserId); 16970 } 16971 } 16972 } else { 16973 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16974 scheduleWritePackageRestrictionsLocked(userId); 16975 } 16976 } 16977 } 16978 16979 void clearDefaultBrowserIfNeeded(String packageName) { 16980 for (int oneUserId : sUserManager.getUserIds()) { 16981 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16982 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16983 if (packageName.equals(defaultBrowserPackageName)) { 16984 setDefaultBrowserPackageName(null, oneUserId); 16985 } 16986 } 16987 } 16988 16989 @Override 16990 public void resetApplicationPreferences(int userId) { 16991 mContext.enforceCallingOrSelfPermission( 16992 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16993 final long identity = Binder.clearCallingIdentity(); 16994 // writer 16995 try { 16996 synchronized (mPackages) { 16997 clearPackagePreferredActivitiesLPw(null, userId); 16998 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16999 // TODO: We have to reset the default SMS and Phone. This requires 17000 // significant refactoring to keep all default apps in the package 17001 // manager (cleaner but more work) or have the services provide 17002 // callbacks to the package manager to request a default app reset. 17003 applyFactoryDefaultBrowserLPw(userId); 17004 clearIntentFilterVerificationsLPw(userId); 17005 primeDomainVerificationsLPw(userId); 17006 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 17007 scheduleWritePackageRestrictionsLocked(userId); 17008 } 17009 resetNetworkPolicies(userId); 17010 } finally { 17011 Binder.restoreCallingIdentity(identity); 17012 } 17013 } 17014 17015 @Override 17016 public int getPreferredActivities(List<IntentFilter> outFilters, 17017 List<ComponentName> outActivities, String packageName) { 17018 17019 int num = 0; 17020 final int userId = UserHandle.getCallingUserId(); 17021 // reader 17022 synchronized (mPackages) { 17023 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 17024 if (pir != null) { 17025 final Iterator<PreferredActivity> it = pir.filterIterator(); 17026 while (it.hasNext()) { 17027 final PreferredActivity pa = it.next(); 17028 if (packageName == null 17029 || (pa.mPref.mComponent.getPackageName().equals(packageName) 17030 && pa.mPref.mAlways)) { 17031 if (outFilters != null) { 17032 outFilters.add(new IntentFilter(pa)); 17033 } 17034 if (outActivities != null) { 17035 outActivities.add(pa.mPref.mComponent); 17036 } 17037 } 17038 } 17039 } 17040 } 17041 17042 return num; 17043 } 17044 17045 @Override 17046 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 17047 int userId) { 17048 int callingUid = Binder.getCallingUid(); 17049 if (callingUid != Process.SYSTEM_UID) { 17050 throw new SecurityException( 17051 "addPersistentPreferredActivity can only be run by the system"); 17052 } 17053 if (filter.countActions() == 0) { 17054 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 17055 return; 17056 } 17057 synchronized (mPackages) { 17058 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 17059 ":"); 17060 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 17061 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 17062 new PersistentPreferredActivity(filter, activity)); 17063 scheduleWritePackageRestrictionsLocked(userId); 17064 } 17065 } 17066 17067 @Override 17068 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 17069 int callingUid = Binder.getCallingUid(); 17070 if (callingUid != Process.SYSTEM_UID) { 17071 throw new SecurityException( 17072 "clearPackagePersistentPreferredActivities can only be run by the system"); 17073 } 17074 ArrayList<PersistentPreferredActivity> removed = null; 17075 boolean changed = false; 17076 synchronized (mPackages) { 17077 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 17078 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 17079 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 17080 .valueAt(i); 17081 if (userId != thisUserId) { 17082 continue; 17083 } 17084 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 17085 while (it.hasNext()) { 17086 PersistentPreferredActivity ppa = it.next(); 17087 // Mark entry for removal only if it matches the package name. 17088 if (ppa.mComponent.getPackageName().equals(packageName)) { 17089 if (removed == null) { 17090 removed = new ArrayList<PersistentPreferredActivity>(); 17091 } 17092 removed.add(ppa); 17093 } 17094 } 17095 if (removed != null) { 17096 for (int j=0; j<removed.size(); j++) { 17097 PersistentPreferredActivity ppa = removed.get(j); 17098 ppir.removeFilter(ppa); 17099 } 17100 changed = true; 17101 } 17102 } 17103 17104 if (changed) { 17105 scheduleWritePackageRestrictionsLocked(userId); 17106 } 17107 } 17108 } 17109 17110 /** 17111 * Common machinery for picking apart a restored XML blob and passing 17112 * it to a caller-supplied functor to be applied to the running system. 17113 */ 17114 private void restoreFromXml(XmlPullParser parser, int userId, 17115 String expectedStartTag, BlobXmlRestorer functor) 17116 throws IOException, XmlPullParserException { 17117 int type; 17118 while ((type = parser.next()) != XmlPullParser.START_TAG 17119 && type != XmlPullParser.END_DOCUMENT) { 17120 } 17121 if (type != XmlPullParser.START_TAG) { 17122 // oops didn't find a start tag?! 17123 if (DEBUG_BACKUP) { 17124 Slog.e(TAG, "Didn't find start tag during restore"); 17125 } 17126 return; 17127 } 17128Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 17129 // this is supposed to be TAG_PREFERRED_BACKUP 17130 if (!expectedStartTag.equals(parser.getName())) { 17131 if (DEBUG_BACKUP) { 17132 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 17133 } 17134 return; 17135 } 17136 17137 // skip interfering stuff, then we're aligned with the backing implementation 17138 while ((type = parser.next()) == XmlPullParser.TEXT) { } 17139Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 17140 functor.apply(parser, userId); 17141 } 17142 17143 private interface BlobXmlRestorer { 17144 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 17145 } 17146 17147 /** 17148 * Non-Binder method, support for the backup/restore mechanism: write the 17149 * full set of preferred activities in its canonical XML format. Returns the 17150 * XML output as a byte array, or null if there is none. 17151 */ 17152 @Override 17153 public byte[] getPreferredActivityBackup(int userId) { 17154 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17155 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 17156 } 17157 17158 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17159 try { 17160 final XmlSerializer serializer = new FastXmlSerializer(); 17161 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17162 serializer.startDocument(null, true); 17163 serializer.startTag(null, TAG_PREFERRED_BACKUP); 17164 17165 synchronized (mPackages) { 17166 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 17167 } 17168 17169 serializer.endTag(null, TAG_PREFERRED_BACKUP); 17170 serializer.endDocument(); 17171 serializer.flush(); 17172 } catch (Exception e) { 17173 if (DEBUG_BACKUP) { 17174 Slog.e(TAG, "Unable to write preferred activities for backup", e); 17175 } 17176 return null; 17177 } 17178 17179 return dataStream.toByteArray(); 17180 } 17181 17182 @Override 17183 public void restorePreferredActivities(byte[] backup, int userId) { 17184 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17185 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17186 } 17187 17188 try { 17189 final XmlPullParser parser = Xml.newPullParser(); 17190 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17191 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 17192 new BlobXmlRestorer() { 17193 @Override 17194 public void apply(XmlPullParser parser, int userId) 17195 throws XmlPullParserException, IOException { 17196 synchronized (mPackages) { 17197 mSettings.readPreferredActivitiesLPw(parser, userId); 17198 } 17199 } 17200 } ); 17201 } catch (Exception e) { 17202 if (DEBUG_BACKUP) { 17203 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17204 } 17205 } 17206 } 17207 17208 /** 17209 * Non-Binder method, support for the backup/restore mechanism: write the 17210 * default browser (etc) settings in its canonical XML format. Returns the default 17211 * browser XML representation as a byte array, or null if there is none. 17212 */ 17213 @Override 17214 public byte[] getDefaultAppsBackup(int userId) { 17215 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17216 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 17217 } 17218 17219 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17220 try { 17221 final XmlSerializer serializer = new FastXmlSerializer(); 17222 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17223 serializer.startDocument(null, true); 17224 serializer.startTag(null, TAG_DEFAULT_APPS); 17225 17226 synchronized (mPackages) { 17227 mSettings.writeDefaultAppsLPr(serializer, userId); 17228 } 17229 17230 serializer.endTag(null, TAG_DEFAULT_APPS); 17231 serializer.endDocument(); 17232 serializer.flush(); 17233 } catch (Exception e) { 17234 if (DEBUG_BACKUP) { 17235 Slog.e(TAG, "Unable to write default apps for backup", e); 17236 } 17237 return null; 17238 } 17239 17240 return dataStream.toByteArray(); 17241 } 17242 17243 @Override 17244 public void restoreDefaultApps(byte[] backup, int userId) { 17245 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17246 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17247 } 17248 17249 try { 17250 final XmlPullParser parser = Xml.newPullParser(); 17251 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17252 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17253 new BlobXmlRestorer() { 17254 @Override 17255 public void apply(XmlPullParser parser, int userId) 17256 throws XmlPullParserException, IOException { 17257 synchronized (mPackages) { 17258 mSettings.readDefaultAppsLPw(parser, userId); 17259 } 17260 } 17261 } ); 17262 } catch (Exception e) { 17263 if (DEBUG_BACKUP) { 17264 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17265 } 17266 } 17267 } 17268 17269 @Override 17270 public byte[] getIntentFilterVerificationBackup(int userId) { 17271 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17272 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17273 } 17274 17275 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17276 try { 17277 final XmlSerializer serializer = new FastXmlSerializer(); 17278 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17279 serializer.startDocument(null, true); 17280 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17281 17282 synchronized (mPackages) { 17283 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17284 } 17285 17286 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17287 serializer.endDocument(); 17288 serializer.flush(); 17289 } catch (Exception e) { 17290 if (DEBUG_BACKUP) { 17291 Slog.e(TAG, "Unable to write default apps for backup", e); 17292 } 17293 return null; 17294 } 17295 17296 return dataStream.toByteArray(); 17297 } 17298 17299 @Override 17300 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17301 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17302 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17303 } 17304 17305 try { 17306 final XmlPullParser parser = Xml.newPullParser(); 17307 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17308 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17309 new BlobXmlRestorer() { 17310 @Override 17311 public void apply(XmlPullParser parser, int userId) 17312 throws XmlPullParserException, IOException { 17313 synchronized (mPackages) { 17314 mSettings.readAllDomainVerificationsLPr(parser, userId); 17315 mSettings.writeLPr(); 17316 } 17317 } 17318 } ); 17319 } catch (Exception e) { 17320 if (DEBUG_BACKUP) { 17321 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17322 } 17323 } 17324 } 17325 17326 @Override 17327 public byte[] getPermissionGrantBackup(int userId) { 17328 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17329 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17330 } 17331 17332 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17333 try { 17334 final XmlSerializer serializer = new FastXmlSerializer(); 17335 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17336 serializer.startDocument(null, true); 17337 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17338 17339 synchronized (mPackages) { 17340 serializeRuntimePermissionGrantsLPr(serializer, userId); 17341 } 17342 17343 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17344 serializer.endDocument(); 17345 serializer.flush(); 17346 } catch (Exception e) { 17347 if (DEBUG_BACKUP) { 17348 Slog.e(TAG, "Unable to write default apps for backup", e); 17349 } 17350 return null; 17351 } 17352 17353 return dataStream.toByteArray(); 17354 } 17355 17356 @Override 17357 public void restorePermissionGrants(byte[] backup, int userId) { 17358 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17359 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17360 } 17361 17362 try { 17363 final XmlPullParser parser = Xml.newPullParser(); 17364 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17365 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17366 new BlobXmlRestorer() { 17367 @Override 17368 public void apply(XmlPullParser parser, int userId) 17369 throws XmlPullParserException, IOException { 17370 synchronized (mPackages) { 17371 processRestoredPermissionGrantsLPr(parser, userId); 17372 } 17373 } 17374 } ); 17375 } catch (Exception e) { 17376 if (DEBUG_BACKUP) { 17377 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17378 } 17379 } 17380 } 17381 17382 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17383 throws IOException { 17384 serializer.startTag(null, TAG_ALL_GRANTS); 17385 17386 final int N = mSettings.mPackages.size(); 17387 for (int i = 0; i < N; i++) { 17388 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17389 boolean pkgGrantsKnown = false; 17390 17391 PermissionsState packagePerms = ps.getPermissionsState(); 17392 17393 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17394 final int grantFlags = state.getFlags(); 17395 // only look at grants that are not system/policy fixed 17396 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17397 final boolean isGranted = state.isGranted(); 17398 // And only back up the user-twiddled state bits 17399 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17400 final String packageName = mSettings.mPackages.keyAt(i); 17401 if (!pkgGrantsKnown) { 17402 serializer.startTag(null, TAG_GRANT); 17403 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17404 pkgGrantsKnown = true; 17405 } 17406 17407 final boolean userSet = 17408 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17409 final boolean userFixed = 17410 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17411 final boolean revoke = 17412 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17413 17414 serializer.startTag(null, TAG_PERMISSION); 17415 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17416 if (isGranted) { 17417 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17418 } 17419 if (userSet) { 17420 serializer.attribute(null, ATTR_USER_SET, "true"); 17421 } 17422 if (userFixed) { 17423 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17424 } 17425 if (revoke) { 17426 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17427 } 17428 serializer.endTag(null, TAG_PERMISSION); 17429 } 17430 } 17431 } 17432 17433 if (pkgGrantsKnown) { 17434 serializer.endTag(null, TAG_GRANT); 17435 } 17436 } 17437 17438 serializer.endTag(null, TAG_ALL_GRANTS); 17439 } 17440 17441 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17442 throws XmlPullParserException, IOException { 17443 String pkgName = null; 17444 int outerDepth = parser.getDepth(); 17445 int type; 17446 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17447 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17448 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17449 continue; 17450 } 17451 17452 final String tagName = parser.getName(); 17453 if (tagName.equals(TAG_GRANT)) { 17454 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17455 if (DEBUG_BACKUP) { 17456 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17457 } 17458 } else if (tagName.equals(TAG_PERMISSION)) { 17459 17460 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17461 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17462 17463 int newFlagSet = 0; 17464 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17465 newFlagSet |= FLAG_PERMISSION_USER_SET; 17466 } 17467 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17468 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17469 } 17470 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17471 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17472 } 17473 if (DEBUG_BACKUP) { 17474 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17475 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17476 } 17477 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17478 if (ps != null) { 17479 // Already installed so we apply the grant immediately 17480 if (DEBUG_BACKUP) { 17481 Slog.v(TAG, " + already installed; applying"); 17482 } 17483 PermissionsState perms = ps.getPermissionsState(); 17484 BasePermission bp = mSettings.mPermissions.get(permName); 17485 if (bp != null) { 17486 if (isGranted) { 17487 perms.grantRuntimePermission(bp, userId); 17488 } 17489 if (newFlagSet != 0) { 17490 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17491 } 17492 } 17493 } else { 17494 // Need to wait for post-restore install to apply the grant 17495 if (DEBUG_BACKUP) { 17496 Slog.v(TAG, " - not yet installed; saving for later"); 17497 } 17498 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17499 isGranted, newFlagSet, userId); 17500 } 17501 } else { 17502 PackageManagerService.reportSettingsProblem(Log.WARN, 17503 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17504 XmlUtils.skipCurrentTag(parser); 17505 } 17506 } 17507 17508 scheduleWriteSettingsLocked(); 17509 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17510 } 17511 17512 @Override 17513 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17514 int sourceUserId, int targetUserId, int flags) { 17515 mContext.enforceCallingOrSelfPermission( 17516 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17517 int callingUid = Binder.getCallingUid(); 17518 enforceOwnerRights(ownerPackage, callingUid); 17519 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17520 if (intentFilter.countActions() == 0) { 17521 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17522 return; 17523 } 17524 synchronized (mPackages) { 17525 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17526 ownerPackage, targetUserId, flags); 17527 CrossProfileIntentResolver resolver = 17528 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17529 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17530 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17531 if (existing != null) { 17532 int size = existing.size(); 17533 for (int i = 0; i < size; i++) { 17534 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17535 return; 17536 } 17537 } 17538 } 17539 resolver.addFilter(newFilter); 17540 scheduleWritePackageRestrictionsLocked(sourceUserId); 17541 } 17542 } 17543 17544 @Override 17545 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17546 mContext.enforceCallingOrSelfPermission( 17547 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17548 int callingUid = Binder.getCallingUid(); 17549 enforceOwnerRights(ownerPackage, callingUid); 17550 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17551 synchronized (mPackages) { 17552 CrossProfileIntentResolver resolver = 17553 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17554 ArraySet<CrossProfileIntentFilter> set = 17555 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17556 for (CrossProfileIntentFilter filter : set) { 17557 if (filter.getOwnerPackage().equals(ownerPackage)) { 17558 resolver.removeFilter(filter); 17559 } 17560 } 17561 scheduleWritePackageRestrictionsLocked(sourceUserId); 17562 } 17563 } 17564 17565 // Enforcing that callingUid is owning pkg on userId 17566 private void enforceOwnerRights(String pkg, int callingUid) { 17567 // The system owns everything. 17568 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17569 return; 17570 } 17571 int callingUserId = UserHandle.getUserId(callingUid); 17572 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17573 if (pi == null) { 17574 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17575 + callingUserId); 17576 } 17577 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17578 throw new SecurityException("Calling uid " + callingUid 17579 + " does not own package " + pkg); 17580 } 17581 } 17582 17583 @Override 17584 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17585 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17586 } 17587 17588 private Intent getHomeIntent() { 17589 Intent intent = new Intent(Intent.ACTION_MAIN); 17590 intent.addCategory(Intent.CATEGORY_HOME); 17591 return intent; 17592 } 17593 17594 private IntentFilter getHomeFilter() { 17595 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17596 filter.addCategory(Intent.CATEGORY_HOME); 17597 filter.addCategory(Intent.CATEGORY_DEFAULT); 17598 return filter; 17599 } 17600 17601 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17602 int userId) { 17603 Intent intent = getHomeIntent(); 17604 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17605 PackageManager.GET_META_DATA, userId); 17606 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17607 true, false, false, userId); 17608 17609 allHomeCandidates.clear(); 17610 if (list != null) { 17611 for (ResolveInfo ri : list) { 17612 allHomeCandidates.add(ri); 17613 } 17614 } 17615 return (preferred == null || preferred.activityInfo == null) 17616 ? null 17617 : new ComponentName(preferred.activityInfo.packageName, 17618 preferred.activityInfo.name); 17619 } 17620 17621 @Override 17622 public void setHomeActivity(ComponentName comp, int userId) { 17623 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17624 getHomeActivitiesAsUser(homeActivities, userId); 17625 17626 boolean found = false; 17627 17628 final int size = homeActivities.size(); 17629 final ComponentName[] set = new ComponentName[size]; 17630 for (int i = 0; i < size; i++) { 17631 final ResolveInfo candidate = homeActivities.get(i); 17632 final ActivityInfo info = candidate.activityInfo; 17633 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17634 set[i] = activityName; 17635 if (!found && activityName.equals(comp)) { 17636 found = true; 17637 } 17638 } 17639 if (!found) { 17640 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17641 + userId); 17642 } 17643 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17644 set, comp, userId); 17645 } 17646 17647 private @Nullable String getSetupWizardPackageName() { 17648 final Intent intent = new Intent(Intent.ACTION_MAIN); 17649 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17650 17651 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17652 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17653 | MATCH_DISABLED_COMPONENTS, 17654 UserHandle.myUserId()); 17655 if (matches.size() == 1) { 17656 return matches.get(0).getComponentInfo().packageName; 17657 } else { 17658 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17659 + ": matches=" + matches); 17660 return null; 17661 } 17662 } 17663 17664 @Override 17665 public void setApplicationEnabledSetting(String appPackageName, 17666 int newState, int flags, int userId, String callingPackage) { 17667 if (!sUserManager.exists(userId)) return; 17668 if (callingPackage == null) { 17669 callingPackage = Integer.toString(Binder.getCallingUid()); 17670 } 17671 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17672 } 17673 17674 @Override 17675 public void setComponentEnabledSetting(ComponentName componentName, 17676 int newState, int flags, int userId) { 17677 if (!sUserManager.exists(userId)) return; 17678 setEnabledSetting(componentName.getPackageName(), 17679 componentName.getClassName(), newState, flags, userId, null); 17680 } 17681 17682 private void setEnabledSetting(final String packageName, String className, int newState, 17683 final int flags, int userId, String callingPackage) { 17684 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17685 || newState == COMPONENT_ENABLED_STATE_ENABLED 17686 || newState == COMPONENT_ENABLED_STATE_DISABLED 17687 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17688 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17689 throw new IllegalArgumentException("Invalid new component state: " 17690 + newState); 17691 } 17692 PackageSetting pkgSetting; 17693 final int uid = Binder.getCallingUid(); 17694 final int permission; 17695 if (uid == Process.SYSTEM_UID) { 17696 permission = PackageManager.PERMISSION_GRANTED; 17697 } else { 17698 permission = mContext.checkCallingOrSelfPermission( 17699 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17700 } 17701 enforceCrossUserPermission(uid, userId, 17702 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17703 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17704 boolean sendNow = false; 17705 boolean isApp = (className == null); 17706 String componentName = isApp ? packageName : className; 17707 int packageUid = -1; 17708 ArrayList<String> components; 17709 17710 // writer 17711 synchronized (mPackages) { 17712 pkgSetting = mSettings.mPackages.get(packageName); 17713 if (pkgSetting == null) { 17714 if (className == null) { 17715 throw new IllegalArgumentException("Unknown package: " + packageName); 17716 } 17717 throw new IllegalArgumentException( 17718 "Unknown component: " + packageName + "/" + className); 17719 } 17720 } 17721 17722 // Limit who can change which apps 17723 if (!UserHandle.isSameApp(uid, pkgSetting.appId)) { 17724 // Don't allow apps that don't have permission to modify other apps 17725 if (!allowedByPermission) { 17726 throw new SecurityException( 17727 "Permission Denial: attempt to change component state from pid=" 17728 + Binder.getCallingPid() 17729 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17730 } 17731 // Don't allow changing profile and device owners. Calling into DPMS, so no locking. 17732 final DevicePolicyManagerInternal dpmi = LocalServices 17733 .getService(DevicePolicyManagerInternal.class); 17734 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 17735 throw new SecurityException("Cannot disable a device owner or a profile owner"); 17736 } 17737 } 17738 17739 synchronized (mPackages) { 17740 if (uid == Process.SHELL_UID) { 17741 // Shell can only change whole packages between ENABLED and DISABLED_USER states 17742 int oldState = pkgSetting.getEnabled(userId); 17743 if (className == null 17744 && 17745 (oldState == COMPONENT_ENABLED_STATE_DISABLED_USER 17746 || oldState == COMPONENT_ENABLED_STATE_DEFAULT 17747 || oldState == COMPONENT_ENABLED_STATE_ENABLED) 17748 && 17749 (newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17750 || newState == COMPONENT_ENABLED_STATE_DEFAULT 17751 || newState == COMPONENT_ENABLED_STATE_ENABLED)) { 17752 // ok 17753 } else { 17754 throw new SecurityException( 17755 "Shell cannot change component state for " + packageName + "/" 17756 + className + " to " + newState); 17757 } 17758 } 17759 if (className == null) { 17760 // We're dealing with an application/package level state change 17761 if (pkgSetting.getEnabled(userId) == newState) { 17762 // Nothing to do 17763 return; 17764 } 17765 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17766 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17767 // Don't care about who enables an app. 17768 callingPackage = null; 17769 } 17770 pkgSetting.setEnabled(newState, userId, callingPackage); 17771 // pkgSetting.pkg.mSetEnabled = newState; 17772 } else { 17773 // We're dealing with a component level state change 17774 // First, verify that this is a valid class name. 17775 PackageParser.Package pkg = pkgSetting.pkg; 17776 if (pkg == null || !pkg.hasComponentClassName(className)) { 17777 if (pkg != null && 17778 pkg.applicationInfo.targetSdkVersion >= 17779 Build.VERSION_CODES.JELLY_BEAN) { 17780 throw new IllegalArgumentException("Component class " + className 17781 + " does not exist in " + packageName); 17782 } else { 17783 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17784 + className + " does not exist in " + packageName); 17785 } 17786 } 17787 switch (newState) { 17788 case COMPONENT_ENABLED_STATE_ENABLED: 17789 if (!pkgSetting.enableComponentLPw(className, userId)) { 17790 return; 17791 } 17792 break; 17793 case COMPONENT_ENABLED_STATE_DISABLED: 17794 if (!pkgSetting.disableComponentLPw(className, userId)) { 17795 return; 17796 } 17797 break; 17798 case COMPONENT_ENABLED_STATE_DEFAULT: 17799 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17800 return; 17801 } 17802 break; 17803 default: 17804 Slog.e(TAG, "Invalid new component state: " + newState); 17805 return; 17806 } 17807 } 17808 scheduleWritePackageRestrictionsLocked(userId); 17809 components = mPendingBroadcasts.get(userId, packageName); 17810 final boolean newPackage = components == null; 17811 if (newPackage) { 17812 components = new ArrayList<String>(); 17813 } 17814 if (!components.contains(componentName)) { 17815 components.add(componentName); 17816 } 17817 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17818 sendNow = true; 17819 // Purge entry from pending broadcast list if another one exists already 17820 // since we are sending one right away. 17821 mPendingBroadcasts.remove(userId, packageName); 17822 } else { 17823 if (newPackage) { 17824 mPendingBroadcasts.put(userId, packageName, components); 17825 } 17826 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17827 // Schedule a message 17828 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17829 } 17830 } 17831 } 17832 17833 long callingId = Binder.clearCallingIdentity(); 17834 try { 17835 if (sendNow) { 17836 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17837 sendPackageChangedBroadcast(packageName, 17838 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17839 } 17840 } finally { 17841 Binder.restoreCallingIdentity(callingId); 17842 } 17843 } 17844 17845 @Override 17846 public void flushPackageRestrictionsAsUser(int userId) { 17847 if (!sUserManager.exists(userId)) { 17848 return; 17849 } 17850 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17851 false /* checkShell */, "flushPackageRestrictions"); 17852 synchronized (mPackages) { 17853 mSettings.writePackageRestrictionsLPr(userId); 17854 mDirtyUsers.remove(userId); 17855 if (mDirtyUsers.isEmpty()) { 17856 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17857 } 17858 } 17859 } 17860 17861 private void sendPackageChangedBroadcast(String packageName, 17862 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17863 if (DEBUG_INSTALL) 17864 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17865 + componentNames); 17866 Bundle extras = new Bundle(4); 17867 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17868 String nameList[] = new String[componentNames.size()]; 17869 componentNames.toArray(nameList); 17870 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17871 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17872 extras.putInt(Intent.EXTRA_UID, packageUid); 17873 // If this is not reporting a change of the overall package, then only send it 17874 // to registered receivers. We don't want to launch a swath of apps for every 17875 // little component state change. 17876 final int flags = !componentNames.contains(packageName) 17877 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17878 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17879 new int[] {UserHandle.getUserId(packageUid)}); 17880 } 17881 17882 @Override 17883 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17884 if (!sUserManager.exists(userId)) return; 17885 final int uid = Binder.getCallingUid(); 17886 final int permission = mContext.checkCallingOrSelfPermission( 17887 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17888 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17889 enforceCrossUserPermission(uid, userId, 17890 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17891 // writer 17892 synchronized (mPackages) { 17893 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17894 allowedByPermission, uid, userId)) { 17895 scheduleWritePackageRestrictionsLocked(userId); 17896 } 17897 } 17898 } 17899 17900 @Override 17901 public String getInstallerPackageName(String packageName) { 17902 // reader 17903 synchronized (mPackages) { 17904 return mSettings.getInstallerPackageNameLPr(packageName); 17905 } 17906 } 17907 17908 public boolean isOrphaned(String packageName) { 17909 // reader 17910 synchronized (mPackages) { 17911 return mSettings.isOrphaned(packageName); 17912 } 17913 } 17914 17915 @Override 17916 public int getApplicationEnabledSetting(String packageName, int userId) { 17917 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17918 int uid = Binder.getCallingUid(); 17919 enforceCrossUserPermission(uid, userId, 17920 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17921 // reader 17922 synchronized (mPackages) { 17923 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17924 } 17925 } 17926 17927 @Override 17928 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17929 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17930 int uid = Binder.getCallingUid(); 17931 enforceCrossUserPermission(uid, userId, 17932 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17933 // reader 17934 synchronized (mPackages) { 17935 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17936 } 17937 } 17938 17939 @Override 17940 public void enterSafeMode() { 17941 enforceSystemOrRoot("Only the system can request entering safe mode"); 17942 17943 if (!mSystemReady) { 17944 mSafeMode = true; 17945 } 17946 } 17947 17948 @Override 17949 public void systemReady() { 17950 mSystemReady = true; 17951 17952 // Read the compatibilty setting when the system is ready. 17953 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17954 mContext.getContentResolver(), 17955 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17956 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17957 if (DEBUG_SETTINGS) { 17958 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17959 } 17960 17961 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17962 17963 synchronized (mPackages) { 17964 // Verify that all of the preferred activity components actually 17965 // exist. It is possible for applications to be updated and at 17966 // that point remove a previously declared activity component that 17967 // had been set as a preferred activity. We try to clean this up 17968 // the next time we encounter that preferred activity, but it is 17969 // possible for the user flow to never be able to return to that 17970 // situation so here we do a sanity check to make sure we haven't 17971 // left any junk around. 17972 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17973 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17974 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17975 removed.clear(); 17976 for (PreferredActivity pa : pir.filterSet()) { 17977 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17978 removed.add(pa); 17979 } 17980 } 17981 if (removed.size() > 0) { 17982 for (int r=0; r<removed.size(); r++) { 17983 PreferredActivity pa = removed.get(r); 17984 Slog.w(TAG, "Removing dangling preferred activity: " 17985 + pa.mPref.mComponent); 17986 pir.removeFilter(pa); 17987 } 17988 mSettings.writePackageRestrictionsLPr( 17989 mSettings.mPreferredActivities.keyAt(i)); 17990 } 17991 } 17992 17993 for (int userId : UserManagerService.getInstance().getUserIds()) { 17994 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17995 grantPermissionsUserIds = ArrayUtils.appendInt( 17996 grantPermissionsUserIds, userId); 17997 } 17998 } 17999 } 18000 sUserManager.systemReady(); 18001 18002 // If we upgraded grant all default permissions before kicking off. 18003 for (int userId : grantPermissionsUserIds) { 18004 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 18005 } 18006 18007 // Kick off any messages waiting for system ready 18008 if (mPostSystemReadyMessages != null) { 18009 for (Message msg : mPostSystemReadyMessages) { 18010 msg.sendToTarget(); 18011 } 18012 mPostSystemReadyMessages = null; 18013 } 18014 18015 // Watch for external volumes that come and go over time 18016 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18017 storage.registerListener(mStorageListener); 18018 18019 mInstallerService.systemReady(); 18020 mPackageDexOptimizer.systemReady(); 18021 18022 MountServiceInternal mountServiceInternal = LocalServices.getService( 18023 MountServiceInternal.class); 18024 mountServiceInternal.addExternalStoragePolicy( 18025 new MountServiceInternal.ExternalStorageMountPolicy() { 18026 @Override 18027 public int getMountMode(int uid, String packageName) { 18028 if (Process.isIsolated(uid)) { 18029 return Zygote.MOUNT_EXTERNAL_NONE; 18030 } 18031 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 18032 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18033 } 18034 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18035 return Zygote.MOUNT_EXTERNAL_DEFAULT; 18036 } 18037 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 18038 return Zygote.MOUNT_EXTERNAL_READ; 18039 } 18040 return Zygote.MOUNT_EXTERNAL_WRITE; 18041 } 18042 18043 @Override 18044 public boolean hasExternalStorage(int uid, String packageName) { 18045 return true; 18046 } 18047 }); 18048 18049 // Now that we're mostly running, clean up stale users and apps 18050 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 18051 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 18052 } 18053 18054 @Override 18055 public boolean isSafeMode() { 18056 return mSafeMode; 18057 } 18058 18059 @Override 18060 public boolean hasSystemUidErrors() { 18061 return mHasSystemUidErrors; 18062 } 18063 18064 static String arrayToString(int[] array) { 18065 StringBuffer buf = new StringBuffer(128); 18066 buf.append('['); 18067 if (array != null) { 18068 for (int i=0; i<array.length; i++) { 18069 if (i > 0) buf.append(", "); 18070 buf.append(array[i]); 18071 } 18072 } 18073 buf.append(']'); 18074 return buf.toString(); 18075 } 18076 18077 static class DumpState { 18078 public static final int DUMP_LIBS = 1 << 0; 18079 public static final int DUMP_FEATURES = 1 << 1; 18080 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 18081 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 18082 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 18083 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 18084 public static final int DUMP_PERMISSIONS = 1 << 6; 18085 public static final int DUMP_PACKAGES = 1 << 7; 18086 public static final int DUMP_SHARED_USERS = 1 << 8; 18087 public static final int DUMP_MESSAGES = 1 << 9; 18088 public static final int DUMP_PROVIDERS = 1 << 10; 18089 public static final int DUMP_VERIFIERS = 1 << 11; 18090 public static final int DUMP_PREFERRED = 1 << 12; 18091 public static final int DUMP_PREFERRED_XML = 1 << 13; 18092 public static final int DUMP_KEYSETS = 1 << 14; 18093 public static final int DUMP_VERSION = 1 << 15; 18094 public static final int DUMP_INSTALLS = 1 << 16; 18095 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 18096 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 18097 public static final int DUMP_FROZEN = 1 << 19; 18098 public static final int DUMP_DEXOPT = 1 << 20; 18099 18100 public static final int OPTION_SHOW_FILTERS = 1 << 0; 18101 18102 private int mTypes; 18103 18104 private int mOptions; 18105 18106 private boolean mTitlePrinted; 18107 18108 private SharedUserSetting mSharedUser; 18109 18110 public boolean isDumping(int type) { 18111 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 18112 return true; 18113 } 18114 18115 return (mTypes & type) != 0; 18116 } 18117 18118 public void setDump(int type) { 18119 mTypes |= type; 18120 } 18121 18122 public boolean isOptionEnabled(int option) { 18123 return (mOptions & option) != 0; 18124 } 18125 18126 public void setOptionEnabled(int option) { 18127 mOptions |= option; 18128 } 18129 18130 public boolean onTitlePrinted() { 18131 final boolean printed = mTitlePrinted; 18132 mTitlePrinted = true; 18133 return printed; 18134 } 18135 18136 public boolean getTitlePrinted() { 18137 return mTitlePrinted; 18138 } 18139 18140 public void setTitlePrinted(boolean enabled) { 18141 mTitlePrinted = enabled; 18142 } 18143 18144 public SharedUserSetting getSharedUser() { 18145 return mSharedUser; 18146 } 18147 18148 public void setSharedUser(SharedUserSetting user) { 18149 mSharedUser = user; 18150 } 18151 } 18152 18153 @Override 18154 public void onShellCommand(FileDescriptor in, FileDescriptor out, 18155 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 18156 (new PackageManagerShellCommand(this)).exec( 18157 this, in, out, err, args, resultReceiver); 18158 } 18159 18160 @Override 18161 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 18162 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 18163 != PackageManager.PERMISSION_GRANTED) { 18164 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 18165 + Binder.getCallingPid() 18166 + ", uid=" + Binder.getCallingUid() 18167 + " without permission " 18168 + android.Manifest.permission.DUMP); 18169 return; 18170 } 18171 18172 DumpState dumpState = new DumpState(); 18173 boolean fullPreferred = false; 18174 boolean checkin = false; 18175 18176 String packageName = null; 18177 ArraySet<String> permissionNames = null; 18178 18179 int opti = 0; 18180 while (opti < args.length) { 18181 String opt = args[opti]; 18182 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 18183 break; 18184 } 18185 opti++; 18186 18187 if ("-a".equals(opt)) { 18188 // Right now we only know how to print all. 18189 } else if ("-h".equals(opt)) { 18190 pw.println("Package manager dump options:"); 18191 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 18192 pw.println(" --checkin: dump for a checkin"); 18193 pw.println(" -f: print details of intent filters"); 18194 pw.println(" -h: print this help"); 18195 pw.println(" cmd may be one of:"); 18196 pw.println(" l[ibraries]: list known shared libraries"); 18197 pw.println(" f[eatures]: list device features"); 18198 pw.println(" k[eysets]: print known keysets"); 18199 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 18200 pw.println(" perm[issions]: dump permissions"); 18201 pw.println(" permission [name ...]: dump declaration and use of given permission"); 18202 pw.println(" pref[erred]: print preferred package settings"); 18203 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 18204 pw.println(" prov[iders]: dump content providers"); 18205 pw.println(" p[ackages]: dump installed packages"); 18206 pw.println(" s[hared-users]: dump shared user IDs"); 18207 pw.println(" m[essages]: print collected runtime messages"); 18208 pw.println(" v[erifiers]: print package verifier info"); 18209 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 18210 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 18211 pw.println(" version: print database version info"); 18212 pw.println(" write: write current settings now"); 18213 pw.println(" installs: details about install sessions"); 18214 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 18215 pw.println(" dexopt: dump dexopt state"); 18216 pw.println(" <package.name>: info about given package"); 18217 return; 18218 } else if ("--checkin".equals(opt)) { 18219 checkin = true; 18220 } else if ("-f".equals(opt)) { 18221 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18222 } else { 18223 pw.println("Unknown argument: " + opt + "; use -h for help"); 18224 } 18225 } 18226 18227 // Is the caller requesting to dump a particular piece of data? 18228 if (opti < args.length) { 18229 String cmd = args[opti]; 18230 opti++; 18231 // Is this a package name? 18232 if ("android".equals(cmd) || cmd.contains(".")) { 18233 packageName = cmd; 18234 // When dumping a single package, we always dump all of its 18235 // filter information since the amount of data will be reasonable. 18236 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 18237 } else if ("check-permission".equals(cmd)) { 18238 if (opti >= args.length) { 18239 pw.println("Error: check-permission missing permission argument"); 18240 return; 18241 } 18242 String perm = args[opti]; 18243 opti++; 18244 if (opti >= args.length) { 18245 pw.println("Error: check-permission missing package argument"); 18246 return; 18247 } 18248 String pkg = args[opti]; 18249 opti++; 18250 int user = UserHandle.getUserId(Binder.getCallingUid()); 18251 if (opti < args.length) { 18252 try { 18253 user = Integer.parseInt(args[opti]); 18254 } catch (NumberFormatException e) { 18255 pw.println("Error: check-permission user argument is not a number: " 18256 + args[opti]); 18257 return; 18258 } 18259 } 18260 pw.println(checkPermission(perm, pkg, user)); 18261 return; 18262 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 18263 dumpState.setDump(DumpState.DUMP_LIBS); 18264 } else if ("f".equals(cmd) || "features".equals(cmd)) { 18265 dumpState.setDump(DumpState.DUMP_FEATURES); 18266 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18267 if (opti >= args.length) { 18268 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18269 | DumpState.DUMP_SERVICE_RESOLVERS 18270 | DumpState.DUMP_RECEIVER_RESOLVERS 18271 | DumpState.DUMP_CONTENT_RESOLVERS); 18272 } else { 18273 while (opti < args.length) { 18274 String name = args[opti]; 18275 if ("a".equals(name) || "activity".equals(name)) { 18276 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18277 } else if ("s".equals(name) || "service".equals(name)) { 18278 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18279 } else if ("r".equals(name) || "receiver".equals(name)) { 18280 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18281 } else if ("c".equals(name) || "content".equals(name)) { 18282 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18283 } else { 18284 pw.println("Error: unknown resolver table type: " + name); 18285 return; 18286 } 18287 opti++; 18288 } 18289 } 18290 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18291 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18292 } else if ("permission".equals(cmd)) { 18293 if (opti >= args.length) { 18294 pw.println("Error: permission requires permission name"); 18295 return; 18296 } 18297 permissionNames = new ArraySet<>(); 18298 while (opti < args.length) { 18299 permissionNames.add(args[opti]); 18300 opti++; 18301 } 18302 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18303 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18304 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18305 dumpState.setDump(DumpState.DUMP_PREFERRED); 18306 } else if ("preferred-xml".equals(cmd)) { 18307 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18308 if (opti < args.length && "--full".equals(args[opti])) { 18309 fullPreferred = true; 18310 opti++; 18311 } 18312 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18313 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18314 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18315 dumpState.setDump(DumpState.DUMP_PACKAGES); 18316 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18317 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18318 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18319 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18320 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18321 dumpState.setDump(DumpState.DUMP_MESSAGES); 18322 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18323 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18324 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18325 || "intent-filter-verifiers".equals(cmd)) { 18326 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18327 } else if ("version".equals(cmd)) { 18328 dumpState.setDump(DumpState.DUMP_VERSION); 18329 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18330 dumpState.setDump(DumpState.DUMP_KEYSETS); 18331 } else if ("installs".equals(cmd)) { 18332 dumpState.setDump(DumpState.DUMP_INSTALLS); 18333 } else if ("frozen".equals(cmd)) { 18334 dumpState.setDump(DumpState.DUMP_FROZEN); 18335 } else if ("dexopt".equals(cmd)) { 18336 dumpState.setDump(DumpState.DUMP_DEXOPT); 18337 } else if ("write".equals(cmd)) { 18338 synchronized (mPackages) { 18339 mSettings.writeLPr(); 18340 pw.println("Settings written."); 18341 return; 18342 } 18343 } 18344 } 18345 18346 if (checkin) { 18347 pw.println("vers,1"); 18348 } 18349 18350 // reader 18351 synchronized (mPackages) { 18352 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18353 if (!checkin) { 18354 if (dumpState.onTitlePrinted()) 18355 pw.println(); 18356 pw.println("Database versions:"); 18357 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18358 } 18359 } 18360 18361 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18362 if (!checkin) { 18363 if (dumpState.onTitlePrinted()) 18364 pw.println(); 18365 pw.println("Verifiers:"); 18366 pw.print(" Required: "); 18367 pw.print(mRequiredVerifierPackage); 18368 pw.print(" (uid="); 18369 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18370 UserHandle.USER_SYSTEM)); 18371 pw.println(")"); 18372 } else if (mRequiredVerifierPackage != null) { 18373 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18374 pw.print(","); 18375 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18376 UserHandle.USER_SYSTEM)); 18377 } 18378 } 18379 18380 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18381 packageName == null) { 18382 if (mIntentFilterVerifierComponent != null) { 18383 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18384 if (!checkin) { 18385 if (dumpState.onTitlePrinted()) 18386 pw.println(); 18387 pw.println("Intent Filter Verifier:"); 18388 pw.print(" Using: "); 18389 pw.print(verifierPackageName); 18390 pw.print(" (uid="); 18391 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18392 UserHandle.USER_SYSTEM)); 18393 pw.println(")"); 18394 } else if (verifierPackageName != null) { 18395 pw.print("ifv,"); pw.print(verifierPackageName); 18396 pw.print(","); 18397 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18398 UserHandle.USER_SYSTEM)); 18399 } 18400 } else { 18401 pw.println(); 18402 pw.println("No Intent Filter Verifier available!"); 18403 } 18404 } 18405 18406 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18407 boolean printedHeader = false; 18408 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18409 while (it.hasNext()) { 18410 String name = it.next(); 18411 SharedLibraryEntry ent = mSharedLibraries.get(name); 18412 if (!checkin) { 18413 if (!printedHeader) { 18414 if (dumpState.onTitlePrinted()) 18415 pw.println(); 18416 pw.println("Libraries:"); 18417 printedHeader = true; 18418 } 18419 pw.print(" "); 18420 } else { 18421 pw.print("lib,"); 18422 } 18423 pw.print(name); 18424 if (!checkin) { 18425 pw.print(" -> "); 18426 } 18427 if (ent.path != null) { 18428 if (!checkin) { 18429 pw.print("(jar) "); 18430 pw.print(ent.path); 18431 } else { 18432 pw.print(",jar,"); 18433 pw.print(ent.path); 18434 } 18435 } else { 18436 if (!checkin) { 18437 pw.print("(apk) "); 18438 pw.print(ent.apk); 18439 } else { 18440 pw.print(",apk,"); 18441 pw.print(ent.apk); 18442 } 18443 } 18444 pw.println(); 18445 } 18446 } 18447 18448 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18449 if (dumpState.onTitlePrinted()) 18450 pw.println(); 18451 if (!checkin) { 18452 pw.println("Features:"); 18453 } 18454 18455 for (FeatureInfo feat : mAvailableFeatures.values()) { 18456 if (checkin) { 18457 pw.print("feat,"); 18458 pw.print(feat.name); 18459 pw.print(","); 18460 pw.println(feat.version); 18461 } else { 18462 pw.print(" "); 18463 pw.print(feat.name); 18464 if (feat.version > 0) { 18465 pw.print(" version="); 18466 pw.print(feat.version); 18467 } 18468 pw.println(); 18469 } 18470 } 18471 } 18472 18473 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18474 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18475 : "Activity Resolver Table:", " ", packageName, 18476 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18477 dumpState.setTitlePrinted(true); 18478 } 18479 } 18480 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18481 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18482 : "Receiver Resolver Table:", " ", packageName, 18483 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18484 dumpState.setTitlePrinted(true); 18485 } 18486 } 18487 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18488 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18489 : "Service Resolver Table:", " ", packageName, 18490 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18491 dumpState.setTitlePrinted(true); 18492 } 18493 } 18494 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18495 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18496 : "Provider Resolver Table:", " ", packageName, 18497 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18498 dumpState.setTitlePrinted(true); 18499 } 18500 } 18501 18502 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18503 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18504 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18505 int user = mSettings.mPreferredActivities.keyAt(i); 18506 if (pir.dump(pw, 18507 dumpState.getTitlePrinted() 18508 ? "\nPreferred Activities User " + user + ":" 18509 : "Preferred Activities User " + user + ":", " ", 18510 packageName, true, false)) { 18511 dumpState.setTitlePrinted(true); 18512 } 18513 } 18514 } 18515 18516 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18517 pw.flush(); 18518 FileOutputStream fout = new FileOutputStream(fd); 18519 BufferedOutputStream str = new BufferedOutputStream(fout); 18520 XmlSerializer serializer = new FastXmlSerializer(); 18521 try { 18522 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18523 serializer.startDocument(null, true); 18524 serializer.setFeature( 18525 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18526 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18527 serializer.endDocument(); 18528 serializer.flush(); 18529 } catch (IllegalArgumentException e) { 18530 pw.println("Failed writing: " + e); 18531 } catch (IllegalStateException e) { 18532 pw.println("Failed writing: " + e); 18533 } catch (IOException e) { 18534 pw.println("Failed writing: " + e); 18535 } 18536 } 18537 18538 if (!checkin 18539 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18540 && packageName == null) { 18541 pw.println(); 18542 int count = mSettings.mPackages.size(); 18543 if (count == 0) { 18544 pw.println("No applications!"); 18545 pw.println(); 18546 } else { 18547 final String prefix = " "; 18548 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18549 if (allPackageSettings.size() == 0) { 18550 pw.println("No domain preferred apps!"); 18551 pw.println(); 18552 } else { 18553 pw.println("App verification status:"); 18554 pw.println(); 18555 count = 0; 18556 for (PackageSetting ps : allPackageSettings) { 18557 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18558 if (ivi == null || ivi.getPackageName() == null) continue; 18559 pw.println(prefix + "Package: " + ivi.getPackageName()); 18560 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18561 pw.println(prefix + "Status: " + ivi.getStatusString()); 18562 pw.println(); 18563 count++; 18564 } 18565 if (count == 0) { 18566 pw.println(prefix + "No app verification established."); 18567 pw.println(); 18568 } 18569 for (int userId : sUserManager.getUserIds()) { 18570 pw.println("App linkages for user " + userId + ":"); 18571 pw.println(); 18572 count = 0; 18573 for (PackageSetting ps : allPackageSettings) { 18574 final long status = ps.getDomainVerificationStatusForUser(userId); 18575 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18576 continue; 18577 } 18578 pw.println(prefix + "Package: " + ps.name); 18579 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18580 String statusStr = IntentFilterVerificationInfo. 18581 getStatusStringFromValue(status); 18582 pw.println(prefix + "Status: " + statusStr); 18583 pw.println(); 18584 count++; 18585 } 18586 if (count == 0) { 18587 pw.println(prefix + "No configured app linkages."); 18588 pw.println(); 18589 } 18590 } 18591 } 18592 } 18593 } 18594 18595 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18596 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18597 if (packageName == null && permissionNames == null) { 18598 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18599 if (iperm == 0) { 18600 if (dumpState.onTitlePrinted()) 18601 pw.println(); 18602 pw.println("AppOp Permissions:"); 18603 } 18604 pw.print(" AppOp Permission "); 18605 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18606 pw.println(":"); 18607 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18608 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18609 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18610 } 18611 } 18612 } 18613 } 18614 18615 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18616 boolean printedSomething = false; 18617 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18618 if (packageName != null && !packageName.equals(p.info.packageName)) { 18619 continue; 18620 } 18621 if (!printedSomething) { 18622 if (dumpState.onTitlePrinted()) 18623 pw.println(); 18624 pw.println("Registered ContentProviders:"); 18625 printedSomething = true; 18626 } 18627 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18628 pw.print(" "); pw.println(p.toString()); 18629 } 18630 printedSomething = false; 18631 for (Map.Entry<String, PackageParser.Provider> entry : 18632 mProvidersByAuthority.entrySet()) { 18633 PackageParser.Provider p = entry.getValue(); 18634 if (packageName != null && !packageName.equals(p.info.packageName)) { 18635 continue; 18636 } 18637 if (!printedSomething) { 18638 if (dumpState.onTitlePrinted()) 18639 pw.println(); 18640 pw.println("ContentProvider Authorities:"); 18641 printedSomething = true; 18642 } 18643 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18644 pw.print(" "); pw.println(p.toString()); 18645 if (p.info != null && p.info.applicationInfo != null) { 18646 final String appInfo = p.info.applicationInfo.toString(); 18647 pw.print(" applicationInfo="); pw.println(appInfo); 18648 } 18649 } 18650 } 18651 18652 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18653 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18654 } 18655 18656 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18657 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18658 } 18659 18660 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18661 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18662 } 18663 18664 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18665 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18666 } 18667 18668 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18669 // XXX should handle packageName != null by dumping only install data that 18670 // the given package is involved with. 18671 if (dumpState.onTitlePrinted()) pw.println(); 18672 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18673 } 18674 18675 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18676 // XXX should handle packageName != null by dumping only install data that 18677 // the given package is involved with. 18678 if (dumpState.onTitlePrinted()) pw.println(); 18679 18680 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18681 ipw.println(); 18682 ipw.println("Frozen packages:"); 18683 ipw.increaseIndent(); 18684 if (mFrozenPackages.size() == 0) { 18685 ipw.println("(none)"); 18686 } else { 18687 for (int i = 0; i < mFrozenPackages.size(); i++) { 18688 ipw.println(mFrozenPackages.valueAt(i)); 18689 } 18690 } 18691 ipw.decreaseIndent(); 18692 } 18693 18694 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18695 if (dumpState.onTitlePrinted()) pw.println(); 18696 dumpDexoptStateLPr(pw, packageName); 18697 } 18698 18699 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18700 if (dumpState.onTitlePrinted()) pw.println(); 18701 mSettings.dumpReadMessagesLPr(pw, dumpState); 18702 18703 pw.println(); 18704 pw.println("Package warning messages:"); 18705 BufferedReader in = null; 18706 String line = null; 18707 try { 18708 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18709 while ((line = in.readLine()) != null) { 18710 if (line.contains("ignored: updated version")) continue; 18711 pw.println(line); 18712 } 18713 } catch (IOException ignored) { 18714 } finally { 18715 IoUtils.closeQuietly(in); 18716 } 18717 } 18718 18719 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18720 BufferedReader in = null; 18721 String line = null; 18722 try { 18723 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18724 while ((line = in.readLine()) != null) { 18725 if (line.contains("ignored: updated version")) continue; 18726 pw.print("msg,"); 18727 pw.println(line); 18728 } 18729 } catch (IOException ignored) { 18730 } finally { 18731 IoUtils.closeQuietly(in); 18732 } 18733 } 18734 } 18735 } 18736 18737 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18738 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18739 ipw.println(); 18740 ipw.println("Dexopt state:"); 18741 ipw.increaseIndent(); 18742 Collection<PackageParser.Package> packages = null; 18743 if (packageName != null) { 18744 PackageParser.Package targetPackage = mPackages.get(packageName); 18745 if (targetPackage != null) { 18746 packages = Collections.singletonList(targetPackage); 18747 } else { 18748 ipw.println("Unable to find package: " + packageName); 18749 return; 18750 } 18751 } else { 18752 packages = mPackages.values(); 18753 } 18754 18755 for (PackageParser.Package pkg : packages) { 18756 ipw.println("[" + pkg.packageName + "]"); 18757 ipw.increaseIndent(); 18758 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18759 ipw.decreaseIndent(); 18760 } 18761 } 18762 18763 private String dumpDomainString(String packageName) { 18764 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18765 .getList(); 18766 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18767 18768 ArraySet<String> result = new ArraySet<>(); 18769 if (iviList.size() > 0) { 18770 for (IntentFilterVerificationInfo ivi : iviList) { 18771 for (String host : ivi.getDomains()) { 18772 result.add(host); 18773 } 18774 } 18775 } 18776 if (filters != null && filters.size() > 0) { 18777 for (IntentFilter filter : filters) { 18778 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18779 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18780 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18781 result.addAll(filter.getHostsList()); 18782 } 18783 } 18784 } 18785 18786 StringBuilder sb = new StringBuilder(result.size() * 16); 18787 for (String domain : result) { 18788 if (sb.length() > 0) sb.append(" "); 18789 sb.append(domain); 18790 } 18791 return sb.toString(); 18792 } 18793 18794 // ------- apps on sdcard specific code ------- 18795 static final boolean DEBUG_SD_INSTALL = false; 18796 18797 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18798 18799 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18800 18801 private boolean mMediaMounted = false; 18802 18803 static String getEncryptKey() { 18804 try { 18805 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18806 SD_ENCRYPTION_KEYSTORE_NAME); 18807 if (sdEncKey == null) { 18808 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18809 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18810 if (sdEncKey == null) { 18811 Slog.e(TAG, "Failed to create encryption keys"); 18812 return null; 18813 } 18814 } 18815 return sdEncKey; 18816 } catch (NoSuchAlgorithmException nsae) { 18817 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18818 return null; 18819 } catch (IOException ioe) { 18820 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18821 return null; 18822 } 18823 } 18824 18825 /* 18826 * Update media status on PackageManager. 18827 */ 18828 @Override 18829 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18830 int callingUid = Binder.getCallingUid(); 18831 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18832 throw new SecurityException("Media status can only be updated by the system"); 18833 } 18834 // reader; this apparently protects mMediaMounted, but should probably 18835 // be a different lock in that case. 18836 synchronized (mPackages) { 18837 Log.i(TAG, "Updating external media status from " 18838 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18839 + (mediaStatus ? "mounted" : "unmounted")); 18840 if (DEBUG_SD_INSTALL) 18841 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18842 + ", mMediaMounted=" + mMediaMounted); 18843 if (mediaStatus == mMediaMounted) { 18844 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18845 : 0, -1); 18846 mHandler.sendMessage(msg); 18847 return; 18848 } 18849 mMediaMounted = mediaStatus; 18850 } 18851 // Queue up an async operation since the package installation may take a 18852 // little while. 18853 mHandler.post(new Runnable() { 18854 public void run() { 18855 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18856 } 18857 }); 18858 } 18859 18860 /** 18861 * Called by MountService when the initial ASECs to scan are available. 18862 * Should block until all the ASEC containers are finished being scanned. 18863 */ 18864 public void scanAvailableAsecs() { 18865 updateExternalMediaStatusInner(true, false, false); 18866 } 18867 18868 /* 18869 * Collect information of applications on external media, map them against 18870 * existing containers and update information based on current mount status. 18871 * Please note that we always have to report status if reportStatus has been 18872 * set to true especially when unloading packages. 18873 */ 18874 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18875 boolean externalStorage) { 18876 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18877 int[] uidArr = EmptyArray.INT; 18878 18879 final String[] list = PackageHelper.getSecureContainerList(); 18880 if (ArrayUtils.isEmpty(list)) { 18881 Log.i(TAG, "No secure containers found"); 18882 } else { 18883 // Process list of secure containers and categorize them 18884 // as active or stale based on their package internal state. 18885 18886 // reader 18887 synchronized (mPackages) { 18888 for (String cid : list) { 18889 // Leave stages untouched for now; installer service owns them 18890 if (PackageInstallerService.isStageName(cid)) continue; 18891 18892 if (DEBUG_SD_INSTALL) 18893 Log.i(TAG, "Processing container " + cid); 18894 String pkgName = getAsecPackageName(cid); 18895 if (pkgName == null) { 18896 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18897 continue; 18898 } 18899 if (DEBUG_SD_INSTALL) 18900 Log.i(TAG, "Looking for pkg : " + pkgName); 18901 18902 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18903 if (ps == null) { 18904 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18905 continue; 18906 } 18907 18908 /* 18909 * Skip packages that are not external if we're unmounting 18910 * external storage. 18911 */ 18912 if (externalStorage && !isMounted && !isExternal(ps)) { 18913 continue; 18914 } 18915 18916 final AsecInstallArgs args = new AsecInstallArgs(cid, 18917 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18918 // The package status is changed only if the code path 18919 // matches between settings and the container id. 18920 if (ps.codePathString != null 18921 && ps.codePathString.startsWith(args.getCodePath())) { 18922 if (DEBUG_SD_INSTALL) { 18923 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18924 + " at code path: " + ps.codePathString); 18925 } 18926 18927 // We do have a valid package installed on sdcard 18928 processCids.put(args, ps.codePathString); 18929 final int uid = ps.appId; 18930 if (uid != -1) { 18931 uidArr = ArrayUtils.appendInt(uidArr, uid); 18932 } 18933 } else { 18934 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18935 + ps.codePathString); 18936 } 18937 } 18938 } 18939 18940 Arrays.sort(uidArr); 18941 } 18942 18943 // Process packages with valid entries. 18944 if (isMounted) { 18945 if (DEBUG_SD_INSTALL) 18946 Log.i(TAG, "Loading packages"); 18947 loadMediaPackages(processCids, uidArr, externalStorage); 18948 startCleaningPackages(); 18949 mInstallerService.onSecureContainersAvailable(); 18950 } else { 18951 if (DEBUG_SD_INSTALL) 18952 Log.i(TAG, "Unloading packages"); 18953 unloadMediaPackages(processCids, uidArr, reportStatus); 18954 } 18955 } 18956 18957 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18958 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18959 final int size = infos.size(); 18960 final String[] packageNames = new String[size]; 18961 final int[] packageUids = new int[size]; 18962 for (int i = 0; i < size; i++) { 18963 final ApplicationInfo info = infos.get(i); 18964 packageNames[i] = info.packageName; 18965 packageUids[i] = info.uid; 18966 } 18967 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18968 finishedReceiver); 18969 } 18970 18971 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18972 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18973 sendResourcesChangedBroadcast(mediaStatus, replacing, 18974 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18975 } 18976 18977 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18978 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18979 int size = pkgList.length; 18980 if (size > 0) { 18981 // Send broadcasts here 18982 Bundle extras = new Bundle(); 18983 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18984 if (uidArr != null) { 18985 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18986 } 18987 if (replacing) { 18988 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18989 } 18990 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18991 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18992 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18993 } 18994 } 18995 18996 /* 18997 * Look at potentially valid container ids from processCids If package 18998 * information doesn't match the one on record or package scanning fails, 18999 * the cid is added to list of removeCids. We currently don't delete stale 19000 * containers. 19001 */ 19002 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 19003 boolean externalStorage) { 19004 ArrayList<String> pkgList = new ArrayList<String>(); 19005 Set<AsecInstallArgs> keys = processCids.keySet(); 19006 19007 for (AsecInstallArgs args : keys) { 19008 String codePath = processCids.get(args); 19009 if (DEBUG_SD_INSTALL) 19010 Log.i(TAG, "Loading container : " + args.cid); 19011 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 19012 try { 19013 // Make sure there are no container errors first. 19014 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 19015 Slog.e(TAG, "Failed to mount cid : " + args.cid 19016 + " when installing from sdcard"); 19017 continue; 19018 } 19019 // Check code path here. 19020 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 19021 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 19022 + " does not match one in settings " + codePath); 19023 continue; 19024 } 19025 // Parse package 19026 int parseFlags = mDefParseFlags; 19027 if (args.isExternalAsec()) { 19028 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 19029 } 19030 if (args.isFwdLocked()) { 19031 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 19032 } 19033 19034 synchronized (mInstallLock) { 19035 PackageParser.Package pkg = null; 19036 try { 19037 // Sadly we don't know the package name yet to freeze it 19038 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 19039 SCAN_IGNORE_FROZEN, 0, null); 19040 } catch (PackageManagerException e) { 19041 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 19042 } 19043 // Scan the package 19044 if (pkg != null) { 19045 /* 19046 * TODO why is the lock being held? doPostInstall is 19047 * called in other places without the lock. This needs 19048 * to be straightened out. 19049 */ 19050 // writer 19051 synchronized (mPackages) { 19052 retCode = PackageManager.INSTALL_SUCCEEDED; 19053 pkgList.add(pkg.packageName); 19054 // Post process args 19055 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 19056 pkg.applicationInfo.uid); 19057 } 19058 } else { 19059 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 19060 } 19061 } 19062 19063 } finally { 19064 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 19065 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 19066 } 19067 } 19068 } 19069 // writer 19070 synchronized (mPackages) { 19071 // If the platform SDK has changed since the last time we booted, 19072 // we need to re-grant app permission to catch any new ones that 19073 // appear. This is really a hack, and means that apps can in some 19074 // cases get permissions that the user didn't initially explicitly 19075 // allow... it would be nice to have some better way to handle 19076 // this situation. 19077 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 19078 : mSettings.getInternalVersion(); 19079 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 19080 : StorageManager.UUID_PRIVATE_INTERNAL; 19081 19082 int updateFlags = UPDATE_PERMISSIONS_ALL; 19083 if (ver.sdkVersion != mSdkVersion) { 19084 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19085 + mSdkVersion + "; regranting permissions for external"); 19086 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19087 } 19088 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19089 19090 // Yay, everything is now upgraded 19091 ver.forceCurrent(); 19092 19093 // can downgrade to reader 19094 // Persist settings 19095 mSettings.writeLPr(); 19096 } 19097 // Send a broadcast to let everyone know we are done processing 19098 if (pkgList.size() > 0) { 19099 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 19100 } 19101 } 19102 19103 /* 19104 * Utility method to unload a list of specified containers 19105 */ 19106 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 19107 // Just unmount all valid containers. 19108 for (AsecInstallArgs arg : cidArgs) { 19109 synchronized (mInstallLock) { 19110 arg.doPostDeleteLI(false); 19111 } 19112 } 19113 } 19114 19115 /* 19116 * Unload packages mounted on external media. This involves deleting package 19117 * data from internal structures, sending broadcasts about disabled packages, 19118 * gc'ing to free up references, unmounting all secure containers 19119 * corresponding to packages on external media, and posting a 19120 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 19121 * that we always have to post this message if status has been requested no 19122 * matter what. 19123 */ 19124 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 19125 final boolean reportStatus) { 19126 if (DEBUG_SD_INSTALL) 19127 Log.i(TAG, "unloading media packages"); 19128 ArrayList<String> pkgList = new ArrayList<String>(); 19129 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 19130 final Set<AsecInstallArgs> keys = processCids.keySet(); 19131 for (AsecInstallArgs args : keys) { 19132 String pkgName = args.getPackageName(); 19133 if (DEBUG_SD_INSTALL) 19134 Log.i(TAG, "Trying to unload pkg : " + pkgName); 19135 // Delete package internally 19136 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19137 synchronized (mInstallLock) { 19138 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19139 final boolean res; 19140 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 19141 "unloadMediaPackages")) { 19142 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 19143 null); 19144 } 19145 if (res) { 19146 pkgList.add(pkgName); 19147 } else { 19148 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 19149 failedList.add(args); 19150 } 19151 } 19152 } 19153 19154 // reader 19155 synchronized (mPackages) { 19156 // We didn't update the settings after removing each package; 19157 // write them now for all packages. 19158 mSettings.writeLPr(); 19159 } 19160 19161 // We have to absolutely send UPDATED_MEDIA_STATUS only 19162 // after confirming that all the receivers processed the ordered 19163 // broadcast when packages get disabled, force a gc to clean things up. 19164 // and unload all the containers. 19165 if (pkgList.size() > 0) { 19166 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 19167 new IIntentReceiver.Stub() { 19168 public void performReceive(Intent intent, int resultCode, String data, 19169 Bundle extras, boolean ordered, boolean sticky, 19170 int sendingUser) throws RemoteException { 19171 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 19172 reportStatus ? 1 : 0, 1, keys); 19173 mHandler.sendMessage(msg); 19174 } 19175 }); 19176 } else { 19177 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 19178 keys); 19179 mHandler.sendMessage(msg); 19180 } 19181 } 19182 19183 private void loadPrivatePackages(final VolumeInfo vol) { 19184 mHandler.post(new Runnable() { 19185 @Override 19186 public void run() { 19187 loadPrivatePackagesInner(vol); 19188 } 19189 }); 19190 } 19191 19192 private void loadPrivatePackagesInner(VolumeInfo vol) { 19193 final String volumeUuid = vol.fsUuid; 19194 if (TextUtils.isEmpty(volumeUuid)) { 19195 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 19196 return; 19197 } 19198 19199 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 19200 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 19201 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 19202 19203 final VersionInfo ver; 19204 final List<PackageSetting> packages; 19205 synchronized (mPackages) { 19206 ver = mSettings.findOrCreateVersion(volumeUuid); 19207 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19208 } 19209 19210 for (PackageSetting ps : packages) { 19211 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 19212 synchronized (mInstallLock) { 19213 final PackageParser.Package pkg; 19214 try { 19215 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 19216 loaded.add(pkg.applicationInfo); 19217 19218 } catch (PackageManagerException e) { 19219 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 19220 } 19221 19222 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 19223 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 19224 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 19225 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 19226 } 19227 } 19228 } 19229 19230 // Reconcile app data for all started/unlocked users 19231 final StorageManager sm = mContext.getSystemService(StorageManager.class); 19232 final UserManager um = mContext.getSystemService(UserManager.class); 19233 UserManagerInternal umInternal = getUserManagerInternal(); 19234 for (UserInfo user : um.getUsers()) { 19235 final int flags; 19236 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19237 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19238 } else if (umInternal.isUserRunning(user.id)) { 19239 flags = StorageManager.FLAG_STORAGE_DE; 19240 } else { 19241 continue; 19242 } 19243 19244 try { 19245 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 19246 synchronized (mInstallLock) { 19247 reconcileAppsDataLI(volumeUuid, user.id, flags); 19248 } 19249 } catch (IllegalStateException e) { 19250 // Device was probably ejected, and we'll process that event momentarily 19251 Slog.w(TAG, "Failed to prepare storage: " + e); 19252 } 19253 } 19254 19255 synchronized (mPackages) { 19256 int updateFlags = UPDATE_PERMISSIONS_ALL; 19257 if (ver.sdkVersion != mSdkVersion) { 19258 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 19259 + mSdkVersion + "; regranting permissions for " + volumeUuid); 19260 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 19261 } 19262 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 19263 19264 // Yay, everything is now upgraded 19265 ver.forceCurrent(); 19266 19267 mSettings.writeLPr(); 19268 } 19269 19270 for (PackageFreezer freezer : freezers) { 19271 freezer.close(); 19272 } 19273 19274 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19275 sendResourcesChangedBroadcast(true, false, loaded, null); 19276 } 19277 19278 private void unloadPrivatePackages(final VolumeInfo vol) { 19279 mHandler.post(new Runnable() { 19280 @Override 19281 public void run() { 19282 unloadPrivatePackagesInner(vol); 19283 } 19284 }); 19285 } 19286 19287 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19288 final String volumeUuid = vol.fsUuid; 19289 if (TextUtils.isEmpty(volumeUuid)) { 19290 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19291 return; 19292 } 19293 19294 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19295 synchronized (mInstallLock) { 19296 synchronized (mPackages) { 19297 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19298 for (PackageSetting ps : packages) { 19299 if (ps.pkg == null) continue; 19300 19301 final ApplicationInfo info = ps.pkg.applicationInfo; 19302 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19303 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19304 19305 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19306 "unloadPrivatePackagesInner")) { 19307 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19308 false, null)) { 19309 unloaded.add(info); 19310 } else { 19311 Slog.w(TAG, "Failed to unload " + ps.codePath); 19312 } 19313 } 19314 19315 // Try very hard to release any references to this package 19316 // so we don't risk the system server being killed due to 19317 // open FDs 19318 AttributeCache.instance().removePackage(ps.name); 19319 } 19320 19321 mSettings.writeLPr(); 19322 } 19323 } 19324 19325 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19326 sendResourcesChangedBroadcast(false, false, unloaded, null); 19327 19328 // Try very hard to release any references to this path so we don't risk 19329 // the system server being killed due to open FDs 19330 ResourcesManager.getInstance().invalidatePath(vol.getPath().getAbsolutePath()); 19331 19332 for (int i = 0; i < 3; i++) { 19333 System.gc(); 19334 System.runFinalization(); 19335 } 19336 } 19337 19338 /** 19339 * Prepare storage areas for given user on all mounted devices. 19340 */ 19341 void prepareUserData(int userId, int userSerial, int flags) { 19342 synchronized (mInstallLock) { 19343 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19344 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19345 final String volumeUuid = vol.getFsUuid(); 19346 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19347 } 19348 } 19349 } 19350 19351 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19352 boolean allowRecover) { 19353 // Prepare storage and verify that serial numbers are consistent; if 19354 // there's a mismatch we need to destroy to avoid leaking data 19355 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19356 try { 19357 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19358 19359 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19360 UserManagerService.enforceSerialNumber( 19361 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19362 } 19363 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19364 UserManagerService.enforceSerialNumber( 19365 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19366 } 19367 19368 synchronized (mInstallLock) { 19369 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19370 } 19371 } catch (Exception e) { 19372 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19373 + " because we failed to prepare: " + e); 19374 destroyUserDataLI(volumeUuid, userId, 19375 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19376 19377 if (allowRecover) { 19378 // Try one last time; if we fail again we're really in trouble 19379 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19380 } 19381 } 19382 } 19383 19384 /** 19385 * Destroy storage areas for given user on all mounted devices. 19386 */ 19387 void destroyUserData(int userId, int flags) { 19388 synchronized (mInstallLock) { 19389 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19390 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19391 final String volumeUuid = vol.getFsUuid(); 19392 destroyUserDataLI(volumeUuid, userId, flags); 19393 } 19394 } 19395 } 19396 19397 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19398 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19399 try { 19400 // Clean up app data, profile data, and media data 19401 mInstaller.destroyUserData(volumeUuid, userId, flags); 19402 19403 // Clean up system data 19404 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19405 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19406 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19407 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19408 } 19409 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19410 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19411 } 19412 } 19413 19414 // Data with special labels is now gone, so finish the job 19415 storage.destroyUserStorage(volumeUuid, userId, flags); 19416 19417 } catch (Exception e) { 19418 logCriticalInfo(Log.WARN, 19419 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19420 } 19421 } 19422 19423 /** 19424 * Examine all users present on given mounted volume, and destroy data 19425 * belonging to users that are no longer valid, or whose user ID has been 19426 * recycled. 19427 */ 19428 private void reconcileUsers(String volumeUuid) { 19429 final List<File> files = new ArrayList<>(); 19430 Collections.addAll(files, FileUtils 19431 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19432 Collections.addAll(files, FileUtils 19433 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19434 for (File file : files) { 19435 if (!file.isDirectory()) continue; 19436 19437 final int userId; 19438 final UserInfo info; 19439 try { 19440 userId = Integer.parseInt(file.getName()); 19441 info = sUserManager.getUserInfo(userId); 19442 } catch (NumberFormatException e) { 19443 Slog.w(TAG, "Invalid user directory " + file); 19444 continue; 19445 } 19446 19447 boolean destroyUser = false; 19448 if (info == null) { 19449 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19450 + " because no matching user was found"); 19451 destroyUser = true; 19452 } else if (!mOnlyCore) { 19453 try { 19454 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19455 } catch (IOException e) { 19456 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19457 + " because we failed to enforce serial number: " + e); 19458 destroyUser = true; 19459 } 19460 } 19461 19462 if (destroyUser) { 19463 synchronized (mInstallLock) { 19464 destroyUserDataLI(volumeUuid, userId, 19465 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19466 } 19467 } 19468 } 19469 } 19470 19471 private void assertPackageKnown(String volumeUuid, String packageName) 19472 throws PackageManagerException { 19473 synchronized (mPackages) { 19474 final PackageSetting ps = mSettings.mPackages.get(packageName); 19475 if (ps == null) { 19476 throw new PackageManagerException("Package " + packageName + " is unknown"); 19477 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19478 throw new PackageManagerException( 19479 "Package " + packageName + " found on unknown volume " + volumeUuid 19480 + "; expected volume " + ps.volumeUuid); 19481 } 19482 } 19483 } 19484 19485 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19486 throws PackageManagerException { 19487 synchronized (mPackages) { 19488 final PackageSetting ps = mSettings.mPackages.get(packageName); 19489 if (ps == null) { 19490 throw new PackageManagerException("Package " + packageName + " is unknown"); 19491 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19492 throw new PackageManagerException( 19493 "Package " + packageName + " found on unknown volume " + volumeUuid 19494 + "; expected volume " + ps.volumeUuid); 19495 } else if (!ps.getInstalled(userId)) { 19496 throw new PackageManagerException( 19497 "Package " + packageName + " not installed for user " + userId); 19498 } 19499 } 19500 } 19501 19502 /** 19503 * Examine all apps present on given mounted volume, and destroy apps that 19504 * aren't expected, either due to uninstallation or reinstallation on 19505 * another volume. 19506 */ 19507 private void reconcileApps(String volumeUuid) { 19508 final File[] files = FileUtils 19509 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19510 for (File file : files) { 19511 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19512 && !PackageInstallerService.isStageName(file.getName()); 19513 if (!isPackage) { 19514 // Ignore entries which are not packages 19515 continue; 19516 } 19517 19518 try { 19519 final PackageLite pkg = PackageParser.parsePackageLite(file, 19520 PackageParser.PARSE_MUST_BE_APK); 19521 assertPackageKnown(volumeUuid, pkg.packageName); 19522 19523 } catch (PackageParserException | PackageManagerException e) { 19524 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19525 synchronized (mInstallLock) { 19526 removeCodePathLI(file); 19527 } 19528 } 19529 } 19530 } 19531 19532 /** 19533 * Reconcile all app data for the given user. 19534 * <p> 19535 * Verifies that directories exist and that ownership and labeling is 19536 * correct for all installed apps on all mounted volumes. 19537 */ 19538 void reconcileAppsData(int userId, int flags) { 19539 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19540 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19541 final String volumeUuid = vol.getFsUuid(); 19542 synchronized (mInstallLock) { 19543 reconcileAppsDataLI(volumeUuid, userId, flags); 19544 } 19545 } 19546 } 19547 19548 /** 19549 * Reconcile all app data on given mounted volume. 19550 * <p> 19551 * Destroys app data that isn't expected, either due to uninstallation or 19552 * reinstallation on another volume. 19553 * <p> 19554 * Verifies that directories exist and that ownership and labeling is 19555 * correct for all installed apps. 19556 */ 19557 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19558 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19559 + Integer.toHexString(flags)); 19560 19561 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19562 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19563 19564 boolean restoreconNeeded = false; 19565 19566 // First look for stale data that doesn't belong, and check if things 19567 // have changed since we did our last restorecon 19568 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19569 if (StorageManager.isFileEncryptedNativeOrEmulated() 19570 && !StorageManager.isUserKeyUnlocked(userId)) { 19571 throw new RuntimeException( 19572 "Yikes, someone asked us to reconcile CE storage while " + userId 19573 + " was still locked; this would have caused massive data loss!"); 19574 } 19575 19576 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19577 19578 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19579 for (File file : files) { 19580 final String packageName = file.getName(); 19581 try { 19582 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19583 } catch (PackageManagerException e) { 19584 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19585 try { 19586 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19587 StorageManager.FLAG_STORAGE_CE, 0); 19588 } catch (InstallerException e2) { 19589 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19590 } 19591 } 19592 } 19593 } 19594 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19595 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19596 19597 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19598 for (File file : files) { 19599 final String packageName = file.getName(); 19600 try { 19601 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19602 } catch (PackageManagerException e) { 19603 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19604 try { 19605 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19606 StorageManager.FLAG_STORAGE_DE, 0); 19607 } catch (InstallerException e2) { 19608 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19609 } 19610 } 19611 } 19612 } 19613 19614 // Ensure that data directories are ready to roll for all packages 19615 // installed for this volume and user 19616 final List<PackageSetting> packages; 19617 synchronized (mPackages) { 19618 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19619 } 19620 int preparedCount = 0; 19621 for (PackageSetting ps : packages) { 19622 final String packageName = ps.name; 19623 if (ps.pkg == null) { 19624 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19625 // TODO: might be due to legacy ASEC apps; we should circle back 19626 // and reconcile again once they're scanned 19627 continue; 19628 } 19629 19630 if (ps.getInstalled(userId)) { 19631 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19632 19633 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19634 // We may have just shuffled around app data directories, so 19635 // prepare them one more time 19636 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19637 } 19638 19639 preparedCount++; 19640 } 19641 } 19642 19643 if (restoreconNeeded) { 19644 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19645 SELinuxMMAC.setRestoreconDone(ceDir); 19646 } 19647 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19648 SELinuxMMAC.setRestoreconDone(deDir); 19649 } 19650 } 19651 19652 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19653 + " packages; restoreconNeeded was " + restoreconNeeded); 19654 } 19655 19656 /** 19657 * Prepare app data for the given app just after it was installed or 19658 * upgraded. This method carefully only touches users that it's installed 19659 * for, and it forces a restorecon to handle any seinfo changes. 19660 * <p> 19661 * Verifies that directories exist and that ownership and labeling is 19662 * correct for all installed apps. If there is an ownership mismatch, it 19663 * will try recovering system apps by wiping data; third-party app data is 19664 * left intact. 19665 * <p> 19666 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19667 */ 19668 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19669 final PackageSetting ps; 19670 synchronized (mPackages) { 19671 ps = mSettings.mPackages.get(pkg.packageName); 19672 mSettings.writeKernelMappingLPr(ps); 19673 } 19674 19675 final UserManager um = mContext.getSystemService(UserManager.class); 19676 UserManagerInternal umInternal = getUserManagerInternal(); 19677 for (UserInfo user : um.getUsers()) { 19678 final int flags; 19679 if (umInternal.isUserUnlockingOrUnlocked(user.id)) { 19680 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19681 } else if (umInternal.isUserRunning(user.id)) { 19682 flags = StorageManager.FLAG_STORAGE_DE; 19683 } else { 19684 continue; 19685 } 19686 19687 if (ps.getInstalled(user.id)) { 19688 // Whenever an app changes, force a restorecon of its data 19689 // TODO: when user data is locked, mark that we're still dirty 19690 prepareAppDataLIF(pkg, user.id, flags, true); 19691 } 19692 } 19693 } 19694 19695 /** 19696 * Prepare app data for the given app. 19697 * <p> 19698 * Verifies that directories exist and that ownership and labeling is 19699 * correct for all installed apps. If there is an ownership mismatch, this 19700 * will try recovering system apps by wiping data; third-party app data is 19701 * left intact. 19702 */ 19703 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19704 boolean restoreconNeeded) { 19705 if (pkg == null) { 19706 Slog.wtf(TAG, "Package was null!", new Throwable()); 19707 return; 19708 } 19709 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19710 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19711 for (int i = 0; i < childCount; i++) { 19712 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19713 } 19714 } 19715 19716 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19717 boolean restoreconNeeded) { 19718 if (DEBUG_APP_DATA) { 19719 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19720 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19721 } 19722 19723 final String volumeUuid = pkg.volumeUuid; 19724 final String packageName = pkg.packageName; 19725 final ApplicationInfo app = pkg.applicationInfo; 19726 final int appId = UserHandle.getAppId(app.uid); 19727 19728 Preconditions.checkNotNull(app.seinfo); 19729 19730 try { 19731 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19732 appId, app.seinfo, app.targetSdkVersion); 19733 } catch (InstallerException e) { 19734 if (app.isSystemApp()) { 19735 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19736 + ", but trying to recover: " + e); 19737 destroyAppDataLeafLIF(pkg, userId, flags); 19738 try { 19739 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19740 appId, app.seinfo, app.targetSdkVersion); 19741 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19742 } catch (InstallerException e2) { 19743 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19744 } 19745 } else { 19746 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19747 } 19748 } 19749 19750 if (restoreconNeeded) { 19751 try { 19752 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19753 app.seinfo); 19754 } catch (InstallerException e) { 19755 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19756 } 19757 } 19758 19759 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19760 try { 19761 // CE storage is unlocked right now, so read out the inode and 19762 // remember for use later when it's locked 19763 // TODO: mark this structure as dirty so we persist it! 19764 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19765 StorageManager.FLAG_STORAGE_CE); 19766 synchronized (mPackages) { 19767 final PackageSetting ps = mSettings.mPackages.get(packageName); 19768 if (ps != null) { 19769 ps.setCeDataInode(ceDataInode, userId); 19770 } 19771 } 19772 } catch (InstallerException e) { 19773 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19774 } 19775 } 19776 19777 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19778 } 19779 19780 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19781 if (pkg == null) { 19782 Slog.wtf(TAG, "Package was null!", new Throwable()); 19783 return; 19784 } 19785 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19786 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19787 for (int i = 0; i < childCount; i++) { 19788 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19789 } 19790 } 19791 19792 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19793 final String volumeUuid = pkg.volumeUuid; 19794 final String packageName = pkg.packageName; 19795 final ApplicationInfo app = pkg.applicationInfo; 19796 19797 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19798 // Create a native library symlink only if we have native libraries 19799 // and if the native libraries are 32 bit libraries. We do not provide 19800 // this symlink for 64 bit libraries. 19801 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19802 final String nativeLibPath = app.nativeLibraryDir; 19803 try { 19804 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19805 nativeLibPath, userId); 19806 } catch (InstallerException e) { 19807 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19808 } 19809 } 19810 } 19811 } 19812 19813 /** 19814 * For system apps on non-FBE devices, this method migrates any existing 19815 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19816 * requested by the app. 19817 */ 19818 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19819 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19820 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19821 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19822 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19823 try { 19824 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19825 storageTarget); 19826 } catch (InstallerException e) { 19827 logCriticalInfo(Log.WARN, 19828 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19829 } 19830 return true; 19831 } else { 19832 return false; 19833 } 19834 } 19835 19836 public PackageFreezer freezePackage(String packageName, String killReason) { 19837 return new PackageFreezer(packageName, killReason); 19838 } 19839 19840 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19841 String killReason) { 19842 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19843 return new PackageFreezer(); 19844 } else { 19845 return freezePackage(packageName, killReason); 19846 } 19847 } 19848 19849 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19850 String killReason) { 19851 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19852 return new PackageFreezer(); 19853 } else { 19854 return freezePackage(packageName, killReason); 19855 } 19856 } 19857 19858 /** 19859 * Class that freezes and kills the given package upon creation, and 19860 * unfreezes it upon closing. This is typically used when doing surgery on 19861 * app code/data to prevent the app from running while you're working. 19862 */ 19863 private class PackageFreezer implements AutoCloseable { 19864 private final String mPackageName; 19865 private final PackageFreezer[] mChildren; 19866 19867 private final boolean mWeFroze; 19868 19869 private final AtomicBoolean mClosed = new AtomicBoolean(); 19870 private final CloseGuard mCloseGuard = CloseGuard.get(); 19871 19872 /** 19873 * Create and return a stub freezer that doesn't actually do anything, 19874 * typically used when someone requested 19875 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19876 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19877 */ 19878 public PackageFreezer() { 19879 mPackageName = null; 19880 mChildren = null; 19881 mWeFroze = false; 19882 mCloseGuard.open("close"); 19883 } 19884 19885 public PackageFreezer(String packageName, String killReason) { 19886 synchronized (mPackages) { 19887 mPackageName = packageName; 19888 mWeFroze = mFrozenPackages.add(mPackageName); 19889 19890 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19891 if (ps != null) { 19892 killApplication(ps.name, ps.appId, killReason); 19893 } 19894 19895 final PackageParser.Package p = mPackages.get(packageName); 19896 if (p != null && p.childPackages != null) { 19897 final int N = p.childPackages.size(); 19898 mChildren = new PackageFreezer[N]; 19899 for (int i = 0; i < N; i++) { 19900 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19901 killReason); 19902 } 19903 } else { 19904 mChildren = null; 19905 } 19906 } 19907 mCloseGuard.open("close"); 19908 } 19909 19910 @Override 19911 protected void finalize() throws Throwable { 19912 try { 19913 mCloseGuard.warnIfOpen(); 19914 close(); 19915 } finally { 19916 super.finalize(); 19917 } 19918 } 19919 19920 @Override 19921 public void close() { 19922 mCloseGuard.close(); 19923 if (mClosed.compareAndSet(false, true)) { 19924 synchronized (mPackages) { 19925 if (mWeFroze) { 19926 mFrozenPackages.remove(mPackageName); 19927 } 19928 19929 if (mChildren != null) { 19930 for (PackageFreezer freezer : mChildren) { 19931 freezer.close(); 19932 } 19933 } 19934 } 19935 } 19936 } 19937 } 19938 19939 /** 19940 * Verify that given package is currently frozen. 19941 */ 19942 private void checkPackageFrozen(String packageName) { 19943 synchronized (mPackages) { 19944 if (!mFrozenPackages.contains(packageName)) { 19945 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19946 } 19947 } 19948 } 19949 19950 @Override 19951 public int movePackage(final String packageName, final String volumeUuid) { 19952 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19953 19954 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19955 final int moveId = mNextMoveId.getAndIncrement(); 19956 mHandler.post(new Runnable() { 19957 @Override 19958 public void run() { 19959 try { 19960 movePackageInternal(packageName, volumeUuid, moveId, user); 19961 } catch (PackageManagerException e) { 19962 Slog.w(TAG, "Failed to move " + packageName, e); 19963 mMoveCallbacks.notifyStatusChanged(moveId, 19964 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19965 } 19966 } 19967 }); 19968 return moveId; 19969 } 19970 19971 private void movePackageInternal(final String packageName, final String volumeUuid, 19972 final int moveId, UserHandle user) throws PackageManagerException { 19973 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19974 final PackageManager pm = mContext.getPackageManager(); 19975 19976 final boolean currentAsec; 19977 final String currentVolumeUuid; 19978 final File codeFile; 19979 final String installerPackageName; 19980 final String packageAbiOverride; 19981 final int appId; 19982 final String seinfo; 19983 final String label; 19984 final int targetSdkVersion; 19985 final PackageFreezer freezer; 19986 final int[] installedUserIds; 19987 19988 // reader 19989 synchronized (mPackages) { 19990 final PackageParser.Package pkg = mPackages.get(packageName); 19991 final PackageSetting ps = mSettings.mPackages.get(packageName); 19992 if (pkg == null || ps == null) { 19993 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19994 } 19995 19996 if (pkg.applicationInfo.isSystemApp()) { 19997 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19998 "Cannot move system application"); 19999 } 20000 20001 if (pkg.applicationInfo.isExternalAsec()) { 20002 currentAsec = true; 20003 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 20004 } else if (pkg.applicationInfo.isForwardLocked()) { 20005 currentAsec = true; 20006 currentVolumeUuid = "forward_locked"; 20007 } else { 20008 currentAsec = false; 20009 currentVolumeUuid = ps.volumeUuid; 20010 20011 final File probe = new File(pkg.codePath); 20012 final File probeOat = new File(probe, "oat"); 20013 if (!probe.isDirectory() || !probeOat.isDirectory()) { 20014 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20015 "Move only supported for modern cluster style installs"); 20016 } 20017 } 20018 20019 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 20020 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20021 "Package already moved to " + volumeUuid); 20022 } 20023 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 20024 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 20025 "Device admin cannot be moved"); 20026 } 20027 20028 if (mFrozenPackages.contains(packageName)) { 20029 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 20030 "Failed to move already frozen package"); 20031 } 20032 20033 codeFile = new File(pkg.codePath); 20034 installerPackageName = ps.installerPackageName; 20035 packageAbiOverride = ps.cpuAbiOverrideString; 20036 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 20037 seinfo = pkg.applicationInfo.seinfo; 20038 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 20039 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 20040 freezer = new PackageFreezer(packageName, "movePackageInternal"); 20041 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 20042 } 20043 20044 final Bundle extras = new Bundle(); 20045 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 20046 extras.putString(Intent.EXTRA_TITLE, label); 20047 mMoveCallbacks.notifyCreated(moveId, extras); 20048 20049 int installFlags; 20050 final boolean moveCompleteApp; 20051 final File measurePath; 20052 20053 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 20054 installFlags = INSTALL_INTERNAL; 20055 moveCompleteApp = !currentAsec; 20056 measurePath = Environment.getDataAppDirectory(volumeUuid); 20057 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 20058 installFlags = INSTALL_EXTERNAL; 20059 moveCompleteApp = false; 20060 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 20061 } else { 20062 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 20063 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 20064 || !volume.isMountedWritable()) { 20065 freezer.close(); 20066 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20067 "Move location not mounted private volume"); 20068 } 20069 20070 Preconditions.checkState(!currentAsec); 20071 20072 installFlags = INSTALL_INTERNAL; 20073 moveCompleteApp = true; 20074 measurePath = Environment.getDataAppDirectory(volumeUuid); 20075 } 20076 20077 final PackageStats stats = new PackageStats(null, -1); 20078 synchronized (mInstaller) { 20079 for (int userId : installedUserIds) { 20080 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 20081 freezer.close(); 20082 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20083 "Failed to measure package size"); 20084 } 20085 } 20086 } 20087 20088 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 20089 + stats.dataSize); 20090 20091 final long startFreeBytes = measurePath.getFreeSpace(); 20092 final long sizeBytes; 20093 if (moveCompleteApp) { 20094 sizeBytes = stats.codeSize + stats.dataSize; 20095 } else { 20096 sizeBytes = stats.codeSize; 20097 } 20098 20099 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 20100 freezer.close(); 20101 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 20102 "Not enough free space to move"); 20103 } 20104 20105 mMoveCallbacks.notifyStatusChanged(moveId, 10); 20106 20107 final CountDownLatch installedLatch = new CountDownLatch(1); 20108 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 20109 @Override 20110 public void onUserActionRequired(Intent intent) throws RemoteException { 20111 throw new IllegalStateException(); 20112 } 20113 20114 @Override 20115 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 20116 Bundle extras) throws RemoteException { 20117 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 20118 + PackageManager.installStatusToString(returnCode, msg)); 20119 20120 installedLatch.countDown(); 20121 freezer.close(); 20122 20123 final int status = PackageManager.installStatusToPublicStatus(returnCode); 20124 switch (status) { 20125 case PackageInstaller.STATUS_SUCCESS: 20126 mMoveCallbacks.notifyStatusChanged(moveId, 20127 PackageManager.MOVE_SUCCEEDED); 20128 break; 20129 case PackageInstaller.STATUS_FAILURE_STORAGE: 20130 mMoveCallbacks.notifyStatusChanged(moveId, 20131 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 20132 break; 20133 default: 20134 mMoveCallbacks.notifyStatusChanged(moveId, 20135 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 20136 break; 20137 } 20138 } 20139 }; 20140 20141 final MoveInfo move; 20142 if (moveCompleteApp) { 20143 // Kick off a thread to report progress estimates 20144 new Thread() { 20145 @Override 20146 public void run() { 20147 while (true) { 20148 try { 20149 if (installedLatch.await(1, TimeUnit.SECONDS)) { 20150 break; 20151 } 20152 } catch (InterruptedException ignored) { 20153 } 20154 20155 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 20156 final int progress = 10 + (int) MathUtils.constrain( 20157 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 20158 mMoveCallbacks.notifyStatusChanged(moveId, progress); 20159 } 20160 } 20161 }.start(); 20162 20163 final String dataAppName = codeFile.getName(); 20164 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 20165 dataAppName, appId, seinfo, targetSdkVersion); 20166 } else { 20167 move = null; 20168 } 20169 20170 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 20171 20172 final Message msg = mHandler.obtainMessage(INIT_COPY); 20173 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 20174 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 20175 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 20176 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 20177 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 20178 msg.obj = params; 20179 20180 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 20181 System.identityHashCode(msg.obj)); 20182 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 20183 System.identityHashCode(msg.obj)); 20184 20185 mHandler.sendMessage(msg); 20186 } 20187 20188 @Override 20189 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 20190 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 20191 20192 final int realMoveId = mNextMoveId.getAndIncrement(); 20193 final Bundle extras = new Bundle(); 20194 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 20195 mMoveCallbacks.notifyCreated(realMoveId, extras); 20196 20197 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 20198 @Override 20199 public void onCreated(int moveId, Bundle extras) { 20200 // Ignored 20201 } 20202 20203 @Override 20204 public void onStatusChanged(int moveId, int status, long estMillis) { 20205 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 20206 } 20207 }; 20208 20209 final StorageManager storage = mContext.getSystemService(StorageManager.class); 20210 storage.setPrimaryStorageUuid(volumeUuid, callback); 20211 return realMoveId; 20212 } 20213 20214 @Override 20215 public int getMoveStatus(int moveId) { 20216 mContext.enforceCallingOrSelfPermission( 20217 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20218 return mMoveCallbacks.mLastStatus.get(moveId); 20219 } 20220 20221 @Override 20222 public void registerMoveCallback(IPackageMoveObserver callback) { 20223 mContext.enforceCallingOrSelfPermission( 20224 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20225 mMoveCallbacks.register(callback); 20226 } 20227 20228 @Override 20229 public void unregisterMoveCallback(IPackageMoveObserver callback) { 20230 mContext.enforceCallingOrSelfPermission( 20231 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 20232 mMoveCallbacks.unregister(callback); 20233 } 20234 20235 @Override 20236 public boolean setInstallLocation(int loc) { 20237 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 20238 null); 20239 if (getInstallLocation() == loc) { 20240 return true; 20241 } 20242 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 20243 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 20244 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 20245 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 20246 return true; 20247 } 20248 return false; 20249 } 20250 20251 @Override 20252 public int getInstallLocation() { 20253 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 20254 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 20255 PackageHelper.APP_INSTALL_AUTO); 20256 } 20257 20258 /** Called by UserManagerService */ 20259 void cleanUpUser(UserManagerService userManager, int userHandle) { 20260 synchronized (mPackages) { 20261 mDirtyUsers.remove(userHandle); 20262 mUserNeedsBadging.delete(userHandle); 20263 mSettings.removeUserLPw(userHandle); 20264 mPendingBroadcasts.remove(userHandle); 20265 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 20266 removeUnusedPackagesLPw(userManager, userHandle); 20267 } 20268 } 20269 20270 /** 20271 * We're removing userHandle and would like to remove any downloaded packages 20272 * that are no longer in use by any other user. 20273 * @param userHandle the user being removed 20274 */ 20275 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 20276 final boolean DEBUG_CLEAN_APKS = false; 20277 int [] users = userManager.getUserIds(); 20278 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 20279 while (psit.hasNext()) { 20280 PackageSetting ps = psit.next(); 20281 if (ps.pkg == null) { 20282 continue; 20283 } 20284 final String packageName = ps.pkg.packageName; 20285 // Skip over if system app 20286 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20287 continue; 20288 } 20289 if (DEBUG_CLEAN_APKS) { 20290 Slog.i(TAG, "Checking package " + packageName); 20291 } 20292 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20293 if (keep) { 20294 if (DEBUG_CLEAN_APKS) { 20295 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20296 } 20297 } else { 20298 for (int i = 0; i < users.length; i++) { 20299 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20300 keep = true; 20301 if (DEBUG_CLEAN_APKS) { 20302 Slog.i(TAG, " Keeping package " + packageName + " for user " 20303 + users[i]); 20304 } 20305 break; 20306 } 20307 } 20308 } 20309 if (!keep) { 20310 if (DEBUG_CLEAN_APKS) { 20311 Slog.i(TAG, " Removing package " + packageName); 20312 } 20313 mHandler.post(new Runnable() { 20314 public void run() { 20315 deletePackageX(packageName, userHandle, 0); 20316 } //end run 20317 }); 20318 } 20319 } 20320 } 20321 20322 /** Called by UserManagerService */ 20323 void createNewUser(int userId) { 20324 synchronized (mInstallLock) { 20325 mSettings.createNewUserLI(this, mInstaller, userId); 20326 } 20327 synchronized (mPackages) { 20328 scheduleWritePackageRestrictionsLocked(userId); 20329 scheduleWritePackageListLocked(userId); 20330 applyFactoryDefaultBrowserLPw(userId); 20331 primeDomainVerificationsLPw(userId); 20332 } 20333 } 20334 20335 void onBeforeUserStartUninitialized(final int userId) { 20336 synchronized (mPackages) { 20337 if (mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 20338 return; 20339 } 20340 } 20341 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 20342 // If permission review for legacy apps is required, we represent 20343 // dagerous permissions for such apps as always granted runtime 20344 // permissions to keep per user flag state whether review is needed. 20345 // Hence, if a new user is added we have to propagate dangerous 20346 // permission grants for these legacy apps. 20347 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20348 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20349 | UPDATE_PERMISSIONS_REPLACE_ALL); 20350 } 20351 } 20352 20353 @Override 20354 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20355 mContext.enforceCallingOrSelfPermission( 20356 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20357 "Only package verification agents can read the verifier device identity"); 20358 20359 synchronized (mPackages) { 20360 return mSettings.getVerifierDeviceIdentityLPw(); 20361 } 20362 } 20363 20364 @Override 20365 public void setPermissionEnforced(String permission, boolean enforced) { 20366 // TODO: Now that we no longer change GID for storage, this should to away. 20367 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20368 "setPermissionEnforced"); 20369 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20370 synchronized (mPackages) { 20371 if (mSettings.mReadExternalStorageEnforced == null 20372 || mSettings.mReadExternalStorageEnforced != enforced) { 20373 mSettings.mReadExternalStorageEnforced = enforced; 20374 mSettings.writeLPr(); 20375 } 20376 } 20377 // kill any non-foreground processes so we restart them and 20378 // grant/revoke the GID. 20379 final IActivityManager am = ActivityManagerNative.getDefault(); 20380 if (am != null) { 20381 final long token = Binder.clearCallingIdentity(); 20382 try { 20383 am.killProcessesBelowForeground("setPermissionEnforcement"); 20384 } catch (RemoteException e) { 20385 } finally { 20386 Binder.restoreCallingIdentity(token); 20387 } 20388 } 20389 } else { 20390 throw new IllegalArgumentException("No selective enforcement for " + permission); 20391 } 20392 } 20393 20394 @Override 20395 @Deprecated 20396 public boolean isPermissionEnforced(String permission) { 20397 return true; 20398 } 20399 20400 @Override 20401 public boolean isStorageLow() { 20402 final long token = Binder.clearCallingIdentity(); 20403 try { 20404 final DeviceStorageMonitorInternal 20405 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20406 if (dsm != null) { 20407 return dsm.isMemoryLow(); 20408 } else { 20409 return false; 20410 } 20411 } finally { 20412 Binder.restoreCallingIdentity(token); 20413 } 20414 } 20415 20416 @Override 20417 public IPackageInstaller getPackageInstaller() { 20418 return mInstallerService; 20419 } 20420 20421 private boolean userNeedsBadging(int userId) { 20422 int index = mUserNeedsBadging.indexOfKey(userId); 20423 if (index < 0) { 20424 final UserInfo userInfo; 20425 final long token = Binder.clearCallingIdentity(); 20426 try { 20427 userInfo = sUserManager.getUserInfo(userId); 20428 } finally { 20429 Binder.restoreCallingIdentity(token); 20430 } 20431 final boolean b; 20432 if (userInfo != null && userInfo.isManagedProfile()) { 20433 b = true; 20434 } else { 20435 b = false; 20436 } 20437 mUserNeedsBadging.put(userId, b); 20438 return b; 20439 } 20440 return mUserNeedsBadging.valueAt(index); 20441 } 20442 20443 @Override 20444 public KeySet getKeySetByAlias(String packageName, String alias) { 20445 if (packageName == null || alias == null) { 20446 return null; 20447 } 20448 synchronized(mPackages) { 20449 final PackageParser.Package pkg = mPackages.get(packageName); 20450 if (pkg == null) { 20451 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20452 throw new IllegalArgumentException("Unknown package: " + packageName); 20453 } 20454 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20455 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20456 } 20457 } 20458 20459 @Override 20460 public KeySet getSigningKeySet(String packageName) { 20461 if (packageName == null) { 20462 return null; 20463 } 20464 synchronized(mPackages) { 20465 final PackageParser.Package pkg = mPackages.get(packageName); 20466 if (pkg == null) { 20467 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20468 throw new IllegalArgumentException("Unknown package: " + packageName); 20469 } 20470 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20471 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20472 throw new SecurityException("May not access signing KeySet of other apps."); 20473 } 20474 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20475 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20476 } 20477 } 20478 20479 @Override 20480 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20481 if (packageName == null || ks == null) { 20482 return false; 20483 } 20484 synchronized(mPackages) { 20485 final PackageParser.Package pkg = mPackages.get(packageName); 20486 if (pkg == null) { 20487 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20488 throw new IllegalArgumentException("Unknown package: " + packageName); 20489 } 20490 IBinder ksh = ks.getToken(); 20491 if (ksh instanceof KeySetHandle) { 20492 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20493 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20494 } 20495 return false; 20496 } 20497 } 20498 20499 @Override 20500 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20501 if (packageName == null || ks == null) { 20502 return false; 20503 } 20504 synchronized(mPackages) { 20505 final PackageParser.Package pkg = mPackages.get(packageName); 20506 if (pkg == null) { 20507 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20508 throw new IllegalArgumentException("Unknown package: " + packageName); 20509 } 20510 IBinder ksh = ks.getToken(); 20511 if (ksh instanceof KeySetHandle) { 20512 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20513 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20514 } 20515 return false; 20516 } 20517 } 20518 20519 private void deletePackageIfUnusedLPr(final String packageName) { 20520 PackageSetting ps = mSettings.mPackages.get(packageName); 20521 if (ps == null) { 20522 return; 20523 } 20524 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20525 // TODO Implement atomic delete if package is unused 20526 // It is currently possible that the package will be deleted even if it is installed 20527 // after this method returns. 20528 mHandler.post(new Runnable() { 20529 public void run() { 20530 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20531 } 20532 }); 20533 } 20534 } 20535 20536 /** 20537 * Check and throw if the given before/after packages would be considered a 20538 * downgrade. 20539 */ 20540 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20541 throws PackageManagerException { 20542 if (after.versionCode < before.mVersionCode) { 20543 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20544 "Update version code " + after.versionCode + " is older than current " 20545 + before.mVersionCode); 20546 } else if (after.versionCode == before.mVersionCode) { 20547 if (after.baseRevisionCode < before.baseRevisionCode) { 20548 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20549 "Update base revision code " + after.baseRevisionCode 20550 + " is older than current " + before.baseRevisionCode); 20551 } 20552 20553 if (!ArrayUtils.isEmpty(after.splitNames)) { 20554 for (int i = 0; i < after.splitNames.length; i++) { 20555 final String splitName = after.splitNames[i]; 20556 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20557 if (j != -1) { 20558 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20559 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20560 "Update split " + splitName + " revision code " 20561 + after.splitRevisionCodes[i] + " is older than current " 20562 + before.splitRevisionCodes[j]); 20563 } 20564 } 20565 } 20566 } 20567 } 20568 } 20569 20570 private static class MoveCallbacks extends Handler { 20571 private static final int MSG_CREATED = 1; 20572 private static final int MSG_STATUS_CHANGED = 2; 20573 20574 private final RemoteCallbackList<IPackageMoveObserver> 20575 mCallbacks = new RemoteCallbackList<>(); 20576 20577 private final SparseIntArray mLastStatus = new SparseIntArray(); 20578 20579 public MoveCallbacks(Looper looper) { 20580 super(looper); 20581 } 20582 20583 public void register(IPackageMoveObserver callback) { 20584 mCallbacks.register(callback); 20585 } 20586 20587 public void unregister(IPackageMoveObserver callback) { 20588 mCallbacks.unregister(callback); 20589 } 20590 20591 @Override 20592 public void handleMessage(Message msg) { 20593 final SomeArgs args = (SomeArgs) msg.obj; 20594 final int n = mCallbacks.beginBroadcast(); 20595 for (int i = 0; i < n; i++) { 20596 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20597 try { 20598 invokeCallback(callback, msg.what, args); 20599 } catch (RemoteException ignored) { 20600 } 20601 } 20602 mCallbacks.finishBroadcast(); 20603 args.recycle(); 20604 } 20605 20606 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20607 throws RemoteException { 20608 switch (what) { 20609 case MSG_CREATED: { 20610 callback.onCreated(args.argi1, (Bundle) args.arg2); 20611 break; 20612 } 20613 case MSG_STATUS_CHANGED: { 20614 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20615 break; 20616 } 20617 } 20618 } 20619 20620 private void notifyCreated(int moveId, Bundle extras) { 20621 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20622 20623 final SomeArgs args = SomeArgs.obtain(); 20624 args.argi1 = moveId; 20625 args.arg2 = extras; 20626 obtainMessage(MSG_CREATED, args).sendToTarget(); 20627 } 20628 20629 private void notifyStatusChanged(int moveId, int status) { 20630 notifyStatusChanged(moveId, status, -1); 20631 } 20632 20633 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20634 Slog.v(TAG, "Move " + moveId + " status " + status); 20635 20636 final SomeArgs args = SomeArgs.obtain(); 20637 args.argi1 = moveId; 20638 args.argi2 = status; 20639 args.arg3 = estMillis; 20640 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20641 20642 synchronized (mLastStatus) { 20643 mLastStatus.put(moveId, status); 20644 } 20645 } 20646 } 20647 20648 private final static class OnPermissionChangeListeners extends Handler { 20649 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20650 20651 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20652 new RemoteCallbackList<>(); 20653 20654 public OnPermissionChangeListeners(Looper looper) { 20655 super(looper); 20656 } 20657 20658 @Override 20659 public void handleMessage(Message msg) { 20660 switch (msg.what) { 20661 case MSG_ON_PERMISSIONS_CHANGED: { 20662 final int uid = msg.arg1; 20663 handleOnPermissionsChanged(uid); 20664 } break; 20665 } 20666 } 20667 20668 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20669 mPermissionListeners.register(listener); 20670 20671 } 20672 20673 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20674 mPermissionListeners.unregister(listener); 20675 } 20676 20677 public void onPermissionsChanged(int uid) { 20678 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20679 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20680 } 20681 } 20682 20683 private void handleOnPermissionsChanged(int uid) { 20684 final int count = mPermissionListeners.beginBroadcast(); 20685 try { 20686 for (int i = 0; i < count; i++) { 20687 IOnPermissionsChangeListener callback = mPermissionListeners 20688 .getBroadcastItem(i); 20689 try { 20690 callback.onPermissionsChanged(uid); 20691 } catch (RemoteException e) { 20692 Log.e(TAG, "Permission listener is dead", e); 20693 } 20694 } 20695 } finally { 20696 mPermissionListeners.finishBroadcast(); 20697 } 20698 } 20699 } 20700 20701 private class PackageManagerInternalImpl extends PackageManagerInternal { 20702 @Override 20703 public void setLocationPackagesProvider(PackagesProvider provider) { 20704 synchronized (mPackages) { 20705 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20706 } 20707 } 20708 20709 @Override 20710 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20711 synchronized (mPackages) { 20712 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20713 } 20714 } 20715 20716 @Override 20717 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20718 synchronized (mPackages) { 20719 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20720 } 20721 } 20722 20723 @Override 20724 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20725 synchronized (mPackages) { 20726 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20727 } 20728 } 20729 20730 @Override 20731 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20732 synchronized (mPackages) { 20733 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20734 } 20735 } 20736 20737 @Override 20738 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20739 synchronized (mPackages) { 20740 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20741 } 20742 } 20743 20744 @Override 20745 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20746 synchronized (mPackages) { 20747 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20748 packageName, userId); 20749 } 20750 } 20751 20752 @Override 20753 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20754 synchronized (mPackages) { 20755 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20756 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20757 packageName, userId); 20758 } 20759 } 20760 20761 @Override 20762 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20763 synchronized (mPackages) { 20764 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20765 packageName, userId); 20766 } 20767 } 20768 20769 @Override 20770 public void setKeepUninstalledPackages(final List<String> packageList) { 20771 Preconditions.checkNotNull(packageList); 20772 List<String> removedFromList = null; 20773 synchronized (mPackages) { 20774 if (mKeepUninstalledPackages != null) { 20775 final int packagesCount = mKeepUninstalledPackages.size(); 20776 for (int i = 0; i < packagesCount; i++) { 20777 String oldPackage = mKeepUninstalledPackages.get(i); 20778 if (packageList != null && packageList.contains(oldPackage)) { 20779 continue; 20780 } 20781 if (removedFromList == null) { 20782 removedFromList = new ArrayList<>(); 20783 } 20784 removedFromList.add(oldPackage); 20785 } 20786 } 20787 mKeepUninstalledPackages = new ArrayList<>(packageList); 20788 if (removedFromList != null) { 20789 final int removedCount = removedFromList.size(); 20790 for (int i = 0; i < removedCount; i++) { 20791 deletePackageIfUnusedLPr(removedFromList.get(i)); 20792 } 20793 } 20794 } 20795 } 20796 20797 @Override 20798 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20799 synchronized (mPackages) { 20800 // If we do not support permission review, done. 20801 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20802 return false; 20803 } 20804 20805 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20806 if (packageSetting == null) { 20807 return false; 20808 } 20809 20810 // Permission review applies only to apps not supporting the new permission model. 20811 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20812 return false; 20813 } 20814 20815 // Legacy apps have the permission and get user consent on launch. 20816 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20817 return permissionsState.isPermissionReviewRequired(userId); 20818 } 20819 } 20820 20821 @Override 20822 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20823 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20824 } 20825 20826 @Override 20827 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20828 int userId) { 20829 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20830 } 20831 } 20832 20833 @Override 20834 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20835 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20836 synchronized (mPackages) { 20837 final long identity = Binder.clearCallingIdentity(); 20838 try { 20839 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20840 packageNames, userId); 20841 } finally { 20842 Binder.restoreCallingIdentity(identity); 20843 } 20844 } 20845 } 20846 20847 private static void enforceSystemOrPhoneCaller(String tag) { 20848 int callingUid = Binder.getCallingUid(); 20849 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20850 throw new SecurityException( 20851 "Cannot call " + tag + " from UID " + callingUid); 20852 } 20853 } 20854 20855 boolean isHistoricalPackageUsageAvailable() { 20856 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20857 } 20858 20859 /** 20860 * Return a <b>copy</b> of the collection of packages known to the package manager. 20861 * @return A copy of the values of mPackages. 20862 */ 20863 Collection<PackageParser.Package> getPackages() { 20864 synchronized (mPackages) { 20865 return new ArrayList<>(mPackages.values()); 20866 } 20867 } 20868 20869 /** 20870 * Logs process start information (including base APK hash) to the security log. 20871 * @hide 20872 */ 20873 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20874 String apkFile, int pid) { 20875 if (!SecurityLog.isLoggingEnabled()) { 20876 return; 20877 } 20878 Bundle data = new Bundle(); 20879 data.putLong("startTimestamp", System.currentTimeMillis()); 20880 data.putString("processName", processName); 20881 data.putInt("uid", uid); 20882 data.putString("seinfo", seinfo); 20883 data.putString("apkFile", apkFile); 20884 data.putInt("pid", pid); 20885 Message msg = mProcessLoggingHandler.obtainMessage( 20886 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20887 msg.setData(data); 20888 mProcessLoggingHandler.sendMessage(msg); 20889 } 20890} 20891