PackageManagerService.java revision b3e435439cad94e5f20c7c9e0c4a5fa321c68443
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.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.INetworkPolicyManager; 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.EventLogTags; 243import com.android.server.FgThread; 244import com.android.server.IntentResolver; 245import com.android.server.LocalServices; 246import com.android.server.ServiceThread; 247import com.android.server.SystemConfig; 248import com.android.server.Watchdog; 249import com.android.server.net.NetworkPolicyManagerInternal; 250import com.android.server.pm.PermissionsState.PermissionState; 251import com.android.server.pm.Settings.DatabaseVersion; 252import com.android.server.pm.Settings.VersionInfo; 253import com.android.server.storage.DeviceStorageMonitorInternal; 254 255import dalvik.system.CloseGuard; 256import dalvik.system.DexFile; 257import dalvik.system.VMRuntime; 258 259import libcore.io.IoUtils; 260import libcore.util.EmptyArray; 261 262import org.xmlpull.v1.XmlPullParser; 263import org.xmlpull.v1.XmlPullParserException; 264import org.xmlpull.v1.XmlSerializer; 265 266import java.io.BufferedInputStream; 267import java.io.BufferedOutputStream; 268import java.io.BufferedReader; 269import java.io.ByteArrayInputStream; 270import java.io.ByteArrayOutputStream; 271import java.io.File; 272import java.io.FileDescriptor; 273import java.io.FileInputStream; 274import java.io.FileNotFoundException; 275import java.io.FileOutputStream; 276import java.io.FileReader; 277import java.io.FilenameFilter; 278import java.io.IOException; 279import java.io.InputStream; 280import java.io.PrintWriter; 281import java.nio.charset.StandardCharsets; 282import java.security.DigestInputStream; 283import java.security.MessageDigest; 284import java.security.NoSuchAlgorithmException; 285import java.security.PublicKey; 286import java.security.cert.Certificate; 287import java.security.cert.CertificateEncodingException; 288import java.security.cert.CertificateException; 289import java.text.SimpleDateFormat; 290import java.util.ArrayList; 291import java.util.Arrays; 292import java.util.Collection; 293import java.util.Collections; 294import java.util.Comparator; 295import java.util.Date; 296import java.util.HashSet; 297import java.util.Iterator; 298import java.util.List; 299import java.util.Map; 300import java.util.Objects; 301import java.util.Set; 302import java.util.concurrent.CountDownLatch; 303import java.util.concurrent.TimeUnit; 304import java.util.concurrent.atomic.AtomicBoolean; 305import java.util.concurrent.atomic.AtomicInteger; 306import java.util.concurrent.atomic.AtomicLong; 307 308/** 309 * Keep track of all those APKs everywhere. 310 * <p> 311 * Internally there are two important locks: 312 * <ul> 313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 314 * and other related state. It is a fine-grained lock that should only be held 315 * momentarily, as it's one of the most contended locks in the system. 316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 317 * operations typically involve heavy lifting of application data on disk. Since 318 * {@code installd} is single-threaded, and it's operations can often be slow, 319 * this lock should never be acquired while already holding {@link #mPackages}. 320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 321 * holding {@link #mInstallLock}. 322 * </ul> 323 * Many internal methods rely on the caller to hold the appropriate locks, and 324 * this contract is expressed through method name suffixes: 325 * <ul> 326 * <li>fooLI(): the caller must hold {@link #mInstallLock} 327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 328 * being modified must be frozen 329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 331 * </ul> 332 * <p> 333 * Because this class is very central to the platform's security; please run all 334 * CTS and unit tests whenever making modifications: 335 * 336 * <pre> 337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 339 * </pre> 340 */ 341public class PackageManagerService extends IPackageManager.Stub { 342 static final String TAG = "PackageManager"; 343 static final boolean DEBUG_SETTINGS = false; 344 static final boolean DEBUG_PREFERRED = false; 345 static final boolean DEBUG_UPGRADE = false; 346 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 347 private static final boolean DEBUG_BACKUP = false; 348 private static final boolean DEBUG_INSTALL = false; 349 private static final boolean DEBUG_REMOVE = false; 350 private static final boolean DEBUG_BROADCASTS = false; 351 private static final boolean DEBUG_SHOW_INFO = false; 352 private static final boolean DEBUG_PACKAGE_INFO = false; 353 private static final boolean DEBUG_INTENT_MATCHING = false; 354 private static final boolean DEBUG_PACKAGE_SCANNING = false; 355 private static final boolean DEBUG_VERIFY = false; 356 private static final boolean DEBUG_FILTERS = false; 357 358 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 359 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 360 // user, but by default initialize to this. 361 static final boolean DEBUG_DEXOPT = false; 362 363 private static final boolean DEBUG_ABI_SELECTION = false; 364 private static final boolean DEBUG_EPHEMERAL = false; 365 private static final boolean DEBUG_TRIAGED_MISSING = false; 366 private static final boolean DEBUG_APP_DATA = false; 367 368 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 369 370 private static final boolean DISABLE_EPHEMERAL_APPS = true; 371 372 private static final int RADIO_UID = Process.PHONE_UID; 373 private static final int LOG_UID = Process.LOG_UID; 374 private static final int NFC_UID = Process.NFC_UID; 375 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 376 private static final int SHELL_UID = Process.SHELL_UID; 377 378 // Cap the size of permission trees that 3rd party apps can define 379 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 380 381 // Suffix used during package installation when copying/moving 382 // package apks to install directory. 383 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 384 385 static final int SCAN_NO_DEX = 1<<1; 386 static final int SCAN_FORCE_DEX = 1<<2; 387 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 388 static final int SCAN_NEW_INSTALL = 1<<4; 389 static final int SCAN_NO_PATHS = 1<<5; 390 static final int SCAN_UPDATE_TIME = 1<<6; 391 static final int SCAN_DEFER_DEX = 1<<7; 392 static final int SCAN_BOOTING = 1<<8; 393 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 394 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 395 static final int SCAN_REPLACING = 1<<11; 396 static final int SCAN_REQUIRE_KNOWN = 1<<12; 397 static final int SCAN_MOVE = 1<<13; 398 static final int SCAN_INITIAL = 1<<14; 399 static final int SCAN_CHECK_ONLY = 1<<15; 400 static final int SCAN_DONT_KILL_APP = 1<<17; 401 static final int SCAN_IGNORE_FROZEN = 1<<18; 402 403 static final int REMOVE_CHATTY = 1<<16; 404 405 private static final int[] EMPTY_INT_ARRAY = new int[0]; 406 407 /** 408 * Timeout (in milliseconds) after which the watchdog should declare that 409 * our handler thread is wedged. The usual default for such things is one 410 * minute but we sometimes do very lengthy I/O operations on this thread, 411 * such as installing multi-gigabyte applications, so ours needs to be longer. 412 */ 413 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 414 415 /** 416 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 417 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 418 * settings entry if available, otherwise we use the hardcoded default. If it's been 419 * more than this long since the last fstrim, we force one during the boot sequence. 420 * 421 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 422 * one gets run at the next available charging+idle time. This final mandatory 423 * no-fstrim check kicks in only of the other scheduling criteria is never met. 424 */ 425 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 426 427 /** 428 * Whether verification is enabled by default. 429 */ 430 private static final boolean DEFAULT_VERIFY_ENABLE = true; 431 432 /** 433 * The default maximum time to wait for the verification agent to return in 434 * milliseconds. 435 */ 436 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 437 438 /** 439 * The default response for package verification timeout. 440 * 441 * This can be either PackageManager.VERIFICATION_ALLOW or 442 * PackageManager.VERIFICATION_REJECT. 443 */ 444 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 445 446 static final String PLATFORM_PACKAGE_NAME = "android"; 447 448 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 449 450 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 451 DEFAULT_CONTAINER_PACKAGE, 452 "com.android.defcontainer.DefaultContainerService"); 453 454 private static final String KILL_APP_REASON_GIDS_CHANGED = 455 "permission grant or revoke changed gids"; 456 457 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 458 "permissions revoked"; 459 460 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 461 462 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 463 464 /** Permission grant: not grant the permission. */ 465 private static final int GRANT_DENIED = 1; 466 467 /** Permission grant: grant the permission as an install permission. */ 468 private static final int GRANT_INSTALL = 2; 469 470 /** Permission grant: grant the permission as a runtime one. */ 471 private static final int GRANT_RUNTIME = 3; 472 473 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 474 private static final int GRANT_UPGRADE = 4; 475 476 /** Canonical intent used to identify what counts as a "web browser" app */ 477 private static final Intent sBrowserIntent; 478 static { 479 sBrowserIntent = new Intent(); 480 sBrowserIntent.setAction(Intent.ACTION_VIEW); 481 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 482 sBrowserIntent.setData(Uri.parse("http:")); 483 } 484 485 /** 486 * The set of all protected actions [i.e. those actions for which a high priority 487 * intent filter is disallowed]. 488 */ 489 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 490 static { 491 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 494 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 495 } 496 497 // Compilation reasons. 498 public static final int REASON_FIRST_BOOT = 0; 499 public static final int REASON_BOOT = 1; 500 public static final int REASON_INSTALL = 2; 501 public static final int REASON_BACKGROUND_DEXOPT = 3; 502 public static final int REASON_AB_OTA = 4; 503 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 504 public static final int REASON_SHARED_APK = 6; 505 public static final int REASON_FORCED_DEXOPT = 7; 506 507 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 508 509 /** Special library name that skips shared libraries check during compilation. */ 510 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 511 512 final ServiceThread mHandlerThread; 513 514 final PackageHandler mHandler; 515 516 private final ProcessLoggingHandler mProcessLoggingHandler; 517 518 /** 519 * Messages for {@link #mHandler} that need to wait for system ready before 520 * being dispatched. 521 */ 522 private ArrayList<Message> mPostSystemReadyMessages; 523 524 final int mSdkVersion = Build.VERSION.SDK_INT; 525 526 final Context mContext; 527 final boolean mFactoryTest; 528 final boolean mOnlyCore; 529 final DisplayMetrics mMetrics; 530 final int mDefParseFlags; 531 final String[] mSeparateProcesses; 532 final boolean mIsUpgrade; 533 final boolean mIsPreNUpgrade; 534 535 /** The location for ASEC container files on internal storage. */ 536 final String mAsecInternalPath; 537 538 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 539 // LOCK HELD. Can be called with mInstallLock held. 540 @GuardedBy("mInstallLock") 541 final Installer mInstaller; 542 543 /** Directory where installed third-party apps stored */ 544 final File mAppInstallDir; 545 final File mEphemeralInstallDir; 546 547 /** 548 * Directory to which applications installed internally have their 549 * 32 bit native libraries copied. 550 */ 551 private File mAppLib32InstallDir; 552 553 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 554 // apps. 555 final File mDrmAppPrivateInstallDir; 556 557 // ---------------------------------------------------------------- 558 559 // Lock for state used when installing and doing other long running 560 // operations. Methods that must be called with this lock held have 561 // the suffix "LI". 562 final Object mInstallLock = new Object(); 563 564 // ---------------------------------------------------------------- 565 566 // Keys are String (package name), values are Package. This also serves 567 // as the lock for the global state. Methods that must be called with 568 // this lock held have the prefix "LP". 569 @GuardedBy("mPackages") 570 final ArrayMap<String, PackageParser.Package> mPackages = 571 new ArrayMap<String, PackageParser.Package>(); 572 573 final ArrayMap<String, Set<String>> mKnownCodebase = 574 new ArrayMap<String, Set<String>>(); 575 576 // Tracks available target package names -> overlay package paths. 577 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 578 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 579 580 /** 581 * Tracks new system packages [received in an OTA] that we expect to 582 * find updated user-installed versions. Keys are package name, values 583 * are package location. 584 */ 585 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 586 /** 587 * Tracks high priority intent filters for protected actions. During boot, certain 588 * filter actions are protected and should never be allowed to have a high priority 589 * intent filter for them. However, there is one, and only one exception -- the 590 * setup wizard. It must be able to define a high priority intent filter for these 591 * actions to ensure there are no escapes from the wizard. We need to delay processing 592 * of these during boot as we need to look at all of the system packages in order 593 * to know which component is the setup wizard. 594 */ 595 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 596 /** 597 * Whether or not processing protected filters should be deferred. 598 */ 599 private boolean mDeferProtectedFilters = true; 600 601 /** 602 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 603 */ 604 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 605 /** 606 * Whether or not system app permissions should be promoted from install to runtime. 607 */ 608 boolean mPromoteSystemApps; 609 610 @GuardedBy("mPackages") 611 final Settings mSettings; 612 613 /** 614 * Set of package names that are currently "frozen", which means active 615 * surgery is being done on the code/data for that package. The platform 616 * will refuse to launch frozen packages to avoid race conditions. 617 * 618 * @see PackageFreezer 619 */ 620 @GuardedBy("mPackages") 621 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 622 623 boolean mRestoredSettings; 624 625 // System configuration read by SystemConfig. 626 final int[] mGlobalGids; 627 final SparseArray<ArraySet<String>> mSystemPermissions; 628 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 629 630 // If mac_permissions.xml was found for seinfo labeling. 631 boolean mFoundPolicyFile; 632 633 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 634 635 public static final class SharedLibraryEntry { 636 public final String path; 637 public final String apk; 638 639 SharedLibraryEntry(String _path, String _apk) { 640 path = _path; 641 apk = _apk; 642 } 643 } 644 645 // Currently known shared libraries. 646 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 647 new ArrayMap<String, SharedLibraryEntry>(); 648 649 // All available activities, for your resolving pleasure. 650 final ActivityIntentResolver mActivities = 651 new ActivityIntentResolver(); 652 653 // All available receivers, for your resolving pleasure. 654 final ActivityIntentResolver mReceivers = 655 new ActivityIntentResolver(); 656 657 // All available services, for your resolving pleasure. 658 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 659 660 // All available providers, for your resolving pleasure. 661 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 662 663 // Mapping from provider base names (first directory in content URI codePath) 664 // to the provider information. 665 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 666 new ArrayMap<String, PackageParser.Provider>(); 667 668 // Mapping from instrumentation class names to info about them. 669 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 670 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 671 672 // Mapping from permission names to info about them. 673 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 674 new ArrayMap<String, PackageParser.PermissionGroup>(); 675 676 // Packages whose data we have transfered into another package, thus 677 // should no longer exist. 678 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 679 680 // Broadcast actions that are only available to the system. 681 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 682 683 /** List of packages waiting for verification. */ 684 final SparseArray<PackageVerificationState> mPendingVerification 685 = new SparseArray<PackageVerificationState>(); 686 687 /** Set of packages associated with each app op permission. */ 688 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 689 690 final PackageInstallerService mInstallerService; 691 692 private final PackageDexOptimizer mPackageDexOptimizer; 693 694 private AtomicInteger mNextMoveId = new AtomicInteger(); 695 private final MoveCallbacks mMoveCallbacks; 696 697 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 698 699 // Cache of users who need badging. 700 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 701 702 /** Token for keys in mPendingVerification. */ 703 private int mPendingVerificationToken = 0; 704 705 volatile boolean mSystemReady; 706 volatile boolean mSafeMode; 707 volatile boolean mHasSystemUidErrors; 708 709 ApplicationInfo mAndroidApplication; 710 final ActivityInfo mResolveActivity = new ActivityInfo(); 711 final ResolveInfo mResolveInfo = new ResolveInfo(); 712 ComponentName mResolveComponentName; 713 PackageParser.Package mPlatformPackage; 714 ComponentName mCustomResolverComponentName; 715 716 boolean mResolverReplaced = false; 717 718 private final @Nullable ComponentName mIntentFilterVerifierComponent; 719 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 720 721 private int mIntentFilterVerificationToken = 0; 722 723 /** Component that knows whether or not an ephemeral application exists */ 724 final ComponentName mEphemeralResolverComponent; 725 /** The service connection to the ephemeral resolver */ 726 final EphemeralResolverConnection mEphemeralResolverConnection; 727 728 /** Component used to install ephemeral applications */ 729 final ComponentName mEphemeralInstallerComponent; 730 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 731 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 732 733 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 734 = new SparseArray<IntentFilterVerificationState>(); 735 736 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 737 new DefaultPermissionGrantPolicy(this); 738 739 // List of packages names to keep cached, even if they are uninstalled for all users 740 private List<String> mKeepUninstalledPackages; 741 742 private UserManagerInternal mUserManagerInternal; 743 744 private static class IFVerificationParams { 745 PackageParser.Package pkg; 746 boolean replacing; 747 int userId; 748 int verifierUid; 749 750 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 751 int _userId, int _verifierUid) { 752 pkg = _pkg; 753 replacing = _replacing; 754 userId = _userId; 755 replacing = _replacing; 756 verifierUid = _verifierUid; 757 } 758 } 759 760 private interface IntentFilterVerifier<T extends IntentFilter> { 761 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 762 T filter, String packageName); 763 void startVerifications(int userId); 764 void receiveVerificationResponse(int verificationId); 765 } 766 767 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 768 private Context mContext; 769 private ComponentName mIntentFilterVerifierComponent; 770 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 771 772 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 773 mContext = context; 774 mIntentFilterVerifierComponent = verifierComponent; 775 } 776 777 private String getDefaultScheme() { 778 return IntentFilter.SCHEME_HTTPS; 779 } 780 781 @Override 782 public void startVerifications(int userId) { 783 // Launch verifications requests 784 int count = mCurrentIntentFilterVerifications.size(); 785 for (int n=0; n<count; n++) { 786 int verificationId = mCurrentIntentFilterVerifications.get(n); 787 final IntentFilterVerificationState ivs = 788 mIntentFilterVerificationStates.get(verificationId); 789 790 String packageName = ivs.getPackageName(); 791 792 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 793 final int filterCount = filters.size(); 794 ArraySet<String> domainsSet = new ArraySet<>(); 795 for (int m=0; m<filterCount; m++) { 796 PackageParser.ActivityIntentInfo filter = filters.get(m); 797 domainsSet.addAll(filter.getHostsList()); 798 } 799 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 800 synchronized (mPackages) { 801 if (mSettings.createIntentFilterVerificationIfNeededLPw( 802 packageName, domainsList) != null) { 803 scheduleWriteSettingsLocked(); 804 } 805 } 806 sendVerificationRequest(userId, verificationId, ivs); 807 } 808 mCurrentIntentFilterVerifications.clear(); 809 } 810 811 private void sendVerificationRequest(int userId, int verificationId, 812 IntentFilterVerificationState ivs) { 813 814 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 815 verificationIntent.putExtra( 816 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 817 verificationId); 818 verificationIntent.putExtra( 819 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 820 getDefaultScheme()); 821 verificationIntent.putExtra( 822 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 823 ivs.getHostsString()); 824 verificationIntent.putExtra( 825 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 826 ivs.getPackageName()); 827 verificationIntent.setComponent(mIntentFilterVerifierComponent); 828 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 829 830 UserHandle user = new UserHandle(userId); 831 mContext.sendBroadcastAsUser(verificationIntent, user); 832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 833 "Sending IntentFilter verification broadcast"); 834 } 835 836 public void receiveVerificationResponse(int verificationId) { 837 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 838 839 final boolean verified = ivs.isVerified(); 840 841 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 842 final int count = filters.size(); 843 if (DEBUG_DOMAIN_VERIFICATION) { 844 Slog.i(TAG, "Received verification response " + verificationId 845 + " for " + count + " filters, verified=" + verified); 846 } 847 for (int n=0; n<count; n++) { 848 PackageParser.ActivityIntentInfo filter = filters.get(n); 849 filter.setVerified(verified); 850 851 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 852 + " verified with result:" + verified + " and hosts:" 853 + ivs.getHostsString()); 854 } 855 856 mIntentFilterVerificationStates.remove(verificationId); 857 858 final String packageName = ivs.getPackageName(); 859 IntentFilterVerificationInfo ivi = null; 860 861 synchronized (mPackages) { 862 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 863 } 864 if (ivi == null) { 865 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 866 + verificationId + " packageName:" + packageName); 867 return; 868 } 869 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 870 "Updating IntentFilterVerificationInfo for package " + packageName 871 +" verificationId:" + verificationId); 872 873 synchronized (mPackages) { 874 if (verified) { 875 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 876 } else { 877 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 878 } 879 scheduleWriteSettingsLocked(); 880 881 final int userId = ivs.getUserId(); 882 if (userId != UserHandle.USER_ALL) { 883 final int userStatus = 884 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 885 886 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 887 boolean needUpdate = false; 888 889 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 890 // already been set by the User thru the Disambiguation dialog 891 switch (userStatus) { 892 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 893 if (verified) { 894 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 895 } else { 896 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 897 } 898 needUpdate = true; 899 break; 900 901 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 902 if (verified) { 903 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 904 needUpdate = true; 905 } 906 break; 907 908 default: 909 // Nothing to do 910 } 911 912 if (needUpdate) { 913 mSettings.updateIntentFilterVerificationStatusLPw( 914 packageName, updatedStatus, userId); 915 scheduleWritePackageRestrictionsLocked(userId); 916 } 917 } 918 } 919 } 920 921 @Override 922 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 923 ActivityIntentInfo filter, String packageName) { 924 if (!hasValidDomains(filter)) { 925 return false; 926 } 927 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 928 if (ivs == null) { 929 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 930 packageName); 931 } 932 if (DEBUG_DOMAIN_VERIFICATION) { 933 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 934 } 935 ivs.addFilter(filter); 936 return true; 937 } 938 939 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 940 int userId, int verificationId, String packageName) { 941 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 942 verifierUid, userId, packageName); 943 ivs.setPendingState(); 944 synchronized (mPackages) { 945 mIntentFilterVerificationStates.append(verificationId, ivs); 946 mCurrentIntentFilterVerifications.add(verificationId); 947 } 948 return ivs; 949 } 950 } 951 952 private static boolean hasValidDomains(ActivityIntentInfo filter) { 953 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 954 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 955 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 956 } 957 958 // Set of pending broadcasts for aggregating enable/disable of components. 959 static class PendingPackageBroadcasts { 960 // for each user id, a map of <package name -> components within that package> 961 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 962 963 public PendingPackageBroadcasts() { 964 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 965 } 966 967 public ArrayList<String> get(int userId, String packageName) { 968 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 969 return packages.get(packageName); 970 } 971 972 public void put(int userId, String packageName, ArrayList<String> components) { 973 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 974 packages.put(packageName, components); 975 } 976 977 public void remove(int userId, String packageName) { 978 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 979 if (packages != null) { 980 packages.remove(packageName); 981 } 982 } 983 984 public void remove(int userId) { 985 mUidMap.remove(userId); 986 } 987 988 public int userIdCount() { 989 return mUidMap.size(); 990 } 991 992 public int userIdAt(int n) { 993 return mUidMap.keyAt(n); 994 } 995 996 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 997 return mUidMap.get(userId); 998 } 999 1000 public int size() { 1001 // total number of pending broadcast entries across all userIds 1002 int num = 0; 1003 for (int i = 0; i< mUidMap.size(); i++) { 1004 num += mUidMap.valueAt(i).size(); 1005 } 1006 return num; 1007 } 1008 1009 public void clear() { 1010 mUidMap.clear(); 1011 } 1012 1013 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1014 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1015 if (map == null) { 1016 map = new ArrayMap<String, ArrayList<String>>(); 1017 mUidMap.put(userId, map); 1018 } 1019 return map; 1020 } 1021 } 1022 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1023 1024 // Service Connection to remote media container service to copy 1025 // package uri's from external media onto secure containers 1026 // or internal storage. 1027 private IMediaContainerService mContainerService = null; 1028 1029 static final int SEND_PENDING_BROADCAST = 1; 1030 static final int MCS_BOUND = 3; 1031 static final int END_COPY = 4; 1032 static final int INIT_COPY = 5; 1033 static final int MCS_UNBIND = 6; 1034 static final int START_CLEANING_PACKAGE = 7; 1035 static final int FIND_INSTALL_LOC = 8; 1036 static final int POST_INSTALL = 9; 1037 static final int MCS_RECONNECT = 10; 1038 static final int MCS_GIVE_UP = 11; 1039 static final int UPDATED_MEDIA_STATUS = 12; 1040 static final int WRITE_SETTINGS = 13; 1041 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1042 static final int PACKAGE_VERIFIED = 15; 1043 static final int CHECK_PENDING_VERIFICATION = 16; 1044 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1045 static final int INTENT_FILTER_VERIFIED = 18; 1046 1047 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1048 1049 // Delay time in millisecs 1050 static final int BROADCAST_DELAY = 10 * 1000; 1051 1052 static UserManagerService sUserManager; 1053 1054 // Stores a list of users whose package restrictions file needs to be updated 1055 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1056 1057 final private DefaultContainerConnection mDefContainerConn = 1058 new DefaultContainerConnection(); 1059 class DefaultContainerConnection implements ServiceConnection { 1060 public void onServiceConnected(ComponentName name, IBinder service) { 1061 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1062 IMediaContainerService imcs = 1063 IMediaContainerService.Stub.asInterface(service); 1064 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1065 } 1066 1067 public void onServiceDisconnected(ComponentName name) { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1069 } 1070 } 1071 1072 // Recordkeeping of restore-after-install operations that are currently in flight 1073 // between the Package Manager and the Backup Manager 1074 static class PostInstallData { 1075 public InstallArgs args; 1076 public PackageInstalledInfo res; 1077 1078 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1079 args = _a; 1080 res = _r; 1081 } 1082 } 1083 1084 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1085 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1086 1087 // XML tags for backup/restore of various bits of state 1088 private static final String TAG_PREFERRED_BACKUP = "pa"; 1089 private static final String TAG_DEFAULT_APPS = "da"; 1090 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1091 1092 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1093 private static final String TAG_ALL_GRANTS = "rt-grants"; 1094 private static final String TAG_GRANT = "grant"; 1095 private static final String ATTR_PACKAGE_NAME = "pkg"; 1096 1097 private static final String TAG_PERMISSION = "perm"; 1098 private static final String ATTR_PERMISSION_NAME = "name"; 1099 private static final String ATTR_IS_GRANTED = "g"; 1100 private static final String ATTR_USER_SET = "set"; 1101 private static final String ATTR_USER_FIXED = "fixed"; 1102 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1103 1104 // System/policy permission grants are not backed up 1105 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_POLICY_FIXED 1107 | FLAG_PERMISSION_SYSTEM_FIXED 1108 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1109 1110 // And we back up these user-adjusted states 1111 private static final int USER_RUNTIME_GRANT_MASK = 1112 FLAG_PERMISSION_USER_SET 1113 | FLAG_PERMISSION_USER_FIXED 1114 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1115 1116 final @Nullable String mRequiredVerifierPackage; 1117 final @NonNull String mRequiredInstallerPackage; 1118 final @Nullable String mSetupWizardPackage; 1119 final @NonNull String mServicesSystemSharedLibraryPackageName; 1120 final @NonNull String mSharedSystemSharedLibraryPackageName; 1121 1122 private final PackageUsage mPackageUsage = new PackageUsage(); 1123 1124 private class PackageUsage { 1125 private static final int WRITE_INTERVAL 1126 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1127 1128 private final Object mFileLock = new Object(); 1129 private final AtomicLong mLastWritten = new AtomicLong(0); 1130 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1131 1132 private boolean mIsHistoricalPackageUsageAvailable = true; 1133 1134 boolean isHistoricalPackageUsageAvailable() { 1135 return mIsHistoricalPackageUsageAvailable; 1136 } 1137 1138 void write(boolean force) { 1139 if (force) { 1140 writeInternal(); 1141 return; 1142 } 1143 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1144 && !DEBUG_DEXOPT) { 1145 return; 1146 } 1147 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1148 new Thread("PackageUsage_DiskWriter") { 1149 @Override 1150 public void run() { 1151 try { 1152 writeInternal(); 1153 } finally { 1154 mBackgroundWriteRunning.set(false); 1155 } 1156 } 1157 }.start(); 1158 } 1159 } 1160 1161 private void writeInternal() { 1162 synchronized (mPackages) { 1163 synchronized (mFileLock) { 1164 AtomicFile file = getFile(); 1165 FileOutputStream f = null; 1166 try { 1167 f = file.startWrite(); 1168 BufferedOutputStream out = new BufferedOutputStream(f); 1169 FileUtils.setPermissions(file.getBaseFile().getPath(), 1170 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1171 StringBuilder sb = new StringBuilder(); 1172 1173 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 1177 for (PackageParser.Package pkg : mPackages.values()) { 1178 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1179 continue; 1180 } 1181 sb.setLength(0); 1182 sb.append(pkg.packageName); 1183 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1184 sb.append(' '); 1185 sb.append(usageTimeInMillis); 1186 } 1187 sb.append('\n'); 1188 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1189 } 1190 out.flush(); 1191 file.finishWrite(f); 1192 } catch (IOException e) { 1193 if (f != null) { 1194 file.failWrite(f); 1195 } 1196 Log.e(TAG, "Failed to write package usage times", e); 1197 } 1198 } 1199 } 1200 mLastWritten.set(SystemClock.elapsedRealtime()); 1201 } 1202 1203 void readLP() { 1204 synchronized (mFileLock) { 1205 AtomicFile file = getFile(); 1206 BufferedInputStream in = null; 1207 try { 1208 in = new BufferedInputStream(file.openRead()); 1209 StringBuffer sb = new StringBuffer(); 1210 1211 String firstLine = readLine(in, sb); 1212 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1213 readVersion1LP(in, sb); 1214 } else { 1215 readVersion0LP(in, sb, firstLine); 1216 } 1217 } catch (FileNotFoundException expected) { 1218 mIsHistoricalPackageUsageAvailable = false; 1219 } catch (IOException e) { 1220 Log.w(TAG, "Failed to read package usage times", e); 1221 } finally { 1222 IoUtils.closeQuietly(in); 1223 } 1224 } 1225 mLastWritten.set(SystemClock.elapsedRealtime()); 1226 } 1227 1228 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1229 throws IOException { 1230 // Initial version of the file had no version number and stored one 1231 // package-timestamp pair per line. 1232 // Note that the first line has already been read from the InputStream. 1233 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1234 String[] tokens = line.split(" "); 1235 if (tokens.length != 2) { 1236 throw new IOException("Failed to parse " + line + 1237 " as package-timestamp pair."); 1238 } 1239 1240 String packageName = tokens[0]; 1241 PackageParser.Package pkg = mPackages.get(packageName); 1242 if (pkg == null) { 1243 continue; 1244 } 1245 1246 long timestamp = parseAsLong(tokens[1]); 1247 for (int reason = 0; 1248 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1249 reason++) { 1250 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1251 } 1252 } 1253 } 1254 1255 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1256 // Version 1 of the file started with the corresponding version 1257 // number and then stored a package name and eight timestamps per line. 1258 String line; 1259 while ((line = readLine(in, sb)) != null) { 1260 String[] tokens = line.split(" "); 1261 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1262 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1263 } 1264 1265 String packageName = tokens[0]; 1266 PackageParser.Package pkg = mPackages.get(packageName); 1267 if (pkg == null) { 1268 continue; 1269 } 1270 1271 for (int reason = 0; 1272 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1273 reason++) { 1274 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1275 } 1276 } 1277 } 1278 1279 private long parseAsLong(String token) throws IOException { 1280 try { 1281 return Long.parseLong(token); 1282 } catch (NumberFormatException e) { 1283 throw new IOException("Failed to parse " + token + " as a long.", e); 1284 } 1285 } 1286 1287 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1288 return readToken(in, sb, '\n'); 1289 } 1290 1291 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1292 throws IOException { 1293 sb.setLength(0); 1294 while (true) { 1295 int ch = in.read(); 1296 if (ch == -1) { 1297 if (sb.length() == 0) { 1298 return null; 1299 } 1300 throw new IOException("Unexpected EOF"); 1301 } 1302 if (ch == endOfToken) { 1303 return sb.toString(); 1304 } 1305 sb.append((char)ch); 1306 } 1307 } 1308 1309 private AtomicFile getFile() { 1310 File dataDir = Environment.getDataDirectory(); 1311 File systemDir = new File(dataDir, "system"); 1312 File fname = new File(systemDir, "package-usage.list"); 1313 return new AtomicFile(fname); 1314 } 1315 1316 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1317 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1318 } 1319 1320 class PackageHandler extends Handler { 1321 private boolean mBound = false; 1322 final ArrayList<HandlerParams> mPendingInstalls = 1323 new ArrayList<HandlerParams>(); 1324 1325 private boolean connectToService() { 1326 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1327 " DefaultContainerService"); 1328 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1331 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 mBound = true; 1334 return true; 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 return false; 1338 } 1339 1340 private void disconnectService() { 1341 mContainerService = null; 1342 mBound = false; 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1344 mContext.unbindService(mDefContainerConn); 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 } 1347 1348 PackageHandler(Looper looper) { 1349 super(looper); 1350 } 1351 1352 public void handleMessage(Message msg) { 1353 try { 1354 doHandleMessage(msg); 1355 } finally { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 } 1358 } 1359 1360 void doHandleMessage(Message msg) { 1361 switch (msg.what) { 1362 case INIT_COPY: { 1363 HandlerParams params = (HandlerParams) msg.obj; 1364 int idx = mPendingInstalls.size(); 1365 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1366 // If a bind was already initiated we dont really 1367 // need to do anything. The pending install 1368 // will be processed later on. 1369 if (!mBound) { 1370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1371 System.identityHashCode(mHandler)); 1372 // If this is the only one pending we might 1373 // have to bind to the service again. 1374 if (!connectToService()) { 1375 Slog.e(TAG, "Failed to bind to media container service"); 1376 params.serviceError(); 1377 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1378 System.identityHashCode(mHandler)); 1379 if (params.traceMethod != null) { 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1381 params.traceCookie); 1382 } 1383 return; 1384 } else { 1385 // Once we bind to the service, the first 1386 // pending request will be processed. 1387 mPendingInstalls.add(idx, params); 1388 } 1389 } else { 1390 mPendingInstalls.add(idx, params); 1391 // Already bound to the service. Just make 1392 // sure we trigger off processing the first request. 1393 if (idx == 0) { 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 break; 1398 } 1399 case MCS_BOUND: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1401 if (msg.obj != null) { 1402 mContainerService = (IMediaContainerService) msg.obj; 1403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1404 System.identityHashCode(mHandler)); 1405 } 1406 if (mContainerService == null) { 1407 if (!mBound) { 1408 // Something seriously wrong since we are not bound and we are not 1409 // waiting for connection. Bail out. 1410 Slog.e(TAG, "Cannot bind to media container service"); 1411 for (HandlerParams params : mPendingInstalls) { 1412 // Indicate service bind error 1413 params.serviceError(); 1414 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1415 System.identityHashCode(params)); 1416 if (params.traceMethod != null) { 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1418 params.traceMethod, params.traceCookie); 1419 } 1420 return; 1421 } 1422 mPendingInstalls.clear(); 1423 } else { 1424 Slog.w(TAG, "Waiting to connect to media container service"); 1425 } 1426 } else if (mPendingInstalls.size() > 0) { 1427 HandlerParams params = mPendingInstalls.get(0); 1428 if (params != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1430 System.identityHashCode(params)); 1431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1432 if (params.startCopy()) { 1433 // We are done... look for more work or to 1434 // go idle. 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, 1436 "Checking for more work or unbind..."); 1437 // Delete pending install 1438 if (mPendingInstalls.size() > 0) { 1439 mPendingInstalls.remove(0); 1440 } 1441 if (mPendingInstalls.size() == 0) { 1442 if (mBound) { 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, 1444 "Posting delayed MCS_UNBIND"); 1445 removeMessages(MCS_UNBIND); 1446 Message ubmsg = obtainMessage(MCS_UNBIND); 1447 // Unbind after a little delay, to avoid 1448 // continual thrashing. 1449 sendMessageDelayed(ubmsg, 10000); 1450 } 1451 } else { 1452 // There are more pending requests in queue. 1453 // Just post MCS_BOUND message to trigger processing 1454 // of next pending install. 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting MCS_BOUND for next work"); 1457 mHandler.sendEmptyMessage(MCS_BOUND); 1458 } 1459 } 1460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1461 } 1462 } else { 1463 // Should never happen ideally. 1464 Slog.w(TAG, "Empty queue"); 1465 } 1466 break; 1467 } 1468 case MCS_RECONNECT: { 1469 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1470 if (mPendingInstalls.size() > 0) { 1471 if (mBound) { 1472 disconnectService(); 1473 } 1474 if (!connectToService()) { 1475 Slog.e(TAG, "Failed to bind to media container service"); 1476 for (HandlerParams params : mPendingInstalls) { 1477 // Indicate service bind error 1478 params.serviceError(); 1479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1480 System.identityHashCode(params)); 1481 } 1482 mPendingInstalls.clear(); 1483 } 1484 } 1485 break; 1486 } 1487 case MCS_UNBIND: { 1488 // If there is no actual work left, then time to unbind. 1489 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1490 1491 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1492 if (mBound) { 1493 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1494 1495 disconnectService(); 1496 } 1497 } else if (mPendingInstalls.size() > 0) { 1498 // There are more pending requests in queue. 1499 // Just post MCS_BOUND message to trigger processing 1500 // of next pending install. 1501 mHandler.sendEmptyMessage(MCS_BOUND); 1502 } 1503 1504 break; 1505 } 1506 case MCS_GIVE_UP: { 1507 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1508 HandlerParams params = mPendingInstalls.remove(0); 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1510 System.identityHashCode(params)); 1511 break; 1512 } 1513 case SEND_PENDING_BROADCAST: { 1514 String packages[]; 1515 ArrayList<String> components[]; 1516 int size = 0; 1517 int uids[]; 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 if (mPendingBroadcasts == null) { 1521 return; 1522 } 1523 size = mPendingBroadcasts.size(); 1524 if (size <= 0) { 1525 // Nothing to be done. Just return 1526 return; 1527 } 1528 packages = new String[size]; 1529 components = new ArrayList[size]; 1530 uids = new int[size]; 1531 int i = 0; // filling out the above arrays 1532 1533 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1534 int packageUserId = mPendingBroadcasts.userIdAt(n); 1535 Iterator<Map.Entry<String, ArrayList<String>>> it 1536 = mPendingBroadcasts.packagesForUserId(packageUserId) 1537 .entrySet().iterator(); 1538 while (it.hasNext() && i < size) { 1539 Map.Entry<String, ArrayList<String>> ent = it.next(); 1540 packages[i] = ent.getKey(); 1541 components[i] = ent.getValue(); 1542 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1543 uids[i] = (ps != null) 1544 ? UserHandle.getUid(packageUserId, ps.appId) 1545 : -1; 1546 i++; 1547 } 1548 } 1549 size = i; 1550 mPendingBroadcasts.clear(); 1551 } 1552 // Send broadcasts 1553 for (int i = 0; i < size; i++) { 1554 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 break; 1558 } 1559 case START_CLEANING_PACKAGE: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 final String packageName = (String)msg.obj; 1562 final int userId = msg.arg1; 1563 final boolean andCode = msg.arg2 != 0; 1564 synchronized (mPackages) { 1565 if (userId == UserHandle.USER_ALL) { 1566 int[] users = sUserManager.getUserIds(); 1567 for (int user : users) { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(user, packageName, andCode)); 1570 } 1571 } else { 1572 mSettings.addPackageToCleanLPw( 1573 new PackageCleanItem(userId, packageName, andCode)); 1574 } 1575 } 1576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1577 startCleaningPackages(); 1578 } break; 1579 case POST_INSTALL: { 1580 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1581 1582 PostInstallData data = mRunningInstalls.get(msg.arg1); 1583 final boolean didRestore = (msg.arg2 != 0); 1584 mRunningInstalls.delete(msg.arg1); 1585 1586 if (data != null) { 1587 InstallArgs args = data.args; 1588 PackageInstalledInfo parentRes = data.res; 1589 1590 final boolean grantPermissions = (args.installFlags 1591 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1592 final boolean killApp = (args.installFlags 1593 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1594 final String[] grantedPermissions = args.installGrantPermissions; 1595 1596 // Handle the parent package 1597 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1598 grantedPermissions, didRestore, args.installerPackageName, 1599 args.observer); 1600 1601 // Handle the child packages 1602 final int childCount = (parentRes.addedChildPackages != null) 1603 ? parentRes.addedChildPackages.size() : 0; 1604 for (int i = 0; i < childCount; i++) { 1605 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1606 handlePackagePostInstall(childRes, grantPermissions, killApp, 1607 grantedPermissions, false, args.installerPackageName, 1608 args.observer); 1609 } 1610 1611 // Log tracing if needed 1612 if (args.traceMethod != null) { 1613 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1614 args.traceCookie); 1615 } 1616 } else { 1617 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1618 } 1619 1620 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1621 } break; 1622 case UPDATED_MEDIA_STATUS: { 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1624 boolean reportStatus = msg.arg1 == 1; 1625 boolean doGc = msg.arg2 == 1; 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1627 if (doGc) { 1628 // Force a gc to clear up stale containers. 1629 Runtime.getRuntime().gc(); 1630 } 1631 if (msg.obj != null) { 1632 @SuppressWarnings("unchecked") 1633 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1635 // Unload containers 1636 unloadAllContainers(args); 1637 } 1638 if (reportStatus) { 1639 try { 1640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1641 PackageHelper.getMountService().finishMediaUpdate(); 1642 } catch (RemoteException e) { 1643 Log.e(TAG, "MountService not running?"); 1644 } 1645 } 1646 } break; 1647 case WRITE_SETTINGS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_SETTINGS); 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 mSettings.writeLPr(); 1653 mDirtyUsers.clear(); 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 } break; 1657 case WRITE_PACKAGE_RESTRICTIONS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1661 for (int userId : mDirtyUsers) { 1662 mSettings.writePackageRestrictionsLPr(userId); 1663 } 1664 mDirtyUsers.clear(); 1665 } 1666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1667 } break; 1668 case CHECK_PENDING_VERIFICATION: { 1669 final int verificationId = msg.arg1; 1670 final PackageVerificationState state = mPendingVerification.get(verificationId); 1671 1672 if ((state != null) && !state.timeoutExtended()) { 1673 final InstallArgs args = state.getInstallArgs(); 1674 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1675 1676 Slog.i(TAG, "Verification timed out for " + originUri); 1677 mPendingVerification.remove(verificationId); 1678 1679 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1680 1681 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1682 Slog.i(TAG, "Continuing with installation of " + originUri); 1683 state.setVerifierResponse(Binder.getCallingUid(), 1684 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1685 broadcastPackageVerified(verificationId, originUri, 1686 PackageManager.VERIFICATION_ALLOW, 1687 state.getInstallArgs().getUser()); 1688 try { 1689 ret = args.copyApk(mContainerService, true); 1690 } catch (RemoteException e) { 1691 Slog.e(TAG, "Could not contact the ContainerService"); 1692 } 1693 } else { 1694 broadcastPackageVerified(verificationId, originUri, 1695 PackageManager.VERIFICATION_REJECT, 1696 state.getInstallArgs().getUser()); 1697 } 1698 1699 Trace.asyncTraceEnd( 1700 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1701 1702 processPendingInstall(args, ret); 1703 mHandler.sendEmptyMessage(MCS_UNBIND); 1704 } 1705 break; 1706 } 1707 case PACKAGE_VERIFIED: { 1708 final int verificationId = msg.arg1; 1709 1710 final PackageVerificationState state = mPendingVerification.get(verificationId); 1711 if (state == null) { 1712 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1713 break; 1714 } 1715 1716 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1717 1718 state.setVerifierResponse(response.callerUid, response.code); 1719 1720 if (state.isVerificationComplete()) { 1721 mPendingVerification.remove(verificationId); 1722 1723 final InstallArgs args = state.getInstallArgs(); 1724 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1725 1726 int ret; 1727 if (state.isInstallAllowed()) { 1728 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1729 broadcastPackageVerified(verificationId, originUri, 1730 response.code, state.getInstallArgs().getUser()); 1731 try { 1732 ret = args.copyApk(mContainerService, true); 1733 } catch (RemoteException e) { 1734 Slog.e(TAG, "Could not contact the ContainerService"); 1735 } 1736 } else { 1737 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1738 } 1739 1740 Trace.asyncTraceEnd( 1741 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1742 1743 processPendingInstall(args, ret); 1744 mHandler.sendEmptyMessage(MCS_UNBIND); 1745 } 1746 1747 break; 1748 } 1749 case START_INTENT_FILTER_VERIFICATIONS: { 1750 IFVerificationParams params = (IFVerificationParams) msg.obj; 1751 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1752 params.replacing, params.pkg); 1753 break; 1754 } 1755 case INTENT_FILTER_VERIFIED: { 1756 final int verificationId = msg.arg1; 1757 1758 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1759 verificationId); 1760 if (state == null) { 1761 Slog.w(TAG, "Invalid IntentFilter verification token " 1762 + verificationId + " received"); 1763 break; 1764 } 1765 1766 final int userId = state.getUserId(); 1767 1768 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1769 "Processing IntentFilter verification with token:" 1770 + verificationId + " and userId:" + userId); 1771 1772 final IntentFilterVerificationResponse response = 1773 (IntentFilterVerificationResponse) msg.obj; 1774 1775 state.setVerifierResponse(response.callerUid, response.code); 1776 1777 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1778 "IntentFilter verification with token:" + verificationId 1779 + " and userId:" + userId 1780 + " is settings verifier response with response code:" 1781 + response.code); 1782 1783 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1784 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1785 + response.getFailedDomainsString()); 1786 } 1787 1788 if (state.isVerificationComplete()) { 1789 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1790 } else { 1791 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1792 "IntentFilter verification with token:" + verificationId 1793 + " was not said to be complete"); 1794 } 1795 1796 break; 1797 } 1798 } 1799 } 1800 } 1801 1802 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1803 boolean killApp, String[] grantedPermissions, 1804 boolean launchedForRestore, String installerPackage, 1805 IPackageInstallObserver2 installObserver) { 1806 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1807 // Send the removed broadcasts 1808 if (res.removedInfo != null) { 1809 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1810 } 1811 1812 // Now that we successfully installed the package, grant runtime 1813 // permissions if requested before broadcasting the install. 1814 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1815 >= Build.VERSION_CODES.M) { 1816 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1817 } 1818 1819 final boolean update = res.removedInfo != null 1820 && res.removedInfo.removedPackage != null; 1821 1822 // If this is the first time we have child packages for a disabled privileged 1823 // app that had no children, we grant requested runtime permissions to the new 1824 // children if the parent on the system image had them already granted. 1825 if (res.pkg.parentPackage != null) { 1826 synchronized (mPackages) { 1827 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1828 } 1829 } 1830 1831 synchronized (mPackages) { 1832 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1833 } 1834 1835 final String packageName = res.pkg.applicationInfo.packageName; 1836 Bundle extras = new Bundle(1); 1837 extras.putInt(Intent.EXTRA_UID, res.uid); 1838 1839 // Determine the set of users who are adding this package for 1840 // the first time vs. those who are seeing an update. 1841 int[] firstUsers = EMPTY_INT_ARRAY; 1842 int[] updateUsers = EMPTY_INT_ARRAY; 1843 if (res.origUsers == null || res.origUsers.length == 0) { 1844 firstUsers = res.newUsers; 1845 } else { 1846 for (int newUser : res.newUsers) { 1847 boolean isNew = true; 1848 for (int origUser : res.origUsers) { 1849 if (origUser == newUser) { 1850 isNew = false; 1851 break; 1852 } 1853 } 1854 if (isNew) { 1855 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1856 } else { 1857 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1858 } 1859 } 1860 } 1861 1862 // Send installed broadcasts if the install/update is not ephemeral 1863 if (!isEphemeral(res.pkg)) { 1864 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1865 1866 // Send added for users that see the package for the first time 1867 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1868 extras, 0 /*flags*/, null /*targetPackage*/, 1869 null /*finishedReceiver*/, firstUsers); 1870 1871 // Send added for users that don't see the package for the first time 1872 if (update) { 1873 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1874 } 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1876 extras, 0 /*flags*/, null /*targetPackage*/, 1877 null /*finishedReceiver*/, updateUsers); 1878 1879 // Send replaced for users that don't see the package for the first time 1880 if (update) { 1881 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1882 packageName, extras, 0 /*flags*/, 1883 null /*targetPackage*/, null /*finishedReceiver*/, 1884 updateUsers); 1885 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1886 null /*package*/, null /*extras*/, 0 /*flags*/, 1887 packageName /*targetPackage*/, 1888 null /*finishedReceiver*/, updateUsers); 1889 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1890 // First-install and we did a restore, so we're responsible for the 1891 // first-launch broadcast. 1892 if (DEBUG_BACKUP) { 1893 Slog.i(TAG, "Post-restore of " + packageName 1894 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1895 } 1896 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1897 } 1898 1899 // Send broadcast package appeared if forward locked/external for all users 1900 // treat asec-hosted packages like removable media on upgrade 1901 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1902 if (DEBUG_INSTALL) { 1903 Slog.i(TAG, "upgrading pkg " + res.pkg 1904 + " is ASEC-hosted -> AVAILABLE"); 1905 } 1906 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1907 ArrayList<String> pkgList = new ArrayList<>(1); 1908 pkgList.add(packageName); 1909 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1910 } 1911 } 1912 1913 // Work that needs to happen on first install within each user 1914 if (firstUsers != null && firstUsers.length > 0) { 1915 synchronized (mPackages) { 1916 for (int userId : firstUsers) { 1917 // If this app is a browser and it's newly-installed for some 1918 // users, clear any default-browser state in those users. The 1919 // app's nature doesn't depend on the user, so we can just check 1920 // its browser nature in any user and generalize. 1921 if (packageIsBrowser(packageName, userId)) { 1922 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1923 } 1924 1925 // We may also need to apply pending (restored) runtime 1926 // permission grants within these users. 1927 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1928 } 1929 } 1930 } 1931 1932 // Log current value of "unknown sources" setting 1933 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1934 getUnknownSourcesSettings()); 1935 1936 // Force a gc to clear up things 1937 Runtime.getRuntime().gc(); 1938 1939 // Remove the replaced package's older resources safely now 1940 // We delete after a gc for applications on sdcard. 1941 if (res.removedInfo != null && res.removedInfo.args != null) { 1942 synchronized (mInstallLock) { 1943 res.removedInfo.args.doPostDeleteLI(true); 1944 } 1945 } 1946 } 1947 1948 // If someone is watching installs - notify them 1949 if (installObserver != null) { 1950 try { 1951 Bundle extras = extrasForInstallResult(res); 1952 installObserver.onPackageInstalled(res.name, res.returnCode, 1953 res.returnMsg, extras); 1954 } catch (RemoteException e) { 1955 Slog.i(TAG, "Observer no longer exists."); 1956 } 1957 } 1958 } 1959 1960 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1961 PackageParser.Package pkg) { 1962 if (pkg.parentPackage == null) { 1963 return; 1964 } 1965 if (pkg.requestedPermissions == null) { 1966 return; 1967 } 1968 final PackageSetting disabledSysParentPs = mSettings 1969 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1970 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1971 || !disabledSysParentPs.isPrivileged() 1972 || (disabledSysParentPs.childPackageNames != null 1973 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1974 return; 1975 } 1976 final int[] allUserIds = sUserManager.getUserIds(); 1977 final int permCount = pkg.requestedPermissions.size(); 1978 for (int i = 0; i < permCount; i++) { 1979 String permission = pkg.requestedPermissions.get(i); 1980 BasePermission bp = mSettings.mPermissions.get(permission); 1981 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1982 continue; 1983 } 1984 for (int userId : allUserIds) { 1985 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1986 permission, userId)) { 1987 grantRuntimePermission(pkg.packageName, permission, userId); 1988 } 1989 } 1990 } 1991 } 1992 1993 private StorageEventListener mStorageListener = new StorageEventListener() { 1994 @Override 1995 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1996 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1997 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1998 final String volumeUuid = vol.getFsUuid(); 1999 2000 // Clean up any users or apps that were removed or recreated 2001 // while this volume was missing 2002 reconcileUsers(volumeUuid); 2003 reconcileApps(volumeUuid); 2004 2005 // Clean up any install sessions that expired or were 2006 // cancelled while this volume was missing 2007 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2008 2009 loadPrivatePackages(vol); 2010 2011 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2012 unloadPrivatePackages(vol); 2013 } 2014 } 2015 2016 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2017 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2018 updateExternalMediaStatus(true, false); 2019 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2020 updateExternalMediaStatus(false, false); 2021 } 2022 } 2023 } 2024 2025 @Override 2026 public void onVolumeForgotten(String fsUuid) { 2027 if (TextUtils.isEmpty(fsUuid)) { 2028 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2029 return; 2030 } 2031 2032 // Remove any apps installed on the forgotten volume 2033 synchronized (mPackages) { 2034 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2035 for (PackageSetting ps : packages) { 2036 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2037 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2038 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2039 } 2040 2041 mSettings.onVolumeForgotten(fsUuid); 2042 mSettings.writeLPr(); 2043 } 2044 } 2045 }; 2046 2047 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2048 String[] grantedPermissions) { 2049 for (int userId : userIds) { 2050 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2051 } 2052 2053 // We could have touched GID membership, so flush out packages.list 2054 synchronized (mPackages) { 2055 mSettings.writePackageListLPr(); 2056 } 2057 } 2058 2059 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2060 String[] grantedPermissions) { 2061 SettingBase sb = (SettingBase) pkg.mExtras; 2062 if (sb == null) { 2063 return; 2064 } 2065 2066 PermissionsState permissionsState = sb.getPermissionsState(); 2067 2068 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2069 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2070 2071 for (String permission : pkg.requestedPermissions) { 2072 final BasePermission bp; 2073 synchronized (mPackages) { 2074 bp = mSettings.mPermissions.get(permission); 2075 } 2076 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2077 && (grantedPermissions == null 2078 || ArrayUtils.contains(grantedPermissions, permission))) { 2079 final int flags = permissionsState.getPermissionFlags(permission, userId); 2080 // Installer cannot change immutable permissions. 2081 if ((flags & immutableFlags) == 0) { 2082 grantRuntimePermission(pkg.packageName, permission, userId); 2083 } 2084 } 2085 } 2086 } 2087 2088 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2089 Bundle extras = null; 2090 switch (res.returnCode) { 2091 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2092 extras = new Bundle(); 2093 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2094 res.origPermission); 2095 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2096 res.origPackage); 2097 break; 2098 } 2099 case PackageManager.INSTALL_SUCCEEDED: { 2100 extras = new Bundle(); 2101 extras.putBoolean(Intent.EXTRA_REPLACING, 2102 res.removedInfo != null && res.removedInfo.removedPackage != null); 2103 break; 2104 } 2105 } 2106 return extras; 2107 } 2108 2109 void scheduleWriteSettingsLocked() { 2110 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2111 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2112 } 2113 } 2114 2115 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2116 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2117 scheduleWritePackageRestrictionsLocked(userId); 2118 } 2119 2120 void scheduleWritePackageRestrictionsLocked(int userId) { 2121 final int[] userIds = (userId == UserHandle.USER_ALL) 2122 ? sUserManager.getUserIds() : new int[]{userId}; 2123 for (int nextUserId : userIds) { 2124 if (!sUserManager.exists(nextUserId)) return; 2125 mDirtyUsers.add(nextUserId); 2126 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2127 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2128 } 2129 } 2130 } 2131 2132 public static PackageManagerService main(Context context, Installer installer, 2133 boolean factoryTest, boolean onlyCore) { 2134 // Self-check for initial settings. 2135 PackageManagerServiceCompilerMapping.checkProperties(); 2136 2137 PackageManagerService m = new PackageManagerService(context, installer, 2138 factoryTest, onlyCore); 2139 m.enableSystemUserPackages(); 2140 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2141 // disabled after already being started. 2142 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2143 UserHandle.USER_SYSTEM); 2144 ServiceManager.addService("package", m); 2145 return m; 2146 } 2147 2148 private void enableSystemUserPackages() { 2149 if (!UserManager.isSplitSystemUser()) { 2150 return; 2151 } 2152 // For system user, enable apps based on the following conditions: 2153 // - app is whitelisted or belong to one of these groups: 2154 // -- system app which has no launcher icons 2155 // -- system app which has INTERACT_ACROSS_USERS permission 2156 // -- system IME app 2157 // - app is not in the blacklist 2158 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2159 Set<String> enableApps = new ArraySet<>(); 2160 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2161 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2162 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2163 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2164 enableApps.addAll(wlApps); 2165 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2166 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2167 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2168 enableApps.removeAll(blApps); 2169 Log.i(TAG, "Applications installed for system user: " + enableApps); 2170 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2171 UserHandle.SYSTEM); 2172 final int allAppsSize = allAps.size(); 2173 synchronized (mPackages) { 2174 for (int i = 0; i < allAppsSize; i++) { 2175 String pName = allAps.get(i); 2176 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2177 // Should not happen, but we shouldn't be failing if it does 2178 if (pkgSetting == null) { 2179 continue; 2180 } 2181 boolean install = enableApps.contains(pName); 2182 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2183 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2184 + " for system user"); 2185 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2186 } 2187 } 2188 } 2189 } 2190 2191 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2192 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2193 Context.DISPLAY_SERVICE); 2194 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2195 } 2196 2197 public PackageManagerService(Context context, Installer installer, 2198 boolean factoryTest, boolean onlyCore) { 2199 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2200 SystemClock.uptimeMillis()); 2201 2202 if (mSdkVersion <= 0) { 2203 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2204 } 2205 2206 mContext = context; 2207 mFactoryTest = factoryTest; 2208 mOnlyCore = onlyCore; 2209 mMetrics = new DisplayMetrics(); 2210 mSettings = new Settings(mPackages); 2211 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2218 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2219 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2220 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2221 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2222 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2223 2224 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2225 if (separateProcesses != null && separateProcesses.length() > 0) { 2226 if ("*".equals(separateProcesses)) { 2227 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2228 mSeparateProcesses = null; 2229 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2230 } else { 2231 mDefParseFlags = 0; 2232 mSeparateProcesses = separateProcesses.split(","); 2233 Slog.w(TAG, "Running with debug.separate_processes: " 2234 + separateProcesses); 2235 } 2236 } else { 2237 mDefParseFlags = 0; 2238 mSeparateProcesses = null; 2239 } 2240 2241 mInstaller = installer; 2242 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2243 "*dexopt*"); 2244 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2245 2246 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2247 FgThread.get().getLooper()); 2248 2249 getDefaultDisplayMetrics(context, mMetrics); 2250 2251 SystemConfig systemConfig = SystemConfig.getInstance(); 2252 mGlobalGids = systemConfig.getGlobalGids(); 2253 mSystemPermissions = systemConfig.getSystemPermissions(); 2254 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2255 2256 synchronized (mInstallLock) { 2257 // writer 2258 synchronized (mPackages) { 2259 mHandlerThread = new ServiceThread(TAG, 2260 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2261 mHandlerThread.start(); 2262 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2263 mProcessLoggingHandler = new ProcessLoggingHandler(); 2264 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2265 2266 File dataDir = Environment.getDataDirectory(); 2267 mAppInstallDir = new File(dataDir, "app"); 2268 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2269 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2270 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2271 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2272 2273 sUserManager = new UserManagerService(context, this, mPackages); 2274 2275 // Propagate permission configuration in to package manager. 2276 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2277 = systemConfig.getPermissions(); 2278 for (int i=0; i<permConfig.size(); i++) { 2279 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2280 BasePermission bp = mSettings.mPermissions.get(perm.name); 2281 if (bp == null) { 2282 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2283 mSettings.mPermissions.put(perm.name, bp); 2284 } 2285 if (perm.gids != null) { 2286 bp.setGids(perm.gids, perm.perUser); 2287 } 2288 } 2289 2290 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2291 for (int i=0; i<libConfig.size(); i++) { 2292 mSharedLibraries.put(libConfig.keyAt(i), 2293 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2294 } 2295 2296 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2297 2298 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2299 2300 String customResolverActivity = Resources.getSystem().getString( 2301 R.string.config_customResolverActivity); 2302 if (TextUtils.isEmpty(customResolverActivity)) { 2303 customResolverActivity = null; 2304 } else { 2305 mCustomResolverComponentName = ComponentName.unflattenFromString( 2306 customResolverActivity); 2307 } 2308 2309 long startTime = SystemClock.uptimeMillis(); 2310 2311 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2312 startTime); 2313 2314 // Set flag to monitor and not change apk file paths when 2315 // scanning install directories. 2316 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2317 2318 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2319 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2320 2321 if (bootClassPath == null) { 2322 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2323 } 2324 2325 if (systemServerClassPath == null) { 2326 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2327 } 2328 2329 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2330 final String[] dexCodeInstructionSets = 2331 getDexCodeInstructionSets( 2332 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2333 2334 /** 2335 * Ensure all external libraries have had dexopt run on them. 2336 */ 2337 if (mSharedLibraries.size() > 0) { 2338 // NOTE: For now, we're compiling these system "shared libraries" 2339 // (and framework jars) into all available architectures. It's possible 2340 // to compile them only when we come across an app that uses them (there's 2341 // already logic for that in scanPackageLI) but that adds some complexity. 2342 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2343 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2344 final String lib = libEntry.path; 2345 if (lib == null) { 2346 continue; 2347 } 2348 2349 try { 2350 // Shared libraries do not have profiles so we perform a full 2351 // AOT compilation (if needed). 2352 int dexoptNeeded = DexFile.getDexOptNeeded( 2353 lib, dexCodeInstructionSet, 2354 getCompilerFilterForReason(REASON_SHARED_APK), 2355 false /* newProfile */); 2356 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2357 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2358 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2359 getCompilerFilterForReason(REASON_SHARED_APK), 2360 StorageManager.UUID_PRIVATE_INTERNAL, 2361 SKIP_SHARED_LIBRARY_CHECK); 2362 } 2363 } catch (FileNotFoundException e) { 2364 Slog.w(TAG, "Library not found: " + lib); 2365 } catch (IOException | InstallerException e) { 2366 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2367 + e.getMessage()); 2368 } 2369 } 2370 } 2371 } 2372 2373 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2374 2375 final VersionInfo ver = mSettings.getInternalVersion(); 2376 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2377 2378 // when upgrading from pre-M, promote system app permissions from install to runtime 2379 mPromoteSystemApps = 2380 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2381 2382 // save off the names of pre-existing system packages prior to scanning; we don't 2383 // want to automatically grant runtime permissions for new system apps 2384 if (mPromoteSystemApps) { 2385 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2386 while (pkgSettingIter.hasNext()) { 2387 PackageSetting ps = pkgSettingIter.next(); 2388 if (isSystemApp(ps)) { 2389 mExistingSystemPackages.add(ps.name); 2390 } 2391 } 2392 } 2393 2394 // When upgrading from pre-N, we need to handle package extraction like first boot, 2395 // as there is no profiling data available. 2396 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2397 mSettings.setNWorkDone(); 2398 2399 // Collect vendor overlay packages. 2400 // (Do this before scanning any apps.) 2401 // For security and version matching reason, only consider 2402 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2403 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2404 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2405 | PackageParser.PARSE_IS_SYSTEM 2406 | PackageParser.PARSE_IS_SYSTEM_DIR 2407 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2408 2409 // Find base frameworks (resource packages without code). 2410 scanDirTracedLI(frameworkDir, mDefParseFlags 2411 | PackageParser.PARSE_IS_SYSTEM 2412 | PackageParser.PARSE_IS_SYSTEM_DIR 2413 | PackageParser.PARSE_IS_PRIVILEGED, 2414 scanFlags | SCAN_NO_DEX, 0); 2415 2416 // Collected privileged system packages. 2417 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2418 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2419 | PackageParser.PARSE_IS_SYSTEM 2420 | PackageParser.PARSE_IS_SYSTEM_DIR 2421 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2422 2423 // Collect ordinary system packages. 2424 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2425 scanDirTracedLI(systemAppDir, mDefParseFlags 2426 | PackageParser.PARSE_IS_SYSTEM 2427 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2428 2429 // Collect all vendor packages. 2430 File vendorAppDir = new File("/vendor/app"); 2431 try { 2432 vendorAppDir = vendorAppDir.getCanonicalFile(); 2433 } catch (IOException e) { 2434 // failed to look up canonical path, continue with original one 2435 } 2436 scanDirTracedLI(vendorAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2439 2440 // Collect all OEM packages. 2441 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2442 scanDirTracedLI(oemAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2445 2446 // Prune any system packages that no longer exist. 2447 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2448 if (!mOnlyCore) { 2449 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2450 while (psit.hasNext()) { 2451 PackageSetting ps = psit.next(); 2452 2453 /* 2454 * If this is not a system app, it can't be a 2455 * disable system app. 2456 */ 2457 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2458 continue; 2459 } 2460 2461 /* 2462 * If the package is scanned, it's not erased. 2463 */ 2464 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2465 if (scannedPkg != null) { 2466 /* 2467 * If the system app is both scanned and in the 2468 * disabled packages list, then it must have been 2469 * added via OTA. Remove it from the currently 2470 * scanned package so the previously user-installed 2471 * application can be scanned. 2472 */ 2473 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2474 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2475 + ps.name + "; removing system app. Last known codePath=" 2476 + ps.codePathString + ", installStatus=" + ps.installStatus 2477 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2478 + scannedPkg.mVersionCode); 2479 removePackageLI(scannedPkg, true); 2480 mExpectingBetter.put(ps.name, ps.codePath); 2481 } 2482 2483 continue; 2484 } 2485 2486 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2487 psit.remove(); 2488 logCriticalInfo(Log.WARN, "System package " + ps.name 2489 + " no longer exists; it's data will be wiped"); 2490 // Actual deletion of code and data will be handled by later 2491 // reconciliation step 2492 } else { 2493 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2494 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2495 possiblyDeletedUpdatedSystemApps.add(ps.name); 2496 } 2497 } 2498 } 2499 } 2500 2501 //look for any incomplete package installations 2502 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2503 for (int i = 0; i < deletePkgsList.size(); i++) { 2504 // Actual deletion of code and data will be handled by later 2505 // reconciliation step 2506 final String packageName = deletePkgsList.get(i).name; 2507 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2508 synchronized (mPackages) { 2509 mSettings.removePackageLPw(packageName); 2510 } 2511 } 2512 2513 //delete tmp files 2514 deleteTempPackageFiles(); 2515 2516 // Remove any shared userIDs that have no associated packages 2517 mSettings.pruneSharedUsersLPw(); 2518 2519 if (!mOnlyCore) { 2520 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2521 SystemClock.uptimeMillis()); 2522 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2523 2524 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2525 | PackageParser.PARSE_FORWARD_LOCK, 2526 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2527 2528 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2529 | PackageParser.PARSE_IS_EPHEMERAL, 2530 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2531 2532 /** 2533 * Remove disable package settings for any updated system 2534 * apps that were removed via an OTA. If they're not a 2535 * previously-updated app, remove them completely. 2536 * Otherwise, just revoke their system-level permissions. 2537 */ 2538 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2539 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2540 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2541 2542 String msg; 2543 if (deletedPkg == null) { 2544 msg = "Updated system package " + deletedAppName 2545 + " no longer exists; it's data will be wiped"; 2546 // Actual deletion of code and data will be handled by later 2547 // reconciliation step 2548 } else { 2549 msg = "Updated system app + " + deletedAppName 2550 + " no longer present; removing system privileges for " 2551 + deletedAppName; 2552 2553 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2554 2555 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2556 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2557 } 2558 logCriticalInfo(Log.WARN, msg); 2559 } 2560 2561 /** 2562 * Make sure all system apps that we expected to appear on 2563 * the userdata partition actually showed up. If they never 2564 * appeared, crawl back and revive the system version. 2565 */ 2566 for (int i = 0; i < mExpectingBetter.size(); i++) { 2567 final String packageName = mExpectingBetter.keyAt(i); 2568 if (!mPackages.containsKey(packageName)) { 2569 final File scanFile = mExpectingBetter.valueAt(i); 2570 2571 logCriticalInfo(Log.WARN, "Expected better " + packageName 2572 + " but never showed up; reverting to system"); 2573 2574 int reparseFlags = mDefParseFlags; 2575 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2576 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2577 | PackageParser.PARSE_IS_SYSTEM_DIR 2578 | PackageParser.PARSE_IS_PRIVILEGED; 2579 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2580 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR; 2582 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2583 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2584 | PackageParser.PARSE_IS_SYSTEM_DIR; 2585 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2586 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2587 | PackageParser.PARSE_IS_SYSTEM_DIR; 2588 } else { 2589 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2590 continue; 2591 } 2592 2593 mSettings.enableSystemPackageLPw(packageName); 2594 2595 try { 2596 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2597 } catch (PackageManagerException e) { 2598 Slog.e(TAG, "Failed to parse original system package: " 2599 + e.getMessage()); 2600 } 2601 } 2602 } 2603 } 2604 mExpectingBetter.clear(); 2605 2606 // Resolve protected action filters. Only the setup wizard is allowed to 2607 // have a high priority filter for these actions. 2608 mSetupWizardPackage = getSetupWizardPackageName(); 2609 if (mProtectedFilters.size() > 0) { 2610 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2611 Slog.i(TAG, "No setup wizard;" 2612 + " All protected intents capped to priority 0"); 2613 } 2614 for (ActivityIntentInfo filter : mProtectedFilters) { 2615 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2616 if (DEBUG_FILTERS) { 2617 Slog.i(TAG, "Found setup wizard;" 2618 + " allow priority " + filter.getPriority() + ";" 2619 + " package: " + filter.activity.info.packageName 2620 + " activity: " + filter.activity.className 2621 + " priority: " + filter.getPriority()); 2622 } 2623 // skip setup wizard; allow it to keep the high priority filter 2624 continue; 2625 } 2626 Slog.w(TAG, "Protected action; cap priority to 0;" 2627 + " package: " + filter.activity.info.packageName 2628 + " activity: " + filter.activity.className 2629 + " origPrio: " + filter.getPriority()); 2630 filter.setPriority(0); 2631 } 2632 } 2633 mDeferProtectedFilters = false; 2634 mProtectedFilters.clear(); 2635 2636 // Now that we know all of the shared libraries, update all clients to have 2637 // the correct library paths. 2638 updateAllSharedLibrariesLPw(); 2639 2640 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2641 // NOTE: We ignore potential failures here during a system scan (like 2642 // the rest of the commands above) because there's precious little we 2643 // can do about it. A settings error is reported, though. 2644 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2645 false /* boot complete */); 2646 } 2647 2648 // Now that we know all the packages we are keeping, 2649 // read and update their last usage times. 2650 mPackageUsage.readLP(); 2651 2652 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2653 SystemClock.uptimeMillis()); 2654 Slog.i(TAG, "Time to scan packages: " 2655 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2656 + " seconds"); 2657 2658 // If the platform SDK has changed since the last time we booted, 2659 // we need to re-grant app permission to catch any new ones that 2660 // appear. This is really a hack, and means that apps can in some 2661 // cases get permissions that the user didn't initially explicitly 2662 // allow... it would be nice to have some better way to handle 2663 // this situation. 2664 int updateFlags = UPDATE_PERMISSIONS_ALL; 2665 if (ver.sdkVersion != mSdkVersion) { 2666 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2667 + mSdkVersion + "; regranting permissions for internal storage"); 2668 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2669 } 2670 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2671 ver.sdkVersion = mSdkVersion; 2672 2673 // If this is the first boot or an update from pre-M, and it is a normal 2674 // boot, then we need to initialize the default preferred apps across 2675 // all defined users. 2676 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2677 for (UserInfo user : sUserManager.getUsers(true)) { 2678 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2679 applyFactoryDefaultBrowserLPw(user.id); 2680 primeDomainVerificationsLPw(user.id); 2681 } 2682 } 2683 2684 // Prepare storage for system user really early during boot, 2685 // since core system apps like SettingsProvider and SystemUI 2686 // can't wait for user to start 2687 final int storageFlags; 2688 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2689 storageFlags = StorageManager.FLAG_STORAGE_DE; 2690 } else { 2691 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2692 } 2693 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2694 storageFlags); 2695 2696 // If this is first boot after an OTA, and a normal boot, then 2697 // we need to clear code cache directories. 2698 if (mIsUpgrade && !onlyCore) { 2699 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2700 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2701 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2702 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2703 // No apps are running this early, so no need to freeze 2704 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2705 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2706 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2707 } 2708 clearAppProfilesLIF(ps.pkg); 2709 } 2710 ver.fingerprint = Build.FINGERPRINT; 2711 } 2712 2713 checkDefaultBrowser(); 2714 2715 // clear only after permissions and other defaults have been updated 2716 mExistingSystemPackages.clear(); 2717 mPromoteSystemApps = false; 2718 2719 // All the changes are done during package scanning. 2720 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2721 2722 // can downgrade to reader 2723 mSettings.writeLPr(); 2724 2725 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2726 SystemClock.uptimeMillis()); 2727 2728 if (!mOnlyCore) { 2729 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2730 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2731 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2732 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2733 mIntentFilterVerifierComponent); 2734 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2735 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2736 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2737 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2738 } else { 2739 mRequiredVerifierPackage = null; 2740 mRequiredInstallerPackage = null; 2741 mIntentFilterVerifierComponent = null; 2742 mIntentFilterVerifier = null; 2743 mServicesSystemSharedLibraryPackageName = null; 2744 mSharedSystemSharedLibraryPackageName = null; 2745 } 2746 2747 mInstallerService = new PackageInstallerService(context, this); 2748 2749 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2750 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2751 // both the installer and resolver must be present to enable ephemeral 2752 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2753 if (DEBUG_EPHEMERAL) { 2754 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2755 + " installer:" + ephemeralInstallerComponent); 2756 } 2757 mEphemeralResolverComponent = ephemeralResolverComponent; 2758 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2759 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2760 mEphemeralResolverConnection = 2761 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2762 } else { 2763 if (DEBUG_EPHEMERAL) { 2764 final String missingComponent = 2765 (ephemeralResolverComponent == null) 2766 ? (ephemeralInstallerComponent == null) 2767 ? "resolver and installer" 2768 : "resolver" 2769 : "installer"; 2770 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2771 } 2772 mEphemeralResolverComponent = null; 2773 mEphemeralInstallerComponent = null; 2774 mEphemeralResolverConnection = null; 2775 } 2776 2777 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2778 } // synchronized (mPackages) 2779 } // synchronized (mInstallLock) 2780 2781 // Now after opening every single application zip, make sure they 2782 // are all flushed. Not really needed, but keeps things nice and 2783 // tidy. 2784 Runtime.getRuntime().gc(); 2785 2786 // The initial scanning above does many calls into installd while 2787 // holding the mPackages lock, but we're mostly interested in yelling 2788 // once we have a booted system. 2789 mInstaller.setWarnIfHeld(mPackages); 2790 2791 // Expose private service for system components to use. 2792 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2793 } 2794 2795 @Override 2796 public boolean isFirstBoot() { 2797 return !mRestoredSettings; 2798 } 2799 2800 @Override 2801 public boolean isOnlyCoreApps() { 2802 return mOnlyCore; 2803 } 2804 2805 @Override 2806 public boolean isUpgrade() { 2807 return mIsUpgrade; 2808 } 2809 2810 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2811 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2812 2813 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2814 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2815 UserHandle.USER_SYSTEM); 2816 if (matches.size() == 1) { 2817 return matches.get(0).getComponentInfo().packageName; 2818 } else { 2819 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2820 return null; 2821 } 2822 } 2823 2824 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2825 synchronized (mPackages) { 2826 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2827 if (libraryEntry == null) { 2828 throw new IllegalStateException("Missing required shared library:" + libraryName); 2829 } 2830 return libraryEntry.apk; 2831 } 2832 } 2833 2834 private @NonNull String getRequiredInstallerLPr() { 2835 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2836 intent.addCategory(Intent.CATEGORY_DEFAULT); 2837 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2838 2839 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2840 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2841 UserHandle.USER_SYSTEM); 2842 if (matches.size() == 1) { 2843 ResolveInfo resolveInfo = matches.get(0); 2844 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2845 throw new RuntimeException("The installer must be a privileged app"); 2846 } 2847 return matches.get(0).getComponentInfo().packageName; 2848 } else { 2849 throw new RuntimeException("There must be exactly one installer; found " + matches); 2850 } 2851 } 2852 2853 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2854 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2855 2856 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2857 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2858 UserHandle.USER_SYSTEM); 2859 ResolveInfo best = null; 2860 final int N = matches.size(); 2861 for (int i = 0; i < N; i++) { 2862 final ResolveInfo cur = matches.get(i); 2863 final String packageName = cur.getComponentInfo().packageName; 2864 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2865 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2866 continue; 2867 } 2868 2869 if (best == null || cur.priority > best.priority) { 2870 best = cur; 2871 } 2872 } 2873 2874 if (best != null) { 2875 return best.getComponentInfo().getComponentName(); 2876 } else { 2877 throw new RuntimeException("There must be at least one intent filter verifier"); 2878 } 2879 } 2880 2881 private @Nullable ComponentName getEphemeralResolverLPr() { 2882 final String[] packageArray = 2883 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2884 if (packageArray.length == 0) { 2885 if (DEBUG_EPHEMERAL) { 2886 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2887 } 2888 return null; 2889 } 2890 2891 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2892 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2893 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2894 UserHandle.USER_SYSTEM); 2895 2896 final int N = resolvers.size(); 2897 if (N == 0) { 2898 if (DEBUG_EPHEMERAL) { 2899 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2900 } 2901 return null; 2902 } 2903 2904 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2905 for (int i = 0; i < N; i++) { 2906 final ResolveInfo info = resolvers.get(i); 2907 2908 if (info.serviceInfo == null) { 2909 continue; 2910 } 2911 2912 final String packageName = info.serviceInfo.packageName; 2913 if (!possiblePackages.contains(packageName)) { 2914 if (DEBUG_EPHEMERAL) { 2915 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2916 + " pkg: " + packageName + ", info:" + info); 2917 } 2918 continue; 2919 } 2920 2921 if (DEBUG_EPHEMERAL) { 2922 Slog.v(TAG, "Ephemeral resolver found;" 2923 + " pkg: " + packageName + ", info:" + info); 2924 } 2925 return new ComponentName(packageName, info.serviceInfo.name); 2926 } 2927 if (DEBUG_EPHEMERAL) { 2928 Slog.v(TAG, "Ephemeral resolver NOT found"); 2929 } 2930 return null; 2931 } 2932 2933 private @Nullable ComponentName getEphemeralInstallerLPr() { 2934 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2935 intent.addCategory(Intent.CATEGORY_DEFAULT); 2936 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2937 2938 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2939 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2940 UserHandle.USER_SYSTEM); 2941 if (matches.size() == 0) { 2942 return null; 2943 } else if (matches.size() == 1) { 2944 return matches.get(0).getComponentInfo().getComponentName(); 2945 } else { 2946 throw new RuntimeException( 2947 "There must be at most one ephemeral installer; found " + matches); 2948 } 2949 } 2950 2951 private void primeDomainVerificationsLPw(int userId) { 2952 if (DEBUG_DOMAIN_VERIFICATION) { 2953 Slog.d(TAG, "Priming domain verifications in user " + userId); 2954 } 2955 2956 SystemConfig systemConfig = SystemConfig.getInstance(); 2957 ArraySet<String> packages = systemConfig.getLinkedApps(); 2958 ArraySet<String> domains = new ArraySet<String>(); 2959 2960 for (String packageName : packages) { 2961 PackageParser.Package pkg = mPackages.get(packageName); 2962 if (pkg != null) { 2963 if (!pkg.isSystemApp()) { 2964 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2965 continue; 2966 } 2967 2968 domains.clear(); 2969 for (PackageParser.Activity a : pkg.activities) { 2970 for (ActivityIntentInfo filter : a.intents) { 2971 if (hasValidDomains(filter)) { 2972 domains.addAll(filter.getHostsList()); 2973 } 2974 } 2975 } 2976 2977 if (domains.size() > 0) { 2978 if (DEBUG_DOMAIN_VERIFICATION) { 2979 Slog.v(TAG, " + " + packageName); 2980 } 2981 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2982 // state w.r.t. the formal app-linkage "no verification attempted" state; 2983 // and then 'always' in the per-user state actually used for intent resolution. 2984 final IntentFilterVerificationInfo ivi; 2985 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2986 new ArrayList<String>(domains)); 2987 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2988 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2989 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2990 } else { 2991 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2992 + "' does not handle web links"); 2993 } 2994 } else { 2995 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2996 } 2997 } 2998 2999 scheduleWritePackageRestrictionsLocked(userId); 3000 scheduleWriteSettingsLocked(); 3001 } 3002 3003 private void applyFactoryDefaultBrowserLPw(int userId) { 3004 // The default browser app's package name is stored in a string resource, 3005 // with a product-specific overlay used for vendor customization. 3006 String browserPkg = mContext.getResources().getString( 3007 com.android.internal.R.string.default_browser); 3008 if (!TextUtils.isEmpty(browserPkg)) { 3009 // non-empty string => required to be a known package 3010 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3011 if (ps == null) { 3012 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3013 browserPkg = null; 3014 } else { 3015 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3016 } 3017 } 3018 3019 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3020 // default. If there's more than one, just leave everything alone. 3021 if (browserPkg == null) { 3022 calculateDefaultBrowserLPw(userId); 3023 } 3024 } 3025 3026 private void calculateDefaultBrowserLPw(int userId) { 3027 List<String> allBrowsers = resolveAllBrowserApps(userId); 3028 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3029 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3030 } 3031 3032 private List<String> resolveAllBrowserApps(int userId) { 3033 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3034 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3035 PackageManager.MATCH_ALL, userId); 3036 3037 final int count = list.size(); 3038 List<String> result = new ArrayList<String>(count); 3039 for (int i=0; i<count; i++) { 3040 ResolveInfo info = list.get(i); 3041 if (info.activityInfo == null 3042 || !info.handleAllWebDataURI 3043 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3044 || result.contains(info.activityInfo.packageName)) { 3045 continue; 3046 } 3047 result.add(info.activityInfo.packageName); 3048 } 3049 3050 return result; 3051 } 3052 3053 private boolean packageIsBrowser(String packageName, int userId) { 3054 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3055 PackageManager.MATCH_ALL, userId); 3056 final int N = list.size(); 3057 for (int i = 0; i < N; i++) { 3058 ResolveInfo info = list.get(i); 3059 if (packageName.equals(info.activityInfo.packageName)) { 3060 return true; 3061 } 3062 } 3063 return false; 3064 } 3065 3066 private void checkDefaultBrowser() { 3067 final int myUserId = UserHandle.myUserId(); 3068 final String packageName = getDefaultBrowserPackageName(myUserId); 3069 if (packageName != null) { 3070 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3071 if (info == null) { 3072 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3073 synchronized (mPackages) { 3074 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3075 } 3076 } 3077 } 3078 } 3079 3080 @Override 3081 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3082 throws RemoteException { 3083 try { 3084 return super.onTransact(code, data, reply, flags); 3085 } catch (RuntimeException e) { 3086 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3087 Slog.wtf(TAG, "Package Manager Crash", e); 3088 } 3089 throw e; 3090 } 3091 } 3092 3093 static int[] appendInts(int[] cur, int[] add) { 3094 if (add == null) return cur; 3095 if (cur == null) return add; 3096 final int N = add.length; 3097 for (int i=0; i<N; i++) { 3098 cur = appendInt(cur, add[i]); 3099 } 3100 return cur; 3101 } 3102 3103 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3104 if (!sUserManager.exists(userId)) return null; 3105 if (ps == null) { 3106 return null; 3107 } 3108 final PackageParser.Package p = ps.pkg; 3109 if (p == null) { 3110 return null; 3111 } 3112 3113 final PermissionsState permissionsState = ps.getPermissionsState(); 3114 3115 final int[] gids = permissionsState.computeGids(userId); 3116 final Set<String> permissions = permissionsState.getPermissions(userId); 3117 final PackageUserState state = ps.readUserState(userId); 3118 3119 return PackageParser.generatePackageInfo(p, gids, flags, 3120 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3121 } 3122 3123 @Override 3124 public void checkPackageStartable(String packageName, int userId) { 3125 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3126 3127 synchronized (mPackages) { 3128 final PackageSetting ps = mSettings.mPackages.get(packageName); 3129 if (ps == null) { 3130 throw new SecurityException("Package " + packageName + " was not found!"); 3131 } 3132 3133 if (!ps.getInstalled(userId)) { 3134 throw new SecurityException( 3135 "Package " + packageName + " was not installed for user " + userId + "!"); 3136 } 3137 3138 if (mSafeMode && !ps.isSystem()) { 3139 throw new SecurityException("Package " + packageName + " not a system app!"); 3140 } 3141 3142 if (mFrozenPackages.contains(packageName)) { 3143 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3144 } 3145 3146 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3147 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3148 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3149 } 3150 } 3151 } 3152 3153 @Override 3154 public boolean isPackageAvailable(String packageName, int userId) { 3155 if (!sUserManager.exists(userId)) return false; 3156 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3157 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3158 synchronized (mPackages) { 3159 PackageParser.Package p = mPackages.get(packageName); 3160 if (p != null) { 3161 final PackageSetting ps = (PackageSetting) p.mExtras; 3162 if (ps != null) { 3163 final PackageUserState state = ps.readUserState(userId); 3164 if (state != null) { 3165 return PackageParser.isAvailable(state); 3166 } 3167 } 3168 } 3169 } 3170 return false; 3171 } 3172 3173 @Override 3174 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3175 if (!sUserManager.exists(userId)) return null; 3176 flags = updateFlagsForPackage(flags, userId, packageName); 3177 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3178 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3179 // reader 3180 synchronized (mPackages) { 3181 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3182 PackageParser.Package p = null; 3183 if (matchFactoryOnly) { 3184 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3185 if (ps != null) { 3186 return generatePackageInfo(ps, flags, userId); 3187 } 3188 } 3189 if (p == null) { 3190 p = mPackages.get(packageName); 3191 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3192 return null; 3193 } 3194 } 3195 if (DEBUG_PACKAGE_INFO) 3196 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3197 if (p != null) { 3198 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3199 } 3200 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3201 final PackageSetting ps = mSettings.mPackages.get(packageName); 3202 return generatePackageInfo(ps, flags, userId); 3203 } 3204 } 3205 return null; 3206 } 3207 3208 @Override 3209 public String[] currentToCanonicalPackageNames(String[] names) { 3210 String[] out = new String[names.length]; 3211 // reader 3212 synchronized (mPackages) { 3213 for (int i=names.length-1; i>=0; i--) { 3214 PackageSetting ps = mSettings.mPackages.get(names[i]); 3215 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3216 } 3217 } 3218 return out; 3219 } 3220 3221 @Override 3222 public String[] canonicalToCurrentPackageNames(String[] names) { 3223 String[] out = new String[names.length]; 3224 // reader 3225 synchronized (mPackages) { 3226 for (int i=names.length-1; i>=0; i--) { 3227 String cur = mSettings.mRenamedPackages.get(names[i]); 3228 out[i] = cur != null ? cur : names[i]; 3229 } 3230 } 3231 return out; 3232 } 3233 3234 @Override 3235 public int getPackageUid(String packageName, int flags, int userId) { 3236 if (!sUserManager.exists(userId)) return -1; 3237 flags = updateFlagsForPackage(flags, userId, packageName); 3238 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3239 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3240 3241 // reader 3242 synchronized (mPackages) { 3243 final PackageParser.Package p = mPackages.get(packageName); 3244 if (p != null && p.isMatch(flags)) { 3245 return UserHandle.getUid(userId, p.applicationInfo.uid); 3246 } 3247 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3248 final PackageSetting ps = mSettings.mPackages.get(packageName); 3249 if (ps != null && ps.isMatch(flags)) { 3250 return UserHandle.getUid(userId, ps.appId); 3251 } 3252 } 3253 } 3254 3255 return -1; 3256 } 3257 3258 @Override 3259 public int[] getPackageGids(String packageName, int flags, int userId) { 3260 if (!sUserManager.exists(userId)) return null; 3261 flags = updateFlagsForPackage(flags, userId, packageName); 3262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3263 false /* requireFullPermission */, false /* checkShell */, 3264 "getPackageGids"); 3265 3266 // reader 3267 synchronized (mPackages) { 3268 final PackageParser.Package p = mPackages.get(packageName); 3269 if (p != null && p.isMatch(flags)) { 3270 PackageSetting ps = (PackageSetting) p.mExtras; 3271 return ps.getPermissionsState().computeGids(userId); 3272 } 3273 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3274 final PackageSetting ps = mSettings.mPackages.get(packageName); 3275 if (ps != null && ps.isMatch(flags)) { 3276 return ps.getPermissionsState().computeGids(userId); 3277 } 3278 } 3279 } 3280 3281 return null; 3282 } 3283 3284 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3285 if (bp.perm != null) { 3286 return PackageParser.generatePermissionInfo(bp.perm, flags); 3287 } 3288 PermissionInfo pi = new PermissionInfo(); 3289 pi.name = bp.name; 3290 pi.packageName = bp.sourcePackage; 3291 pi.nonLocalizedLabel = bp.name; 3292 pi.protectionLevel = bp.protectionLevel; 3293 return pi; 3294 } 3295 3296 @Override 3297 public PermissionInfo getPermissionInfo(String name, int flags) { 3298 // reader 3299 synchronized (mPackages) { 3300 final BasePermission p = mSettings.mPermissions.get(name); 3301 if (p != null) { 3302 return generatePermissionInfo(p, flags); 3303 } 3304 return null; 3305 } 3306 } 3307 3308 @Override 3309 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3310 int flags) { 3311 // reader 3312 synchronized (mPackages) { 3313 if (group != null && !mPermissionGroups.containsKey(group)) { 3314 // This is thrown as NameNotFoundException 3315 return null; 3316 } 3317 3318 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3319 for (BasePermission p : mSettings.mPermissions.values()) { 3320 if (group == null) { 3321 if (p.perm == null || p.perm.info.group == null) { 3322 out.add(generatePermissionInfo(p, flags)); 3323 } 3324 } else { 3325 if (p.perm != null && group.equals(p.perm.info.group)) { 3326 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3327 } 3328 } 3329 } 3330 return new ParceledListSlice<>(out); 3331 } 3332 } 3333 3334 @Override 3335 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3336 // reader 3337 synchronized (mPackages) { 3338 return PackageParser.generatePermissionGroupInfo( 3339 mPermissionGroups.get(name), flags); 3340 } 3341 } 3342 3343 @Override 3344 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3345 // reader 3346 synchronized (mPackages) { 3347 final int N = mPermissionGroups.size(); 3348 ArrayList<PermissionGroupInfo> out 3349 = new ArrayList<PermissionGroupInfo>(N); 3350 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3351 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3352 } 3353 return new ParceledListSlice<>(out); 3354 } 3355 } 3356 3357 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3358 int userId) { 3359 if (!sUserManager.exists(userId)) return null; 3360 PackageSetting ps = mSettings.mPackages.get(packageName); 3361 if (ps != null) { 3362 if (ps.pkg == null) { 3363 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3364 if (pInfo != null) { 3365 return pInfo.applicationInfo; 3366 } 3367 return null; 3368 } 3369 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3370 ps.readUserState(userId), userId); 3371 } 3372 return null; 3373 } 3374 3375 @Override 3376 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3377 if (!sUserManager.exists(userId)) return null; 3378 flags = updateFlagsForApplication(flags, userId, packageName); 3379 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3380 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3381 // writer 3382 synchronized (mPackages) { 3383 PackageParser.Package p = mPackages.get(packageName); 3384 if (DEBUG_PACKAGE_INFO) Log.v( 3385 TAG, "getApplicationInfo " + packageName 3386 + ": " + p); 3387 if (p != null) { 3388 PackageSetting ps = mSettings.mPackages.get(packageName); 3389 if (ps == null) return null; 3390 // Note: isEnabledLP() does not apply here - always return info 3391 return PackageParser.generateApplicationInfo( 3392 p, flags, ps.readUserState(userId), userId); 3393 } 3394 if ("android".equals(packageName)||"system".equals(packageName)) { 3395 return mAndroidApplication; 3396 } 3397 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3398 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3399 } 3400 } 3401 return null; 3402 } 3403 3404 @Override 3405 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3406 final IPackageDataObserver observer) { 3407 mContext.enforceCallingOrSelfPermission( 3408 android.Manifest.permission.CLEAR_APP_CACHE, null); 3409 // Queue up an async operation since clearing cache may take a little while. 3410 mHandler.post(new Runnable() { 3411 public void run() { 3412 mHandler.removeCallbacks(this); 3413 boolean success = true; 3414 synchronized (mInstallLock) { 3415 try { 3416 mInstaller.freeCache(volumeUuid, freeStorageSize); 3417 } catch (InstallerException e) { 3418 Slog.w(TAG, "Couldn't clear application caches: " + e); 3419 success = false; 3420 } 3421 } 3422 if (observer != null) { 3423 try { 3424 observer.onRemoveCompleted(null, success); 3425 } catch (RemoteException e) { 3426 Slog.w(TAG, "RemoveException when invoking call back"); 3427 } 3428 } 3429 } 3430 }); 3431 } 3432 3433 @Override 3434 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3435 final IntentSender pi) { 3436 mContext.enforceCallingOrSelfPermission( 3437 android.Manifest.permission.CLEAR_APP_CACHE, null); 3438 // Queue up an async operation since clearing cache may take a little while. 3439 mHandler.post(new Runnable() { 3440 public void run() { 3441 mHandler.removeCallbacks(this); 3442 boolean success = true; 3443 synchronized (mInstallLock) { 3444 try { 3445 mInstaller.freeCache(volumeUuid, freeStorageSize); 3446 } catch (InstallerException e) { 3447 Slog.w(TAG, "Couldn't clear application caches: " + e); 3448 success = false; 3449 } 3450 } 3451 if(pi != null) { 3452 try { 3453 // Callback via pending intent 3454 int code = success ? 1 : 0; 3455 pi.sendIntent(null, code, null, 3456 null, null); 3457 } catch (SendIntentException e1) { 3458 Slog.i(TAG, "Failed to send pending intent"); 3459 } 3460 } 3461 } 3462 }); 3463 } 3464 3465 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3466 synchronized (mInstallLock) { 3467 try { 3468 mInstaller.freeCache(volumeUuid, freeStorageSize); 3469 } catch (InstallerException e) { 3470 throw new IOException("Failed to free enough space", e); 3471 } 3472 } 3473 } 3474 3475 /** 3476 * Update given flags based on encryption status of current user. 3477 */ 3478 private int updateFlags(int flags, int userId) { 3479 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3480 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3481 // Caller expressed an explicit opinion about what encryption 3482 // aware/unaware components they want to see, so fall through and 3483 // give them what they want 3484 } else { 3485 // Caller expressed no opinion, so match based on user state 3486 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3487 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3488 } else { 3489 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3490 } 3491 } 3492 return flags; 3493 } 3494 3495 private UserManagerInternal getUserManagerInternal() { 3496 if (mUserManagerInternal == null) { 3497 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3498 } 3499 return mUserManagerInternal; 3500 } 3501 3502 /** 3503 * Update given flags when being used to request {@link PackageInfo}. 3504 */ 3505 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3506 boolean triaged = true; 3507 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3508 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3509 // Caller is asking for component details, so they'd better be 3510 // asking for specific encryption matching behavior, or be triaged 3511 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3512 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3513 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3514 triaged = false; 3515 } 3516 } 3517 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3518 | PackageManager.MATCH_SYSTEM_ONLY 3519 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3520 triaged = false; 3521 } 3522 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3523 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3524 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3525 } 3526 return updateFlags(flags, userId); 3527 } 3528 3529 /** 3530 * Update given flags when being used to request {@link ApplicationInfo}. 3531 */ 3532 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3533 return updateFlagsForPackage(flags, userId, cookie); 3534 } 3535 3536 /** 3537 * Update given flags when being used to request {@link ComponentInfo}. 3538 */ 3539 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3540 if (cookie instanceof Intent) { 3541 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3542 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3543 } 3544 } 3545 3546 boolean triaged = true; 3547 // Caller is asking for component details, so they'd better be 3548 // asking for specific encryption matching behavior, or be triaged 3549 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3550 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3551 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3552 triaged = false; 3553 } 3554 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3555 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3556 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3557 } 3558 3559 return updateFlags(flags, userId); 3560 } 3561 3562 /** 3563 * Update given flags when being used to request {@link ResolveInfo}. 3564 */ 3565 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3566 // Safe mode means we shouldn't match any third-party components 3567 if (mSafeMode) { 3568 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3569 } 3570 3571 return updateFlagsForComponent(flags, userId, cookie); 3572 } 3573 3574 @Override 3575 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3576 if (!sUserManager.exists(userId)) return null; 3577 flags = updateFlagsForComponent(flags, userId, component); 3578 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3579 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3580 synchronized (mPackages) { 3581 PackageParser.Activity a = mActivities.mActivities.get(component); 3582 3583 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3584 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3585 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3586 if (ps == null) return null; 3587 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3588 userId); 3589 } 3590 if (mResolveComponentName.equals(component)) { 3591 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3592 new PackageUserState(), userId); 3593 } 3594 } 3595 return null; 3596 } 3597 3598 @Override 3599 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3600 String resolvedType) { 3601 synchronized (mPackages) { 3602 if (component.equals(mResolveComponentName)) { 3603 // The resolver supports EVERYTHING! 3604 return true; 3605 } 3606 PackageParser.Activity a = mActivities.mActivities.get(component); 3607 if (a == null) { 3608 return false; 3609 } 3610 for (int i=0; i<a.intents.size(); i++) { 3611 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3612 intent.getData(), intent.getCategories(), TAG) >= 0) { 3613 return true; 3614 } 3615 } 3616 return false; 3617 } 3618 } 3619 3620 @Override 3621 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3622 if (!sUserManager.exists(userId)) return null; 3623 flags = updateFlagsForComponent(flags, userId, component); 3624 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3625 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3626 synchronized (mPackages) { 3627 PackageParser.Activity a = mReceivers.mActivities.get(component); 3628 if (DEBUG_PACKAGE_INFO) Log.v( 3629 TAG, "getReceiverInfo " + component + ": " + a); 3630 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3631 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3632 if (ps == null) return null; 3633 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3634 userId); 3635 } 3636 } 3637 return null; 3638 } 3639 3640 @Override 3641 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3642 if (!sUserManager.exists(userId)) return null; 3643 flags = updateFlagsForComponent(flags, userId, component); 3644 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3645 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3646 synchronized (mPackages) { 3647 PackageParser.Service s = mServices.mServices.get(component); 3648 if (DEBUG_PACKAGE_INFO) Log.v( 3649 TAG, "getServiceInfo " + component + ": " + s); 3650 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3651 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3652 if (ps == null) return null; 3653 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3654 userId); 3655 } 3656 } 3657 return null; 3658 } 3659 3660 @Override 3661 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3662 if (!sUserManager.exists(userId)) return null; 3663 flags = updateFlagsForComponent(flags, userId, component); 3664 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3665 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3666 synchronized (mPackages) { 3667 PackageParser.Provider p = mProviders.mProviders.get(component); 3668 if (DEBUG_PACKAGE_INFO) Log.v( 3669 TAG, "getProviderInfo " + component + ": " + p); 3670 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3671 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3672 if (ps == null) return null; 3673 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3674 userId); 3675 } 3676 } 3677 return null; 3678 } 3679 3680 @Override 3681 public String[] getSystemSharedLibraryNames() { 3682 Set<String> libSet; 3683 synchronized (mPackages) { 3684 libSet = mSharedLibraries.keySet(); 3685 int size = libSet.size(); 3686 if (size > 0) { 3687 String[] libs = new String[size]; 3688 libSet.toArray(libs); 3689 return libs; 3690 } 3691 } 3692 return null; 3693 } 3694 3695 @Override 3696 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3697 synchronized (mPackages) { 3698 return mServicesSystemSharedLibraryPackageName; 3699 } 3700 } 3701 3702 @Override 3703 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3704 synchronized (mPackages) { 3705 return mSharedSystemSharedLibraryPackageName; 3706 } 3707 } 3708 3709 @Override 3710 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3711 synchronized (mPackages) { 3712 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3713 3714 final FeatureInfo fi = new FeatureInfo(); 3715 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3716 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3717 res.add(fi); 3718 3719 return new ParceledListSlice<>(res); 3720 } 3721 } 3722 3723 @Override 3724 public boolean hasSystemFeature(String name, int version) { 3725 synchronized (mPackages) { 3726 final FeatureInfo feat = mAvailableFeatures.get(name); 3727 if (feat == null) { 3728 return false; 3729 } else { 3730 return feat.version >= version; 3731 } 3732 } 3733 } 3734 3735 @Override 3736 public int checkPermission(String permName, String pkgName, int userId) { 3737 if (!sUserManager.exists(userId)) { 3738 return PackageManager.PERMISSION_DENIED; 3739 } 3740 3741 synchronized (mPackages) { 3742 final PackageParser.Package p = mPackages.get(pkgName); 3743 if (p != null && p.mExtras != null) { 3744 final PackageSetting ps = (PackageSetting) p.mExtras; 3745 final PermissionsState permissionsState = ps.getPermissionsState(); 3746 if (permissionsState.hasPermission(permName, userId)) { 3747 return PackageManager.PERMISSION_GRANTED; 3748 } 3749 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3750 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3751 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3752 return PackageManager.PERMISSION_GRANTED; 3753 } 3754 } 3755 } 3756 3757 return PackageManager.PERMISSION_DENIED; 3758 } 3759 3760 @Override 3761 public int checkUidPermission(String permName, int uid) { 3762 final int userId = UserHandle.getUserId(uid); 3763 3764 if (!sUserManager.exists(userId)) { 3765 return PackageManager.PERMISSION_DENIED; 3766 } 3767 3768 synchronized (mPackages) { 3769 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3770 if (obj != null) { 3771 final SettingBase ps = (SettingBase) obj; 3772 final PermissionsState permissionsState = ps.getPermissionsState(); 3773 if (permissionsState.hasPermission(permName, userId)) { 3774 return PackageManager.PERMISSION_GRANTED; 3775 } 3776 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3777 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3778 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 } else { 3782 ArraySet<String> perms = mSystemPermissions.get(uid); 3783 if (perms != null) { 3784 if (perms.contains(permName)) { 3785 return PackageManager.PERMISSION_GRANTED; 3786 } 3787 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3788 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3789 return PackageManager.PERMISSION_GRANTED; 3790 } 3791 } 3792 } 3793 } 3794 3795 return PackageManager.PERMISSION_DENIED; 3796 } 3797 3798 @Override 3799 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3800 if (UserHandle.getCallingUserId() != userId) { 3801 mContext.enforceCallingPermission( 3802 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3803 "isPermissionRevokedByPolicy for user " + userId); 3804 } 3805 3806 if (checkPermission(permission, packageName, userId) 3807 == PackageManager.PERMISSION_GRANTED) { 3808 return false; 3809 } 3810 3811 final long identity = Binder.clearCallingIdentity(); 3812 try { 3813 final int flags = getPermissionFlags(permission, packageName, userId); 3814 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3815 } finally { 3816 Binder.restoreCallingIdentity(identity); 3817 } 3818 } 3819 3820 @Override 3821 public String getPermissionControllerPackageName() { 3822 synchronized (mPackages) { 3823 return mRequiredInstallerPackage; 3824 } 3825 } 3826 3827 /** 3828 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3829 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3830 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3831 * @param message the message to log on security exception 3832 */ 3833 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3834 boolean checkShell, String message) { 3835 if (userId < 0) { 3836 throw new IllegalArgumentException("Invalid userId " + userId); 3837 } 3838 if (checkShell) { 3839 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3840 } 3841 if (userId == UserHandle.getUserId(callingUid)) return; 3842 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3843 if (requireFullPermission) { 3844 mContext.enforceCallingOrSelfPermission( 3845 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3846 } else { 3847 try { 3848 mContext.enforceCallingOrSelfPermission( 3849 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3850 } catch (SecurityException se) { 3851 mContext.enforceCallingOrSelfPermission( 3852 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3853 } 3854 } 3855 } 3856 } 3857 3858 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3859 if (callingUid == Process.SHELL_UID) { 3860 if (userHandle >= 0 3861 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3862 throw new SecurityException("Shell does not have permission to access user " 3863 + userHandle); 3864 } else if (userHandle < 0) { 3865 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3866 + Debug.getCallers(3)); 3867 } 3868 } 3869 } 3870 3871 private BasePermission findPermissionTreeLP(String permName) { 3872 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3873 if (permName.startsWith(bp.name) && 3874 permName.length() > bp.name.length() && 3875 permName.charAt(bp.name.length()) == '.') { 3876 return bp; 3877 } 3878 } 3879 return null; 3880 } 3881 3882 private BasePermission checkPermissionTreeLP(String permName) { 3883 if (permName != null) { 3884 BasePermission bp = findPermissionTreeLP(permName); 3885 if (bp != null) { 3886 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3887 return bp; 3888 } 3889 throw new SecurityException("Calling uid " 3890 + Binder.getCallingUid() 3891 + " is not allowed to add to permission tree " 3892 + bp.name + " owned by uid " + bp.uid); 3893 } 3894 } 3895 throw new SecurityException("No permission tree found for " + permName); 3896 } 3897 3898 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3899 if (s1 == null) { 3900 return s2 == null; 3901 } 3902 if (s2 == null) { 3903 return false; 3904 } 3905 if (s1.getClass() != s2.getClass()) { 3906 return false; 3907 } 3908 return s1.equals(s2); 3909 } 3910 3911 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3912 if (pi1.icon != pi2.icon) return false; 3913 if (pi1.logo != pi2.logo) return false; 3914 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3915 if (!compareStrings(pi1.name, pi2.name)) return false; 3916 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3917 // We'll take care of setting this one. 3918 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3919 // These are not currently stored in settings. 3920 //if (!compareStrings(pi1.group, pi2.group)) return false; 3921 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3922 //if (pi1.labelRes != pi2.labelRes) return false; 3923 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3924 return true; 3925 } 3926 3927 int permissionInfoFootprint(PermissionInfo info) { 3928 int size = info.name.length(); 3929 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3930 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3931 return size; 3932 } 3933 3934 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3935 int size = 0; 3936 for (BasePermission perm : mSettings.mPermissions.values()) { 3937 if (perm.uid == tree.uid) { 3938 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3939 } 3940 } 3941 return size; 3942 } 3943 3944 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3945 // We calculate the max size of permissions defined by this uid and throw 3946 // if that plus the size of 'info' would exceed our stated maximum. 3947 if (tree.uid != Process.SYSTEM_UID) { 3948 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3949 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3950 throw new SecurityException("Permission tree size cap exceeded"); 3951 } 3952 } 3953 } 3954 3955 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3956 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3957 throw new SecurityException("Label must be specified in permission"); 3958 } 3959 BasePermission tree = checkPermissionTreeLP(info.name); 3960 BasePermission bp = mSettings.mPermissions.get(info.name); 3961 boolean added = bp == null; 3962 boolean changed = true; 3963 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3964 if (added) { 3965 enforcePermissionCapLocked(info, tree); 3966 bp = new BasePermission(info.name, tree.sourcePackage, 3967 BasePermission.TYPE_DYNAMIC); 3968 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3969 throw new SecurityException( 3970 "Not allowed to modify non-dynamic permission " 3971 + info.name); 3972 } else { 3973 if (bp.protectionLevel == fixedLevel 3974 && bp.perm.owner.equals(tree.perm.owner) 3975 && bp.uid == tree.uid 3976 && comparePermissionInfos(bp.perm.info, info)) { 3977 changed = false; 3978 } 3979 } 3980 bp.protectionLevel = fixedLevel; 3981 info = new PermissionInfo(info); 3982 info.protectionLevel = fixedLevel; 3983 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3984 bp.perm.info.packageName = tree.perm.info.packageName; 3985 bp.uid = tree.uid; 3986 if (added) { 3987 mSettings.mPermissions.put(info.name, bp); 3988 } 3989 if (changed) { 3990 if (!async) { 3991 mSettings.writeLPr(); 3992 } else { 3993 scheduleWriteSettingsLocked(); 3994 } 3995 } 3996 return added; 3997 } 3998 3999 @Override 4000 public boolean addPermission(PermissionInfo info) { 4001 synchronized (mPackages) { 4002 return addPermissionLocked(info, false); 4003 } 4004 } 4005 4006 @Override 4007 public boolean addPermissionAsync(PermissionInfo info) { 4008 synchronized (mPackages) { 4009 return addPermissionLocked(info, true); 4010 } 4011 } 4012 4013 @Override 4014 public void removePermission(String name) { 4015 synchronized (mPackages) { 4016 checkPermissionTreeLP(name); 4017 BasePermission bp = mSettings.mPermissions.get(name); 4018 if (bp != null) { 4019 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4020 throw new SecurityException( 4021 "Not allowed to modify non-dynamic permission " 4022 + name); 4023 } 4024 mSettings.mPermissions.remove(name); 4025 mSettings.writeLPr(); 4026 } 4027 } 4028 } 4029 4030 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4031 BasePermission bp) { 4032 int index = pkg.requestedPermissions.indexOf(bp.name); 4033 if (index == -1) { 4034 throw new SecurityException("Package " + pkg.packageName 4035 + " has not requested permission " + bp.name); 4036 } 4037 if (!bp.isRuntime() && !bp.isDevelopment()) { 4038 throw new SecurityException("Permission " + bp.name 4039 + " is not a changeable permission type"); 4040 } 4041 } 4042 4043 @Override 4044 public void grantRuntimePermission(String packageName, String name, final int userId) { 4045 if (!sUserManager.exists(userId)) { 4046 Log.e(TAG, "No such user:" + userId); 4047 return; 4048 } 4049 4050 mContext.enforceCallingOrSelfPermission( 4051 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4052 "grantRuntimePermission"); 4053 4054 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4055 true /* requireFullPermission */, true /* checkShell */, 4056 "grantRuntimePermission"); 4057 4058 final int uid; 4059 final SettingBase sb; 4060 4061 synchronized (mPackages) { 4062 final PackageParser.Package pkg = mPackages.get(packageName); 4063 if (pkg == null) { 4064 throw new IllegalArgumentException("Unknown package: " + packageName); 4065 } 4066 4067 final BasePermission bp = mSettings.mPermissions.get(name); 4068 if (bp == null) { 4069 throw new IllegalArgumentException("Unknown permission: " + name); 4070 } 4071 4072 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4073 4074 // If a permission review is required for legacy apps we represent 4075 // their permissions as always granted runtime ones since we need 4076 // to keep the review required permission flag per user while an 4077 // install permission's state is shared across all users. 4078 if (Build.PERMISSIONS_REVIEW_REQUIRED 4079 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4080 && bp.isRuntime()) { 4081 return; 4082 } 4083 4084 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4085 sb = (SettingBase) pkg.mExtras; 4086 if (sb == null) { 4087 throw new IllegalArgumentException("Unknown package: " + packageName); 4088 } 4089 4090 final PermissionsState permissionsState = sb.getPermissionsState(); 4091 4092 final int flags = permissionsState.getPermissionFlags(name, userId); 4093 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4094 throw new SecurityException("Cannot grant system fixed permission " 4095 + name + " for package " + packageName); 4096 } 4097 4098 if (bp.isDevelopment()) { 4099 // Development permissions must be handled specially, since they are not 4100 // normal runtime permissions. For now they apply to all users. 4101 if (permissionsState.grantInstallPermission(bp) != 4102 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4103 scheduleWriteSettingsLocked(); 4104 } 4105 return; 4106 } 4107 4108 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4109 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4110 return; 4111 } 4112 4113 final int result = permissionsState.grantRuntimePermission(bp, userId); 4114 switch (result) { 4115 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4116 return; 4117 } 4118 4119 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4120 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4121 mHandler.post(new Runnable() { 4122 @Override 4123 public void run() { 4124 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4125 } 4126 }); 4127 } 4128 break; 4129 } 4130 4131 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4132 4133 // Not critical if that is lost - app has to request again. 4134 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4135 } 4136 4137 // Only need to do this if user is initialized. Otherwise it's a new user 4138 // and there are no processes running as the user yet and there's no need 4139 // to make an expensive call to remount processes for the changed permissions. 4140 if (READ_EXTERNAL_STORAGE.equals(name) 4141 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4142 final long token = Binder.clearCallingIdentity(); 4143 try { 4144 if (sUserManager.isInitialized(userId)) { 4145 MountServiceInternal mountServiceInternal = LocalServices.getService( 4146 MountServiceInternal.class); 4147 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4148 } 4149 } finally { 4150 Binder.restoreCallingIdentity(token); 4151 } 4152 } 4153 } 4154 4155 @Override 4156 public void revokeRuntimePermission(String packageName, String name, int userId) { 4157 if (!sUserManager.exists(userId)) { 4158 Log.e(TAG, "No such user:" + userId); 4159 return; 4160 } 4161 4162 mContext.enforceCallingOrSelfPermission( 4163 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4164 "revokeRuntimePermission"); 4165 4166 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4167 true /* requireFullPermission */, true /* checkShell */, 4168 "revokeRuntimePermission"); 4169 4170 final int appId; 4171 4172 synchronized (mPackages) { 4173 final PackageParser.Package pkg = mPackages.get(packageName); 4174 if (pkg == null) { 4175 throw new IllegalArgumentException("Unknown package: " + packageName); 4176 } 4177 4178 final BasePermission bp = mSettings.mPermissions.get(name); 4179 if (bp == null) { 4180 throw new IllegalArgumentException("Unknown permission: " + name); 4181 } 4182 4183 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4184 4185 // If a permission review is required for legacy apps we represent 4186 // their permissions as always granted runtime ones since we need 4187 // to keep the review required permission flag per user while an 4188 // install permission's state is shared across all users. 4189 if (Build.PERMISSIONS_REVIEW_REQUIRED 4190 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4191 && bp.isRuntime()) { 4192 return; 4193 } 4194 4195 SettingBase sb = (SettingBase) pkg.mExtras; 4196 if (sb == null) { 4197 throw new IllegalArgumentException("Unknown package: " + packageName); 4198 } 4199 4200 final PermissionsState permissionsState = sb.getPermissionsState(); 4201 4202 final int flags = permissionsState.getPermissionFlags(name, userId); 4203 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4204 throw new SecurityException("Cannot revoke system fixed permission " 4205 + name + " for package " + packageName); 4206 } 4207 4208 if (bp.isDevelopment()) { 4209 // Development permissions must be handled specially, since they are not 4210 // normal runtime permissions. For now they apply to all users. 4211 if (permissionsState.revokeInstallPermission(bp) != 4212 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4213 scheduleWriteSettingsLocked(); 4214 } 4215 return; 4216 } 4217 4218 if (permissionsState.revokeRuntimePermission(bp, userId) == 4219 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4220 return; 4221 } 4222 4223 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4224 4225 // Critical, after this call app should never have the permission. 4226 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4227 4228 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4229 } 4230 4231 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4232 } 4233 4234 @Override 4235 public void resetRuntimePermissions() { 4236 mContext.enforceCallingOrSelfPermission( 4237 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4238 "revokeRuntimePermission"); 4239 4240 int callingUid = Binder.getCallingUid(); 4241 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4242 mContext.enforceCallingOrSelfPermission( 4243 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4244 "resetRuntimePermissions"); 4245 } 4246 4247 synchronized (mPackages) { 4248 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4249 for (int userId : UserManagerService.getInstance().getUserIds()) { 4250 final int packageCount = mPackages.size(); 4251 for (int i = 0; i < packageCount; i++) { 4252 PackageParser.Package pkg = mPackages.valueAt(i); 4253 if (!(pkg.mExtras instanceof PackageSetting)) { 4254 continue; 4255 } 4256 PackageSetting ps = (PackageSetting) pkg.mExtras; 4257 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4258 } 4259 } 4260 } 4261 } 4262 4263 @Override 4264 public int getPermissionFlags(String name, String packageName, int userId) { 4265 if (!sUserManager.exists(userId)) { 4266 return 0; 4267 } 4268 4269 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4270 4271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4272 true /* requireFullPermission */, false /* checkShell */, 4273 "getPermissionFlags"); 4274 4275 synchronized (mPackages) { 4276 final PackageParser.Package pkg = mPackages.get(packageName); 4277 if (pkg == null) { 4278 return 0; 4279 } 4280 4281 final BasePermission bp = mSettings.mPermissions.get(name); 4282 if (bp == null) { 4283 return 0; 4284 } 4285 4286 SettingBase sb = (SettingBase) pkg.mExtras; 4287 if (sb == null) { 4288 return 0; 4289 } 4290 4291 PermissionsState permissionsState = sb.getPermissionsState(); 4292 return permissionsState.getPermissionFlags(name, userId); 4293 } 4294 } 4295 4296 @Override 4297 public void updatePermissionFlags(String name, String packageName, int flagMask, 4298 int flagValues, int userId) { 4299 if (!sUserManager.exists(userId)) { 4300 return; 4301 } 4302 4303 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4304 4305 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4306 true /* requireFullPermission */, true /* checkShell */, 4307 "updatePermissionFlags"); 4308 4309 // Only the system can change these flags and nothing else. 4310 if (getCallingUid() != Process.SYSTEM_UID) { 4311 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4312 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4313 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4314 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4315 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4316 } 4317 4318 synchronized (mPackages) { 4319 final PackageParser.Package pkg = mPackages.get(packageName); 4320 if (pkg == null) { 4321 throw new IllegalArgumentException("Unknown package: " + packageName); 4322 } 4323 4324 final BasePermission bp = mSettings.mPermissions.get(name); 4325 if (bp == null) { 4326 throw new IllegalArgumentException("Unknown permission: " + name); 4327 } 4328 4329 SettingBase sb = (SettingBase) pkg.mExtras; 4330 if (sb == null) { 4331 throw new IllegalArgumentException("Unknown package: " + packageName); 4332 } 4333 4334 PermissionsState permissionsState = sb.getPermissionsState(); 4335 4336 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4337 4338 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4339 // Install and runtime permissions are stored in different places, 4340 // so figure out what permission changed and persist the change. 4341 if (permissionsState.getInstallPermissionState(name) != null) { 4342 scheduleWriteSettingsLocked(); 4343 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4344 || hadState) { 4345 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4346 } 4347 } 4348 } 4349 } 4350 4351 /** 4352 * Update the permission flags for all packages and runtime permissions of a user in order 4353 * to allow device or profile owner to remove POLICY_FIXED. 4354 */ 4355 @Override 4356 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4357 if (!sUserManager.exists(userId)) { 4358 return; 4359 } 4360 4361 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4362 4363 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4364 true /* requireFullPermission */, true /* checkShell */, 4365 "updatePermissionFlagsForAllApps"); 4366 4367 // Only the system can change system fixed flags. 4368 if (getCallingUid() != Process.SYSTEM_UID) { 4369 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4370 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4371 } 4372 4373 synchronized (mPackages) { 4374 boolean changed = false; 4375 final int packageCount = mPackages.size(); 4376 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4377 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4378 SettingBase sb = (SettingBase) pkg.mExtras; 4379 if (sb == null) { 4380 continue; 4381 } 4382 PermissionsState permissionsState = sb.getPermissionsState(); 4383 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4384 userId, flagMask, flagValues); 4385 } 4386 if (changed) { 4387 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4388 } 4389 } 4390 } 4391 4392 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4393 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4394 != PackageManager.PERMISSION_GRANTED 4395 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4396 != PackageManager.PERMISSION_GRANTED) { 4397 throw new SecurityException(message + " requires " 4398 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4399 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4400 } 4401 } 4402 4403 @Override 4404 public boolean shouldShowRequestPermissionRationale(String permissionName, 4405 String packageName, int userId) { 4406 if (UserHandle.getCallingUserId() != userId) { 4407 mContext.enforceCallingPermission( 4408 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4409 "canShowRequestPermissionRationale for user " + userId); 4410 } 4411 4412 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4413 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4414 return false; 4415 } 4416 4417 if (checkPermission(permissionName, packageName, userId) 4418 == PackageManager.PERMISSION_GRANTED) { 4419 return false; 4420 } 4421 4422 final int flags; 4423 4424 final long identity = Binder.clearCallingIdentity(); 4425 try { 4426 flags = getPermissionFlags(permissionName, 4427 packageName, userId); 4428 } finally { 4429 Binder.restoreCallingIdentity(identity); 4430 } 4431 4432 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4433 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4434 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4435 4436 if ((flags & fixedFlags) != 0) { 4437 return false; 4438 } 4439 4440 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4441 } 4442 4443 @Override 4444 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4445 mContext.enforceCallingOrSelfPermission( 4446 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4447 "addOnPermissionsChangeListener"); 4448 4449 synchronized (mPackages) { 4450 mOnPermissionChangeListeners.addListenerLocked(listener); 4451 } 4452 } 4453 4454 @Override 4455 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4456 synchronized (mPackages) { 4457 mOnPermissionChangeListeners.removeListenerLocked(listener); 4458 } 4459 } 4460 4461 @Override 4462 public boolean isProtectedBroadcast(String actionName) { 4463 synchronized (mPackages) { 4464 if (mProtectedBroadcasts.contains(actionName)) { 4465 return true; 4466 } else if (actionName != null) { 4467 // TODO: remove these terrible hacks 4468 if (actionName.startsWith("android.net.netmon.lingerExpired") 4469 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4470 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4471 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4472 return true; 4473 } 4474 } 4475 } 4476 return false; 4477 } 4478 4479 @Override 4480 public int checkSignatures(String pkg1, String pkg2) { 4481 synchronized (mPackages) { 4482 final PackageParser.Package p1 = mPackages.get(pkg1); 4483 final PackageParser.Package p2 = mPackages.get(pkg2); 4484 if (p1 == null || p1.mExtras == null 4485 || p2 == null || p2.mExtras == null) { 4486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4487 } 4488 return compareSignatures(p1.mSignatures, p2.mSignatures); 4489 } 4490 } 4491 4492 @Override 4493 public int checkUidSignatures(int uid1, int uid2) { 4494 // Map to base uids. 4495 uid1 = UserHandle.getAppId(uid1); 4496 uid2 = UserHandle.getAppId(uid2); 4497 // reader 4498 synchronized (mPackages) { 4499 Signature[] s1; 4500 Signature[] s2; 4501 Object obj = mSettings.getUserIdLPr(uid1); 4502 if (obj != null) { 4503 if (obj instanceof SharedUserSetting) { 4504 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4505 } else if (obj instanceof PackageSetting) { 4506 s1 = ((PackageSetting)obj).signatures.mSignatures; 4507 } else { 4508 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4509 } 4510 } else { 4511 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4512 } 4513 obj = mSettings.getUserIdLPr(uid2); 4514 if (obj != null) { 4515 if (obj instanceof SharedUserSetting) { 4516 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4517 } else if (obj instanceof PackageSetting) { 4518 s2 = ((PackageSetting)obj).signatures.mSignatures; 4519 } else { 4520 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4521 } 4522 } else { 4523 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4524 } 4525 return compareSignatures(s1, s2); 4526 } 4527 } 4528 4529 /** 4530 * This method should typically only be used when granting or revoking 4531 * permissions, since the app may immediately restart after this call. 4532 * <p> 4533 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4534 * guard your work against the app being relaunched. 4535 */ 4536 private void killUid(int appId, int userId, String reason) { 4537 final long identity = Binder.clearCallingIdentity(); 4538 try { 4539 IActivityManager am = ActivityManagerNative.getDefault(); 4540 if (am != null) { 4541 try { 4542 am.killUid(appId, userId, reason); 4543 } catch (RemoteException e) { 4544 /* ignore - same process */ 4545 } 4546 } 4547 } finally { 4548 Binder.restoreCallingIdentity(identity); 4549 } 4550 } 4551 4552 /** 4553 * Compares two sets of signatures. Returns: 4554 * <br /> 4555 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4556 * <br /> 4557 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4558 * <br /> 4559 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4560 * <br /> 4561 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4562 * <br /> 4563 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4564 */ 4565 static int compareSignatures(Signature[] s1, Signature[] s2) { 4566 if (s1 == null) { 4567 return s2 == null 4568 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4569 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4570 } 4571 4572 if (s2 == null) { 4573 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4574 } 4575 4576 if (s1.length != s2.length) { 4577 return PackageManager.SIGNATURE_NO_MATCH; 4578 } 4579 4580 // Since both signature sets are of size 1, we can compare without HashSets. 4581 if (s1.length == 1) { 4582 return s1[0].equals(s2[0]) ? 4583 PackageManager.SIGNATURE_MATCH : 4584 PackageManager.SIGNATURE_NO_MATCH; 4585 } 4586 4587 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4588 for (Signature sig : s1) { 4589 set1.add(sig); 4590 } 4591 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4592 for (Signature sig : s2) { 4593 set2.add(sig); 4594 } 4595 // Make sure s2 contains all signatures in s1. 4596 if (set1.equals(set2)) { 4597 return PackageManager.SIGNATURE_MATCH; 4598 } 4599 return PackageManager.SIGNATURE_NO_MATCH; 4600 } 4601 4602 /** 4603 * If the database version for this type of package (internal storage or 4604 * external storage) is less than the version where package signatures 4605 * were updated, return true. 4606 */ 4607 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4608 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4609 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4610 } 4611 4612 /** 4613 * Used for backward compatibility to make sure any packages with 4614 * certificate chains get upgraded to the new style. {@code existingSigs} 4615 * will be in the old format (since they were stored on disk from before the 4616 * system upgrade) and {@code scannedSigs} will be in the newer format. 4617 */ 4618 private int compareSignaturesCompat(PackageSignatures existingSigs, 4619 PackageParser.Package scannedPkg) { 4620 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4621 return PackageManager.SIGNATURE_NO_MATCH; 4622 } 4623 4624 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4625 for (Signature sig : existingSigs.mSignatures) { 4626 existingSet.add(sig); 4627 } 4628 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4629 for (Signature sig : scannedPkg.mSignatures) { 4630 try { 4631 Signature[] chainSignatures = sig.getChainSignatures(); 4632 for (Signature chainSig : chainSignatures) { 4633 scannedCompatSet.add(chainSig); 4634 } 4635 } catch (CertificateEncodingException e) { 4636 scannedCompatSet.add(sig); 4637 } 4638 } 4639 /* 4640 * Make sure the expanded scanned set contains all signatures in the 4641 * existing one. 4642 */ 4643 if (scannedCompatSet.equals(existingSet)) { 4644 // Migrate the old signatures to the new scheme. 4645 existingSigs.assignSignatures(scannedPkg.mSignatures); 4646 // The new KeySets will be re-added later in the scanning process. 4647 synchronized (mPackages) { 4648 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4649 } 4650 return PackageManager.SIGNATURE_MATCH; 4651 } 4652 return PackageManager.SIGNATURE_NO_MATCH; 4653 } 4654 4655 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4656 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4657 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4658 } 4659 4660 private int compareSignaturesRecover(PackageSignatures existingSigs, 4661 PackageParser.Package scannedPkg) { 4662 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4663 return PackageManager.SIGNATURE_NO_MATCH; 4664 } 4665 4666 String msg = null; 4667 try { 4668 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4669 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4670 + scannedPkg.packageName); 4671 return PackageManager.SIGNATURE_MATCH; 4672 } 4673 } catch (CertificateException e) { 4674 msg = e.getMessage(); 4675 } 4676 4677 logCriticalInfo(Log.INFO, 4678 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4679 return PackageManager.SIGNATURE_NO_MATCH; 4680 } 4681 4682 @Override 4683 public List<String> getAllPackages() { 4684 synchronized (mPackages) { 4685 return new ArrayList<String>(mPackages.keySet()); 4686 } 4687 } 4688 4689 @Override 4690 public String[] getPackagesForUid(int uid) { 4691 uid = UserHandle.getAppId(uid); 4692 // reader 4693 synchronized (mPackages) { 4694 Object obj = mSettings.getUserIdLPr(uid); 4695 if (obj instanceof SharedUserSetting) { 4696 final SharedUserSetting sus = (SharedUserSetting) obj; 4697 final int N = sus.packages.size(); 4698 final String[] res = new String[N]; 4699 final Iterator<PackageSetting> it = sus.packages.iterator(); 4700 int i = 0; 4701 while (it.hasNext()) { 4702 res[i++] = it.next().name; 4703 } 4704 return res; 4705 } else if (obj instanceof PackageSetting) { 4706 final PackageSetting ps = (PackageSetting) obj; 4707 return new String[] { ps.name }; 4708 } 4709 } 4710 return null; 4711 } 4712 4713 @Override 4714 public String getNameForUid(int uid) { 4715 // reader 4716 synchronized (mPackages) { 4717 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4718 if (obj instanceof SharedUserSetting) { 4719 final SharedUserSetting sus = (SharedUserSetting) obj; 4720 return sus.name + ":" + sus.userId; 4721 } else if (obj instanceof PackageSetting) { 4722 final PackageSetting ps = (PackageSetting) obj; 4723 return ps.name; 4724 } 4725 } 4726 return null; 4727 } 4728 4729 @Override 4730 public int getUidForSharedUser(String sharedUserName) { 4731 if(sharedUserName == null) { 4732 return -1; 4733 } 4734 // reader 4735 synchronized (mPackages) { 4736 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4737 if (suid == null) { 4738 return -1; 4739 } 4740 return suid.userId; 4741 } 4742 } 4743 4744 @Override 4745 public int getFlagsForUid(int uid) { 4746 synchronized (mPackages) { 4747 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4748 if (obj instanceof SharedUserSetting) { 4749 final SharedUserSetting sus = (SharedUserSetting) obj; 4750 return sus.pkgFlags; 4751 } else if (obj instanceof PackageSetting) { 4752 final PackageSetting ps = (PackageSetting) obj; 4753 return ps.pkgFlags; 4754 } 4755 } 4756 return 0; 4757 } 4758 4759 @Override 4760 public int getPrivateFlagsForUid(int uid) { 4761 synchronized (mPackages) { 4762 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4763 if (obj instanceof SharedUserSetting) { 4764 final SharedUserSetting sus = (SharedUserSetting) obj; 4765 return sus.pkgPrivateFlags; 4766 } else if (obj instanceof PackageSetting) { 4767 final PackageSetting ps = (PackageSetting) obj; 4768 return ps.pkgPrivateFlags; 4769 } 4770 } 4771 return 0; 4772 } 4773 4774 @Override 4775 public boolean isUidPrivileged(int uid) { 4776 uid = UserHandle.getAppId(uid); 4777 // reader 4778 synchronized (mPackages) { 4779 Object obj = mSettings.getUserIdLPr(uid); 4780 if (obj instanceof SharedUserSetting) { 4781 final SharedUserSetting sus = (SharedUserSetting) obj; 4782 final Iterator<PackageSetting> it = sus.packages.iterator(); 4783 while (it.hasNext()) { 4784 if (it.next().isPrivileged()) { 4785 return true; 4786 } 4787 } 4788 } else if (obj instanceof PackageSetting) { 4789 final PackageSetting ps = (PackageSetting) obj; 4790 return ps.isPrivileged(); 4791 } 4792 } 4793 return false; 4794 } 4795 4796 @Override 4797 public String[] getAppOpPermissionPackages(String permissionName) { 4798 synchronized (mPackages) { 4799 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4800 if (pkgs == null) { 4801 return null; 4802 } 4803 return pkgs.toArray(new String[pkgs.size()]); 4804 } 4805 } 4806 4807 @Override 4808 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4809 int flags, int userId) { 4810 try { 4811 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4812 4813 if (!sUserManager.exists(userId)) return null; 4814 flags = updateFlagsForResolve(flags, userId, intent); 4815 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4816 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4817 4818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4819 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4820 flags, userId); 4821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4822 4823 final ResolveInfo bestChoice = 4824 chooseBestActivity(intent, resolvedType, flags, query, userId); 4825 4826 if (isEphemeralAllowed(intent, query, userId)) { 4827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4828 final EphemeralResolveInfo ai = 4829 getEphemeralResolveInfo(intent, resolvedType, userId); 4830 if (ai != null) { 4831 if (DEBUG_EPHEMERAL) { 4832 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4833 } 4834 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4835 bestChoice.ephemeralResolveInfo = ai; 4836 } 4837 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4838 } 4839 return bestChoice; 4840 } finally { 4841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4842 } 4843 } 4844 4845 @Override 4846 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4847 IntentFilter filter, int match, ComponentName activity) { 4848 final int userId = UserHandle.getCallingUserId(); 4849 if (DEBUG_PREFERRED) { 4850 Log.v(TAG, "setLastChosenActivity intent=" + intent 4851 + " resolvedType=" + resolvedType 4852 + " flags=" + flags 4853 + " filter=" + filter 4854 + " match=" + match 4855 + " activity=" + activity); 4856 filter.dump(new PrintStreamPrinter(System.out), " "); 4857 } 4858 intent.setComponent(null); 4859 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4860 userId); 4861 // Find any earlier preferred or last chosen entries and nuke them 4862 findPreferredActivity(intent, resolvedType, 4863 flags, query, 0, false, true, false, userId); 4864 // Add the new activity as the last chosen for this filter 4865 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4866 "Setting last chosen"); 4867 } 4868 4869 @Override 4870 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4871 final int userId = UserHandle.getCallingUserId(); 4872 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4873 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4874 userId); 4875 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4876 false, false, false, userId); 4877 } 4878 4879 4880 private boolean isEphemeralAllowed( 4881 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4882 // Short circuit and return early if possible. 4883 if (DISABLE_EPHEMERAL_APPS) { 4884 return false; 4885 } 4886 final int callingUser = UserHandle.getCallingUserId(); 4887 if (callingUser != UserHandle.USER_SYSTEM) { 4888 return false; 4889 } 4890 if (mEphemeralResolverConnection == null) { 4891 return false; 4892 } 4893 if (intent.getComponent() != null) { 4894 return false; 4895 } 4896 if (intent.getPackage() != null) { 4897 return false; 4898 } 4899 final boolean isWebUri = hasWebURI(intent); 4900 if (!isWebUri) { 4901 return false; 4902 } 4903 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4904 synchronized (mPackages) { 4905 final int count = resolvedActivites.size(); 4906 for (int n = 0; n < count; n++) { 4907 ResolveInfo info = resolvedActivites.get(n); 4908 String packageName = info.activityInfo.packageName; 4909 PackageSetting ps = mSettings.mPackages.get(packageName); 4910 if (ps != null) { 4911 // Try to get the status from User settings first 4912 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4913 int status = (int) (packedStatus >> 32); 4914 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4915 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4916 if (DEBUG_EPHEMERAL) { 4917 Slog.v(TAG, "DENY ephemeral apps;" 4918 + " pkg: " + packageName + ", status: " + status); 4919 } 4920 return false; 4921 } 4922 } 4923 } 4924 } 4925 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4926 return true; 4927 } 4928 4929 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4930 int userId) { 4931 MessageDigest digest = null; 4932 try { 4933 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4934 } catch (NoSuchAlgorithmException e) { 4935 // If we can't create a digest, ignore ephemeral apps. 4936 return null; 4937 } 4938 4939 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4940 final byte[] digestBytes = digest.digest(hostBytes); 4941 int shaPrefix = 4942 digestBytes[0] << 24 4943 | digestBytes[1] << 16 4944 | digestBytes[2] << 8 4945 | digestBytes[3] << 0; 4946 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4947 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4948 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4949 // No hash prefix match; there are no ephemeral apps for this domain. 4950 return null; 4951 } 4952 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4953 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4954 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4955 continue; 4956 } 4957 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4958 // No filters; this should never happen. 4959 if (filters.isEmpty()) { 4960 continue; 4961 } 4962 // We have a domain match; resolve the filters to see if anything matches. 4963 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4964 for (int j = filters.size() - 1; j >= 0; --j) { 4965 final EphemeralResolveIntentInfo intentInfo = 4966 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4967 ephemeralResolver.addFilter(intentInfo); 4968 } 4969 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4970 intent, resolvedType, false /*defaultOnly*/, userId); 4971 if (!matchedResolveInfoList.isEmpty()) { 4972 return matchedResolveInfoList.get(0); 4973 } 4974 } 4975 // Hash or filter mis-match; no ephemeral apps for this domain. 4976 return null; 4977 } 4978 4979 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4980 int flags, List<ResolveInfo> query, int userId) { 4981 if (query != null) { 4982 final int N = query.size(); 4983 if (N == 1) { 4984 return query.get(0); 4985 } else if (N > 1) { 4986 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4987 // If there is more than one activity with the same priority, 4988 // then let the user decide between them. 4989 ResolveInfo r0 = query.get(0); 4990 ResolveInfo r1 = query.get(1); 4991 if (DEBUG_INTENT_MATCHING || debug) { 4992 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4993 + r1.activityInfo.name + "=" + r1.priority); 4994 } 4995 // If the first activity has a higher priority, or a different 4996 // default, then it is always desirable to pick it. 4997 if (r0.priority != r1.priority 4998 || r0.preferredOrder != r1.preferredOrder 4999 || r0.isDefault != r1.isDefault) { 5000 return query.get(0); 5001 } 5002 // If we have saved a preference for a preferred activity for 5003 // this Intent, use that. 5004 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5005 flags, query, r0.priority, true, false, debug, userId); 5006 if (ri != null) { 5007 return ri; 5008 } 5009 ri = new ResolveInfo(mResolveInfo); 5010 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5011 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5012 ri.activityInfo.applicationInfo = new ApplicationInfo( 5013 ri.activityInfo.applicationInfo); 5014 if (userId != 0) { 5015 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5016 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5017 } 5018 // Make sure that the resolver is displayable in car mode 5019 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5020 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5021 return ri; 5022 } 5023 } 5024 return null; 5025 } 5026 5027 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5028 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5029 final int N = query.size(); 5030 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5031 .get(userId); 5032 // Get the list of persistent preferred activities that handle the intent 5033 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5034 List<PersistentPreferredActivity> pprefs = ppir != null 5035 ? ppir.queryIntent(intent, resolvedType, 5036 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5037 : null; 5038 if (pprefs != null && pprefs.size() > 0) { 5039 final int M = pprefs.size(); 5040 for (int i=0; i<M; i++) { 5041 final PersistentPreferredActivity ppa = pprefs.get(i); 5042 if (DEBUG_PREFERRED || debug) { 5043 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5044 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5045 + "\n component=" + ppa.mComponent); 5046 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5047 } 5048 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5049 flags | MATCH_DISABLED_COMPONENTS, userId); 5050 if (DEBUG_PREFERRED || debug) { 5051 Slog.v(TAG, "Found persistent preferred activity:"); 5052 if (ai != null) { 5053 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5054 } else { 5055 Slog.v(TAG, " null"); 5056 } 5057 } 5058 if (ai == null) { 5059 // This previously registered persistent preferred activity 5060 // component is no longer known. Ignore it and do NOT remove it. 5061 continue; 5062 } 5063 for (int j=0; j<N; j++) { 5064 final ResolveInfo ri = query.get(j); 5065 if (!ri.activityInfo.applicationInfo.packageName 5066 .equals(ai.applicationInfo.packageName)) { 5067 continue; 5068 } 5069 if (!ri.activityInfo.name.equals(ai.name)) { 5070 continue; 5071 } 5072 // Found a persistent preference that can handle the intent. 5073 if (DEBUG_PREFERRED || debug) { 5074 Slog.v(TAG, "Returning persistent preferred activity: " + 5075 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5076 } 5077 return ri; 5078 } 5079 } 5080 } 5081 return null; 5082 } 5083 5084 // TODO: handle preferred activities missing while user has amnesia 5085 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5086 List<ResolveInfo> query, int priority, boolean always, 5087 boolean removeMatches, boolean debug, int userId) { 5088 if (!sUserManager.exists(userId)) return null; 5089 flags = updateFlagsForResolve(flags, userId, intent); 5090 // writer 5091 synchronized (mPackages) { 5092 if (intent.getSelector() != null) { 5093 intent = intent.getSelector(); 5094 } 5095 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5096 5097 // Try to find a matching persistent preferred activity. 5098 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5099 debug, userId); 5100 5101 // If a persistent preferred activity matched, use it. 5102 if (pri != null) { 5103 return pri; 5104 } 5105 5106 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5107 // Get the list of preferred activities that handle the intent 5108 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5109 List<PreferredActivity> prefs = pir != null 5110 ? pir.queryIntent(intent, resolvedType, 5111 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5112 : null; 5113 if (prefs != null && prefs.size() > 0) { 5114 boolean changed = false; 5115 try { 5116 // First figure out how good the original match set is. 5117 // We will only allow preferred activities that came 5118 // from the same match quality. 5119 int match = 0; 5120 5121 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5122 5123 final int N = query.size(); 5124 for (int j=0; j<N; j++) { 5125 final ResolveInfo ri = query.get(j); 5126 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5127 + ": 0x" + Integer.toHexString(match)); 5128 if (ri.match > match) { 5129 match = ri.match; 5130 } 5131 } 5132 5133 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5134 + Integer.toHexString(match)); 5135 5136 match &= IntentFilter.MATCH_CATEGORY_MASK; 5137 final int M = prefs.size(); 5138 for (int i=0; i<M; i++) { 5139 final PreferredActivity pa = prefs.get(i); 5140 if (DEBUG_PREFERRED || debug) { 5141 Slog.v(TAG, "Checking PreferredActivity ds=" 5142 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5143 + "\n component=" + pa.mPref.mComponent); 5144 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5145 } 5146 if (pa.mPref.mMatch != match) { 5147 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5148 + Integer.toHexString(pa.mPref.mMatch)); 5149 continue; 5150 } 5151 // If it's not an "always" type preferred activity and that's what we're 5152 // looking for, skip it. 5153 if (always && !pa.mPref.mAlways) { 5154 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5155 continue; 5156 } 5157 final ActivityInfo ai = getActivityInfo( 5158 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5159 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5160 userId); 5161 if (DEBUG_PREFERRED || debug) { 5162 Slog.v(TAG, "Found preferred activity:"); 5163 if (ai != null) { 5164 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5165 } else { 5166 Slog.v(TAG, " null"); 5167 } 5168 } 5169 if (ai == null) { 5170 // This previously registered preferred activity 5171 // component is no longer known. Most likely an update 5172 // to the app was installed and in the new version this 5173 // component no longer exists. Clean it up by removing 5174 // it from the preferred activities list, and skip it. 5175 Slog.w(TAG, "Removing dangling preferred activity: " 5176 + pa.mPref.mComponent); 5177 pir.removeFilter(pa); 5178 changed = true; 5179 continue; 5180 } 5181 for (int j=0; j<N; j++) { 5182 final ResolveInfo ri = query.get(j); 5183 if (!ri.activityInfo.applicationInfo.packageName 5184 .equals(ai.applicationInfo.packageName)) { 5185 continue; 5186 } 5187 if (!ri.activityInfo.name.equals(ai.name)) { 5188 continue; 5189 } 5190 5191 if (removeMatches) { 5192 pir.removeFilter(pa); 5193 changed = true; 5194 if (DEBUG_PREFERRED) { 5195 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5196 } 5197 break; 5198 } 5199 5200 // Okay we found a previously set preferred or last chosen app. 5201 // If the result set is different from when this 5202 // was created, we need to clear it and re-ask the 5203 // user their preference, if we're looking for an "always" type entry. 5204 if (always && !pa.mPref.sameSet(query)) { 5205 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5206 + intent + " type " + resolvedType); 5207 if (DEBUG_PREFERRED) { 5208 Slog.v(TAG, "Removing preferred activity since set changed " 5209 + pa.mPref.mComponent); 5210 } 5211 pir.removeFilter(pa); 5212 // Re-add the filter as a "last chosen" entry (!always) 5213 PreferredActivity lastChosen = new PreferredActivity( 5214 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5215 pir.addFilter(lastChosen); 5216 changed = true; 5217 return null; 5218 } 5219 5220 // Yay! Either the set matched or we're looking for the last chosen 5221 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5222 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5223 return ri; 5224 } 5225 } 5226 } finally { 5227 if (changed) { 5228 if (DEBUG_PREFERRED) { 5229 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5230 } 5231 scheduleWritePackageRestrictionsLocked(userId); 5232 } 5233 } 5234 } 5235 } 5236 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5237 return null; 5238 } 5239 5240 /* 5241 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5242 */ 5243 @Override 5244 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5245 int targetUserId) { 5246 mContext.enforceCallingOrSelfPermission( 5247 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5248 List<CrossProfileIntentFilter> matches = 5249 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5250 if (matches != null) { 5251 int size = matches.size(); 5252 for (int i = 0; i < size; i++) { 5253 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5254 } 5255 } 5256 if (hasWebURI(intent)) { 5257 // cross-profile app linking works only towards the parent. 5258 final UserInfo parent = getProfileParent(sourceUserId); 5259 synchronized(mPackages) { 5260 int flags = updateFlagsForResolve(0, parent.id, intent); 5261 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5262 intent, resolvedType, flags, sourceUserId, parent.id); 5263 return xpDomainInfo != null; 5264 } 5265 } 5266 return false; 5267 } 5268 5269 private UserInfo getProfileParent(int userId) { 5270 final long identity = Binder.clearCallingIdentity(); 5271 try { 5272 return sUserManager.getProfileParent(userId); 5273 } finally { 5274 Binder.restoreCallingIdentity(identity); 5275 } 5276 } 5277 5278 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5279 String resolvedType, int userId) { 5280 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5281 if (resolver != null) { 5282 return resolver.queryIntent(intent, resolvedType, false, userId); 5283 } 5284 return null; 5285 } 5286 5287 @Override 5288 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5289 String resolvedType, int flags, int userId) { 5290 try { 5291 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5292 5293 return new ParceledListSlice<>( 5294 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5295 } finally { 5296 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5297 } 5298 } 5299 5300 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5301 String resolvedType, int flags, int userId) { 5302 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5303 flags = updateFlagsForResolve(flags, userId, intent); 5304 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5305 false /* requireFullPermission */, false /* checkShell */, 5306 "query intent activities"); 5307 ComponentName comp = intent.getComponent(); 5308 if (comp == null) { 5309 if (intent.getSelector() != null) { 5310 intent = intent.getSelector(); 5311 comp = intent.getComponent(); 5312 } 5313 } 5314 5315 if (comp != null) { 5316 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5317 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5318 if (ai != null) { 5319 final ResolveInfo ri = new ResolveInfo(); 5320 ri.activityInfo = ai; 5321 list.add(ri); 5322 } 5323 return list; 5324 } 5325 5326 // reader 5327 synchronized (mPackages) { 5328 final String pkgName = intent.getPackage(); 5329 if (pkgName == null) { 5330 List<CrossProfileIntentFilter> matchingFilters = 5331 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5332 // Check for results that need to skip the current profile. 5333 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5334 resolvedType, flags, userId); 5335 if (xpResolveInfo != null) { 5336 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5337 result.add(xpResolveInfo); 5338 return filterIfNotSystemUser(result, userId); 5339 } 5340 5341 // Check for results in the current profile. 5342 List<ResolveInfo> result = mActivities.queryIntent( 5343 intent, resolvedType, flags, userId); 5344 result = filterIfNotSystemUser(result, userId); 5345 5346 // Check for cross profile results. 5347 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5348 xpResolveInfo = queryCrossProfileIntents( 5349 matchingFilters, intent, resolvedType, flags, userId, 5350 hasNonNegativePriorityResult); 5351 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5352 boolean isVisibleToUser = filterIfNotSystemUser( 5353 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5354 if (isVisibleToUser) { 5355 result.add(xpResolveInfo); 5356 Collections.sort(result, mResolvePrioritySorter); 5357 } 5358 } 5359 if (hasWebURI(intent)) { 5360 CrossProfileDomainInfo xpDomainInfo = null; 5361 final UserInfo parent = getProfileParent(userId); 5362 if (parent != null) { 5363 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5364 flags, userId, parent.id); 5365 } 5366 if (xpDomainInfo != null) { 5367 if (xpResolveInfo != null) { 5368 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5369 // in the result. 5370 result.remove(xpResolveInfo); 5371 } 5372 if (result.size() == 0) { 5373 result.add(xpDomainInfo.resolveInfo); 5374 return result; 5375 } 5376 } else if (result.size() <= 1) { 5377 return result; 5378 } 5379 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5380 xpDomainInfo, userId); 5381 Collections.sort(result, mResolvePrioritySorter); 5382 } 5383 return result; 5384 } 5385 final PackageParser.Package pkg = mPackages.get(pkgName); 5386 if (pkg != null) { 5387 return filterIfNotSystemUser( 5388 mActivities.queryIntentForPackage( 5389 intent, resolvedType, flags, pkg.activities, userId), 5390 userId); 5391 } 5392 return new ArrayList<ResolveInfo>(); 5393 } 5394 } 5395 5396 private static class CrossProfileDomainInfo { 5397 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5398 ResolveInfo resolveInfo; 5399 /* Best domain verification status of the activities found in the other profile */ 5400 int bestDomainVerificationStatus; 5401 } 5402 5403 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5404 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5405 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5406 sourceUserId)) { 5407 return null; 5408 } 5409 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5410 resolvedType, flags, parentUserId); 5411 5412 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5413 return null; 5414 } 5415 CrossProfileDomainInfo result = null; 5416 int size = resultTargetUser.size(); 5417 for (int i = 0; i < size; i++) { 5418 ResolveInfo riTargetUser = resultTargetUser.get(i); 5419 // Intent filter verification is only for filters that specify a host. So don't return 5420 // those that handle all web uris. 5421 if (riTargetUser.handleAllWebDataURI) { 5422 continue; 5423 } 5424 String packageName = riTargetUser.activityInfo.packageName; 5425 PackageSetting ps = mSettings.mPackages.get(packageName); 5426 if (ps == null) { 5427 continue; 5428 } 5429 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5430 int status = (int)(verificationState >> 32); 5431 if (result == null) { 5432 result = new CrossProfileDomainInfo(); 5433 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5434 sourceUserId, parentUserId); 5435 result.bestDomainVerificationStatus = status; 5436 } else { 5437 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5438 result.bestDomainVerificationStatus); 5439 } 5440 } 5441 // Don't consider matches with status NEVER across profiles. 5442 if (result != null && result.bestDomainVerificationStatus 5443 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5444 return null; 5445 } 5446 return result; 5447 } 5448 5449 /** 5450 * Verification statuses are ordered from the worse to the best, except for 5451 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5452 */ 5453 private int bestDomainVerificationStatus(int status1, int status2) { 5454 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5455 return status2; 5456 } 5457 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5458 return status1; 5459 } 5460 return (int) MathUtils.max(status1, status2); 5461 } 5462 5463 private boolean isUserEnabled(int userId) { 5464 long callingId = Binder.clearCallingIdentity(); 5465 try { 5466 UserInfo userInfo = sUserManager.getUserInfo(userId); 5467 return userInfo != null && userInfo.isEnabled(); 5468 } finally { 5469 Binder.restoreCallingIdentity(callingId); 5470 } 5471 } 5472 5473 /** 5474 * Filter out activities with systemUserOnly flag set, when current user is not System. 5475 * 5476 * @return filtered list 5477 */ 5478 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5479 if (userId == UserHandle.USER_SYSTEM) { 5480 return resolveInfos; 5481 } 5482 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5483 ResolveInfo info = resolveInfos.get(i); 5484 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5485 resolveInfos.remove(i); 5486 } 5487 } 5488 return resolveInfos; 5489 } 5490 5491 /** 5492 * @param resolveInfos list of resolve infos in descending priority order 5493 * @return if the list contains a resolve info with non-negative priority 5494 */ 5495 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5496 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5497 } 5498 5499 private static boolean hasWebURI(Intent intent) { 5500 if (intent.getData() == null) { 5501 return false; 5502 } 5503 final String scheme = intent.getScheme(); 5504 if (TextUtils.isEmpty(scheme)) { 5505 return false; 5506 } 5507 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5508 } 5509 5510 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5511 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5512 int userId) { 5513 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5514 5515 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5516 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5517 candidates.size()); 5518 } 5519 5520 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5521 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5522 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5523 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5524 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5525 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5526 5527 synchronized (mPackages) { 5528 final int count = candidates.size(); 5529 // First, try to use linked apps. Partition the candidates into four lists: 5530 // one for the final results, one for the "do not use ever", one for "undefined status" 5531 // and finally one for "browser app type". 5532 for (int n=0; n<count; n++) { 5533 ResolveInfo info = candidates.get(n); 5534 String packageName = info.activityInfo.packageName; 5535 PackageSetting ps = mSettings.mPackages.get(packageName); 5536 if (ps != null) { 5537 // Add to the special match all list (Browser use case) 5538 if (info.handleAllWebDataURI) { 5539 matchAllList.add(info); 5540 continue; 5541 } 5542 // Try to get the status from User settings first 5543 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5544 int status = (int)(packedStatus >> 32); 5545 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5546 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5547 if (DEBUG_DOMAIN_VERIFICATION) { 5548 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5549 + " : linkgen=" + linkGeneration); 5550 } 5551 // Use link-enabled generation as preferredOrder, i.e. 5552 // prefer newly-enabled over earlier-enabled. 5553 info.preferredOrder = linkGeneration; 5554 alwaysList.add(info); 5555 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5556 if (DEBUG_DOMAIN_VERIFICATION) { 5557 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5558 } 5559 neverList.add(info); 5560 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5561 if (DEBUG_DOMAIN_VERIFICATION) { 5562 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5563 } 5564 alwaysAskList.add(info); 5565 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5566 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5567 if (DEBUG_DOMAIN_VERIFICATION) { 5568 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5569 } 5570 undefinedList.add(info); 5571 } 5572 } 5573 } 5574 5575 // We'll want to include browser possibilities in a few cases 5576 boolean includeBrowser = false; 5577 5578 // First try to add the "always" resolution(s) for the current user, if any 5579 if (alwaysList.size() > 0) { 5580 result.addAll(alwaysList); 5581 } else { 5582 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5583 result.addAll(undefinedList); 5584 // Maybe add one for the other profile. 5585 if (xpDomainInfo != null && ( 5586 xpDomainInfo.bestDomainVerificationStatus 5587 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5588 result.add(xpDomainInfo.resolveInfo); 5589 } 5590 includeBrowser = true; 5591 } 5592 5593 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5594 // If there were 'always' entries their preferred order has been set, so we also 5595 // back that off to make the alternatives equivalent 5596 if (alwaysAskList.size() > 0) { 5597 for (ResolveInfo i : result) { 5598 i.preferredOrder = 0; 5599 } 5600 result.addAll(alwaysAskList); 5601 includeBrowser = true; 5602 } 5603 5604 if (includeBrowser) { 5605 // Also add browsers (all of them or only the default one) 5606 if (DEBUG_DOMAIN_VERIFICATION) { 5607 Slog.v(TAG, " ...including browsers in candidate set"); 5608 } 5609 if ((matchFlags & MATCH_ALL) != 0) { 5610 result.addAll(matchAllList); 5611 } else { 5612 // Browser/generic handling case. If there's a default browser, go straight 5613 // to that (but only if there is no other higher-priority match). 5614 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5615 int maxMatchPrio = 0; 5616 ResolveInfo defaultBrowserMatch = null; 5617 final int numCandidates = matchAllList.size(); 5618 for (int n = 0; n < numCandidates; n++) { 5619 ResolveInfo info = matchAllList.get(n); 5620 // track the highest overall match priority... 5621 if (info.priority > maxMatchPrio) { 5622 maxMatchPrio = info.priority; 5623 } 5624 // ...and the highest-priority default browser match 5625 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5626 if (defaultBrowserMatch == null 5627 || (defaultBrowserMatch.priority < info.priority)) { 5628 if (debug) { 5629 Slog.v(TAG, "Considering default browser match " + info); 5630 } 5631 defaultBrowserMatch = info; 5632 } 5633 } 5634 } 5635 if (defaultBrowserMatch != null 5636 && defaultBrowserMatch.priority >= maxMatchPrio 5637 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5638 { 5639 if (debug) { 5640 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5641 } 5642 result.add(defaultBrowserMatch); 5643 } else { 5644 result.addAll(matchAllList); 5645 } 5646 } 5647 5648 // If there is nothing selected, add all candidates and remove the ones that the user 5649 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5650 if (result.size() == 0) { 5651 result.addAll(candidates); 5652 result.removeAll(neverList); 5653 } 5654 } 5655 } 5656 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5657 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5658 result.size()); 5659 for (ResolveInfo info : result) { 5660 Slog.v(TAG, " + " + info.activityInfo); 5661 } 5662 } 5663 return result; 5664 } 5665 5666 // Returns a packed value as a long: 5667 // 5668 // high 'int'-sized word: link status: undefined/ask/never/always. 5669 // low 'int'-sized word: relative priority among 'always' results. 5670 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5671 long result = ps.getDomainVerificationStatusForUser(userId); 5672 // if none available, get the master status 5673 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5674 if (ps.getIntentFilterVerificationInfo() != null) { 5675 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5676 } 5677 } 5678 return result; 5679 } 5680 5681 private ResolveInfo querySkipCurrentProfileIntents( 5682 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5683 int flags, int sourceUserId) { 5684 if (matchingFilters != null) { 5685 int size = matchingFilters.size(); 5686 for (int i = 0; i < size; i ++) { 5687 CrossProfileIntentFilter filter = matchingFilters.get(i); 5688 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5689 // Checking if there are activities in the target user that can handle the 5690 // intent. 5691 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5692 resolvedType, flags, sourceUserId); 5693 if (resolveInfo != null) { 5694 return resolveInfo; 5695 } 5696 } 5697 } 5698 } 5699 return null; 5700 } 5701 5702 // Return matching ResolveInfo in target user if any. 5703 private ResolveInfo queryCrossProfileIntents( 5704 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5705 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5706 if (matchingFilters != null) { 5707 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5708 // match the same intent. For performance reasons, it is better not to 5709 // run queryIntent twice for the same userId 5710 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5711 int size = matchingFilters.size(); 5712 for (int i = 0; i < size; i++) { 5713 CrossProfileIntentFilter filter = matchingFilters.get(i); 5714 int targetUserId = filter.getTargetUserId(); 5715 boolean skipCurrentProfile = 5716 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5717 boolean skipCurrentProfileIfNoMatchFound = 5718 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5719 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5720 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5721 // Checking if there are activities in the target user that can handle the 5722 // intent. 5723 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5724 resolvedType, flags, sourceUserId); 5725 if (resolveInfo != null) return resolveInfo; 5726 alreadyTriedUserIds.put(targetUserId, true); 5727 } 5728 } 5729 } 5730 return null; 5731 } 5732 5733 /** 5734 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5735 * will forward the intent to the filter's target user. 5736 * Otherwise, returns null. 5737 */ 5738 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5739 String resolvedType, int flags, int sourceUserId) { 5740 int targetUserId = filter.getTargetUserId(); 5741 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5742 resolvedType, flags, targetUserId); 5743 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5744 // If all the matches in the target profile are suspended, return null. 5745 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5746 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5747 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5748 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5749 targetUserId); 5750 } 5751 } 5752 } 5753 return null; 5754 } 5755 5756 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5757 int sourceUserId, int targetUserId) { 5758 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5759 long ident = Binder.clearCallingIdentity(); 5760 boolean targetIsProfile; 5761 try { 5762 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5763 } finally { 5764 Binder.restoreCallingIdentity(ident); 5765 } 5766 String className; 5767 if (targetIsProfile) { 5768 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5769 } else { 5770 className = FORWARD_INTENT_TO_PARENT; 5771 } 5772 ComponentName forwardingActivityComponentName = new ComponentName( 5773 mAndroidApplication.packageName, className); 5774 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5775 sourceUserId); 5776 if (!targetIsProfile) { 5777 forwardingActivityInfo.showUserIcon = targetUserId; 5778 forwardingResolveInfo.noResourceId = true; 5779 } 5780 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5781 forwardingResolveInfo.priority = 0; 5782 forwardingResolveInfo.preferredOrder = 0; 5783 forwardingResolveInfo.match = 0; 5784 forwardingResolveInfo.isDefault = true; 5785 forwardingResolveInfo.filter = filter; 5786 forwardingResolveInfo.targetUserId = targetUserId; 5787 return forwardingResolveInfo; 5788 } 5789 5790 @Override 5791 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5792 Intent[] specifics, String[] specificTypes, Intent intent, 5793 String resolvedType, int flags, int userId) { 5794 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5795 specificTypes, intent, resolvedType, flags, userId)); 5796 } 5797 5798 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5799 Intent[] specifics, String[] specificTypes, Intent intent, 5800 String resolvedType, int flags, int userId) { 5801 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5802 flags = updateFlagsForResolve(flags, userId, intent); 5803 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5804 false /* requireFullPermission */, false /* checkShell */, 5805 "query intent activity options"); 5806 final String resultsAction = intent.getAction(); 5807 5808 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5809 | PackageManager.GET_RESOLVED_FILTER, userId); 5810 5811 if (DEBUG_INTENT_MATCHING) { 5812 Log.v(TAG, "Query " + intent + ": " + results); 5813 } 5814 5815 int specificsPos = 0; 5816 int N; 5817 5818 // todo: note that the algorithm used here is O(N^2). This 5819 // isn't a problem in our current environment, but if we start running 5820 // into situations where we have more than 5 or 10 matches then this 5821 // should probably be changed to something smarter... 5822 5823 // First we go through and resolve each of the specific items 5824 // that were supplied, taking care of removing any corresponding 5825 // duplicate items in the generic resolve list. 5826 if (specifics != null) { 5827 for (int i=0; i<specifics.length; i++) { 5828 final Intent sintent = specifics[i]; 5829 if (sintent == null) { 5830 continue; 5831 } 5832 5833 if (DEBUG_INTENT_MATCHING) { 5834 Log.v(TAG, "Specific #" + i + ": " + sintent); 5835 } 5836 5837 String action = sintent.getAction(); 5838 if (resultsAction != null && resultsAction.equals(action)) { 5839 // If this action was explicitly requested, then don't 5840 // remove things that have it. 5841 action = null; 5842 } 5843 5844 ResolveInfo ri = null; 5845 ActivityInfo ai = null; 5846 5847 ComponentName comp = sintent.getComponent(); 5848 if (comp == null) { 5849 ri = resolveIntent( 5850 sintent, 5851 specificTypes != null ? specificTypes[i] : null, 5852 flags, userId); 5853 if (ri == null) { 5854 continue; 5855 } 5856 if (ri == mResolveInfo) { 5857 // ACK! Must do something better with this. 5858 } 5859 ai = ri.activityInfo; 5860 comp = new ComponentName(ai.applicationInfo.packageName, 5861 ai.name); 5862 } else { 5863 ai = getActivityInfo(comp, flags, userId); 5864 if (ai == null) { 5865 continue; 5866 } 5867 } 5868 5869 // Look for any generic query activities that are duplicates 5870 // of this specific one, and remove them from the results. 5871 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5872 N = results.size(); 5873 int j; 5874 for (j=specificsPos; j<N; j++) { 5875 ResolveInfo sri = results.get(j); 5876 if ((sri.activityInfo.name.equals(comp.getClassName()) 5877 && sri.activityInfo.applicationInfo.packageName.equals( 5878 comp.getPackageName())) 5879 || (action != null && sri.filter.matchAction(action))) { 5880 results.remove(j); 5881 if (DEBUG_INTENT_MATCHING) Log.v( 5882 TAG, "Removing duplicate item from " + j 5883 + " due to specific " + specificsPos); 5884 if (ri == null) { 5885 ri = sri; 5886 } 5887 j--; 5888 N--; 5889 } 5890 } 5891 5892 // Add this specific item to its proper place. 5893 if (ri == null) { 5894 ri = new ResolveInfo(); 5895 ri.activityInfo = ai; 5896 } 5897 results.add(specificsPos, ri); 5898 ri.specificIndex = i; 5899 specificsPos++; 5900 } 5901 } 5902 5903 // Now we go through the remaining generic results and remove any 5904 // duplicate actions that are found here. 5905 N = results.size(); 5906 for (int i=specificsPos; i<N-1; i++) { 5907 final ResolveInfo rii = results.get(i); 5908 if (rii.filter == null) { 5909 continue; 5910 } 5911 5912 // Iterate over all of the actions of this result's intent 5913 // filter... typically this should be just one. 5914 final Iterator<String> it = rii.filter.actionsIterator(); 5915 if (it == null) { 5916 continue; 5917 } 5918 while (it.hasNext()) { 5919 final String action = it.next(); 5920 if (resultsAction != null && resultsAction.equals(action)) { 5921 // If this action was explicitly requested, then don't 5922 // remove things that have it. 5923 continue; 5924 } 5925 for (int j=i+1; j<N; j++) { 5926 final ResolveInfo rij = results.get(j); 5927 if (rij.filter != null && rij.filter.hasAction(action)) { 5928 results.remove(j); 5929 if (DEBUG_INTENT_MATCHING) Log.v( 5930 TAG, "Removing duplicate item from " + j 5931 + " due to action " + action + " at " + i); 5932 j--; 5933 N--; 5934 } 5935 } 5936 } 5937 5938 // If the caller didn't request filter information, drop it now 5939 // so we don't have to marshall/unmarshall it. 5940 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5941 rii.filter = null; 5942 } 5943 } 5944 5945 // Filter out the caller activity if so requested. 5946 if (caller != null) { 5947 N = results.size(); 5948 for (int i=0; i<N; i++) { 5949 ActivityInfo ainfo = results.get(i).activityInfo; 5950 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5951 && caller.getClassName().equals(ainfo.name)) { 5952 results.remove(i); 5953 break; 5954 } 5955 } 5956 } 5957 5958 // If the caller didn't request filter information, 5959 // drop them now so we don't have to 5960 // marshall/unmarshall it. 5961 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5962 N = results.size(); 5963 for (int i=0; i<N; i++) { 5964 results.get(i).filter = null; 5965 } 5966 } 5967 5968 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5969 return results; 5970 } 5971 5972 @Override 5973 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5974 String resolvedType, int flags, int userId) { 5975 return new ParceledListSlice<>( 5976 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5977 } 5978 5979 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5980 String resolvedType, int flags, int userId) { 5981 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5982 flags = updateFlagsForResolve(flags, userId, intent); 5983 ComponentName comp = intent.getComponent(); 5984 if (comp == null) { 5985 if (intent.getSelector() != null) { 5986 intent = intent.getSelector(); 5987 comp = intent.getComponent(); 5988 } 5989 } 5990 if (comp != null) { 5991 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5992 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5993 if (ai != null) { 5994 ResolveInfo ri = new ResolveInfo(); 5995 ri.activityInfo = ai; 5996 list.add(ri); 5997 } 5998 return list; 5999 } 6000 6001 // reader 6002 synchronized (mPackages) { 6003 String pkgName = intent.getPackage(); 6004 if (pkgName == null) { 6005 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6006 } 6007 final PackageParser.Package pkg = mPackages.get(pkgName); 6008 if (pkg != null) { 6009 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6010 userId); 6011 } 6012 return Collections.emptyList(); 6013 } 6014 } 6015 6016 @Override 6017 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6018 if (!sUserManager.exists(userId)) return null; 6019 flags = updateFlagsForResolve(flags, userId, intent); 6020 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6021 if (query != null) { 6022 if (query.size() >= 1) { 6023 // If there is more than one service with the same priority, 6024 // just arbitrarily pick the first one. 6025 return query.get(0); 6026 } 6027 } 6028 return null; 6029 } 6030 6031 @Override 6032 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6033 String resolvedType, int flags, int userId) { 6034 return new ParceledListSlice<>( 6035 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6036 } 6037 6038 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6039 String resolvedType, int flags, int userId) { 6040 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6041 flags = updateFlagsForResolve(flags, userId, intent); 6042 ComponentName comp = intent.getComponent(); 6043 if (comp == null) { 6044 if (intent.getSelector() != null) { 6045 intent = intent.getSelector(); 6046 comp = intent.getComponent(); 6047 } 6048 } 6049 if (comp != null) { 6050 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6051 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6052 if (si != null) { 6053 final ResolveInfo ri = new ResolveInfo(); 6054 ri.serviceInfo = si; 6055 list.add(ri); 6056 } 6057 return list; 6058 } 6059 6060 // reader 6061 synchronized (mPackages) { 6062 String pkgName = intent.getPackage(); 6063 if (pkgName == null) { 6064 return mServices.queryIntent(intent, resolvedType, flags, userId); 6065 } 6066 final PackageParser.Package pkg = mPackages.get(pkgName); 6067 if (pkg != null) { 6068 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6069 userId); 6070 } 6071 return Collections.emptyList(); 6072 } 6073 } 6074 6075 @Override 6076 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6077 String resolvedType, int flags, int userId) { 6078 return new ParceledListSlice<>( 6079 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6080 } 6081 6082 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6083 Intent intent, String resolvedType, int flags, int userId) { 6084 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6085 flags = updateFlagsForResolve(flags, userId, intent); 6086 ComponentName comp = intent.getComponent(); 6087 if (comp == null) { 6088 if (intent.getSelector() != null) { 6089 intent = intent.getSelector(); 6090 comp = intent.getComponent(); 6091 } 6092 } 6093 if (comp != null) { 6094 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6095 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6096 if (pi != null) { 6097 final ResolveInfo ri = new ResolveInfo(); 6098 ri.providerInfo = pi; 6099 list.add(ri); 6100 } 6101 return list; 6102 } 6103 6104 // reader 6105 synchronized (mPackages) { 6106 String pkgName = intent.getPackage(); 6107 if (pkgName == null) { 6108 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6109 } 6110 final PackageParser.Package pkg = mPackages.get(pkgName); 6111 if (pkg != null) { 6112 return mProviders.queryIntentForPackage( 6113 intent, resolvedType, flags, pkg.providers, userId); 6114 } 6115 return Collections.emptyList(); 6116 } 6117 } 6118 6119 @Override 6120 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6121 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6122 flags = updateFlagsForPackage(flags, userId, null); 6123 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6124 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6125 true /* requireFullPermission */, false /* checkShell */, 6126 "get installed packages"); 6127 6128 // writer 6129 synchronized (mPackages) { 6130 ArrayList<PackageInfo> list; 6131 if (listUninstalled) { 6132 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6133 for (PackageSetting ps : mSettings.mPackages.values()) { 6134 final PackageInfo pi; 6135 if (ps.pkg != null) { 6136 pi = generatePackageInfo(ps, flags, userId); 6137 } else { 6138 pi = generatePackageInfo(ps, flags, userId); 6139 } 6140 if (pi != null) { 6141 list.add(pi); 6142 } 6143 } 6144 } else { 6145 list = new ArrayList<PackageInfo>(mPackages.size()); 6146 for (PackageParser.Package p : mPackages.values()) { 6147 final PackageInfo pi = 6148 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6149 if (pi != null) { 6150 list.add(pi); 6151 } 6152 } 6153 } 6154 6155 return new ParceledListSlice<PackageInfo>(list); 6156 } 6157 } 6158 6159 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6160 String[] permissions, boolean[] tmp, int flags, int userId) { 6161 int numMatch = 0; 6162 final PermissionsState permissionsState = ps.getPermissionsState(); 6163 for (int i=0; i<permissions.length; i++) { 6164 final String permission = permissions[i]; 6165 if (permissionsState.hasPermission(permission, userId)) { 6166 tmp[i] = true; 6167 numMatch++; 6168 } else { 6169 tmp[i] = false; 6170 } 6171 } 6172 if (numMatch == 0) { 6173 return; 6174 } 6175 final PackageInfo pi; 6176 if (ps.pkg != null) { 6177 pi = generatePackageInfo(ps, flags, userId); 6178 } else { 6179 pi = generatePackageInfo(ps, flags, userId); 6180 } 6181 // The above might return null in cases of uninstalled apps or install-state 6182 // skew across users/profiles. 6183 if (pi != null) { 6184 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6185 if (numMatch == permissions.length) { 6186 pi.requestedPermissions = permissions; 6187 } else { 6188 pi.requestedPermissions = new String[numMatch]; 6189 numMatch = 0; 6190 for (int i=0; i<permissions.length; i++) { 6191 if (tmp[i]) { 6192 pi.requestedPermissions[numMatch] = permissions[i]; 6193 numMatch++; 6194 } 6195 } 6196 } 6197 } 6198 list.add(pi); 6199 } 6200 } 6201 6202 @Override 6203 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6204 String[] permissions, int flags, int userId) { 6205 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6206 flags = updateFlagsForPackage(flags, userId, permissions); 6207 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6208 6209 // writer 6210 synchronized (mPackages) { 6211 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6212 boolean[] tmpBools = new boolean[permissions.length]; 6213 if (listUninstalled) { 6214 for (PackageSetting ps : mSettings.mPackages.values()) { 6215 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6216 } 6217 } else { 6218 for (PackageParser.Package pkg : mPackages.values()) { 6219 PackageSetting ps = (PackageSetting)pkg.mExtras; 6220 if (ps != null) { 6221 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6222 userId); 6223 } 6224 } 6225 } 6226 6227 return new ParceledListSlice<PackageInfo>(list); 6228 } 6229 } 6230 6231 @Override 6232 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6233 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6234 flags = updateFlagsForApplication(flags, userId, null); 6235 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6236 6237 // writer 6238 synchronized (mPackages) { 6239 ArrayList<ApplicationInfo> list; 6240 if (listUninstalled) { 6241 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6242 for (PackageSetting ps : mSettings.mPackages.values()) { 6243 ApplicationInfo ai; 6244 if (ps.pkg != null) { 6245 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6246 ps.readUserState(userId), userId); 6247 } else { 6248 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6249 } 6250 if (ai != null) { 6251 list.add(ai); 6252 } 6253 } 6254 } else { 6255 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6256 for (PackageParser.Package p : mPackages.values()) { 6257 if (p.mExtras != null) { 6258 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6259 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6260 if (ai != null) { 6261 list.add(ai); 6262 } 6263 } 6264 } 6265 } 6266 6267 return new ParceledListSlice<ApplicationInfo>(list); 6268 } 6269 } 6270 6271 @Override 6272 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6273 if (DISABLE_EPHEMERAL_APPS) { 6274 return null; 6275 } 6276 6277 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6278 "getEphemeralApplications"); 6279 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6280 true /* requireFullPermission */, false /* checkShell */, 6281 "getEphemeralApplications"); 6282 synchronized (mPackages) { 6283 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6284 .getEphemeralApplicationsLPw(userId); 6285 if (ephemeralApps != null) { 6286 return new ParceledListSlice<>(ephemeralApps); 6287 } 6288 } 6289 return null; 6290 } 6291 6292 @Override 6293 public boolean isEphemeralApplication(String packageName, int userId) { 6294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6295 true /* requireFullPermission */, false /* checkShell */, 6296 "isEphemeral"); 6297 if (DISABLE_EPHEMERAL_APPS) { 6298 return false; 6299 } 6300 6301 if (!isCallerSameApp(packageName)) { 6302 return false; 6303 } 6304 synchronized (mPackages) { 6305 PackageParser.Package pkg = mPackages.get(packageName); 6306 if (pkg != null) { 6307 return pkg.applicationInfo.isEphemeralApp(); 6308 } 6309 } 6310 return false; 6311 } 6312 6313 @Override 6314 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6315 if (DISABLE_EPHEMERAL_APPS) { 6316 return null; 6317 } 6318 6319 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6320 true /* requireFullPermission */, false /* checkShell */, 6321 "getCookie"); 6322 if (!isCallerSameApp(packageName)) { 6323 return null; 6324 } 6325 synchronized (mPackages) { 6326 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6327 packageName, userId); 6328 } 6329 } 6330 6331 @Override 6332 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6333 if (DISABLE_EPHEMERAL_APPS) { 6334 return true; 6335 } 6336 6337 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6338 true /* requireFullPermission */, true /* checkShell */, 6339 "setCookie"); 6340 if (!isCallerSameApp(packageName)) { 6341 return false; 6342 } 6343 synchronized (mPackages) { 6344 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6345 packageName, cookie, userId); 6346 } 6347 } 6348 6349 @Override 6350 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6351 if (DISABLE_EPHEMERAL_APPS) { 6352 return null; 6353 } 6354 6355 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6356 "getEphemeralApplicationIcon"); 6357 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6358 true /* requireFullPermission */, false /* checkShell */, 6359 "getEphemeralApplicationIcon"); 6360 synchronized (mPackages) { 6361 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6362 packageName, userId); 6363 } 6364 } 6365 6366 private boolean isCallerSameApp(String packageName) { 6367 PackageParser.Package pkg = mPackages.get(packageName); 6368 return pkg != null 6369 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6370 } 6371 6372 @Override 6373 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6374 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6375 } 6376 6377 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6378 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6379 6380 // reader 6381 synchronized (mPackages) { 6382 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6383 final int userId = UserHandle.getCallingUserId(); 6384 while (i.hasNext()) { 6385 final PackageParser.Package p = i.next(); 6386 if (p.applicationInfo == null) continue; 6387 6388 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6389 && !p.applicationInfo.isDirectBootAware(); 6390 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6391 && p.applicationInfo.isDirectBootAware(); 6392 6393 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6394 && (!mSafeMode || isSystemApp(p)) 6395 && (matchesUnaware || matchesAware)) { 6396 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6397 if (ps != null) { 6398 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6399 ps.readUserState(userId), userId); 6400 if (ai != null) { 6401 finalList.add(ai); 6402 } 6403 } 6404 } 6405 } 6406 } 6407 6408 return finalList; 6409 } 6410 6411 @Override 6412 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6413 if (!sUserManager.exists(userId)) return null; 6414 flags = updateFlagsForComponent(flags, userId, name); 6415 // reader 6416 synchronized (mPackages) { 6417 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6418 PackageSetting ps = provider != null 6419 ? mSettings.mPackages.get(provider.owner.packageName) 6420 : null; 6421 return ps != null 6422 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6423 ? PackageParser.generateProviderInfo(provider, flags, 6424 ps.readUserState(userId), userId) 6425 : null; 6426 } 6427 } 6428 6429 /** 6430 * @deprecated 6431 */ 6432 @Deprecated 6433 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6434 // reader 6435 synchronized (mPackages) { 6436 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6437 .entrySet().iterator(); 6438 final int userId = UserHandle.getCallingUserId(); 6439 while (i.hasNext()) { 6440 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6441 PackageParser.Provider p = entry.getValue(); 6442 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6443 6444 if (ps != null && p.syncable 6445 && (!mSafeMode || (p.info.applicationInfo.flags 6446 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6447 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6448 ps.readUserState(userId), userId); 6449 if (info != null) { 6450 outNames.add(entry.getKey()); 6451 outInfo.add(info); 6452 } 6453 } 6454 } 6455 } 6456 } 6457 6458 @Override 6459 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6460 int uid, int flags) { 6461 final int userId = processName != null ? UserHandle.getUserId(uid) 6462 : UserHandle.getCallingUserId(); 6463 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6464 flags = updateFlagsForComponent(flags, userId, processName); 6465 6466 ArrayList<ProviderInfo> finalList = null; 6467 // reader 6468 synchronized (mPackages) { 6469 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6470 while (i.hasNext()) { 6471 final PackageParser.Provider p = i.next(); 6472 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6473 if (ps != null && p.info.authority != null 6474 && (processName == null 6475 || (p.info.processName.equals(processName) 6476 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6477 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6478 if (finalList == null) { 6479 finalList = new ArrayList<ProviderInfo>(3); 6480 } 6481 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6482 ps.readUserState(userId), userId); 6483 if (info != null) { 6484 finalList.add(info); 6485 } 6486 } 6487 } 6488 } 6489 6490 if (finalList != null) { 6491 Collections.sort(finalList, mProviderInitOrderSorter); 6492 return new ParceledListSlice<ProviderInfo>(finalList); 6493 } 6494 6495 return ParceledListSlice.emptyList(); 6496 } 6497 6498 @Override 6499 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6500 // reader 6501 synchronized (mPackages) { 6502 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6503 return PackageParser.generateInstrumentationInfo(i, flags); 6504 } 6505 } 6506 6507 @Override 6508 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6509 String targetPackage, int flags) { 6510 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6511 } 6512 6513 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6514 int flags) { 6515 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6516 6517 // reader 6518 synchronized (mPackages) { 6519 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6520 while (i.hasNext()) { 6521 final PackageParser.Instrumentation p = i.next(); 6522 if (targetPackage == null 6523 || targetPackage.equals(p.info.targetPackage)) { 6524 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6525 flags); 6526 if (ii != null) { 6527 finalList.add(ii); 6528 } 6529 } 6530 } 6531 } 6532 6533 return finalList; 6534 } 6535 6536 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6537 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6538 if (overlays == null) { 6539 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6540 return; 6541 } 6542 for (PackageParser.Package opkg : overlays.values()) { 6543 // Not much to do if idmap fails: we already logged the error 6544 // and we certainly don't want to abort installation of pkg simply 6545 // because an overlay didn't fit properly. For these reasons, 6546 // ignore the return value of createIdmapForPackagePairLI. 6547 createIdmapForPackagePairLI(pkg, opkg); 6548 } 6549 } 6550 6551 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6552 PackageParser.Package opkg) { 6553 if (!opkg.mTrustedOverlay) { 6554 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6555 opkg.baseCodePath + ": overlay not trusted"); 6556 return false; 6557 } 6558 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6559 if (overlaySet == null) { 6560 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6561 opkg.baseCodePath + " but target package has no known overlays"); 6562 return false; 6563 } 6564 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6565 // TODO: generate idmap for split APKs 6566 try { 6567 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6568 } catch (InstallerException e) { 6569 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6570 + opkg.baseCodePath); 6571 return false; 6572 } 6573 PackageParser.Package[] overlayArray = 6574 overlaySet.values().toArray(new PackageParser.Package[0]); 6575 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6576 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6577 return p1.mOverlayPriority - p2.mOverlayPriority; 6578 } 6579 }; 6580 Arrays.sort(overlayArray, cmp); 6581 6582 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6583 int i = 0; 6584 for (PackageParser.Package p : overlayArray) { 6585 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6586 } 6587 return true; 6588 } 6589 6590 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6592 try { 6593 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6594 } finally { 6595 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6596 } 6597 } 6598 6599 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6600 final File[] files = dir.listFiles(); 6601 if (ArrayUtils.isEmpty(files)) { 6602 Log.d(TAG, "No files in app dir " + dir); 6603 return; 6604 } 6605 6606 if (DEBUG_PACKAGE_SCANNING) { 6607 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6608 + " flags=0x" + Integer.toHexString(parseFlags)); 6609 } 6610 6611 for (File file : files) { 6612 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6613 && !PackageInstallerService.isStageName(file.getName()); 6614 if (!isPackage) { 6615 // Ignore entries which are not packages 6616 continue; 6617 } 6618 try { 6619 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6620 scanFlags, currentTime, null); 6621 } catch (PackageManagerException e) { 6622 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6623 6624 // Delete invalid userdata apps 6625 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6626 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6627 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6628 removeCodePathLI(file); 6629 } 6630 } 6631 } 6632 } 6633 6634 private static File getSettingsProblemFile() { 6635 File dataDir = Environment.getDataDirectory(); 6636 File systemDir = new File(dataDir, "system"); 6637 File fname = new File(systemDir, "uiderrors.txt"); 6638 return fname; 6639 } 6640 6641 static void reportSettingsProblem(int priority, String msg) { 6642 logCriticalInfo(priority, msg); 6643 } 6644 6645 static void logCriticalInfo(int priority, String msg) { 6646 Slog.println(priority, TAG, msg); 6647 EventLogTags.writePmCriticalInfo(msg); 6648 try { 6649 File fname = getSettingsProblemFile(); 6650 FileOutputStream out = new FileOutputStream(fname, true); 6651 PrintWriter pw = new FastPrintWriter(out); 6652 SimpleDateFormat formatter = new SimpleDateFormat(); 6653 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6654 pw.println(dateString + ": " + msg); 6655 pw.close(); 6656 FileUtils.setPermissions( 6657 fname.toString(), 6658 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6659 -1, -1); 6660 } catch (java.io.IOException e) { 6661 } 6662 } 6663 6664 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6665 final int policyFlags) throws PackageManagerException { 6666 if (ps != null 6667 && ps.codePath.equals(srcFile) 6668 && ps.timeStamp == srcFile.lastModified() 6669 && !isCompatSignatureUpdateNeeded(pkg) 6670 && !isRecoverSignatureUpdateNeeded(pkg)) { 6671 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6672 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6673 ArraySet<PublicKey> signingKs; 6674 synchronized (mPackages) { 6675 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6676 } 6677 if (ps.signatures.mSignatures != null 6678 && ps.signatures.mSignatures.length != 0 6679 && signingKs != null) { 6680 // Optimization: reuse the existing cached certificates 6681 // if the package appears to be unchanged. 6682 pkg.mSignatures = ps.signatures.mSignatures; 6683 pkg.mSigningKeys = signingKs; 6684 return; 6685 } 6686 6687 Slog.w(TAG, "PackageSetting for " + ps.name 6688 + " is missing signatures. Collecting certs again to recover them."); 6689 } else { 6690 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6691 } 6692 6693 try { 6694 PackageParser.collectCertificates(pkg, policyFlags); 6695 } catch (PackageParserException e) { 6696 throw PackageManagerException.from(e); 6697 } 6698 } 6699 6700 /** 6701 * Traces a package scan. 6702 * @see #scanPackageLI(File, int, int, long, UserHandle) 6703 */ 6704 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6705 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6706 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6707 try { 6708 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6709 } finally { 6710 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6711 } 6712 } 6713 6714 /** 6715 * Scans a package and returns the newly parsed package. 6716 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6717 */ 6718 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6719 long currentTime, UserHandle user) throws PackageManagerException { 6720 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6721 PackageParser pp = new PackageParser(); 6722 pp.setSeparateProcesses(mSeparateProcesses); 6723 pp.setOnlyCoreApps(mOnlyCore); 6724 pp.setDisplayMetrics(mMetrics); 6725 6726 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6727 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6728 } 6729 6730 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6731 final PackageParser.Package pkg; 6732 try { 6733 pkg = pp.parsePackage(scanFile, parseFlags); 6734 } catch (PackageParserException e) { 6735 throw PackageManagerException.from(e); 6736 } finally { 6737 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6738 } 6739 6740 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6741 } 6742 6743 /** 6744 * Scans a package and returns the newly parsed package. 6745 * @throws PackageManagerException on a parse error. 6746 */ 6747 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6748 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6749 throws PackageManagerException { 6750 // If the package has children and this is the first dive in the function 6751 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6752 // packages (parent and children) would be successfully scanned before the 6753 // actual scan since scanning mutates internal state and we want to atomically 6754 // install the package and its children. 6755 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6756 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6757 scanFlags |= SCAN_CHECK_ONLY; 6758 } 6759 } else { 6760 scanFlags &= ~SCAN_CHECK_ONLY; 6761 } 6762 6763 // Scan the parent 6764 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6765 scanFlags, currentTime, user); 6766 6767 // Scan the children 6768 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6769 for (int i = 0; i < childCount; i++) { 6770 PackageParser.Package childPackage = pkg.childPackages.get(i); 6771 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6772 currentTime, user); 6773 } 6774 6775 6776 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6777 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6778 } 6779 6780 return scannedPkg; 6781 } 6782 6783 /** 6784 * Scans a package and returns the newly parsed package. 6785 * @throws PackageManagerException on a parse error. 6786 */ 6787 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6788 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6789 throws PackageManagerException { 6790 PackageSetting ps = null; 6791 PackageSetting updatedPkg; 6792 // reader 6793 synchronized (mPackages) { 6794 // Look to see if we already know about this package. 6795 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6796 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6797 // This package has been renamed to its original name. Let's 6798 // use that. 6799 ps = mSettings.peekPackageLPr(oldName); 6800 } 6801 // If there was no original package, see one for the real package name. 6802 if (ps == null) { 6803 ps = mSettings.peekPackageLPr(pkg.packageName); 6804 } 6805 // Check to see if this package could be hiding/updating a system 6806 // package. Must look for it either under the original or real 6807 // package name depending on our state. 6808 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6809 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6810 6811 // If this is a package we don't know about on the system partition, we 6812 // may need to remove disabled child packages on the system partition 6813 // or may need to not add child packages if the parent apk is updated 6814 // on the data partition and no longer defines this child package. 6815 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6816 // If this is a parent package for an updated system app and this system 6817 // app got an OTA update which no longer defines some of the child packages 6818 // we have to prune them from the disabled system packages. 6819 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6820 if (disabledPs != null) { 6821 final int scannedChildCount = (pkg.childPackages != null) 6822 ? pkg.childPackages.size() : 0; 6823 final int disabledChildCount = disabledPs.childPackageNames != null 6824 ? disabledPs.childPackageNames.size() : 0; 6825 for (int i = 0; i < disabledChildCount; i++) { 6826 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6827 boolean disabledPackageAvailable = false; 6828 for (int j = 0; j < scannedChildCount; j++) { 6829 PackageParser.Package childPkg = pkg.childPackages.get(j); 6830 if (childPkg.packageName.equals(disabledChildPackageName)) { 6831 disabledPackageAvailable = true; 6832 break; 6833 } 6834 } 6835 if (!disabledPackageAvailable) { 6836 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6837 } 6838 } 6839 } 6840 } 6841 } 6842 6843 boolean updatedPkgBetter = false; 6844 // First check if this is a system package that may involve an update 6845 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6846 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6847 // it needs to drop FLAG_PRIVILEGED. 6848 if (locationIsPrivileged(scanFile)) { 6849 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6850 } else { 6851 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6852 } 6853 6854 if (ps != null && !ps.codePath.equals(scanFile)) { 6855 // The path has changed from what was last scanned... check the 6856 // version of the new path against what we have stored to determine 6857 // what to do. 6858 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6859 if (pkg.mVersionCode <= ps.versionCode) { 6860 // The system package has been updated and the code path does not match 6861 // Ignore entry. Skip it. 6862 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6863 + " ignored: updated version " + ps.versionCode 6864 + " better than this " + pkg.mVersionCode); 6865 if (!updatedPkg.codePath.equals(scanFile)) { 6866 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6867 + ps.name + " changing from " + updatedPkg.codePathString 6868 + " to " + scanFile); 6869 updatedPkg.codePath = scanFile; 6870 updatedPkg.codePathString = scanFile.toString(); 6871 updatedPkg.resourcePath = scanFile; 6872 updatedPkg.resourcePathString = scanFile.toString(); 6873 } 6874 updatedPkg.pkg = pkg; 6875 updatedPkg.versionCode = pkg.mVersionCode; 6876 6877 // Update the disabled system child packages to point to the package too. 6878 final int childCount = updatedPkg.childPackageNames != null 6879 ? updatedPkg.childPackageNames.size() : 0; 6880 for (int i = 0; i < childCount; i++) { 6881 String childPackageName = updatedPkg.childPackageNames.get(i); 6882 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6883 childPackageName); 6884 if (updatedChildPkg != null) { 6885 updatedChildPkg.pkg = pkg; 6886 updatedChildPkg.versionCode = pkg.mVersionCode; 6887 } 6888 } 6889 6890 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6891 + scanFile + " ignored: updated version " + ps.versionCode 6892 + " better than this " + pkg.mVersionCode); 6893 } else { 6894 // The current app on the system partition is better than 6895 // what we have updated to on the data partition; switch 6896 // back to the system partition version. 6897 // At this point, its safely assumed that package installation for 6898 // apps in system partition will go through. If not there won't be a working 6899 // version of the app 6900 // writer 6901 synchronized (mPackages) { 6902 // Just remove the loaded entries from package lists. 6903 mPackages.remove(ps.name); 6904 } 6905 6906 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6907 + " reverting from " + ps.codePathString 6908 + ": new version " + pkg.mVersionCode 6909 + " better than installed " + ps.versionCode); 6910 6911 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6912 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6913 synchronized (mInstallLock) { 6914 args.cleanUpResourcesLI(); 6915 } 6916 synchronized (mPackages) { 6917 mSettings.enableSystemPackageLPw(ps.name); 6918 } 6919 updatedPkgBetter = true; 6920 } 6921 } 6922 } 6923 6924 if (updatedPkg != null) { 6925 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6926 // initially 6927 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6928 6929 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6930 // flag set initially 6931 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6932 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6933 } 6934 } 6935 6936 // Verify certificates against what was last scanned 6937 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6938 6939 /* 6940 * A new system app appeared, but we already had a non-system one of the 6941 * same name installed earlier. 6942 */ 6943 boolean shouldHideSystemApp = false; 6944 if (updatedPkg == null && ps != null 6945 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6946 /* 6947 * Check to make sure the signatures match first. If they don't, 6948 * wipe the installed application and its data. 6949 */ 6950 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6951 != PackageManager.SIGNATURE_MATCH) { 6952 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6953 + " signatures don't match existing userdata copy; removing"); 6954 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6955 "scanPackageInternalLI")) { 6956 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6957 } 6958 ps = null; 6959 } else { 6960 /* 6961 * If the newly-added system app is an older version than the 6962 * already installed version, hide it. It will be scanned later 6963 * and re-added like an update. 6964 */ 6965 if (pkg.mVersionCode <= ps.versionCode) { 6966 shouldHideSystemApp = true; 6967 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6968 + " but new version " + pkg.mVersionCode + " better than installed " 6969 + ps.versionCode + "; hiding system"); 6970 } else { 6971 /* 6972 * The newly found system app is a newer version that the 6973 * one previously installed. Simply remove the 6974 * already-installed application and replace it with our own 6975 * while keeping the application data. 6976 */ 6977 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6978 + " reverting from " + ps.codePathString + ": new version " 6979 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6980 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6981 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6982 synchronized (mInstallLock) { 6983 args.cleanUpResourcesLI(); 6984 } 6985 } 6986 } 6987 } 6988 6989 // The apk is forward locked (not public) if its code and resources 6990 // are kept in different files. (except for app in either system or 6991 // vendor path). 6992 // TODO grab this value from PackageSettings 6993 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6994 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6995 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6996 } 6997 } 6998 6999 // TODO: extend to support forward-locked splits 7000 String resourcePath = null; 7001 String baseResourcePath = null; 7002 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7003 if (ps != null && ps.resourcePathString != null) { 7004 resourcePath = ps.resourcePathString; 7005 baseResourcePath = ps.resourcePathString; 7006 } else { 7007 // Should not happen at all. Just log an error. 7008 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7009 } 7010 } else { 7011 resourcePath = pkg.codePath; 7012 baseResourcePath = pkg.baseCodePath; 7013 } 7014 7015 // Set application objects path explicitly. 7016 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7017 pkg.setApplicationInfoCodePath(pkg.codePath); 7018 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7019 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7020 pkg.setApplicationInfoResourcePath(resourcePath); 7021 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7022 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7023 7024 // Note that we invoke the following method only if we are about to unpack an application 7025 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7026 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7027 7028 /* 7029 * If the system app should be overridden by a previously installed 7030 * data, hide the system app now and let the /data/app scan pick it up 7031 * again. 7032 */ 7033 if (shouldHideSystemApp) { 7034 synchronized (mPackages) { 7035 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7036 } 7037 } 7038 7039 return scannedPkg; 7040 } 7041 7042 private static String fixProcessName(String defProcessName, 7043 String processName, int uid) { 7044 if (processName == null) { 7045 return defProcessName; 7046 } 7047 return processName; 7048 } 7049 7050 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7051 throws PackageManagerException { 7052 if (pkgSetting.signatures.mSignatures != null) { 7053 // Already existing package. Make sure signatures match 7054 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7055 == PackageManager.SIGNATURE_MATCH; 7056 if (!match) { 7057 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7058 == PackageManager.SIGNATURE_MATCH; 7059 } 7060 if (!match) { 7061 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7062 == PackageManager.SIGNATURE_MATCH; 7063 } 7064 if (!match) { 7065 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7066 + pkg.packageName + " signatures do not match the " 7067 + "previously installed version; ignoring!"); 7068 } 7069 } 7070 7071 // Check for shared user signatures 7072 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7073 // Already existing package. Make sure signatures match 7074 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7075 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7076 if (!match) { 7077 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7078 == PackageManager.SIGNATURE_MATCH; 7079 } 7080 if (!match) { 7081 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7082 == PackageManager.SIGNATURE_MATCH; 7083 } 7084 if (!match) { 7085 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7086 "Package " + pkg.packageName 7087 + " has no signatures that match those in shared user " 7088 + pkgSetting.sharedUser.name + "; ignoring!"); 7089 } 7090 } 7091 } 7092 7093 /** 7094 * Enforces that only the system UID or root's UID can call a method exposed 7095 * via Binder. 7096 * 7097 * @param message used as message if SecurityException is thrown 7098 * @throws SecurityException if the caller is not system or root 7099 */ 7100 private static final void enforceSystemOrRoot(String message) { 7101 final int uid = Binder.getCallingUid(); 7102 if (uid != Process.SYSTEM_UID && uid != 0) { 7103 throw new SecurityException(message); 7104 } 7105 } 7106 7107 @Override 7108 public void performFstrimIfNeeded() { 7109 enforceSystemOrRoot("Only the system can request fstrim"); 7110 7111 // Before everything else, see whether we need to fstrim. 7112 try { 7113 IMountService ms = PackageHelper.getMountService(); 7114 if (ms != null) { 7115 final boolean isUpgrade = isUpgrade(); 7116 boolean doTrim = isUpgrade; 7117 if (doTrim) { 7118 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7119 } else { 7120 final long interval = android.provider.Settings.Global.getLong( 7121 mContext.getContentResolver(), 7122 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7123 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7124 if (interval > 0) { 7125 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7126 if (timeSinceLast > interval) { 7127 doTrim = true; 7128 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7129 + "; running immediately"); 7130 } 7131 } 7132 } 7133 if (doTrim) { 7134 if (!isFirstBoot()) { 7135 try { 7136 ActivityManagerNative.getDefault().showBootMessage( 7137 mContext.getResources().getString( 7138 R.string.android_upgrading_fstrim), true); 7139 } catch (RemoteException e) { 7140 } 7141 } 7142 ms.runMaintenance(); 7143 } 7144 } else { 7145 Slog.e(TAG, "Mount service unavailable!"); 7146 } 7147 } catch (RemoteException e) { 7148 // Can't happen; MountService is local 7149 } 7150 } 7151 7152 @Override 7153 public void updatePackagesIfNeeded() { 7154 enforceSystemOrRoot("Only the system can request package update"); 7155 7156 // We need to re-extract after an OTA. 7157 boolean causeUpgrade = isUpgrade(); 7158 7159 // First boot or factory reset. 7160 // Note: we also handle devices that are upgrading to N right now as if it is their 7161 // first boot, as they do not have profile data. 7162 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7163 7164 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7165 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7166 7167 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7168 return; 7169 } 7170 7171 List<PackageParser.Package> pkgs; 7172 synchronized (mPackages) { 7173 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7174 } 7175 7176 int numberOfPackagesVisited = 0; 7177 int numberOfPackagesOptimized = 0; 7178 int numberOfPackagesSkipped = 0; 7179 int numberOfPackagesFailed = 0; 7180 final int numberOfPackagesToDexopt = pkgs.size(); 7181 final long startTime = System.nanoTime(); 7182 7183 for (PackageParser.Package pkg : pkgs) { 7184 numberOfPackagesVisited++; 7185 7186 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7187 if (DEBUG_DEXOPT) { 7188 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7189 } 7190 numberOfPackagesSkipped++; 7191 continue; 7192 } 7193 7194 if (DEBUG_DEXOPT) { 7195 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7196 numberOfPackagesToDexopt + ": " + pkg.packageName); 7197 } 7198 7199 if (mIsPreNUpgrade) { 7200 try { 7201 ActivityManagerNative.getDefault().showBootMessage( 7202 mContext.getResources().getString(R.string.android_upgrading_apk, 7203 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7204 } catch (RemoteException e) { 7205 } 7206 } 7207 7208 // checkProfiles is false to avoid merging profiles during boot which 7209 // might interfere with background compilation (b/28612421). 7210 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7211 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7212 // trade-off worth doing to save boot time work. 7213 int dexOptStatus = performDexOptTraced(pkg.packageName, 7214 null /* instructionSet */, 7215 false /* checkProfiles */, 7216 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7217 false /* force */); 7218 switch (dexOptStatus) { 7219 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7220 numberOfPackagesOptimized++; 7221 break; 7222 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7223 numberOfPackagesSkipped++; 7224 break; 7225 case PackageDexOptimizer.DEX_OPT_FAILED: 7226 numberOfPackagesFailed++; 7227 break; 7228 default: 7229 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7230 break; 7231 } 7232 } 7233 7234 final int elapsedTimeSeconds = 7235 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7236 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7237 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7238 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7239 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7240 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7241 } 7242 7243 @Override 7244 public void notifyPackageUse(String packageName, int reason) { 7245 synchronized (mPackages) { 7246 PackageParser.Package p = mPackages.get(packageName); 7247 if (p == null) { 7248 return; 7249 } 7250 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7251 } 7252 } 7253 7254 // TODO: this is not used nor needed. Delete it. 7255 @Override 7256 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7257 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7258 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7259 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7260 } 7261 7262 @Override 7263 public boolean performDexOpt(String packageName, String instructionSet, 7264 boolean checkProfiles, int compileReason, boolean force) { 7265 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7266 getCompilerFilterForReason(compileReason), force); 7267 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7268 } 7269 7270 @Override 7271 public boolean performDexOptMode(String packageName, String instructionSet, 7272 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7273 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7274 targetCompilerFilter, force); 7275 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7276 } 7277 7278 private int performDexOptTraced(String packageName, String instructionSet, 7279 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7280 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7281 try { 7282 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7283 targetCompilerFilter, force); 7284 } finally { 7285 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7286 } 7287 } 7288 7289 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7290 // if the package can now be considered up to date for the given filter. 7291 private int performDexOptInternal(String packageName, String instructionSet, 7292 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7293 PackageParser.Package p; 7294 final String targetInstructionSet; 7295 synchronized (mPackages) { 7296 p = mPackages.get(packageName); 7297 if (p == null) { 7298 // Package could not be found. Report failure. 7299 return PackageDexOptimizer.DEX_OPT_FAILED; 7300 } 7301 mPackageUsage.write(false); 7302 7303 targetInstructionSet = instructionSet != null ? instructionSet : 7304 getPrimaryInstructionSet(p.applicationInfo); 7305 } 7306 long callingId = Binder.clearCallingIdentity(); 7307 try { 7308 synchronized (mInstallLock) { 7309 final String[] instructionSets = new String[] { targetInstructionSet }; 7310 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7311 targetCompilerFilter, force); 7312 } 7313 } finally { 7314 Binder.restoreCallingIdentity(callingId); 7315 } 7316 } 7317 7318 public ArraySet<String> getOptimizablePackages() { 7319 ArraySet<String> pkgs = new ArraySet<String>(); 7320 synchronized (mPackages) { 7321 for (PackageParser.Package p : mPackages.values()) { 7322 if (PackageDexOptimizer.canOptimizePackage(p)) { 7323 pkgs.add(p.packageName); 7324 } 7325 } 7326 } 7327 return pkgs; 7328 } 7329 7330 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7331 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7332 boolean force) { 7333 // Select the dex optimizer based on the force parameter. 7334 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7335 // allocate an object here. 7336 PackageDexOptimizer pdo = force 7337 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7338 : mPackageDexOptimizer; 7339 7340 // Optimize all dependencies first. Note: we ignore the return value and march on 7341 // on errors. 7342 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7343 if (!deps.isEmpty()) { 7344 for (PackageParser.Package depPackage : deps) { 7345 // TODO: Analyze and investigate if we (should) profile libraries. 7346 // Currently this will do a full compilation of the library by default. 7347 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7348 false /* checkProfiles */, 7349 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7350 } 7351 } 7352 7353 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7354 targetCompilerFilter); 7355 } 7356 7357 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7358 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7359 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7360 Set<String> collectedNames = new HashSet<>(); 7361 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7362 7363 retValue.remove(p); 7364 7365 return retValue; 7366 } else { 7367 return Collections.emptyList(); 7368 } 7369 } 7370 7371 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7372 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7373 if (!collectedNames.contains(p.packageName)) { 7374 collectedNames.add(p.packageName); 7375 collected.add(p); 7376 7377 if (p.usesLibraries != null) { 7378 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7379 } 7380 if (p.usesOptionalLibraries != null) { 7381 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7382 collectedNames); 7383 } 7384 } 7385 } 7386 7387 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7388 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7389 for (String libName : libs) { 7390 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7391 if (libPkg != null) { 7392 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7393 } 7394 } 7395 } 7396 7397 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7398 synchronized (mPackages) { 7399 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7400 if (lib != null && lib.apk != null) { 7401 return mPackages.get(lib.apk); 7402 } 7403 } 7404 return null; 7405 } 7406 7407 public void shutdown() { 7408 mPackageUsage.write(true); 7409 } 7410 7411 @Override 7412 public void forceDexOpt(String packageName) { 7413 enforceSystemOrRoot("forceDexOpt"); 7414 7415 PackageParser.Package pkg; 7416 synchronized (mPackages) { 7417 pkg = mPackages.get(packageName); 7418 if (pkg == null) { 7419 throw new IllegalArgumentException("Unknown package: " + packageName); 7420 } 7421 } 7422 7423 synchronized (mInstallLock) { 7424 final String[] instructionSets = new String[] { 7425 getPrimaryInstructionSet(pkg.applicationInfo) }; 7426 7427 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7428 7429 // Whoever is calling forceDexOpt wants a fully compiled package. 7430 // Don't use profiles since that may cause compilation to be skipped. 7431 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7432 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7433 true /* force */); 7434 7435 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7436 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7437 throw new IllegalStateException("Failed to dexopt: " + res); 7438 } 7439 } 7440 } 7441 7442 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7443 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7444 Slog.w(TAG, "Unable to update from " + oldPkg.name 7445 + " to " + newPkg.packageName 7446 + ": old package not in system partition"); 7447 return false; 7448 } else if (mPackages.get(oldPkg.name) != null) { 7449 Slog.w(TAG, "Unable to update from " + oldPkg.name 7450 + " to " + newPkg.packageName 7451 + ": old package still exists"); 7452 return false; 7453 } 7454 return true; 7455 } 7456 7457 void removeCodePathLI(File codePath) { 7458 if (codePath.isDirectory()) { 7459 try { 7460 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7461 } catch (InstallerException e) { 7462 Slog.w(TAG, "Failed to remove code path", e); 7463 } 7464 } else { 7465 codePath.delete(); 7466 } 7467 } 7468 7469 private int[] resolveUserIds(int userId) { 7470 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7471 } 7472 7473 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7474 if (pkg == null) { 7475 Slog.wtf(TAG, "Package was null!", new Throwable()); 7476 return; 7477 } 7478 clearAppDataLeafLIF(pkg, userId, flags); 7479 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7480 for (int i = 0; i < childCount; i++) { 7481 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7482 } 7483 } 7484 7485 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7486 final PackageSetting ps; 7487 synchronized (mPackages) { 7488 ps = mSettings.mPackages.get(pkg.packageName); 7489 } 7490 for (int realUserId : resolveUserIds(userId)) { 7491 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7492 try { 7493 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7494 ceDataInode); 7495 } catch (InstallerException e) { 7496 Slog.w(TAG, String.valueOf(e)); 7497 } 7498 } 7499 } 7500 7501 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7502 if (pkg == null) { 7503 Slog.wtf(TAG, "Package was null!", new Throwable()); 7504 return; 7505 } 7506 destroyAppDataLeafLIF(pkg, userId, flags); 7507 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7508 for (int i = 0; i < childCount; i++) { 7509 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7510 } 7511 } 7512 7513 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7514 final PackageSetting ps; 7515 synchronized (mPackages) { 7516 ps = mSettings.mPackages.get(pkg.packageName); 7517 } 7518 for (int realUserId : resolveUserIds(userId)) { 7519 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7520 try { 7521 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7522 ceDataInode); 7523 } catch (InstallerException e) { 7524 Slog.w(TAG, String.valueOf(e)); 7525 } 7526 } 7527 } 7528 7529 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7530 if (pkg == null) { 7531 Slog.wtf(TAG, "Package was null!", new Throwable()); 7532 return; 7533 } 7534 destroyAppProfilesLeafLIF(pkg); 7535 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7536 for (int i = 0; i < childCount; i++) { 7537 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7538 } 7539 } 7540 7541 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7542 try { 7543 mInstaller.destroyAppProfiles(pkg.packageName); 7544 } catch (InstallerException e) { 7545 Slog.w(TAG, String.valueOf(e)); 7546 } 7547 } 7548 7549 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7550 if (pkg == null) { 7551 Slog.wtf(TAG, "Package was null!", new Throwable()); 7552 return; 7553 } 7554 clearAppProfilesLeafLIF(pkg); 7555 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7556 for (int i = 0; i < childCount; i++) { 7557 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7558 } 7559 } 7560 7561 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7562 try { 7563 mInstaller.clearAppProfiles(pkg.packageName); 7564 } catch (InstallerException e) { 7565 Slog.w(TAG, String.valueOf(e)); 7566 } 7567 } 7568 7569 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7570 long lastUpdateTime) { 7571 // Set parent install/update time 7572 PackageSetting ps = (PackageSetting) pkg.mExtras; 7573 if (ps != null) { 7574 ps.firstInstallTime = firstInstallTime; 7575 ps.lastUpdateTime = lastUpdateTime; 7576 } 7577 // Set children install/update time 7578 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7579 for (int i = 0; i < childCount; i++) { 7580 PackageParser.Package childPkg = pkg.childPackages.get(i); 7581 ps = (PackageSetting) childPkg.mExtras; 7582 if (ps != null) { 7583 ps.firstInstallTime = firstInstallTime; 7584 ps.lastUpdateTime = lastUpdateTime; 7585 } 7586 } 7587 } 7588 7589 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7590 PackageParser.Package changingLib) { 7591 if (file.path != null) { 7592 usesLibraryFiles.add(file.path); 7593 return; 7594 } 7595 PackageParser.Package p = mPackages.get(file.apk); 7596 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7597 // If we are doing this while in the middle of updating a library apk, 7598 // then we need to make sure to use that new apk for determining the 7599 // dependencies here. (We haven't yet finished committing the new apk 7600 // to the package manager state.) 7601 if (p == null || p.packageName.equals(changingLib.packageName)) { 7602 p = changingLib; 7603 } 7604 } 7605 if (p != null) { 7606 usesLibraryFiles.addAll(p.getAllCodePaths()); 7607 } 7608 } 7609 7610 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7611 PackageParser.Package changingLib) throws PackageManagerException { 7612 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7613 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7614 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7615 for (int i=0; i<N; i++) { 7616 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7617 if (file == null) { 7618 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7619 "Package " + pkg.packageName + " requires unavailable shared library " 7620 + pkg.usesLibraries.get(i) + "; failing!"); 7621 } 7622 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7623 } 7624 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7625 for (int i=0; i<N; i++) { 7626 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7627 if (file == null) { 7628 Slog.w(TAG, "Package " + pkg.packageName 7629 + " desires unavailable shared library " 7630 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7631 } else { 7632 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7633 } 7634 } 7635 N = usesLibraryFiles.size(); 7636 if (N > 0) { 7637 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7638 } else { 7639 pkg.usesLibraryFiles = null; 7640 } 7641 } 7642 } 7643 7644 private static boolean hasString(List<String> list, List<String> which) { 7645 if (list == null) { 7646 return false; 7647 } 7648 for (int i=list.size()-1; i>=0; i--) { 7649 for (int j=which.size()-1; j>=0; j--) { 7650 if (which.get(j).equals(list.get(i))) { 7651 return true; 7652 } 7653 } 7654 } 7655 return false; 7656 } 7657 7658 private void updateAllSharedLibrariesLPw() { 7659 for (PackageParser.Package pkg : mPackages.values()) { 7660 try { 7661 updateSharedLibrariesLPw(pkg, null); 7662 } catch (PackageManagerException e) { 7663 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7664 } 7665 } 7666 } 7667 7668 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7669 PackageParser.Package changingPkg) { 7670 ArrayList<PackageParser.Package> res = null; 7671 for (PackageParser.Package pkg : mPackages.values()) { 7672 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7673 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7674 if (res == null) { 7675 res = new ArrayList<PackageParser.Package>(); 7676 } 7677 res.add(pkg); 7678 try { 7679 updateSharedLibrariesLPw(pkg, changingPkg); 7680 } catch (PackageManagerException e) { 7681 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7682 } 7683 } 7684 } 7685 return res; 7686 } 7687 7688 /** 7689 * Derive the value of the {@code cpuAbiOverride} based on the provided 7690 * value and an optional stored value from the package settings. 7691 */ 7692 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7693 String cpuAbiOverride = null; 7694 7695 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7696 cpuAbiOverride = null; 7697 } else if (abiOverride != null) { 7698 cpuAbiOverride = abiOverride; 7699 } else if (settings != null) { 7700 cpuAbiOverride = settings.cpuAbiOverrideString; 7701 } 7702 7703 return cpuAbiOverride; 7704 } 7705 7706 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7707 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7708 throws PackageManagerException { 7709 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7710 // If the package has children and this is the first dive in the function 7711 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7712 // whether all packages (parent and children) would be successfully scanned 7713 // before the actual scan since scanning mutates internal state and we want 7714 // to atomically install the package and its children. 7715 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7716 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7717 scanFlags |= SCAN_CHECK_ONLY; 7718 } 7719 } else { 7720 scanFlags &= ~SCAN_CHECK_ONLY; 7721 } 7722 7723 final PackageParser.Package scannedPkg; 7724 try { 7725 // Scan the parent 7726 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7727 // Scan the children 7728 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7729 for (int i = 0; i < childCount; i++) { 7730 PackageParser.Package childPkg = pkg.childPackages.get(i); 7731 scanPackageLI(childPkg, policyFlags, 7732 scanFlags, currentTime, user); 7733 } 7734 } finally { 7735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7736 } 7737 7738 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7739 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7740 } 7741 7742 return scannedPkg; 7743 } 7744 7745 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7746 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7747 boolean success = false; 7748 try { 7749 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7750 currentTime, user); 7751 success = true; 7752 return res; 7753 } finally { 7754 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7755 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7756 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7757 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7758 destroyAppProfilesLIF(pkg); 7759 } 7760 } 7761 } 7762 7763 /** 7764 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7765 */ 7766 private static boolean apkHasCode(String fileName) { 7767 StrictJarFile jarFile = null; 7768 try { 7769 jarFile = new StrictJarFile(fileName, 7770 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7771 return jarFile.findEntry("classes.dex") != null; 7772 } catch (IOException ignore) { 7773 } finally { 7774 try { 7775 jarFile.close(); 7776 } catch (IOException ignore) {} 7777 } 7778 return false; 7779 } 7780 7781 /** 7782 * Enforces code policy for the package. This ensures that if an APK has 7783 * declared hasCode="true" in its manifest that the APK actually contains 7784 * code. 7785 * 7786 * @throws PackageManagerException If bytecode could not be found when it should exist 7787 */ 7788 private static void enforceCodePolicy(PackageParser.Package pkg) 7789 throws PackageManagerException { 7790 final boolean shouldHaveCode = 7791 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7792 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7793 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7794 "Package " + pkg.baseCodePath + " code is missing"); 7795 } 7796 7797 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7798 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7799 final boolean splitShouldHaveCode = 7800 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7801 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7802 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7803 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7804 } 7805 } 7806 } 7807 } 7808 7809 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7810 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7811 throws PackageManagerException { 7812 final File scanFile = new File(pkg.codePath); 7813 if (pkg.applicationInfo.getCodePath() == null || 7814 pkg.applicationInfo.getResourcePath() == null) { 7815 // Bail out. The resource and code paths haven't been set. 7816 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7817 "Code and resource paths haven't been set correctly"); 7818 } 7819 7820 // Apply policy 7821 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7822 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7823 if (pkg.applicationInfo.isDirectBootAware()) { 7824 // we're direct boot aware; set for all components 7825 for (PackageParser.Service s : pkg.services) { 7826 s.info.encryptionAware = s.info.directBootAware = true; 7827 } 7828 for (PackageParser.Provider p : pkg.providers) { 7829 p.info.encryptionAware = p.info.directBootAware = true; 7830 } 7831 for (PackageParser.Activity a : pkg.activities) { 7832 a.info.encryptionAware = a.info.directBootAware = true; 7833 } 7834 for (PackageParser.Activity r : pkg.receivers) { 7835 r.info.encryptionAware = r.info.directBootAware = true; 7836 } 7837 } 7838 } else { 7839 // Only allow system apps to be flagged as core apps. 7840 pkg.coreApp = false; 7841 // clear flags not applicable to regular apps 7842 pkg.applicationInfo.privateFlags &= 7843 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7844 pkg.applicationInfo.privateFlags &= 7845 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7846 } 7847 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7848 7849 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7850 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7851 } 7852 7853 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7854 enforceCodePolicy(pkg); 7855 } 7856 7857 if (mCustomResolverComponentName != null && 7858 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7859 setUpCustomResolverActivity(pkg); 7860 } 7861 7862 if (pkg.packageName.equals("android")) { 7863 synchronized (mPackages) { 7864 if (mAndroidApplication != null) { 7865 Slog.w(TAG, "*************************************************"); 7866 Slog.w(TAG, "Core android package being redefined. Skipping."); 7867 Slog.w(TAG, " file=" + scanFile); 7868 Slog.w(TAG, "*************************************************"); 7869 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7870 "Core android package being redefined. Skipping."); 7871 } 7872 7873 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7874 // Set up information for our fall-back user intent resolution activity. 7875 mPlatformPackage = pkg; 7876 pkg.mVersionCode = mSdkVersion; 7877 mAndroidApplication = pkg.applicationInfo; 7878 7879 if (!mResolverReplaced) { 7880 mResolveActivity.applicationInfo = mAndroidApplication; 7881 mResolveActivity.name = ResolverActivity.class.getName(); 7882 mResolveActivity.packageName = mAndroidApplication.packageName; 7883 mResolveActivity.processName = "system:ui"; 7884 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7885 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7886 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7887 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7888 mResolveActivity.exported = true; 7889 mResolveActivity.enabled = true; 7890 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7891 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7892 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7893 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7894 | ActivityInfo.CONFIG_ORIENTATION 7895 | ActivityInfo.CONFIG_KEYBOARD 7896 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7897 mResolveInfo.activityInfo = mResolveActivity; 7898 mResolveInfo.priority = 0; 7899 mResolveInfo.preferredOrder = 0; 7900 mResolveInfo.match = 0; 7901 mResolveComponentName = new ComponentName( 7902 mAndroidApplication.packageName, mResolveActivity.name); 7903 } 7904 } 7905 } 7906 } 7907 7908 if (DEBUG_PACKAGE_SCANNING) { 7909 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7910 Log.d(TAG, "Scanning package " + pkg.packageName); 7911 } 7912 7913 synchronized (mPackages) { 7914 if (mPackages.containsKey(pkg.packageName) 7915 || mSharedLibraries.containsKey(pkg.packageName)) { 7916 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7917 "Application package " + pkg.packageName 7918 + " already installed. Skipping duplicate."); 7919 } 7920 7921 // If we're only installing presumed-existing packages, require that the 7922 // scanned APK is both already known and at the path previously established 7923 // for it. Previously unknown packages we pick up normally, but if we have an 7924 // a priori expectation about this package's install presence, enforce it. 7925 // With a singular exception for new system packages. When an OTA contains 7926 // a new system package, we allow the codepath to change from a system location 7927 // to the user-installed location. If we don't allow this change, any newer, 7928 // user-installed version of the application will be ignored. 7929 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7930 if (mExpectingBetter.containsKey(pkg.packageName)) { 7931 logCriticalInfo(Log.WARN, 7932 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7933 } else { 7934 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7935 if (known != null) { 7936 if (DEBUG_PACKAGE_SCANNING) { 7937 Log.d(TAG, "Examining " + pkg.codePath 7938 + " and requiring known paths " + known.codePathString 7939 + " & " + known.resourcePathString); 7940 } 7941 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7942 || !pkg.applicationInfo.getResourcePath().equals( 7943 known.resourcePathString)) { 7944 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7945 "Application package " + pkg.packageName 7946 + " found at " + pkg.applicationInfo.getCodePath() 7947 + " but expected at " + known.codePathString 7948 + "; ignoring."); 7949 } 7950 } 7951 } 7952 } 7953 } 7954 7955 // Initialize package source and resource directories 7956 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7957 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7958 7959 SharedUserSetting suid = null; 7960 PackageSetting pkgSetting = null; 7961 7962 if (!isSystemApp(pkg)) { 7963 // Only system apps can use these features. 7964 pkg.mOriginalPackages = null; 7965 pkg.mRealPackage = null; 7966 pkg.mAdoptPermissions = null; 7967 } 7968 7969 // Getting the package setting may have a side-effect, so if we 7970 // are only checking if scan would succeed, stash a copy of the 7971 // old setting to restore at the end. 7972 PackageSetting nonMutatedPs = null; 7973 7974 // writer 7975 synchronized (mPackages) { 7976 if (pkg.mSharedUserId != null) { 7977 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7978 if (suid == null) { 7979 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7980 "Creating application package " + pkg.packageName 7981 + " for shared user failed"); 7982 } 7983 if (DEBUG_PACKAGE_SCANNING) { 7984 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7985 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7986 + "): packages=" + suid.packages); 7987 } 7988 } 7989 7990 // Check if we are renaming from an original package name. 7991 PackageSetting origPackage = null; 7992 String realName = null; 7993 if (pkg.mOriginalPackages != null) { 7994 // This package may need to be renamed to a previously 7995 // installed name. Let's check on that... 7996 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7997 if (pkg.mOriginalPackages.contains(renamed)) { 7998 // This package had originally been installed as the 7999 // original name, and we have already taken care of 8000 // transitioning to the new one. Just update the new 8001 // one to continue using the old name. 8002 realName = pkg.mRealPackage; 8003 if (!pkg.packageName.equals(renamed)) { 8004 // Callers into this function may have already taken 8005 // care of renaming the package; only do it here if 8006 // it is not already done. 8007 pkg.setPackageName(renamed); 8008 } 8009 8010 } else { 8011 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8012 if ((origPackage = mSettings.peekPackageLPr( 8013 pkg.mOriginalPackages.get(i))) != null) { 8014 // We do have the package already installed under its 8015 // original name... should we use it? 8016 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8017 // New package is not compatible with original. 8018 origPackage = null; 8019 continue; 8020 } else if (origPackage.sharedUser != null) { 8021 // Make sure uid is compatible between packages. 8022 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8023 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8024 + " to " + pkg.packageName + ": old uid " 8025 + origPackage.sharedUser.name 8026 + " differs from " + pkg.mSharedUserId); 8027 origPackage = null; 8028 continue; 8029 } 8030 // TODO: Add case when shared user id is added [b/28144775] 8031 } else { 8032 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8033 + pkg.packageName + " to old name " + origPackage.name); 8034 } 8035 break; 8036 } 8037 } 8038 } 8039 } 8040 8041 if (mTransferedPackages.contains(pkg.packageName)) { 8042 Slog.w(TAG, "Package " + pkg.packageName 8043 + " was transferred to another, but its .apk remains"); 8044 } 8045 8046 // See comments in nonMutatedPs declaration 8047 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8048 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8049 if (foundPs != null) { 8050 nonMutatedPs = new PackageSetting(foundPs); 8051 } 8052 } 8053 8054 // Just create the setting, don't add it yet. For already existing packages 8055 // the PkgSetting exists already and doesn't have to be created. 8056 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8057 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8058 pkg.applicationInfo.primaryCpuAbi, 8059 pkg.applicationInfo.secondaryCpuAbi, 8060 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8061 user, false); 8062 if (pkgSetting == null) { 8063 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8064 "Creating application package " + pkg.packageName + " failed"); 8065 } 8066 8067 if (pkgSetting.origPackage != null) { 8068 // If we are first transitioning from an original package, 8069 // fix up the new package's name now. We need to do this after 8070 // looking up the package under its new name, so getPackageLP 8071 // can take care of fiddling things correctly. 8072 pkg.setPackageName(origPackage.name); 8073 8074 // File a report about this. 8075 String msg = "New package " + pkgSetting.realName 8076 + " renamed to replace old package " + pkgSetting.name; 8077 reportSettingsProblem(Log.WARN, msg); 8078 8079 // Make a note of it. 8080 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8081 mTransferedPackages.add(origPackage.name); 8082 } 8083 8084 // No longer need to retain this. 8085 pkgSetting.origPackage = null; 8086 } 8087 8088 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8089 // Make a note of it. 8090 mTransferedPackages.add(pkg.packageName); 8091 } 8092 8093 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8094 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8095 } 8096 8097 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8098 // Check all shared libraries and map to their actual file path. 8099 // We only do this here for apps not on a system dir, because those 8100 // are the only ones that can fail an install due to this. We 8101 // will take care of the system apps by updating all of their 8102 // library paths after the scan is done. 8103 updateSharedLibrariesLPw(pkg, null); 8104 } 8105 8106 if (mFoundPolicyFile) { 8107 SELinuxMMAC.assignSeinfoValue(pkg); 8108 } 8109 8110 pkg.applicationInfo.uid = pkgSetting.appId; 8111 pkg.mExtras = pkgSetting; 8112 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8113 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8114 // We just determined the app is signed correctly, so bring 8115 // over the latest parsed certs. 8116 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8117 } else { 8118 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8119 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8120 "Package " + pkg.packageName + " upgrade keys do not match the " 8121 + "previously installed version"); 8122 } else { 8123 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8124 String msg = "System package " + pkg.packageName 8125 + " signature changed; retaining data."; 8126 reportSettingsProblem(Log.WARN, msg); 8127 } 8128 } 8129 } else { 8130 try { 8131 verifySignaturesLP(pkgSetting, pkg); 8132 // We just determined the app is signed correctly, so bring 8133 // over the latest parsed certs. 8134 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8135 } catch (PackageManagerException e) { 8136 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8137 throw e; 8138 } 8139 // The signature has changed, but this package is in the system 8140 // image... let's recover! 8141 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8142 // However... if this package is part of a shared user, but it 8143 // doesn't match the signature of the shared user, let's fail. 8144 // What this means is that you can't change the signatures 8145 // associated with an overall shared user, which doesn't seem all 8146 // that unreasonable. 8147 if (pkgSetting.sharedUser != null) { 8148 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8149 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8150 throw new PackageManagerException( 8151 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8152 "Signature mismatch for shared user: " 8153 + pkgSetting.sharedUser); 8154 } 8155 } 8156 // File a report about this. 8157 String msg = "System package " + pkg.packageName 8158 + " signature changed; retaining data."; 8159 reportSettingsProblem(Log.WARN, msg); 8160 } 8161 } 8162 // Verify that this new package doesn't have any content providers 8163 // that conflict with existing packages. Only do this if the 8164 // package isn't already installed, since we don't want to break 8165 // things that are installed. 8166 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8167 final int N = pkg.providers.size(); 8168 int i; 8169 for (i=0; i<N; i++) { 8170 PackageParser.Provider p = pkg.providers.get(i); 8171 if (p.info.authority != null) { 8172 String names[] = p.info.authority.split(";"); 8173 for (int j = 0; j < names.length; j++) { 8174 if (mProvidersByAuthority.containsKey(names[j])) { 8175 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8176 final String otherPackageName = 8177 ((other != null && other.getComponentName() != null) ? 8178 other.getComponentName().getPackageName() : "?"); 8179 throw new PackageManagerException( 8180 INSTALL_FAILED_CONFLICTING_PROVIDER, 8181 "Can't install because provider name " + names[j] 8182 + " (in package " + pkg.applicationInfo.packageName 8183 + ") is already used by " + otherPackageName); 8184 } 8185 } 8186 } 8187 } 8188 } 8189 8190 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8191 // This package wants to adopt ownership of permissions from 8192 // another package. 8193 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8194 final String origName = pkg.mAdoptPermissions.get(i); 8195 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8196 if (orig != null) { 8197 if (verifyPackageUpdateLPr(orig, pkg)) { 8198 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8199 + pkg.packageName); 8200 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8201 } 8202 } 8203 } 8204 } 8205 } 8206 8207 final String pkgName = pkg.packageName; 8208 8209 final long scanFileTime = scanFile.lastModified(); 8210 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8211 pkg.applicationInfo.processName = fixProcessName( 8212 pkg.applicationInfo.packageName, 8213 pkg.applicationInfo.processName, 8214 pkg.applicationInfo.uid); 8215 8216 if (pkg != mPlatformPackage) { 8217 // Get all of our default paths setup 8218 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8219 } 8220 8221 final String path = scanFile.getPath(); 8222 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8223 8224 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8225 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8226 8227 // Some system apps still use directory structure for native libraries 8228 // in which case we might end up not detecting abi solely based on apk 8229 // structure. Try to detect abi based on directory structure. 8230 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8231 pkg.applicationInfo.primaryCpuAbi == null) { 8232 setBundledAppAbisAndRoots(pkg, pkgSetting); 8233 setNativeLibraryPaths(pkg); 8234 } 8235 8236 } else { 8237 if ((scanFlags & SCAN_MOVE) != 0) { 8238 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8239 // but we already have this packages package info in the PackageSetting. We just 8240 // use that and derive the native library path based on the new codepath. 8241 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8242 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8243 } 8244 8245 // Set native library paths again. For moves, the path will be updated based on the 8246 // ABIs we've determined above. For non-moves, the path will be updated based on the 8247 // ABIs we determined during compilation, but the path will depend on the final 8248 // package path (after the rename away from the stage path). 8249 setNativeLibraryPaths(pkg); 8250 } 8251 8252 // This is a special case for the "system" package, where the ABI is 8253 // dictated by the zygote configuration (and init.rc). We should keep track 8254 // of this ABI so that we can deal with "normal" applications that run under 8255 // the same UID correctly. 8256 if (mPlatformPackage == pkg) { 8257 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8258 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8259 } 8260 8261 // If there's a mismatch between the abi-override in the package setting 8262 // and the abiOverride specified for the install. Warn about this because we 8263 // would've already compiled the app without taking the package setting into 8264 // account. 8265 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8266 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8267 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8268 " for package " + pkg.packageName); 8269 } 8270 } 8271 8272 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8273 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8274 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8275 8276 // Copy the derived override back to the parsed package, so that we can 8277 // update the package settings accordingly. 8278 pkg.cpuAbiOverride = cpuAbiOverride; 8279 8280 if (DEBUG_ABI_SELECTION) { 8281 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8282 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8283 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8284 } 8285 8286 // Push the derived path down into PackageSettings so we know what to 8287 // clean up at uninstall time. 8288 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8289 8290 if (DEBUG_ABI_SELECTION) { 8291 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8292 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8293 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8294 } 8295 8296 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8297 // We don't do this here during boot because we can do it all 8298 // at once after scanning all existing packages. 8299 // 8300 // We also do this *before* we perform dexopt on this package, so that 8301 // we can avoid redundant dexopts, and also to make sure we've got the 8302 // code and package path correct. 8303 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8304 pkg, true /* boot complete */); 8305 } 8306 8307 if (mFactoryTest && pkg.requestedPermissions.contains( 8308 android.Manifest.permission.FACTORY_TEST)) { 8309 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8310 } 8311 8312 ArrayList<PackageParser.Package> clientLibPkgs = null; 8313 8314 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8315 if (nonMutatedPs != null) { 8316 synchronized (mPackages) { 8317 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8318 } 8319 } 8320 return pkg; 8321 } 8322 8323 // Only privileged apps and updated privileged apps can add child packages. 8324 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8325 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8326 throw new PackageManagerException("Only privileged apps and updated " 8327 + "privileged apps can add child packages. Ignoring package " 8328 + pkg.packageName); 8329 } 8330 final int childCount = pkg.childPackages.size(); 8331 for (int i = 0; i < childCount; i++) { 8332 PackageParser.Package childPkg = pkg.childPackages.get(i); 8333 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8334 childPkg.packageName)) { 8335 throw new PackageManagerException("Cannot override a child package of " 8336 + "another disabled system app. Ignoring package " + pkg.packageName); 8337 } 8338 } 8339 } 8340 8341 // writer 8342 synchronized (mPackages) { 8343 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8344 // Only system apps can add new shared libraries. 8345 if (pkg.libraryNames != null) { 8346 for (int i=0; i<pkg.libraryNames.size(); i++) { 8347 String name = pkg.libraryNames.get(i); 8348 boolean allowed = false; 8349 if (pkg.isUpdatedSystemApp()) { 8350 // New library entries can only be added through the 8351 // system image. This is important to get rid of a lot 8352 // of nasty edge cases: for example if we allowed a non- 8353 // system update of the app to add a library, then uninstalling 8354 // the update would make the library go away, and assumptions 8355 // we made such as through app install filtering would now 8356 // have allowed apps on the device which aren't compatible 8357 // with it. Better to just have the restriction here, be 8358 // conservative, and create many fewer cases that can negatively 8359 // impact the user experience. 8360 final PackageSetting sysPs = mSettings 8361 .getDisabledSystemPkgLPr(pkg.packageName); 8362 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8363 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8364 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8365 allowed = true; 8366 break; 8367 } 8368 } 8369 } 8370 } else { 8371 allowed = true; 8372 } 8373 if (allowed) { 8374 if (!mSharedLibraries.containsKey(name)) { 8375 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8376 } else if (!name.equals(pkg.packageName)) { 8377 Slog.w(TAG, "Package " + pkg.packageName + " library " 8378 + name + " already exists; skipping"); 8379 } 8380 } else { 8381 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8382 + name + " that is not declared on system image; skipping"); 8383 } 8384 } 8385 if ((scanFlags & SCAN_BOOTING) == 0) { 8386 // If we are not booting, we need to update any applications 8387 // that are clients of our shared library. If we are booting, 8388 // this will all be done once the scan is complete. 8389 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8390 } 8391 } 8392 } 8393 } 8394 8395 if ((scanFlags & SCAN_BOOTING) != 0) { 8396 // No apps can run during boot scan, so they don't need to be frozen 8397 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8398 // Caller asked to not kill app, so it's probably not frozen 8399 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8400 // Caller asked us to ignore frozen check for some reason; they 8401 // probably didn't know the package name 8402 } else { 8403 // We're doing major surgery on this package, so it better be frozen 8404 // right now to keep it from launching 8405 checkPackageFrozen(pkgName); 8406 } 8407 8408 // Also need to kill any apps that are dependent on the library. 8409 if (clientLibPkgs != null) { 8410 for (int i=0; i<clientLibPkgs.size(); i++) { 8411 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8412 killApplication(clientPkg.applicationInfo.packageName, 8413 clientPkg.applicationInfo.uid, "update lib"); 8414 } 8415 } 8416 8417 // Make sure we're not adding any bogus keyset info 8418 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8419 ksms.assertScannedPackageValid(pkg); 8420 8421 // writer 8422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8423 8424 boolean createIdmapFailed = false; 8425 synchronized (mPackages) { 8426 // We don't expect installation to fail beyond this point 8427 8428 // Add the new setting to mSettings 8429 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8430 // Add the new setting to mPackages 8431 mPackages.put(pkg.applicationInfo.packageName, pkg); 8432 // Make sure we don't accidentally delete its data. 8433 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8434 while (iter.hasNext()) { 8435 PackageCleanItem item = iter.next(); 8436 if (pkgName.equals(item.packageName)) { 8437 iter.remove(); 8438 } 8439 } 8440 8441 // Take care of first install / last update times. 8442 if (currentTime != 0) { 8443 if (pkgSetting.firstInstallTime == 0) { 8444 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8445 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8446 pkgSetting.lastUpdateTime = currentTime; 8447 } 8448 } else if (pkgSetting.firstInstallTime == 0) { 8449 // We need *something*. Take time time stamp of the file. 8450 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8451 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8452 if (scanFileTime != pkgSetting.timeStamp) { 8453 // A package on the system image has changed; consider this 8454 // to be an update. 8455 pkgSetting.lastUpdateTime = scanFileTime; 8456 } 8457 } 8458 8459 // Add the package's KeySets to the global KeySetManagerService 8460 ksms.addScannedPackageLPw(pkg); 8461 8462 int N = pkg.providers.size(); 8463 StringBuilder r = null; 8464 int i; 8465 for (i=0; i<N; i++) { 8466 PackageParser.Provider p = pkg.providers.get(i); 8467 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8468 p.info.processName, pkg.applicationInfo.uid); 8469 mProviders.addProvider(p); 8470 p.syncable = p.info.isSyncable; 8471 if (p.info.authority != null) { 8472 String names[] = p.info.authority.split(";"); 8473 p.info.authority = null; 8474 for (int j = 0; j < names.length; j++) { 8475 if (j == 1 && p.syncable) { 8476 // We only want the first authority for a provider to possibly be 8477 // syncable, so if we already added this provider using a different 8478 // authority clear the syncable flag. We copy the provider before 8479 // changing it because the mProviders object contains a reference 8480 // to a provider that we don't want to change. 8481 // Only do this for the second authority since the resulting provider 8482 // object can be the same for all future authorities for this provider. 8483 p = new PackageParser.Provider(p); 8484 p.syncable = false; 8485 } 8486 if (!mProvidersByAuthority.containsKey(names[j])) { 8487 mProvidersByAuthority.put(names[j], p); 8488 if (p.info.authority == null) { 8489 p.info.authority = names[j]; 8490 } else { 8491 p.info.authority = p.info.authority + ";" + names[j]; 8492 } 8493 if (DEBUG_PACKAGE_SCANNING) { 8494 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8495 Log.d(TAG, "Registered content provider: " + names[j] 8496 + ", className = " + p.info.name + ", isSyncable = " 8497 + p.info.isSyncable); 8498 } 8499 } else { 8500 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8501 Slog.w(TAG, "Skipping provider name " + names[j] + 8502 " (in package " + pkg.applicationInfo.packageName + 8503 "): name already used by " 8504 + ((other != null && other.getComponentName() != null) 8505 ? other.getComponentName().getPackageName() : "?")); 8506 } 8507 } 8508 } 8509 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8510 if (r == null) { 8511 r = new StringBuilder(256); 8512 } else { 8513 r.append(' '); 8514 } 8515 r.append(p.info.name); 8516 } 8517 } 8518 if (r != null) { 8519 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8520 } 8521 8522 N = pkg.services.size(); 8523 r = null; 8524 for (i=0; i<N; i++) { 8525 PackageParser.Service s = pkg.services.get(i); 8526 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8527 s.info.processName, pkg.applicationInfo.uid); 8528 mServices.addService(s); 8529 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8530 if (r == null) { 8531 r = new StringBuilder(256); 8532 } else { 8533 r.append(' '); 8534 } 8535 r.append(s.info.name); 8536 } 8537 } 8538 if (r != null) { 8539 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8540 } 8541 8542 N = pkg.receivers.size(); 8543 r = null; 8544 for (i=0; i<N; i++) { 8545 PackageParser.Activity a = pkg.receivers.get(i); 8546 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8547 a.info.processName, pkg.applicationInfo.uid); 8548 mReceivers.addActivity(a, "receiver"); 8549 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8550 if (r == null) { 8551 r = new StringBuilder(256); 8552 } else { 8553 r.append(' '); 8554 } 8555 r.append(a.info.name); 8556 } 8557 } 8558 if (r != null) { 8559 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8560 } 8561 8562 N = pkg.activities.size(); 8563 r = null; 8564 for (i=0; i<N; i++) { 8565 PackageParser.Activity a = pkg.activities.get(i); 8566 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8567 a.info.processName, pkg.applicationInfo.uid); 8568 mActivities.addActivity(a, "activity"); 8569 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8570 if (r == null) { 8571 r = new StringBuilder(256); 8572 } else { 8573 r.append(' '); 8574 } 8575 r.append(a.info.name); 8576 } 8577 } 8578 if (r != null) { 8579 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8580 } 8581 8582 N = pkg.permissionGroups.size(); 8583 r = null; 8584 for (i=0; i<N; i++) { 8585 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8586 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8587 if (cur == null) { 8588 mPermissionGroups.put(pg.info.name, pg); 8589 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8590 if (r == null) { 8591 r = new StringBuilder(256); 8592 } else { 8593 r.append(' '); 8594 } 8595 r.append(pg.info.name); 8596 } 8597 } else { 8598 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8599 + pg.info.packageName + " ignored: original from " 8600 + cur.info.packageName); 8601 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8602 if (r == null) { 8603 r = new StringBuilder(256); 8604 } else { 8605 r.append(' '); 8606 } 8607 r.append("DUP:"); 8608 r.append(pg.info.name); 8609 } 8610 } 8611 } 8612 if (r != null) { 8613 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8614 } 8615 8616 N = pkg.permissions.size(); 8617 r = null; 8618 for (i=0; i<N; i++) { 8619 PackageParser.Permission p = pkg.permissions.get(i); 8620 8621 // Assume by default that we did not install this permission into the system. 8622 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8623 8624 // Now that permission groups have a special meaning, we ignore permission 8625 // groups for legacy apps to prevent unexpected behavior. In particular, 8626 // permissions for one app being granted to someone just becase they happen 8627 // to be in a group defined by another app (before this had no implications). 8628 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8629 p.group = mPermissionGroups.get(p.info.group); 8630 // Warn for a permission in an unknown group. 8631 if (p.info.group != null && p.group == null) { 8632 Slog.w(TAG, "Permission " + p.info.name + " from package " 8633 + p.info.packageName + " in an unknown group " + p.info.group); 8634 } 8635 } 8636 8637 ArrayMap<String, BasePermission> permissionMap = 8638 p.tree ? mSettings.mPermissionTrees 8639 : mSettings.mPermissions; 8640 BasePermission bp = permissionMap.get(p.info.name); 8641 8642 // Allow system apps to redefine non-system permissions 8643 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8644 final boolean currentOwnerIsSystem = (bp.perm != null 8645 && isSystemApp(bp.perm.owner)); 8646 if (isSystemApp(p.owner)) { 8647 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8648 // It's a built-in permission and no owner, take ownership now 8649 bp.packageSetting = pkgSetting; 8650 bp.perm = p; 8651 bp.uid = pkg.applicationInfo.uid; 8652 bp.sourcePackage = p.info.packageName; 8653 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8654 } else if (!currentOwnerIsSystem) { 8655 String msg = "New decl " + p.owner + " of permission " 8656 + p.info.name + " is system; overriding " + bp.sourcePackage; 8657 reportSettingsProblem(Log.WARN, msg); 8658 bp = null; 8659 } 8660 } 8661 } 8662 8663 if (bp == null) { 8664 bp = new BasePermission(p.info.name, p.info.packageName, 8665 BasePermission.TYPE_NORMAL); 8666 permissionMap.put(p.info.name, bp); 8667 } 8668 8669 if (bp.perm == null) { 8670 if (bp.sourcePackage == null 8671 || bp.sourcePackage.equals(p.info.packageName)) { 8672 BasePermission tree = findPermissionTreeLP(p.info.name); 8673 if (tree == null 8674 || tree.sourcePackage.equals(p.info.packageName)) { 8675 bp.packageSetting = pkgSetting; 8676 bp.perm = p; 8677 bp.uid = pkg.applicationInfo.uid; 8678 bp.sourcePackage = p.info.packageName; 8679 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8680 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8681 if (r == null) { 8682 r = new StringBuilder(256); 8683 } else { 8684 r.append(' '); 8685 } 8686 r.append(p.info.name); 8687 } 8688 } else { 8689 Slog.w(TAG, "Permission " + p.info.name + " from package " 8690 + p.info.packageName + " ignored: base tree " 8691 + tree.name + " is from package " 8692 + tree.sourcePackage); 8693 } 8694 } else { 8695 Slog.w(TAG, "Permission " + p.info.name + " from package " 8696 + p.info.packageName + " ignored: original from " 8697 + bp.sourcePackage); 8698 } 8699 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8700 if (r == null) { 8701 r = new StringBuilder(256); 8702 } else { 8703 r.append(' '); 8704 } 8705 r.append("DUP:"); 8706 r.append(p.info.name); 8707 } 8708 if (bp.perm == p) { 8709 bp.protectionLevel = p.info.protectionLevel; 8710 } 8711 } 8712 8713 if (r != null) { 8714 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8715 } 8716 8717 N = pkg.instrumentation.size(); 8718 r = null; 8719 for (i=0; i<N; i++) { 8720 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8721 a.info.packageName = pkg.applicationInfo.packageName; 8722 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8723 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8724 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8725 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8726 a.info.dataDir = pkg.applicationInfo.dataDir; 8727 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8728 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8729 8730 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8731 // need other information about the application, like the ABI and what not ? 8732 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8733 mInstrumentation.put(a.getComponentName(), a); 8734 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8735 if (r == null) { 8736 r = new StringBuilder(256); 8737 } else { 8738 r.append(' '); 8739 } 8740 r.append(a.info.name); 8741 } 8742 } 8743 if (r != null) { 8744 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8745 } 8746 8747 if (pkg.protectedBroadcasts != null) { 8748 N = pkg.protectedBroadcasts.size(); 8749 for (i=0; i<N; i++) { 8750 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8751 } 8752 } 8753 8754 pkgSetting.setTimeStamp(scanFileTime); 8755 8756 // Create idmap files for pairs of (packages, overlay packages). 8757 // Note: "android", ie framework-res.apk, is handled by native layers. 8758 if (pkg.mOverlayTarget != null) { 8759 // This is an overlay package. 8760 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8761 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8762 mOverlays.put(pkg.mOverlayTarget, 8763 new ArrayMap<String, PackageParser.Package>()); 8764 } 8765 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8766 map.put(pkg.packageName, pkg); 8767 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8768 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8769 createIdmapFailed = true; 8770 } 8771 } 8772 } else if (mOverlays.containsKey(pkg.packageName) && 8773 !pkg.packageName.equals("android")) { 8774 // This is a regular package, with one or more known overlay packages. 8775 createIdmapsForPackageLI(pkg); 8776 } 8777 } 8778 8779 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8780 8781 if (createIdmapFailed) { 8782 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8783 "scanPackageLI failed to createIdmap"); 8784 } 8785 return pkg; 8786 } 8787 8788 /** 8789 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8790 * is derived purely on the basis of the contents of {@code scanFile} and 8791 * {@code cpuAbiOverride}. 8792 * 8793 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8794 */ 8795 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8796 String cpuAbiOverride, boolean extractLibs) 8797 throws PackageManagerException { 8798 // TODO: We can probably be smarter about this stuff. For installed apps, 8799 // we can calculate this information at install time once and for all. For 8800 // system apps, we can probably assume that this information doesn't change 8801 // after the first boot scan. As things stand, we do lots of unnecessary work. 8802 8803 // Give ourselves some initial paths; we'll come back for another 8804 // pass once we've determined ABI below. 8805 setNativeLibraryPaths(pkg); 8806 8807 // We would never need to extract libs for forward-locked and external packages, 8808 // since the container service will do it for us. We shouldn't attempt to 8809 // extract libs from system app when it was not updated. 8810 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8811 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8812 extractLibs = false; 8813 } 8814 8815 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8816 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8817 8818 NativeLibraryHelper.Handle handle = null; 8819 try { 8820 handle = NativeLibraryHelper.Handle.create(pkg); 8821 // TODO(multiArch): This can be null for apps that didn't go through the 8822 // usual installation process. We can calculate it again, like we 8823 // do during install time. 8824 // 8825 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8826 // unnecessary. 8827 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8828 8829 // Null out the abis so that they can be recalculated. 8830 pkg.applicationInfo.primaryCpuAbi = null; 8831 pkg.applicationInfo.secondaryCpuAbi = null; 8832 if (isMultiArch(pkg.applicationInfo)) { 8833 // Warn if we've set an abiOverride for multi-lib packages.. 8834 // By definition, we need to copy both 32 and 64 bit libraries for 8835 // such packages. 8836 if (pkg.cpuAbiOverride != null 8837 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8838 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8839 } 8840 8841 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8842 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8843 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8844 if (extractLibs) { 8845 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8846 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8847 useIsaSpecificSubdirs); 8848 } else { 8849 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8850 } 8851 } 8852 8853 maybeThrowExceptionForMultiArchCopy( 8854 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8855 8856 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8857 if (extractLibs) { 8858 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8859 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8860 useIsaSpecificSubdirs); 8861 } else { 8862 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8863 } 8864 } 8865 8866 maybeThrowExceptionForMultiArchCopy( 8867 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8868 8869 if (abi64 >= 0) { 8870 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8871 } 8872 8873 if (abi32 >= 0) { 8874 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8875 if (abi64 >= 0) { 8876 if (pkg.use32bitAbi) { 8877 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8878 pkg.applicationInfo.primaryCpuAbi = abi; 8879 } else { 8880 pkg.applicationInfo.secondaryCpuAbi = abi; 8881 } 8882 } else { 8883 pkg.applicationInfo.primaryCpuAbi = abi; 8884 } 8885 } 8886 8887 } else { 8888 String[] abiList = (cpuAbiOverride != null) ? 8889 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8890 8891 // Enable gross and lame hacks for apps that are built with old 8892 // SDK tools. We must scan their APKs for renderscript bitcode and 8893 // not launch them if it's present. Don't bother checking on devices 8894 // that don't have 64 bit support. 8895 boolean needsRenderScriptOverride = false; 8896 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8897 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8898 abiList = Build.SUPPORTED_32_BIT_ABIS; 8899 needsRenderScriptOverride = true; 8900 } 8901 8902 final int copyRet; 8903 if (extractLibs) { 8904 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8905 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8906 } else { 8907 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8908 } 8909 8910 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8911 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8912 "Error unpackaging native libs for app, errorCode=" + copyRet); 8913 } 8914 8915 if (copyRet >= 0) { 8916 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8917 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8918 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8919 } else if (needsRenderScriptOverride) { 8920 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8921 } 8922 } 8923 } catch (IOException ioe) { 8924 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8925 } finally { 8926 IoUtils.closeQuietly(handle); 8927 } 8928 8929 // Now that we've calculated the ABIs and determined if it's an internal app, 8930 // we will go ahead and populate the nativeLibraryPath. 8931 setNativeLibraryPaths(pkg); 8932 } 8933 8934 /** 8935 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8936 * i.e, so that all packages can be run inside a single process if required. 8937 * 8938 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8939 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8940 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8941 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8942 * updating a package that belongs to a shared user. 8943 * 8944 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8945 * adds unnecessary complexity. 8946 */ 8947 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8948 PackageParser.Package scannedPackage, boolean bootComplete) { 8949 String requiredInstructionSet = null; 8950 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8951 requiredInstructionSet = VMRuntime.getInstructionSet( 8952 scannedPackage.applicationInfo.primaryCpuAbi); 8953 } 8954 8955 PackageSetting requirer = null; 8956 for (PackageSetting ps : packagesForUser) { 8957 // If packagesForUser contains scannedPackage, we skip it. This will happen 8958 // when scannedPackage is an update of an existing package. Without this check, 8959 // we will never be able to change the ABI of any package belonging to a shared 8960 // user, even if it's compatible with other packages. 8961 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8962 if (ps.primaryCpuAbiString == null) { 8963 continue; 8964 } 8965 8966 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8967 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8968 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8969 // this but there's not much we can do. 8970 String errorMessage = "Instruction set mismatch, " 8971 + ((requirer == null) ? "[caller]" : requirer) 8972 + " requires " + requiredInstructionSet + " whereas " + ps 8973 + " requires " + instructionSet; 8974 Slog.w(TAG, errorMessage); 8975 } 8976 8977 if (requiredInstructionSet == null) { 8978 requiredInstructionSet = instructionSet; 8979 requirer = ps; 8980 } 8981 } 8982 } 8983 8984 if (requiredInstructionSet != null) { 8985 String adjustedAbi; 8986 if (requirer != null) { 8987 // requirer != null implies that either scannedPackage was null or that scannedPackage 8988 // did not require an ABI, in which case we have to adjust scannedPackage to match 8989 // the ABI of the set (which is the same as requirer's ABI) 8990 adjustedAbi = requirer.primaryCpuAbiString; 8991 if (scannedPackage != null) { 8992 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8993 } 8994 } else { 8995 // requirer == null implies that we're updating all ABIs in the set to 8996 // match scannedPackage. 8997 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8998 } 8999 9000 for (PackageSetting ps : packagesForUser) { 9001 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9002 if (ps.primaryCpuAbiString != null) { 9003 continue; 9004 } 9005 9006 ps.primaryCpuAbiString = adjustedAbi; 9007 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9008 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9009 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9010 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9011 + " (requirer=" 9012 + (requirer == null ? "null" : requirer.pkg.packageName) 9013 + ", scannedPackage=" 9014 + (scannedPackage != null ? scannedPackage.packageName : "null") 9015 + ")"); 9016 try { 9017 mInstaller.rmdex(ps.codePathString, 9018 getDexCodeInstructionSet(getPreferredInstructionSet())); 9019 } catch (InstallerException ignored) { 9020 } 9021 } 9022 } 9023 } 9024 } 9025 } 9026 9027 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9028 synchronized (mPackages) { 9029 mResolverReplaced = true; 9030 // Set up information for custom user intent resolution activity. 9031 mResolveActivity.applicationInfo = pkg.applicationInfo; 9032 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9033 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9034 mResolveActivity.processName = pkg.applicationInfo.packageName; 9035 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9036 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9037 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9038 mResolveActivity.theme = 0; 9039 mResolveActivity.exported = true; 9040 mResolveActivity.enabled = true; 9041 mResolveInfo.activityInfo = mResolveActivity; 9042 mResolveInfo.priority = 0; 9043 mResolveInfo.preferredOrder = 0; 9044 mResolveInfo.match = 0; 9045 mResolveComponentName = mCustomResolverComponentName; 9046 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9047 mResolveComponentName); 9048 } 9049 } 9050 9051 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9052 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9053 9054 // Set up information for ephemeral installer activity 9055 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9056 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9057 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9058 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9059 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9060 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9061 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9062 mEphemeralInstallerActivity.theme = 0; 9063 mEphemeralInstallerActivity.exported = true; 9064 mEphemeralInstallerActivity.enabled = true; 9065 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9066 mEphemeralInstallerInfo.priority = 0; 9067 mEphemeralInstallerInfo.preferredOrder = 0; 9068 mEphemeralInstallerInfo.match = 0; 9069 9070 if (DEBUG_EPHEMERAL) { 9071 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9072 } 9073 } 9074 9075 private static String calculateBundledApkRoot(final String codePathString) { 9076 final File codePath = new File(codePathString); 9077 final File codeRoot; 9078 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9079 codeRoot = Environment.getRootDirectory(); 9080 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9081 codeRoot = Environment.getOemDirectory(); 9082 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9083 codeRoot = Environment.getVendorDirectory(); 9084 } else { 9085 // Unrecognized code path; take its top real segment as the apk root: 9086 // e.g. /something/app/blah.apk => /something 9087 try { 9088 File f = codePath.getCanonicalFile(); 9089 File parent = f.getParentFile(); // non-null because codePath is a file 9090 File tmp; 9091 while ((tmp = parent.getParentFile()) != null) { 9092 f = parent; 9093 parent = tmp; 9094 } 9095 codeRoot = f; 9096 Slog.w(TAG, "Unrecognized code path " 9097 + codePath + " - using " + codeRoot); 9098 } catch (IOException e) { 9099 // Can't canonicalize the code path -- shenanigans? 9100 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9101 return Environment.getRootDirectory().getPath(); 9102 } 9103 } 9104 return codeRoot.getPath(); 9105 } 9106 9107 /** 9108 * Derive and set the location of native libraries for the given package, 9109 * which varies depending on where and how the package was installed. 9110 */ 9111 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9112 final ApplicationInfo info = pkg.applicationInfo; 9113 final String codePath = pkg.codePath; 9114 final File codeFile = new File(codePath); 9115 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9116 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9117 9118 info.nativeLibraryRootDir = null; 9119 info.nativeLibraryRootRequiresIsa = false; 9120 info.nativeLibraryDir = null; 9121 info.secondaryNativeLibraryDir = null; 9122 9123 if (isApkFile(codeFile)) { 9124 // Monolithic install 9125 if (bundledApp) { 9126 // If "/system/lib64/apkname" exists, assume that is the per-package 9127 // native library directory to use; otherwise use "/system/lib/apkname". 9128 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9129 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9130 getPrimaryInstructionSet(info)); 9131 9132 // This is a bundled system app so choose the path based on the ABI. 9133 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9134 // is just the default path. 9135 final String apkName = deriveCodePathName(codePath); 9136 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9137 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9138 apkName).getAbsolutePath(); 9139 9140 if (info.secondaryCpuAbi != null) { 9141 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9142 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9143 secondaryLibDir, apkName).getAbsolutePath(); 9144 } 9145 } else if (asecApp) { 9146 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9147 .getAbsolutePath(); 9148 } else { 9149 final String apkName = deriveCodePathName(codePath); 9150 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9151 .getAbsolutePath(); 9152 } 9153 9154 info.nativeLibraryRootRequiresIsa = false; 9155 info.nativeLibraryDir = info.nativeLibraryRootDir; 9156 } else { 9157 // Cluster install 9158 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9159 info.nativeLibraryRootRequiresIsa = true; 9160 9161 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9162 getPrimaryInstructionSet(info)).getAbsolutePath(); 9163 9164 if (info.secondaryCpuAbi != null) { 9165 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9166 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9167 } 9168 } 9169 } 9170 9171 /** 9172 * Calculate the abis and roots for a bundled app. These can uniquely 9173 * be determined from the contents of the system partition, i.e whether 9174 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9175 * of this information, and instead assume that the system was built 9176 * sensibly. 9177 */ 9178 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9179 PackageSetting pkgSetting) { 9180 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9181 9182 // If "/system/lib64/apkname" exists, assume that is the per-package 9183 // native library directory to use; otherwise use "/system/lib/apkname". 9184 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9185 setBundledAppAbi(pkg, apkRoot, apkName); 9186 // pkgSetting might be null during rescan following uninstall of updates 9187 // to a bundled app, so accommodate that possibility. The settings in 9188 // that case will be established later from the parsed package. 9189 // 9190 // If the settings aren't null, sync them up with what we've just derived. 9191 // note that apkRoot isn't stored in the package settings. 9192 if (pkgSetting != null) { 9193 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9194 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9195 } 9196 } 9197 9198 /** 9199 * Deduces the ABI of a bundled app and sets the relevant fields on the 9200 * parsed pkg object. 9201 * 9202 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9203 * under which system libraries are installed. 9204 * @param apkName the name of the installed package. 9205 */ 9206 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9207 final File codeFile = new File(pkg.codePath); 9208 9209 final boolean has64BitLibs; 9210 final boolean has32BitLibs; 9211 if (isApkFile(codeFile)) { 9212 // Monolithic install 9213 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9214 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9215 } else { 9216 // Cluster install 9217 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9218 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9219 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9220 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9221 has64BitLibs = (new File(rootDir, isa)).exists(); 9222 } else { 9223 has64BitLibs = false; 9224 } 9225 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9226 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9227 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9228 has32BitLibs = (new File(rootDir, isa)).exists(); 9229 } else { 9230 has32BitLibs = false; 9231 } 9232 } 9233 9234 if (has64BitLibs && !has32BitLibs) { 9235 // The package has 64 bit libs, but not 32 bit libs. Its primary 9236 // ABI should be 64 bit. We can safely assume here that the bundled 9237 // native libraries correspond to the most preferred ABI in the list. 9238 9239 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9240 pkg.applicationInfo.secondaryCpuAbi = null; 9241 } else if (has32BitLibs && !has64BitLibs) { 9242 // The package has 32 bit libs but not 64 bit libs. Its primary 9243 // ABI should be 32 bit. 9244 9245 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9246 pkg.applicationInfo.secondaryCpuAbi = null; 9247 } else if (has32BitLibs && has64BitLibs) { 9248 // The application has both 64 and 32 bit bundled libraries. We check 9249 // here that the app declares multiArch support, and warn if it doesn't. 9250 // 9251 // We will be lenient here and record both ABIs. The primary will be the 9252 // ABI that's higher on the list, i.e, a device that's configured to prefer 9253 // 64 bit apps will see a 64 bit primary ABI, 9254 9255 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9256 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9257 } 9258 9259 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9260 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9261 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9262 } else { 9263 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9264 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9265 } 9266 } else { 9267 pkg.applicationInfo.primaryCpuAbi = null; 9268 pkg.applicationInfo.secondaryCpuAbi = null; 9269 } 9270 } 9271 9272 private void killApplication(String pkgName, int appId, String reason) { 9273 // Request the ActivityManager to kill the process(only for existing packages) 9274 // so that we do not end up in a confused state while the user is still using the older 9275 // version of the application while the new one gets installed. 9276 final long token = Binder.clearCallingIdentity(); 9277 try { 9278 IActivityManager am = ActivityManagerNative.getDefault(); 9279 if (am != null) { 9280 try { 9281 am.killApplicationWithAppId(pkgName, appId, reason); 9282 } catch (RemoteException e) { 9283 } 9284 } 9285 } finally { 9286 Binder.restoreCallingIdentity(token); 9287 } 9288 } 9289 9290 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9291 // Remove the parent package setting 9292 PackageSetting ps = (PackageSetting) pkg.mExtras; 9293 if (ps != null) { 9294 removePackageLI(ps, chatty); 9295 } 9296 // Remove the child package setting 9297 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9298 for (int i = 0; i < childCount; i++) { 9299 PackageParser.Package childPkg = pkg.childPackages.get(i); 9300 ps = (PackageSetting) childPkg.mExtras; 9301 if (ps != null) { 9302 removePackageLI(ps, chatty); 9303 } 9304 } 9305 } 9306 9307 void removePackageLI(PackageSetting ps, boolean chatty) { 9308 if (DEBUG_INSTALL) { 9309 if (chatty) 9310 Log.d(TAG, "Removing package " + ps.name); 9311 } 9312 9313 // writer 9314 synchronized (mPackages) { 9315 mPackages.remove(ps.name); 9316 final PackageParser.Package pkg = ps.pkg; 9317 if (pkg != null) { 9318 cleanPackageDataStructuresLILPw(pkg, chatty); 9319 } 9320 } 9321 } 9322 9323 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9324 if (DEBUG_INSTALL) { 9325 if (chatty) 9326 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9327 } 9328 9329 // writer 9330 synchronized (mPackages) { 9331 // Remove the parent package 9332 mPackages.remove(pkg.applicationInfo.packageName); 9333 cleanPackageDataStructuresLILPw(pkg, chatty); 9334 9335 // Remove the child packages 9336 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9337 for (int i = 0; i < childCount; i++) { 9338 PackageParser.Package childPkg = pkg.childPackages.get(i); 9339 mPackages.remove(childPkg.applicationInfo.packageName); 9340 cleanPackageDataStructuresLILPw(childPkg, chatty); 9341 } 9342 } 9343 } 9344 9345 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9346 int N = pkg.providers.size(); 9347 StringBuilder r = null; 9348 int i; 9349 for (i=0; i<N; i++) { 9350 PackageParser.Provider p = pkg.providers.get(i); 9351 mProviders.removeProvider(p); 9352 if (p.info.authority == null) { 9353 9354 /* There was another ContentProvider with this authority when 9355 * this app was installed so this authority is null, 9356 * Ignore it as we don't have to unregister the provider. 9357 */ 9358 continue; 9359 } 9360 String names[] = p.info.authority.split(";"); 9361 for (int j = 0; j < names.length; j++) { 9362 if (mProvidersByAuthority.get(names[j]) == p) { 9363 mProvidersByAuthority.remove(names[j]); 9364 if (DEBUG_REMOVE) { 9365 if (chatty) 9366 Log.d(TAG, "Unregistered content provider: " + names[j] 9367 + ", className = " + p.info.name + ", isSyncable = " 9368 + p.info.isSyncable); 9369 } 9370 } 9371 } 9372 if (DEBUG_REMOVE && chatty) { 9373 if (r == null) { 9374 r = new StringBuilder(256); 9375 } else { 9376 r.append(' '); 9377 } 9378 r.append(p.info.name); 9379 } 9380 } 9381 if (r != null) { 9382 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9383 } 9384 9385 N = pkg.services.size(); 9386 r = null; 9387 for (i=0; i<N; i++) { 9388 PackageParser.Service s = pkg.services.get(i); 9389 mServices.removeService(s); 9390 if (chatty) { 9391 if (r == null) { 9392 r = new StringBuilder(256); 9393 } else { 9394 r.append(' '); 9395 } 9396 r.append(s.info.name); 9397 } 9398 } 9399 if (r != null) { 9400 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9401 } 9402 9403 N = pkg.receivers.size(); 9404 r = null; 9405 for (i=0; i<N; i++) { 9406 PackageParser.Activity a = pkg.receivers.get(i); 9407 mReceivers.removeActivity(a, "receiver"); 9408 if (DEBUG_REMOVE && chatty) { 9409 if (r == null) { 9410 r = new StringBuilder(256); 9411 } else { 9412 r.append(' '); 9413 } 9414 r.append(a.info.name); 9415 } 9416 } 9417 if (r != null) { 9418 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9419 } 9420 9421 N = pkg.activities.size(); 9422 r = null; 9423 for (i=0; i<N; i++) { 9424 PackageParser.Activity a = pkg.activities.get(i); 9425 mActivities.removeActivity(a, "activity"); 9426 if (DEBUG_REMOVE && chatty) { 9427 if (r == null) { 9428 r = new StringBuilder(256); 9429 } else { 9430 r.append(' '); 9431 } 9432 r.append(a.info.name); 9433 } 9434 } 9435 if (r != null) { 9436 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9437 } 9438 9439 N = pkg.permissions.size(); 9440 r = null; 9441 for (i=0; i<N; i++) { 9442 PackageParser.Permission p = pkg.permissions.get(i); 9443 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9444 if (bp == null) { 9445 bp = mSettings.mPermissionTrees.get(p.info.name); 9446 } 9447 if (bp != null && bp.perm == p) { 9448 bp.perm = null; 9449 if (DEBUG_REMOVE && chatty) { 9450 if (r == null) { 9451 r = new StringBuilder(256); 9452 } else { 9453 r.append(' '); 9454 } 9455 r.append(p.info.name); 9456 } 9457 } 9458 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9459 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9460 if (appOpPkgs != null) { 9461 appOpPkgs.remove(pkg.packageName); 9462 } 9463 } 9464 } 9465 if (r != null) { 9466 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9467 } 9468 9469 N = pkg.requestedPermissions.size(); 9470 r = null; 9471 for (i=0; i<N; i++) { 9472 String perm = pkg.requestedPermissions.get(i); 9473 BasePermission bp = mSettings.mPermissions.get(perm); 9474 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9475 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9476 if (appOpPkgs != null) { 9477 appOpPkgs.remove(pkg.packageName); 9478 if (appOpPkgs.isEmpty()) { 9479 mAppOpPermissionPackages.remove(perm); 9480 } 9481 } 9482 } 9483 } 9484 if (r != null) { 9485 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9486 } 9487 9488 N = pkg.instrumentation.size(); 9489 r = null; 9490 for (i=0; i<N; i++) { 9491 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9492 mInstrumentation.remove(a.getComponentName()); 9493 if (DEBUG_REMOVE && chatty) { 9494 if (r == null) { 9495 r = new StringBuilder(256); 9496 } else { 9497 r.append(' '); 9498 } 9499 r.append(a.info.name); 9500 } 9501 } 9502 if (r != null) { 9503 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9504 } 9505 9506 r = null; 9507 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9508 // Only system apps can hold shared libraries. 9509 if (pkg.libraryNames != null) { 9510 for (i=0; i<pkg.libraryNames.size(); i++) { 9511 String name = pkg.libraryNames.get(i); 9512 SharedLibraryEntry cur = mSharedLibraries.get(name); 9513 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9514 mSharedLibraries.remove(name); 9515 if (DEBUG_REMOVE && chatty) { 9516 if (r == null) { 9517 r = new StringBuilder(256); 9518 } else { 9519 r.append(' '); 9520 } 9521 r.append(name); 9522 } 9523 } 9524 } 9525 } 9526 } 9527 if (r != null) { 9528 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9529 } 9530 } 9531 9532 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9533 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9534 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9535 return true; 9536 } 9537 } 9538 return false; 9539 } 9540 9541 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9542 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9543 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9544 9545 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9546 // Update the parent permissions 9547 updatePermissionsLPw(pkg.packageName, pkg, flags); 9548 // Update the child permissions 9549 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9550 for (int i = 0; i < childCount; i++) { 9551 PackageParser.Package childPkg = pkg.childPackages.get(i); 9552 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9553 } 9554 } 9555 9556 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9557 int flags) { 9558 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9559 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9560 } 9561 9562 private void updatePermissionsLPw(String changingPkg, 9563 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9564 // Make sure there are no dangling permission trees. 9565 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9566 while (it.hasNext()) { 9567 final BasePermission bp = it.next(); 9568 if (bp.packageSetting == null) { 9569 // We may not yet have parsed the package, so just see if 9570 // we still know about its settings. 9571 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9572 } 9573 if (bp.packageSetting == null) { 9574 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9575 + " from package " + bp.sourcePackage); 9576 it.remove(); 9577 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9578 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9579 Slog.i(TAG, "Removing old permission tree: " + bp.name 9580 + " from package " + bp.sourcePackage); 9581 flags |= UPDATE_PERMISSIONS_ALL; 9582 it.remove(); 9583 } 9584 } 9585 } 9586 9587 // Make sure all dynamic permissions have been assigned to a package, 9588 // and make sure there are no dangling permissions. 9589 it = mSettings.mPermissions.values().iterator(); 9590 while (it.hasNext()) { 9591 final BasePermission bp = it.next(); 9592 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9593 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9594 + bp.name + " pkg=" + bp.sourcePackage 9595 + " info=" + bp.pendingInfo); 9596 if (bp.packageSetting == null && bp.pendingInfo != null) { 9597 final BasePermission tree = findPermissionTreeLP(bp.name); 9598 if (tree != null && tree.perm != null) { 9599 bp.packageSetting = tree.packageSetting; 9600 bp.perm = new PackageParser.Permission(tree.perm.owner, 9601 new PermissionInfo(bp.pendingInfo)); 9602 bp.perm.info.packageName = tree.perm.info.packageName; 9603 bp.perm.info.name = bp.name; 9604 bp.uid = tree.uid; 9605 } 9606 } 9607 } 9608 if (bp.packageSetting == null) { 9609 // We may not yet have parsed the package, so just see if 9610 // we still know about its settings. 9611 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9612 } 9613 if (bp.packageSetting == null) { 9614 Slog.w(TAG, "Removing dangling permission: " + bp.name 9615 + " from package " + bp.sourcePackage); 9616 it.remove(); 9617 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9618 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9619 Slog.i(TAG, "Removing old permission: " + bp.name 9620 + " from package " + bp.sourcePackage); 9621 flags |= UPDATE_PERMISSIONS_ALL; 9622 it.remove(); 9623 } 9624 } 9625 } 9626 9627 // Now update the permissions for all packages, in particular 9628 // replace the granted permissions of the system packages. 9629 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9630 for (PackageParser.Package pkg : mPackages.values()) { 9631 if (pkg != pkgInfo) { 9632 // Only replace for packages on requested volume 9633 final String volumeUuid = getVolumeUuidForPackage(pkg); 9634 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9635 && Objects.equals(replaceVolumeUuid, volumeUuid); 9636 grantPermissionsLPw(pkg, replace, changingPkg); 9637 } 9638 } 9639 } 9640 9641 if (pkgInfo != null) { 9642 // Only replace for packages on requested volume 9643 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9644 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9645 && Objects.equals(replaceVolumeUuid, volumeUuid); 9646 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9647 } 9648 } 9649 9650 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9651 String packageOfInterest) { 9652 // IMPORTANT: There are two types of permissions: install and runtime. 9653 // Install time permissions are granted when the app is installed to 9654 // all device users and users added in the future. Runtime permissions 9655 // are granted at runtime explicitly to specific users. Normal and signature 9656 // protected permissions are install time permissions. Dangerous permissions 9657 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9658 // otherwise they are runtime permissions. This function does not manage 9659 // runtime permissions except for the case an app targeting Lollipop MR1 9660 // being upgraded to target a newer SDK, in which case dangerous permissions 9661 // are transformed from install time to runtime ones. 9662 9663 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9664 if (ps == null) { 9665 return; 9666 } 9667 9668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9669 9670 PermissionsState permissionsState = ps.getPermissionsState(); 9671 PermissionsState origPermissions = permissionsState; 9672 9673 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9674 9675 boolean runtimePermissionsRevoked = false; 9676 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9677 9678 boolean changedInstallPermission = false; 9679 9680 if (replace) { 9681 ps.installPermissionsFixed = false; 9682 if (!ps.isSharedUser()) { 9683 origPermissions = new PermissionsState(permissionsState); 9684 permissionsState.reset(); 9685 } else { 9686 // We need to know only about runtime permission changes since the 9687 // calling code always writes the install permissions state but 9688 // the runtime ones are written only if changed. The only cases of 9689 // changed runtime permissions here are promotion of an install to 9690 // runtime and revocation of a runtime from a shared user. 9691 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9692 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9693 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9694 runtimePermissionsRevoked = true; 9695 } 9696 } 9697 } 9698 9699 permissionsState.setGlobalGids(mGlobalGids); 9700 9701 final int N = pkg.requestedPermissions.size(); 9702 for (int i=0; i<N; i++) { 9703 final String name = pkg.requestedPermissions.get(i); 9704 final BasePermission bp = mSettings.mPermissions.get(name); 9705 9706 if (DEBUG_INSTALL) { 9707 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9708 } 9709 9710 if (bp == null || bp.packageSetting == null) { 9711 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9712 Slog.w(TAG, "Unknown permission " + name 9713 + " in package " + pkg.packageName); 9714 } 9715 continue; 9716 } 9717 9718 final String perm = bp.name; 9719 boolean allowedSig = false; 9720 int grant = GRANT_DENIED; 9721 9722 // Keep track of app op permissions. 9723 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9724 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9725 if (pkgs == null) { 9726 pkgs = new ArraySet<>(); 9727 mAppOpPermissionPackages.put(bp.name, pkgs); 9728 } 9729 pkgs.add(pkg.packageName); 9730 } 9731 9732 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9733 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9734 >= Build.VERSION_CODES.M; 9735 switch (level) { 9736 case PermissionInfo.PROTECTION_NORMAL: { 9737 // For all apps normal permissions are install time ones. 9738 grant = GRANT_INSTALL; 9739 } break; 9740 9741 case PermissionInfo.PROTECTION_DANGEROUS: { 9742 // If a permission review is required for legacy apps we represent 9743 // their permissions as always granted runtime ones since we need 9744 // to keep the review required permission flag per user while an 9745 // install permission's state is shared across all users. 9746 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9747 // For legacy apps dangerous permissions are install time ones. 9748 grant = GRANT_INSTALL; 9749 } else if (origPermissions.hasInstallPermission(bp.name)) { 9750 // For legacy apps that became modern, install becomes runtime. 9751 grant = GRANT_UPGRADE; 9752 } else if (mPromoteSystemApps 9753 && isSystemApp(ps) 9754 && mExistingSystemPackages.contains(ps.name)) { 9755 // For legacy system apps, install becomes runtime. 9756 // We cannot check hasInstallPermission() for system apps since those 9757 // permissions were granted implicitly and not persisted pre-M. 9758 grant = GRANT_UPGRADE; 9759 } else { 9760 // For modern apps keep runtime permissions unchanged. 9761 grant = GRANT_RUNTIME; 9762 } 9763 } break; 9764 9765 case PermissionInfo.PROTECTION_SIGNATURE: { 9766 // For all apps signature permissions are install time ones. 9767 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9768 if (allowedSig) { 9769 grant = GRANT_INSTALL; 9770 } 9771 } break; 9772 } 9773 9774 if (DEBUG_INSTALL) { 9775 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9776 } 9777 9778 if (grant != GRANT_DENIED) { 9779 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9780 // If this is an existing, non-system package, then 9781 // we can't add any new permissions to it. 9782 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9783 // Except... if this is a permission that was added 9784 // to the platform (note: need to only do this when 9785 // updating the platform). 9786 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9787 grant = GRANT_DENIED; 9788 } 9789 } 9790 } 9791 9792 switch (grant) { 9793 case GRANT_INSTALL: { 9794 // Revoke this as runtime permission to handle the case of 9795 // a runtime permission being downgraded to an install one. 9796 // Also in permission review mode we keep dangerous permissions 9797 // for legacy apps 9798 for (int userId : UserManagerService.getInstance().getUserIds()) { 9799 if (origPermissions.getRuntimePermissionState( 9800 bp.name, userId) != null) { 9801 // Revoke the runtime permission and clear the flags. 9802 origPermissions.revokeRuntimePermission(bp, userId); 9803 origPermissions.updatePermissionFlags(bp, userId, 9804 PackageManager.MASK_PERMISSION_FLAGS, 0); 9805 // If we revoked a permission permission, we have to write. 9806 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9807 changedRuntimePermissionUserIds, userId); 9808 } 9809 } 9810 // Grant an install permission. 9811 if (permissionsState.grantInstallPermission(bp) != 9812 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9813 changedInstallPermission = true; 9814 } 9815 } break; 9816 9817 case GRANT_RUNTIME: { 9818 // Grant previously granted runtime permissions. 9819 for (int userId : UserManagerService.getInstance().getUserIds()) { 9820 PermissionState permissionState = origPermissions 9821 .getRuntimePermissionState(bp.name, userId); 9822 int flags = permissionState != null 9823 ? permissionState.getFlags() : 0; 9824 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9825 if (permissionsState.grantRuntimePermission(bp, userId) == 9826 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9827 // If we cannot put the permission as it was, we have to write. 9828 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9829 changedRuntimePermissionUserIds, userId); 9830 } 9831 // If the app supports runtime permissions no need for a review. 9832 if (Build.PERMISSIONS_REVIEW_REQUIRED 9833 && appSupportsRuntimePermissions 9834 && (flags & PackageManager 9835 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9836 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9837 // Since we changed the flags, we have to write. 9838 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9839 changedRuntimePermissionUserIds, userId); 9840 } 9841 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9842 && !appSupportsRuntimePermissions) { 9843 // For legacy apps that need a permission review, every new 9844 // runtime permission is granted but it is pending a review. 9845 // We also need to review only platform defined runtime 9846 // permissions as these are the only ones the platform knows 9847 // how to disable the API to simulate revocation as legacy 9848 // apps don't expect to run with revoked permissions. 9849 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9850 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9851 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9852 // We changed the flags, hence have to write. 9853 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9854 changedRuntimePermissionUserIds, userId); 9855 } 9856 } 9857 if (permissionsState.grantRuntimePermission(bp, userId) 9858 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9859 // We changed the permission, hence have to write. 9860 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9861 changedRuntimePermissionUserIds, userId); 9862 } 9863 } 9864 // Propagate the permission flags. 9865 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9866 } 9867 } break; 9868 9869 case GRANT_UPGRADE: { 9870 // Grant runtime permissions for a previously held install permission. 9871 PermissionState permissionState = origPermissions 9872 .getInstallPermissionState(bp.name); 9873 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9874 9875 if (origPermissions.revokeInstallPermission(bp) 9876 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9877 // We will be transferring the permission flags, so clear them. 9878 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9879 PackageManager.MASK_PERMISSION_FLAGS, 0); 9880 changedInstallPermission = true; 9881 } 9882 9883 // If the permission is not to be promoted to runtime we ignore it and 9884 // also its other flags as they are not applicable to install permissions. 9885 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9886 for (int userId : currentUserIds) { 9887 if (permissionsState.grantRuntimePermission(bp, userId) != 9888 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9889 // Transfer the permission flags. 9890 permissionsState.updatePermissionFlags(bp, userId, 9891 flags, flags); 9892 // If we granted the permission, we have to write. 9893 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9894 changedRuntimePermissionUserIds, userId); 9895 } 9896 } 9897 } 9898 } break; 9899 9900 default: { 9901 if (packageOfInterest == null 9902 || packageOfInterest.equals(pkg.packageName)) { 9903 Slog.w(TAG, "Not granting permission " + perm 9904 + " to package " + pkg.packageName 9905 + " because it was previously installed without"); 9906 } 9907 } break; 9908 } 9909 } else { 9910 if (permissionsState.revokeInstallPermission(bp) != 9911 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9912 // Also drop the permission flags. 9913 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9914 PackageManager.MASK_PERMISSION_FLAGS, 0); 9915 changedInstallPermission = true; 9916 Slog.i(TAG, "Un-granting permission " + perm 9917 + " from package " + pkg.packageName 9918 + " (protectionLevel=" + bp.protectionLevel 9919 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9920 + ")"); 9921 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9922 // Don't print warning for app op permissions, since it is fine for them 9923 // not to be granted, there is a UI for the user to decide. 9924 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9925 Slog.w(TAG, "Not granting permission " + perm 9926 + " to package " + pkg.packageName 9927 + " (protectionLevel=" + bp.protectionLevel 9928 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9929 + ")"); 9930 } 9931 } 9932 } 9933 } 9934 9935 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9936 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9937 // This is the first that we have heard about this package, so the 9938 // permissions we have now selected are fixed until explicitly 9939 // changed. 9940 ps.installPermissionsFixed = true; 9941 } 9942 9943 // Persist the runtime permissions state for users with changes. If permissions 9944 // were revoked because no app in the shared user declares them we have to 9945 // write synchronously to avoid losing runtime permissions state. 9946 for (int userId : changedRuntimePermissionUserIds) { 9947 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9948 } 9949 9950 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9951 } 9952 9953 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9954 boolean allowed = false; 9955 final int NP = PackageParser.NEW_PERMISSIONS.length; 9956 for (int ip=0; ip<NP; ip++) { 9957 final PackageParser.NewPermissionInfo npi 9958 = PackageParser.NEW_PERMISSIONS[ip]; 9959 if (npi.name.equals(perm) 9960 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9961 allowed = true; 9962 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9963 + pkg.packageName); 9964 break; 9965 } 9966 } 9967 return allowed; 9968 } 9969 9970 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9971 BasePermission bp, PermissionsState origPermissions) { 9972 boolean allowed; 9973 allowed = (compareSignatures( 9974 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9975 == PackageManager.SIGNATURE_MATCH) 9976 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9977 == PackageManager.SIGNATURE_MATCH); 9978 if (!allowed && (bp.protectionLevel 9979 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9980 if (isSystemApp(pkg)) { 9981 // For updated system applications, a system permission 9982 // is granted only if it had been defined by the original application. 9983 if (pkg.isUpdatedSystemApp()) { 9984 final PackageSetting sysPs = mSettings 9985 .getDisabledSystemPkgLPr(pkg.packageName); 9986 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9987 // If the original was granted this permission, we take 9988 // that grant decision as read and propagate it to the 9989 // update. 9990 if (sysPs.isPrivileged()) { 9991 allowed = true; 9992 } 9993 } else { 9994 // The system apk may have been updated with an older 9995 // version of the one on the data partition, but which 9996 // granted a new system permission that it didn't have 9997 // before. In this case we do want to allow the app to 9998 // now get the new permission if the ancestral apk is 9999 // privileged to get it. 10000 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10001 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10002 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10003 allowed = true; 10004 break; 10005 } 10006 } 10007 } 10008 // Also if a privileged parent package on the system image or any of 10009 // its children requested a privileged permission, the updated child 10010 // packages can also get the permission. 10011 if (pkg.parentPackage != null) { 10012 final PackageSetting disabledSysParentPs = mSettings 10013 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10014 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10015 && disabledSysParentPs.isPrivileged()) { 10016 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10017 allowed = true; 10018 } else if (disabledSysParentPs.pkg.childPackages != null) { 10019 final int count = disabledSysParentPs.pkg.childPackages.size(); 10020 for (int i = 0; i < count; i++) { 10021 PackageParser.Package disabledSysChildPkg = 10022 disabledSysParentPs.pkg.childPackages.get(i); 10023 if (isPackageRequestingPermission(disabledSysChildPkg, 10024 perm)) { 10025 allowed = true; 10026 break; 10027 } 10028 } 10029 } 10030 } 10031 } 10032 } 10033 } else { 10034 allowed = isPrivilegedApp(pkg); 10035 } 10036 } 10037 } 10038 if (!allowed) { 10039 if (!allowed && (bp.protectionLevel 10040 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10041 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10042 // If this was a previously normal/dangerous permission that got moved 10043 // to a system permission as part of the runtime permission redesign, then 10044 // we still want to blindly grant it to old apps. 10045 allowed = true; 10046 } 10047 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10048 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10049 // If this permission is to be granted to the system installer and 10050 // this app is an installer, then it gets the permission. 10051 allowed = true; 10052 } 10053 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10054 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10055 // If this permission is to be granted to the system verifier and 10056 // this app is a verifier, then it gets the permission. 10057 allowed = true; 10058 } 10059 if (!allowed && (bp.protectionLevel 10060 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10061 && isSystemApp(pkg)) { 10062 // Any pre-installed system app is allowed to get this permission. 10063 allowed = true; 10064 } 10065 if (!allowed && (bp.protectionLevel 10066 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10067 // For development permissions, a development permission 10068 // is granted only if it was already granted. 10069 allowed = origPermissions.hasInstallPermission(perm); 10070 } 10071 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10072 && pkg.packageName.equals(mSetupWizardPackage)) { 10073 // If this permission is to be granted to the system setup wizard and 10074 // this app is a setup wizard, then it gets the permission. 10075 allowed = true; 10076 } 10077 } 10078 return allowed; 10079 } 10080 10081 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10082 final int permCount = pkg.requestedPermissions.size(); 10083 for (int j = 0; j < permCount; j++) { 10084 String requestedPermission = pkg.requestedPermissions.get(j); 10085 if (permission.equals(requestedPermission)) { 10086 return true; 10087 } 10088 } 10089 return false; 10090 } 10091 10092 final class ActivityIntentResolver 10093 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10094 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10095 boolean defaultOnly, int userId) { 10096 if (!sUserManager.exists(userId)) return null; 10097 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10098 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10099 } 10100 10101 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10102 int userId) { 10103 if (!sUserManager.exists(userId)) return null; 10104 mFlags = flags; 10105 return super.queryIntent(intent, resolvedType, 10106 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10107 } 10108 10109 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10110 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10111 if (!sUserManager.exists(userId)) return null; 10112 if (packageActivities == null) { 10113 return null; 10114 } 10115 mFlags = flags; 10116 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10117 final int N = packageActivities.size(); 10118 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10119 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10120 10121 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10122 for (int i = 0; i < N; ++i) { 10123 intentFilters = packageActivities.get(i).intents; 10124 if (intentFilters != null && intentFilters.size() > 0) { 10125 PackageParser.ActivityIntentInfo[] array = 10126 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10127 intentFilters.toArray(array); 10128 listCut.add(array); 10129 } 10130 } 10131 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10132 } 10133 10134 /** 10135 * Finds a privileged activity that matches the specified activity names. 10136 */ 10137 private PackageParser.Activity findMatchingActivity( 10138 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10139 for (PackageParser.Activity sysActivity : activityList) { 10140 if (sysActivity.info.name.equals(activityInfo.name)) { 10141 return sysActivity; 10142 } 10143 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10144 return sysActivity; 10145 } 10146 if (sysActivity.info.targetActivity != null) { 10147 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10148 return sysActivity; 10149 } 10150 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10151 return sysActivity; 10152 } 10153 } 10154 } 10155 return null; 10156 } 10157 10158 public class IterGenerator<E> { 10159 public Iterator<E> generate(ActivityIntentInfo info) { 10160 return null; 10161 } 10162 } 10163 10164 public class ActionIterGenerator extends IterGenerator<String> { 10165 @Override 10166 public Iterator<String> generate(ActivityIntentInfo info) { 10167 return info.actionsIterator(); 10168 } 10169 } 10170 10171 public class CategoriesIterGenerator extends IterGenerator<String> { 10172 @Override 10173 public Iterator<String> generate(ActivityIntentInfo info) { 10174 return info.categoriesIterator(); 10175 } 10176 } 10177 10178 public class SchemesIterGenerator extends IterGenerator<String> { 10179 @Override 10180 public Iterator<String> generate(ActivityIntentInfo info) { 10181 return info.schemesIterator(); 10182 } 10183 } 10184 10185 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10186 @Override 10187 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10188 return info.authoritiesIterator(); 10189 } 10190 } 10191 10192 /** 10193 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10194 * MODIFIED. Do not pass in a list that should not be changed. 10195 */ 10196 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10197 IterGenerator<T> generator, Iterator<T> searchIterator) { 10198 // loop through the set of actions; every one must be found in the intent filter 10199 while (searchIterator.hasNext()) { 10200 // we must have at least one filter in the list to consider a match 10201 if (intentList.size() == 0) { 10202 break; 10203 } 10204 10205 final T searchAction = searchIterator.next(); 10206 10207 // loop through the set of intent filters 10208 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10209 while (intentIter.hasNext()) { 10210 final ActivityIntentInfo intentInfo = intentIter.next(); 10211 boolean selectionFound = false; 10212 10213 // loop through the intent filter's selection criteria; at least one 10214 // of them must match the searched criteria 10215 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10216 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10217 final T intentSelection = intentSelectionIter.next(); 10218 if (intentSelection != null && intentSelection.equals(searchAction)) { 10219 selectionFound = true; 10220 break; 10221 } 10222 } 10223 10224 // the selection criteria wasn't found in this filter's set; this filter 10225 // is not a potential match 10226 if (!selectionFound) { 10227 intentIter.remove(); 10228 } 10229 } 10230 } 10231 } 10232 10233 private boolean isProtectedAction(ActivityIntentInfo filter) { 10234 final Iterator<String> actionsIter = filter.actionsIterator(); 10235 while (actionsIter != null && actionsIter.hasNext()) { 10236 final String filterAction = actionsIter.next(); 10237 if (PROTECTED_ACTIONS.contains(filterAction)) { 10238 return true; 10239 } 10240 } 10241 return false; 10242 } 10243 10244 /** 10245 * Adjusts the priority of the given intent filter according to policy. 10246 * <p> 10247 * <ul> 10248 * <li>The priority for non privileged applications is capped to '0'</li> 10249 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10250 * <li>The priority for unbundled updates to privileged applications is capped to the 10251 * priority defined on the system partition</li> 10252 * </ul> 10253 * <p> 10254 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10255 * allowed to obtain any priority on any action. 10256 */ 10257 private void adjustPriority( 10258 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10259 // nothing to do; priority is fine as-is 10260 if (intent.getPriority() <= 0) { 10261 return; 10262 } 10263 10264 final ActivityInfo activityInfo = intent.activity.info; 10265 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10266 10267 final boolean privilegedApp = 10268 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10269 if (!privilegedApp) { 10270 // non-privileged applications can never define a priority >0 10271 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10272 + " package: " + applicationInfo.packageName 10273 + " activity: " + intent.activity.className 10274 + " origPrio: " + intent.getPriority()); 10275 intent.setPriority(0); 10276 return; 10277 } 10278 10279 if (systemActivities == null) { 10280 // the system package is not disabled; we're parsing the system partition 10281 if (isProtectedAction(intent)) { 10282 if (mDeferProtectedFilters) { 10283 // We can't deal with these just yet. No component should ever obtain a 10284 // >0 priority for a protected actions, with ONE exception -- the setup 10285 // wizard. The setup wizard, however, cannot be known until we're able to 10286 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10287 // until all intent filters have been processed. Chicken, meet egg. 10288 // Let the filter temporarily have a high priority and rectify the 10289 // priorities after all system packages have been scanned. 10290 mProtectedFilters.add(intent); 10291 if (DEBUG_FILTERS) { 10292 Slog.i(TAG, "Protected action; save for later;" 10293 + " package: " + applicationInfo.packageName 10294 + " activity: " + intent.activity.className 10295 + " origPrio: " + intent.getPriority()); 10296 } 10297 return; 10298 } else { 10299 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10300 Slog.i(TAG, "No setup wizard;" 10301 + " All protected intents capped to priority 0"); 10302 } 10303 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10304 if (DEBUG_FILTERS) { 10305 Slog.i(TAG, "Found setup wizard;" 10306 + " allow priority " + intent.getPriority() + ";" 10307 + " package: " + intent.activity.info.packageName 10308 + " activity: " + intent.activity.className 10309 + " priority: " + intent.getPriority()); 10310 } 10311 // setup wizard gets whatever it wants 10312 return; 10313 } 10314 Slog.w(TAG, "Protected action; cap priority to 0;" 10315 + " package: " + intent.activity.info.packageName 10316 + " activity: " + intent.activity.className 10317 + " origPrio: " + intent.getPriority()); 10318 intent.setPriority(0); 10319 return; 10320 } 10321 } 10322 // privileged apps on the system image get whatever priority they request 10323 return; 10324 } 10325 10326 // privileged app unbundled update ... try to find the same activity 10327 final PackageParser.Activity foundActivity = 10328 findMatchingActivity(systemActivities, activityInfo); 10329 if (foundActivity == null) { 10330 // this is a new activity; it cannot obtain >0 priority 10331 if (DEBUG_FILTERS) { 10332 Slog.i(TAG, "New activity; cap priority to 0;" 10333 + " package: " + applicationInfo.packageName 10334 + " activity: " + intent.activity.className 10335 + " origPrio: " + intent.getPriority()); 10336 } 10337 intent.setPriority(0); 10338 return; 10339 } 10340 10341 // found activity, now check for filter equivalence 10342 10343 // a shallow copy is enough; we modify the list, not its contents 10344 final List<ActivityIntentInfo> intentListCopy = 10345 new ArrayList<>(foundActivity.intents); 10346 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10347 10348 // find matching action subsets 10349 final Iterator<String> actionsIterator = intent.actionsIterator(); 10350 if (actionsIterator != null) { 10351 getIntentListSubset( 10352 intentListCopy, new ActionIterGenerator(), actionsIterator); 10353 if (intentListCopy.size() == 0) { 10354 // no more intents to match; we're not equivalent 10355 if (DEBUG_FILTERS) { 10356 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10357 + " package: " + applicationInfo.packageName 10358 + " activity: " + intent.activity.className 10359 + " origPrio: " + intent.getPriority()); 10360 } 10361 intent.setPriority(0); 10362 return; 10363 } 10364 } 10365 10366 // find matching category subsets 10367 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10368 if (categoriesIterator != null) { 10369 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10370 categoriesIterator); 10371 if (intentListCopy.size() == 0) { 10372 // no more intents to match; we're not equivalent 10373 if (DEBUG_FILTERS) { 10374 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10375 + " package: " + applicationInfo.packageName 10376 + " activity: " + intent.activity.className 10377 + " origPrio: " + intent.getPriority()); 10378 } 10379 intent.setPriority(0); 10380 return; 10381 } 10382 } 10383 10384 // find matching schemes subsets 10385 final Iterator<String> schemesIterator = intent.schemesIterator(); 10386 if (schemesIterator != null) { 10387 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10388 schemesIterator); 10389 if (intentListCopy.size() == 0) { 10390 // no more intents to match; we're not equivalent 10391 if (DEBUG_FILTERS) { 10392 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10393 + " package: " + applicationInfo.packageName 10394 + " activity: " + intent.activity.className 10395 + " origPrio: " + intent.getPriority()); 10396 } 10397 intent.setPriority(0); 10398 return; 10399 } 10400 } 10401 10402 // find matching authorities subsets 10403 final Iterator<IntentFilter.AuthorityEntry> 10404 authoritiesIterator = intent.authoritiesIterator(); 10405 if (authoritiesIterator != null) { 10406 getIntentListSubset(intentListCopy, 10407 new AuthoritiesIterGenerator(), 10408 authoritiesIterator); 10409 if (intentListCopy.size() == 0) { 10410 // no more intents to match; we're not equivalent 10411 if (DEBUG_FILTERS) { 10412 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10413 + " package: " + applicationInfo.packageName 10414 + " activity: " + intent.activity.className 10415 + " origPrio: " + intent.getPriority()); 10416 } 10417 intent.setPriority(0); 10418 return; 10419 } 10420 } 10421 10422 // we found matching filter(s); app gets the max priority of all intents 10423 int cappedPriority = 0; 10424 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10425 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10426 } 10427 if (intent.getPriority() > cappedPriority) { 10428 if (DEBUG_FILTERS) { 10429 Slog.i(TAG, "Found matching filter(s);" 10430 + " cap priority to " + cappedPriority + ";" 10431 + " package: " + applicationInfo.packageName 10432 + " activity: " + intent.activity.className 10433 + " origPrio: " + intent.getPriority()); 10434 } 10435 intent.setPriority(cappedPriority); 10436 return; 10437 } 10438 // all this for nothing; the requested priority was <= what was on the system 10439 } 10440 10441 public final void addActivity(PackageParser.Activity a, String type) { 10442 mActivities.put(a.getComponentName(), a); 10443 if (DEBUG_SHOW_INFO) 10444 Log.v( 10445 TAG, " " + type + " " + 10446 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10447 if (DEBUG_SHOW_INFO) 10448 Log.v(TAG, " Class=" + a.info.name); 10449 final int NI = a.intents.size(); 10450 for (int j=0; j<NI; j++) { 10451 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10452 if ("activity".equals(type)) { 10453 final PackageSetting ps = 10454 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10455 final List<PackageParser.Activity> systemActivities = 10456 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10457 adjustPriority(systemActivities, intent); 10458 } 10459 if (DEBUG_SHOW_INFO) { 10460 Log.v(TAG, " IntentFilter:"); 10461 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10462 } 10463 if (!intent.debugCheck()) { 10464 Log.w(TAG, "==> For Activity " + a.info.name); 10465 } 10466 addFilter(intent); 10467 } 10468 } 10469 10470 public final void removeActivity(PackageParser.Activity a, String type) { 10471 mActivities.remove(a.getComponentName()); 10472 if (DEBUG_SHOW_INFO) { 10473 Log.v(TAG, " " + type + " " 10474 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10475 : a.info.name) + ":"); 10476 Log.v(TAG, " Class=" + a.info.name); 10477 } 10478 final int NI = a.intents.size(); 10479 for (int j=0; j<NI; j++) { 10480 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10481 if (DEBUG_SHOW_INFO) { 10482 Log.v(TAG, " IntentFilter:"); 10483 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10484 } 10485 removeFilter(intent); 10486 } 10487 } 10488 10489 @Override 10490 protected boolean allowFilterResult( 10491 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10492 ActivityInfo filterAi = filter.activity.info; 10493 for (int i=dest.size()-1; i>=0; i--) { 10494 ActivityInfo destAi = dest.get(i).activityInfo; 10495 if (destAi.name == filterAi.name 10496 && destAi.packageName == filterAi.packageName) { 10497 return false; 10498 } 10499 } 10500 return true; 10501 } 10502 10503 @Override 10504 protected ActivityIntentInfo[] newArray(int size) { 10505 return new ActivityIntentInfo[size]; 10506 } 10507 10508 @Override 10509 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10510 if (!sUserManager.exists(userId)) return true; 10511 PackageParser.Package p = filter.activity.owner; 10512 if (p != null) { 10513 PackageSetting ps = (PackageSetting)p.mExtras; 10514 if (ps != null) { 10515 // System apps are never considered stopped for purposes of 10516 // filtering, because there may be no way for the user to 10517 // actually re-launch them. 10518 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10519 && ps.getStopped(userId); 10520 } 10521 } 10522 return false; 10523 } 10524 10525 @Override 10526 protected boolean isPackageForFilter(String packageName, 10527 PackageParser.ActivityIntentInfo info) { 10528 return packageName.equals(info.activity.owner.packageName); 10529 } 10530 10531 @Override 10532 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10533 int match, int userId) { 10534 if (!sUserManager.exists(userId)) return null; 10535 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10536 return null; 10537 } 10538 final PackageParser.Activity activity = info.activity; 10539 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10540 if (ps == null) { 10541 return null; 10542 } 10543 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10544 ps.readUserState(userId), userId); 10545 if (ai == null) { 10546 return null; 10547 } 10548 final ResolveInfo res = new ResolveInfo(); 10549 res.activityInfo = ai; 10550 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10551 res.filter = info; 10552 } 10553 if (info != null) { 10554 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10555 } 10556 res.priority = info.getPriority(); 10557 res.preferredOrder = activity.owner.mPreferredOrder; 10558 //System.out.println("Result: " + res.activityInfo.className + 10559 // " = " + res.priority); 10560 res.match = match; 10561 res.isDefault = info.hasDefault; 10562 res.labelRes = info.labelRes; 10563 res.nonLocalizedLabel = info.nonLocalizedLabel; 10564 if (userNeedsBadging(userId)) { 10565 res.noResourceId = true; 10566 } else { 10567 res.icon = info.icon; 10568 } 10569 res.iconResourceId = info.icon; 10570 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10571 return res; 10572 } 10573 10574 @Override 10575 protected void sortResults(List<ResolveInfo> results) { 10576 Collections.sort(results, mResolvePrioritySorter); 10577 } 10578 10579 @Override 10580 protected void dumpFilter(PrintWriter out, String prefix, 10581 PackageParser.ActivityIntentInfo filter) { 10582 out.print(prefix); out.print( 10583 Integer.toHexString(System.identityHashCode(filter.activity))); 10584 out.print(' '); 10585 filter.activity.printComponentShortName(out); 10586 out.print(" filter "); 10587 out.println(Integer.toHexString(System.identityHashCode(filter))); 10588 } 10589 10590 @Override 10591 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10592 return filter.activity; 10593 } 10594 10595 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10596 PackageParser.Activity activity = (PackageParser.Activity)label; 10597 out.print(prefix); out.print( 10598 Integer.toHexString(System.identityHashCode(activity))); 10599 out.print(' '); 10600 activity.printComponentShortName(out); 10601 if (count > 1) { 10602 out.print(" ("); out.print(count); out.print(" filters)"); 10603 } 10604 out.println(); 10605 } 10606 10607 // Keys are String (activity class name), values are Activity. 10608 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10609 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10610 private int mFlags; 10611 } 10612 10613 private final class ServiceIntentResolver 10614 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10615 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10616 boolean defaultOnly, int userId) { 10617 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10618 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10619 } 10620 10621 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10622 int userId) { 10623 if (!sUserManager.exists(userId)) return null; 10624 mFlags = flags; 10625 return super.queryIntent(intent, resolvedType, 10626 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10627 } 10628 10629 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10630 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10631 if (!sUserManager.exists(userId)) return null; 10632 if (packageServices == null) { 10633 return null; 10634 } 10635 mFlags = flags; 10636 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10637 final int N = packageServices.size(); 10638 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10639 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10640 10641 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10642 for (int i = 0; i < N; ++i) { 10643 intentFilters = packageServices.get(i).intents; 10644 if (intentFilters != null && intentFilters.size() > 0) { 10645 PackageParser.ServiceIntentInfo[] array = 10646 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10647 intentFilters.toArray(array); 10648 listCut.add(array); 10649 } 10650 } 10651 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10652 } 10653 10654 public final void addService(PackageParser.Service s) { 10655 mServices.put(s.getComponentName(), s); 10656 if (DEBUG_SHOW_INFO) { 10657 Log.v(TAG, " " 10658 + (s.info.nonLocalizedLabel != null 10659 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10660 Log.v(TAG, " Class=" + s.info.name); 10661 } 10662 final int NI = s.intents.size(); 10663 int j; 10664 for (j=0; j<NI; j++) { 10665 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10666 if (DEBUG_SHOW_INFO) { 10667 Log.v(TAG, " IntentFilter:"); 10668 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10669 } 10670 if (!intent.debugCheck()) { 10671 Log.w(TAG, "==> For Service " + s.info.name); 10672 } 10673 addFilter(intent); 10674 } 10675 } 10676 10677 public final void removeService(PackageParser.Service s) { 10678 mServices.remove(s.getComponentName()); 10679 if (DEBUG_SHOW_INFO) { 10680 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10681 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10682 Log.v(TAG, " Class=" + s.info.name); 10683 } 10684 final int NI = s.intents.size(); 10685 int j; 10686 for (j=0; j<NI; j++) { 10687 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10688 if (DEBUG_SHOW_INFO) { 10689 Log.v(TAG, " IntentFilter:"); 10690 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10691 } 10692 removeFilter(intent); 10693 } 10694 } 10695 10696 @Override 10697 protected boolean allowFilterResult( 10698 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10699 ServiceInfo filterSi = filter.service.info; 10700 for (int i=dest.size()-1; i>=0; i--) { 10701 ServiceInfo destAi = dest.get(i).serviceInfo; 10702 if (destAi.name == filterSi.name 10703 && destAi.packageName == filterSi.packageName) { 10704 return false; 10705 } 10706 } 10707 return true; 10708 } 10709 10710 @Override 10711 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10712 return new PackageParser.ServiceIntentInfo[size]; 10713 } 10714 10715 @Override 10716 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10717 if (!sUserManager.exists(userId)) return true; 10718 PackageParser.Package p = filter.service.owner; 10719 if (p != null) { 10720 PackageSetting ps = (PackageSetting)p.mExtras; 10721 if (ps != null) { 10722 // System apps are never considered stopped for purposes of 10723 // filtering, because there may be no way for the user to 10724 // actually re-launch them. 10725 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10726 && ps.getStopped(userId); 10727 } 10728 } 10729 return false; 10730 } 10731 10732 @Override 10733 protected boolean isPackageForFilter(String packageName, 10734 PackageParser.ServiceIntentInfo info) { 10735 return packageName.equals(info.service.owner.packageName); 10736 } 10737 10738 @Override 10739 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10740 int match, int userId) { 10741 if (!sUserManager.exists(userId)) return null; 10742 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10743 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10744 return null; 10745 } 10746 final PackageParser.Service service = info.service; 10747 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10748 if (ps == null) { 10749 return null; 10750 } 10751 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10752 ps.readUserState(userId), userId); 10753 if (si == null) { 10754 return null; 10755 } 10756 final ResolveInfo res = new ResolveInfo(); 10757 res.serviceInfo = si; 10758 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10759 res.filter = filter; 10760 } 10761 res.priority = info.getPriority(); 10762 res.preferredOrder = service.owner.mPreferredOrder; 10763 res.match = match; 10764 res.isDefault = info.hasDefault; 10765 res.labelRes = info.labelRes; 10766 res.nonLocalizedLabel = info.nonLocalizedLabel; 10767 res.icon = info.icon; 10768 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10769 return res; 10770 } 10771 10772 @Override 10773 protected void sortResults(List<ResolveInfo> results) { 10774 Collections.sort(results, mResolvePrioritySorter); 10775 } 10776 10777 @Override 10778 protected void dumpFilter(PrintWriter out, String prefix, 10779 PackageParser.ServiceIntentInfo filter) { 10780 out.print(prefix); out.print( 10781 Integer.toHexString(System.identityHashCode(filter.service))); 10782 out.print(' '); 10783 filter.service.printComponentShortName(out); 10784 out.print(" filter "); 10785 out.println(Integer.toHexString(System.identityHashCode(filter))); 10786 } 10787 10788 @Override 10789 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10790 return filter.service; 10791 } 10792 10793 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10794 PackageParser.Service service = (PackageParser.Service)label; 10795 out.print(prefix); out.print( 10796 Integer.toHexString(System.identityHashCode(service))); 10797 out.print(' '); 10798 service.printComponentShortName(out); 10799 if (count > 1) { 10800 out.print(" ("); out.print(count); out.print(" filters)"); 10801 } 10802 out.println(); 10803 } 10804 10805// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10806// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10807// final List<ResolveInfo> retList = Lists.newArrayList(); 10808// while (i.hasNext()) { 10809// final ResolveInfo resolveInfo = (ResolveInfo) i; 10810// if (isEnabledLP(resolveInfo.serviceInfo)) { 10811// retList.add(resolveInfo); 10812// } 10813// } 10814// return retList; 10815// } 10816 10817 // Keys are String (activity class name), values are Activity. 10818 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10819 = new ArrayMap<ComponentName, PackageParser.Service>(); 10820 private int mFlags; 10821 }; 10822 10823 private final class ProviderIntentResolver 10824 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10825 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10826 boolean defaultOnly, int userId) { 10827 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10828 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10829 } 10830 10831 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10832 int userId) { 10833 if (!sUserManager.exists(userId)) 10834 return null; 10835 mFlags = flags; 10836 return super.queryIntent(intent, resolvedType, 10837 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10838 } 10839 10840 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10841 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10842 if (!sUserManager.exists(userId)) 10843 return null; 10844 if (packageProviders == null) { 10845 return null; 10846 } 10847 mFlags = flags; 10848 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10849 final int N = packageProviders.size(); 10850 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10851 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10852 10853 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10854 for (int i = 0; i < N; ++i) { 10855 intentFilters = packageProviders.get(i).intents; 10856 if (intentFilters != null && intentFilters.size() > 0) { 10857 PackageParser.ProviderIntentInfo[] array = 10858 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10859 intentFilters.toArray(array); 10860 listCut.add(array); 10861 } 10862 } 10863 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10864 } 10865 10866 public final void addProvider(PackageParser.Provider p) { 10867 if (mProviders.containsKey(p.getComponentName())) { 10868 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10869 return; 10870 } 10871 10872 mProviders.put(p.getComponentName(), p); 10873 if (DEBUG_SHOW_INFO) { 10874 Log.v(TAG, " " 10875 + (p.info.nonLocalizedLabel != null 10876 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10877 Log.v(TAG, " Class=" + p.info.name); 10878 } 10879 final int NI = p.intents.size(); 10880 int j; 10881 for (j = 0; j < NI; j++) { 10882 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10883 if (DEBUG_SHOW_INFO) { 10884 Log.v(TAG, " IntentFilter:"); 10885 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10886 } 10887 if (!intent.debugCheck()) { 10888 Log.w(TAG, "==> For Provider " + p.info.name); 10889 } 10890 addFilter(intent); 10891 } 10892 } 10893 10894 public final void removeProvider(PackageParser.Provider p) { 10895 mProviders.remove(p.getComponentName()); 10896 if (DEBUG_SHOW_INFO) { 10897 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10898 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10899 Log.v(TAG, " Class=" + p.info.name); 10900 } 10901 final int NI = p.intents.size(); 10902 int j; 10903 for (j = 0; j < NI; j++) { 10904 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10905 if (DEBUG_SHOW_INFO) { 10906 Log.v(TAG, " IntentFilter:"); 10907 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10908 } 10909 removeFilter(intent); 10910 } 10911 } 10912 10913 @Override 10914 protected boolean allowFilterResult( 10915 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10916 ProviderInfo filterPi = filter.provider.info; 10917 for (int i = dest.size() - 1; i >= 0; i--) { 10918 ProviderInfo destPi = dest.get(i).providerInfo; 10919 if (destPi.name == filterPi.name 10920 && destPi.packageName == filterPi.packageName) { 10921 return false; 10922 } 10923 } 10924 return true; 10925 } 10926 10927 @Override 10928 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10929 return new PackageParser.ProviderIntentInfo[size]; 10930 } 10931 10932 @Override 10933 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10934 if (!sUserManager.exists(userId)) 10935 return true; 10936 PackageParser.Package p = filter.provider.owner; 10937 if (p != null) { 10938 PackageSetting ps = (PackageSetting) p.mExtras; 10939 if (ps != null) { 10940 // System apps are never considered stopped for purposes of 10941 // filtering, because there may be no way for the user to 10942 // actually re-launch them. 10943 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10944 && ps.getStopped(userId); 10945 } 10946 } 10947 return false; 10948 } 10949 10950 @Override 10951 protected boolean isPackageForFilter(String packageName, 10952 PackageParser.ProviderIntentInfo info) { 10953 return packageName.equals(info.provider.owner.packageName); 10954 } 10955 10956 @Override 10957 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10958 int match, int userId) { 10959 if (!sUserManager.exists(userId)) 10960 return null; 10961 final PackageParser.ProviderIntentInfo info = filter; 10962 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10963 return null; 10964 } 10965 final PackageParser.Provider provider = info.provider; 10966 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10967 if (ps == null) { 10968 return null; 10969 } 10970 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10971 ps.readUserState(userId), userId); 10972 if (pi == null) { 10973 return null; 10974 } 10975 final ResolveInfo res = new ResolveInfo(); 10976 res.providerInfo = pi; 10977 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10978 res.filter = filter; 10979 } 10980 res.priority = info.getPriority(); 10981 res.preferredOrder = provider.owner.mPreferredOrder; 10982 res.match = match; 10983 res.isDefault = info.hasDefault; 10984 res.labelRes = info.labelRes; 10985 res.nonLocalizedLabel = info.nonLocalizedLabel; 10986 res.icon = info.icon; 10987 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10988 return res; 10989 } 10990 10991 @Override 10992 protected void sortResults(List<ResolveInfo> results) { 10993 Collections.sort(results, mResolvePrioritySorter); 10994 } 10995 10996 @Override 10997 protected void dumpFilter(PrintWriter out, String prefix, 10998 PackageParser.ProviderIntentInfo filter) { 10999 out.print(prefix); 11000 out.print( 11001 Integer.toHexString(System.identityHashCode(filter.provider))); 11002 out.print(' '); 11003 filter.provider.printComponentShortName(out); 11004 out.print(" filter "); 11005 out.println(Integer.toHexString(System.identityHashCode(filter))); 11006 } 11007 11008 @Override 11009 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11010 return filter.provider; 11011 } 11012 11013 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11014 PackageParser.Provider provider = (PackageParser.Provider)label; 11015 out.print(prefix); out.print( 11016 Integer.toHexString(System.identityHashCode(provider))); 11017 out.print(' '); 11018 provider.printComponentShortName(out); 11019 if (count > 1) { 11020 out.print(" ("); out.print(count); out.print(" filters)"); 11021 } 11022 out.println(); 11023 } 11024 11025 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11026 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11027 private int mFlags; 11028 } 11029 11030 private static final class EphemeralIntentResolver 11031 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11032 @Override 11033 protected EphemeralResolveIntentInfo[] newArray(int size) { 11034 return new EphemeralResolveIntentInfo[size]; 11035 } 11036 11037 @Override 11038 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11039 return true; 11040 } 11041 11042 @Override 11043 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11044 int userId) { 11045 if (!sUserManager.exists(userId)) { 11046 return null; 11047 } 11048 return info.getEphemeralResolveInfo(); 11049 } 11050 } 11051 11052 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11053 new Comparator<ResolveInfo>() { 11054 public int compare(ResolveInfo r1, ResolveInfo r2) { 11055 int v1 = r1.priority; 11056 int v2 = r2.priority; 11057 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11058 if (v1 != v2) { 11059 return (v1 > v2) ? -1 : 1; 11060 } 11061 v1 = r1.preferredOrder; 11062 v2 = r2.preferredOrder; 11063 if (v1 != v2) { 11064 return (v1 > v2) ? -1 : 1; 11065 } 11066 if (r1.isDefault != r2.isDefault) { 11067 return r1.isDefault ? -1 : 1; 11068 } 11069 v1 = r1.match; 11070 v2 = r2.match; 11071 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11072 if (v1 != v2) { 11073 return (v1 > v2) ? -1 : 1; 11074 } 11075 if (r1.system != r2.system) { 11076 return r1.system ? -1 : 1; 11077 } 11078 if (r1.activityInfo != null) { 11079 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11080 } 11081 if (r1.serviceInfo != null) { 11082 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11083 } 11084 if (r1.providerInfo != null) { 11085 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11086 } 11087 return 0; 11088 } 11089 }; 11090 11091 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11092 new Comparator<ProviderInfo>() { 11093 public int compare(ProviderInfo p1, ProviderInfo p2) { 11094 final int v1 = p1.initOrder; 11095 final int v2 = p2.initOrder; 11096 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11097 } 11098 }; 11099 11100 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11101 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11102 final int[] userIds) { 11103 mHandler.post(new Runnable() { 11104 @Override 11105 public void run() { 11106 try { 11107 final IActivityManager am = ActivityManagerNative.getDefault(); 11108 if (am == null) return; 11109 final int[] resolvedUserIds; 11110 if (userIds == null) { 11111 resolvedUserIds = am.getRunningUserIds(); 11112 } else { 11113 resolvedUserIds = userIds; 11114 } 11115 for (int id : resolvedUserIds) { 11116 final Intent intent = new Intent(action, 11117 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11118 if (extras != null) { 11119 intent.putExtras(extras); 11120 } 11121 if (targetPkg != null) { 11122 intent.setPackage(targetPkg); 11123 } 11124 // Modify the UID when posting to other users 11125 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11126 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11127 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11128 intent.putExtra(Intent.EXTRA_UID, uid); 11129 } 11130 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11131 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11132 if (DEBUG_BROADCASTS) { 11133 RuntimeException here = new RuntimeException("here"); 11134 here.fillInStackTrace(); 11135 Slog.d(TAG, "Sending to user " + id + ": " 11136 + intent.toShortString(false, true, false, false) 11137 + " " + intent.getExtras(), here); 11138 } 11139 am.broadcastIntent(null, intent, null, finishedReceiver, 11140 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11141 null, finishedReceiver != null, false, id); 11142 } 11143 } catch (RemoteException ex) { 11144 } 11145 } 11146 }); 11147 } 11148 11149 /** 11150 * Check if the external storage media is available. This is true if there 11151 * is a mounted external storage medium or if the external storage is 11152 * emulated. 11153 */ 11154 private boolean isExternalMediaAvailable() { 11155 return mMediaMounted || Environment.isExternalStorageEmulated(); 11156 } 11157 11158 @Override 11159 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11160 // writer 11161 synchronized (mPackages) { 11162 if (!isExternalMediaAvailable()) { 11163 // If the external storage is no longer mounted at this point, 11164 // the caller may not have been able to delete all of this 11165 // packages files and can not delete any more. Bail. 11166 return null; 11167 } 11168 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11169 if (lastPackage != null) { 11170 pkgs.remove(lastPackage); 11171 } 11172 if (pkgs.size() > 0) { 11173 return pkgs.get(0); 11174 } 11175 } 11176 return null; 11177 } 11178 11179 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11180 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11181 userId, andCode ? 1 : 0, packageName); 11182 if (mSystemReady) { 11183 msg.sendToTarget(); 11184 } else { 11185 if (mPostSystemReadyMessages == null) { 11186 mPostSystemReadyMessages = new ArrayList<>(); 11187 } 11188 mPostSystemReadyMessages.add(msg); 11189 } 11190 } 11191 11192 void startCleaningPackages() { 11193 // reader 11194 if (!isExternalMediaAvailable()) { 11195 return; 11196 } 11197 synchronized (mPackages) { 11198 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11199 return; 11200 } 11201 } 11202 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11203 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11204 IActivityManager am = ActivityManagerNative.getDefault(); 11205 if (am != null) { 11206 try { 11207 am.startService(null, intent, null, mContext.getOpPackageName(), 11208 UserHandle.USER_SYSTEM); 11209 } catch (RemoteException e) { 11210 } 11211 } 11212 } 11213 11214 @Override 11215 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11216 int installFlags, String installerPackageName, int userId) { 11217 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11218 11219 final int callingUid = Binder.getCallingUid(); 11220 enforceCrossUserPermission(callingUid, userId, 11221 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11222 11223 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11224 try { 11225 if (observer != null) { 11226 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11227 } 11228 } catch (RemoteException re) { 11229 } 11230 return; 11231 } 11232 11233 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11234 installFlags |= PackageManager.INSTALL_FROM_ADB; 11235 11236 } else { 11237 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11238 // about installerPackageName. 11239 11240 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11241 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11242 } 11243 11244 UserHandle user; 11245 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11246 user = UserHandle.ALL; 11247 } else { 11248 user = new UserHandle(userId); 11249 } 11250 11251 // Only system components can circumvent runtime permissions when installing. 11252 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11253 && mContext.checkCallingOrSelfPermission(Manifest.permission 11254 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11255 throw new SecurityException("You need the " 11256 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11257 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11258 } 11259 11260 final File originFile = new File(originPath); 11261 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11262 11263 final Message msg = mHandler.obtainMessage(INIT_COPY); 11264 final VerificationInfo verificationInfo = new VerificationInfo( 11265 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11266 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11267 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11268 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11269 null /*certificates*/); 11270 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11271 msg.obj = params; 11272 11273 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11274 System.identityHashCode(msg.obj)); 11275 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11276 System.identityHashCode(msg.obj)); 11277 11278 mHandler.sendMessage(msg); 11279 } 11280 11281 void installStage(String packageName, File stagedDir, String stagedCid, 11282 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11283 String installerPackageName, int installerUid, UserHandle user, 11284 Certificate[][] certificates) { 11285 if (DEBUG_EPHEMERAL) { 11286 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11287 Slog.d(TAG, "Ephemeral install of " + packageName); 11288 } 11289 } 11290 final VerificationInfo verificationInfo = new VerificationInfo( 11291 sessionParams.originatingUri, sessionParams.referrerUri, 11292 sessionParams.originatingUid, installerUid); 11293 11294 final OriginInfo origin; 11295 if (stagedDir != null) { 11296 origin = OriginInfo.fromStagedFile(stagedDir); 11297 } else { 11298 origin = OriginInfo.fromStagedContainer(stagedCid); 11299 } 11300 11301 final Message msg = mHandler.obtainMessage(INIT_COPY); 11302 final InstallParams params = new InstallParams(origin, null, observer, 11303 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11304 verificationInfo, user, sessionParams.abiOverride, 11305 sessionParams.grantedRuntimePermissions, certificates); 11306 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11307 msg.obj = params; 11308 11309 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11310 System.identityHashCode(msg.obj)); 11311 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11312 System.identityHashCode(msg.obj)); 11313 11314 mHandler.sendMessage(msg); 11315 } 11316 11317 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11318 int userId) { 11319 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11320 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11321 } 11322 11323 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11324 int appId, int userId) { 11325 Bundle extras = new Bundle(1); 11326 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11327 11328 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11329 packageName, extras, 0, null, null, new int[] {userId}); 11330 try { 11331 IActivityManager am = ActivityManagerNative.getDefault(); 11332 if (isSystem && am.isUserRunning(userId, 0)) { 11333 // The just-installed/enabled app is bundled on the system, so presumed 11334 // to be able to run automatically without needing an explicit launch. 11335 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11336 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11337 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11338 .setPackage(packageName); 11339 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11340 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11341 } 11342 } catch (RemoteException e) { 11343 // shouldn't happen 11344 Slog.w(TAG, "Unable to bootstrap installed package", e); 11345 } 11346 } 11347 11348 @Override 11349 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11350 int userId) { 11351 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11352 PackageSetting pkgSetting; 11353 final int uid = Binder.getCallingUid(); 11354 enforceCrossUserPermission(uid, userId, 11355 true /* requireFullPermission */, true /* checkShell */, 11356 "setApplicationHiddenSetting for user " + userId); 11357 11358 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11359 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11360 return false; 11361 } 11362 11363 long callingId = Binder.clearCallingIdentity(); 11364 try { 11365 boolean sendAdded = false; 11366 boolean sendRemoved = false; 11367 // writer 11368 synchronized (mPackages) { 11369 pkgSetting = mSettings.mPackages.get(packageName); 11370 if (pkgSetting == null) { 11371 return false; 11372 } 11373 if (pkgSetting.getHidden(userId) != hidden) { 11374 pkgSetting.setHidden(hidden, userId); 11375 mSettings.writePackageRestrictionsLPr(userId); 11376 if (hidden) { 11377 sendRemoved = true; 11378 } else { 11379 sendAdded = true; 11380 } 11381 } 11382 } 11383 if (sendAdded) { 11384 sendPackageAddedForUser(packageName, pkgSetting, userId); 11385 return true; 11386 } 11387 if (sendRemoved) { 11388 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11389 "hiding pkg"); 11390 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11391 return true; 11392 } 11393 } finally { 11394 Binder.restoreCallingIdentity(callingId); 11395 } 11396 return false; 11397 } 11398 11399 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11400 int userId) { 11401 final PackageRemovedInfo info = new PackageRemovedInfo(); 11402 info.removedPackage = packageName; 11403 info.removedUsers = new int[] {userId}; 11404 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11405 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11406 } 11407 11408 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11409 if (pkgList.length > 0) { 11410 Bundle extras = new Bundle(1); 11411 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11412 11413 sendPackageBroadcast( 11414 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11415 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11416 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11417 new int[] {userId}); 11418 } 11419 } 11420 11421 /** 11422 * Returns true if application is not found or there was an error. Otherwise it returns 11423 * the hidden state of the package for the given user. 11424 */ 11425 @Override 11426 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11427 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11428 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11429 true /* requireFullPermission */, false /* checkShell */, 11430 "getApplicationHidden for user " + userId); 11431 PackageSetting pkgSetting; 11432 long callingId = Binder.clearCallingIdentity(); 11433 try { 11434 // writer 11435 synchronized (mPackages) { 11436 pkgSetting = mSettings.mPackages.get(packageName); 11437 if (pkgSetting == null) { 11438 return true; 11439 } 11440 return pkgSetting.getHidden(userId); 11441 } 11442 } finally { 11443 Binder.restoreCallingIdentity(callingId); 11444 } 11445 } 11446 11447 /** 11448 * @hide 11449 */ 11450 @Override 11451 public int installExistingPackageAsUser(String packageName, int userId) { 11452 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11453 null); 11454 PackageSetting pkgSetting; 11455 final int uid = Binder.getCallingUid(); 11456 enforceCrossUserPermission(uid, userId, 11457 true /* requireFullPermission */, true /* checkShell */, 11458 "installExistingPackage for user " + userId); 11459 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11460 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11461 } 11462 11463 long callingId = Binder.clearCallingIdentity(); 11464 try { 11465 boolean installed = false; 11466 11467 // writer 11468 synchronized (mPackages) { 11469 pkgSetting = mSettings.mPackages.get(packageName); 11470 if (pkgSetting == null) { 11471 return PackageManager.INSTALL_FAILED_INVALID_URI; 11472 } 11473 if (!pkgSetting.getInstalled(userId)) { 11474 pkgSetting.setInstalled(true, userId); 11475 pkgSetting.setHidden(false, userId); 11476 mSettings.writePackageRestrictionsLPr(userId); 11477 installed = true; 11478 } 11479 } 11480 11481 if (installed) { 11482 if (pkgSetting.pkg != null) { 11483 synchronized (mInstallLock) { 11484 // We don't need to freeze for a brand new install 11485 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11486 } 11487 } 11488 sendPackageAddedForUser(packageName, pkgSetting, userId); 11489 } 11490 } finally { 11491 Binder.restoreCallingIdentity(callingId); 11492 } 11493 11494 return PackageManager.INSTALL_SUCCEEDED; 11495 } 11496 11497 boolean isUserRestricted(int userId, String restrictionKey) { 11498 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11499 if (restrictions.getBoolean(restrictionKey, false)) { 11500 Log.w(TAG, "User is restricted: " + restrictionKey); 11501 return true; 11502 } 11503 return false; 11504 } 11505 11506 @Override 11507 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11508 int userId) { 11509 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11510 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11511 true /* requireFullPermission */, true /* checkShell */, 11512 "setPackagesSuspended for user " + userId); 11513 11514 if (ArrayUtils.isEmpty(packageNames)) { 11515 return packageNames; 11516 } 11517 11518 // List of package names for whom the suspended state has changed. 11519 List<String> changedPackages = new ArrayList<>(packageNames.length); 11520 // List of package names for whom the suspended state is not set as requested in this 11521 // method. 11522 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11523 long callingId = Binder.clearCallingIdentity(); 11524 try { 11525 for (int i = 0; i < packageNames.length; i++) { 11526 String packageName = packageNames[i]; 11527 boolean changed = false; 11528 final int appId; 11529 synchronized (mPackages) { 11530 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11531 if (pkgSetting == null) { 11532 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11533 + "\". Skipping suspending/un-suspending."); 11534 unactionedPackages.add(packageName); 11535 continue; 11536 } 11537 appId = pkgSetting.appId; 11538 if (pkgSetting.getSuspended(userId) != suspended) { 11539 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11540 unactionedPackages.add(packageName); 11541 continue; 11542 } 11543 pkgSetting.setSuspended(suspended, userId); 11544 mSettings.writePackageRestrictionsLPr(userId); 11545 changed = true; 11546 changedPackages.add(packageName); 11547 } 11548 } 11549 11550 if (changed && suspended) { 11551 killApplication(packageName, UserHandle.getUid(userId, appId), 11552 "suspending package"); 11553 } 11554 } 11555 } finally { 11556 Binder.restoreCallingIdentity(callingId); 11557 } 11558 11559 if (!changedPackages.isEmpty()) { 11560 sendPackagesSuspendedForUser(changedPackages.toArray( 11561 new String[changedPackages.size()]), userId, suspended); 11562 } 11563 11564 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11565 } 11566 11567 @Override 11568 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11569 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11570 true /* requireFullPermission */, false /* checkShell */, 11571 "isPackageSuspendedForUser for user " + userId); 11572 synchronized (mPackages) { 11573 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11574 if (pkgSetting == null) { 11575 throw new IllegalArgumentException("Unknown target package: " + packageName); 11576 } 11577 return pkgSetting.getSuspended(userId); 11578 } 11579 } 11580 11581 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11582 if (isPackageDeviceAdmin(packageName, userId)) { 11583 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11584 + "\": has an active device admin"); 11585 return false; 11586 } 11587 11588 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11589 if (packageName.equals(activeLauncherPackageName)) { 11590 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11591 + "\": contains the active launcher"); 11592 return false; 11593 } 11594 11595 if (packageName.equals(mRequiredInstallerPackage)) { 11596 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11597 + "\": required for package installation"); 11598 return false; 11599 } 11600 11601 if (packageName.equals(mRequiredVerifierPackage)) { 11602 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11603 + "\": required for package verification"); 11604 return false; 11605 } 11606 11607 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11608 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11609 + "\": is the default dialer"); 11610 return false; 11611 } 11612 11613 return true; 11614 } 11615 11616 private String getActiveLauncherPackageName(int userId) { 11617 Intent intent = new Intent(Intent.ACTION_MAIN); 11618 intent.addCategory(Intent.CATEGORY_HOME); 11619 ResolveInfo resolveInfo = resolveIntent( 11620 intent, 11621 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11622 PackageManager.MATCH_DEFAULT_ONLY, 11623 userId); 11624 11625 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11626 } 11627 11628 private String getDefaultDialerPackageName(int userId) { 11629 synchronized (mPackages) { 11630 return mSettings.getDefaultDialerPackageNameLPw(userId); 11631 } 11632 } 11633 11634 @Override 11635 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11636 mContext.enforceCallingOrSelfPermission( 11637 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11638 "Only package verification agents can verify applications"); 11639 11640 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11641 final PackageVerificationResponse response = new PackageVerificationResponse( 11642 verificationCode, Binder.getCallingUid()); 11643 msg.arg1 = id; 11644 msg.obj = response; 11645 mHandler.sendMessage(msg); 11646 } 11647 11648 @Override 11649 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11650 long millisecondsToDelay) { 11651 mContext.enforceCallingOrSelfPermission( 11652 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11653 "Only package verification agents can extend verification timeouts"); 11654 11655 final PackageVerificationState state = mPendingVerification.get(id); 11656 final PackageVerificationResponse response = new PackageVerificationResponse( 11657 verificationCodeAtTimeout, Binder.getCallingUid()); 11658 11659 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11660 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11661 } 11662 if (millisecondsToDelay < 0) { 11663 millisecondsToDelay = 0; 11664 } 11665 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11666 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11667 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11668 } 11669 11670 if ((state != null) && !state.timeoutExtended()) { 11671 state.extendTimeout(); 11672 11673 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11674 msg.arg1 = id; 11675 msg.obj = response; 11676 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11677 } 11678 } 11679 11680 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11681 int verificationCode, UserHandle user) { 11682 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11683 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11684 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11685 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11686 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11687 11688 mContext.sendBroadcastAsUser(intent, user, 11689 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11690 } 11691 11692 private ComponentName matchComponentForVerifier(String packageName, 11693 List<ResolveInfo> receivers) { 11694 ActivityInfo targetReceiver = null; 11695 11696 final int NR = receivers.size(); 11697 for (int i = 0; i < NR; i++) { 11698 final ResolveInfo info = receivers.get(i); 11699 if (info.activityInfo == null) { 11700 continue; 11701 } 11702 11703 if (packageName.equals(info.activityInfo.packageName)) { 11704 targetReceiver = info.activityInfo; 11705 break; 11706 } 11707 } 11708 11709 if (targetReceiver == null) { 11710 return null; 11711 } 11712 11713 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11714 } 11715 11716 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11717 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11718 if (pkgInfo.verifiers.length == 0) { 11719 return null; 11720 } 11721 11722 final int N = pkgInfo.verifiers.length; 11723 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11724 for (int i = 0; i < N; i++) { 11725 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11726 11727 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11728 receivers); 11729 if (comp == null) { 11730 continue; 11731 } 11732 11733 final int verifierUid = getUidForVerifier(verifierInfo); 11734 if (verifierUid == -1) { 11735 continue; 11736 } 11737 11738 if (DEBUG_VERIFY) { 11739 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11740 + " with the correct signature"); 11741 } 11742 sufficientVerifiers.add(comp); 11743 verificationState.addSufficientVerifier(verifierUid); 11744 } 11745 11746 return sufficientVerifiers; 11747 } 11748 11749 private int getUidForVerifier(VerifierInfo verifierInfo) { 11750 synchronized (mPackages) { 11751 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11752 if (pkg == null) { 11753 return -1; 11754 } else if (pkg.mSignatures.length != 1) { 11755 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11756 + " has more than one signature; ignoring"); 11757 return -1; 11758 } 11759 11760 /* 11761 * If the public key of the package's signature does not match 11762 * our expected public key, then this is a different package and 11763 * we should skip. 11764 */ 11765 11766 final byte[] expectedPublicKey; 11767 try { 11768 final Signature verifierSig = pkg.mSignatures[0]; 11769 final PublicKey publicKey = verifierSig.getPublicKey(); 11770 expectedPublicKey = publicKey.getEncoded(); 11771 } catch (CertificateException e) { 11772 return -1; 11773 } 11774 11775 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11776 11777 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11778 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11779 + " does not have the expected public key; ignoring"); 11780 return -1; 11781 } 11782 11783 return pkg.applicationInfo.uid; 11784 } 11785 } 11786 11787 @Override 11788 public void finishPackageInstall(int token, boolean didLaunch) { 11789 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11790 11791 if (DEBUG_INSTALL) { 11792 Slog.v(TAG, "BM finishing package install for " + token); 11793 } 11794 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11795 11796 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11797 mHandler.sendMessage(msg); 11798 } 11799 11800 /** 11801 * Get the verification agent timeout. 11802 * 11803 * @return verification timeout in milliseconds 11804 */ 11805 private long getVerificationTimeout() { 11806 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11807 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11808 DEFAULT_VERIFICATION_TIMEOUT); 11809 } 11810 11811 /** 11812 * Get the default verification agent response code. 11813 * 11814 * @return default verification response code 11815 */ 11816 private int getDefaultVerificationResponse() { 11817 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11818 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11819 DEFAULT_VERIFICATION_RESPONSE); 11820 } 11821 11822 /** 11823 * Check whether or not package verification has been enabled. 11824 * 11825 * @return true if verification should be performed 11826 */ 11827 private boolean isVerificationEnabled(int userId, int installFlags) { 11828 if (!DEFAULT_VERIFY_ENABLE) { 11829 return false; 11830 } 11831 // Ephemeral apps don't get the full verification treatment 11832 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11833 if (DEBUG_EPHEMERAL) { 11834 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11835 } 11836 return false; 11837 } 11838 11839 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11840 11841 // Check if installing from ADB 11842 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11843 // Do not run verification in a test harness environment 11844 if (ActivityManager.isRunningInTestHarness()) { 11845 return false; 11846 } 11847 if (ensureVerifyAppsEnabled) { 11848 return true; 11849 } 11850 // Check if the developer does not want package verification for ADB installs 11851 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11852 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11853 return false; 11854 } 11855 } 11856 11857 if (ensureVerifyAppsEnabled) { 11858 return true; 11859 } 11860 11861 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11862 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11863 } 11864 11865 @Override 11866 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11867 throws RemoteException { 11868 mContext.enforceCallingOrSelfPermission( 11869 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11870 "Only intentfilter verification agents can verify applications"); 11871 11872 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11873 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11874 Binder.getCallingUid(), verificationCode, failedDomains); 11875 msg.arg1 = id; 11876 msg.obj = response; 11877 mHandler.sendMessage(msg); 11878 } 11879 11880 @Override 11881 public int getIntentVerificationStatus(String packageName, int userId) { 11882 synchronized (mPackages) { 11883 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11884 } 11885 } 11886 11887 @Override 11888 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11889 mContext.enforceCallingOrSelfPermission( 11890 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11891 11892 boolean result = false; 11893 synchronized (mPackages) { 11894 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11895 } 11896 if (result) { 11897 scheduleWritePackageRestrictionsLocked(userId); 11898 } 11899 return result; 11900 } 11901 11902 @Override 11903 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11904 String packageName) { 11905 synchronized (mPackages) { 11906 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11907 } 11908 } 11909 11910 @Override 11911 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11912 if (TextUtils.isEmpty(packageName)) { 11913 return ParceledListSlice.emptyList(); 11914 } 11915 synchronized (mPackages) { 11916 PackageParser.Package pkg = mPackages.get(packageName); 11917 if (pkg == null || pkg.activities == null) { 11918 return ParceledListSlice.emptyList(); 11919 } 11920 final int count = pkg.activities.size(); 11921 ArrayList<IntentFilter> result = new ArrayList<>(); 11922 for (int n=0; n<count; n++) { 11923 PackageParser.Activity activity = pkg.activities.get(n); 11924 if (activity.intents != null && activity.intents.size() > 0) { 11925 result.addAll(activity.intents); 11926 } 11927 } 11928 return new ParceledListSlice<>(result); 11929 } 11930 } 11931 11932 @Override 11933 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11934 mContext.enforceCallingOrSelfPermission( 11935 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11936 11937 synchronized (mPackages) { 11938 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11939 if (packageName != null) { 11940 result |= updateIntentVerificationStatus(packageName, 11941 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11942 userId); 11943 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11944 packageName, userId); 11945 } 11946 return result; 11947 } 11948 } 11949 11950 @Override 11951 public String getDefaultBrowserPackageName(int userId) { 11952 synchronized (mPackages) { 11953 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11954 } 11955 } 11956 11957 /** 11958 * Get the "allow unknown sources" setting. 11959 * 11960 * @return the current "allow unknown sources" setting 11961 */ 11962 private int getUnknownSourcesSettings() { 11963 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11964 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11965 -1); 11966 } 11967 11968 @Override 11969 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11970 final int uid = Binder.getCallingUid(); 11971 // writer 11972 synchronized (mPackages) { 11973 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11974 if (targetPackageSetting == null) { 11975 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11976 } 11977 11978 PackageSetting installerPackageSetting; 11979 if (installerPackageName != null) { 11980 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11981 if (installerPackageSetting == null) { 11982 throw new IllegalArgumentException("Unknown installer package: " 11983 + installerPackageName); 11984 } 11985 } else { 11986 installerPackageSetting = null; 11987 } 11988 11989 Signature[] callerSignature; 11990 Object obj = mSettings.getUserIdLPr(uid); 11991 if (obj != null) { 11992 if (obj instanceof SharedUserSetting) { 11993 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11994 } else if (obj instanceof PackageSetting) { 11995 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11996 } else { 11997 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11998 } 11999 } else { 12000 throw new SecurityException("Unknown calling UID: " + uid); 12001 } 12002 12003 // Verify: can't set installerPackageName to a package that is 12004 // not signed with the same cert as the caller. 12005 if (installerPackageSetting != null) { 12006 if (compareSignatures(callerSignature, 12007 installerPackageSetting.signatures.mSignatures) 12008 != PackageManager.SIGNATURE_MATCH) { 12009 throw new SecurityException( 12010 "Caller does not have same cert as new installer package " 12011 + installerPackageName); 12012 } 12013 } 12014 12015 // Verify: if target already has an installer package, it must 12016 // be signed with the same cert as the caller. 12017 if (targetPackageSetting.installerPackageName != null) { 12018 PackageSetting setting = mSettings.mPackages.get( 12019 targetPackageSetting.installerPackageName); 12020 // If the currently set package isn't valid, then it's always 12021 // okay to change it. 12022 if (setting != null) { 12023 if (compareSignatures(callerSignature, 12024 setting.signatures.mSignatures) 12025 != PackageManager.SIGNATURE_MATCH) { 12026 throw new SecurityException( 12027 "Caller does not have same cert as old installer package " 12028 + targetPackageSetting.installerPackageName); 12029 } 12030 } 12031 } 12032 12033 // Okay! 12034 targetPackageSetting.installerPackageName = installerPackageName; 12035 if (installerPackageName != null) { 12036 mSettings.mInstallerPackages.add(installerPackageName); 12037 } 12038 scheduleWriteSettingsLocked(); 12039 } 12040 } 12041 12042 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12043 // Queue up an async operation since the package installation may take a little while. 12044 mHandler.post(new Runnable() { 12045 public void run() { 12046 mHandler.removeCallbacks(this); 12047 // Result object to be returned 12048 PackageInstalledInfo res = new PackageInstalledInfo(); 12049 res.setReturnCode(currentStatus); 12050 res.uid = -1; 12051 res.pkg = null; 12052 res.removedInfo = null; 12053 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12054 args.doPreInstall(res.returnCode); 12055 synchronized (mInstallLock) { 12056 installPackageTracedLI(args, res); 12057 } 12058 args.doPostInstall(res.returnCode, res.uid); 12059 } 12060 12061 // A restore should be performed at this point if (a) the install 12062 // succeeded, (b) the operation is not an update, and (c) the new 12063 // package has not opted out of backup participation. 12064 final boolean update = res.removedInfo != null 12065 && res.removedInfo.removedPackage != null; 12066 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12067 boolean doRestore = !update 12068 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12069 12070 // Set up the post-install work request bookkeeping. This will be used 12071 // and cleaned up by the post-install event handling regardless of whether 12072 // there's a restore pass performed. Token values are >= 1. 12073 int token; 12074 if (mNextInstallToken < 0) mNextInstallToken = 1; 12075 token = mNextInstallToken++; 12076 12077 PostInstallData data = new PostInstallData(args, res); 12078 mRunningInstalls.put(token, data); 12079 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12080 12081 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12082 // Pass responsibility to the Backup Manager. It will perform a 12083 // restore if appropriate, then pass responsibility back to the 12084 // Package Manager to run the post-install observer callbacks 12085 // and broadcasts. 12086 IBackupManager bm = IBackupManager.Stub.asInterface( 12087 ServiceManager.getService(Context.BACKUP_SERVICE)); 12088 if (bm != null) { 12089 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12090 + " to BM for possible restore"); 12091 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12092 try { 12093 // TODO: http://b/22388012 12094 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12095 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12096 } else { 12097 doRestore = false; 12098 } 12099 } catch (RemoteException e) { 12100 // can't happen; the backup manager is local 12101 } catch (Exception e) { 12102 Slog.e(TAG, "Exception trying to enqueue restore", e); 12103 doRestore = false; 12104 } 12105 } else { 12106 Slog.e(TAG, "Backup Manager not found!"); 12107 doRestore = false; 12108 } 12109 } 12110 12111 if (!doRestore) { 12112 // No restore possible, or the Backup Manager was mysteriously not 12113 // available -- just fire the post-install work request directly. 12114 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12115 12116 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12117 12118 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12119 mHandler.sendMessage(msg); 12120 } 12121 } 12122 }); 12123 } 12124 12125 /** 12126 * Callback from PackageSettings whenever an app is first transitioned out of the 12127 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12128 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12129 * here whether the app is the target of an ongoing install, and only send the 12130 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12131 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12132 * handling. 12133 */ 12134 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12135 // Serialize this with the rest of the install-process message chain. In the 12136 // restore-at-install case, this Runnable will necessarily run before the 12137 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12138 // are coherent. In the non-restore case, the app has already completed install 12139 // and been launched through some other means, so it is not in a problematic 12140 // state for observers to see the FIRST_LAUNCH signal. 12141 mHandler.post(new Runnable() { 12142 @Override 12143 public void run() { 12144 for (int i = 0; i < mRunningInstalls.size(); i++) { 12145 final PostInstallData data = mRunningInstalls.valueAt(i); 12146 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12147 // right package; but is it for the right user? 12148 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12149 if (userId == data.res.newUsers[uIndex]) { 12150 if (DEBUG_BACKUP) { 12151 Slog.i(TAG, "Package " + pkgName 12152 + " being restored so deferring FIRST_LAUNCH"); 12153 } 12154 return; 12155 } 12156 } 12157 } 12158 } 12159 // didn't find it, so not being restored 12160 if (DEBUG_BACKUP) { 12161 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12162 } 12163 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12164 } 12165 }); 12166 } 12167 12168 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12169 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12170 installerPkg, null, userIds); 12171 } 12172 12173 private abstract class HandlerParams { 12174 private static final int MAX_RETRIES = 4; 12175 12176 /** 12177 * Number of times startCopy() has been attempted and had a non-fatal 12178 * error. 12179 */ 12180 private int mRetries = 0; 12181 12182 /** User handle for the user requesting the information or installation. */ 12183 private final UserHandle mUser; 12184 String traceMethod; 12185 int traceCookie; 12186 12187 HandlerParams(UserHandle user) { 12188 mUser = user; 12189 } 12190 12191 UserHandle getUser() { 12192 return mUser; 12193 } 12194 12195 HandlerParams setTraceMethod(String traceMethod) { 12196 this.traceMethod = traceMethod; 12197 return this; 12198 } 12199 12200 HandlerParams setTraceCookie(int traceCookie) { 12201 this.traceCookie = traceCookie; 12202 return this; 12203 } 12204 12205 final boolean startCopy() { 12206 boolean res; 12207 try { 12208 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12209 12210 if (++mRetries > MAX_RETRIES) { 12211 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12212 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12213 handleServiceError(); 12214 return false; 12215 } else { 12216 handleStartCopy(); 12217 res = true; 12218 } 12219 } catch (RemoteException e) { 12220 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12221 mHandler.sendEmptyMessage(MCS_RECONNECT); 12222 res = false; 12223 } 12224 handleReturnCode(); 12225 return res; 12226 } 12227 12228 final void serviceError() { 12229 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12230 handleServiceError(); 12231 handleReturnCode(); 12232 } 12233 12234 abstract void handleStartCopy() throws RemoteException; 12235 abstract void handleServiceError(); 12236 abstract void handleReturnCode(); 12237 } 12238 12239 class MeasureParams extends HandlerParams { 12240 private final PackageStats mStats; 12241 private boolean mSuccess; 12242 12243 private final IPackageStatsObserver mObserver; 12244 12245 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12246 super(new UserHandle(stats.userHandle)); 12247 mObserver = observer; 12248 mStats = stats; 12249 } 12250 12251 @Override 12252 public String toString() { 12253 return "MeasureParams{" 12254 + Integer.toHexString(System.identityHashCode(this)) 12255 + " " + mStats.packageName + "}"; 12256 } 12257 12258 @Override 12259 void handleStartCopy() throws RemoteException { 12260 synchronized (mInstallLock) { 12261 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12262 } 12263 12264 if (mSuccess) { 12265 final boolean mounted; 12266 if (Environment.isExternalStorageEmulated()) { 12267 mounted = true; 12268 } else { 12269 final String status = Environment.getExternalStorageState(); 12270 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12271 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12272 } 12273 12274 if (mounted) { 12275 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12276 12277 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12278 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12279 12280 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12281 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12282 12283 // Always subtract cache size, since it's a subdirectory 12284 mStats.externalDataSize -= mStats.externalCacheSize; 12285 12286 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12287 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12288 12289 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12290 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12291 } 12292 } 12293 } 12294 12295 @Override 12296 void handleReturnCode() { 12297 if (mObserver != null) { 12298 try { 12299 mObserver.onGetStatsCompleted(mStats, mSuccess); 12300 } catch (RemoteException e) { 12301 Slog.i(TAG, "Observer no longer exists."); 12302 } 12303 } 12304 } 12305 12306 @Override 12307 void handleServiceError() { 12308 Slog.e(TAG, "Could not measure application " + mStats.packageName 12309 + " external storage"); 12310 } 12311 } 12312 12313 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12314 throws RemoteException { 12315 long result = 0; 12316 for (File path : paths) { 12317 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12318 } 12319 return result; 12320 } 12321 12322 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12323 for (File path : paths) { 12324 try { 12325 mcs.clearDirectory(path.getAbsolutePath()); 12326 } catch (RemoteException e) { 12327 } 12328 } 12329 } 12330 12331 static class OriginInfo { 12332 /** 12333 * Location where install is coming from, before it has been 12334 * copied/renamed into place. This could be a single monolithic APK 12335 * file, or a cluster directory. This location may be untrusted. 12336 */ 12337 final File file; 12338 final String cid; 12339 12340 /** 12341 * Flag indicating that {@link #file} or {@link #cid} has already been 12342 * staged, meaning downstream users don't need to defensively copy the 12343 * contents. 12344 */ 12345 final boolean staged; 12346 12347 /** 12348 * Flag indicating that {@link #file} or {@link #cid} is an already 12349 * installed app that is being moved. 12350 */ 12351 final boolean existing; 12352 12353 final String resolvedPath; 12354 final File resolvedFile; 12355 12356 static OriginInfo fromNothing() { 12357 return new OriginInfo(null, null, false, false); 12358 } 12359 12360 static OriginInfo fromUntrustedFile(File file) { 12361 return new OriginInfo(file, null, false, false); 12362 } 12363 12364 static OriginInfo fromExistingFile(File file) { 12365 return new OriginInfo(file, null, false, true); 12366 } 12367 12368 static OriginInfo fromStagedFile(File file) { 12369 return new OriginInfo(file, null, true, false); 12370 } 12371 12372 static OriginInfo fromStagedContainer(String cid) { 12373 return new OriginInfo(null, cid, true, false); 12374 } 12375 12376 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12377 this.file = file; 12378 this.cid = cid; 12379 this.staged = staged; 12380 this.existing = existing; 12381 12382 if (cid != null) { 12383 resolvedPath = PackageHelper.getSdDir(cid); 12384 resolvedFile = new File(resolvedPath); 12385 } else if (file != null) { 12386 resolvedPath = file.getAbsolutePath(); 12387 resolvedFile = file; 12388 } else { 12389 resolvedPath = null; 12390 resolvedFile = null; 12391 } 12392 } 12393 } 12394 12395 static class MoveInfo { 12396 final int moveId; 12397 final String fromUuid; 12398 final String toUuid; 12399 final String packageName; 12400 final String dataAppName; 12401 final int appId; 12402 final String seinfo; 12403 final int targetSdkVersion; 12404 12405 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12406 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12407 this.moveId = moveId; 12408 this.fromUuid = fromUuid; 12409 this.toUuid = toUuid; 12410 this.packageName = packageName; 12411 this.dataAppName = dataAppName; 12412 this.appId = appId; 12413 this.seinfo = seinfo; 12414 this.targetSdkVersion = targetSdkVersion; 12415 } 12416 } 12417 12418 static class VerificationInfo { 12419 /** A constant used to indicate that a uid value is not present. */ 12420 public static final int NO_UID = -1; 12421 12422 /** URI referencing where the package was downloaded from. */ 12423 final Uri originatingUri; 12424 12425 /** HTTP referrer URI associated with the originatingURI. */ 12426 final Uri referrer; 12427 12428 /** UID of the application that the install request originated from. */ 12429 final int originatingUid; 12430 12431 /** UID of application requesting the install */ 12432 final int installerUid; 12433 12434 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12435 this.originatingUri = originatingUri; 12436 this.referrer = referrer; 12437 this.originatingUid = originatingUid; 12438 this.installerUid = installerUid; 12439 } 12440 } 12441 12442 class InstallParams extends HandlerParams { 12443 final OriginInfo origin; 12444 final MoveInfo move; 12445 final IPackageInstallObserver2 observer; 12446 int installFlags; 12447 final String installerPackageName; 12448 final String volumeUuid; 12449 private InstallArgs mArgs; 12450 private int mRet; 12451 final String packageAbiOverride; 12452 final String[] grantedRuntimePermissions; 12453 final VerificationInfo verificationInfo; 12454 final Certificate[][] certificates; 12455 12456 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12457 int installFlags, String installerPackageName, String volumeUuid, 12458 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12459 String[] grantedPermissions, Certificate[][] certificates) { 12460 super(user); 12461 this.origin = origin; 12462 this.move = move; 12463 this.observer = observer; 12464 this.installFlags = installFlags; 12465 this.installerPackageName = installerPackageName; 12466 this.volumeUuid = volumeUuid; 12467 this.verificationInfo = verificationInfo; 12468 this.packageAbiOverride = packageAbiOverride; 12469 this.grantedRuntimePermissions = grantedPermissions; 12470 this.certificates = certificates; 12471 } 12472 12473 @Override 12474 public String toString() { 12475 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12476 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12477 } 12478 12479 private int installLocationPolicy(PackageInfoLite pkgLite) { 12480 String packageName = pkgLite.packageName; 12481 int installLocation = pkgLite.installLocation; 12482 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12483 // reader 12484 synchronized (mPackages) { 12485 // Currently installed package which the new package is attempting to replace or 12486 // null if no such package is installed. 12487 PackageParser.Package installedPkg = mPackages.get(packageName); 12488 // Package which currently owns the data which the new package will own if installed. 12489 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12490 // will be null whereas dataOwnerPkg will contain information about the package 12491 // which was uninstalled while keeping its data. 12492 PackageParser.Package dataOwnerPkg = installedPkg; 12493 if (dataOwnerPkg == null) { 12494 PackageSetting ps = mSettings.mPackages.get(packageName); 12495 if (ps != null) { 12496 dataOwnerPkg = ps.pkg; 12497 } 12498 } 12499 12500 if (dataOwnerPkg != null) { 12501 // If installed, the package will get access to data left on the device by its 12502 // predecessor. As a security measure, this is permited only if this is not a 12503 // version downgrade or if the predecessor package is marked as debuggable and 12504 // a downgrade is explicitly requested. 12505 // 12506 // On debuggable platform builds, downgrades are permitted even for 12507 // non-debuggable packages to make testing easier. Debuggable platform builds do 12508 // not offer security guarantees and thus it's OK to disable some security 12509 // mechanisms to make debugging/testing easier on those builds. However, even on 12510 // debuggable builds downgrades of packages are permitted only if requested via 12511 // installFlags. This is because we aim to keep the behavior of debuggable 12512 // platform builds as close as possible to the behavior of non-debuggable 12513 // platform builds. 12514 final boolean downgradeRequested = 12515 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12516 final boolean packageDebuggable = 12517 (dataOwnerPkg.applicationInfo.flags 12518 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12519 final boolean downgradePermitted = 12520 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12521 if (!downgradePermitted) { 12522 try { 12523 checkDowngrade(dataOwnerPkg, pkgLite); 12524 } catch (PackageManagerException e) { 12525 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12526 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12527 } 12528 } 12529 } 12530 12531 if (installedPkg != null) { 12532 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12533 // Check for updated system application. 12534 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12535 if (onSd) { 12536 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12537 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12538 } 12539 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12540 } else { 12541 if (onSd) { 12542 // Install flag overrides everything. 12543 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12544 } 12545 // If current upgrade specifies particular preference 12546 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12547 // Application explicitly specified internal. 12548 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12549 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12550 // App explictly prefers external. Let policy decide 12551 } else { 12552 // Prefer previous location 12553 if (isExternal(installedPkg)) { 12554 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12555 } 12556 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12557 } 12558 } 12559 } else { 12560 // Invalid install. Return error code 12561 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12562 } 12563 } 12564 } 12565 // All the special cases have been taken care of. 12566 // Return result based on recommended install location. 12567 if (onSd) { 12568 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12569 } 12570 return pkgLite.recommendedInstallLocation; 12571 } 12572 12573 /* 12574 * Invoke remote method to get package information and install 12575 * location values. Override install location based on default 12576 * policy if needed and then create install arguments based 12577 * on the install location. 12578 */ 12579 public void handleStartCopy() throws RemoteException { 12580 int ret = PackageManager.INSTALL_SUCCEEDED; 12581 12582 // If we're already staged, we've firmly committed to an install location 12583 if (origin.staged) { 12584 if (origin.file != null) { 12585 installFlags |= PackageManager.INSTALL_INTERNAL; 12586 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12587 } else if (origin.cid != null) { 12588 installFlags |= PackageManager.INSTALL_EXTERNAL; 12589 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12590 } else { 12591 throw new IllegalStateException("Invalid stage location"); 12592 } 12593 } 12594 12595 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12596 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12597 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12598 PackageInfoLite pkgLite = null; 12599 12600 if (onInt && onSd) { 12601 // Check if both bits are set. 12602 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12603 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12604 } else if (onSd && ephemeral) { 12605 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12606 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12607 } else { 12608 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12609 packageAbiOverride); 12610 12611 if (DEBUG_EPHEMERAL && ephemeral) { 12612 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12613 } 12614 12615 /* 12616 * If we have too little free space, try to free cache 12617 * before giving up. 12618 */ 12619 if (!origin.staged && pkgLite.recommendedInstallLocation 12620 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12621 // TODO: focus freeing disk space on the target device 12622 final StorageManager storage = StorageManager.from(mContext); 12623 final long lowThreshold = storage.getStorageLowBytes( 12624 Environment.getDataDirectory()); 12625 12626 final long sizeBytes = mContainerService.calculateInstalledSize( 12627 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12628 12629 try { 12630 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12631 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12632 installFlags, packageAbiOverride); 12633 } catch (InstallerException e) { 12634 Slog.w(TAG, "Failed to free cache", e); 12635 } 12636 12637 /* 12638 * The cache free must have deleted the file we 12639 * downloaded to install. 12640 * 12641 * TODO: fix the "freeCache" call to not delete 12642 * the file we care about. 12643 */ 12644 if (pkgLite.recommendedInstallLocation 12645 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12646 pkgLite.recommendedInstallLocation 12647 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12648 } 12649 } 12650 } 12651 12652 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12653 int loc = pkgLite.recommendedInstallLocation; 12654 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12655 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12656 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12657 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12658 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12659 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12660 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12661 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12662 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12663 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12664 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12665 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12666 } else { 12667 // Override with defaults if needed. 12668 loc = installLocationPolicy(pkgLite); 12669 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12670 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12671 } else if (!onSd && !onInt) { 12672 // Override install location with flags 12673 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12674 // Set the flag to install on external media. 12675 installFlags |= PackageManager.INSTALL_EXTERNAL; 12676 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12677 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12678 if (DEBUG_EPHEMERAL) { 12679 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12680 } 12681 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12682 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12683 |PackageManager.INSTALL_INTERNAL); 12684 } else { 12685 // Make sure the flag for installing on external 12686 // media is unset 12687 installFlags |= PackageManager.INSTALL_INTERNAL; 12688 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12689 } 12690 } 12691 } 12692 } 12693 12694 final InstallArgs args = createInstallArgs(this); 12695 mArgs = args; 12696 12697 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12698 // TODO: http://b/22976637 12699 // Apps installed for "all" users use the device owner to verify the app 12700 UserHandle verifierUser = getUser(); 12701 if (verifierUser == UserHandle.ALL) { 12702 verifierUser = UserHandle.SYSTEM; 12703 } 12704 12705 /* 12706 * Determine if we have any installed package verifiers. If we 12707 * do, then we'll defer to them to verify the packages. 12708 */ 12709 final int requiredUid = mRequiredVerifierPackage == null ? -1 12710 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12711 verifierUser.getIdentifier()); 12712 if (!origin.existing && requiredUid != -1 12713 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12714 final Intent verification = new Intent( 12715 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12716 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12717 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12718 PACKAGE_MIME_TYPE); 12719 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12720 12721 // Query all live verifiers based on current user state 12722 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12723 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12724 12725 if (DEBUG_VERIFY) { 12726 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12727 + verification.toString() + " with " + pkgLite.verifiers.length 12728 + " optional verifiers"); 12729 } 12730 12731 final int verificationId = mPendingVerificationToken++; 12732 12733 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12734 12735 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12736 installerPackageName); 12737 12738 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12739 installFlags); 12740 12741 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12742 pkgLite.packageName); 12743 12744 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12745 pkgLite.versionCode); 12746 12747 if (verificationInfo != null) { 12748 if (verificationInfo.originatingUri != null) { 12749 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12750 verificationInfo.originatingUri); 12751 } 12752 if (verificationInfo.referrer != null) { 12753 verification.putExtra(Intent.EXTRA_REFERRER, 12754 verificationInfo.referrer); 12755 } 12756 if (verificationInfo.originatingUid >= 0) { 12757 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12758 verificationInfo.originatingUid); 12759 } 12760 if (verificationInfo.installerUid >= 0) { 12761 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12762 verificationInfo.installerUid); 12763 } 12764 } 12765 12766 final PackageVerificationState verificationState = new PackageVerificationState( 12767 requiredUid, args); 12768 12769 mPendingVerification.append(verificationId, verificationState); 12770 12771 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12772 receivers, verificationState); 12773 12774 /* 12775 * If any sufficient verifiers were listed in the package 12776 * manifest, attempt to ask them. 12777 */ 12778 if (sufficientVerifiers != null) { 12779 final int N = sufficientVerifiers.size(); 12780 if (N == 0) { 12781 Slog.i(TAG, "Additional verifiers required, but none installed."); 12782 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12783 } else { 12784 for (int i = 0; i < N; i++) { 12785 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12786 12787 final Intent sufficientIntent = new Intent(verification); 12788 sufficientIntent.setComponent(verifierComponent); 12789 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12790 } 12791 } 12792 } 12793 12794 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12795 mRequiredVerifierPackage, receivers); 12796 if (ret == PackageManager.INSTALL_SUCCEEDED 12797 && mRequiredVerifierPackage != null) { 12798 Trace.asyncTraceBegin( 12799 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12800 /* 12801 * Send the intent to the required verification agent, 12802 * but only start the verification timeout after the 12803 * target BroadcastReceivers have run. 12804 */ 12805 verification.setComponent(requiredVerifierComponent); 12806 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12807 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12808 new BroadcastReceiver() { 12809 @Override 12810 public void onReceive(Context context, Intent intent) { 12811 final Message msg = mHandler 12812 .obtainMessage(CHECK_PENDING_VERIFICATION); 12813 msg.arg1 = verificationId; 12814 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12815 } 12816 }, null, 0, null, null); 12817 12818 /* 12819 * We don't want the copy to proceed until verification 12820 * succeeds, so null out this field. 12821 */ 12822 mArgs = null; 12823 } 12824 } else { 12825 /* 12826 * No package verification is enabled, so immediately start 12827 * the remote call to initiate copy using temporary file. 12828 */ 12829 ret = args.copyApk(mContainerService, true); 12830 } 12831 } 12832 12833 mRet = ret; 12834 } 12835 12836 @Override 12837 void handleReturnCode() { 12838 // If mArgs is null, then MCS couldn't be reached. When it 12839 // reconnects, it will try again to install. At that point, this 12840 // will succeed. 12841 if (mArgs != null) { 12842 processPendingInstall(mArgs, mRet); 12843 } 12844 } 12845 12846 @Override 12847 void handleServiceError() { 12848 mArgs = createInstallArgs(this); 12849 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12850 } 12851 12852 public boolean isForwardLocked() { 12853 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12854 } 12855 } 12856 12857 /** 12858 * Used during creation of InstallArgs 12859 * 12860 * @param installFlags package installation flags 12861 * @return true if should be installed on external storage 12862 */ 12863 private static boolean installOnExternalAsec(int installFlags) { 12864 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12865 return false; 12866 } 12867 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12868 return true; 12869 } 12870 return false; 12871 } 12872 12873 /** 12874 * Used during creation of InstallArgs 12875 * 12876 * @param installFlags package installation flags 12877 * @return true if should be installed as forward locked 12878 */ 12879 private static boolean installForwardLocked(int installFlags) { 12880 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12881 } 12882 12883 private InstallArgs createInstallArgs(InstallParams params) { 12884 if (params.move != null) { 12885 return new MoveInstallArgs(params); 12886 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12887 return new AsecInstallArgs(params); 12888 } else { 12889 return new FileInstallArgs(params); 12890 } 12891 } 12892 12893 /** 12894 * Create args that describe an existing installed package. Typically used 12895 * when cleaning up old installs, or used as a move source. 12896 */ 12897 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12898 String resourcePath, String[] instructionSets) { 12899 final boolean isInAsec; 12900 if (installOnExternalAsec(installFlags)) { 12901 /* Apps on SD card are always in ASEC containers. */ 12902 isInAsec = true; 12903 } else if (installForwardLocked(installFlags) 12904 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12905 /* 12906 * Forward-locked apps are only in ASEC containers if they're the 12907 * new style 12908 */ 12909 isInAsec = true; 12910 } else { 12911 isInAsec = false; 12912 } 12913 12914 if (isInAsec) { 12915 return new AsecInstallArgs(codePath, instructionSets, 12916 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12917 } else { 12918 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12919 } 12920 } 12921 12922 static abstract class InstallArgs { 12923 /** @see InstallParams#origin */ 12924 final OriginInfo origin; 12925 /** @see InstallParams#move */ 12926 final MoveInfo move; 12927 12928 final IPackageInstallObserver2 observer; 12929 // Always refers to PackageManager flags only 12930 final int installFlags; 12931 final String installerPackageName; 12932 final String volumeUuid; 12933 final UserHandle user; 12934 final String abiOverride; 12935 final String[] installGrantPermissions; 12936 /** If non-null, drop an async trace when the install completes */ 12937 final String traceMethod; 12938 final int traceCookie; 12939 final Certificate[][] certificates; 12940 12941 // The list of instruction sets supported by this app. This is currently 12942 // only used during the rmdex() phase to clean up resources. We can get rid of this 12943 // if we move dex files under the common app path. 12944 /* nullable */ String[] instructionSets; 12945 12946 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12947 int installFlags, String installerPackageName, String volumeUuid, 12948 UserHandle user, String[] instructionSets, 12949 String abiOverride, String[] installGrantPermissions, 12950 String traceMethod, int traceCookie, Certificate[][] certificates) { 12951 this.origin = origin; 12952 this.move = move; 12953 this.installFlags = installFlags; 12954 this.observer = observer; 12955 this.installerPackageName = installerPackageName; 12956 this.volumeUuid = volumeUuid; 12957 this.user = user; 12958 this.instructionSets = instructionSets; 12959 this.abiOverride = abiOverride; 12960 this.installGrantPermissions = installGrantPermissions; 12961 this.traceMethod = traceMethod; 12962 this.traceCookie = traceCookie; 12963 this.certificates = certificates; 12964 } 12965 12966 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12967 abstract int doPreInstall(int status); 12968 12969 /** 12970 * Rename package into final resting place. All paths on the given 12971 * scanned package should be updated to reflect the rename. 12972 */ 12973 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12974 abstract int doPostInstall(int status, int uid); 12975 12976 /** @see PackageSettingBase#codePathString */ 12977 abstract String getCodePath(); 12978 /** @see PackageSettingBase#resourcePathString */ 12979 abstract String getResourcePath(); 12980 12981 // Need installer lock especially for dex file removal. 12982 abstract void cleanUpResourcesLI(); 12983 abstract boolean doPostDeleteLI(boolean delete); 12984 12985 /** 12986 * Called before the source arguments are copied. This is used mostly 12987 * for MoveParams when it needs to read the source file to put it in the 12988 * destination. 12989 */ 12990 int doPreCopy() { 12991 return PackageManager.INSTALL_SUCCEEDED; 12992 } 12993 12994 /** 12995 * Called after the source arguments are copied. This is used mostly for 12996 * MoveParams when it needs to read the source file to put it in the 12997 * destination. 12998 */ 12999 int doPostCopy(int uid) { 13000 return PackageManager.INSTALL_SUCCEEDED; 13001 } 13002 13003 protected boolean isFwdLocked() { 13004 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13005 } 13006 13007 protected boolean isExternalAsec() { 13008 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13009 } 13010 13011 protected boolean isEphemeral() { 13012 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13013 } 13014 13015 UserHandle getUser() { 13016 return user; 13017 } 13018 } 13019 13020 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13021 if (!allCodePaths.isEmpty()) { 13022 if (instructionSets == null) { 13023 throw new IllegalStateException("instructionSet == null"); 13024 } 13025 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13026 for (String codePath : allCodePaths) { 13027 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13028 try { 13029 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13030 } catch (InstallerException ignored) { 13031 } 13032 } 13033 } 13034 } 13035 } 13036 13037 /** 13038 * Logic to handle installation of non-ASEC applications, including copying 13039 * and renaming logic. 13040 */ 13041 class FileInstallArgs extends InstallArgs { 13042 private File codeFile; 13043 private File resourceFile; 13044 13045 // Example topology: 13046 // /data/app/com.example/base.apk 13047 // /data/app/com.example/split_foo.apk 13048 // /data/app/com.example/lib/arm/libfoo.so 13049 // /data/app/com.example/lib/arm64/libfoo.so 13050 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13051 13052 /** New install */ 13053 FileInstallArgs(InstallParams params) { 13054 super(params.origin, params.move, params.observer, params.installFlags, 13055 params.installerPackageName, params.volumeUuid, 13056 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13057 params.grantedRuntimePermissions, 13058 params.traceMethod, params.traceCookie, params.certificates); 13059 if (isFwdLocked()) { 13060 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13061 } 13062 } 13063 13064 /** Existing install */ 13065 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13066 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13067 null, null, null, 0, null /*certificates*/); 13068 this.codeFile = (codePath != null) ? new File(codePath) : null; 13069 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13070 } 13071 13072 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13073 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13074 try { 13075 return doCopyApk(imcs, temp); 13076 } finally { 13077 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13078 } 13079 } 13080 13081 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13082 if (origin.staged) { 13083 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13084 codeFile = origin.file; 13085 resourceFile = origin.file; 13086 return PackageManager.INSTALL_SUCCEEDED; 13087 } 13088 13089 try { 13090 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13091 final File tempDir = 13092 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13093 codeFile = tempDir; 13094 resourceFile = tempDir; 13095 } catch (IOException e) { 13096 Slog.w(TAG, "Failed to create copy file: " + e); 13097 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13098 } 13099 13100 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13101 @Override 13102 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13103 if (!FileUtils.isValidExtFilename(name)) { 13104 throw new IllegalArgumentException("Invalid filename: " + name); 13105 } 13106 try { 13107 final File file = new File(codeFile, name); 13108 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13109 O_RDWR | O_CREAT, 0644); 13110 Os.chmod(file.getAbsolutePath(), 0644); 13111 return new ParcelFileDescriptor(fd); 13112 } catch (ErrnoException e) { 13113 throw new RemoteException("Failed to open: " + e.getMessage()); 13114 } 13115 } 13116 }; 13117 13118 int ret = PackageManager.INSTALL_SUCCEEDED; 13119 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13120 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13121 Slog.e(TAG, "Failed to copy package"); 13122 return ret; 13123 } 13124 13125 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13126 NativeLibraryHelper.Handle handle = null; 13127 try { 13128 handle = NativeLibraryHelper.Handle.create(codeFile); 13129 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13130 abiOverride); 13131 } catch (IOException e) { 13132 Slog.e(TAG, "Copying native libraries failed", e); 13133 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13134 } finally { 13135 IoUtils.closeQuietly(handle); 13136 } 13137 13138 return ret; 13139 } 13140 13141 int doPreInstall(int status) { 13142 if (status != PackageManager.INSTALL_SUCCEEDED) { 13143 cleanUp(); 13144 } 13145 return status; 13146 } 13147 13148 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13149 if (status != PackageManager.INSTALL_SUCCEEDED) { 13150 cleanUp(); 13151 return false; 13152 } 13153 13154 final File targetDir = codeFile.getParentFile(); 13155 final File beforeCodeFile = codeFile; 13156 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13157 13158 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13159 try { 13160 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13161 } catch (ErrnoException e) { 13162 Slog.w(TAG, "Failed to rename", e); 13163 return false; 13164 } 13165 13166 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13167 Slog.w(TAG, "Failed to restorecon"); 13168 return false; 13169 } 13170 13171 // Reflect the rename internally 13172 codeFile = afterCodeFile; 13173 resourceFile = afterCodeFile; 13174 13175 // Reflect the rename in scanned details 13176 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13177 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13178 afterCodeFile, pkg.baseCodePath)); 13179 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13180 afterCodeFile, pkg.splitCodePaths)); 13181 13182 // Reflect the rename in app info 13183 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13184 pkg.setApplicationInfoCodePath(pkg.codePath); 13185 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13186 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13187 pkg.setApplicationInfoResourcePath(pkg.codePath); 13188 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13189 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13190 13191 return true; 13192 } 13193 13194 int doPostInstall(int status, int uid) { 13195 if (status != PackageManager.INSTALL_SUCCEEDED) { 13196 cleanUp(); 13197 } 13198 return status; 13199 } 13200 13201 @Override 13202 String getCodePath() { 13203 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13204 } 13205 13206 @Override 13207 String getResourcePath() { 13208 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13209 } 13210 13211 private boolean cleanUp() { 13212 if (codeFile == null || !codeFile.exists()) { 13213 return false; 13214 } 13215 13216 removeCodePathLI(codeFile); 13217 13218 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13219 resourceFile.delete(); 13220 } 13221 13222 return true; 13223 } 13224 13225 void cleanUpResourcesLI() { 13226 // Try enumerating all code paths before deleting 13227 List<String> allCodePaths = Collections.EMPTY_LIST; 13228 if (codeFile != null && codeFile.exists()) { 13229 try { 13230 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13231 allCodePaths = pkg.getAllCodePaths(); 13232 } catch (PackageParserException e) { 13233 // Ignored; we tried our best 13234 } 13235 } 13236 13237 cleanUp(); 13238 removeDexFiles(allCodePaths, instructionSets); 13239 } 13240 13241 boolean doPostDeleteLI(boolean delete) { 13242 // XXX err, shouldn't we respect the delete flag? 13243 cleanUpResourcesLI(); 13244 return true; 13245 } 13246 } 13247 13248 private boolean isAsecExternal(String cid) { 13249 final String asecPath = PackageHelper.getSdFilesystem(cid); 13250 return !asecPath.startsWith(mAsecInternalPath); 13251 } 13252 13253 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13254 PackageManagerException { 13255 if (copyRet < 0) { 13256 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13257 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13258 throw new PackageManagerException(copyRet, message); 13259 } 13260 } 13261 } 13262 13263 /** 13264 * Extract the MountService "container ID" from the full code path of an 13265 * .apk. 13266 */ 13267 static String cidFromCodePath(String fullCodePath) { 13268 int eidx = fullCodePath.lastIndexOf("/"); 13269 String subStr1 = fullCodePath.substring(0, eidx); 13270 int sidx = subStr1.lastIndexOf("/"); 13271 return subStr1.substring(sidx+1, eidx); 13272 } 13273 13274 /** 13275 * Logic to handle installation of ASEC applications, including copying and 13276 * renaming logic. 13277 */ 13278 class AsecInstallArgs extends InstallArgs { 13279 static final String RES_FILE_NAME = "pkg.apk"; 13280 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13281 13282 String cid; 13283 String packagePath; 13284 String resourcePath; 13285 13286 /** New install */ 13287 AsecInstallArgs(InstallParams params) { 13288 super(params.origin, params.move, params.observer, params.installFlags, 13289 params.installerPackageName, params.volumeUuid, 13290 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13291 params.grantedRuntimePermissions, 13292 params.traceMethod, params.traceCookie, params.certificates); 13293 } 13294 13295 /** Existing install */ 13296 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13297 boolean isExternal, boolean isForwardLocked) { 13298 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13299 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13300 instructionSets, null, null, null, 0, null /*certificates*/); 13301 // Hackily pretend we're still looking at a full code path 13302 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13303 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13304 } 13305 13306 // Extract cid from fullCodePath 13307 int eidx = fullCodePath.lastIndexOf("/"); 13308 String subStr1 = fullCodePath.substring(0, eidx); 13309 int sidx = subStr1.lastIndexOf("/"); 13310 cid = subStr1.substring(sidx+1, eidx); 13311 setMountPath(subStr1); 13312 } 13313 13314 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13315 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13316 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13317 instructionSets, null, null, null, 0, null /*certificates*/); 13318 this.cid = cid; 13319 setMountPath(PackageHelper.getSdDir(cid)); 13320 } 13321 13322 void createCopyFile() { 13323 cid = mInstallerService.allocateExternalStageCidLegacy(); 13324 } 13325 13326 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13327 if (origin.staged && origin.cid != null) { 13328 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13329 cid = origin.cid; 13330 setMountPath(PackageHelper.getSdDir(cid)); 13331 return PackageManager.INSTALL_SUCCEEDED; 13332 } 13333 13334 if (temp) { 13335 createCopyFile(); 13336 } else { 13337 /* 13338 * Pre-emptively destroy the container since it's destroyed if 13339 * copying fails due to it existing anyway. 13340 */ 13341 PackageHelper.destroySdDir(cid); 13342 } 13343 13344 final String newMountPath = imcs.copyPackageToContainer( 13345 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13346 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13347 13348 if (newMountPath != null) { 13349 setMountPath(newMountPath); 13350 return PackageManager.INSTALL_SUCCEEDED; 13351 } else { 13352 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13353 } 13354 } 13355 13356 @Override 13357 String getCodePath() { 13358 return packagePath; 13359 } 13360 13361 @Override 13362 String getResourcePath() { 13363 return resourcePath; 13364 } 13365 13366 int doPreInstall(int status) { 13367 if (status != PackageManager.INSTALL_SUCCEEDED) { 13368 // Destroy container 13369 PackageHelper.destroySdDir(cid); 13370 } else { 13371 boolean mounted = PackageHelper.isContainerMounted(cid); 13372 if (!mounted) { 13373 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13374 Process.SYSTEM_UID); 13375 if (newMountPath != null) { 13376 setMountPath(newMountPath); 13377 } else { 13378 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13379 } 13380 } 13381 } 13382 return status; 13383 } 13384 13385 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13386 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13387 String newMountPath = null; 13388 if (PackageHelper.isContainerMounted(cid)) { 13389 // Unmount the container 13390 if (!PackageHelper.unMountSdDir(cid)) { 13391 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13392 return false; 13393 } 13394 } 13395 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13396 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13397 " which might be stale. Will try to clean up."); 13398 // Clean up the stale container and proceed to recreate. 13399 if (!PackageHelper.destroySdDir(newCacheId)) { 13400 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13401 return false; 13402 } 13403 // Successfully cleaned up stale container. Try to rename again. 13404 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13405 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13406 + " inspite of cleaning it up."); 13407 return false; 13408 } 13409 } 13410 if (!PackageHelper.isContainerMounted(newCacheId)) { 13411 Slog.w(TAG, "Mounting container " + newCacheId); 13412 newMountPath = PackageHelper.mountSdDir(newCacheId, 13413 getEncryptKey(), Process.SYSTEM_UID); 13414 } else { 13415 newMountPath = PackageHelper.getSdDir(newCacheId); 13416 } 13417 if (newMountPath == null) { 13418 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13419 return false; 13420 } 13421 Log.i(TAG, "Succesfully renamed " + cid + 13422 " to " + newCacheId + 13423 " at new path: " + newMountPath); 13424 cid = newCacheId; 13425 13426 final File beforeCodeFile = new File(packagePath); 13427 setMountPath(newMountPath); 13428 final File afterCodeFile = new File(packagePath); 13429 13430 // Reflect the rename in scanned details 13431 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13432 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13433 afterCodeFile, pkg.baseCodePath)); 13434 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13435 afterCodeFile, pkg.splitCodePaths)); 13436 13437 // Reflect the rename in app info 13438 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13439 pkg.setApplicationInfoCodePath(pkg.codePath); 13440 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13441 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13442 pkg.setApplicationInfoResourcePath(pkg.codePath); 13443 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13444 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13445 13446 return true; 13447 } 13448 13449 private void setMountPath(String mountPath) { 13450 final File mountFile = new File(mountPath); 13451 13452 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13453 if (monolithicFile.exists()) { 13454 packagePath = monolithicFile.getAbsolutePath(); 13455 if (isFwdLocked()) { 13456 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13457 } else { 13458 resourcePath = packagePath; 13459 } 13460 } else { 13461 packagePath = mountFile.getAbsolutePath(); 13462 resourcePath = packagePath; 13463 } 13464 } 13465 13466 int doPostInstall(int status, int uid) { 13467 if (status != PackageManager.INSTALL_SUCCEEDED) { 13468 cleanUp(); 13469 } else { 13470 final int groupOwner; 13471 final String protectedFile; 13472 if (isFwdLocked()) { 13473 groupOwner = UserHandle.getSharedAppGid(uid); 13474 protectedFile = RES_FILE_NAME; 13475 } else { 13476 groupOwner = -1; 13477 protectedFile = null; 13478 } 13479 13480 if (uid < Process.FIRST_APPLICATION_UID 13481 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13482 Slog.e(TAG, "Failed to finalize " + cid); 13483 PackageHelper.destroySdDir(cid); 13484 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13485 } 13486 13487 boolean mounted = PackageHelper.isContainerMounted(cid); 13488 if (!mounted) { 13489 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13490 } 13491 } 13492 return status; 13493 } 13494 13495 private void cleanUp() { 13496 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13497 13498 // Destroy secure container 13499 PackageHelper.destroySdDir(cid); 13500 } 13501 13502 private List<String> getAllCodePaths() { 13503 final File codeFile = new File(getCodePath()); 13504 if (codeFile != null && codeFile.exists()) { 13505 try { 13506 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13507 return pkg.getAllCodePaths(); 13508 } catch (PackageParserException e) { 13509 // Ignored; we tried our best 13510 } 13511 } 13512 return Collections.EMPTY_LIST; 13513 } 13514 13515 void cleanUpResourcesLI() { 13516 // Enumerate all code paths before deleting 13517 cleanUpResourcesLI(getAllCodePaths()); 13518 } 13519 13520 private void cleanUpResourcesLI(List<String> allCodePaths) { 13521 cleanUp(); 13522 removeDexFiles(allCodePaths, instructionSets); 13523 } 13524 13525 String getPackageName() { 13526 return getAsecPackageName(cid); 13527 } 13528 13529 boolean doPostDeleteLI(boolean delete) { 13530 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13531 final List<String> allCodePaths = getAllCodePaths(); 13532 boolean mounted = PackageHelper.isContainerMounted(cid); 13533 if (mounted) { 13534 // Unmount first 13535 if (PackageHelper.unMountSdDir(cid)) { 13536 mounted = false; 13537 } 13538 } 13539 if (!mounted && delete) { 13540 cleanUpResourcesLI(allCodePaths); 13541 } 13542 return !mounted; 13543 } 13544 13545 @Override 13546 int doPreCopy() { 13547 if (isFwdLocked()) { 13548 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13549 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13550 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13551 } 13552 } 13553 13554 return PackageManager.INSTALL_SUCCEEDED; 13555 } 13556 13557 @Override 13558 int doPostCopy(int uid) { 13559 if (isFwdLocked()) { 13560 if (uid < Process.FIRST_APPLICATION_UID 13561 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13562 RES_FILE_NAME)) { 13563 Slog.e(TAG, "Failed to finalize " + cid); 13564 PackageHelper.destroySdDir(cid); 13565 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13566 } 13567 } 13568 13569 return PackageManager.INSTALL_SUCCEEDED; 13570 } 13571 } 13572 13573 /** 13574 * Logic to handle movement of existing installed applications. 13575 */ 13576 class MoveInstallArgs extends InstallArgs { 13577 private File codeFile; 13578 private File resourceFile; 13579 13580 /** New install */ 13581 MoveInstallArgs(InstallParams params) { 13582 super(params.origin, params.move, params.observer, params.installFlags, 13583 params.installerPackageName, params.volumeUuid, 13584 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13585 params.grantedRuntimePermissions, 13586 params.traceMethod, params.traceCookie, params.certificates); 13587 } 13588 13589 int copyApk(IMediaContainerService imcs, boolean temp) { 13590 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13591 + move.fromUuid + " to " + move.toUuid); 13592 synchronized (mInstaller) { 13593 try { 13594 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13595 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13596 } catch (InstallerException e) { 13597 Slog.w(TAG, "Failed to move app", e); 13598 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13599 } 13600 } 13601 13602 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13603 resourceFile = codeFile; 13604 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13605 13606 return PackageManager.INSTALL_SUCCEEDED; 13607 } 13608 13609 int doPreInstall(int status) { 13610 if (status != PackageManager.INSTALL_SUCCEEDED) { 13611 cleanUp(move.toUuid); 13612 } 13613 return status; 13614 } 13615 13616 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13617 if (status != PackageManager.INSTALL_SUCCEEDED) { 13618 cleanUp(move.toUuid); 13619 return false; 13620 } 13621 13622 // Reflect the move in app info 13623 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13624 pkg.setApplicationInfoCodePath(pkg.codePath); 13625 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13626 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13627 pkg.setApplicationInfoResourcePath(pkg.codePath); 13628 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13629 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13630 13631 return true; 13632 } 13633 13634 int doPostInstall(int status, int uid) { 13635 if (status == PackageManager.INSTALL_SUCCEEDED) { 13636 cleanUp(move.fromUuid); 13637 } else { 13638 cleanUp(move.toUuid); 13639 } 13640 return status; 13641 } 13642 13643 @Override 13644 String getCodePath() { 13645 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13646 } 13647 13648 @Override 13649 String getResourcePath() { 13650 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13651 } 13652 13653 private boolean cleanUp(String volumeUuid) { 13654 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13655 move.dataAppName); 13656 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13657 final int[] userIds = sUserManager.getUserIds(); 13658 synchronized (mInstallLock) { 13659 // Clean up both app data and code 13660 // All package moves are frozen until finished 13661 for (int userId : userIds) { 13662 try { 13663 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13664 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13665 } catch (InstallerException e) { 13666 Slog.w(TAG, String.valueOf(e)); 13667 } 13668 } 13669 removeCodePathLI(codeFile); 13670 } 13671 return true; 13672 } 13673 13674 void cleanUpResourcesLI() { 13675 throw new UnsupportedOperationException(); 13676 } 13677 13678 boolean doPostDeleteLI(boolean delete) { 13679 throw new UnsupportedOperationException(); 13680 } 13681 } 13682 13683 static String getAsecPackageName(String packageCid) { 13684 int idx = packageCid.lastIndexOf("-"); 13685 if (idx == -1) { 13686 return packageCid; 13687 } 13688 return packageCid.substring(0, idx); 13689 } 13690 13691 // Utility method used to create code paths based on package name and available index. 13692 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13693 String idxStr = ""; 13694 int idx = 1; 13695 // Fall back to default value of idx=1 if prefix is not 13696 // part of oldCodePath 13697 if (oldCodePath != null) { 13698 String subStr = oldCodePath; 13699 // Drop the suffix right away 13700 if (suffix != null && subStr.endsWith(suffix)) { 13701 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13702 } 13703 // If oldCodePath already contains prefix find out the 13704 // ending index to either increment or decrement. 13705 int sidx = subStr.lastIndexOf(prefix); 13706 if (sidx != -1) { 13707 subStr = subStr.substring(sidx + prefix.length()); 13708 if (subStr != null) { 13709 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13710 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13711 } 13712 try { 13713 idx = Integer.parseInt(subStr); 13714 if (idx <= 1) { 13715 idx++; 13716 } else { 13717 idx--; 13718 } 13719 } catch(NumberFormatException e) { 13720 } 13721 } 13722 } 13723 } 13724 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13725 return prefix + idxStr; 13726 } 13727 13728 private File getNextCodePath(File targetDir, String packageName) { 13729 int suffix = 1; 13730 File result; 13731 do { 13732 result = new File(targetDir, packageName + "-" + suffix); 13733 suffix++; 13734 } while (result.exists()); 13735 return result; 13736 } 13737 13738 // Utility method that returns the relative package path with respect 13739 // to the installation directory. Like say for /data/data/com.test-1.apk 13740 // string com.test-1 is returned. 13741 static String deriveCodePathName(String codePath) { 13742 if (codePath == null) { 13743 return null; 13744 } 13745 final File codeFile = new File(codePath); 13746 final String name = codeFile.getName(); 13747 if (codeFile.isDirectory()) { 13748 return name; 13749 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13750 final int lastDot = name.lastIndexOf('.'); 13751 return name.substring(0, lastDot); 13752 } else { 13753 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13754 return null; 13755 } 13756 } 13757 13758 static class PackageInstalledInfo { 13759 String name; 13760 int uid; 13761 // The set of users that originally had this package installed. 13762 int[] origUsers; 13763 // The set of users that now have this package installed. 13764 int[] newUsers; 13765 PackageParser.Package pkg; 13766 int returnCode; 13767 String returnMsg; 13768 PackageRemovedInfo removedInfo; 13769 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13770 13771 public void setError(int code, String msg) { 13772 setReturnCode(code); 13773 setReturnMessage(msg); 13774 Slog.w(TAG, msg); 13775 } 13776 13777 public void setError(String msg, PackageParserException e) { 13778 setReturnCode(e.error); 13779 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13780 Slog.w(TAG, msg, e); 13781 } 13782 13783 public void setError(String msg, PackageManagerException e) { 13784 returnCode = e.error; 13785 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13786 Slog.w(TAG, msg, e); 13787 } 13788 13789 public void setReturnCode(int returnCode) { 13790 this.returnCode = returnCode; 13791 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13792 for (int i = 0; i < childCount; i++) { 13793 addedChildPackages.valueAt(i).returnCode = returnCode; 13794 } 13795 } 13796 13797 private void setReturnMessage(String returnMsg) { 13798 this.returnMsg = returnMsg; 13799 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13800 for (int i = 0; i < childCount; i++) { 13801 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13802 } 13803 } 13804 13805 // In some error cases we want to convey more info back to the observer 13806 String origPackage; 13807 String origPermission; 13808 } 13809 13810 /* 13811 * Install a non-existing package. 13812 */ 13813 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13814 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13815 PackageInstalledInfo res) { 13816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13817 13818 // Remember this for later, in case we need to rollback this install 13819 String pkgName = pkg.packageName; 13820 13821 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13822 13823 synchronized(mPackages) { 13824 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13825 // A package with the same name is already installed, though 13826 // it has been renamed to an older name. The package we 13827 // are trying to install should be installed as an update to 13828 // the existing one, but that has not been requested, so bail. 13829 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13830 + " without first uninstalling package running as " 13831 + mSettings.mRenamedPackages.get(pkgName)); 13832 return; 13833 } 13834 if (mPackages.containsKey(pkgName)) { 13835 // Don't allow installation over an existing package with the same name. 13836 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13837 + " without first uninstalling."); 13838 return; 13839 } 13840 } 13841 13842 try { 13843 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13844 System.currentTimeMillis(), user); 13845 13846 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13847 13848 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13849 prepareAppDataAfterInstallLIF(newPackage); 13850 13851 } else { 13852 // Remove package from internal structures, but keep around any 13853 // data that might have already existed 13854 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13855 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13856 } 13857 } catch (PackageManagerException e) { 13858 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13859 } 13860 13861 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13862 } 13863 13864 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13865 // Can't rotate keys during boot or if sharedUser. 13866 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13867 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13868 return false; 13869 } 13870 // app is using upgradeKeySets; make sure all are valid 13871 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13872 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13873 for (int i = 0; i < upgradeKeySets.length; i++) { 13874 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13875 Slog.wtf(TAG, "Package " 13876 + (oldPs.name != null ? oldPs.name : "<null>") 13877 + " contains upgrade-key-set reference to unknown key-set: " 13878 + upgradeKeySets[i] 13879 + " reverting to signatures check."); 13880 return false; 13881 } 13882 } 13883 return true; 13884 } 13885 13886 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13887 // Upgrade keysets are being used. Determine if new package has a superset of the 13888 // required keys. 13889 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13890 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13891 for (int i = 0; i < upgradeKeySets.length; i++) { 13892 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13893 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13894 return true; 13895 } 13896 } 13897 return false; 13898 } 13899 13900 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13901 try (DigestInputStream digestStream = 13902 new DigestInputStream(new FileInputStream(file), digest)) { 13903 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13904 } 13905 } 13906 13907 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13908 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13909 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13910 13911 final PackageParser.Package oldPackage; 13912 final String pkgName = pkg.packageName; 13913 final int[] allUsers; 13914 final int[] installedUsers; 13915 13916 synchronized(mPackages) { 13917 oldPackage = mPackages.get(pkgName); 13918 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13919 13920 // don't allow upgrade to target a release SDK from a pre-release SDK 13921 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13922 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13923 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13924 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13925 if (oldTargetsPreRelease 13926 && !newTargetsPreRelease 13927 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13928 Slog.w(TAG, "Can't install package targeting released sdk"); 13929 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13930 return; 13931 } 13932 13933 // don't allow an upgrade from full to ephemeral 13934 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13935 if (isEphemeral && !oldIsEphemeral) { 13936 // can't downgrade from full to ephemeral 13937 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13938 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13939 return; 13940 } 13941 13942 // verify signatures are valid 13943 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13944 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13945 if (!checkUpgradeKeySetLP(ps, pkg)) { 13946 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13947 "New package not signed by keys specified by upgrade-keysets: " 13948 + pkgName); 13949 return; 13950 } 13951 } else { 13952 // default to original signature matching 13953 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13954 != PackageManager.SIGNATURE_MATCH) { 13955 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13956 "New package has a different signature: " + pkgName); 13957 return; 13958 } 13959 } 13960 13961 // don't allow a system upgrade unless the upgrade hash matches 13962 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13963 byte[] digestBytes = null; 13964 try { 13965 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13966 updateDigest(digest, new File(pkg.baseCodePath)); 13967 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13968 for (String path : pkg.splitCodePaths) { 13969 updateDigest(digest, new File(path)); 13970 } 13971 } 13972 digestBytes = digest.digest(); 13973 } catch (NoSuchAlgorithmException | IOException e) { 13974 res.setError(INSTALL_FAILED_INVALID_APK, 13975 "Could not compute hash: " + pkgName); 13976 return; 13977 } 13978 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13979 res.setError(INSTALL_FAILED_INVALID_APK, 13980 "New package fails restrict-update check: " + pkgName); 13981 return; 13982 } 13983 // retain upgrade restriction 13984 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13985 } 13986 13987 // Check for shared user id changes 13988 String invalidPackageName = 13989 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13990 if (invalidPackageName != null) { 13991 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13992 "Package " + invalidPackageName + " tried to change user " 13993 + oldPackage.mSharedUserId); 13994 return; 13995 } 13996 13997 // In case of rollback, remember per-user/profile install state 13998 allUsers = sUserManager.getUserIds(); 13999 installedUsers = ps.queryInstalledUsers(allUsers, true); 14000 } 14001 14002 // Update what is removed 14003 res.removedInfo = new PackageRemovedInfo(); 14004 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14005 res.removedInfo.removedPackage = oldPackage.packageName; 14006 res.removedInfo.isUpdate = true; 14007 res.removedInfo.origUsers = installedUsers; 14008 final int childCount = (oldPackage.childPackages != null) 14009 ? oldPackage.childPackages.size() : 0; 14010 for (int i = 0; i < childCount; i++) { 14011 boolean childPackageUpdated = false; 14012 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14013 if (res.addedChildPackages != null) { 14014 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14015 if (childRes != null) { 14016 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14017 childRes.removedInfo.removedPackage = childPkg.packageName; 14018 childRes.removedInfo.isUpdate = true; 14019 childPackageUpdated = true; 14020 } 14021 } 14022 if (!childPackageUpdated) { 14023 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14024 childRemovedRes.removedPackage = childPkg.packageName; 14025 childRemovedRes.isUpdate = false; 14026 childRemovedRes.dataRemoved = true; 14027 synchronized (mPackages) { 14028 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14029 if (childPs != null) { 14030 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14031 } 14032 } 14033 if (res.removedInfo.removedChildPackages == null) { 14034 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14035 } 14036 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14037 } 14038 } 14039 14040 boolean sysPkg = (isSystemApp(oldPackage)); 14041 if (sysPkg) { 14042 // Set the system/privileged flags as needed 14043 final boolean privileged = 14044 (oldPackage.applicationInfo.privateFlags 14045 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14046 final int systemPolicyFlags = policyFlags 14047 | PackageParser.PARSE_IS_SYSTEM 14048 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14049 14050 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14051 user, allUsers, installerPackageName, res); 14052 } else { 14053 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14054 user, allUsers, installerPackageName, res); 14055 } 14056 } 14057 14058 public List<String> getPreviousCodePaths(String packageName) { 14059 final PackageSetting ps = mSettings.mPackages.get(packageName); 14060 final List<String> result = new ArrayList<String>(); 14061 if (ps != null && ps.oldCodePaths != null) { 14062 result.addAll(ps.oldCodePaths); 14063 } 14064 return result; 14065 } 14066 14067 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14068 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14069 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14070 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14071 + deletedPackage); 14072 14073 String pkgName = deletedPackage.packageName; 14074 boolean deletedPkg = true; 14075 boolean addedPkg = false; 14076 boolean updatedSettings = false; 14077 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14078 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14079 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14080 14081 final long origUpdateTime = (pkg.mExtras != null) 14082 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14083 14084 // First delete the existing package while retaining the data directory 14085 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14086 res.removedInfo, true, pkg)) { 14087 // If the existing package wasn't successfully deleted 14088 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14089 deletedPkg = false; 14090 } else { 14091 // Successfully deleted the old package; proceed with replace. 14092 14093 // If deleted package lived in a container, give users a chance to 14094 // relinquish resources before killing. 14095 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14096 if (DEBUG_INSTALL) { 14097 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14098 } 14099 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14100 final ArrayList<String> pkgList = new ArrayList<String>(1); 14101 pkgList.add(deletedPackage.applicationInfo.packageName); 14102 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14103 } 14104 14105 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14106 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14107 clearAppProfilesLIF(pkg); 14108 14109 try { 14110 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14111 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14112 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14113 14114 // Update the in-memory copy of the previous code paths. 14115 PackageSetting ps = mSettings.mPackages.get(pkgName); 14116 if (!killApp) { 14117 if (ps.oldCodePaths == null) { 14118 ps.oldCodePaths = new ArraySet<>(); 14119 } 14120 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14121 if (deletedPackage.splitCodePaths != null) { 14122 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14123 } 14124 } else { 14125 ps.oldCodePaths = null; 14126 } 14127 if (ps.childPackageNames != null) { 14128 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14129 final String childPkgName = ps.childPackageNames.get(i); 14130 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14131 childPs.oldCodePaths = ps.oldCodePaths; 14132 } 14133 } 14134 prepareAppDataAfterInstallLIF(newPackage); 14135 addedPkg = true; 14136 } catch (PackageManagerException e) { 14137 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14138 } 14139 } 14140 14141 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14142 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14143 14144 // Revert all internal state mutations and added folders for the failed install 14145 if (addedPkg) { 14146 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14147 res.removedInfo, true, null); 14148 } 14149 14150 // Restore the old package 14151 if (deletedPkg) { 14152 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14153 File restoreFile = new File(deletedPackage.codePath); 14154 // Parse old package 14155 boolean oldExternal = isExternal(deletedPackage); 14156 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14157 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14158 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14159 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14160 try { 14161 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14162 null); 14163 } catch (PackageManagerException e) { 14164 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14165 + e.getMessage()); 14166 return; 14167 } 14168 14169 synchronized (mPackages) { 14170 // Ensure the installer package name up to date 14171 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14172 14173 // Update permissions for restored package 14174 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14175 14176 mSettings.writeLPr(); 14177 } 14178 14179 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14180 } 14181 } else { 14182 synchronized (mPackages) { 14183 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14184 if (ps != null) { 14185 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14186 if (res.removedInfo.removedChildPackages != null) { 14187 final int childCount = res.removedInfo.removedChildPackages.size(); 14188 // Iterate in reverse as we may modify the collection 14189 for (int i = childCount - 1; i >= 0; i--) { 14190 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14191 if (res.addedChildPackages.containsKey(childPackageName)) { 14192 res.removedInfo.removedChildPackages.removeAt(i); 14193 } else { 14194 PackageRemovedInfo childInfo = res.removedInfo 14195 .removedChildPackages.valueAt(i); 14196 childInfo.removedForAllUsers = mPackages.get( 14197 childInfo.removedPackage) == null; 14198 } 14199 } 14200 } 14201 } 14202 } 14203 } 14204 } 14205 14206 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14207 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14208 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14209 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14210 + ", old=" + deletedPackage); 14211 14212 final boolean disabledSystem; 14213 14214 // Remove existing system package 14215 removePackageLI(deletedPackage, true); 14216 14217 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14218 if (!disabledSystem) { 14219 // We didn't need to disable the .apk as a current system package, 14220 // which means we are replacing another update that is already 14221 // installed. We need to make sure to delete the older one's .apk. 14222 res.removedInfo.args = createInstallArgsForExisting(0, 14223 deletedPackage.applicationInfo.getCodePath(), 14224 deletedPackage.applicationInfo.getResourcePath(), 14225 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14226 } else { 14227 res.removedInfo.args = null; 14228 } 14229 14230 // Successfully disabled the old package. Now proceed with re-installation 14231 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14232 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14233 clearAppProfilesLIF(pkg); 14234 14235 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14236 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14237 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14238 14239 PackageParser.Package newPackage = null; 14240 try { 14241 // Add the package to the internal data structures 14242 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14243 14244 // Set the update and install times 14245 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14246 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14247 System.currentTimeMillis()); 14248 14249 // Update the package dynamic state if succeeded 14250 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14251 // Now that the install succeeded make sure we remove data 14252 // directories for any child package the update removed. 14253 final int deletedChildCount = (deletedPackage.childPackages != null) 14254 ? deletedPackage.childPackages.size() : 0; 14255 final int newChildCount = (newPackage.childPackages != null) 14256 ? newPackage.childPackages.size() : 0; 14257 for (int i = 0; i < deletedChildCount; i++) { 14258 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14259 boolean childPackageDeleted = true; 14260 for (int j = 0; j < newChildCount; j++) { 14261 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14262 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14263 childPackageDeleted = false; 14264 break; 14265 } 14266 } 14267 if (childPackageDeleted) { 14268 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14269 deletedChildPkg.packageName); 14270 if (ps != null && res.removedInfo.removedChildPackages != null) { 14271 PackageRemovedInfo removedChildRes = res.removedInfo 14272 .removedChildPackages.get(deletedChildPkg.packageName); 14273 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14274 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14275 } 14276 } 14277 } 14278 14279 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14280 prepareAppDataAfterInstallLIF(newPackage); 14281 } 14282 } catch (PackageManagerException e) { 14283 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14284 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14285 } 14286 14287 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14288 // Re installation failed. Restore old information 14289 // Remove new pkg information 14290 if (newPackage != null) { 14291 removeInstalledPackageLI(newPackage, true); 14292 } 14293 // Add back the old system package 14294 try { 14295 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14296 } catch (PackageManagerException e) { 14297 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14298 } 14299 14300 synchronized (mPackages) { 14301 if (disabledSystem) { 14302 enableSystemPackageLPw(deletedPackage); 14303 } 14304 14305 // Ensure the installer package name up to date 14306 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14307 14308 // Update permissions for restored package 14309 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14310 14311 mSettings.writeLPr(); 14312 } 14313 14314 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14315 + " after failed upgrade"); 14316 } 14317 } 14318 14319 /** 14320 * Checks whether the parent or any of the child packages have a change shared 14321 * user. For a package to be a valid update the shred users of the parent and 14322 * the children should match. We may later support changing child shared users. 14323 * @param oldPkg The updated package. 14324 * @param newPkg The update package. 14325 * @return The shared user that change between the versions. 14326 */ 14327 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14328 PackageParser.Package newPkg) { 14329 // Check parent shared user 14330 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14331 return newPkg.packageName; 14332 } 14333 // Check child shared users 14334 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14335 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14336 for (int i = 0; i < newChildCount; i++) { 14337 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14338 // If this child was present, did it have the same shared user? 14339 for (int j = 0; j < oldChildCount; j++) { 14340 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14341 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14342 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14343 return newChildPkg.packageName; 14344 } 14345 } 14346 } 14347 return null; 14348 } 14349 14350 private void removeNativeBinariesLI(PackageSetting ps) { 14351 // Remove the lib path for the parent package 14352 if (ps != null) { 14353 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14354 // Remove the lib path for the child packages 14355 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14356 for (int i = 0; i < childCount; i++) { 14357 PackageSetting childPs = null; 14358 synchronized (mPackages) { 14359 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14360 } 14361 if (childPs != null) { 14362 NativeLibraryHelper.removeNativeBinariesLI(childPs 14363 .legacyNativeLibraryPathString); 14364 } 14365 } 14366 } 14367 } 14368 14369 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14370 // Enable the parent package 14371 mSettings.enableSystemPackageLPw(pkg.packageName); 14372 // Enable the child packages 14373 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14374 for (int i = 0; i < childCount; i++) { 14375 PackageParser.Package childPkg = pkg.childPackages.get(i); 14376 mSettings.enableSystemPackageLPw(childPkg.packageName); 14377 } 14378 } 14379 14380 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14381 PackageParser.Package newPkg) { 14382 // Disable the parent package (parent always replaced) 14383 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14384 // Disable the child packages 14385 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14386 for (int i = 0; i < childCount; i++) { 14387 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14388 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14389 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14390 } 14391 return disabled; 14392 } 14393 14394 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14395 String installerPackageName) { 14396 // Enable the parent package 14397 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14398 // Enable the child packages 14399 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14400 for (int i = 0; i < childCount; i++) { 14401 PackageParser.Package childPkg = pkg.childPackages.get(i); 14402 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14403 } 14404 } 14405 14406 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14407 // Collect all used permissions in the UID 14408 ArraySet<String> usedPermissions = new ArraySet<>(); 14409 final int packageCount = su.packages.size(); 14410 for (int i = 0; i < packageCount; i++) { 14411 PackageSetting ps = su.packages.valueAt(i); 14412 if (ps.pkg == null) { 14413 continue; 14414 } 14415 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14416 for (int j = 0; j < requestedPermCount; j++) { 14417 String permission = ps.pkg.requestedPermissions.get(j); 14418 BasePermission bp = mSettings.mPermissions.get(permission); 14419 if (bp != null) { 14420 usedPermissions.add(permission); 14421 } 14422 } 14423 } 14424 14425 PermissionsState permissionsState = su.getPermissionsState(); 14426 // Prune install permissions 14427 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14428 final int installPermCount = installPermStates.size(); 14429 for (int i = installPermCount - 1; i >= 0; i--) { 14430 PermissionState permissionState = installPermStates.get(i); 14431 if (!usedPermissions.contains(permissionState.getName())) { 14432 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14433 if (bp != null) { 14434 permissionsState.revokeInstallPermission(bp); 14435 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14436 PackageManager.MASK_PERMISSION_FLAGS, 0); 14437 } 14438 } 14439 } 14440 14441 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14442 14443 // Prune runtime permissions 14444 for (int userId : allUserIds) { 14445 List<PermissionState> runtimePermStates = permissionsState 14446 .getRuntimePermissionStates(userId); 14447 final int runtimePermCount = runtimePermStates.size(); 14448 for (int i = runtimePermCount - 1; i >= 0; i--) { 14449 PermissionState permissionState = runtimePermStates.get(i); 14450 if (!usedPermissions.contains(permissionState.getName())) { 14451 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14452 if (bp != null) { 14453 permissionsState.revokeRuntimePermission(bp, userId); 14454 permissionsState.updatePermissionFlags(bp, userId, 14455 PackageManager.MASK_PERMISSION_FLAGS, 0); 14456 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14457 runtimePermissionChangedUserIds, userId); 14458 } 14459 } 14460 } 14461 } 14462 14463 return runtimePermissionChangedUserIds; 14464 } 14465 14466 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14467 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14468 // Update the parent package setting 14469 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14470 res, user); 14471 // Update the child packages setting 14472 final int childCount = (newPackage.childPackages != null) 14473 ? newPackage.childPackages.size() : 0; 14474 for (int i = 0; i < childCount; i++) { 14475 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14476 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14477 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14478 childRes.origUsers, childRes, user); 14479 } 14480 } 14481 14482 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14483 String installerPackageName, int[] allUsers, int[] installedForUsers, 14484 PackageInstalledInfo res, UserHandle user) { 14485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14486 14487 String pkgName = newPackage.packageName; 14488 synchronized (mPackages) { 14489 //write settings. the installStatus will be incomplete at this stage. 14490 //note that the new package setting would have already been 14491 //added to mPackages. It hasn't been persisted yet. 14492 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14493 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14494 mSettings.writeLPr(); 14495 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14496 } 14497 14498 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14499 synchronized (mPackages) { 14500 updatePermissionsLPw(newPackage.packageName, newPackage, 14501 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14502 ? UPDATE_PERMISSIONS_ALL : 0)); 14503 // For system-bundled packages, we assume that installing an upgraded version 14504 // of the package implies that the user actually wants to run that new code, 14505 // so we enable the package. 14506 PackageSetting ps = mSettings.mPackages.get(pkgName); 14507 final int userId = user.getIdentifier(); 14508 if (ps != null) { 14509 if (isSystemApp(newPackage)) { 14510 if (DEBUG_INSTALL) { 14511 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14512 } 14513 // Enable system package for requested users 14514 if (res.origUsers != null) { 14515 for (int origUserId : res.origUsers) { 14516 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14517 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14518 origUserId, installerPackageName); 14519 } 14520 } 14521 } 14522 // Also convey the prior install/uninstall state 14523 if (allUsers != null && installedForUsers != null) { 14524 for (int currentUserId : allUsers) { 14525 final boolean installed = ArrayUtils.contains( 14526 installedForUsers, currentUserId); 14527 if (DEBUG_INSTALL) { 14528 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14529 } 14530 ps.setInstalled(installed, currentUserId); 14531 } 14532 // these install state changes will be persisted in the 14533 // upcoming call to mSettings.writeLPr(). 14534 } 14535 } 14536 // It's implied that when a user requests installation, they want the app to be 14537 // installed and enabled. 14538 if (userId != UserHandle.USER_ALL) { 14539 ps.setInstalled(true, userId); 14540 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14541 } 14542 } 14543 res.name = pkgName; 14544 res.uid = newPackage.applicationInfo.uid; 14545 res.pkg = newPackage; 14546 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14547 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14548 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14549 //to update install status 14550 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14551 mSettings.writeLPr(); 14552 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14553 } 14554 14555 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14556 } 14557 14558 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14559 try { 14560 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14561 installPackageLI(args, res); 14562 } finally { 14563 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14564 } 14565 } 14566 14567 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14568 final int installFlags = args.installFlags; 14569 final String installerPackageName = args.installerPackageName; 14570 final String volumeUuid = args.volumeUuid; 14571 final File tmpPackageFile = new File(args.getCodePath()); 14572 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14573 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14574 || (args.volumeUuid != null)); 14575 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14576 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14577 boolean replace = false; 14578 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14579 if (args.move != null) { 14580 // moving a complete application; perform an initial scan on the new install location 14581 scanFlags |= SCAN_INITIAL; 14582 } 14583 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14584 scanFlags |= SCAN_DONT_KILL_APP; 14585 } 14586 14587 // Result object to be returned 14588 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14589 14590 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14591 14592 // Sanity check 14593 if (ephemeral && (forwardLocked || onExternal)) { 14594 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14595 + " external=" + onExternal); 14596 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14597 return; 14598 } 14599 14600 // Retrieve PackageSettings and parse package 14601 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14602 | PackageParser.PARSE_ENFORCE_CODE 14603 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14604 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14605 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14606 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14607 PackageParser pp = new PackageParser(); 14608 pp.setSeparateProcesses(mSeparateProcesses); 14609 pp.setDisplayMetrics(mMetrics); 14610 14611 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14612 final PackageParser.Package pkg; 14613 try { 14614 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14615 } catch (PackageParserException e) { 14616 res.setError("Failed parse during installPackageLI", e); 14617 return; 14618 } finally { 14619 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14620 } 14621 14622 // If we are installing a clustered package add results for the children 14623 if (pkg.childPackages != null) { 14624 synchronized (mPackages) { 14625 final int childCount = pkg.childPackages.size(); 14626 for (int i = 0; i < childCount; i++) { 14627 PackageParser.Package childPkg = pkg.childPackages.get(i); 14628 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14629 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14630 childRes.pkg = childPkg; 14631 childRes.name = childPkg.packageName; 14632 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14633 if (childPs != null) { 14634 childRes.origUsers = childPs.queryInstalledUsers( 14635 sUserManager.getUserIds(), true); 14636 } 14637 if ((mPackages.containsKey(childPkg.packageName))) { 14638 childRes.removedInfo = new PackageRemovedInfo(); 14639 childRes.removedInfo.removedPackage = childPkg.packageName; 14640 } 14641 if (res.addedChildPackages == null) { 14642 res.addedChildPackages = new ArrayMap<>(); 14643 } 14644 res.addedChildPackages.put(childPkg.packageName, childRes); 14645 } 14646 } 14647 } 14648 14649 // If package doesn't declare API override, mark that we have an install 14650 // time CPU ABI override. 14651 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14652 pkg.cpuAbiOverride = args.abiOverride; 14653 } 14654 14655 String pkgName = res.name = pkg.packageName; 14656 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14657 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14658 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14659 return; 14660 } 14661 } 14662 14663 try { 14664 // either use what we've been given or parse directly from the APK 14665 if (args.certificates != null) { 14666 try { 14667 PackageParser.populateCertificates(pkg, args.certificates); 14668 } catch (PackageParserException e) { 14669 // there was something wrong with the certificates we were given; 14670 // try to pull them from the APK 14671 PackageParser.collectCertificates(pkg, parseFlags); 14672 } 14673 } else { 14674 PackageParser.collectCertificates(pkg, parseFlags); 14675 } 14676 } catch (PackageParserException e) { 14677 res.setError("Failed collect during installPackageLI", e); 14678 return; 14679 } 14680 14681 // Get rid of all references to package scan path via parser. 14682 pp = null; 14683 String oldCodePath = null; 14684 boolean systemApp = false; 14685 synchronized (mPackages) { 14686 // Check if installing already existing package 14687 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14688 String oldName = mSettings.mRenamedPackages.get(pkgName); 14689 if (pkg.mOriginalPackages != null 14690 && pkg.mOriginalPackages.contains(oldName) 14691 && mPackages.containsKey(oldName)) { 14692 // This package is derived from an original package, 14693 // and this device has been updating from that original 14694 // name. We must continue using the original name, so 14695 // rename the new package here. 14696 pkg.setPackageName(oldName); 14697 pkgName = pkg.packageName; 14698 replace = true; 14699 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14700 + oldName + " pkgName=" + pkgName); 14701 } else if (mPackages.containsKey(pkgName)) { 14702 // This package, under its official name, already exists 14703 // on the device; we should replace it. 14704 replace = true; 14705 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14706 } 14707 14708 // Child packages are installed through the parent package 14709 if (pkg.parentPackage != null) { 14710 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14711 "Package " + pkg.packageName + " is child of package " 14712 + pkg.parentPackage.parentPackage + ". Child packages " 14713 + "can be updated only through the parent package."); 14714 return; 14715 } 14716 14717 if (replace) { 14718 // Prevent apps opting out from runtime permissions 14719 PackageParser.Package oldPackage = mPackages.get(pkgName); 14720 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14721 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14722 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14723 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14724 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14725 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14726 + " doesn't support runtime permissions but the old" 14727 + " target SDK " + oldTargetSdk + " does."); 14728 return; 14729 } 14730 14731 // Prevent installing of child packages 14732 if (oldPackage.parentPackage != null) { 14733 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14734 "Package " + pkg.packageName + " is child of package " 14735 + oldPackage.parentPackage + ". Child packages " 14736 + "can be updated only through the parent package."); 14737 return; 14738 } 14739 } 14740 } 14741 14742 PackageSetting ps = mSettings.mPackages.get(pkgName); 14743 if (ps != null) { 14744 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14745 14746 // Quick sanity check that we're signed correctly if updating; 14747 // we'll check this again later when scanning, but we want to 14748 // bail early here before tripping over redefined permissions. 14749 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14750 if (!checkUpgradeKeySetLP(ps, pkg)) { 14751 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14752 + pkg.packageName + " upgrade keys do not match the " 14753 + "previously installed version"); 14754 return; 14755 } 14756 } else { 14757 try { 14758 verifySignaturesLP(ps, pkg); 14759 } catch (PackageManagerException e) { 14760 res.setError(e.error, e.getMessage()); 14761 return; 14762 } 14763 } 14764 14765 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14766 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14767 systemApp = (ps.pkg.applicationInfo.flags & 14768 ApplicationInfo.FLAG_SYSTEM) != 0; 14769 } 14770 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14771 } 14772 14773 // Check whether the newly-scanned package wants to define an already-defined perm 14774 int N = pkg.permissions.size(); 14775 for (int i = N-1; i >= 0; i--) { 14776 PackageParser.Permission perm = pkg.permissions.get(i); 14777 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14778 if (bp != null) { 14779 // If the defining package is signed with our cert, it's okay. This 14780 // also includes the "updating the same package" case, of course. 14781 // "updating same package" could also involve key-rotation. 14782 final boolean sigsOk; 14783 if (bp.sourcePackage.equals(pkg.packageName) 14784 && (bp.packageSetting instanceof PackageSetting) 14785 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14786 scanFlags))) { 14787 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14788 } else { 14789 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14790 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14791 } 14792 if (!sigsOk) { 14793 // If the owning package is the system itself, we log but allow 14794 // install to proceed; we fail the install on all other permission 14795 // redefinitions. 14796 if (!bp.sourcePackage.equals("android")) { 14797 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14798 + pkg.packageName + " attempting to redeclare permission " 14799 + perm.info.name + " already owned by " + bp.sourcePackage); 14800 res.origPermission = perm.info.name; 14801 res.origPackage = bp.sourcePackage; 14802 return; 14803 } else { 14804 Slog.w(TAG, "Package " + pkg.packageName 14805 + " attempting to redeclare system permission " 14806 + perm.info.name + "; ignoring new declaration"); 14807 pkg.permissions.remove(i); 14808 } 14809 } 14810 } 14811 } 14812 } 14813 14814 if (systemApp) { 14815 if (onExternal) { 14816 // Abort update; system app can't be replaced with app on sdcard 14817 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14818 "Cannot install updates to system apps on sdcard"); 14819 return; 14820 } else if (ephemeral) { 14821 // Abort update; system app can't be replaced with an ephemeral app 14822 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14823 "Cannot update a system app with an ephemeral app"); 14824 return; 14825 } 14826 } 14827 14828 if (args.move != null) { 14829 // We did an in-place move, so dex is ready to roll 14830 scanFlags |= SCAN_NO_DEX; 14831 scanFlags |= SCAN_MOVE; 14832 14833 synchronized (mPackages) { 14834 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14835 if (ps == null) { 14836 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14837 "Missing settings for moved package " + pkgName); 14838 } 14839 14840 // We moved the entire application as-is, so bring over the 14841 // previously derived ABI information. 14842 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14843 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14844 } 14845 14846 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14847 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14848 scanFlags |= SCAN_NO_DEX; 14849 14850 try { 14851 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14852 args.abiOverride : pkg.cpuAbiOverride); 14853 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14854 true /* extract libs */); 14855 } catch (PackageManagerException pme) { 14856 Slog.e(TAG, "Error deriving application ABI", pme); 14857 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14858 return; 14859 } 14860 14861 // Shared libraries for the package need to be updated. 14862 synchronized (mPackages) { 14863 try { 14864 updateSharedLibrariesLPw(pkg, null); 14865 } catch (PackageManagerException e) { 14866 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14867 } 14868 } 14869 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14870 // Do not run PackageDexOptimizer through the local performDexOpt 14871 // method because `pkg` is not in `mPackages` yet. 14872 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14873 null /* instructionSets */, false /* checkProfiles */, 14874 getCompilerFilterForReason(REASON_INSTALL)); 14875 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14876 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14877 String msg = "Extracting package failed for " + pkgName; 14878 res.setError(INSTALL_FAILED_DEXOPT, msg); 14879 return; 14880 } 14881 14882 // Notify BackgroundDexOptService that the package has been changed. 14883 // If this is an update of a package which used to fail to compile, 14884 // BDOS will remove it from its blacklist. 14885 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14886 } 14887 14888 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14889 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14890 return; 14891 } 14892 14893 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14894 14895 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14896 "installPackageLI")) { 14897 if (replace) { 14898 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14899 installerPackageName, res); 14900 } else { 14901 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14902 args.user, installerPackageName, volumeUuid, res); 14903 } 14904 } 14905 synchronized (mPackages) { 14906 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14907 if (ps != null) { 14908 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14909 } 14910 14911 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14912 for (int i = 0; i < childCount; i++) { 14913 PackageParser.Package childPkg = pkg.childPackages.get(i); 14914 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14915 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14916 if (childPs != null) { 14917 childRes.newUsers = childPs.queryInstalledUsers( 14918 sUserManager.getUserIds(), true); 14919 } 14920 } 14921 } 14922 } 14923 14924 private void startIntentFilterVerifications(int userId, boolean replacing, 14925 PackageParser.Package pkg) { 14926 if (mIntentFilterVerifierComponent == null) { 14927 Slog.w(TAG, "No IntentFilter verification will not be done as " 14928 + "there is no IntentFilterVerifier available!"); 14929 return; 14930 } 14931 14932 final int verifierUid = getPackageUid( 14933 mIntentFilterVerifierComponent.getPackageName(), 14934 MATCH_DEBUG_TRIAGED_MISSING, 14935 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14936 14937 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14938 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14939 mHandler.sendMessage(msg); 14940 14941 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14942 for (int i = 0; i < childCount; i++) { 14943 PackageParser.Package childPkg = pkg.childPackages.get(i); 14944 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14945 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14946 mHandler.sendMessage(msg); 14947 } 14948 } 14949 14950 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14951 PackageParser.Package pkg) { 14952 int size = pkg.activities.size(); 14953 if (size == 0) { 14954 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14955 "No activity, so no need to verify any IntentFilter!"); 14956 return; 14957 } 14958 14959 final boolean hasDomainURLs = hasDomainURLs(pkg); 14960 if (!hasDomainURLs) { 14961 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14962 "No domain URLs, so no need to verify any IntentFilter!"); 14963 return; 14964 } 14965 14966 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14967 + " if any IntentFilter from the " + size 14968 + " Activities needs verification ..."); 14969 14970 int count = 0; 14971 final String packageName = pkg.packageName; 14972 14973 synchronized (mPackages) { 14974 // If this is a new install and we see that we've already run verification for this 14975 // package, we have nothing to do: it means the state was restored from backup. 14976 if (!replacing) { 14977 IntentFilterVerificationInfo ivi = 14978 mSettings.getIntentFilterVerificationLPr(packageName); 14979 if (ivi != null) { 14980 if (DEBUG_DOMAIN_VERIFICATION) { 14981 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14982 + ivi.getStatusString()); 14983 } 14984 return; 14985 } 14986 } 14987 14988 // If any filters need to be verified, then all need to be. 14989 boolean needToVerify = false; 14990 for (PackageParser.Activity a : pkg.activities) { 14991 for (ActivityIntentInfo filter : a.intents) { 14992 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14993 if (DEBUG_DOMAIN_VERIFICATION) { 14994 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14995 } 14996 needToVerify = true; 14997 break; 14998 } 14999 } 15000 } 15001 15002 if (needToVerify) { 15003 final int verificationId = mIntentFilterVerificationToken++; 15004 for (PackageParser.Activity a : pkg.activities) { 15005 for (ActivityIntentInfo filter : a.intents) { 15006 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15007 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15008 "Verification needed for IntentFilter:" + filter.toString()); 15009 mIntentFilterVerifier.addOneIntentFilterVerification( 15010 verifierUid, userId, verificationId, filter, packageName); 15011 count++; 15012 } 15013 } 15014 } 15015 } 15016 } 15017 15018 if (count > 0) { 15019 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15020 + " IntentFilter verification" + (count > 1 ? "s" : "") 15021 + " for userId:" + userId); 15022 mIntentFilterVerifier.startVerifications(userId); 15023 } else { 15024 if (DEBUG_DOMAIN_VERIFICATION) { 15025 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15026 } 15027 } 15028 } 15029 15030 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15031 final ComponentName cn = filter.activity.getComponentName(); 15032 final String packageName = cn.getPackageName(); 15033 15034 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15035 packageName); 15036 if (ivi == null) { 15037 return true; 15038 } 15039 int status = ivi.getStatus(); 15040 switch (status) { 15041 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15042 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15043 return true; 15044 15045 default: 15046 // Nothing to do 15047 return false; 15048 } 15049 } 15050 15051 private static boolean isMultiArch(ApplicationInfo info) { 15052 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15053 } 15054 15055 private static boolean isExternal(PackageParser.Package pkg) { 15056 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15057 } 15058 15059 private static boolean isExternal(PackageSetting ps) { 15060 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15061 } 15062 15063 private static boolean isEphemeral(PackageParser.Package pkg) { 15064 return pkg.applicationInfo.isEphemeralApp(); 15065 } 15066 15067 private static boolean isEphemeral(PackageSetting ps) { 15068 return ps.pkg != null && isEphemeral(ps.pkg); 15069 } 15070 15071 private static boolean isSystemApp(PackageParser.Package pkg) { 15072 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15073 } 15074 15075 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15076 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15077 } 15078 15079 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15080 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15081 } 15082 15083 private static boolean isSystemApp(PackageSetting ps) { 15084 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15085 } 15086 15087 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15088 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15089 } 15090 15091 private int packageFlagsToInstallFlags(PackageSetting ps) { 15092 int installFlags = 0; 15093 if (isEphemeral(ps)) { 15094 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15095 } 15096 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15097 // This existing package was an external ASEC install when we have 15098 // the external flag without a UUID 15099 installFlags |= PackageManager.INSTALL_EXTERNAL; 15100 } 15101 if (ps.isForwardLocked()) { 15102 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15103 } 15104 return installFlags; 15105 } 15106 15107 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15108 if (isExternal(pkg)) { 15109 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15110 return StorageManager.UUID_PRIMARY_PHYSICAL; 15111 } else { 15112 return pkg.volumeUuid; 15113 } 15114 } else { 15115 return StorageManager.UUID_PRIVATE_INTERNAL; 15116 } 15117 } 15118 15119 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15120 if (isExternal(pkg)) { 15121 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15122 return mSettings.getExternalVersion(); 15123 } else { 15124 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15125 } 15126 } else { 15127 return mSettings.getInternalVersion(); 15128 } 15129 } 15130 15131 private void deleteTempPackageFiles() { 15132 final FilenameFilter filter = new FilenameFilter() { 15133 public boolean accept(File dir, String name) { 15134 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15135 } 15136 }; 15137 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15138 file.delete(); 15139 } 15140 } 15141 15142 @Override 15143 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15144 int flags) { 15145 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15146 flags); 15147 } 15148 15149 @Override 15150 public void deletePackage(final String packageName, 15151 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15152 mContext.enforceCallingOrSelfPermission( 15153 android.Manifest.permission.DELETE_PACKAGES, null); 15154 Preconditions.checkNotNull(packageName); 15155 Preconditions.checkNotNull(observer); 15156 final int uid = Binder.getCallingUid(); 15157 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15158 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15159 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15160 mContext.enforceCallingOrSelfPermission( 15161 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15162 "deletePackage for user " + userId); 15163 } 15164 15165 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15166 try { 15167 observer.onPackageDeleted(packageName, 15168 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15169 } catch (RemoteException re) { 15170 } 15171 return; 15172 } 15173 15174 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15175 try { 15176 observer.onPackageDeleted(packageName, 15177 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15178 } catch (RemoteException re) { 15179 } 15180 return; 15181 } 15182 15183 if (DEBUG_REMOVE) { 15184 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15185 + " deleteAllUsers: " + deleteAllUsers ); 15186 } 15187 // Queue up an async operation since the package deletion may take a little while. 15188 mHandler.post(new Runnable() { 15189 public void run() { 15190 mHandler.removeCallbacks(this); 15191 int returnCode; 15192 if (!deleteAllUsers) { 15193 returnCode = deletePackageX(packageName, userId, deleteFlags); 15194 } else { 15195 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15196 // If nobody is blocking uninstall, proceed with delete for all users 15197 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15198 returnCode = deletePackageX(packageName, userId, deleteFlags); 15199 } else { 15200 // Otherwise uninstall individually for users with blockUninstalls=false 15201 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15202 for (int userId : users) { 15203 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15204 returnCode = deletePackageX(packageName, userId, userFlags); 15205 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15206 Slog.w(TAG, "Package delete failed for user " + userId 15207 + ", returnCode " + returnCode); 15208 } 15209 } 15210 } 15211 // The app has only been marked uninstalled for certain users. 15212 // We still need to report that delete was blocked 15213 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15214 } 15215 } 15216 try { 15217 observer.onPackageDeleted(packageName, returnCode, null); 15218 } catch (RemoteException e) { 15219 Log.i(TAG, "Observer no longer exists."); 15220 } //end catch 15221 } //end run 15222 }); 15223 } 15224 15225 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15226 int[] result = EMPTY_INT_ARRAY; 15227 for (int userId : userIds) { 15228 if (getBlockUninstallForUser(packageName, userId)) { 15229 result = ArrayUtils.appendInt(result, userId); 15230 } 15231 } 15232 return result; 15233 } 15234 15235 @Override 15236 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15237 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15238 } 15239 15240 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15241 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15242 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15243 try { 15244 if (dpm != null) { 15245 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15246 /* callingUserOnly =*/ false); 15247 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15248 : deviceOwnerComponentName.getPackageName(); 15249 // Does the package contains the device owner? 15250 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15251 // this check is probably not needed, since DO should be registered as a device 15252 // admin on some user too. (Original bug for this: b/17657954) 15253 if (packageName.equals(deviceOwnerPackageName)) { 15254 return true; 15255 } 15256 // Does it contain a device admin for any user? 15257 int[] users; 15258 if (userId == UserHandle.USER_ALL) { 15259 users = sUserManager.getUserIds(); 15260 } else { 15261 users = new int[]{userId}; 15262 } 15263 for (int i = 0; i < users.length; ++i) { 15264 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15265 return true; 15266 } 15267 } 15268 } 15269 } catch (RemoteException e) { 15270 } 15271 return false; 15272 } 15273 15274 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15275 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15276 } 15277 15278 /** 15279 * This method is an internal method that could be get invoked either 15280 * to delete an installed package or to clean up a failed installation. 15281 * After deleting an installed package, a broadcast is sent to notify any 15282 * listeners that the package has been removed. For cleaning up a failed 15283 * installation, the broadcast is not necessary since the package's 15284 * installation wouldn't have sent the initial broadcast either 15285 * The key steps in deleting a package are 15286 * deleting the package information in internal structures like mPackages, 15287 * deleting the packages base directories through installd 15288 * updating mSettings to reflect current status 15289 * persisting settings for later use 15290 * sending a broadcast if necessary 15291 */ 15292 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15293 final PackageRemovedInfo info = new PackageRemovedInfo(); 15294 final boolean res; 15295 15296 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15297 ? UserHandle.ALL : new UserHandle(userId); 15298 15299 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15300 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15301 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15302 } 15303 15304 PackageSetting uninstalledPs = null; 15305 15306 // for the uninstall-updates case and restricted profiles, remember the per- 15307 // user handle installed state 15308 int[] allUsers; 15309 synchronized (mPackages) { 15310 uninstalledPs = mSettings.mPackages.get(packageName); 15311 if (uninstalledPs == null) { 15312 Slog.w(TAG, "Not removing non-existent package " + packageName); 15313 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15314 } 15315 allUsers = sUserManager.getUserIds(); 15316 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15317 } 15318 15319 synchronized (mInstallLock) { 15320 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15321 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15322 "deletePackageX")) { 15323 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15324 deleteFlags | REMOVE_CHATTY, info, true, null); 15325 } 15326 synchronized (mPackages) { 15327 if (res) { 15328 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15329 } 15330 } 15331 } 15332 15333 if (res) { 15334 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15335 info.sendPackageRemovedBroadcasts(killApp); 15336 info.sendSystemPackageUpdatedBroadcasts(); 15337 info.sendSystemPackageAppearedBroadcasts(); 15338 } 15339 // Force a gc here. 15340 Runtime.getRuntime().gc(); 15341 // Delete the resources here after sending the broadcast to let 15342 // other processes clean up before deleting resources. 15343 if (info.args != null) { 15344 synchronized (mInstallLock) { 15345 info.args.doPostDeleteLI(true); 15346 } 15347 } 15348 15349 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15350 } 15351 15352 class PackageRemovedInfo { 15353 String removedPackage; 15354 int uid = -1; 15355 int removedAppId = -1; 15356 int[] origUsers; 15357 int[] removedUsers = null; 15358 boolean isRemovedPackageSystemUpdate = false; 15359 boolean isUpdate; 15360 boolean dataRemoved; 15361 boolean removedForAllUsers; 15362 // Clean up resources deleted packages. 15363 InstallArgs args = null; 15364 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15365 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15366 15367 void sendPackageRemovedBroadcasts(boolean killApp) { 15368 sendPackageRemovedBroadcastInternal(killApp); 15369 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15370 for (int i = 0; i < childCount; i++) { 15371 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15372 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15373 } 15374 } 15375 15376 void sendSystemPackageUpdatedBroadcasts() { 15377 if (isRemovedPackageSystemUpdate) { 15378 sendSystemPackageUpdatedBroadcastsInternal(); 15379 final int childCount = (removedChildPackages != null) 15380 ? removedChildPackages.size() : 0; 15381 for (int i = 0; i < childCount; i++) { 15382 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15383 if (childInfo.isRemovedPackageSystemUpdate) { 15384 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15385 } 15386 } 15387 } 15388 } 15389 15390 void sendSystemPackageAppearedBroadcasts() { 15391 final int packageCount = (appearedChildPackages != null) 15392 ? appearedChildPackages.size() : 0; 15393 for (int i = 0; i < packageCount; i++) { 15394 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15395 for (int userId : installedInfo.newUsers) { 15396 sendPackageAddedForUser(installedInfo.name, true, 15397 UserHandle.getAppId(installedInfo.uid), userId); 15398 } 15399 } 15400 } 15401 15402 private void sendSystemPackageUpdatedBroadcastsInternal() { 15403 Bundle extras = new Bundle(2); 15404 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15405 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15406 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15407 extras, 0, null, null, null); 15408 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15409 extras, 0, null, null, null); 15410 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15411 null, 0, removedPackage, null, null); 15412 } 15413 15414 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15415 Bundle extras = new Bundle(2); 15416 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15417 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15418 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15419 if (isUpdate || isRemovedPackageSystemUpdate) { 15420 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15421 } 15422 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15423 if (removedPackage != null) { 15424 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15425 extras, 0, null, null, removedUsers); 15426 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15427 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15428 removedPackage, extras, 0, null, null, removedUsers); 15429 } 15430 } 15431 if (removedAppId >= 0) { 15432 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15433 removedUsers); 15434 } 15435 } 15436 } 15437 15438 /* 15439 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15440 * flag is not set, the data directory is removed as well. 15441 * make sure this flag is set for partially installed apps. If not its meaningless to 15442 * delete a partially installed application. 15443 */ 15444 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15445 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15446 String packageName = ps.name; 15447 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15448 // Retrieve object to delete permissions for shared user later on 15449 final PackageParser.Package deletedPkg; 15450 final PackageSetting deletedPs; 15451 // reader 15452 synchronized (mPackages) { 15453 deletedPkg = mPackages.get(packageName); 15454 deletedPs = mSettings.mPackages.get(packageName); 15455 if (outInfo != null) { 15456 outInfo.removedPackage = packageName; 15457 outInfo.removedUsers = deletedPs != null 15458 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15459 : null; 15460 } 15461 } 15462 15463 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15464 15465 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15466 final PackageParser.Package resolvedPkg; 15467 if (deletedPkg != null) { 15468 resolvedPkg = deletedPkg; 15469 } else { 15470 // We don't have a parsed package when it lives on an ejected 15471 // adopted storage device, so fake something together 15472 resolvedPkg = new PackageParser.Package(ps.name); 15473 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15474 } 15475 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15476 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15477 destroyAppProfilesLIF(resolvedPkg); 15478 if (outInfo != null) { 15479 outInfo.dataRemoved = true; 15480 } 15481 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15482 } 15483 15484 // writer 15485 synchronized (mPackages) { 15486 if (deletedPs != null) { 15487 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15488 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15489 clearDefaultBrowserIfNeeded(packageName); 15490 if (outInfo != null) { 15491 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15492 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15493 } 15494 updatePermissionsLPw(deletedPs.name, null, 0); 15495 if (deletedPs.sharedUser != null) { 15496 // Remove permissions associated with package. Since runtime 15497 // permissions are per user we have to kill the removed package 15498 // or packages running under the shared user of the removed 15499 // package if revoking the permissions requested only by the removed 15500 // package is successful and this causes a change in gids. 15501 for (int userId : UserManagerService.getInstance().getUserIds()) { 15502 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15503 userId); 15504 if (userIdToKill == UserHandle.USER_ALL 15505 || userIdToKill >= UserHandle.USER_SYSTEM) { 15506 // If gids changed for this user, kill all affected packages. 15507 mHandler.post(new Runnable() { 15508 @Override 15509 public void run() { 15510 // This has to happen with no lock held. 15511 killApplication(deletedPs.name, deletedPs.appId, 15512 KILL_APP_REASON_GIDS_CHANGED); 15513 } 15514 }); 15515 break; 15516 } 15517 } 15518 } 15519 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15520 } 15521 // make sure to preserve per-user disabled state if this removal was just 15522 // a downgrade of a system app to the factory package 15523 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15524 if (DEBUG_REMOVE) { 15525 Slog.d(TAG, "Propagating install state across downgrade"); 15526 } 15527 for (int userId : allUserHandles) { 15528 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15529 if (DEBUG_REMOVE) { 15530 Slog.d(TAG, " user " + userId + " => " + installed); 15531 } 15532 ps.setInstalled(installed, userId); 15533 } 15534 } 15535 } 15536 // can downgrade to reader 15537 if (writeSettings) { 15538 // Save settings now 15539 mSettings.writeLPr(); 15540 } 15541 } 15542 if (outInfo != null) { 15543 // A user ID was deleted here. Go through all users and remove it 15544 // from KeyStore. 15545 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15546 } 15547 } 15548 15549 static boolean locationIsPrivileged(File path) { 15550 try { 15551 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15552 .getCanonicalPath(); 15553 return path.getCanonicalPath().startsWith(privilegedAppDir); 15554 } catch (IOException e) { 15555 Slog.e(TAG, "Unable to access code path " + path); 15556 } 15557 return false; 15558 } 15559 15560 /* 15561 * Tries to delete system package. 15562 */ 15563 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15564 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15565 boolean writeSettings) { 15566 if (deletedPs.parentPackageName != null) { 15567 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15568 return false; 15569 } 15570 15571 final boolean applyUserRestrictions 15572 = (allUserHandles != null) && (outInfo.origUsers != null); 15573 final PackageSetting disabledPs; 15574 // Confirm if the system package has been updated 15575 // An updated system app can be deleted. This will also have to restore 15576 // the system pkg from system partition 15577 // reader 15578 synchronized (mPackages) { 15579 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15580 } 15581 15582 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15583 + " disabledPs=" + disabledPs); 15584 15585 if (disabledPs == null) { 15586 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15587 return false; 15588 } else if (DEBUG_REMOVE) { 15589 Slog.d(TAG, "Deleting system pkg from data partition"); 15590 } 15591 15592 if (DEBUG_REMOVE) { 15593 if (applyUserRestrictions) { 15594 Slog.d(TAG, "Remembering install states:"); 15595 for (int userId : allUserHandles) { 15596 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15597 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15598 } 15599 } 15600 } 15601 15602 // Delete the updated package 15603 outInfo.isRemovedPackageSystemUpdate = true; 15604 if (outInfo.removedChildPackages != null) { 15605 final int childCount = (deletedPs.childPackageNames != null) 15606 ? deletedPs.childPackageNames.size() : 0; 15607 for (int i = 0; i < childCount; i++) { 15608 String childPackageName = deletedPs.childPackageNames.get(i); 15609 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15610 .contains(childPackageName)) { 15611 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15612 childPackageName); 15613 if (childInfo != null) { 15614 childInfo.isRemovedPackageSystemUpdate = true; 15615 } 15616 } 15617 } 15618 } 15619 15620 if (disabledPs.versionCode < deletedPs.versionCode) { 15621 // Delete data for downgrades 15622 flags &= ~PackageManager.DELETE_KEEP_DATA; 15623 } else { 15624 // Preserve data by setting flag 15625 flags |= PackageManager.DELETE_KEEP_DATA; 15626 } 15627 15628 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15629 outInfo, writeSettings, disabledPs.pkg); 15630 if (!ret) { 15631 return false; 15632 } 15633 15634 // writer 15635 synchronized (mPackages) { 15636 // Reinstate the old system package 15637 enableSystemPackageLPw(disabledPs.pkg); 15638 // Remove any native libraries from the upgraded package. 15639 removeNativeBinariesLI(deletedPs); 15640 } 15641 15642 // Install the system package 15643 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15644 int parseFlags = mDefParseFlags 15645 | PackageParser.PARSE_MUST_BE_APK 15646 | PackageParser.PARSE_IS_SYSTEM 15647 | PackageParser.PARSE_IS_SYSTEM_DIR; 15648 if (locationIsPrivileged(disabledPs.codePath)) { 15649 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15650 } 15651 15652 final PackageParser.Package newPkg; 15653 try { 15654 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15655 } catch (PackageManagerException e) { 15656 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15657 + e.getMessage()); 15658 return false; 15659 } 15660 15661 prepareAppDataAfterInstallLIF(newPkg); 15662 15663 // writer 15664 synchronized (mPackages) { 15665 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15666 15667 // Propagate the permissions state as we do not want to drop on the floor 15668 // runtime permissions. The update permissions method below will take 15669 // care of removing obsolete permissions and grant install permissions. 15670 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15671 updatePermissionsLPw(newPkg.packageName, newPkg, 15672 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15673 15674 if (applyUserRestrictions) { 15675 if (DEBUG_REMOVE) { 15676 Slog.d(TAG, "Propagating install state across reinstall"); 15677 } 15678 for (int userId : allUserHandles) { 15679 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15680 if (DEBUG_REMOVE) { 15681 Slog.d(TAG, " user " + userId + " => " + installed); 15682 } 15683 ps.setInstalled(installed, userId); 15684 15685 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15686 } 15687 // Regardless of writeSettings we need to ensure that this restriction 15688 // state propagation is persisted 15689 mSettings.writeAllUsersPackageRestrictionsLPr(); 15690 } 15691 // can downgrade to reader here 15692 if (writeSettings) { 15693 mSettings.writeLPr(); 15694 } 15695 } 15696 return true; 15697 } 15698 15699 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15700 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15701 PackageRemovedInfo outInfo, boolean writeSettings, 15702 PackageParser.Package replacingPackage) { 15703 synchronized (mPackages) { 15704 if (outInfo != null) { 15705 outInfo.uid = ps.appId; 15706 } 15707 15708 if (outInfo != null && outInfo.removedChildPackages != null) { 15709 final int childCount = (ps.childPackageNames != null) 15710 ? ps.childPackageNames.size() : 0; 15711 for (int i = 0; i < childCount; i++) { 15712 String childPackageName = ps.childPackageNames.get(i); 15713 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15714 if (childPs == null) { 15715 return false; 15716 } 15717 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15718 childPackageName); 15719 if (childInfo != null) { 15720 childInfo.uid = childPs.appId; 15721 } 15722 } 15723 } 15724 } 15725 15726 // Delete package data from internal structures and also remove data if flag is set 15727 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15728 15729 // Delete the child packages data 15730 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15731 for (int i = 0; i < childCount; i++) { 15732 PackageSetting childPs; 15733 synchronized (mPackages) { 15734 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15735 } 15736 if (childPs != null) { 15737 PackageRemovedInfo childOutInfo = (outInfo != null 15738 && outInfo.removedChildPackages != null) 15739 ? outInfo.removedChildPackages.get(childPs.name) : null; 15740 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15741 && (replacingPackage != null 15742 && !replacingPackage.hasChildPackage(childPs.name)) 15743 ? flags & ~DELETE_KEEP_DATA : flags; 15744 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15745 deleteFlags, writeSettings); 15746 } 15747 } 15748 15749 // Delete application code and resources only for parent packages 15750 if (ps.parentPackageName == null) { 15751 if (deleteCodeAndResources && (outInfo != null)) { 15752 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15753 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15754 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15755 } 15756 } 15757 15758 return true; 15759 } 15760 15761 @Override 15762 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15763 int userId) { 15764 mContext.enforceCallingOrSelfPermission( 15765 android.Manifest.permission.DELETE_PACKAGES, null); 15766 synchronized (mPackages) { 15767 PackageSetting ps = mSettings.mPackages.get(packageName); 15768 if (ps == null) { 15769 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15770 return false; 15771 } 15772 if (!ps.getInstalled(userId)) { 15773 // Can't block uninstall for an app that is not installed or enabled. 15774 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15775 return false; 15776 } 15777 ps.setBlockUninstall(blockUninstall, userId); 15778 mSettings.writePackageRestrictionsLPr(userId); 15779 } 15780 return true; 15781 } 15782 15783 @Override 15784 public boolean getBlockUninstallForUser(String packageName, int userId) { 15785 synchronized (mPackages) { 15786 PackageSetting ps = mSettings.mPackages.get(packageName); 15787 if (ps == null) { 15788 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15789 return false; 15790 } 15791 return ps.getBlockUninstall(userId); 15792 } 15793 } 15794 15795 @Override 15796 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15797 int callingUid = Binder.getCallingUid(); 15798 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15799 throw new SecurityException( 15800 "setRequiredForSystemUser can only be run by the system or root"); 15801 } 15802 synchronized (mPackages) { 15803 PackageSetting ps = mSettings.mPackages.get(packageName); 15804 if (ps == null) { 15805 Log.w(TAG, "Package doesn't exist: " + packageName); 15806 return false; 15807 } 15808 if (systemUserApp) { 15809 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15810 } else { 15811 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15812 } 15813 mSettings.writeLPr(); 15814 } 15815 return true; 15816 } 15817 15818 /* 15819 * This method handles package deletion in general 15820 */ 15821 private boolean deletePackageLIF(String packageName, UserHandle user, 15822 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15823 PackageRemovedInfo outInfo, boolean writeSettings, 15824 PackageParser.Package replacingPackage) { 15825 if (packageName == null) { 15826 Slog.w(TAG, "Attempt to delete null packageName."); 15827 return false; 15828 } 15829 15830 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15831 15832 PackageSetting ps; 15833 15834 synchronized (mPackages) { 15835 ps = mSettings.mPackages.get(packageName); 15836 if (ps == null) { 15837 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15838 return false; 15839 } 15840 15841 if (ps.parentPackageName != null && (!isSystemApp(ps) 15842 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15843 if (DEBUG_REMOVE) { 15844 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15845 + ((user == null) ? UserHandle.USER_ALL : user)); 15846 } 15847 final int removedUserId = (user != null) ? user.getIdentifier() 15848 : UserHandle.USER_ALL; 15849 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15850 return false; 15851 } 15852 markPackageUninstalledForUserLPw(ps, user); 15853 scheduleWritePackageRestrictionsLocked(user); 15854 return true; 15855 } 15856 } 15857 15858 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15859 && user.getIdentifier() != UserHandle.USER_ALL)) { 15860 // The caller is asking that the package only be deleted for a single 15861 // user. To do this, we just mark its uninstalled state and delete 15862 // its data. If this is a system app, we only allow this to happen if 15863 // they have set the special DELETE_SYSTEM_APP which requests different 15864 // semantics than normal for uninstalling system apps. 15865 markPackageUninstalledForUserLPw(ps, user); 15866 15867 if (!isSystemApp(ps)) { 15868 // Do not uninstall the APK if an app should be cached 15869 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15870 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15871 // Other user still have this package installed, so all 15872 // we need to do is clear this user's data and save that 15873 // it is uninstalled. 15874 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15875 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15876 return false; 15877 } 15878 scheduleWritePackageRestrictionsLocked(user); 15879 return true; 15880 } else { 15881 // We need to set it back to 'installed' so the uninstall 15882 // broadcasts will be sent correctly. 15883 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15884 ps.setInstalled(true, user.getIdentifier()); 15885 } 15886 } else { 15887 // This is a system app, so we assume that the 15888 // other users still have this package installed, so all 15889 // we need to do is clear this user's data and save that 15890 // it is uninstalled. 15891 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15892 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15893 return false; 15894 } 15895 scheduleWritePackageRestrictionsLocked(user); 15896 return true; 15897 } 15898 } 15899 15900 // If we are deleting a composite package for all users, keep track 15901 // of result for each child. 15902 if (ps.childPackageNames != null && outInfo != null) { 15903 synchronized (mPackages) { 15904 final int childCount = ps.childPackageNames.size(); 15905 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15906 for (int i = 0; i < childCount; i++) { 15907 String childPackageName = ps.childPackageNames.get(i); 15908 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15909 childInfo.removedPackage = childPackageName; 15910 outInfo.removedChildPackages.put(childPackageName, childInfo); 15911 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15912 if (childPs != null) { 15913 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15914 } 15915 } 15916 } 15917 } 15918 15919 boolean ret = false; 15920 if (isSystemApp(ps)) { 15921 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15922 // When an updated system application is deleted we delete the existing resources 15923 // as well and fall back to existing code in system partition 15924 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15925 } else { 15926 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15927 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15928 outInfo, writeSettings, replacingPackage); 15929 } 15930 15931 // Take a note whether we deleted the package for all users 15932 if (outInfo != null) { 15933 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15934 if (outInfo.removedChildPackages != null) { 15935 synchronized (mPackages) { 15936 final int childCount = outInfo.removedChildPackages.size(); 15937 for (int i = 0; i < childCount; i++) { 15938 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15939 if (childInfo != null) { 15940 childInfo.removedForAllUsers = mPackages.get( 15941 childInfo.removedPackage) == null; 15942 } 15943 } 15944 } 15945 } 15946 // If we uninstalled an update to a system app there may be some 15947 // child packages that appeared as they are declared in the system 15948 // app but were not declared in the update. 15949 if (isSystemApp(ps)) { 15950 synchronized (mPackages) { 15951 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15952 final int childCount = (updatedPs.childPackageNames != null) 15953 ? updatedPs.childPackageNames.size() : 0; 15954 for (int i = 0; i < childCount; i++) { 15955 String childPackageName = updatedPs.childPackageNames.get(i); 15956 if (outInfo.removedChildPackages == null 15957 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15958 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15959 if (childPs == null) { 15960 continue; 15961 } 15962 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15963 installRes.name = childPackageName; 15964 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15965 installRes.pkg = mPackages.get(childPackageName); 15966 installRes.uid = childPs.pkg.applicationInfo.uid; 15967 if (outInfo.appearedChildPackages == null) { 15968 outInfo.appearedChildPackages = new ArrayMap<>(); 15969 } 15970 outInfo.appearedChildPackages.put(childPackageName, installRes); 15971 } 15972 } 15973 } 15974 } 15975 } 15976 15977 return ret; 15978 } 15979 15980 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15981 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15982 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15983 for (int nextUserId : userIds) { 15984 if (DEBUG_REMOVE) { 15985 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15986 } 15987 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15988 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15989 false /*hidden*/, false /*suspended*/, null, null, null, 15990 false /*blockUninstall*/, 15991 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15992 } 15993 } 15994 15995 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15996 PackageRemovedInfo outInfo) { 15997 final PackageParser.Package pkg; 15998 synchronized (mPackages) { 15999 pkg = mPackages.get(ps.name); 16000 } 16001 16002 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16003 : new int[] {userId}; 16004 for (int nextUserId : userIds) { 16005 if (DEBUG_REMOVE) { 16006 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16007 + nextUserId); 16008 } 16009 16010 destroyAppDataLIF(pkg, userId, 16011 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16012 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16013 schedulePackageCleaning(ps.name, nextUserId, false); 16014 synchronized (mPackages) { 16015 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16016 scheduleWritePackageRestrictionsLocked(nextUserId); 16017 } 16018 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16019 } 16020 } 16021 16022 if (outInfo != null) { 16023 outInfo.removedPackage = ps.name; 16024 outInfo.removedAppId = ps.appId; 16025 outInfo.removedUsers = userIds; 16026 } 16027 16028 return true; 16029 } 16030 16031 private final class ClearStorageConnection implements ServiceConnection { 16032 IMediaContainerService mContainerService; 16033 16034 @Override 16035 public void onServiceConnected(ComponentName name, IBinder service) { 16036 synchronized (this) { 16037 mContainerService = IMediaContainerService.Stub.asInterface(service); 16038 notifyAll(); 16039 } 16040 } 16041 16042 @Override 16043 public void onServiceDisconnected(ComponentName name) { 16044 } 16045 } 16046 16047 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16048 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16049 16050 final boolean mounted; 16051 if (Environment.isExternalStorageEmulated()) { 16052 mounted = true; 16053 } else { 16054 final String status = Environment.getExternalStorageState(); 16055 16056 mounted = status.equals(Environment.MEDIA_MOUNTED) 16057 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16058 } 16059 16060 if (!mounted) { 16061 return; 16062 } 16063 16064 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16065 int[] users; 16066 if (userId == UserHandle.USER_ALL) { 16067 users = sUserManager.getUserIds(); 16068 } else { 16069 users = new int[] { userId }; 16070 } 16071 final ClearStorageConnection conn = new ClearStorageConnection(); 16072 if (mContext.bindServiceAsUser( 16073 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16074 try { 16075 for (int curUser : users) { 16076 long timeout = SystemClock.uptimeMillis() + 5000; 16077 synchronized (conn) { 16078 long now = SystemClock.uptimeMillis(); 16079 while (conn.mContainerService == null && now < timeout) { 16080 try { 16081 conn.wait(timeout - now); 16082 } catch (InterruptedException e) { 16083 } 16084 } 16085 } 16086 if (conn.mContainerService == null) { 16087 return; 16088 } 16089 16090 final UserEnvironment userEnv = new UserEnvironment(curUser); 16091 clearDirectory(conn.mContainerService, 16092 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16093 if (allData) { 16094 clearDirectory(conn.mContainerService, 16095 userEnv.buildExternalStorageAppDataDirs(packageName)); 16096 clearDirectory(conn.mContainerService, 16097 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16098 } 16099 } 16100 } finally { 16101 mContext.unbindService(conn); 16102 } 16103 } 16104 } 16105 16106 @Override 16107 public void clearApplicationProfileData(String packageName) { 16108 enforceSystemOrRoot("Only the system can clear all profile data"); 16109 16110 final PackageParser.Package pkg; 16111 synchronized (mPackages) { 16112 pkg = mPackages.get(packageName); 16113 } 16114 16115 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16116 synchronized (mInstallLock) { 16117 clearAppProfilesLIF(pkg); 16118 } 16119 } 16120 } 16121 16122 @Override 16123 public void clearApplicationUserData(final String packageName, 16124 final IPackageDataObserver observer, final int userId) { 16125 mContext.enforceCallingOrSelfPermission( 16126 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16127 16128 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16129 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16130 16131 final DevicePolicyManagerInternal dpmi = LocalServices 16132 .getService(DevicePolicyManagerInternal.class); 16133 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16134 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16135 } 16136 // Queue up an async operation since the package deletion may take a little while. 16137 mHandler.post(new Runnable() { 16138 public void run() { 16139 mHandler.removeCallbacks(this); 16140 final boolean succeeded; 16141 try (PackageFreezer freezer = freezePackage(packageName, 16142 "clearApplicationUserData")) { 16143 synchronized (mInstallLock) { 16144 succeeded = clearApplicationUserDataLIF(packageName, userId); 16145 } 16146 clearExternalStorageDataSync(packageName, userId, true); 16147 } 16148 if (succeeded) { 16149 // invoke DeviceStorageMonitor's update method to clear any notifications 16150 DeviceStorageMonitorInternal dsm = LocalServices 16151 .getService(DeviceStorageMonitorInternal.class); 16152 if (dsm != null) { 16153 dsm.checkMemory(); 16154 } 16155 } 16156 if(observer != null) { 16157 try { 16158 observer.onRemoveCompleted(packageName, succeeded); 16159 } catch (RemoteException e) { 16160 Log.i(TAG, "Observer no longer exists."); 16161 } 16162 } //end if observer 16163 } //end run 16164 }); 16165 } 16166 16167 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16168 if (packageName == null) { 16169 Slog.w(TAG, "Attempt to delete null packageName."); 16170 return false; 16171 } 16172 16173 // Try finding details about the requested package 16174 PackageParser.Package pkg; 16175 synchronized (mPackages) { 16176 pkg = mPackages.get(packageName); 16177 if (pkg == null) { 16178 final PackageSetting ps = mSettings.mPackages.get(packageName); 16179 if (ps != null) { 16180 pkg = ps.pkg; 16181 } 16182 } 16183 16184 if (pkg == null) { 16185 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16186 return false; 16187 } 16188 16189 PackageSetting ps = (PackageSetting) pkg.mExtras; 16190 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16191 } 16192 16193 clearAppDataLIF(pkg, userId, 16194 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16195 16196 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16197 removeKeystoreDataIfNeeded(userId, appId); 16198 16199 final UserManager um = mContext.getSystemService(UserManager.class); 16200 final int flags; 16201 if (um.isUserUnlockingOrUnlocked(userId)) { 16202 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16203 } else if (um.isUserRunning(userId)) { 16204 flags = StorageManager.FLAG_STORAGE_DE; 16205 } else { 16206 flags = 0; 16207 } 16208 prepareAppDataContentsLIF(pkg, userId, flags); 16209 16210 return true; 16211 } 16212 16213 /** 16214 * Reverts user permission state changes (permissions and flags) in 16215 * all packages for a given user. 16216 * 16217 * @param userId The device user for which to do a reset. 16218 */ 16219 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16220 final int packageCount = mPackages.size(); 16221 for (int i = 0; i < packageCount; i++) { 16222 PackageParser.Package pkg = mPackages.valueAt(i); 16223 PackageSetting ps = (PackageSetting) pkg.mExtras; 16224 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16225 } 16226 } 16227 16228 private void resetNetworkPolicies(int userId) { 16229 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16230 } 16231 16232 /** 16233 * Reverts user permission state changes (permissions and flags). 16234 * 16235 * @param ps The package for which to reset. 16236 * @param userId The device user for which to do a reset. 16237 */ 16238 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16239 final PackageSetting ps, final int userId) { 16240 if (ps.pkg == null) { 16241 return; 16242 } 16243 16244 // These are flags that can change base on user actions. 16245 final int userSettableMask = FLAG_PERMISSION_USER_SET 16246 | FLAG_PERMISSION_USER_FIXED 16247 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16248 | FLAG_PERMISSION_REVIEW_REQUIRED; 16249 16250 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16251 | FLAG_PERMISSION_POLICY_FIXED; 16252 16253 boolean writeInstallPermissions = false; 16254 boolean writeRuntimePermissions = false; 16255 16256 final int permissionCount = ps.pkg.requestedPermissions.size(); 16257 for (int i = 0; i < permissionCount; i++) { 16258 String permission = ps.pkg.requestedPermissions.get(i); 16259 16260 BasePermission bp = mSettings.mPermissions.get(permission); 16261 if (bp == null) { 16262 continue; 16263 } 16264 16265 // If shared user we just reset the state to which only this app contributed. 16266 if (ps.sharedUser != null) { 16267 boolean used = false; 16268 final int packageCount = ps.sharedUser.packages.size(); 16269 for (int j = 0; j < packageCount; j++) { 16270 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16271 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16272 && pkg.pkg.requestedPermissions.contains(permission)) { 16273 used = true; 16274 break; 16275 } 16276 } 16277 if (used) { 16278 continue; 16279 } 16280 } 16281 16282 PermissionsState permissionsState = ps.getPermissionsState(); 16283 16284 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16285 16286 // Always clear the user settable flags. 16287 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16288 bp.name) != null; 16289 // If permission review is enabled and this is a legacy app, mark the 16290 // permission as requiring a review as this is the initial state. 16291 int flags = 0; 16292 if (Build.PERMISSIONS_REVIEW_REQUIRED 16293 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16294 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16295 } 16296 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16297 if (hasInstallState) { 16298 writeInstallPermissions = true; 16299 } else { 16300 writeRuntimePermissions = true; 16301 } 16302 } 16303 16304 // Below is only runtime permission handling. 16305 if (!bp.isRuntime()) { 16306 continue; 16307 } 16308 16309 // Never clobber system or policy. 16310 if ((oldFlags & policyOrSystemFlags) != 0) { 16311 continue; 16312 } 16313 16314 // If this permission was granted by default, make sure it is. 16315 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16316 if (permissionsState.grantRuntimePermission(bp, userId) 16317 != PERMISSION_OPERATION_FAILURE) { 16318 writeRuntimePermissions = true; 16319 } 16320 // If permission review is enabled the permissions for a legacy apps 16321 // are represented as constantly granted runtime ones, so don't revoke. 16322 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16323 // Otherwise, reset the permission. 16324 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16325 switch (revokeResult) { 16326 case PERMISSION_OPERATION_SUCCESS: 16327 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16328 writeRuntimePermissions = true; 16329 final int appId = ps.appId; 16330 mHandler.post(new Runnable() { 16331 @Override 16332 public void run() { 16333 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16334 } 16335 }); 16336 } break; 16337 } 16338 } 16339 } 16340 16341 // Synchronously write as we are taking permissions away. 16342 if (writeRuntimePermissions) { 16343 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16344 } 16345 16346 // Synchronously write as we are taking permissions away. 16347 if (writeInstallPermissions) { 16348 mSettings.writeLPr(); 16349 } 16350 } 16351 16352 /** 16353 * Remove entries from the keystore daemon. Will only remove it if the 16354 * {@code appId} is valid. 16355 */ 16356 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16357 if (appId < 0) { 16358 return; 16359 } 16360 16361 final KeyStore keyStore = KeyStore.getInstance(); 16362 if (keyStore != null) { 16363 if (userId == UserHandle.USER_ALL) { 16364 for (final int individual : sUserManager.getUserIds()) { 16365 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16366 } 16367 } else { 16368 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16369 } 16370 } else { 16371 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16372 } 16373 } 16374 16375 @Override 16376 public void deleteApplicationCacheFiles(final String packageName, 16377 final IPackageDataObserver observer) { 16378 final int userId = UserHandle.getCallingUserId(); 16379 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16380 } 16381 16382 @Override 16383 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16384 final IPackageDataObserver observer) { 16385 mContext.enforceCallingOrSelfPermission( 16386 android.Manifest.permission.DELETE_CACHE_FILES, null); 16387 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16388 /* requireFullPermission= */ true, /* checkShell= */ false, 16389 "delete application cache files"); 16390 16391 final PackageParser.Package pkg; 16392 synchronized (mPackages) { 16393 pkg = mPackages.get(packageName); 16394 } 16395 16396 // Queue up an async operation since the package deletion may take a little while. 16397 mHandler.post(new Runnable() { 16398 public void run() { 16399 synchronized (mInstallLock) { 16400 final int flags = StorageManager.FLAG_STORAGE_DE 16401 | StorageManager.FLAG_STORAGE_CE; 16402 // We're only clearing cache files, so we don't care if the 16403 // app is unfrozen and still able to run 16404 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16405 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16406 } 16407 clearExternalStorageDataSync(packageName, userId, false); 16408 if (observer != null) { 16409 try { 16410 observer.onRemoveCompleted(packageName, true); 16411 } catch (RemoteException e) { 16412 Log.i(TAG, "Observer no longer exists."); 16413 } 16414 } 16415 } 16416 }); 16417 } 16418 16419 @Override 16420 public void getPackageSizeInfo(final String packageName, int userHandle, 16421 final IPackageStatsObserver observer) { 16422 mContext.enforceCallingOrSelfPermission( 16423 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16424 if (packageName == null) { 16425 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16426 } 16427 16428 PackageStats stats = new PackageStats(packageName, userHandle); 16429 16430 /* 16431 * Queue up an async operation since the package measurement may take a 16432 * little while. 16433 */ 16434 Message msg = mHandler.obtainMessage(INIT_COPY); 16435 msg.obj = new MeasureParams(stats, observer); 16436 mHandler.sendMessage(msg); 16437 } 16438 16439 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16440 final PackageSetting ps; 16441 synchronized (mPackages) { 16442 ps = mSettings.mPackages.get(packageName); 16443 if (ps == null) { 16444 Slog.w(TAG, "Failed to find settings for " + packageName); 16445 return false; 16446 } 16447 } 16448 try { 16449 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16450 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16451 ps.getCeDataInode(userId), ps.codePathString, stats); 16452 } catch (InstallerException e) { 16453 Slog.w(TAG, String.valueOf(e)); 16454 return false; 16455 } 16456 16457 // For now, ignore code size of packages on system partition 16458 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16459 stats.codeSize = 0; 16460 } 16461 16462 return true; 16463 } 16464 16465 private int getUidTargetSdkVersionLockedLPr(int uid) { 16466 Object obj = mSettings.getUserIdLPr(uid); 16467 if (obj instanceof SharedUserSetting) { 16468 final SharedUserSetting sus = (SharedUserSetting) obj; 16469 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16470 final Iterator<PackageSetting> it = sus.packages.iterator(); 16471 while (it.hasNext()) { 16472 final PackageSetting ps = it.next(); 16473 if (ps.pkg != null) { 16474 int v = ps.pkg.applicationInfo.targetSdkVersion; 16475 if (v < vers) vers = v; 16476 } 16477 } 16478 return vers; 16479 } else if (obj instanceof PackageSetting) { 16480 final PackageSetting ps = (PackageSetting) obj; 16481 if (ps.pkg != null) { 16482 return ps.pkg.applicationInfo.targetSdkVersion; 16483 } 16484 } 16485 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16486 } 16487 16488 @Override 16489 public void addPreferredActivity(IntentFilter filter, int match, 16490 ComponentName[] set, ComponentName activity, int userId) { 16491 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16492 "Adding preferred"); 16493 } 16494 16495 private void addPreferredActivityInternal(IntentFilter filter, int match, 16496 ComponentName[] set, ComponentName activity, boolean always, int userId, 16497 String opname) { 16498 // writer 16499 int callingUid = Binder.getCallingUid(); 16500 enforceCrossUserPermission(callingUid, userId, 16501 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16502 if (filter.countActions() == 0) { 16503 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16504 return; 16505 } 16506 synchronized (mPackages) { 16507 if (mContext.checkCallingOrSelfPermission( 16508 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16509 != PackageManager.PERMISSION_GRANTED) { 16510 if (getUidTargetSdkVersionLockedLPr(callingUid) 16511 < Build.VERSION_CODES.FROYO) { 16512 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16513 + callingUid); 16514 return; 16515 } 16516 mContext.enforceCallingOrSelfPermission( 16517 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16518 } 16519 16520 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16521 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16522 + userId + ":"); 16523 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16524 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16525 scheduleWritePackageRestrictionsLocked(userId); 16526 } 16527 } 16528 16529 @Override 16530 public void replacePreferredActivity(IntentFilter filter, int match, 16531 ComponentName[] set, ComponentName activity, int userId) { 16532 if (filter.countActions() != 1) { 16533 throw new IllegalArgumentException( 16534 "replacePreferredActivity expects filter to have only 1 action."); 16535 } 16536 if (filter.countDataAuthorities() != 0 16537 || filter.countDataPaths() != 0 16538 || filter.countDataSchemes() > 1 16539 || filter.countDataTypes() != 0) { 16540 throw new IllegalArgumentException( 16541 "replacePreferredActivity expects filter to have no data authorities, " + 16542 "paths, or types; and at most one scheme."); 16543 } 16544 16545 final int callingUid = Binder.getCallingUid(); 16546 enforceCrossUserPermission(callingUid, userId, 16547 true /* requireFullPermission */, false /* checkShell */, 16548 "replace preferred activity"); 16549 synchronized (mPackages) { 16550 if (mContext.checkCallingOrSelfPermission( 16551 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16552 != PackageManager.PERMISSION_GRANTED) { 16553 if (getUidTargetSdkVersionLockedLPr(callingUid) 16554 < Build.VERSION_CODES.FROYO) { 16555 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16556 + Binder.getCallingUid()); 16557 return; 16558 } 16559 mContext.enforceCallingOrSelfPermission( 16560 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16561 } 16562 16563 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16564 if (pir != null) { 16565 // Get all of the existing entries that exactly match this filter. 16566 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16567 if (existing != null && existing.size() == 1) { 16568 PreferredActivity cur = existing.get(0); 16569 if (DEBUG_PREFERRED) { 16570 Slog.i(TAG, "Checking replace of preferred:"); 16571 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16572 if (!cur.mPref.mAlways) { 16573 Slog.i(TAG, " -- CUR; not mAlways!"); 16574 } else { 16575 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16576 Slog.i(TAG, " -- CUR: mSet=" 16577 + Arrays.toString(cur.mPref.mSetComponents)); 16578 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16579 Slog.i(TAG, " -- NEW: mMatch=" 16580 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16581 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16582 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16583 } 16584 } 16585 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16586 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16587 && cur.mPref.sameSet(set)) { 16588 // Setting the preferred activity to what it happens to be already 16589 if (DEBUG_PREFERRED) { 16590 Slog.i(TAG, "Replacing with same preferred activity " 16591 + cur.mPref.mShortComponent + " for user " 16592 + userId + ":"); 16593 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16594 } 16595 return; 16596 } 16597 } 16598 16599 if (existing != null) { 16600 if (DEBUG_PREFERRED) { 16601 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16602 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16603 } 16604 for (int i = 0; i < existing.size(); i++) { 16605 PreferredActivity pa = existing.get(i); 16606 if (DEBUG_PREFERRED) { 16607 Slog.i(TAG, "Removing existing preferred activity " 16608 + pa.mPref.mComponent + ":"); 16609 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16610 } 16611 pir.removeFilter(pa); 16612 } 16613 } 16614 } 16615 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16616 "Replacing preferred"); 16617 } 16618 } 16619 16620 @Override 16621 public void clearPackagePreferredActivities(String packageName) { 16622 final int uid = Binder.getCallingUid(); 16623 // writer 16624 synchronized (mPackages) { 16625 PackageParser.Package pkg = mPackages.get(packageName); 16626 if (pkg == null || pkg.applicationInfo.uid != uid) { 16627 if (mContext.checkCallingOrSelfPermission( 16628 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16629 != PackageManager.PERMISSION_GRANTED) { 16630 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16631 < Build.VERSION_CODES.FROYO) { 16632 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16633 + Binder.getCallingUid()); 16634 return; 16635 } 16636 mContext.enforceCallingOrSelfPermission( 16637 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16638 } 16639 } 16640 16641 int user = UserHandle.getCallingUserId(); 16642 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16643 scheduleWritePackageRestrictionsLocked(user); 16644 } 16645 } 16646 } 16647 16648 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16649 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16650 ArrayList<PreferredActivity> removed = null; 16651 boolean changed = false; 16652 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16653 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16654 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16655 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16656 continue; 16657 } 16658 Iterator<PreferredActivity> it = pir.filterIterator(); 16659 while (it.hasNext()) { 16660 PreferredActivity pa = it.next(); 16661 // Mark entry for removal only if it matches the package name 16662 // and the entry is of type "always". 16663 if (packageName == null || 16664 (pa.mPref.mComponent.getPackageName().equals(packageName) 16665 && pa.mPref.mAlways)) { 16666 if (removed == null) { 16667 removed = new ArrayList<PreferredActivity>(); 16668 } 16669 removed.add(pa); 16670 } 16671 } 16672 if (removed != null) { 16673 for (int j=0; j<removed.size(); j++) { 16674 PreferredActivity pa = removed.get(j); 16675 pir.removeFilter(pa); 16676 } 16677 changed = true; 16678 } 16679 } 16680 return changed; 16681 } 16682 16683 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16684 private void clearIntentFilterVerificationsLPw(int userId) { 16685 final int packageCount = mPackages.size(); 16686 for (int i = 0; i < packageCount; i++) { 16687 PackageParser.Package pkg = mPackages.valueAt(i); 16688 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16689 } 16690 } 16691 16692 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16693 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16694 if (userId == UserHandle.USER_ALL) { 16695 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16696 sUserManager.getUserIds())) { 16697 for (int oneUserId : sUserManager.getUserIds()) { 16698 scheduleWritePackageRestrictionsLocked(oneUserId); 16699 } 16700 } 16701 } else { 16702 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16703 scheduleWritePackageRestrictionsLocked(userId); 16704 } 16705 } 16706 } 16707 16708 void clearDefaultBrowserIfNeeded(String packageName) { 16709 for (int oneUserId : sUserManager.getUserIds()) { 16710 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16711 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16712 if (packageName.equals(defaultBrowserPackageName)) { 16713 setDefaultBrowserPackageName(null, oneUserId); 16714 } 16715 } 16716 } 16717 16718 @Override 16719 public void resetApplicationPreferences(int userId) { 16720 mContext.enforceCallingOrSelfPermission( 16721 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16722 final long identity = Binder.clearCallingIdentity(); 16723 // writer 16724 try { 16725 synchronized (mPackages) { 16726 clearPackagePreferredActivitiesLPw(null, userId); 16727 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16728 // TODO: We have to reset the default SMS and Phone. This requires 16729 // significant refactoring to keep all default apps in the package 16730 // manager (cleaner but more work) or have the services provide 16731 // callbacks to the package manager to request a default app reset. 16732 applyFactoryDefaultBrowserLPw(userId); 16733 clearIntentFilterVerificationsLPw(userId); 16734 primeDomainVerificationsLPw(userId); 16735 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16736 scheduleWritePackageRestrictionsLocked(userId); 16737 } 16738 resetNetworkPolicies(userId); 16739 } finally { 16740 Binder.restoreCallingIdentity(identity); 16741 } 16742 } 16743 16744 @Override 16745 public int getPreferredActivities(List<IntentFilter> outFilters, 16746 List<ComponentName> outActivities, String packageName) { 16747 16748 int num = 0; 16749 final int userId = UserHandle.getCallingUserId(); 16750 // reader 16751 synchronized (mPackages) { 16752 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16753 if (pir != null) { 16754 final Iterator<PreferredActivity> it = pir.filterIterator(); 16755 while (it.hasNext()) { 16756 final PreferredActivity pa = it.next(); 16757 if (packageName == null 16758 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16759 && pa.mPref.mAlways)) { 16760 if (outFilters != null) { 16761 outFilters.add(new IntentFilter(pa)); 16762 } 16763 if (outActivities != null) { 16764 outActivities.add(pa.mPref.mComponent); 16765 } 16766 } 16767 } 16768 } 16769 } 16770 16771 return num; 16772 } 16773 16774 @Override 16775 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16776 int userId) { 16777 int callingUid = Binder.getCallingUid(); 16778 if (callingUid != Process.SYSTEM_UID) { 16779 throw new SecurityException( 16780 "addPersistentPreferredActivity can only be run by the system"); 16781 } 16782 if (filter.countActions() == 0) { 16783 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16784 return; 16785 } 16786 synchronized (mPackages) { 16787 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16788 ":"); 16789 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16790 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16791 new PersistentPreferredActivity(filter, activity)); 16792 scheduleWritePackageRestrictionsLocked(userId); 16793 } 16794 } 16795 16796 @Override 16797 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16798 int callingUid = Binder.getCallingUid(); 16799 if (callingUid != Process.SYSTEM_UID) { 16800 throw new SecurityException( 16801 "clearPackagePersistentPreferredActivities can only be run by the system"); 16802 } 16803 ArrayList<PersistentPreferredActivity> removed = null; 16804 boolean changed = false; 16805 synchronized (mPackages) { 16806 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16807 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16808 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16809 .valueAt(i); 16810 if (userId != thisUserId) { 16811 continue; 16812 } 16813 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16814 while (it.hasNext()) { 16815 PersistentPreferredActivity ppa = it.next(); 16816 // Mark entry for removal only if it matches the package name. 16817 if (ppa.mComponent.getPackageName().equals(packageName)) { 16818 if (removed == null) { 16819 removed = new ArrayList<PersistentPreferredActivity>(); 16820 } 16821 removed.add(ppa); 16822 } 16823 } 16824 if (removed != null) { 16825 for (int j=0; j<removed.size(); j++) { 16826 PersistentPreferredActivity ppa = removed.get(j); 16827 ppir.removeFilter(ppa); 16828 } 16829 changed = true; 16830 } 16831 } 16832 16833 if (changed) { 16834 scheduleWritePackageRestrictionsLocked(userId); 16835 } 16836 } 16837 } 16838 16839 /** 16840 * Common machinery for picking apart a restored XML blob and passing 16841 * it to a caller-supplied functor to be applied to the running system. 16842 */ 16843 private void restoreFromXml(XmlPullParser parser, int userId, 16844 String expectedStartTag, BlobXmlRestorer functor) 16845 throws IOException, XmlPullParserException { 16846 int type; 16847 while ((type = parser.next()) != XmlPullParser.START_TAG 16848 && type != XmlPullParser.END_DOCUMENT) { 16849 } 16850 if (type != XmlPullParser.START_TAG) { 16851 // oops didn't find a start tag?! 16852 if (DEBUG_BACKUP) { 16853 Slog.e(TAG, "Didn't find start tag during restore"); 16854 } 16855 return; 16856 } 16857Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16858 // this is supposed to be TAG_PREFERRED_BACKUP 16859 if (!expectedStartTag.equals(parser.getName())) { 16860 if (DEBUG_BACKUP) { 16861 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16862 } 16863 return; 16864 } 16865 16866 // skip interfering stuff, then we're aligned with the backing implementation 16867 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16868Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16869 functor.apply(parser, userId); 16870 } 16871 16872 private interface BlobXmlRestorer { 16873 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16874 } 16875 16876 /** 16877 * Non-Binder method, support for the backup/restore mechanism: write the 16878 * full set of preferred activities in its canonical XML format. Returns the 16879 * XML output as a byte array, or null if there is none. 16880 */ 16881 @Override 16882 public byte[] getPreferredActivityBackup(int userId) { 16883 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16884 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16885 } 16886 16887 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16888 try { 16889 final XmlSerializer serializer = new FastXmlSerializer(); 16890 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16891 serializer.startDocument(null, true); 16892 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16893 16894 synchronized (mPackages) { 16895 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16896 } 16897 16898 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16899 serializer.endDocument(); 16900 serializer.flush(); 16901 } catch (Exception e) { 16902 if (DEBUG_BACKUP) { 16903 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16904 } 16905 return null; 16906 } 16907 16908 return dataStream.toByteArray(); 16909 } 16910 16911 @Override 16912 public void restorePreferredActivities(byte[] backup, int userId) { 16913 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16914 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16915 } 16916 16917 try { 16918 final XmlPullParser parser = Xml.newPullParser(); 16919 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16920 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16921 new BlobXmlRestorer() { 16922 @Override 16923 public void apply(XmlPullParser parser, int userId) 16924 throws XmlPullParserException, IOException { 16925 synchronized (mPackages) { 16926 mSettings.readPreferredActivitiesLPw(parser, userId); 16927 } 16928 } 16929 } ); 16930 } catch (Exception e) { 16931 if (DEBUG_BACKUP) { 16932 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16933 } 16934 } 16935 } 16936 16937 /** 16938 * Non-Binder method, support for the backup/restore mechanism: write the 16939 * default browser (etc) settings in its canonical XML format. Returns the default 16940 * browser XML representation as a byte array, or null if there is none. 16941 */ 16942 @Override 16943 public byte[] getDefaultAppsBackup(int userId) { 16944 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16945 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16946 } 16947 16948 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16949 try { 16950 final XmlSerializer serializer = new FastXmlSerializer(); 16951 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16952 serializer.startDocument(null, true); 16953 serializer.startTag(null, TAG_DEFAULT_APPS); 16954 16955 synchronized (mPackages) { 16956 mSettings.writeDefaultAppsLPr(serializer, userId); 16957 } 16958 16959 serializer.endTag(null, TAG_DEFAULT_APPS); 16960 serializer.endDocument(); 16961 serializer.flush(); 16962 } catch (Exception e) { 16963 if (DEBUG_BACKUP) { 16964 Slog.e(TAG, "Unable to write default apps for backup", e); 16965 } 16966 return null; 16967 } 16968 16969 return dataStream.toByteArray(); 16970 } 16971 16972 @Override 16973 public void restoreDefaultApps(byte[] backup, int userId) { 16974 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16975 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16976 } 16977 16978 try { 16979 final XmlPullParser parser = Xml.newPullParser(); 16980 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16981 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16982 new BlobXmlRestorer() { 16983 @Override 16984 public void apply(XmlPullParser parser, int userId) 16985 throws XmlPullParserException, IOException { 16986 synchronized (mPackages) { 16987 mSettings.readDefaultAppsLPw(parser, userId); 16988 } 16989 } 16990 } ); 16991 } catch (Exception e) { 16992 if (DEBUG_BACKUP) { 16993 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16994 } 16995 } 16996 } 16997 16998 @Override 16999 public byte[] getIntentFilterVerificationBackup(int userId) { 17000 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17001 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17002 } 17003 17004 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17005 try { 17006 final XmlSerializer serializer = new FastXmlSerializer(); 17007 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17008 serializer.startDocument(null, true); 17009 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17010 17011 synchronized (mPackages) { 17012 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17013 } 17014 17015 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17016 serializer.endDocument(); 17017 serializer.flush(); 17018 } catch (Exception e) { 17019 if (DEBUG_BACKUP) { 17020 Slog.e(TAG, "Unable to write default apps for backup", e); 17021 } 17022 return null; 17023 } 17024 17025 return dataStream.toByteArray(); 17026 } 17027 17028 @Override 17029 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17030 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17031 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17032 } 17033 17034 try { 17035 final XmlPullParser parser = Xml.newPullParser(); 17036 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17037 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17038 new BlobXmlRestorer() { 17039 @Override 17040 public void apply(XmlPullParser parser, int userId) 17041 throws XmlPullParserException, IOException { 17042 synchronized (mPackages) { 17043 mSettings.readAllDomainVerificationsLPr(parser, userId); 17044 mSettings.writeLPr(); 17045 } 17046 } 17047 } ); 17048 } catch (Exception e) { 17049 if (DEBUG_BACKUP) { 17050 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17051 } 17052 } 17053 } 17054 17055 @Override 17056 public byte[] getPermissionGrantBackup(int userId) { 17057 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17058 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17059 } 17060 17061 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17062 try { 17063 final XmlSerializer serializer = new FastXmlSerializer(); 17064 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17065 serializer.startDocument(null, true); 17066 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17067 17068 synchronized (mPackages) { 17069 serializeRuntimePermissionGrantsLPr(serializer, userId); 17070 } 17071 17072 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17073 serializer.endDocument(); 17074 serializer.flush(); 17075 } catch (Exception e) { 17076 if (DEBUG_BACKUP) { 17077 Slog.e(TAG, "Unable to write default apps for backup", e); 17078 } 17079 return null; 17080 } 17081 17082 return dataStream.toByteArray(); 17083 } 17084 17085 @Override 17086 public void restorePermissionGrants(byte[] backup, int userId) { 17087 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17088 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17089 } 17090 17091 try { 17092 final XmlPullParser parser = Xml.newPullParser(); 17093 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17094 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17095 new BlobXmlRestorer() { 17096 @Override 17097 public void apply(XmlPullParser parser, int userId) 17098 throws XmlPullParserException, IOException { 17099 synchronized (mPackages) { 17100 processRestoredPermissionGrantsLPr(parser, userId); 17101 } 17102 } 17103 } ); 17104 } catch (Exception e) { 17105 if (DEBUG_BACKUP) { 17106 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17107 } 17108 } 17109 } 17110 17111 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17112 throws IOException { 17113 serializer.startTag(null, TAG_ALL_GRANTS); 17114 17115 final int N = mSettings.mPackages.size(); 17116 for (int i = 0; i < N; i++) { 17117 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17118 boolean pkgGrantsKnown = false; 17119 17120 PermissionsState packagePerms = ps.getPermissionsState(); 17121 17122 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17123 final int grantFlags = state.getFlags(); 17124 // only look at grants that are not system/policy fixed 17125 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17126 final boolean isGranted = state.isGranted(); 17127 // And only back up the user-twiddled state bits 17128 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17129 final String packageName = mSettings.mPackages.keyAt(i); 17130 if (!pkgGrantsKnown) { 17131 serializer.startTag(null, TAG_GRANT); 17132 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17133 pkgGrantsKnown = true; 17134 } 17135 17136 final boolean userSet = 17137 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17138 final boolean userFixed = 17139 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17140 final boolean revoke = 17141 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17142 17143 serializer.startTag(null, TAG_PERMISSION); 17144 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17145 if (isGranted) { 17146 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17147 } 17148 if (userSet) { 17149 serializer.attribute(null, ATTR_USER_SET, "true"); 17150 } 17151 if (userFixed) { 17152 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17153 } 17154 if (revoke) { 17155 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17156 } 17157 serializer.endTag(null, TAG_PERMISSION); 17158 } 17159 } 17160 } 17161 17162 if (pkgGrantsKnown) { 17163 serializer.endTag(null, TAG_GRANT); 17164 } 17165 } 17166 17167 serializer.endTag(null, TAG_ALL_GRANTS); 17168 } 17169 17170 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17171 throws XmlPullParserException, IOException { 17172 String pkgName = null; 17173 int outerDepth = parser.getDepth(); 17174 int type; 17175 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17176 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17177 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17178 continue; 17179 } 17180 17181 final String tagName = parser.getName(); 17182 if (tagName.equals(TAG_GRANT)) { 17183 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17184 if (DEBUG_BACKUP) { 17185 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17186 } 17187 } else if (tagName.equals(TAG_PERMISSION)) { 17188 17189 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17190 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17191 17192 int newFlagSet = 0; 17193 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17194 newFlagSet |= FLAG_PERMISSION_USER_SET; 17195 } 17196 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17197 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17198 } 17199 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17200 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17201 } 17202 if (DEBUG_BACKUP) { 17203 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17204 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17205 } 17206 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17207 if (ps != null) { 17208 // Already installed so we apply the grant immediately 17209 if (DEBUG_BACKUP) { 17210 Slog.v(TAG, " + already installed; applying"); 17211 } 17212 PermissionsState perms = ps.getPermissionsState(); 17213 BasePermission bp = mSettings.mPermissions.get(permName); 17214 if (bp != null) { 17215 if (isGranted) { 17216 perms.grantRuntimePermission(bp, userId); 17217 } 17218 if (newFlagSet != 0) { 17219 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17220 } 17221 } 17222 } else { 17223 // Need to wait for post-restore install to apply the grant 17224 if (DEBUG_BACKUP) { 17225 Slog.v(TAG, " - not yet installed; saving for later"); 17226 } 17227 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17228 isGranted, newFlagSet, userId); 17229 } 17230 } else { 17231 PackageManagerService.reportSettingsProblem(Log.WARN, 17232 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17233 XmlUtils.skipCurrentTag(parser); 17234 } 17235 } 17236 17237 scheduleWriteSettingsLocked(); 17238 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17239 } 17240 17241 @Override 17242 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17243 int sourceUserId, int targetUserId, int flags) { 17244 mContext.enforceCallingOrSelfPermission( 17245 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17246 int callingUid = Binder.getCallingUid(); 17247 enforceOwnerRights(ownerPackage, callingUid); 17248 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17249 if (intentFilter.countActions() == 0) { 17250 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17251 return; 17252 } 17253 synchronized (mPackages) { 17254 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17255 ownerPackage, targetUserId, flags); 17256 CrossProfileIntentResolver resolver = 17257 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17258 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17259 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17260 if (existing != null) { 17261 int size = existing.size(); 17262 for (int i = 0; i < size; i++) { 17263 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17264 return; 17265 } 17266 } 17267 } 17268 resolver.addFilter(newFilter); 17269 scheduleWritePackageRestrictionsLocked(sourceUserId); 17270 } 17271 } 17272 17273 @Override 17274 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17275 mContext.enforceCallingOrSelfPermission( 17276 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17277 int callingUid = Binder.getCallingUid(); 17278 enforceOwnerRights(ownerPackage, callingUid); 17279 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17280 synchronized (mPackages) { 17281 CrossProfileIntentResolver resolver = 17282 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17283 ArraySet<CrossProfileIntentFilter> set = 17284 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17285 for (CrossProfileIntentFilter filter : set) { 17286 if (filter.getOwnerPackage().equals(ownerPackage)) { 17287 resolver.removeFilter(filter); 17288 } 17289 } 17290 scheduleWritePackageRestrictionsLocked(sourceUserId); 17291 } 17292 } 17293 17294 // Enforcing that callingUid is owning pkg on userId 17295 private void enforceOwnerRights(String pkg, int callingUid) { 17296 // The system owns everything. 17297 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17298 return; 17299 } 17300 int callingUserId = UserHandle.getUserId(callingUid); 17301 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17302 if (pi == null) { 17303 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17304 + callingUserId); 17305 } 17306 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17307 throw new SecurityException("Calling uid " + callingUid 17308 + " does not own package " + pkg); 17309 } 17310 } 17311 17312 @Override 17313 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17314 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17315 } 17316 17317 private Intent getHomeIntent() { 17318 Intent intent = new Intent(Intent.ACTION_MAIN); 17319 intent.addCategory(Intent.CATEGORY_HOME); 17320 return intent; 17321 } 17322 17323 private IntentFilter getHomeFilter() { 17324 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17325 filter.addCategory(Intent.CATEGORY_HOME); 17326 filter.addCategory(Intent.CATEGORY_DEFAULT); 17327 return filter; 17328 } 17329 17330 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17331 int userId) { 17332 Intent intent = getHomeIntent(); 17333 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17334 PackageManager.GET_META_DATA, userId); 17335 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17336 true, false, false, userId); 17337 17338 allHomeCandidates.clear(); 17339 if (list != null) { 17340 for (ResolveInfo ri : list) { 17341 allHomeCandidates.add(ri); 17342 } 17343 } 17344 return (preferred == null || preferred.activityInfo == null) 17345 ? null 17346 : new ComponentName(preferred.activityInfo.packageName, 17347 preferred.activityInfo.name); 17348 } 17349 17350 @Override 17351 public void setHomeActivity(ComponentName comp, int userId) { 17352 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17353 getHomeActivitiesAsUser(homeActivities, userId); 17354 17355 boolean found = false; 17356 17357 final int size = homeActivities.size(); 17358 final ComponentName[] set = new ComponentName[size]; 17359 for (int i = 0; i < size; i++) { 17360 final ResolveInfo candidate = homeActivities.get(i); 17361 final ActivityInfo info = candidate.activityInfo; 17362 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17363 set[i] = activityName; 17364 if (!found && activityName.equals(comp)) { 17365 found = true; 17366 } 17367 } 17368 if (!found) { 17369 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17370 + userId); 17371 } 17372 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17373 set, comp, userId); 17374 } 17375 17376 private @Nullable String getSetupWizardPackageName() { 17377 final Intent intent = new Intent(Intent.ACTION_MAIN); 17378 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17379 17380 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17381 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17382 | MATCH_DISABLED_COMPONENTS, 17383 UserHandle.myUserId()); 17384 if (matches.size() == 1) { 17385 return matches.get(0).getComponentInfo().packageName; 17386 } else { 17387 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17388 + ": matches=" + matches); 17389 return null; 17390 } 17391 } 17392 17393 @Override 17394 public void setApplicationEnabledSetting(String appPackageName, 17395 int newState, int flags, int userId, String callingPackage) { 17396 if (!sUserManager.exists(userId)) return; 17397 if (callingPackage == null) { 17398 callingPackage = Integer.toString(Binder.getCallingUid()); 17399 } 17400 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17401 } 17402 17403 @Override 17404 public void setComponentEnabledSetting(ComponentName componentName, 17405 int newState, int flags, int userId) { 17406 if (!sUserManager.exists(userId)) return; 17407 setEnabledSetting(componentName.getPackageName(), 17408 componentName.getClassName(), newState, flags, userId, null); 17409 } 17410 17411 private void setEnabledSetting(final String packageName, String className, int newState, 17412 final int flags, int userId, String callingPackage) { 17413 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17414 || newState == COMPONENT_ENABLED_STATE_ENABLED 17415 || newState == COMPONENT_ENABLED_STATE_DISABLED 17416 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17417 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17418 throw new IllegalArgumentException("Invalid new component state: " 17419 + newState); 17420 } 17421 PackageSetting pkgSetting; 17422 final int uid = Binder.getCallingUid(); 17423 final int permission; 17424 if (uid == Process.SYSTEM_UID) { 17425 permission = PackageManager.PERMISSION_GRANTED; 17426 } else { 17427 permission = mContext.checkCallingOrSelfPermission( 17428 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17429 } 17430 enforceCrossUserPermission(uid, userId, 17431 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17432 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17433 boolean sendNow = false; 17434 boolean isApp = (className == null); 17435 String componentName = isApp ? packageName : className; 17436 int packageUid = -1; 17437 ArrayList<String> components; 17438 17439 // writer 17440 synchronized (mPackages) { 17441 pkgSetting = mSettings.mPackages.get(packageName); 17442 if (pkgSetting == null) { 17443 if (className == null) { 17444 throw new IllegalArgumentException("Unknown package: " + packageName); 17445 } 17446 throw new IllegalArgumentException( 17447 "Unknown component: " + packageName + "/" + className); 17448 } 17449 // Allow root and verify that userId is not being specified by a different user 17450 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17451 throw new SecurityException( 17452 "Permission Denial: attempt to change component state from pid=" 17453 + Binder.getCallingPid() 17454 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17455 } 17456 if (className == null) { 17457 // We're dealing with an application/package level state change 17458 if (pkgSetting.getEnabled(userId) == newState) { 17459 // Nothing to do 17460 return; 17461 } 17462 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17463 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17464 // Don't care about who enables an app. 17465 callingPackage = null; 17466 } 17467 pkgSetting.setEnabled(newState, userId, callingPackage); 17468 // pkgSetting.pkg.mSetEnabled = newState; 17469 } else { 17470 // We're dealing with a component level state change 17471 // First, verify that this is a valid class name. 17472 PackageParser.Package pkg = pkgSetting.pkg; 17473 if (pkg == null || !pkg.hasComponentClassName(className)) { 17474 if (pkg != null && 17475 pkg.applicationInfo.targetSdkVersion >= 17476 Build.VERSION_CODES.JELLY_BEAN) { 17477 throw new IllegalArgumentException("Component class " + className 17478 + " does not exist in " + packageName); 17479 } else { 17480 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17481 + className + " does not exist in " + packageName); 17482 } 17483 } 17484 switch (newState) { 17485 case COMPONENT_ENABLED_STATE_ENABLED: 17486 if (!pkgSetting.enableComponentLPw(className, userId)) { 17487 return; 17488 } 17489 break; 17490 case COMPONENT_ENABLED_STATE_DISABLED: 17491 if (!pkgSetting.disableComponentLPw(className, userId)) { 17492 return; 17493 } 17494 break; 17495 case COMPONENT_ENABLED_STATE_DEFAULT: 17496 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17497 return; 17498 } 17499 break; 17500 default: 17501 Slog.e(TAG, "Invalid new component state: " + newState); 17502 return; 17503 } 17504 } 17505 scheduleWritePackageRestrictionsLocked(userId); 17506 components = mPendingBroadcasts.get(userId, packageName); 17507 final boolean newPackage = components == null; 17508 if (newPackage) { 17509 components = new ArrayList<String>(); 17510 } 17511 if (!components.contains(componentName)) { 17512 components.add(componentName); 17513 } 17514 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17515 sendNow = true; 17516 // Purge entry from pending broadcast list if another one exists already 17517 // since we are sending one right away. 17518 mPendingBroadcasts.remove(userId, packageName); 17519 } else { 17520 if (newPackage) { 17521 mPendingBroadcasts.put(userId, packageName, components); 17522 } 17523 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17524 // Schedule a message 17525 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17526 } 17527 } 17528 } 17529 17530 long callingId = Binder.clearCallingIdentity(); 17531 try { 17532 if (sendNow) { 17533 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17534 sendPackageChangedBroadcast(packageName, 17535 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17536 } 17537 } finally { 17538 Binder.restoreCallingIdentity(callingId); 17539 } 17540 } 17541 17542 @Override 17543 public void flushPackageRestrictionsAsUser(int userId) { 17544 if (!sUserManager.exists(userId)) { 17545 return; 17546 } 17547 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17548 false /* checkShell */, "flushPackageRestrictions"); 17549 synchronized (mPackages) { 17550 mSettings.writePackageRestrictionsLPr(userId); 17551 mDirtyUsers.remove(userId); 17552 if (mDirtyUsers.isEmpty()) { 17553 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17554 } 17555 } 17556 } 17557 17558 private void sendPackageChangedBroadcast(String packageName, 17559 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17560 if (DEBUG_INSTALL) 17561 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17562 + componentNames); 17563 Bundle extras = new Bundle(4); 17564 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17565 String nameList[] = new String[componentNames.size()]; 17566 componentNames.toArray(nameList); 17567 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17568 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17569 extras.putInt(Intent.EXTRA_UID, packageUid); 17570 // If this is not reporting a change of the overall package, then only send it 17571 // to registered receivers. We don't want to launch a swath of apps for every 17572 // little component state change. 17573 final int flags = !componentNames.contains(packageName) 17574 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17575 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17576 new int[] {UserHandle.getUserId(packageUid)}); 17577 } 17578 17579 @Override 17580 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17581 if (!sUserManager.exists(userId)) return; 17582 final int uid = Binder.getCallingUid(); 17583 final int permission = mContext.checkCallingOrSelfPermission( 17584 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17585 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17586 enforceCrossUserPermission(uid, userId, 17587 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17588 // writer 17589 synchronized (mPackages) { 17590 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17591 allowedByPermission, uid, userId)) { 17592 scheduleWritePackageRestrictionsLocked(userId); 17593 } 17594 } 17595 } 17596 17597 @Override 17598 public String getInstallerPackageName(String packageName) { 17599 // reader 17600 synchronized (mPackages) { 17601 return mSettings.getInstallerPackageNameLPr(packageName); 17602 } 17603 } 17604 17605 public boolean isOrphaned(String packageName) { 17606 // reader 17607 synchronized (mPackages) { 17608 return mSettings.isOrphaned(packageName); 17609 } 17610 } 17611 17612 @Override 17613 public int getApplicationEnabledSetting(String packageName, int userId) { 17614 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17615 int uid = Binder.getCallingUid(); 17616 enforceCrossUserPermission(uid, userId, 17617 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17618 // reader 17619 synchronized (mPackages) { 17620 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17621 } 17622 } 17623 17624 @Override 17625 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17626 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17627 int uid = Binder.getCallingUid(); 17628 enforceCrossUserPermission(uid, userId, 17629 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17630 // reader 17631 synchronized (mPackages) { 17632 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17633 } 17634 } 17635 17636 @Override 17637 public void enterSafeMode() { 17638 enforceSystemOrRoot("Only the system can request entering safe mode"); 17639 17640 if (!mSystemReady) { 17641 mSafeMode = true; 17642 } 17643 } 17644 17645 @Override 17646 public void systemReady() { 17647 mSystemReady = true; 17648 17649 // Read the compatibilty setting when the system is ready. 17650 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17651 mContext.getContentResolver(), 17652 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17653 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17654 if (DEBUG_SETTINGS) { 17655 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17656 } 17657 17658 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17659 17660 synchronized (mPackages) { 17661 // Verify that all of the preferred activity components actually 17662 // exist. It is possible for applications to be updated and at 17663 // that point remove a previously declared activity component that 17664 // had been set as a preferred activity. We try to clean this up 17665 // the next time we encounter that preferred activity, but it is 17666 // possible for the user flow to never be able to return to that 17667 // situation so here we do a sanity check to make sure we haven't 17668 // left any junk around. 17669 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17670 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17671 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17672 removed.clear(); 17673 for (PreferredActivity pa : pir.filterSet()) { 17674 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17675 removed.add(pa); 17676 } 17677 } 17678 if (removed.size() > 0) { 17679 for (int r=0; r<removed.size(); r++) { 17680 PreferredActivity pa = removed.get(r); 17681 Slog.w(TAG, "Removing dangling preferred activity: " 17682 + pa.mPref.mComponent); 17683 pir.removeFilter(pa); 17684 } 17685 mSettings.writePackageRestrictionsLPr( 17686 mSettings.mPreferredActivities.keyAt(i)); 17687 } 17688 } 17689 17690 for (int userId : UserManagerService.getInstance().getUserIds()) { 17691 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17692 grantPermissionsUserIds = ArrayUtils.appendInt( 17693 grantPermissionsUserIds, userId); 17694 } 17695 } 17696 } 17697 sUserManager.systemReady(); 17698 17699 // If we upgraded grant all default permissions before kicking off. 17700 for (int userId : grantPermissionsUserIds) { 17701 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17702 } 17703 17704 // Kick off any messages waiting for system ready 17705 if (mPostSystemReadyMessages != null) { 17706 for (Message msg : mPostSystemReadyMessages) { 17707 msg.sendToTarget(); 17708 } 17709 mPostSystemReadyMessages = null; 17710 } 17711 17712 // Watch for external volumes that come and go over time 17713 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17714 storage.registerListener(mStorageListener); 17715 17716 mInstallerService.systemReady(); 17717 mPackageDexOptimizer.systemReady(); 17718 17719 MountServiceInternal mountServiceInternal = LocalServices.getService( 17720 MountServiceInternal.class); 17721 mountServiceInternal.addExternalStoragePolicy( 17722 new MountServiceInternal.ExternalStorageMountPolicy() { 17723 @Override 17724 public int getMountMode(int uid, String packageName) { 17725 if (Process.isIsolated(uid)) { 17726 return Zygote.MOUNT_EXTERNAL_NONE; 17727 } 17728 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17729 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17730 } 17731 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17732 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17733 } 17734 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17735 return Zygote.MOUNT_EXTERNAL_READ; 17736 } 17737 return Zygote.MOUNT_EXTERNAL_WRITE; 17738 } 17739 17740 @Override 17741 public boolean hasExternalStorage(int uid, String packageName) { 17742 return true; 17743 } 17744 }); 17745 17746 // Now that we're mostly running, clean up stale users and apps 17747 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17748 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17749 } 17750 17751 @Override 17752 public boolean isSafeMode() { 17753 return mSafeMode; 17754 } 17755 17756 @Override 17757 public boolean hasSystemUidErrors() { 17758 return mHasSystemUidErrors; 17759 } 17760 17761 static String arrayToString(int[] array) { 17762 StringBuffer buf = new StringBuffer(128); 17763 buf.append('['); 17764 if (array != null) { 17765 for (int i=0; i<array.length; i++) { 17766 if (i > 0) buf.append(", "); 17767 buf.append(array[i]); 17768 } 17769 } 17770 buf.append(']'); 17771 return buf.toString(); 17772 } 17773 17774 static class DumpState { 17775 public static final int DUMP_LIBS = 1 << 0; 17776 public static final int DUMP_FEATURES = 1 << 1; 17777 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17778 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17779 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17780 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17781 public static final int DUMP_PERMISSIONS = 1 << 6; 17782 public static final int DUMP_PACKAGES = 1 << 7; 17783 public static final int DUMP_SHARED_USERS = 1 << 8; 17784 public static final int DUMP_MESSAGES = 1 << 9; 17785 public static final int DUMP_PROVIDERS = 1 << 10; 17786 public static final int DUMP_VERIFIERS = 1 << 11; 17787 public static final int DUMP_PREFERRED = 1 << 12; 17788 public static final int DUMP_PREFERRED_XML = 1 << 13; 17789 public static final int DUMP_KEYSETS = 1 << 14; 17790 public static final int DUMP_VERSION = 1 << 15; 17791 public static final int DUMP_INSTALLS = 1 << 16; 17792 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17793 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17794 public static final int DUMP_FROZEN = 1 << 19; 17795 public static final int DUMP_DEXOPT = 1 << 20; 17796 17797 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17798 17799 private int mTypes; 17800 17801 private int mOptions; 17802 17803 private boolean mTitlePrinted; 17804 17805 private SharedUserSetting mSharedUser; 17806 17807 public boolean isDumping(int type) { 17808 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17809 return true; 17810 } 17811 17812 return (mTypes & type) != 0; 17813 } 17814 17815 public void setDump(int type) { 17816 mTypes |= type; 17817 } 17818 17819 public boolean isOptionEnabled(int option) { 17820 return (mOptions & option) != 0; 17821 } 17822 17823 public void setOptionEnabled(int option) { 17824 mOptions |= option; 17825 } 17826 17827 public boolean onTitlePrinted() { 17828 final boolean printed = mTitlePrinted; 17829 mTitlePrinted = true; 17830 return printed; 17831 } 17832 17833 public boolean getTitlePrinted() { 17834 return mTitlePrinted; 17835 } 17836 17837 public void setTitlePrinted(boolean enabled) { 17838 mTitlePrinted = enabled; 17839 } 17840 17841 public SharedUserSetting getSharedUser() { 17842 return mSharedUser; 17843 } 17844 17845 public void setSharedUser(SharedUserSetting user) { 17846 mSharedUser = user; 17847 } 17848 } 17849 17850 @Override 17851 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17852 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17853 (new PackageManagerShellCommand(this)).exec( 17854 this, in, out, err, args, resultReceiver); 17855 } 17856 17857 @Override 17858 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17859 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17860 != PackageManager.PERMISSION_GRANTED) { 17861 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17862 + Binder.getCallingPid() 17863 + ", uid=" + Binder.getCallingUid() 17864 + " without permission " 17865 + android.Manifest.permission.DUMP); 17866 return; 17867 } 17868 17869 DumpState dumpState = new DumpState(); 17870 boolean fullPreferred = false; 17871 boolean checkin = false; 17872 17873 String packageName = null; 17874 ArraySet<String> permissionNames = null; 17875 17876 int opti = 0; 17877 while (opti < args.length) { 17878 String opt = args[opti]; 17879 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17880 break; 17881 } 17882 opti++; 17883 17884 if ("-a".equals(opt)) { 17885 // Right now we only know how to print all. 17886 } else if ("-h".equals(opt)) { 17887 pw.println("Package manager dump options:"); 17888 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17889 pw.println(" --checkin: dump for a checkin"); 17890 pw.println(" -f: print details of intent filters"); 17891 pw.println(" -h: print this help"); 17892 pw.println(" cmd may be one of:"); 17893 pw.println(" l[ibraries]: list known shared libraries"); 17894 pw.println(" f[eatures]: list device features"); 17895 pw.println(" k[eysets]: print known keysets"); 17896 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17897 pw.println(" perm[issions]: dump permissions"); 17898 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17899 pw.println(" pref[erred]: print preferred package settings"); 17900 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17901 pw.println(" prov[iders]: dump content providers"); 17902 pw.println(" p[ackages]: dump installed packages"); 17903 pw.println(" s[hared-users]: dump shared user IDs"); 17904 pw.println(" m[essages]: print collected runtime messages"); 17905 pw.println(" v[erifiers]: print package verifier info"); 17906 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17907 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17908 pw.println(" version: print database version info"); 17909 pw.println(" write: write current settings now"); 17910 pw.println(" installs: details about install sessions"); 17911 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17912 pw.println(" dexopt: dump dexopt state"); 17913 pw.println(" <package.name>: info about given package"); 17914 return; 17915 } else if ("--checkin".equals(opt)) { 17916 checkin = true; 17917 } else if ("-f".equals(opt)) { 17918 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17919 } else { 17920 pw.println("Unknown argument: " + opt + "; use -h for help"); 17921 } 17922 } 17923 17924 // Is the caller requesting to dump a particular piece of data? 17925 if (opti < args.length) { 17926 String cmd = args[opti]; 17927 opti++; 17928 // Is this a package name? 17929 if ("android".equals(cmd) || cmd.contains(".")) { 17930 packageName = cmd; 17931 // When dumping a single package, we always dump all of its 17932 // filter information since the amount of data will be reasonable. 17933 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17934 } else if ("check-permission".equals(cmd)) { 17935 if (opti >= args.length) { 17936 pw.println("Error: check-permission missing permission argument"); 17937 return; 17938 } 17939 String perm = args[opti]; 17940 opti++; 17941 if (opti >= args.length) { 17942 pw.println("Error: check-permission missing package argument"); 17943 return; 17944 } 17945 String pkg = args[opti]; 17946 opti++; 17947 int user = UserHandle.getUserId(Binder.getCallingUid()); 17948 if (opti < args.length) { 17949 try { 17950 user = Integer.parseInt(args[opti]); 17951 } catch (NumberFormatException e) { 17952 pw.println("Error: check-permission user argument is not a number: " 17953 + args[opti]); 17954 return; 17955 } 17956 } 17957 pw.println(checkPermission(perm, pkg, user)); 17958 return; 17959 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17960 dumpState.setDump(DumpState.DUMP_LIBS); 17961 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17962 dumpState.setDump(DumpState.DUMP_FEATURES); 17963 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17964 if (opti >= args.length) { 17965 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17966 | DumpState.DUMP_SERVICE_RESOLVERS 17967 | DumpState.DUMP_RECEIVER_RESOLVERS 17968 | DumpState.DUMP_CONTENT_RESOLVERS); 17969 } else { 17970 while (opti < args.length) { 17971 String name = args[opti]; 17972 if ("a".equals(name) || "activity".equals(name)) { 17973 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17974 } else if ("s".equals(name) || "service".equals(name)) { 17975 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17976 } else if ("r".equals(name) || "receiver".equals(name)) { 17977 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17978 } else if ("c".equals(name) || "content".equals(name)) { 17979 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17980 } else { 17981 pw.println("Error: unknown resolver table type: " + name); 17982 return; 17983 } 17984 opti++; 17985 } 17986 } 17987 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17988 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17989 } else if ("permission".equals(cmd)) { 17990 if (opti >= args.length) { 17991 pw.println("Error: permission requires permission name"); 17992 return; 17993 } 17994 permissionNames = new ArraySet<>(); 17995 while (opti < args.length) { 17996 permissionNames.add(args[opti]); 17997 opti++; 17998 } 17999 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18000 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18001 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18002 dumpState.setDump(DumpState.DUMP_PREFERRED); 18003 } else if ("preferred-xml".equals(cmd)) { 18004 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18005 if (opti < args.length && "--full".equals(args[opti])) { 18006 fullPreferred = true; 18007 opti++; 18008 } 18009 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18010 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18011 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18012 dumpState.setDump(DumpState.DUMP_PACKAGES); 18013 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18014 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18015 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18016 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18017 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18018 dumpState.setDump(DumpState.DUMP_MESSAGES); 18019 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18020 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18021 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18022 || "intent-filter-verifiers".equals(cmd)) { 18023 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18024 } else if ("version".equals(cmd)) { 18025 dumpState.setDump(DumpState.DUMP_VERSION); 18026 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18027 dumpState.setDump(DumpState.DUMP_KEYSETS); 18028 } else if ("installs".equals(cmd)) { 18029 dumpState.setDump(DumpState.DUMP_INSTALLS); 18030 } else if ("frozen".equals(cmd)) { 18031 dumpState.setDump(DumpState.DUMP_FROZEN); 18032 } else if ("dexopt".equals(cmd)) { 18033 dumpState.setDump(DumpState.DUMP_DEXOPT); 18034 } else if ("write".equals(cmd)) { 18035 synchronized (mPackages) { 18036 mSettings.writeLPr(); 18037 pw.println("Settings written."); 18038 return; 18039 } 18040 } 18041 } 18042 18043 if (checkin) { 18044 pw.println("vers,1"); 18045 } 18046 18047 // reader 18048 synchronized (mPackages) { 18049 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18050 if (!checkin) { 18051 if (dumpState.onTitlePrinted()) 18052 pw.println(); 18053 pw.println("Database versions:"); 18054 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18055 } 18056 } 18057 18058 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18059 if (!checkin) { 18060 if (dumpState.onTitlePrinted()) 18061 pw.println(); 18062 pw.println("Verifiers:"); 18063 pw.print(" Required: "); 18064 pw.print(mRequiredVerifierPackage); 18065 pw.print(" (uid="); 18066 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18067 UserHandle.USER_SYSTEM)); 18068 pw.println(")"); 18069 } else if (mRequiredVerifierPackage != null) { 18070 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18071 pw.print(","); 18072 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18073 UserHandle.USER_SYSTEM)); 18074 } 18075 } 18076 18077 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18078 packageName == null) { 18079 if (mIntentFilterVerifierComponent != null) { 18080 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18081 if (!checkin) { 18082 if (dumpState.onTitlePrinted()) 18083 pw.println(); 18084 pw.println("Intent Filter Verifier:"); 18085 pw.print(" Using: "); 18086 pw.print(verifierPackageName); 18087 pw.print(" (uid="); 18088 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18089 UserHandle.USER_SYSTEM)); 18090 pw.println(")"); 18091 } else if (verifierPackageName != null) { 18092 pw.print("ifv,"); pw.print(verifierPackageName); 18093 pw.print(","); 18094 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18095 UserHandle.USER_SYSTEM)); 18096 } 18097 } else { 18098 pw.println(); 18099 pw.println("No Intent Filter Verifier available!"); 18100 } 18101 } 18102 18103 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18104 boolean printedHeader = false; 18105 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18106 while (it.hasNext()) { 18107 String name = it.next(); 18108 SharedLibraryEntry ent = mSharedLibraries.get(name); 18109 if (!checkin) { 18110 if (!printedHeader) { 18111 if (dumpState.onTitlePrinted()) 18112 pw.println(); 18113 pw.println("Libraries:"); 18114 printedHeader = true; 18115 } 18116 pw.print(" "); 18117 } else { 18118 pw.print("lib,"); 18119 } 18120 pw.print(name); 18121 if (!checkin) { 18122 pw.print(" -> "); 18123 } 18124 if (ent.path != null) { 18125 if (!checkin) { 18126 pw.print("(jar) "); 18127 pw.print(ent.path); 18128 } else { 18129 pw.print(",jar,"); 18130 pw.print(ent.path); 18131 } 18132 } else { 18133 if (!checkin) { 18134 pw.print("(apk) "); 18135 pw.print(ent.apk); 18136 } else { 18137 pw.print(",apk,"); 18138 pw.print(ent.apk); 18139 } 18140 } 18141 pw.println(); 18142 } 18143 } 18144 18145 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18146 if (dumpState.onTitlePrinted()) 18147 pw.println(); 18148 if (!checkin) { 18149 pw.println("Features:"); 18150 } 18151 18152 for (FeatureInfo feat : mAvailableFeatures.values()) { 18153 if (checkin) { 18154 pw.print("feat,"); 18155 pw.print(feat.name); 18156 pw.print(","); 18157 pw.println(feat.version); 18158 } else { 18159 pw.print(" "); 18160 pw.print(feat.name); 18161 if (feat.version > 0) { 18162 pw.print(" version="); 18163 pw.print(feat.version); 18164 } 18165 pw.println(); 18166 } 18167 } 18168 } 18169 18170 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18171 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18172 : "Activity Resolver Table:", " ", packageName, 18173 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18174 dumpState.setTitlePrinted(true); 18175 } 18176 } 18177 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18178 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18179 : "Receiver Resolver Table:", " ", packageName, 18180 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18181 dumpState.setTitlePrinted(true); 18182 } 18183 } 18184 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18185 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18186 : "Service Resolver Table:", " ", packageName, 18187 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18188 dumpState.setTitlePrinted(true); 18189 } 18190 } 18191 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18192 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18193 : "Provider Resolver Table:", " ", packageName, 18194 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18195 dumpState.setTitlePrinted(true); 18196 } 18197 } 18198 18199 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18200 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18201 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18202 int user = mSettings.mPreferredActivities.keyAt(i); 18203 if (pir.dump(pw, 18204 dumpState.getTitlePrinted() 18205 ? "\nPreferred Activities User " + user + ":" 18206 : "Preferred Activities User " + user + ":", " ", 18207 packageName, true, false)) { 18208 dumpState.setTitlePrinted(true); 18209 } 18210 } 18211 } 18212 18213 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18214 pw.flush(); 18215 FileOutputStream fout = new FileOutputStream(fd); 18216 BufferedOutputStream str = new BufferedOutputStream(fout); 18217 XmlSerializer serializer = new FastXmlSerializer(); 18218 try { 18219 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18220 serializer.startDocument(null, true); 18221 serializer.setFeature( 18222 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18223 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18224 serializer.endDocument(); 18225 serializer.flush(); 18226 } catch (IllegalArgumentException e) { 18227 pw.println("Failed writing: " + e); 18228 } catch (IllegalStateException e) { 18229 pw.println("Failed writing: " + e); 18230 } catch (IOException e) { 18231 pw.println("Failed writing: " + e); 18232 } 18233 } 18234 18235 if (!checkin 18236 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18237 && packageName == null) { 18238 pw.println(); 18239 int count = mSettings.mPackages.size(); 18240 if (count == 0) { 18241 pw.println("No applications!"); 18242 pw.println(); 18243 } else { 18244 final String prefix = " "; 18245 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18246 if (allPackageSettings.size() == 0) { 18247 pw.println("No domain preferred apps!"); 18248 pw.println(); 18249 } else { 18250 pw.println("App verification status:"); 18251 pw.println(); 18252 count = 0; 18253 for (PackageSetting ps : allPackageSettings) { 18254 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18255 if (ivi == null || ivi.getPackageName() == null) continue; 18256 pw.println(prefix + "Package: " + ivi.getPackageName()); 18257 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18258 pw.println(prefix + "Status: " + ivi.getStatusString()); 18259 pw.println(); 18260 count++; 18261 } 18262 if (count == 0) { 18263 pw.println(prefix + "No app verification established."); 18264 pw.println(); 18265 } 18266 for (int userId : sUserManager.getUserIds()) { 18267 pw.println("App linkages for user " + userId + ":"); 18268 pw.println(); 18269 count = 0; 18270 for (PackageSetting ps : allPackageSettings) { 18271 final long status = ps.getDomainVerificationStatusForUser(userId); 18272 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18273 continue; 18274 } 18275 pw.println(prefix + "Package: " + ps.name); 18276 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18277 String statusStr = IntentFilterVerificationInfo. 18278 getStatusStringFromValue(status); 18279 pw.println(prefix + "Status: " + statusStr); 18280 pw.println(); 18281 count++; 18282 } 18283 if (count == 0) { 18284 pw.println(prefix + "No configured app linkages."); 18285 pw.println(); 18286 } 18287 } 18288 } 18289 } 18290 } 18291 18292 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18293 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18294 if (packageName == null && permissionNames == null) { 18295 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18296 if (iperm == 0) { 18297 if (dumpState.onTitlePrinted()) 18298 pw.println(); 18299 pw.println("AppOp Permissions:"); 18300 } 18301 pw.print(" AppOp Permission "); 18302 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18303 pw.println(":"); 18304 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18305 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18306 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18307 } 18308 } 18309 } 18310 } 18311 18312 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18313 boolean printedSomething = false; 18314 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18315 if (packageName != null && !packageName.equals(p.info.packageName)) { 18316 continue; 18317 } 18318 if (!printedSomething) { 18319 if (dumpState.onTitlePrinted()) 18320 pw.println(); 18321 pw.println("Registered ContentProviders:"); 18322 printedSomething = true; 18323 } 18324 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18325 pw.print(" "); pw.println(p.toString()); 18326 } 18327 printedSomething = false; 18328 for (Map.Entry<String, PackageParser.Provider> entry : 18329 mProvidersByAuthority.entrySet()) { 18330 PackageParser.Provider p = entry.getValue(); 18331 if (packageName != null && !packageName.equals(p.info.packageName)) { 18332 continue; 18333 } 18334 if (!printedSomething) { 18335 if (dumpState.onTitlePrinted()) 18336 pw.println(); 18337 pw.println("ContentProvider Authorities:"); 18338 printedSomething = true; 18339 } 18340 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18341 pw.print(" "); pw.println(p.toString()); 18342 if (p.info != null && p.info.applicationInfo != null) { 18343 final String appInfo = p.info.applicationInfo.toString(); 18344 pw.print(" applicationInfo="); pw.println(appInfo); 18345 } 18346 } 18347 } 18348 18349 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18350 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18351 } 18352 18353 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18354 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18355 } 18356 18357 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18358 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18359 } 18360 18361 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18362 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18363 } 18364 18365 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18366 // XXX should handle packageName != null by dumping only install data that 18367 // the given package is involved with. 18368 if (dumpState.onTitlePrinted()) pw.println(); 18369 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18370 } 18371 18372 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18373 // XXX should handle packageName != null by dumping only install data that 18374 // the given package is involved with. 18375 if (dumpState.onTitlePrinted()) pw.println(); 18376 18377 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18378 ipw.println(); 18379 ipw.println("Frozen packages:"); 18380 ipw.increaseIndent(); 18381 if (mFrozenPackages.size() == 0) { 18382 ipw.println("(none)"); 18383 } else { 18384 for (int i = 0; i < mFrozenPackages.size(); i++) { 18385 ipw.println(mFrozenPackages.valueAt(i)); 18386 } 18387 } 18388 ipw.decreaseIndent(); 18389 } 18390 18391 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18392 if (dumpState.onTitlePrinted()) pw.println(); 18393 dumpDexoptStateLPr(pw, packageName); 18394 } 18395 18396 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18397 if (dumpState.onTitlePrinted()) pw.println(); 18398 mSettings.dumpReadMessagesLPr(pw, dumpState); 18399 18400 pw.println(); 18401 pw.println("Package warning messages:"); 18402 BufferedReader in = null; 18403 String line = null; 18404 try { 18405 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18406 while ((line = in.readLine()) != null) { 18407 if (line.contains("ignored: updated version")) continue; 18408 pw.println(line); 18409 } 18410 } catch (IOException ignored) { 18411 } finally { 18412 IoUtils.closeQuietly(in); 18413 } 18414 } 18415 18416 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18417 BufferedReader in = null; 18418 String line = null; 18419 try { 18420 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18421 while ((line = in.readLine()) != null) { 18422 if (line.contains("ignored: updated version")) continue; 18423 pw.print("msg,"); 18424 pw.println(line); 18425 } 18426 } catch (IOException ignored) { 18427 } finally { 18428 IoUtils.closeQuietly(in); 18429 } 18430 } 18431 } 18432 } 18433 18434 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18435 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18436 ipw.println(); 18437 ipw.println("Dexopt state:"); 18438 ipw.increaseIndent(); 18439 Collection<PackageParser.Package> packages = null; 18440 if (packageName != null) { 18441 PackageParser.Package targetPackage = mPackages.get(packageName); 18442 if (targetPackage != null) { 18443 packages = Collections.singletonList(targetPackage); 18444 } else { 18445 ipw.println("Unable to find package: " + packageName); 18446 return; 18447 } 18448 } else { 18449 packages = mPackages.values(); 18450 } 18451 18452 for (PackageParser.Package pkg : packages) { 18453 ipw.println("[" + pkg.packageName + "]"); 18454 ipw.increaseIndent(); 18455 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18456 ipw.decreaseIndent(); 18457 } 18458 } 18459 18460 private String dumpDomainString(String packageName) { 18461 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18462 .getList(); 18463 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18464 18465 ArraySet<String> result = new ArraySet<>(); 18466 if (iviList.size() > 0) { 18467 for (IntentFilterVerificationInfo ivi : iviList) { 18468 for (String host : ivi.getDomains()) { 18469 result.add(host); 18470 } 18471 } 18472 } 18473 if (filters != null && filters.size() > 0) { 18474 for (IntentFilter filter : filters) { 18475 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18476 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18477 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18478 result.addAll(filter.getHostsList()); 18479 } 18480 } 18481 } 18482 18483 StringBuilder sb = new StringBuilder(result.size() * 16); 18484 for (String domain : result) { 18485 if (sb.length() > 0) sb.append(" "); 18486 sb.append(domain); 18487 } 18488 return sb.toString(); 18489 } 18490 18491 // ------- apps on sdcard specific code ------- 18492 static final boolean DEBUG_SD_INSTALL = false; 18493 18494 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18495 18496 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18497 18498 private boolean mMediaMounted = false; 18499 18500 static String getEncryptKey() { 18501 try { 18502 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18503 SD_ENCRYPTION_KEYSTORE_NAME); 18504 if (sdEncKey == null) { 18505 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18506 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18507 if (sdEncKey == null) { 18508 Slog.e(TAG, "Failed to create encryption keys"); 18509 return null; 18510 } 18511 } 18512 return sdEncKey; 18513 } catch (NoSuchAlgorithmException nsae) { 18514 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18515 return null; 18516 } catch (IOException ioe) { 18517 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18518 return null; 18519 } 18520 } 18521 18522 /* 18523 * Update media status on PackageManager. 18524 */ 18525 @Override 18526 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18527 int callingUid = Binder.getCallingUid(); 18528 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18529 throw new SecurityException("Media status can only be updated by the system"); 18530 } 18531 // reader; this apparently protects mMediaMounted, but should probably 18532 // be a different lock in that case. 18533 synchronized (mPackages) { 18534 Log.i(TAG, "Updating external media status from " 18535 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18536 + (mediaStatus ? "mounted" : "unmounted")); 18537 if (DEBUG_SD_INSTALL) 18538 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18539 + ", mMediaMounted=" + mMediaMounted); 18540 if (mediaStatus == mMediaMounted) { 18541 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18542 : 0, -1); 18543 mHandler.sendMessage(msg); 18544 return; 18545 } 18546 mMediaMounted = mediaStatus; 18547 } 18548 // Queue up an async operation since the package installation may take a 18549 // little while. 18550 mHandler.post(new Runnable() { 18551 public void run() { 18552 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18553 } 18554 }); 18555 } 18556 18557 /** 18558 * Called by MountService when the initial ASECs to scan are available. 18559 * Should block until all the ASEC containers are finished being scanned. 18560 */ 18561 public void scanAvailableAsecs() { 18562 updateExternalMediaStatusInner(true, false, false); 18563 } 18564 18565 /* 18566 * Collect information of applications on external media, map them against 18567 * existing containers and update information based on current mount status. 18568 * Please note that we always have to report status if reportStatus has been 18569 * set to true especially when unloading packages. 18570 */ 18571 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18572 boolean externalStorage) { 18573 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18574 int[] uidArr = EmptyArray.INT; 18575 18576 final String[] list = PackageHelper.getSecureContainerList(); 18577 if (ArrayUtils.isEmpty(list)) { 18578 Log.i(TAG, "No secure containers found"); 18579 } else { 18580 // Process list of secure containers and categorize them 18581 // as active or stale based on their package internal state. 18582 18583 // reader 18584 synchronized (mPackages) { 18585 for (String cid : list) { 18586 // Leave stages untouched for now; installer service owns them 18587 if (PackageInstallerService.isStageName(cid)) continue; 18588 18589 if (DEBUG_SD_INSTALL) 18590 Log.i(TAG, "Processing container " + cid); 18591 String pkgName = getAsecPackageName(cid); 18592 if (pkgName == null) { 18593 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18594 continue; 18595 } 18596 if (DEBUG_SD_INSTALL) 18597 Log.i(TAG, "Looking for pkg : " + pkgName); 18598 18599 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18600 if (ps == null) { 18601 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18602 continue; 18603 } 18604 18605 /* 18606 * Skip packages that are not external if we're unmounting 18607 * external storage. 18608 */ 18609 if (externalStorage && !isMounted && !isExternal(ps)) { 18610 continue; 18611 } 18612 18613 final AsecInstallArgs args = new AsecInstallArgs(cid, 18614 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18615 // The package status is changed only if the code path 18616 // matches between settings and the container id. 18617 if (ps.codePathString != null 18618 && ps.codePathString.startsWith(args.getCodePath())) { 18619 if (DEBUG_SD_INSTALL) { 18620 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18621 + " at code path: " + ps.codePathString); 18622 } 18623 18624 // We do have a valid package installed on sdcard 18625 processCids.put(args, ps.codePathString); 18626 final int uid = ps.appId; 18627 if (uid != -1) { 18628 uidArr = ArrayUtils.appendInt(uidArr, uid); 18629 } 18630 } else { 18631 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18632 + ps.codePathString); 18633 } 18634 } 18635 } 18636 18637 Arrays.sort(uidArr); 18638 } 18639 18640 // Process packages with valid entries. 18641 if (isMounted) { 18642 if (DEBUG_SD_INSTALL) 18643 Log.i(TAG, "Loading packages"); 18644 loadMediaPackages(processCids, uidArr, externalStorage); 18645 startCleaningPackages(); 18646 mInstallerService.onSecureContainersAvailable(); 18647 } else { 18648 if (DEBUG_SD_INSTALL) 18649 Log.i(TAG, "Unloading packages"); 18650 unloadMediaPackages(processCids, uidArr, reportStatus); 18651 } 18652 } 18653 18654 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18655 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18656 final int size = infos.size(); 18657 final String[] packageNames = new String[size]; 18658 final int[] packageUids = new int[size]; 18659 for (int i = 0; i < size; i++) { 18660 final ApplicationInfo info = infos.get(i); 18661 packageNames[i] = info.packageName; 18662 packageUids[i] = info.uid; 18663 } 18664 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18665 finishedReceiver); 18666 } 18667 18668 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18669 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18670 sendResourcesChangedBroadcast(mediaStatus, replacing, 18671 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18672 } 18673 18674 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18675 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18676 int size = pkgList.length; 18677 if (size > 0) { 18678 // Send broadcasts here 18679 Bundle extras = new Bundle(); 18680 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18681 if (uidArr != null) { 18682 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18683 } 18684 if (replacing) { 18685 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18686 } 18687 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18688 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18689 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18690 } 18691 } 18692 18693 /* 18694 * Look at potentially valid container ids from processCids If package 18695 * information doesn't match the one on record or package scanning fails, 18696 * the cid is added to list of removeCids. We currently don't delete stale 18697 * containers. 18698 */ 18699 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18700 boolean externalStorage) { 18701 ArrayList<String> pkgList = new ArrayList<String>(); 18702 Set<AsecInstallArgs> keys = processCids.keySet(); 18703 18704 for (AsecInstallArgs args : keys) { 18705 String codePath = processCids.get(args); 18706 if (DEBUG_SD_INSTALL) 18707 Log.i(TAG, "Loading container : " + args.cid); 18708 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18709 try { 18710 // Make sure there are no container errors first. 18711 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18712 Slog.e(TAG, "Failed to mount cid : " + args.cid 18713 + " when installing from sdcard"); 18714 continue; 18715 } 18716 // Check code path here. 18717 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18718 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18719 + " does not match one in settings " + codePath); 18720 continue; 18721 } 18722 // Parse package 18723 int parseFlags = mDefParseFlags; 18724 if (args.isExternalAsec()) { 18725 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18726 } 18727 if (args.isFwdLocked()) { 18728 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18729 } 18730 18731 synchronized (mInstallLock) { 18732 PackageParser.Package pkg = null; 18733 try { 18734 // Sadly we don't know the package name yet to freeze it 18735 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18736 SCAN_IGNORE_FROZEN, 0, null); 18737 } catch (PackageManagerException e) { 18738 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18739 } 18740 // Scan the package 18741 if (pkg != null) { 18742 /* 18743 * TODO why is the lock being held? doPostInstall is 18744 * called in other places without the lock. This needs 18745 * to be straightened out. 18746 */ 18747 // writer 18748 synchronized (mPackages) { 18749 retCode = PackageManager.INSTALL_SUCCEEDED; 18750 pkgList.add(pkg.packageName); 18751 // Post process args 18752 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18753 pkg.applicationInfo.uid); 18754 } 18755 } else { 18756 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18757 } 18758 } 18759 18760 } finally { 18761 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18762 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18763 } 18764 } 18765 } 18766 // writer 18767 synchronized (mPackages) { 18768 // If the platform SDK has changed since the last time we booted, 18769 // we need to re-grant app permission to catch any new ones that 18770 // appear. This is really a hack, and means that apps can in some 18771 // cases get permissions that the user didn't initially explicitly 18772 // allow... it would be nice to have some better way to handle 18773 // this situation. 18774 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18775 : mSettings.getInternalVersion(); 18776 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18777 : StorageManager.UUID_PRIVATE_INTERNAL; 18778 18779 int updateFlags = UPDATE_PERMISSIONS_ALL; 18780 if (ver.sdkVersion != mSdkVersion) { 18781 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18782 + mSdkVersion + "; regranting permissions for external"); 18783 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18784 } 18785 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18786 18787 // Yay, everything is now upgraded 18788 ver.forceCurrent(); 18789 18790 // can downgrade to reader 18791 // Persist settings 18792 mSettings.writeLPr(); 18793 } 18794 // Send a broadcast to let everyone know we are done processing 18795 if (pkgList.size() > 0) { 18796 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18797 } 18798 } 18799 18800 /* 18801 * Utility method to unload a list of specified containers 18802 */ 18803 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18804 // Just unmount all valid containers. 18805 for (AsecInstallArgs arg : cidArgs) { 18806 synchronized (mInstallLock) { 18807 arg.doPostDeleteLI(false); 18808 } 18809 } 18810 } 18811 18812 /* 18813 * Unload packages mounted on external media. This involves deleting package 18814 * data from internal structures, sending broadcasts about disabled packages, 18815 * gc'ing to free up references, unmounting all secure containers 18816 * corresponding to packages on external media, and posting a 18817 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18818 * that we always have to post this message if status has been requested no 18819 * matter what. 18820 */ 18821 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18822 final boolean reportStatus) { 18823 if (DEBUG_SD_INSTALL) 18824 Log.i(TAG, "unloading media packages"); 18825 ArrayList<String> pkgList = new ArrayList<String>(); 18826 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18827 final Set<AsecInstallArgs> keys = processCids.keySet(); 18828 for (AsecInstallArgs args : keys) { 18829 String pkgName = args.getPackageName(); 18830 if (DEBUG_SD_INSTALL) 18831 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18832 // Delete package internally 18833 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18834 synchronized (mInstallLock) { 18835 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18836 final boolean res; 18837 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18838 "unloadMediaPackages")) { 18839 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18840 null); 18841 } 18842 if (res) { 18843 pkgList.add(pkgName); 18844 } else { 18845 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18846 failedList.add(args); 18847 } 18848 } 18849 } 18850 18851 // reader 18852 synchronized (mPackages) { 18853 // We didn't update the settings after removing each package; 18854 // write them now for all packages. 18855 mSettings.writeLPr(); 18856 } 18857 18858 // We have to absolutely send UPDATED_MEDIA_STATUS only 18859 // after confirming that all the receivers processed the ordered 18860 // broadcast when packages get disabled, force a gc to clean things up. 18861 // and unload all the containers. 18862 if (pkgList.size() > 0) { 18863 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18864 new IIntentReceiver.Stub() { 18865 public void performReceive(Intent intent, int resultCode, String data, 18866 Bundle extras, boolean ordered, boolean sticky, 18867 int sendingUser) throws RemoteException { 18868 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18869 reportStatus ? 1 : 0, 1, keys); 18870 mHandler.sendMessage(msg); 18871 } 18872 }); 18873 } else { 18874 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18875 keys); 18876 mHandler.sendMessage(msg); 18877 } 18878 } 18879 18880 private void loadPrivatePackages(final VolumeInfo vol) { 18881 mHandler.post(new Runnable() { 18882 @Override 18883 public void run() { 18884 loadPrivatePackagesInner(vol); 18885 } 18886 }); 18887 } 18888 18889 private void loadPrivatePackagesInner(VolumeInfo vol) { 18890 final String volumeUuid = vol.fsUuid; 18891 if (TextUtils.isEmpty(volumeUuid)) { 18892 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18893 return; 18894 } 18895 18896 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18897 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18898 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18899 18900 final VersionInfo ver; 18901 final List<PackageSetting> packages; 18902 synchronized (mPackages) { 18903 ver = mSettings.findOrCreateVersion(volumeUuid); 18904 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18905 } 18906 18907 for (PackageSetting ps : packages) { 18908 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18909 synchronized (mInstallLock) { 18910 final PackageParser.Package pkg; 18911 try { 18912 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18913 loaded.add(pkg.applicationInfo); 18914 18915 } catch (PackageManagerException e) { 18916 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18917 } 18918 18919 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18920 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18921 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18922 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18923 } 18924 } 18925 } 18926 18927 // Reconcile app data for all started/unlocked users 18928 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18929 final UserManager um = mContext.getSystemService(UserManager.class); 18930 for (UserInfo user : um.getUsers()) { 18931 final int flags; 18932 if (um.isUserUnlockingOrUnlocked(user.id)) { 18933 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18934 } else if (um.isUserRunning(user.id)) { 18935 flags = StorageManager.FLAG_STORAGE_DE; 18936 } else { 18937 continue; 18938 } 18939 18940 try { 18941 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18942 synchronized (mInstallLock) { 18943 reconcileAppsDataLI(volumeUuid, user.id, flags); 18944 } 18945 } catch (IllegalStateException e) { 18946 // Device was probably ejected, and we'll process that event momentarily 18947 Slog.w(TAG, "Failed to prepare storage: " + e); 18948 } 18949 } 18950 18951 synchronized (mPackages) { 18952 int updateFlags = UPDATE_PERMISSIONS_ALL; 18953 if (ver.sdkVersion != mSdkVersion) { 18954 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18955 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18956 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18957 } 18958 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18959 18960 // Yay, everything is now upgraded 18961 ver.forceCurrent(); 18962 18963 mSettings.writeLPr(); 18964 } 18965 18966 for (PackageFreezer freezer : freezers) { 18967 freezer.close(); 18968 } 18969 18970 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18971 sendResourcesChangedBroadcast(true, false, loaded, null); 18972 } 18973 18974 private void unloadPrivatePackages(final VolumeInfo vol) { 18975 mHandler.post(new Runnable() { 18976 @Override 18977 public void run() { 18978 unloadPrivatePackagesInner(vol); 18979 } 18980 }); 18981 } 18982 18983 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18984 final String volumeUuid = vol.fsUuid; 18985 if (TextUtils.isEmpty(volumeUuid)) { 18986 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18987 return; 18988 } 18989 18990 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18991 synchronized (mInstallLock) { 18992 synchronized (mPackages) { 18993 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18994 for (PackageSetting ps : packages) { 18995 if (ps.pkg == null) continue; 18996 18997 final ApplicationInfo info = ps.pkg.applicationInfo; 18998 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18999 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19000 19001 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19002 "unloadPrivatePackagesInner")) { 19003 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19004 false, null)) { 19005 unloaded.add(info); 19006 } else { 19007 Slog.w(TAG, "Failed to unload " + ps.codePath); 19008 } 19009 } 19010 } 19011 19012 mSettings.writeLPr(); 19013 } 19014 } 19015 19016 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19017 sendResourcesChangedBroadcast(false, false, unloaded, null); 19018 } 19019 19020 /** 19021 * Prepare storage areas for given user on all mounted devices. 19022 */ 19023 void prepareUserData(int userId, int userSerial, int flags) { 19024 synchronized (mInstallLock) { 19025 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19026 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19027 final String volumeUuid = vol.getFsUuid(); 19028 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19029 } 19030 } 19031 } 19032 19033 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19034 boolean allowRecover) { 19035 // Prepare storage and verify that serial numbers are consistent; if 19036 // there's a mismatch we need to destroy to avoid leaking data 19037 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19038 try { 19039 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19040 19041 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19042 UserManagerService.enforceSerialNumber( 19043 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19044 } 19045 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19046 UserManagerService.enforceSerialNumber( 19047 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19048 } 19049 19050 synchronized (mInstallLock) { 19051 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19052 } 19053 } catch (Exception e) { 19054 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19055 + " because we failed to prepare: " + e); 19056 destroyUserDataLI(volumeUuid, userId, 19057 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19058 19059 if (allowRecover) { 19060 // Try one last time; if we fail again we're really in trouble 19061 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19062 } 19063 } 19064 } 19065 19066 /** 19067 * Destroy storage areas for given user on all mounted devices. 19068 */ 19069 void destroyUserData(int userId, int flags) { 19070 synchronized (mInstallLock) { 19071 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19072 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19073 final String volumeUuid = vol.getFsUuid(); 19074 destroyUserDataLI(volumeUuid, userId, flags); 19075 } 19076 } 19077 } 19078 19079 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19080 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19081 try { 19082 // Clean up app data, profile data, and media data 19083 mInstaller.destroyUserData(volumeUuid, userId, flags); 19084 19085 // Clean up system data 19086 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19087 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19088 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19089 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19090 } 19091 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19092 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19093 } 19094 } 19095 19096 // Data with special labels is now gone, so finish the job 19097 storage.destroyUserStorage(volumeUuid, userId, flags); 19098 19099 } catch (Exception e) { 19100 logCriticalInfo(Log.WARN, 19101 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19102 } 19103 } 19104 19105 /** 19106 * Examine all users present on given mounted volume, and destroy data 19107 * belonging to users that are no longer valid, or whose user ID has been 19108 * recycled. 19109 */ 19110 private void reconcileUsers(String volumeUuid) { 19111 final List<File> files = new ArrayList<>(); 19112 Collections.addAll(files, FileUtils 19113 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19114 Collections.addAll(files, FileUtils 19115 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19116 for (File file : files) { 19117 if (!file.isDirectory()) continue; 19118 19119 final int userId; 19120 final UserInfo info; 19121 try { 19122 userId = Integer.parseInt(file.getName()); 19123 info = sUserManager.getUserInfo(userId); 19124 } catch (NumberFormatException e) { 19125 Slog.w(TAG, "Invalid user directory " + file); 19126 continue; 19127 } 19128 19129 boolean destroyUser = false; 19130 if (info == null) { 19131 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19132 + " because no matching user was found"); 19133 destroyUser = true; 19134 } else if (!mOnlyCore) { 19135 try { 19136 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19137 } catch (IOException e) { 19138 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19139 + " because we failed to enforce serial number: " + e); 19140 destroyUser = true; 19141 } 19142 } 19143 19144 if (destroyUser) { 19145 synchronized (mInstallLock) { 19146 destroyUserDataLI(volumeUuid, userId, 19147 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19148 } 19149 } 19150 } 19151 } 19152 19153 private void assertPackageKnown(String volumeUuid, String packageName) 19154 throws PackageManagerException { 19155 synchronized (mPackages) { 19156 final PackageSetting ps = mSettings.mPackages.get(packageName); 19157 if (ps == null) { 19158 throw new PackageManagerException("Package " + packageName + " is unknown"); 19159 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19160 throw new PackageManagerException( 19161 "Package " + packageName + " found on unknown volume " + volumeUuid 19162 + "; expected volume " + ps.volumeUuid); 19163 } 19164 } 19165 } 19166 19167 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19168 throws PackageManagerException { 19169 synchronized (mPackages) { 19170 final PackageSetting ps = mSettings.mPackages.get(packageName); 19171 if (ps == null) { 19172 throw new PackageManagerException("Package " + packageName + " is unknown"); 19173 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19174 throw new PackageManagerException( 19175 "Package " + packageName + " found on unknown volume " + volumeUuid 19176 + "; expected volume " + ps.volumeUuid); 19177 } else if (!ps.getInstalled(userId)) { 19178 throw new PackageManagerException( 19179 "Package " + packageName + " not installed for user " + userId); 19180 } 19181 } 19182 } 19183 19184 /** 19185 * Examine all apps present on given mounted volume, and destroy apps that 19186 * aren't expected, either due to uninstallation or reinstallation on 19187 * another volume. 19188 */ 19189 private void reconcileApps(String volumeUuid) { 19190 final File[] files = FileUtils 19191 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19192 for (File file : files) { 19193 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19194 && !PackageInstallerService.isStageName(file.getName()); 19195 if (!isPackage) { 19196 // Ignore entries which are not packages 19197 continue; 19198 } 19199 19200 try { 19201 final PackageLite pkg = PackageParser.parsePackageLite(file, 19202 PackageParser.PARSE_MUST_BE_APK); 19203 assertPackageKnown(volumeUuid, pkg.packageName); 19204 19205 } catch (PackageParserException | PackageManagerException e) { 19206 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19207 synchronized (mInstallLock) { 19208 removeCodePathLI(file); 19209 } 19210 } 19211 } 19212 } 19213 19214 /** 19215 * Reconcile all app data for the given user. 19216 * <p> 19217 * Verifies that directories exist and that ownership and labeling is 19218 * correct for all installed apps on all mounted volumes. 19219 */ 19220 void reconcileAppsData(int userId, int flags) { 19221 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19222 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19223 final String volumeUuid = vol.getFsUuid(); 19224 synchronized (mInstallLock) { 19225 reconcileAppsDataLI(volumeUuid, userId, flags); 19226 } 19227 } 19228 } 19229 19230 /** 19231 * Reconcile all app data on given mounted volume. 19232 * <p> 19233 * Destroys app data that isn't expected, either due to uninstallation or 19234 * reinstallation on another volume. 19235 * <p> 19236 * Verifies that directories exist and that ownership and labeling is 19237 * correct for all installed apps. 19238 */ 19239 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19240 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19241 + Integer.toHexString(flags)); 19242 19243 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19244 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19245 19246 boolean restoreconNeeded = false; 19247 19248 // First look for stale data that doesn't belong, and check if things 19249 // have changed since we did our last restorecon 19250 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19251 if (StorageManager.isFileEncryptedNativeOrEmulated() 19252 && !StorageManager.isUserKeyUnlocked(userId)) { 19253 throw new RuntimeException( 19254 "Yikes, someone asked us to reconcile CE storage while " + userId 19255 + " was still locked; this would have caused massive data loss!"); 19256 } 19257 19258 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19259 19260 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19261 for (File file : files) { 19262 final String packageName = file.getName(); 19263 try { 19264 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19265 } catch (PackageManagerException e) { 19266 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19267 try { 19268 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19269 StorageManager.FLAG_STORAGE_CE, 0); 19270 } catch (InstallerException e2) { 19271 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19272 } 19273 } 19274 } 19275 } 19276 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19277 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19278 19279 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19280 for (File file : files) { 19281 final String packageName = file.getName(); 19282 try { 19283 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19284 } catch (PackageManagerException e) { 19285 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19286 try { 19287 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19288 StorageManager.FLAG_STORAGE_DE, 0); 19289 } catch (InstallerException e2) { 19290 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19291 } 19292 } 19293 } 19294 } 19295 19296 // Ensure that data directories are ready to roll for all packages 19297 // installed for this volume and user 19298 final List<PackageSetting> packages; 19299 synchronized (mPackages) { 19300 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19301 } 19302 int preparedCount = 0; 19303 for (PackageSetting ps : packages) { 19304 final String packageName = ps.name; 19305 if (ps.pkg == null) { 19306 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19307 // TODO: might be due to legacy ASEC apps; we should circle back 19308 // and reconcile again once they're scanned 19309 continue; 19310 } 19311 19312 if (ps.getInstalled(userId)) { 19313 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19314 19315 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19316 // We may have just shuffled around app data directories, so 19317 // prepare them one more time 19318 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19319 } 19320 19321 preparedCount++; 19322 } 19323 } 19324 19325 if (restoreconNeeded) { 19326 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19327 SELinuxMMAC.setRestoreconDone(ceDir); 19328 } 19329 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19330 SELinuxMMAC.setRestoreconDone(deDir); 19331 } 19332 } 19333 19334 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19335 + " packages; restoreconNeeded was " + restoreconNeeded); 19336 } 19337 19338 /** 19339 * Prepare app data for the given app just after it was installed or 19340 * upgraded. This method carefully only touches users that it's installed 19341 * for, and it forces a restorecon to handle any seinfo changes. 19342 * <p> 19343 * Verifies that directories exist and that ownership and labeling is 19344 * correct for all installed apps. If there is an ownership mismatch, it 19345 * will try recovering system apps by wiping data; third-party app data is 19346 * left intact. 19347 * <p> 19348 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19349 */ 19350 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19351 final PackageSetting ps; 19352 synchronized (mPackages) { 19353 ps = mSettings.mPackages.get(pkg.packageName); 19354 mSettings.writeKernelMappingLPr(ps); 19355 } 19356 19357 final UserManager um = mContext.getSystemService(UserManager.class); 19358 for (UserInfo user : um.getUsers()) { 19359 final int flags; 19360 if (um.isUserUnlockingOrUnlocked(user.id)) { 19361 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19362 } else if (um.isUserRunning(user.id)) { 19363 flags = StorageManager.FLAG_STORAGE_DE; 19364 } else { 19365 continue; 19366 } 19367 19368 if (ps.getInstalled(user.id)) { 19369 // Whenever an app changes, force a restorecon of its data 19370 // TODO: when user data is locked, mark that we're still dirty 19371 prepareAppDataLIF(pkg, user.id, flags, true); 19372 } 19373 } 19374 } 19375 19376 /** 19377 * Prepare app data for the given app. 19378 * <p> 19379 * Verifies that directories exist and that ownership and labeling is 19380 * correct for all installed apps. If there is an ownership mismatch, this 19381 * will try recovering system apps by wiping data; third-party app data is 19382 * left intact. 19383 */ 19384 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19385 boolean restoreconNeeded) { 19386 if (pkg == null) { 19387 Slog.wtf(TAG, "Package was null!", new Throwable()); 19388 return; 19389 } 19390 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19391 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19392 for (int i = 0; i < childCount; i++) { 19393 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19394 } 19395 } 19396 19397 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19398 boolean restoreconNeeded) { 19399 if (DEBUG_APP_DATA) { 19400 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19401 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19402 } 19403 19404 final String volumeUuid = pkg.volumeUuid; 19405 final String packageName = pkg.packageName; 19406 final ApplicationInfo app = pkg.applicationInfo; 19407 final int appId = UserHandle.getAppId(app.uid); 19408 19409 Preconditions.checkNotNull(app.seinfo); 19410 19411 try { 19412 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19413 appId, app.seinfo, app.targetSdkVersion); 19414 } catch (InstallerException e) { 19415 if (app.isSystemApp()) { 19416 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19417 + ", but trying to recover: " + e); 19418 destroyAppDataLeafLIF(pkg, userId, flags); 19419 try { 19420 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19421 appId, app.seinfo, app.targetSdkVersion); 19422 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19423 } catch (InstallerException e2) { 19424 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19425 } 19426 } else { 19427 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19428 } 19429 } 19430 19431 if (restoreconNeeded) { 19432 try { 19433 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19434 app.seinfo); 19435 } catch (InstallerException e) { 19436 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19437 } 19438 } 19439 19440 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19441 try { 19442 // CE storage is unlocked right now, so read out the inode and 19443 // remember for use later when it's locked 19444 // TODO: mark this structure as dirty so we persist it! 19445 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19446 StorageManager.FLAG_STORAGE_CE); 19447 synchronized (mPackages) { 19448 final PackageSetting ps = mSettings.mPackages.get(packageName); 19449 if (ps != null) { 19450 ps.setCeDataInode(ceDataInode, userId); 19451 } 19452 } 19453 } catch (InstallerException e) { 19454 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19455 } 19456 } 19457 19458 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19459 } 19460 19461 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19462 if (pkg == null) { 19463 Slog.wtf(TAG, "Package was null!", new Throwable()); 19464 return; 19465 } 19466 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19467 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19468 for (int i = 0; i < childCount; i++) { 19469 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19470 } 19471 } 19472 19473 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19474 final String volumeUuid = pkg.volumeUuid; 19475 final String packageName = pkg.packageName; 19476 final ApplicationInfo app = pkg.applicationInfo; 19477 19478 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19479 // Create a native library symlink only if we have native libraries 19480 // and if the native libraries are 32 bit libraries. We do not provide 19481 // this symlink for 64 bit libraries. 19482 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19483 final String nativeLibPath = app.nativeLibraryDir; 19484 try { 19485 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19486 nativeLibPath, userId); 19487 } catch (InstallerException e) { 19488 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19489 } 19490 } 19491 } 19492 } 19493 19494 /** 19495 * For system apps on non-FBE devices, this method migrates any existing 19496 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19497 * requested by the app. 19498 */ 19499 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19500 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19501 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19502 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19503 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19504 try { 19505 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19506 storageTarget); 19507 } catch (InstallerException e) { 19508 logCriticalInfo(Log.WARN, 19509 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19510 } 19511 return true; 19512 } else { 19513 return false; 19514 } 19515 } 19516 19517 public PackageFreezer freezePackage(String packageName, String killReason) { 19518 return new PackageFreezer(packageName, killReason); 19519 } 19520 19521 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19522 String killReason) { 19523 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19524 return new PackageFreezer(); 19525 } else { 19526 return freezePackage(packageName, killReason); 19527 } 19528 } 19529 19530 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19531 String killReason) { 19532 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19533 return new PackageFreezer(); 19534 } else { 19535 return freezePackage(packageName, killReason); 19536 } 19537 } 19538 19539 /** 19540 * Class that freezes and kills the given package upon creation, and 19541 * unfreezes it upon closing. This is typically used when doing surgery on 19542 * app code/data to prevent the app from running while you're working. 19543 */ 19544 private class PackageFreezer implements AutoCloseable { 19545 private final String mPackageName; 19546 private final PackageFreezer[] mChildren; 19547 19548 private final boolean mWeFroze; 19549 19550 private final AtomicBoolean mClosed = new AtomicBoolean(); 19551 private final CloseGuard mCloseGuard = CloseGuard.get(); 19552 19553 /** 19554 * Create and return a stub freezer that doesn't actually do anything, 19555 * typically used when someone requested 19556 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19557 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19558 */ 19559 public PackageFreezer() { 19560 mPackageName = null; 19561 mChildren = null; 19562 mWeFroze = false; 19563 mCloseGuard.open("close"); 19564 } 19565 19566 public PackageFreezer(String packageName, String killReason) { 19567 synchronized (mPackages) { 19568 mPackageName = packageName; 19569 mWeFroze = mFrozenPackages.add(mPackageName); 19570 19571 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19572 if (ps != null) { 19573 killApplication(ps.name, ps.appId, killReason); 19574 } 19575 19576 final PackageParser.Package p = mPackages.get(packageName); 19577 if (p != null && p.childPackages != null) { 19578 final int N = p.childPackages.size(); 19579 mChildren = new PackageFreezer[N]; 19580 for (int i = 0; i < N; i++) { 19581 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19582 killReason); 19583 } 19584 } else { 19585 mChildren = null; 19586 } 19587 } 19588 mCloseGuard.open("close"); 19589 } 19590 19591 @Override 19592 protected void finalize() throws Throwable { 19593 try { 19594 mCloseGuard.warnIfOpen(); 19595 close(); 19596 } finally { 19597 super.finalize(); 19598 } 19599 } 19600 19601 @Override 19602 public void close() { 19603 mCloseGuard.close(); 19604 if (mClosed.compareAndSet(false, true)) { 19605 synchronized (mPackages) { 19606 if (mWeFroze) { 19607 mFrozenPackages.remove(mPackageName); 19608 } 19609 19610 if (mChildren != null) { 19611 for (PackageFreezer freezer : mChildren) { 19612 freezer.close(); 19613 } 19614 } 19615 } 19616 } 19617 } 19618 } 19619 19620 /** 19621 * Verify that given package is currently frozen. 19622 */ 19623 private void checkPackageFrozen(String packageName) { 19624 synchronized (mPackages) { 19625 if (!mFrozenPackages.contains(packageName)) { 19626 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19627 } 19628 } 19629 } 19630 19631 @Override 19632 public int movePackage(final String packageName, final String volumeUuid) { 19633 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19634 19635 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19636 final int moveId = mNextMoveId.getAndIncrement(); 19637 mHandler.post(new Runnable() { 19638 @Override 19639 public void run() { 19640 try { 19641 movePackageInternal(packageName, volumeUuid, moveId, user); 19642 } catch (PackageManagerException e) { 19643 Slog.w(TAG, "Failed to move " + packageName, e); 19644 mMoveCallbacks.notifyStatusChanged(moveId, 19645 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19646 } 19647 } 19648 }); 19649 return moveId; 19650 } 19651 19652 private void movePackageInternal(final String packageName, final String volumeUuid, 19653 final int moveId, UserHandle user) throws PackageManagerException { 19654 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19655 final PackageManager pm = mContext.getPackageManager(); 19656 19657 final boolean currentAsec; 19658 final String currentVolumeUuid; 19659 final File codeFile; 19660 final String installerPackageName; 19661 final String packageAbiOverride; 19662 final int appId; 19663 final String seinfo; 19664 final String label; 19665 final int targetSdkVersion; 19666 final PackageFreezer freezer; 19667 final int[] installedUserIds; 19668 19669 // reader 19670 synchronized (mPackages) { 19671 final PackageParser.Package pkg = mPackages.get(packageName); 19672 final PackageSetting ps = mSettings.mPackages.get(packageName); 19673 if (pkg == null || ps == null) { 19674 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19675 } 19676 19677 if (pkg.applicationInfo.isSystemApp()) { 19678 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19679 "Cannot move system application"); 19680 } 19681 19682 if (pkg.applicationInfo.isExternalAsec()) { 19683 currentAsec = true; 19684 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19685 } else if (pkg.applicationInfo.isForwardLocked()) { 19686 currentAsec = true; 19687 currentVolumeUuid = "forward_locked"; 19688 } else { 19689 currentAsec = false; 19690 currentVolumeUuid = ps.volumeUuid; 19691 19692 final File probe = new File(pkg.codePath); 19693 final File probeOat = new File(probe, "oat"); 19694 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19695 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19696 "Move only supported for modern cluster style installs"); 19697 } 19698 } 19699 19700 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19701 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19702 "Package already moved to " + volumeUuid); 19703 } 19704 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19705 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19706 "Device admin cannot be moved"); 19707 } 19708 19709 if (mFrozenPackages.contains(packageName)) { 19710 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19711 "Failed to move already frozen package"); 19712 } 19713 19714 codeFile = new File(pkg.codePath); 19715 installerPackageName = ps.installerPackageName; 19716 packageAbiOverride = ps.cpuAbiOverrideString; 19717 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19718 seinfo = pkg.applicationInfo.seinfo; 19719 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19720 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19721 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19722 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19723 } 19724 19725 final Bundle extras = new Bundle(); 19726 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19727 extras.putString(Intent.EXTRA_TITLE, label); 19728 mMoveCallbacks.notifyCreated(moveId, extras); 19729 19730 int installFlags; 19731 final boolean moveCompleteApp; 19732 final File measurePath; 19733 19734 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19735 installFlags = INSTALL_INTERNAL; 19736 moveCompleteApp = !currentAsec; 19737 measurePath = Environment.getDataAppDirectory(volumeUuid); 19738 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19739 installFlags = INSTALL_EXTERNAL; 19740 moveCompleteApp = false; 19741 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19742 } else { 19743 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19744 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19745 || !volume.isMountedWritable()) { 19746 freezer.close(); 19747 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19748 "Move location not mounted private volume"); 19749 } 19750 19751 Preconditions.checkState(!currentAsec); 19752 19753 installFlags = INSTALL_INTERNAL; 19754 moveCompleteApp = true; 19755 measurePath = Environment.getDataAppDirectory(volumeUuid); 19756 } 19757 19758 final PackageStats stats = new PackageStats(null, -1); 19759 synchronized (mInstaller) { 19760 for (int userId : installedUserIds) { 19761 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19762 freezer.close(); 19763 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19764 "Failed to measure package size"); 19765 } 19766 } 19767 } 19768 19769 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19770 + stats.dataSize); 19771 19772 final long startFreeBytes = measurePath.getFreeSpace(); 19773 final long sizeBytes; 19774 if (moveCompleteApp) { 19775 sizeBytes = stats.codeSize + stats.dataSize; 19776 } else { 19777 sizeBytes = stats.codeSize; 19778 } 19779 19780 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19781 freezer.close(); 19782 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19783 "Not enough free space to move"); 19784 } 19785 19786 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19787 19788 final CountDownLatch installedLatch = new CountDownLatch(1); 19789 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19790 @Override 19791 public void onUserActionRequired(Intent intent) throws RemoteException { 19792 throw new IllegalStateException(); 19793 } 19794 19795 @Override 19796 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19797 Bundle extras) throws RemoteException { 19798 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19799 + PackageManager.installStatusToString(returnCode, msg)); 19800 19801 installedLatch.countDown(); 19802 freezer.close(); 19803 19804 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19805 switch (status) { 19806 case PackageInstaller.STATUS_SUCCESS: 19807 mMoveCallbacks.notifyStatusChanged(moveId, 19808 PackageManager.MOVE_SUCCEEDED); 19809 break; 19810 case PackageInstaller.STATUS_FAILURE_STORAGE: 19811 mMoveCallbacks.notifyStatusChanged(moveId, 19812 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19813 break; 19814 default: 19815 mMoveCallbacks.notifyStatusChanged(moveId, 19816 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19817 break; 19818 } 19819 } 19820 }; 19821 19822 final MoveInfo move; 19823 if (moveCompleteApp) { 19824 // Kick off a thread to report progress estimates 19825 new Thread() { 19826 @Override 19827 public void run() { 19828 while (true) { 19829 try { 19830 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19831 break; 19832 } 19833 } catch (InterruptedException ignored) { 19834 } 19835 19836 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19837 final int progress = 10 + (int) MathUtils.constrain( 19838 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19839 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19840 } 19841 } 19842 }.start(); 19843 19844 final String dataAppName = codeFile.getName(); 19845 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19846 dataAppName, appId, seinfo, targetSdkVersion); 19847 } else { 19848 move = null; 19849 } 19850 19851 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19852 19853 final Message msg = mHandler.obtainMessage(INIT_COPY); 19854 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19855 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19856 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19857 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19858 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19859 msg.obj = params; 19860 19861 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19862 System.identityHashCode(msg.obj)); 19863 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19864 System.identityHashCode(msg.obj)); 19865 19866 mHandler.sendMessage(msg); 19867 } 19868 19869 @Override 19870 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19871 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19872 19873 final int realMoveId = mNextMoveId.getAndIncrement(); 19874 final Bundle extras = new Bundle(); 19875 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19876 mMoveCallbacks.notifyCreated(realMoveId, extras); 19877 19878 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19879 @Override 19880 public void onCreated(int moveId, Bundle extras) { 19881 // Ignored 19882 } 19883 19884 @Override 19885 public void onStatusChanged(int moveId, int status, long estMillis) { 19886 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19887 } 19888 }; 19889 19890 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19891 storage.setPrimaryStorageUuid(volumeUuid, callback); 19892 return realMoveId; 19893 } 19894 19895 @Override 19896 public int getMoveStatus(int moveId) { 19897 mContext.enforceCallingOrSelfPermission( 19898 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19899 return mMoveCallbacks.mLastStatus.get(moveId); 19900 } 19901 19902 @Override 19903 public void registerMoveCallback(IPackageMoveObserver callback) { 19904 mContext.enforceCallingOrSelfPermission( 19905 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19906 mMoveCallbacks.register(callback); 19907 } 19908 19909 @Override 19910 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19911 mContext.enforceCallingOrSelfPermission( 19912 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19913 mMoveCallbacks.unregister(callback); 19914 } 19915 19916 @Override 19917 public boolean setInstallLocation(int loc) { 19918 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19919 null); 19920 if (getInstallLocation() == loc) { 19921 return true; 19922 } 19923 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19924 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19925 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19926 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19927 return true; 19928 } 19929 return false; 19930 } 19931 19932 @Override 19933 public int getInstallLocation() { 19934 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19935 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19936 PackageHelper.APP_INSTALL_AUTO); 19937 } 19938 19939 /** Called by UserManagerService */ 19940 void cleanUpUser(UserManagerService userManager, int userHandle) { 19941 synchronized (mPackages) { 19942 mDirtyUsers.remove(userHandle); 19943 mUserNeedsBadging.delete(userHandle); 19944 mSettings.removeUserLPw(userHandle); 19945 mPendingBroadcasts.remove(userHandle); 19946 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19947 removeUnusedPackagesLPw(userManager, userHandle); 19948 } 19949 } 19950 19951 /** 19952 * We're removing userHandle and would like to remove any downloaded packages 19953 * that are no longer in use by any other user. 19954 * @param userHandle the user being removed 19955 */ 19956 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19957 final boolean DEBUG_CLEAN_APKS = false; 19958 int [] users = userManager.getUserIds(); 19959 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19960 while (psit.hasNext()) { 19961 PackageSetting ps = psit.next(); 19962 if (ps.pkg == null) { 19963 continue; 19964 } 19965 final String packageName = ps.pkg.packageName; 19966 // Skip over if system app 19967 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19968 continue; 19969 } 19970 if (DEBUG_CLEAN_APKS) { 19971 Slog.i(TAG, "Checking package " + packageName); 19972 } 19973 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19974 if (keep) { 19975 if (DEBUG_CLEAN_APKS) { 19976 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19977 } 19978 } else { 19979 for (int i = 0; i < users.length; i++) { 19980 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19981 keep = true; 19982 if (DEBUG_CLEAN_APKS) { 19983 Slog.i(TAG, " Keeping package " + packageName + " for user " 19984 + users[i]); 19985 } 19986 break; 19987 } 19988 } 19989 } 19990 if (!keep) { 19991 if (DEBUG_CLEAN_APKS) { 19992 Slog.i(TAG, " Removing package " + packageName); 19993 } 19994 mHandler.post(new Runnable() { 19995 public void run() { 19996 deletePackageX(packageName, userHandle, 0); 19997 } //end run 19998 }); 19999 } 20000 } 20001 } 20002 20003 /** Called by UserManagerService */ 20004 void createNewUser(int userHandle) { 20005 synchronized (mInstallLock) { 20006 mSettings.createNewUserLI(this, mInstaller, userHandle); 20007 } 20008 synchronized (mPackages) { 20009 applyFactoryDefaultBrowserLPw(userHandle); 20010 primeDomainVerificationsLPw(userHandle); 20011 } 20012 } 20013 20014 void newUserCreated(final int userHandle) { 20015 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20016 // If permission review for legacy apps is required, we represent 20017 // dagerous permissions for such apps as always granted runtime 20018 // permissions to keep per user flag state whether review is needed. 20019 // Hence, if a new user is added we have to propagate dangerous 20020 // permission grants for these legacy apps. 20021 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20022 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20023 | UPDATE_PERMISSIONS_REPLACE_ALL); 20024 } 20025 } 20026 20027 @Override 20028 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20029 mContext.enforceCallingOrSelfPermission( 20030 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20031 "Only package verification agents can read the verifier device identity"); 20032 20033 synchronized (mPackages) { 20034 return mSettings.getVerifierDeviceIdentityLPw(); 20035 } 20036 } 20037 20038 @Override 20039 public void setPermissionEnforced(String permission, boolean enforced) { 20040 // TODO: Now that we no longer change GID for storage, this should to away. 20041 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20042 "setPermissionEnforced"); 20043 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20044 synchronized (mPackages) { 20045 if (mSettings.mReadExternalStorageEnforced == null 20046 || mSettings.mReadExternalStorageEnforced != enforced) { 20047 mSettings.mReadExternalStorageEnforced = enforced; 20048 mSettings.writeLPr(); 20049 } 20050 } 20051 // kill any non-foreground processes so we restart them and 20052 // grant/revoke the GID. 20053 final IActivityManager am = ActivityManagerNative.getDefault(); 20054 if (am != null) { 20055 final long token = Binder.clearCallingIdentity(); 20056 try { 20057 am.killProcessesBelowForeground("setPermissionEnforcement"); 20058 } catch (RemoteException e) { 20059 } finally { 20060 Binder.restoreCallingIdentity(token); 20061 } 20062 } 20063 } else { 20064 throw new IllegalArgumentException("No selective enforcement for " + permission); 20065 } 20066 } 20067 20068 @Override 20069 @Deprecated 20070 public boolean isPermissionEnforced(String permission) { 20071 return true; 20072 } 20073 20074 @Override 20075 public boolean isStorageLow() { 20076 final long token = Binder.clearCallingIdentity(); 20077 try { 20078 final DeviceStorageMonitorInternal 20079 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20080 if (dsm != null) { 20081 return dsm.isMemoryLow(); 20082 } else { 20083 return false; 20084 } 20085 } finally { 20086 Binder.restoreCallingIdentity(token); 20087 } 20088 } 20089 20090 @Override 20091 public IPackageInstaller getPackageInstaller() { 20092 return mInstallerService; 20093 } 20094 20095 private boolean userNeedsBadging(int userId) { 20096 int index = mUserNeedsBadging.indexOfKey(userId); 20097 if (index < 0) { 20098 final UserInfo userInfo; 20099 final long token = Binder.clearCallingIdentity(); 20100 try { 20101 userInfo = sUserManager.getUserInfo(userId); 20102 } finally { 20103 Binder.restoreCallingIdentity(token); 20104 } 20105 final boolean b; 20106 if (userInfo != null && userInfo.isManagedProfile()) { 20107 b = true; 20108 } else { 20109 b = false; 20110 } 20111 mUserNeedsBadging.put(userId, b); 20112 return b; 20113 } 20114 return mUserNeedsBadging.valueAt(index); 20115 } 20116 20117 @Override 20118 public KeySet getKeySetByAlias(String packageName, String alias) { 20119 if (packageName == null || alias == null) { 20120 return null; 20121 } 20122 synchronized(mPackages) { 20123 final PackageParser.Package pkg = mPackages.get(packageName); 20124 if (pkg == null) { 20125 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20126 throw new IllegalArgumentException("Unknown package: " + packageName); 20127 } 20128 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20129 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20130 } 20131 } 20132 20133 @Override 20134 public KeySet getSigningKeySet(String packageName) { 20135 if (packageName == null) { 20136 return null; 20137 } 20138 synchronized(mPackages) { 20139 final PackageParser.Package pkg = mPackages.get(packageName); 20140 if (pkg == null) { 20141 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20142 throw new IllegalArgumentException("Unknown package: " + packageName); 20143 } 20144 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20145 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20146 throw new SecurityException("May not access signing KeySet of other apps."); 20147 } 20148 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20149 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20150 } 20151 } 20152 20153 @Override 20154 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20155 if (packageName == null || ks == null) { 20156 return false; 20157 } 20158 synchronized(mPackages) { 20159 final PackageParser.Package pkg = mPackages.get(packageName); 20160 if (pkg == null) { 20161 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20162 throw new IllegalArgumentException("Unknown package: " + packageName); 20163 } 20164 IBinder ksh = ks.getToken(); 20165 if (ksh instanceof KeySetHandle) { 20166 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20167 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20168 } 20169 return false; 20170 } 20171 } 20172 20173 @Override 20174 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20175 if (packageName == null || ks == null) { 20176 return false; 20177 } 20178 synchronized(mPackages) { 20179 final PackageParser.Package pkg = mPackages.get(packageName); 20180 if (pkg == null) { 20181 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20182 throw new IllegalArgumentException("Unknown package: " + packageName); 20183 } 20184 IBinder ksh = ks.getToken(); 20185 if (ksh instanceof KeySetHandle) { 20186 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20187 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20188 } 20189 return false; 20190 } 20191 } 20192 20193 private void deletePackageIfUnusedLPr(final String packageName) { 20194 PackageSetting ps = mSettings.mPackages.get(packageName); 20195 if (ps == null) { 20196 return; 20197 } 20198 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20199 // TODO Implement atomic delete if package is unused 20200 // It is currently possible that the package will be deleted even if it is installed 20201 // after this method returns. 20202 mHandler.post(new Runnable() { 20203 public void run() { 20204 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20205 } 20206 }); 20207 } 20208 } 20209 20210 /** 20211 * Check and throw if the given before/after packages would be considered a 20212 * downgrade. 20213 */ 20214 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20215 throws PackageManagerException { 20216 if (after.versionCode < before.mVersionCode) { 20217 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20218 "Update version code " + after.versionCode + " is older than current " 20219 + before.mVersionCode); 20220 } else if (after.versionCode == before.mVersionCode) { 20221 if (after.baseRevisionCode < before.baseRevisionCode) { 20222 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20223 "Update base revision code " + after.baseRevisionCode 20224 + " is older than current " + before.baseRevisionCode); 20225 } 20226 20227 if (!ArrayUtils.isEmpty(after.splitNames)) { 20228 for (int i = 0; i < after.splitNames.length; i++) { 20229 final String splitName = after.splitNames[i]; 20230 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20231 if (j != -1) { 20232 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20233 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20234 "Update split " + splitName + " revision code " 20235 + after.splitRevisionCodes[i] + " is older than current " 20236 + before.splitRevisionCodes[j]); 20237 } 20238 } 20239 } 20240 } 20241 } 20242 } 20243 20244 private static class MoveCallbacks extends Handler { 20245 private static final int MSG_CREATED = 1; 20246 private static final int MSG_STATUS_CHANGED = 2; 20247 20248 private final RemoteCallbackList<IPackageMoveObserver> 20249 mCallbacks = new RemoteCallbackList<>(); 20250 20251 private final SparseIntArray mLastStatus = new SparseIntArray(); 20252 20253 public MoveCallbacks(Looper looper) { 20254 super(looper); 20255 } 20256 20257 public void register(IPackageMoveObserver callback) { 20258 mCallbacks.register(callback); 20259 } 20260 20261 public void unregister(IPackageMoveObserver callback) { 20262 mCallbacks.unregister(callback); 20263 } 20264 20265 @Override 20266 public void handleMessage(Message msg) { 20267 final SomeArgs args = (SomeArgs) msg.obj; 20268 final int n = mCallbacks.beginBroadcast(); 20269 for (int i = 0; i < n; i++) { 20270 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20271 try { 20272 invokeCallback(callback, msg.what, args); 20273 } catch (RemoteException ignored) { 20274 } 20275 } 20276 mCallbacks.finishBroadcast(); 20277 args.recycle(); 20278 } 20279 20280 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20281 throws RemoteException { 20282 switch (what) { 20283 case MSG_CREATED: { 20284 callback.onCreated(args.argi1, (Bundle) args.arg2); 20285 break; 20286 } 20287 case MSG_STATUS_CHANGED: { 20288 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20289 break; 20290 } 20291 } 20292 } 20293 20294 private void notifyCreated(int moveId, Bundle extras) { 20295 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20296 20297 final SomeArgs args = SomeArgs.obtain(); 20298 args.argi1 = moveId; 20299 args.arg2 = extras; 20300 obtainMessage(MSG_CREATED, args).sendToTarget(); 20301 } 20302 20303 private void notifyStatusChanged(int moveId, int status) { 20304 notifyStatusChanged(moveId, status, -1); 20305 } 20306 20307 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20308 Slog.v(TAG, "Move " + moveId + " status " + status); 20309 20310 final SomeArgs args = SomeArgs.obtain(); 20311 args.argi1 = moveId; 20312 args.argi2 = status; 20313 args.arg3 = estMillis; 20314 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20315 20316 synchronized (mLastStatus) { 20317 mLastStatus.put(moveId, status); 20318 } 20319 } 20320 } 20321 20322 private final static class OnPermissionChangeListeners extends Handler { 20323 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20324 20325 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20326 new RemoteCallbackList<>(); 20327 20328 public OnPermissionChangeListeners(Looper looper) { 20329 super(looper); 20330 } 20331 20332 @Override 20333 public void handleMessage(Message msg) { 20334 switch (msg.what) { 20335 case MSG_ON_PERMISSIONS_CHANGED: { 20336 final int uid = msg.arg1; 20337 handleOnPermissionsChanged(uid); 20338 } break; 20339 } 20340 } 20341 20342 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20343 mPermissionListeners.register(listener); 20344 20345 } 20346 20347 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20348 mPermissionListeners.unregister(listener); 20349 } 20350 20351 public void onPermissionsChanged(int uid) { 20352 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20353 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20354 } 20355 } 20356 20357 private void handleOnPermissionsChanged(int uid) { 20358 final int count = mPermissionListeners.beginBroadcast(); 20359 try { 20360 for (int i = 0; i < count; i++) { 20361 IOnPermissionsChangeListener callback = mPermissionListeners 20362 .getBroadcastItem(i); 20363 try { 20364 callback.onPermissionsChanged(uid); 20365 } catch (RemoteException e) { 20366 Log.e(TAG, "Permission listener is dead", e); 20367 } 20368 } 20369 } finally { 20370 mPermissionListeners.finishBroadcast(); 20371 } 20372 } 20373 } 20374 20375 private class PackageManagerInternalImpl extends PackageManagerInternal { 20376 @Override 20377 public void setLocationPackagesProvider(PackagesProvider provider) { 20378 synchronized (mPackages) { 20379 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20380 } 20381 } 20382 20383 @Override 20384 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20385 synchronized (mPackages) { 20386 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20387 } 20388 } 20389 20390 @Override 20391 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20392 synchronized (mPackages) { 20393 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20394 } 20395 } 20396 20397 @Override 20398 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20399 synchronized (mPackages) { 20400 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20401 } 20402 } 20403 20404 @Override 20405 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20406 synchronized (mPackages) { 20407 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20408 } 20409 } 20410 20411 @Override 20412 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20413 synchronized (mPackages) { 20414 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20415 } 20416 } 20417 20418 @Override 20419 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20420 synchronized (mPackages) { 20421 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20422 packageName, userId); 20423 } 20424 } 20425 20426 @Override 20427 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20428 synchronized (mPackages) { 20429 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20430 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20431 packageName, userId); 20432 } 20433 } 20434 20435 @Override 20436 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20437 synchronized (mPackages) { 20438 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20439 packageName, userId); 20440 } 20441 } 20442 20443 @Override 20444 public void setKeepUninstalledPackages(final List<String> packageList) { 20445 Preconditions.checkNotNull(packageList); 20446 List<String> removedFromList = null; 20447 synchronized (mPackages) { 20448 if (mKeepUninstalledPackages != null) { 20449 final int packagesCount = mKeepUninstalledPackages.size(); 20450 for (int i = 0; i < packagesCount; i++) { 20451 String oldPackage = mKeepUninstalledPackages.get(i); 20452 if (packageList != null && packageList.contains(oldPackage)) { 20453 continue; 20454 } 20455 if (removedFromList == null) { 20456 removedFromList = new ArrayList<>(); 20457 } 20458 removedFromList.add(oldPackage); 20459 } 20460 } 20461 mKeepUninstalledPackages = new ArrayList<>(packageList); 20462 if (removedFromList != null) { 20463 final int removedCount = removedFromList.size(); 20464 for (int i = 0; i < removedCount; i++) { 20465 deletePackageIfUnusedLPr(removedFromList.get(i)); 20466 } 20467 } 20468 } 20469 } 20470 20471 @Override 20472 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20473 synchronized (mPackages) { 20474 // If we do not support permission review, done. 20475 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20476 return false; 20477 } 20478 20479 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20480 if (packageSetting == null) { 20481 return false; 20482 } 20483 20484 // Permission review applies only to apps not supporting the new permission model. 20485 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20486 return false; 20487 } 20488 20489 // Legacy apps have the permission and get user consent on launch. 20490 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20491 return permissionsState.isPermissionReviewRequired(userId); 20492 } 20493 } 20494 20495 @Override 20496 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20497 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20498 } 20499 20500 @Override 20501 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20502 int userId) { 20503 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20504 } 20505 } 20506 20507 @Override 20508 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20509 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20510 synchronized (mPackages) { 20511 final long identity = Binder.clearCallingIdentity(); 20512 try { 20513 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20514 packageNames, userId); 20515 } finally { 20516 Binder.restoreCallingIdentity(identity); 20517 } 20518 } 20519 } 20520 20521 private static void enforceSystemOrPhoneCaller(String tag) { 20522 int callingUid = Binder.getCallingUid(); 20523 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20524 throw new SecurityException( 20525 "Cannot call " + tag + " from UID " + callingUid); 20526 } 20527 } 20528 20529 boolean isHistoricalPackageUsageAvailable() { 20530 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20531 } 20532 20533 /** 20534 * Return a <b>copy</b> of the collection of packages known to the package manager. 20535 * @return A copy of the values of mPackages. 20536 */ 20537 Collection<PackageParser.Package> getPackages() { 20538 synchronized (mPackages) { 20539 return new ArrayList<>(mPackages.values()); 20540 } 20541 } 20542 20543 /** 20544 * Logs process start information (including base APK hash) to the security log. 20545 * @hide 20546 */ 20547 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20548 String apkFile, int pid) { 20549 if (!SecurityLog.isLoggingEnabled()) { 20550 return; 20551 } 20552 Bundle data = new Bundle(); 20553 data.putLong("startTimestamp", System.currentTimeMillis()); 20554 data.putString("processName", processName); 20555 data.putInt("uid", uid); 20556 data.putString("seinfo", seinfo); 20557 data.putString("apkFile", apkFile); 20558 data.putInt("pid", pid); 20559 Message msg = mProcessLoggingHandler.obtainMessage( 20560 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20561 msg.setData(data); 20562 mProcessLoggingHandler.sendMessage(msg); 20563 } 20564} 20565