PackageManagerService.java revision aab8cbfa234e1c53f909ac4bebeccbe2ddbeda05
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.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.util.jar.StrictJarFile; 221import android.view.Display; 222 223import com.android.internal.R; 224import com.android.internal.annotations.GuardedBy; 225import com.android.internal.app.IMediaContainerService; 226import com.android.internal.app.ResolverActivity; 227import com.android.internal.content.NativeLibraryHelper; 228import com.android.internal.content.PackageHelper; 229import com.android.internal.logging.MetricsLogger; 230import com.android.internal.logging.MetricsProto.MetricsEvent; 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 static class IFVerificationParams { 743 PackageParser.Package pkg; 744 boolean replacing; 745 int userId; 746 int verifierUid; 747 748 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 749 int _userId, int _verifierUid) { 750 pkg = _pkg; 751 replacing = _replacing; 752 userId = _userId; 753 replacing = _replacing; 754 verifierUid = _verifierUid; 755 } 756 } 757 758 private interface IntentFilterVerifier<T extends IntentFilter> { 759 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 760 T filter, String packageName); 761 void startVerifications(int userId); 762 void receiveVerificationResponse(int verificationId); 763 } 764 765 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 766 private Context mContext; 767 private ComponentName mIntentFilterVerifierComponent; 768 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 769 770 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 771 mContext = context; 772 mIntentFilterVerifierComponent = verifierComponent; 773 } 774 775 private String getDefaultScheme() { 776 return IntentFilter.SCHEME_HTTPS; 777 } 778 779 @Override 780 public void startVerifications(int userId) { 781 // Launch verifications requests 782 int count = mCurrentIntentFilterVerifications.size(); 783 for (int n=0; n<count; n++) { 784 int verificationId = mCurrentIntentFilterVerifications.get(n); 785 final IntentFilterVerificationState ivs = 786 mIntentFilterVerificationStates.get(verificationId); 787 788 String packageName = ivs.getPackageName(); 789 790 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 791 final int filterCount = filters.size(); 792 ArraySet<String> domainsSet = new ArraySet<>(); 793 for (int m=0; m<filterCount; m++) { 794 PackageParser.ActivityIntentInfo filter = filters.get(m); 795 domainsSet.addAll(filter.getHostsList()); 796 } 797 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 798 synchronized (mPackages) { 799 if (mSettings.createIntentFilterVerificationIfNeededLPw( 800 packageName, domainsList) != null) { 801 scheduleWriteSettingsLocked(); 802 } 803 } 804 sendVerificationRequest(userId, verificationId, ivs); 805 } 806 mCurrentIntentFilterVerifications.clear(); 807 } 808 809 private void sendVerificationRequest(int userId, int verificationId, 810 IntentFilterVerificationState ivs) { 811 812 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 813 verificationIntent.putExtra( 814 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 815 verificationId); 816 verificationIntent.putExtra( 817 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 818 getDefaultScheme()); 819 verificationIntent.putExtra( 820 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 821 ivs.getHostsString()); 822 verificationIntent.putExtra( 823 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 824 ivs.getPackageName()); 825 verificationIntent.setComponent(mIntentFilterVerifierComponent); 826 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 827 828 UserHandle user = new UserHandle(userId); 829 mContext.sendBroadcastAsUser(verificationIntent, user); 830 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 831 "Sending IntentFilter verification broadcast"); 832 } 833 834 public void receiveVerificationResponse(int verificationId) { 835 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 836 837 final boolean verified = ivs.isVerified(); 838 839 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 840 final int count = filters.size(); 841 if (DEBUG_DOMAIN_VERIFICATION) { 842 Slog.i(TAG, "Received verification response " + verificationId 843 + " for " + count + " filters, verified=" + verified); 844 } 845 for (int n=0; n<count; n++) { 846 PackageParser.ActivityIntentInfo filter = filters.get(n); 847 filter.setVerified(verified); 848 849 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 850 + " verified with result:" + verified + " and hosts:" 851 + ivs.getHostsString()); 852 } 853 854 mIntentFilterVerificationStates.remove(verificationId); 855 856 final String packageName = ivs.getPackageName(); 857 IntentFilterVerificationInfo ivi = null; 858 859 synchronized (mPackages) { 860 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 861 } 862 if (ivi == null) { 863 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 864 + verificationId + " packageName:" + packageName); 865 return; 866 } 867 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 868 "Updating IntentFilterVerificationInfo for package " + packageName 869 +" verificationId:" + verificationId); 870 871 synchronized (mPackages) { 872 if (verified) { 873 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 874 } else { 875 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 876 } 877 scheduleWriteSettingsLocked(); 878 879 final int userId = ivs.getUserId(); 880 if (userId != UserHandle.USER_ALL) { 881 final int userStatus = 882 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 883 884 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 885 boolean needUpdate = false; 886 887 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 888 // already been set by the User thru the Disambiguation dialog 889 switch (userStatus) { 890 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 891 if (verified) { 892 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 893 } else { 894 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 895 } 896 needUpdate = true; 897 break; 898 899 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 900 if (verified) { 901 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 902 needUpdate = true; 903 } 904 break; 905 906 default: 907 // Nothing to do 908 } 909 910 if (needUpdate) { 911 mSettings.updateIntentFilterVerificationStatusLPw( 912 packageName, updatedStatus, userId); 913 scheduleWritePackageRestrictionsLocked(userId); 914 } 915 } 916 } 917 } 918 919 @Override 920 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 921 ActivityIntentInfo filter, String packageName) { 922 if (!hasValidDomains(filter)) { 923 return false; 924 } 925 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 926 if (ivs == null) { 927 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 928 packageName); 929 } 930 if (DEBUG_DOMAIN_VERIFICATION) { 931 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 932 } 933 ivs.addFilter(filter); 934 return true; 935 } 936 937 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 938 int userId, int verificationId, String packageName) { 939 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 940 verifierUid, userId, packageName); 941 ivs.setPendingState(); 942 synchronized (mPackages) { 943 mIntentFilterVerificationStates.append(verificationId, ivs); 944 mCurrentIntentFilterVerifications.add(verificationId); 945 } 946 return ivs; 947 } 948 } 949 950 private static boolean hasValidDomains(ActivityIntentInfo filter) { 951 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 952 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 953 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 954 } 955 956 // Set of pending broadcasts for aggregating enable/disable of components. 957 static class PendingPackageBroadcasts { 958 // for each user id, a map of <package name -> components within that package> 959 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 960 961 public PendingPackageBroadcasts() { 962 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 963 } 964 965 public ArrayList<String> get(int userId, String packageName) { 966 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 967 return packages.get(packageName); 968 } 969 970 public void put(int userId, String packageName, ArrayList<String> components) { 971 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 972 packages.put(packageName, components); 973 } 974 975 public void remove(int userId, String packageName) { 976 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 977 if (packages != null) { 978 packages.remove(packageName); 979 } 980 } 981 982 public void remove(int userId) { 983 mUidMap.remove(userId); 984 } 985 986 public int userIdCount() { 987 return mUidMap.size(); 988 } 989 990 public int userIdAt(int n) { 991 return mUidMap.keyAt(n); 992 } 993 994 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 995 return mUidMap.get(userId); 996 } 997 998 public int size() { 999 // total number of pending broadcast entries across all userIds 1000 int num = 0; 1001 for (int i = 0; i< mUidMap.size(); i++) { 1002 num += mUidMap.valueAt(i).size(); 1003 } 1004 return num; 1005 } 1006 1007 public void clear() { 1008 mUidMap.clear(); 1009 } 1010 1011 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1012 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1013 if (map == null) { 1014 map = new ArrayMap<String, ArrayList<String>>(); 1015 mUidMap.put(userId, map); 1016 } 1017 return map; 1018 } 1019 } 1020 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1021 1022 // Service Connection to remote media container service to copy 1023 // package uri's from external media onto secure containers 1024 // or internal storage. 1025 private IMediaContainerService mContainerService = null; 1026 1027 static final int SEND_PENDING_BROADCAST = 1; 1028 static final int MCS_BOUND = 3; 1029 static final int END_COPY = 4; 1030 static final int INIT_COPY = 5; 1031 static final int MCS_UNBIND = 6; 1032 static final int START_CLEANING_PACKAGE = 7; 1033 static final int FIND_INSTALL_LOC = 8; 1034 static final int POST_INSTALL = 9; 1035 static final int MCS_RECONNECT = 10; 1036 static final int MCS_GIVE_UP = 11; 1037 static final int UPDATED_MEDIA_STATUS = 12; 1038 static final int WRITE_SETTINGS = 13; 1039 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1040 static final int PACKAGE_VERIFIED = 15; 1041 static final int CHECK_PENDING_VERIFICATION = 16; 1042 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1043 static final int INTENT_FILTER_VERIFIED = 18; 1044 1045 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1046 1047 // Delay time in millisecs 1048 static final int BROADCAST_DELAY = 10 * 1000; 1049 1050 static UserManagerService sUserManager; 1051 1052 // Stores a list of users whose package restrictions file needs to be updated 1053 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1054 1055 final private DefaultContainerConnection mDefContainerConn = 1056 new DefaultContainerConnection(); 1057 class DefaultContainerConnection implements ServiceConnection { 1058 public void onServiceConnected(ComponentName name, IBinder service) { 1059 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1060 IMediaContainerService imcs = 1061 IMediaContainerService.Stub.asInterface(service); 1062 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1063 } 1064 1065 public void onServiceDisconnected(ComponentName name) { 1066 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1067 } 1068 } 1069 1070 // Recordkeeping of restore-after-install operations that are currently in flight 1071 // between the Package Manager and the Backup Manager 1072 static class PostInstallData { 1073 public InstallArgs args; 1074 public PackageInstalledInfo res; 1075 1076 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1077 args = _a; 1078 res = _r; 1079 } 1080 } 1081 1082 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1083 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1084 1085 // XML tags for backup/restore of various bits of state 1086 private static final String TAG_PREFERRED_BACKUP = "pa"; 1087 private static final String TAG_DEFAULT_APPS = "da"; 1088 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1089 1090 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1091 private static final String TAG_ALL_GRANTS = "rt-grants"; 1092 private static final String TAG_GRANT = "grant"; 1093 private static final String ATTR_PACKAGE_NAME = "pkg"; 1094 1095 private static final String TAG_PERMISSION = "perm"; 1096 private static final String ATTR_PERMISSION_NAME = "name"; 1097 private static final String ATTR_IS_GRANTED = "g"; 1098 private static final String ATTR_USER_SET = "set"; 1099 private static final String ATTR_USER_FIXED = "fixed"; 1100 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1101 1102 // System/policy permission grants are not backed up 1103 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1104 FLAG_PERMISSION_POLICY_FIXED 1105 | FLAG_PERMISSION_SYSTEM_FIXED 1106 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1107 1108 // And we back up these user-adjusted states 1109 private static final int USER_RUNTIME_GRANT_MASK = 1110 FLAG_PERMISSION_USER_SET 1111 | FLAG_PERMISSION_USER_FIXED 1112 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1113 1114 final @Nullable String mRequiredVerifierPackage; 1115 final @NonNull String mRequiredInstallerPackage; 1116 final @Nullable String mSetupWizardPackage; 1117 final @NonNull String mServicesSystemSharedLibraryPackageName; 1118 final @NonNull String mSharedSystemSharedLibraryPackageName; 1119 1120 private final PackageUsage mPackageUsage = new PackageUsage(); 1121 1122 private class PackageUsage { 1123 private static final int WRITE_INTERVAL 1124 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1125 1126 private final Object mFileLock = new Object(); 1127 private final AtomicLong mLastWritten = new AtomicLong(0); 1128 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1129 1130 private boolean mIsHistoricalPackageUsageAvailable = true; 1131 1132 boolean isHistoricalPackageUsageAvailable() { 1133 return mIsHistoricalPackageUsageAvailable; 1134 } 1135 1136 void write(boolean force) { 1137 if (force) { 1138 writeInternal(); 1139 return; 1140 } 1141 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1142 && !DEBUG_DEXOPT) { 1143 return; 1144 } 1145 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1146 new Thread("PackageUsage_DiskWriter") { 1147 @Override 1148 public void run() { 1149 try { 1150 writeInternal(); 1151 } finally { 1152 mBackgroundWriteRunning.set(false); 1153 } 1154 } 1155 }.start(); 1156 } 1157 } 1158 1159 private void writeInternal() { 1160 synchronized (mPackages) { 1161 synchronized (mFileLock) { 1162 AtomicFile file = getFile(); 1163 FileOutputStream f = null; 1164 try { 1165 f = file.startWrite(); 1166 BufferedOutputStream out = new BufferedOutputStream(f); 1167 FileUtils.setPermissions(file.getBaseFile().getPath(), 1168 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1169 StringBuilder sb = new StringBuilder(); 1170 1171 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1172 sb.append('\n'); 1173 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1174 1175 for (PackageParser.Package pkg : mPackages.values()) { 1176 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1177 continue; 1178 } 1179 sb.setLength(0); 1180 sb.append(pkg.packageName); 1181 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1182 sb.append(' '); 1183 sb.append(usageTimeInMillis); 1184 } 1185 sb.append('\n'); 1186 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1187 } 1188 out.flush(); 1189 file.finishWrite(f); 1190 } catch (IOException e) { 1191 if (f != null) { 1192 file.failWrite(f); 1193 } 1194 Log.e(TAG, "Failed to write package usage times", e); 1195 } 1196 } 1197 } 1198 mLastWritten.set(SystemClock.elapsedRealtime()); 1199 } 1200 1201 void readLP() { 1202 synchronized (mFileLock) { 1203 AtomicFile file = getFile(); 1204 BufferedInputStream in = null; 1205 try { 1206 in = new BufferedInputStream(file.openRead()); 1207 StringBuffer sb = new StringBuffer(); 1208 1209 String firstLine = readLine(in, sb); 1210 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1211 readVersion1LP(in, sb); 1212 } else { 1213 readVersion0LP(in, sb, firstLine); 1214 } 1215 } catch (FileNotFoundException expected) { 1216 mIsHistoricalPackageUsageAvailable = false; 1217 } catch (IOException e) { 1218 Log.w(TAG, "Failed to read package usage times", e); 1219 } finally { 1220 IoUtils.closeQuietly(in); 1221 } 1222 } 1223 mLastWritten.set(SystemClock.elapsedRealtime()); 1224 } 1225 1226 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1227 throws IOException { 1228 // Initial version of the file had no version number and stored one 1229 // package-timestamp pair per line. 1230 // Note that the first line has already been read from the InputStream. 1231 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1232 String[] tokens = line.split(" "); 1233 if (tokens.length != 2) { 1234 throw new IOException("Failed to parse " + line + 1235 " as package-timestamp pair."); 1236 } 1237 1238 String packageName = tokens[0]; 1239 PackageParser.Package pkg = mPackages.get(packageName); 1240 if (pkg == null) { 1241 continue; 1242 } 1243 1244 long timestamp = parseAsLong(tokens[1]); 1245 for (int reason = 0; 1246 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1247 reason++) { 1248 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1249 } 1250 } 1251 } 1252 1253 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1254 // Version 1 of the file started with the corresponding version 1255 // number and then stored a package name and eight timestamps per line. 1256 String line; 1257 while ((line = readLine(in, sb)) != null) { 1258 String[] tokens = line.split(" "); 1259 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1260 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1261 } 1262 1263 String packageName = tokens[0]; 1264 PackageParser.Package pkg = mPackages.get(packageName); 1265 if (pkg == null) { 1266 continue; 1267 } 1268 1269 for (int reason = 0; 1270 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1271 reason++) { 1272 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1273 } 1274 } 1275 } 1276 1277 private long parseAsLong(String token) throws IOException { 1278 try { 1279 return Long.parseLong(token); 1280 } catch (NumberFormatException e) { 1281 throw new IOException("Failed to parse " + token + " as a long.", e); 1282 } 1283 } 1284 1285 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1286 return readToken(in, sb, '\n'); 1287 } 1288 1289 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1290 throws IOException { 1291 sb.setLength(0); 1292 while (true) { 1293 int ch = in.read(); 1294 if (ch == -1) { 1295 if (sb.length() == 0) { 1296 return null; 1297 } 1298 throw new IOException("Unexpected EOF"); 1299 } 1300 if (ch == endOfToken) { 1301 return sb.toString(); 1302 } 1303 sb.append((char)ch); 1304 } 1305 } 1306 1307 private AtomicFile getFile() { 1308 File dataDir = Environment.getDataDirectory(); 1309 File systemDir = new File(dataDir, "system"); 1310 File fname = new File(systemDir, "package-usage.list"); 1311 return new AtomicFile(fname); 1312 } 1313 1314 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1315 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1316 } 1317 1318 class PackageHandler extends Handler { 1319 private boolean mBound = false; 1320 final ArrayList<HandlerParams> mPendingInstalls = 1321 new ArrayList<HandlerParams>(); 1322 1323 private boolean connectToService() { 1324 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1325 " DefaultContainerService"); 1326 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1327 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1328 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1329 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1331 mBound = true; 1332 return true; 1333 } 1334 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1335 return false; 1336 } 1337 1338 private void disconnectService() { 1339 mContainerService = null; 1340 mBound = false; 1341 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1342 mContext.unbindService(mDefContainerConn); 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1344 } 1345 1346 PackageHandler(Looper looper) { 1347 super(looper); 1348 } 1349 1350 public void handleMessage(Message msg) { 1351 try { 1352 doHandleMessage(msg); 1353 } finally { 1354 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1355 } 1356 } 1357 1358 void doHandleMessage(Message msg) { 1359 switch (msg.what) { 1360 case INIT_COPY: { 1361 HandlerParams params = (HandlerParams) msg.obj; 1362 int idx = mPendingInstalls.size(); 1363 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1364 // If a bind was already initiated we dont really 1365 // need to do anything. The pending install 1366 // will be processed later on. 1367 if (!mBound) { 1368 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1369 System.identityHashCode(mHandler)); 1370 // If this is the only one pending we might 1371 // have to bind to the service again. 1372 if (!connectToService()) { 1373 Slog.e(TAG, "Failed to bind to media container service"); 1374 params.serviceError(); 1375 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1376 System.identityHashCode(mHandler)); 1377 if (params.traceMethod != null) { 1378 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1379 params.traceCookie); 1380 } 1381 return; 1382 } else { 1383 // Once we bind to the service, the first 1384 // pending request will be processed. 1385 mPendingInstalls.add(idx, params); 1386 } 1387 } else { 1388 mPendingInstalls.add(idx, params); 1389 // Already bound to the service. Just make 1390 // sure we trigger off processing the first request. 1391 if (idx == 0) { 1392 mHandler.sendEmptyMessage(MCS_BOUND); 1393 } 1394 } 1395 break; 1396 } 1397 case MCS_BOUND: { 1398 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1399 if (msg.obj != null) { 1400 mContainerService = (IMediaContainerService) msg.obj; 1401 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1402 System.identityHashCode(mHandler)); 1403 } 1404 if (mContainerService == null) { 1405 if (!mBound) { 1406 // Something seriously wrong since we are not bound and we are not 1407 // waiting for connection. Bail out. 1408 Slog.e(TAG, "Cannot bind to media container service"); 1409 for (HandlerParams params : mPendingInstalls) { 1410 // Indicate service bind error 1411 params.serviceError(); 1412 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1413 System.identityHashCode(params)); 1414 if (params.traceMethod != null) { 1415 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1416 params.traceMethod, params.traceCookie); 1417 } 1418 return; 1419 } 1420 mPendingInstalls.clear(); 1421 } else { 1422 Slog.w(TAG, "Waiting to connect to media container service"); 1423 } 1424 } else if (mPendingInstalls.size() > 0) { 1425 HandlerParams params = mPendingInstalls.get(0); 1426 if (params != null) { 1427 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1428 System.identityHashCode(params)); 1429 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1430 if (params.startCopy()) { 1431 // We are done... look for more work or to 1432 // go idle. 1433 if (DEBUG_SD_INSTALL) Log.i(TAG, 1434 "Checking for more work or unbind..."); 1435 // Delete pending install 1436 if (mPendingInstalls.size() > 0) { 1437 mPendingInstalls.remove(0); 1438 } 1439 if (mPendingInstalls.size() == 0) { 1440 if (mBound) { 1441 if (DEBUG_SD_INSTALL) Log.i(TAG, 1442 "Posting delayed MCS_UNBIND"); 1443 removeMessages(MCS_UNBIND); 1444 Message ubmsg = obtainMessage(MCS_UNBIND); 1445 // Unbind after a little delay, to avoid 1446 // continual thrashing. 1447 sendMessageDelayed(ubmsg, 10000); 1448 } 1449 } else { 1450 // There are more pending requests in queue. 1451 // Just post MCS_BOUND message to trigger processing 1452 // of next pending install. 1453 if (DEBUG_SD_INSTALL) Log.i(TAG, 1454 "Posting MCS_BOUND for next work"); 1455 mHandler.sendEmptyMessage(MCS_BOUND); 1456 } 1457 } 1458 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1459 } 1460 } else { 1461 // Should never happen ideally. 1462 Slog.w(TAG, "Empty queue"); 1463 } 1464 break; 1465 } 1466 case MCS_RECONNECT: { 1467 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1468 if (mPendingInstalls.size() > 0) { 1469 if (mBound) { 1470 disconnectService(); 1471 } 1472 if (!connectToService()) { 1473 Slog.e(TAG, "Failed to bind to media container service"); 1474 for (HandlerParams params : mPendingInstalls) { 1475 // Indicate service bind error 1476 params.serviceError(); 1477 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1478 System.identityHashCode(params)); 1479 } 1480 mPendingInstalls.clear(); 1481 } 1482 } 1483 break; 1484 } 1485 case MCS_UNBIND: { 1486 // If there is no actual work left, then time to unbind. 1487 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1488 1489 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1490 if (mBound) { 1491 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1492 1493 disconnectService(); 1494 } 1495 } else if (mPendingInstalls.size() > 0) { 1496 // There are more pending requests in queue. 1497 // Just post MCS_BOUND message to trigger processing 1498 // of next pending install. 1499 mHandler.sendEmptyMessage(MCS_BOUND); 1500 } 1501 1502 break; 1503 } 1504 case MCS_GIVE_UP: { 1505 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1506 HandlerParams params = mPendingInstalls.remove(0); 1507 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1508 System.identityHashCode(params)); 1509 break; 1510 } 1511 case SEND_PENDING_BROADCAST: { 1512 String packages[]; 1513 ArrayList<String> components[]; 1514 int size = 0; 1515 int uids[]; 1516 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1517 synchronized (mPackages) { 1518 if (mPendingBroadcasts == null) { 1519 return; 1520 } 1521 size = mPendingBroadcasts.size(); 1522 if (size <= 0) { 1523 // Nothing to be done. Just return 1524 return; 1525 } 1526 packages = new String[size]; 1527 components = new ArrayList[size]; 1528 uids = new int[size]; 1529 int i = 0; // filling out the above arrays 1530 1531 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1532 int packageUserId = mPendingBroadcasts.userIdAt(n); 1533 Iterator<Map.Entry<String, ArrayList<String>>> it 1534 = mPendingBroadcasts.packagesForUserId(packageUserId) 1535 .entrySet().iterator(); 1536 while (it.hasNext() && i < size) { 1537 Map.Entry<String, ArrayList<String>> ent = it.next(); 1538 packages[i] = ent.getKey(); 1539 components[i] = ent.getValue(); 1540 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1541 uids[i] = (ps != null) 1542 ? UserHandle.getUid(packageUserId, ps.appId) 1543 : -1; 1544 i++; 1545 } 1546 } 1547 size = i; 1548 mPendingBroadcasts.clear(); 1549 } 1550 // Send broadcasts 1551 for (int i = 0; i < size; i++) { 1552 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1553 } 1554 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1555 break; 1556 } 1557 case START_CLEANING_PACKAGE: { 1558 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1559 final String packageName = (String)msg.obj; 1560 final int userId = msg.arg1; 1561 final boolean andCode = msg.arg2 != 0; 1562 synchronized (mPackages) { 1563 if (userId == UserHandle.USER_ALL) { 1564 int[] users = sUserManager.getUserIds(); 1565 for (int user : users) { 1566 mSettings.addPackageToCleanLPw( 1567 new PackageCleanItem(user, packageName, andCode)); 1568 } 1569 } else { 1570 mSettings.addPackageToCleanLPw( 1571 new PackageCleanItem(userId, packageName, andCode)); 1572 } 1573 } 1574 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1575 startCleaningPackages(); 1576 } break; 1577 case POST_INSTALL: { 1578 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1579 1580 PostInstallData data = mRunningInstalls.get(msg.arg1); 1581 final boolean didRestore = (msg.arg2 != 0); 1582 mRunningInstalls.delete(msg.arg1); 1583 1584 if (data != null) { 1585 InstallArgs args = data.args; 1586 PackageInstalledInfo parentRes = data.res; 1587 1588 final boolean grantPermissions = (args.installFlags 1589 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1590 final boolean killApp = (args.installFlags 1591 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1592 final String[] grantedPermissions = args.installGrantPermissions; 1593 1594 // Handle the parent package 1595 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1596 grantedPermissions, didRestore, args.installerPackageName, 1597 args.observer); 1598 1599 // Handle the child packages 1600 final int childCount = (parentRes.addedChildPackages != null) 1601 ? parentRes.addedChildPackages.size() : 0; 1602 for (int i = 0; i < childCount; i++) { 1603 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1604 handlePackagePostInstall(childRes, grantPermissions, killApp, 1605 grantedPermissions, false, args.installerPackageName, 1606 args.observer); 1607 } 1608 1609 // Log tracing if needed 1610 if (args.traceMethod != null) { 1611 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1612 args.traceCookie); 1613 } 1614 } else { 1615 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1616 } 1617 1618 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1619 } break; 1620 case UPDATED_MEDIA_STATUS: { 1621 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1622 boolean reportStatus = msg.arg1 == 1; 1623 boolean doGc = msg.arg2 == 1; 1624 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1625 if (doGc) { 1626 // Force a gc to clear up stale containers. 1627 Runtime.getRuntime().gc(); 1628 } 1629 if (msg.obj != null) { 1630 @SuppressWarnings("unchecked") 1631 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1632 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1633 // Unload containers 1634 unloadAllContainers(args); 1635 } 1636 if (reportStatus) { 1637 try { 1638 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1639 PackageHelper.getMountService().finishMediaUpdate(); 1640 } catch (RemoteException e) { 1641 Log.e(TAG, "MountService not running?"); 1642 } 1643 } 1644 } break; 1645 case WRITE_SETTINGS: { 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1647 synchronized (mPackages) { 1648 removeMessages(WRITE_SETTINGS); 1649 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1650 mSettings.writeLPr(); 1651 mDirtyUsers.clear(); 1652 } 1653 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1654 } break; 1655 case WRITE_PACKAGE_RESTRICTIONS: { 1656 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1657 synchronized (mPackages) { 1658 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1659 for (int userId : mDirtyUsers) { 1660 mSettings.writePackageRestrictionsLPr(userId); 1661 } 1662 mDirtyUsers.clear(); 1663 } 1664 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1665 } break; 1666 case CHECK_PENDING_VERIFICATION: { 1667 final int verificationId = msg.arg1; 1668 final PackageVerificationState state = mPendingVerification.get(verificationId); 1669 1670 if ((state != null) && !state.timeoutExtended()) { 1671 final InstallArgs args = state.getInstallArgs(); 1672 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1673 1674 Slog.i(TAG, "Verification timed out for " + originUri); 1675 mPendingVerification.remove(verificationId); 1676 1677 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1678 1679 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1680 Slog.i(TAG, "Continuing with installation of " + originUri); 1681 state.setVerifierResponse(Binder.getCallingUid(), 1682 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1683 broadcastPackageVerified(verificationId, originUri, 1684 PackageManager.VERIFICATION_ALLOW, 1685 state.getInstallArgs().getUser()); 1686 try { 1687 ret = args.copyApk(mContainerService, true); 1688 } catch (RemoteException e) { 1689 Slog.e(TAG, "Could not contact the ContainerService"); 1690 } 1691 } else { 1692 broadcastPackageVerified(verificationId, originUri, 1693 PackageManager.VERIFICATION_REJECT, 1694 state.getInstallArgs().getUser()); 1695 } 1696 1697 Trace.asyncTraceEnd( 1698 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1699 1700 processPendingInstall(args, ret); 1701 mHandler.sendEmptyMessage(MCS_UNBIND); 1702 } 1703 break; 1704 } 1705 case PACKAGE_VERIFIED: { 1706 final int verificationId = msg.arg1; 1707 1708 final PackageVerificationState state = mPendingVerification.get(verificationId); 1709 if (state == null) { 1710 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1711 break; 1712 } 1713 1714 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1715 1716 state.setVerifierResponse(response.callerUid, response.code); 1717 1718 if (state.isVerificationComplete()) { 1719 mPendingVerification.remove(verificationId); 1720 1721 final InstallArgs args = state.getInstallArgs(); 1722 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1723 1724 int ret; 1725 if (state.isInstallAllowed()) { 1726 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1727 broadcastPackageVerified(verificationId, originUri, 1728 response.code, state.getInstallArgs().getUser()); 1729 try { 1730 ret = args.copyApk(mContainerService, true); 1731 } catch (RemoteException e) { 1732 Slog.e(TAG, "Could not contact the ContainerService"); 1733 } 1734 } else { 1735 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1736 } 1737 1738 Trace.asyncTraceEnd( 1739 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1740 1741 processPendingInstall(args, ret); 1742 mHandler.sendEmptyMessage(MCS_UNBIND); 1743 } 1744 1745 break; 1746 } 1747 case START_INTENT_FILTER_VERIFICATIONS: { 1748 IFVerificationParams params = (IFVerificationParams) msg.obj; 1749 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1750 params.replacing, params.pkg); 1751 break; 1752 } 1753 case INTENT_FILTER_VERIFIED: { 1754 final int verificationId = msg.arg1; 1755 1756 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1757 verificationId); 1758 if (state == null) { 1759 Slog.w(TAG, "Invalid IntentFilter verification token " 1760 + verificationId + " received"); 1761 break; 1762 } 1763 1764 final int userId = state.getUserId(); 1765 1766 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1767 "Processing IntentFilter verification with token:" 1768 + verificationId + " and userId:" + userId); 1769 1770 final IntentFilterVerificationResponse response = 1771 (IntentFilterVerificationResponse) msg.obj; 1772 1773 state.setVerifierResponse(response.callerUid, response.code); 1774 1775 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1776 "IntentFilter verification with token:" + verificationId 1777 + " and userId:" + userId 1778 + " is settings verifier response with response code:" 1779 + response.code); 1780 1781 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1782 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1783 + response.getFailedDomainsString()); 1784 } 1785 1786 if (state.isVerificationComplete()) { 1787 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1788 } else { 1789 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1790 "IntentFilter verification with token:" + verificationId 1791 + " was not said to be complete"); 1792 } 1793 1794 break; 1795 } 1796 } 1797 } 1798 } 1799 1800 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1801 boolean killApp, String[] grantedPermissions, 1802 boolean launchedForRestore, String installerPackage, 1803 IPackageInstallObserver2 installObserver) { 1804 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1805 // Send the removed broadcasts 1806 if (res.removedInfo != null) { 1807 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1808 } 1809 1810 // Now that we successfully installed the package, grant runtime 1811 // permissions if requested before broadcasting the install. 1812 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1813 >= Build.VERSION_CODES.M) { 1814 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1815 } 1816 1817 final boolean update = res.removedInfo != null 1818 && res.removedInfo.removedPackage != null; 1819 1820 // If this is the first time we have child packages for a disabled privileged 1821 // app that had no children, we grant requested runtime permissions to the new 1822 // children if the parent on the system image had them already granted. 1823 if (res.pkg.parentPackage != null) { 1824 synchronized (mPackages) { 1825 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1826 } 1827 } 1828 1829 synchronized (mPackages) { 1830 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1831 } 1832 1833 final String packageName = res.pkg.applicationInfo.packageName; 1834 Bundle extras = new Bundle(1); 1835 extras.putInt(Intent.EXTRA_UID, res.uid); 1836 1837 // Determine the set of users who are adding this package for 1838 // the first time vs. those who are seeing an update. 1839 int[] firstUsers = EMPTY_INT_ARRAY; 1840 int[] updateUsers = EMPTY_INT_ARRAY; 1841 if (res.origUsers == null || res.origUsers.length == 0) { 1842 firstUsers = res.newUsers; 1843 } else { 1844 for (int newUser : res.newUsers) { 1845 boolean isNew = true; 1846 for (int origUser : res.origUsers) { 1847 if (origUser == newUser) { 1848 isNew = false; 1849 break; 1850 } 1851 } 1852 if (isNew) { 1853 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1854 } else { 1855 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1856 } 1857 } 1858 } 1859 1860 // Send installed broadcasts if the install/update is not ephemeral 1861 if (!isEphemeral(res.pkg)) { 1862 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1863 1864 // Send added for users that see the package for the first time 1865 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1866 extras, 0 /*flags*/, null /*targetPackage*/, 1867 null /*finishedReceiver*/, firstUsers); 1868 1869 // Send added for users that don't see the package for the first time 1870 if (update) { 1871 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1872 } 1873 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1874 extras, 0 /*flags*/, null /*targetPackage*/, 1875 null /*finishedReceiver*/, updateUsers); 1876 1877 // Send replaced for users that don't see the package for the first time 1878 if (update) { 1879 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1880 packageName, extras, 0 /*flags*/, 1881 null /*targetPackage*/, null /*finishedReceiver*/, 1882 updateUsers); 1883 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1884 null /*package*/, null /*extras*/, 0 /*flags*/, 1885 packageName /*targetPackage*/, 1886 null /*finishedReceiver*/, updateUsers); 1887 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1888 // First-install and we did a restore, so we're responsible for the 1889 // first-launch broadcast. 1890 if (DEBUG_BACKUP) { 1891 Slog.i(TAG, "Post-restore of " + packageName 1892 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1893 } 1894 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1895 } 1896 1897 // Send broadcast package appeared if forward locked/external for all users 1898 // treat asec-hosted packages like removable media on upgrade 1899 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1900 if (DEBUG_INSTALL) { 1901 Slog.i(TAG, "upgrading pkg " + res.pkg 1902 + " is ASEC-hosted -> AVAILABLE"); 1903 } 1904 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1905 ArrayList<String> pkgList = new ArrayList<>(1); 1906 pkgList.add(packageName); 1907 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1908 } 1909 } 1910 1911 // Work that needs to happen on first install within each user 1912 if (firstUsers != null && firstUsers.length > 0) { 1913 synchronized (mPackages) { 1914 for (int userId : firstUsers) { 1915 // If this app is a browser and it's newly-installed for some 1916 // users, clear any default-browser state in those users. The 1917 // app's nature doesn't depend on the user, so we can just check 1918 // its browser nature in any user and generalize. 1919 if (packageIsBrowser(packageName, userId)) { 1920 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1921 } 1922 1923 // We may also need to apply pending (restored) runtime 1924 // permission grants within these users. 1925 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1926 } 1927 } 1928 } 1929 1930 // Log current value of "unknown sources" setting 1931 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1932 getUnknownSourcesSettings()); 1933 1934 // Force a gc to clear up things 1935 Runtime.getRuntime().gc(); 1936 1937 // Remove the replaced package's older resources safely now 1938 // We delete after a gc for applications on sdcard. 1939 if (res.removedInfo != null && res.removedInfo.args != null) { 1940 synchronized (mInstallLock) { 1941 res.removedInfo.args.doPostDeleteLI(true); 1942 } 1943 } 1944 } 1945 1946 // If someone is watching installs - notify them 1947 if (installObserver != null) { 1948 try { 1949 Bundle extras = extrasForInstallResult(res); 1950 installObserver.onPackageInstalled(res.name, res.returnCode, 1951 res.returnMsg, extras); 1952 } catch (RemoteException e) { 1953 Slog.i(TAG, "Observer no longer exists."); 1954 } 1955 } 1956 } 1957 1958 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1959 PackageParser.Package pkg) { 1960 if (pkg.parentPackage == null) { 1961 return; 1962 } 1963 if (pkg.requestedPermissions == null) { 1964 return; 1965 } 1966 final PackageSetting disabledSysParentPs = mSettings 1967 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1968 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1969 || !disabledSysParentPs.isPrivileged() 1970 || (disabledSysParentPs.childPackageNames != null 1971 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1972 return; 1973 } 1974 final int[] allUserIds = sUserManager.getUserIds(); 1975 final int permCount = pkg.requestedPermissions.size(); 1976 for (int i = 0; i < permCount; i++) { 1977 String permission = pkg.requestedPermissions.get(i); 1978 BasePermission bp = mSettings.mPermissions.get(permission); 1979 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1980 continue; 1981 } 1982 for (int userId : allUserIds) { 1983 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1984 permission, userId)) { 1985 grantRuntimePermission(pkg.packageName, permission, userId); 1986 } 1987 } 1988 } 1989 } 1990 1991 private StorageEventListener mStorageListener = new StorageEventListener() { 1992 @Override 1993 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1994 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1995 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1996 final String volumeUuid = vol.getFsUuid(); 1997 1998 // Clean up any users or apps that were removed or recreated 1999 // while this volume was missing 2000 reconcileUsers(volumeUuid); 2001 reconcileApps(volumeUuid); 2002 2003 // Clean up any install sessions that expired or were 2004 // cancelled while this volume was missing 2005 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2006 2007 loadPrivatePackages(vol); 2008 2009 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2010 unloadPrivatePackages(vol); 2011 } 2012 } 2013 2014 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2015 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2016 updateExternalMediaStatus(true, false); 2017 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2018 updateExternalMediaStatus(false, false); 2019 } 2020 } 2021 } 2022 2023 @Override 2024 public void onVolumeForgotten(String fsUuid) { 2025 if (TextUtils.isEmpty(fsUuid)) { 2026 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2027 return; 2028 } 2029 2030 // Remove any apps installed on the forgotten volume 2031 synchronized (mPackages) { 2032 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2033 for (PackageSetting ps : packages) { 2034 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2035 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2036 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2037 } 2038 2039 mSettings.onVolumeForgotten(fsUuid); 2040 mSettings.writeLPr(); 2041 } 2042 } 2043 }; 2044 2045 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2046 String[] grantedPermissions) { 2047 for (int userId : userIds) { 2048 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2049 } 2050 2051 // We could have touched GID membership, so flush out packages.list 2052 synchronized (mPackages) { 2053 mSettings.writePackageListLPr(); 2054 } 2055 } 2056 2057 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2058 String[] grantedPermissions) { 2059 SettingBase sb = (SettingBase) pkg.mExtras; 2060 if (sb == null) { 2061 return; 2062 } 2063 2064 PermissionsState permissionsState = sb.getPermissionsState(); 2065 2066 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2067 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2068 2069 for (String permission : pkg.requestedPermissions) { 2070 final BasePermission bp; 2071 synchronized (mPackages) { 2072 bp = mSettings.mPermissions.get(permission); 2073 } 2074 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2075 && (grantedPermissions == null 2076 || ArrayUtils.contains(grantedPermissions, permission))) { 2077 final int flags = permissionsState.getPermissionFlags(permission, userId); 2078 // Installer cannot change immutable permissions. 2079 if ((flags & immutableFlags) == 0) { 2080 grantRuntimePermission(pkg.packageName, permission, userId); 2081 } 2082 } 2083 } 2084 } 2085 2086 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2087 Bundle extras = null; 2088 switch (res.returnCode) { 2089 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2090 extras = new Bundle(); 2091 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2092 res.origPermission); 2093 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2094 res.origPackage); 2095 break; 2096 } 2097 case PackageManager.INSTALL_SUCCEEDED: { 2098 extras = new Bundle(); 2099 extras.putBoolean(Intent.EXTRA_REPLACING, 2100 res.removedInfo != null && res.removedInfo.removedPackage != null); 2101 break; 2102 } 2103 } 2104 return extras; 2105 } 2106 2107 void scheduleWriteSettingsLocked() { 2108 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2109 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2110 } 2111 } 2112 2113 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2114 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2115 scheduleWritePackageRestrictionsLocked(userId); 2116 } 2117 2118 void scheduleWritePackageRestrictionsLocked(int userId) { 2119 final int[] userIds = (userId == UserHandle.USER_ALL) 2120 ? sUserManager.getUserIds() : new int[]{userId}; 2121 for (int nextUserId : userIds) { 2122 if (!sUserManager.exists(nextUserId)) return; 2123 mDirtyUsers.add(nextUserId); 2124 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2125 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2126 } 2127 } 2128 } 2129 2130 public static PackageManagerService main(Context context, Installer installer, 2131 boolean factoryTest, boolean onlyCore) { 2132 // Self-check for initial settings. 2133 PackageManagerServiceCompilerMapping.checkProperties(); 2134 2135 PackageManagerService m = new PackageManagerService(context, installer, 2136 factoryTest, onlyCore); 2137 m.enableSystemUserPackages(); 2138 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2139 // disabled after already being started. 2140 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2141 UserHandle.USER_SYSTEM); 2142 ServiceManager.addService("package", m); 2143 return m; 2144 } 2145 2146 private void enableSystemUserPackages() { 2147 if (!UserManager.isSplitSystemUser()) { 2148 return; 2149 } 2150 // For system user, enable apps based on the following conditions: 2151 // - app is whitelisted or belong to one of these groups: 2152 // -- system app which has no launcher icons 2153 // -- system app which has INTERACT_ACROSS_USERS permission 2154 // -- system IME app 2155 // - app is not in the blacklist 2156 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2157 Set<String> enableApps = new ArraySet<>(); 2158 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2159 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2160 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2161 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2162 enableApps.addAll(wlApps); 2163 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2164 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2165 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2166 enableApps.removeAll(blApps); 2167 Log.i(TAG, "Applications installed for system user: " + enableApps); 2168 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2169 UserHandle.SYSTEM); 2170 final int allAppsSize = allAps.size(); 2171 synchronized (mPackages) { 2172 for (int i = 0; i < allAppsSize; i++) { 2173 String pName = allAps.get(i); 2174 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2175 // Should not happen, but we shouldn't be failing if it does 2176 if (pkgSetting == null) { 2177 continue; 2178 } 2179 boolean install = enableApps.contains(pName); 2180 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2181 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2182 + " for system user"); 2183 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2184 } 2185 } 2186 } 2187 } 2188 2189 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2190 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2191 Context.DISPLAY_SERVICE); 2192 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2193 } 2194 2195 public PackageManagerService(Context context, Installer installer, 2196 boolean factoryTest, boolean onlyCore) { 2197 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2198 SystemClock.uptimeMillis()); 2199 2200 if (mSdkVersion <= 0) { 2201 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2202 } 2203 2204 mContext = context; 2205 mFactoryTest = factoryTest; 2206 mOnlyCore = onlyCore; 2207 mMetrics = new DisplayMetrics(); 2208 mSettings = new Settings(mPackages); 2209 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2210 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2211 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2218 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2219 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2220 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2221 2222 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2223 if (separateProcesses != null && separateProcesses.length() > 0) { 2224 if ("*".equals(separateProcesses)) { 2225 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2226 mSeparateProcesses = null; 2227 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2228 } else { 2229 mDefParseFlags = 0; 2230 mSeparateProcesses = separateProcesses.split(","); 2231 Slog.w(TAG, "Running with debug.separate_processes: " 2232 + separateProcesses); 2233 } 2234 } else { 2235 mDefParseFlags = 0; 2236 mSeparateProcesses = null; 2237 } 2238 2239 mInstaller = installer; 2240 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2241 "*dexopt*"); 2242 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2243 2244 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2245 FgThread.get().getLooper()); 2246 2247 getDefaultDisplayMetrics(context, mMetrics); 2248 2249 SystemConfig systemConfig = SystemConfig.getInstance(); 2250 mGlobalGids = systemConfig.getGlobalGids(); 2251 mSystemPermissions = systemConfig.getSystemPermissions(); 2252 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2253 2254 synchronized (mInstallLock) { 2255 // writer 2256 synchronized (mPackages) { 2257 mHandlerThread = new ServiceThread(TAG, 2258 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2259 mHandlerThread.start(); 2260 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2261 mProcessLoggingHandler = new ProcessLoggingHandler(); 2262 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2263 2264 File dataDir = Environment.getDataDirectory(); 2265 mAppInstallDir = new File(dataDir, "app"); 2266 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2267 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2268 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2269 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2270 2271 sUserManager = new UserManagerService(context, this, mPackages); 2272 2273 // Propagate permission configuration in to package manager. 2274 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2275 = systemConfig.getPermissions(); 2276 for (int i=0; i<permConfig.size(); i++) { 2277 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2278 BasePermission bp = mSettings.mPermissions.get(perm.name); 2279 if (bp == null) { 2280 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2281 mSettings.mPermissions.put(perm.name, bp); 2282 } 2283 if (perm.gids != null) { 2284 bp.setGids(perm.gids, perm.perUser); 2285 } 2286 } 2287 2288 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2289 for (int i=0; i<libConfig.size(); i++) { 2290 mSharedLibraries.put(libConfig.keyAt(i), 2291 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2292 } 2293 2294 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2295 2296 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2297 2298 String customResolverActivity = Resources.getSystem().getString( 2299 R.string.config_customResolverActivity); 2300 if (TextUtils.isEmpty(customResolverActivity)) { 2301 customResolverActivity = null; 2302 } else { 2303 mCustomResolverComponentName = ComponentName.unflattenFromString( 2304 customResolverActivity); 2305 } 2306 2307 long startTime = SystemClock.uptimeMillis(); 2308 2309 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2310 startTime); 2311 2312 // Set flag to monitor and not change apk file paths when 2313 // scanning install directories. 2314 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2315 2316 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2317 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2318 2319 if (bootClassPath == null) { 2320 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2321 } 2322 2323 if (systemServerClassPath == null) { 2324 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2325 } 2326 2327 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2328 final String[] dexCodeInstructionSets = 2329 getDexCodeInstructionSets( 2330 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2331 2332 /** 2333 * Ensure all external libraries have had dexopt run on them. 2334 */ 2335 if (mSharedLibraries.size() > 0) { 2336 // NOTE: For now, we're compiling these system "shared libraries" 2337 // (and framework jars) into all available architectures. It's possible 2338 // to compile them only when we come across an app that uses them (there's 2339 // already logic for that in scanPackageLI) but that adds some complexity. 2340 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2341 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2342 final String lib = libEntry.path; 2343 if (lib == null) { 2344 continue; 2345 } 2346 2347 try { 2348 // Shared libraries do not have profiles so we perform a full 2349 // AOT compilation (if needed). 2350 int dexoptNeeded = DexFile.getDexOptNeeded( 2351 lib, dexCodeInstructionSet, 2352 getCompilerFilterForReason(REASON_SHARED_APK), 2353 false /* newProfile */); 2354 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2355 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2356 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2357 getCompilerFilterForReason(REASON_SHARED_APK), 2358 StorageManager.UUID_PRIVATE_INTERNAL, 2359 SKIP_SHARED_LIBRARY_CHECK); 2360 } 2361 } catch (FileNotFoundException e) { 2362 Slog.w(TAG, "Library not found: " + lib); 2363 } catch (IOException | InstallerException e) { 2364 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2365 + e.getMessage()); 2366 } 2367 } 2368 } 2369 } 2370 2371 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2372 2373 final VersionInfo ver = mSettings.getInternalVersion(); 2374 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2375 2376 // when upgrading from pre-M, promote system app permissions from install to runtime 2377 mPromoteSystemApps = 2378 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2379 2380 // save off the names of pre-existing system packages prior to scanning; we don't 2381 // want to automatically grant runtime permissions for new system apps 2382 if (mPromoteSystemApps) { 2383 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2384 while (pkgSettingIter.hasNext()) { 2385 PackageSetting ps = pkgSettingIter.next(); 2386 if (isSystemApp(ps)) { 2387 mExistingSystemPackages.add(ps.name); 2388 } 2389 } 2390 } 2391 2392 // When upgrading from pre-N, we need to handle package extraction like first boot, 2393 // as there is no profiling data available. 2394 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2395 mSettings.setNWorkDone(); 2396 2397 // Collect vendor overlay packages. 2398 // (Do this before scanning any apps.) 2399 // For security and version matching reason, only consider 2400 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2401 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2402 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2403 | PackageParser.PARSE_IS_SYSTEM 2404 | PackageParser.PARSE_IS_SYSTEM_DIR 2405 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2406 2407 // Find base frameworks (resource packages without code). 2408 scanDirTracedLI(frameworkDir, mDefParseFlags 2409 | PackageParser.PARSE_IS_SYSTEM 2410 | PackageParser.PARSE_IS_SYSTEM_DIR 2411 | PackageParser.PARSE_IS_PRIVILEGED, 2412 scanFlags | SCAN_NO_DEX, 0); 2413 2414 // Collected privileged system packages. 2415 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2416 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2417 | PackageParser.PARSE_IS_SYSTEM 2418 | PackageParser.PARSE_IS_SYSTEM_DIR 2419 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2420 2421 // Collect ordinary system packages. 2422 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2423 scanDirTracedLI(systemAppDir, mDefParseFlags 2424 | PackageParser.PARSE_IS_SYSTEM 2425 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2426 2427 // Collect all vendor packages. 2428 File vendorAppDir = new File("/vendor/app"); 2429 try { 2430 vendorAppDir = vendorAppDir.getCanonicalFile(); 2431 } catch (IOException e) { 2432 // failed to look up canonical path, continue with original one 2433 } 2434 scanDirTracedLI(vendorAppDir, mDefParseFlags 2435 | PackageParser.PARSE_IS_SYSTEM 2436 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2437 2438 // Collect all OEM packages. 2439 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2440 scanDirTracedLI(oemAppDir, mDefParseFlags 2441 | PackageParser.PARSE_IS_SYSTEM 2442 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2443 2444 // Prune any system packages that no longer exist. 2445 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2446 if (!mOnlyCore) { 2447 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2448 while (psit.hasNext()) { 2449 PackageSetting ps = psit.next(); 2450 2451 /* 2452 * If this is not a system app, it can't be a 2453 * disable system app. 2454 */ 2455 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2456 continue; 2457 } 2458 2459 /* 2460 * If the package is scanned, it's not erased. 2461 */ 2462 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2463 if (scannedPkg != null) { 2464 /* 2465 * If the system app is both scanned and in the 2466 * disabled packages list, then it must have been 2467 * added via OTA. Remove it from the currently 2468 * scanned package so the previously user-installed 2469 * application can be scanned. 2470 */ 2471 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2472 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2473 + ps.name + "; removing system app. Last known codePath=" 2474 + ps.codePathString + ", installStatus=" + ps.installStatus 2475 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2476 + scannedPkg.mVersionCode); 2477 removePackageLI(scannedPkg, true); 2478 mExpectingBetter.put(ps.name, ps.codePath); 2479 } 2480 2481 continue; 2482 } 2483 2484 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2485 psit.remove(); 2486 logCriticalInfo(Log.WARN, "System package " + ps.name 2487 + " no longer exists; it's data will be wiped"); 2488 // Actual deletion of code and data will be handled by later 2489 // reconciliation step 2490 } else { 2491 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2492 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2493 possiblyDeletedUpdatedSystemApps.add(ps.name); 2494 } 2495 } 2496 } 2497 } 2498 2499 //look for any incomplete package installations 2500 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2501 for (int i = 0; i < deletePkgsList.size(); i++) { 2502 // Actual deletion of code and data will be handled by later 2503 // reconciliation step 2504 final String packageName = deletePkgsList.get(i).name; 2505 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2506 synchronized (mPackages) { 2507 mSettings.removePackageLPw(packageName); 2508 } 2509 } 2510 2511 //delete tmp files 2512 deleteTempPackageFiles(); 2513 2514 // Remove any shared userIDs that have no associated packages 2515 mSettings.pruneSharedUsersLPw(); 2516 2517 if (!mOnlyCore) { 2518 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2519 SystemClock.uptimeMillis()); 2520 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2521 2522 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2523 | PackageParser.PARSE_FORWARD_LOCK, 2524 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2525 2526 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2527 | PackageParser.PARSE_IS_EPHEMERAL, 2528 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2529 2530 /** 2531 * Remove disable package settings for any updated system 2532 * apps that were removed via an OTA. If they're not a 2533 * previously-updated app, remove them completely. 2534 * Otherwise, just revoke their system-level permissions. 2535 */ 2536 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2537 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2538 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2539 2540 String msg; 2541 if (deletedPkg == null) { 2542 msg = "Updated system package " + deletedAppName 2543 + " no longer exists; it's data will be wiped"; 2544 // Actual deletion of code and data will be handled by later 2545 // reconciliation step 2546 } else { 2547 msg = "Updated system app + " + deletedAppName 2548 + " no longer present; removing system privileges for " 2549 + deletedAppName; 2550 2551 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2552 2553 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2554 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2555 } 2556 logCriticalInfo(Log.WARN, msg); 2557 } 2558 2559 /** 2560 * Make sure all system apps that we expected to appear on 2561 * the userdata partition actually showed up. If they never 2562 * appeared, crawl back and revive the system version. 2563 */ 2564 for (int i = 0; i < mExpectingBetter.size(); i++) { 2565 final String packageName = mExpectingBetter.keyAt(i); 2566 if (!mPackages.containsKey(packageName)) { 2567 final File scanFile = mExpectingBetter.valueAt(i); 2568 2569 logCriticalInfo(Log.WARN, "Expected better " + packageName 2570 + " but never showed up; reverting to system"); 2571 2572 int reparseFlags = mDefParseFlags; 2573 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2574 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2575 | PackageParser.PARSE_IS_SYSTEM_DIR 2576 | PackageParser.PARSE_IS_PRIVILEGED; 2577 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2578 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2579 | PackageParser.PARSE_IS_SYSTEM_DIR; 2580 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2581 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2582 | PackageParser.PARSE_IS_SYSTEM_DIR; 2583 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2584 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2585 | PackageParser.PARSE_IS_SYSTEM_DIR; 2586 } else { 2587 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2588 continue; 2589 } 2590 2591 mSettings.enableSystemPackageLPw(packageName); 2592 2593 try { 2594 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2595 } catch (PackageManagerException e) { 2596 Slog.e(TAG, "Failed to parse original system package: " 2597 + e.getMessage()); 2598 } 2599 } 2600 } 2601 } 2602 mExpectingBetter.clear(); 2603 2604 // Resolve protected action filters. Only the setup wizard is allowed to 2605 // have a high priority filter for these actions. 2606 mSetupWizardPackage = getSetupWizardPackageName(); 2607 if (mProtectedFilters.size() > 0) { 2608 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2609 Slog.i(TAG, "No setup wizard;" 2610 + " All protected intents capped to priority 0"); 2611 } 2612 for (ActivityIntentInfo filter : mProtectedFilters) { 2613 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2614 if (DEBUG_FILTERS) { 2615 Slog.i(TAG, "Found setup wizard;" 2616 + " allow priority " + filter.getPriority() + ";" 2617 + " package: " + filter.activity.info.packageName 2618 + " activity: " + filter.activity.className 2619 + " priority: " + filter.getPriority()); 2620 } 2621 // skip setup wizard; allow it to keep the high priority filter 2622 continue; 2623 } 2624 Slog.w(TAG, "Protected action; cap priority to 0;" 2625 + " package: " + filter.activity.info.packageName 2626 + " activity: " + filter.activity.className 2627 + " origPrio: " + filter.getPriority()); 2628 filter.setPriority(0); 2629 } 2630 } 2631 mDeferProtectedFilters = false; 2632 mProtectedFilters.clear(); 2633 2634 // Now that we know all of the shared libraries, update all clients to have 2635 // the correct library paths. 2636 updateAllSharedLibrariesLPw(); 2637 2638 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2639 // NOTE: We ignore potential failures here during a system scan (like 2640 // the rest of the commands above) because there's precious little we 2641 // can do about it. A settings error is reported, though. 2642 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2643 false /* boot complete */); 2644 } 2645 2646 // Now that we know all the packages we are keeping, 2647 // read and update their last usage times. 2648 mPackageUsage.readLP(); 2649 2650 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2651 SystemClock.uptimeMillis()); 2652 Slog.i(TAG, "Time to scan packages: " 2653 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2654 + " seconds"); 2655 2656 // If the platform SDK has changed since the last time we booted, 2657 // we need to re-grant app permission to catch any new ones that 2658 // appear. This is really a hack, and means that apps can in some 2659 // cases get permissions that the user didn't initially explicitly 2660 // allow... it would be nice to have some better way to handle 2661 // this situation. 2662 int updateFlags = UPDATE_PERMISSIONS_ALL; 2663 if (ver.sdkVersion != mSdkVersion) { 2664 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2665 + mSdkVersion + "; regranting permissions for internal storage"); 2666 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2667 } 2668 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2669 ver.sdkVersion = mSdkVersion; 2670 2671 // If this is the first boot or an update from pre-M, and it is a normal 2672 // boot, then we need to initialize the default preferred apps across 2673 // all defined users. 2674 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2675 for (UserInfo user : sUserManager.getUsers(true)) { 2676 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2677 applyFactoryDefaultBrowserLPw(user.id); 2678 primeDomainVerificationsLPw(user.id); 2679 } 2680 } 2681 2682 // Prepare storage for system user really early during boot, 2683 // since core system apps like SettingsProvider and SystemUI 2684 // can't wait for user to start 2685 final int storageFlags; 2686 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2687 storageFlags = StorageManager.FLAG_STORAGE_DE; 2688 } else { 2689 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2690 } 2691 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2692 storageFlags); 2693 2694 // If this is first boot after an OTA, and a normal boot, then 2695 // we need to clear code cache directories. 2696 if (mIsUpgrade && !onlyCore) { 2697 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2698 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2699 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2700 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2701 // No apps are running this early, so no need to freeze 2702 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2703 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2704 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2705 } 2706 clearAppProfilesLIF(ps.pkg); 2707 } 2708 ver.fingerprint = Build.FINGERPRINT; 2709 } 2710 2711 checkDefaultBrowser(); 2712 2713 // clear only after permissions and other defaults have been updated 2714 mExistingSystemPackages.clear(); 2715 mPromoteSystemApps = false; 2716 2717 // All the changes are done during package scanning. 2718 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2719 2720 // can downgrade to reader 2721 mSettings.writeLPr(); 2722 2723 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2724 SystemClock.uptimeMillis()); 2725 2726 if (!mOnlyCore) { 2727 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2728 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2729 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2730 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2731 mIntentFilterVerifierComponent); 2732 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2733 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2734 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2735 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2736 } else { 2737 mRequiredVerifierPackage = null; 2738 mRequiredInstallerPackage = null; 2739 mIntentFilterVerifierComponent = null; 2740 mIntentFilterVerifier = null; 2741 mServicesSystemSharedLibraryPackageName = null; 2742 mSharedSystemSharedLibraryPackageName = null; 2743 } 2744 2745 mInstallerService = new PackageInstallerService(context, this); 2746 2747 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2748 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2749 // both the installer and resolver must be present to enable ephemeral 2750 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2751 if (DEBUG_EPHEMERAL) { 2752 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2753 + " installer:" + ephemeralInstallerComponent); 2754 } 2755 mEphemeralResolverComponent = ephemeralResolverComponent; 2756 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2757 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2758 mEphemeralResolverConnection = 2759 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2760 } else { 2761 if (DEBUG_EPHEMERAL) { 2762 final String missingComponent = 2763 (ephemeralResolverComponent == null) 2764 ? (ephemeralInstallerComponent == null) 2765 ? "resolver and installer" 2766 : "resolver" 2767 : "installer"; 2768 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2769 } 2770 mEphemeralResolverComponent = null; 2771 mEphemeralInstallerComponent = null; 2772 mEphemeralResolverConnection = null; 2773 } 2774 2775 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2776 } // synchronized (mPackages) 2777 } // synchronized (mInstallLock) 2778 2779 // Now after opening every single application zip, make sure they 2780 // are all flushed. Not really needed, but keeps things nice and 2781 // tidy. 2782 Runtime.getRuntime().gc(); 2783 2784 // The initial scanning above does many calls into installd while 2785 // holding the mPackages lock, but we're mostly interested in yelling 2786 // once we have a booted system. 2787 mInstaller.setWarnIfHeld(mPackages); 2788 2789 // Expose private service for system components to use. 2790 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2791 } 2792 2793 @Override 2794 public boolean isFirstBoot() { 2795 return !mRestoredSettings; 2796 } 2797 2798 @Override 2799 public boolean isOnlyCoreApps() { 2800 return mOnlyCore; 2801 } 2802 2803 @Override 2804 public boolean isUpgrade() { 2805 return mIsUpgrade; 2806 } 2807 2808 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2809 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2810 2811 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2812 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2813 UserHandle.USER_SYSTEM); 2814 if (matches.size() == 1) { 2815 return matches.get(0).getComponentInfo().packageName; 2816 } else { 2817 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2818 return null; 2819 } 2820 } 2821 2822 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2823 synchronized (mPackages) { 2824 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2825 if (libraryEntry == null) { 2826 throw new IllegalStateException("Missing required shared library:" + libraryName); 2827 } 2828 return libraryEntry.apk; 2829 } 2830 } 2831 2832 private @NonNull String getRequiredInstallerLPr() { 2833 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2834 intent.addCategory(Intent.CATEGORY_DEFAULT); 2835 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2836 2837 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2838 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2839 UserHandle.USER_SYSTEM); 2840 if (matches.size() == 1) { 2841 ResolveInfo resolveInfo = matches.get(0); 2842 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2843 throw new RuntimeException("The installer must be a privileged app"); 2844 } 2845 return matches.get(0).getComponentInfo().packageName; 2846 } else { 2847 throw new RuntimeException("There must be exactly one installer; found " + matches); 2848 } 2849 } 2850 2851 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2852 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2853 2854 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2855 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2856 UserHandle.USER_SYSTEM); 2857 ResolveInfo best = null; 2858 final int N = matches.size(); 2859 for (int i = 0; i < N; i++) { 2860 final ResolveInfo cur = matches.get(i); 2861 final String packageName = cur.getComponentInfo().packageName; 2862 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2863 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2864 continue; 2865 } 2866 2867 if (best == null || cur.priority > best.priority) { 2868 best = cur; 2869 } 2870 } 2871 2872 if (best != null) { 2873 return best.getComponentInfo().getComponentName(); 2874 } else { 2875 throw new RuntimeException("There must be at least one intent filter verifier"); 2876 } 2877 } 2878 2879 private @Nullable ComponentName getEphemeralResolverLPr() { 2880 final String[] packageArray = 2881 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2882 if (packageArray.length == 0) { 2883 if (DEBUG_EPHEMERAL) { 2884 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2885 } 2886 return null; 2887 } 2888 2889 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2890 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2891 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2892 UserHandle.USER_SYSTEM); 2893 2894 final int N = resolvers.size(); 2895 if (N == 0) { 2896 if (DEBUG_EPHEMERAL) { 2897 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2898 } 2899 return null; 2900 } 2901 2902 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2903 for (int i = 0; i < N; i++) { 2904 final ResolveInfo info = resolvers.get(i); 2905 2906 if (info.serviceInfo == null) { 2907 continue; 2908 } 2909 2910 final String packageName = info.serviceInfo.packageName; 2911 if (!possiblePackages.contains(packageName)) { 2912 if (DEBUG_EPHEMERAL) { 2913 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2914 + " pkg: " + packageName + ", info:" + info); 2915 } 2916 continue; 2917 } 2918 2919 if (DEBUG_EPHEMERAL) { 2920 Slog.v(TAG, "Ephemeral resolver found;" 2921 + " pkg: " + packageName + ", info:" + info); 2922 } 2923 return new ComponentName(packageName, info.serviceInfo.name); 2924 } 2925 if (DEBUG_EPHEMERAL) { 2926 Slog.v(TAG, "Ephemeral resolver NOT found"); 2927 } 2928 return null; 2929 } 2930 2931 private @Nullable ComponentName getEphemeralInstallerLPr() { 2932 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2933 intent.addCategory(Intent.CATEGORY_DEFAULT); 2934 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2935 2936 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2937 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2938 UserHandle.USER_SYSTEM); 2939 if (matches.size() == 0) { 2940 return null; 2941 } else if (matches.size() == 1) { 2942 return matches.get(0).getComponentInfo().getComponentName(); 2943 } else { 2944 throw new RuntimeException( 2945 "There must be at most one ephemeral installer; found " + matches); 2946 } 2947 } 2948 2949 private void primeDomainVerificationsLPw(int userId) { 2950 if (DEBUG_DOMAIN_VERIFICATION) { 2951 Slog.d(TAG, "Priming domain verifications in user " + userId); 2952 } 2953 2954 SystemConfig systemConfig = SystemConfig.getInstance(); 2955 ArraySet<String> packages = systemConfig.getLinkedApps(); 2956 ArraySet<String> domains = new ArraySet<String>(); 2957 2958 for (String packageName : packages) { 2959 PackageParser.Package pkg = mPackages.get(packageName); 2960 if (pkg != null) { 2961 if (!pkg.isSystemApp()) { 2962 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2963 continue; 2964 } 2965 2966 domains.clear(); 2967 for (PackageParser.Activity a : pkg.activities) { 2968 for (ActivityIntentInfo filter : a.intents) { 2969 if (hasValidDomains(filter)) { 2970 domains.addAll(filter.getHostsList()); 2971 } 2972 } 2973 } 2974 2975 if (domains.size() > 0) { 2976 if (DEBUG_DOMAIN_VERIFICATION) { 2977 Slog.v(TAG, " + " + packageName); 2978 } 2979 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2980 // state w.r.t. the formal app-linkage "no verification attempted" state; 2981 // and then 'always' in the per-user state actually used for intent resolution. 2982 final IntentFilterVerificationInfo ivi; 2983 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2984 new ArrayList<String>(domains)); 2985 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2986 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2987 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2988 } else { 2989 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2990 + "' does not handle web links"); 2991 } 2992 } else { 2993 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2994 } 2995 } 2996 2997 scheduleWritePackageRestrictionsLocked(userId); 2998 scheduleWriteSettingsLocked(); 2999 } 3000 3001 private void applyFactoryDefaultBrowserLPw(int userId) { 3002 // The default browser app's package name is stored in a string resource, 3003 // with a product-specific overlay used for vendor customization. 3004 String browserPkg = mContext.getResources().getString( 3005 com.android.internal.R.string.default_browser); 3006 if (!TextUtils.isEmpty(browserPkg)) { 3007 // non-empty string => required to be a known package 3008 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3009 if (ps == null) { 3010 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3011 browserPkg = null; 3012 } else { 3013 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3014 } 3015 } 3016 3017 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3018 // default. If there's more than one, just leave everything alone. 3019 if (browserPkg == null) { 3020 calculateDefaultBrowserLPw(userId); 3021 } 3022 } 3023 3024 private void calculateDefaultBrowserLPw(int userId) { 3025 List<String> allBrowsers = resolveAllBrowserApps(userId); 3026 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3027 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3028 } 3029 3030 private List<String> resolveAllBrowserApps(int userId) { 3031 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3032 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3033 PackageManager.MATCH_ALL, userId); 3034 3035 final int count = list.size(); 3036 List<String> result = new ArrayList<String>(count); 3037 for (int i=0; i<count; i++) { 3038 ResolveInfo info = list.get(i); 3039 if (info.activityInfo == null 3040 || !info.handleAllWebDataURI 3041 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3042 || result.contains(info.activityInfo.packageName)) { 3043 continue; 3044 } 3045 result.add(info.activityInfo.packageName); 3046 } 3047 3048 return result; 3049 } 3050 3051 private boolean packageIsBrowser(String packageName, int userId) { 3052 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3053 PackageManager.MATCH_ALL, userId); 3054 final int N = list.size(); 3055 for (int i = 0; i < N; i++) { 3056 ResolveInfo info = list.get(i); 3057 if (packageName.equals(info.activityInfo.packageName)) { 3058 return true; 3059 } 3060 } 3061 return false; 3062 } 3063 3064 private void checkDefaultBrowser() { 3065 final int myUserId = UserHandle.myUserId(); 3066 final String packageName = getDefaultBrowserPackageName(myUserId); 3067 if (packageName != null) { 3068 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3069 if (info == null) { 3070 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3071 synchronized (mPackages) { 3072 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3073 } 3074 } 3075 } 3076 } 3077 3078 @Override 3079 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3080 throws RemoteException { 3081 try { 3082 return super.onTransact(code, data, reply, flags); 3083 } catch (RuntimeException e) { 3084 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3085 Slog.wtf(TAG, "Package Manager Crash", e); 3086 } 3087 throw e; 3088 } 3089 } 3090 3091 static int[] appendInts(int[] cur, int[] add) { 3092 if (add == null) return cur; 3093 if (cur == null) return add; 3094 final int N = add.length; 3095 for (int i=0; i<N; i++) { 3096 cur = appendInt(cur, add[i]); 3097 } 3098 return cur; 3099 } 3100 3101 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3102 if (!sUserManager.exists(userId)) return null; 3103 if (ps == null) { 3104 return null; 3105 } 3106 final PackageParser.Package p = ps.pkg; 3107 if (p == null) { 3108 return null; 3109 } 3110 3111 final PermissionsState permissionsState = ps.getPermissionsState(); 3112 3113 final int[] gids = permissionsState.computeGids(userId); 3114 final Set<String> permissions = permissionsState.getPermissions(userId); 3115 final PackageUserState state = ps.readUserState(userId); 3116 3117 return PackageParser.generatePackageInfo(p, gids, flags, 3118 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3119 } 3120 3121 @Override 3122 public void checkPackageStartable(String packageName, int userId) { 3123 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3124 3125 synchronized (mPackages) { 3126 final PackageSetting ps = mSettings.mPackages.get(packageName); 3127 if (ps == null) { 3128 throw new SecurityException("Package " + packageName + " was not found!"); 3129 } 3130 3131 if (!ps.getInstalled(userId)) { 3132 throw new SecurityException( 3133 "Package " + packageName + " was not installed for user " + userId + "!"); 3134 } 3135 3136 if (mSafeMode && !ps.isSystem()) { 3137 throw new SecurityException("Package " + packageName + " not a system app!"); 3138 } 3139 3140 if (mFrozenPackages.contains(packageName)) { 3141 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3142 } 3143 3144 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3145 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3146 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3147 } 3148 } 3149 } 3150 3151 @Override 3152 public boolean isPackageAvailable(String packageName, int userId) { 3153 if (!sUserManager.exists(userId)) return false; 3154 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3155 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3156 synchronized (mPackages) { 3157 PackageParser.Package p = mPackages.get(packageName); 3158 if (p != null) { 3159 final PackageSetting ps = (PackageSetting) p.mExtras; 3160 if (ps != null) { 3161 final PackageUserState state = ps.readUserState(userId); 3162 if (state != null) { 3163 return PackageParser.isAvailable(state); 3164 } 3165 } 3166 } 3167 } 3168 return false; 3169 } 3170 3171 @Override 3172 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3173 if (!sUserManager.exists(userId)) return null; 3174 flags = updateFlagsForPackage(flags, userId, packageName); 3175 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3176 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3177 // reader 3178 synchronized (mPackages) { 3179 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3180 PackageParser.Package p = null; 3181 if (matchFactoryOnly) { 3182 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3183 if (ps != null) { 3184 return generatePackageInfo(ps, flags, userId); 3185 } 3186 } 3187 if (p == null) { 3188 p = mPackages.get(packageName); 3189 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3190 return null; 3191 } 3192 } 3193 if (DEBUG_PACKAGE_INFO) 3194 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3195 if (p != null) { 3196 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3197 } 3198 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3199 final PackageSetting ps = mSettings.mPackages.get(packageName); 3200 return generatePackageInfo(ps, flags, userId); 3201 } 3202 } 3203 return null; 3204 } 3205 3206 @Override 3207 public String[] currentToCanonicalPackageNames(String[] names) { 3208 String[] out = new String[names.length]; 3209 // reader 3210 synchronized (mPackages) { 3211 for (int i=names.length-1; i>=0; i--) { 3212 PackageSetting ps = mSettings.mPackages.get(names[i]); 3213 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3214 } 3215 } 3216 return out; 3217 } 3218 3219 @Override 3220 public String[] canonicalToCurrentPackageNames(String[] names) { 3221 String[] out = new String[names.length]; 3222 // reader 3223 synchronized (mPackages) { 3224 for (int i=names.length-1; i>=0; i--) { 3225 String cur = mSettings.mRenamedPackages.get(names[i]); 3226 out[i] = cur != null ? cur : names[i]; 3227 } 3228 } 3229 return out; 3230 } 3231 3232 @Override 3233 public int getPackageUid(String packageName, int flags, int userId) { 3234 if (!sUserManager.exists(userId)) return -1; 3235 flags = updateFlagsForPackage(flags, userId, packageName); 3236 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3237 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3238 3239 // reader 3240 synchronized (mPackages) { 3241 final PackageParser.Package p = mPackages.get(packageName); 3242 if (p != null && p.isMatch(flags)) { 3243 return UserHandle.getUid(userId, p.applicationInfo.uid); 3244 } 3245 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3246 final PackageSetting ps = mSettings.mPackages.get(packageName); 3247 if (ps != null && ps.isMatch(flags)) { 3248 return UserHandle.getUid(userId, ps.appId); 3249 } 3250 } 3251 } 3252 3253 return -1; 3254 } 3255 3256 @Override 3257 public int[] getPackageGids(String packageName, int flags, int userId) { 3258 if (!sUserManager.exists(userId)) return null; 3259 flags = updateFlagsForPackage(flags, userId, packageName); 3260 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3261 false /* requireFullPermission */, false /* checkShell */, 3262 "getPackageGids"); 3263 3264 // reader 3265 synchronized (mPackages) { 3266 final PackageParser.Package p = mPackages.get(packageName); 3267 if (p != null && p.isMatch(flags)) { 3268 PackageSetting ps = (PackageSetting) p.mExtras; 3269 return ps.getPermissionsState().computeGids(userId); 3270 } 3271 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3272 final PackageSetting ps = mSettings.mPackages.get(packageName); 3273 if (ps != null && ps.isMatch(flags)) { 3274 return ps.getPermissionsState().computeGids(userId); 3275 } 3276 } 3277 } 3278 3279 return null; 3280 } 3281 3282 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3283 if (bp.perm != null) { 3284 return PackageParser.generatePermissionInfo(bp.perm, flags); 3285 } 3286 PermissionInfo pi = new PermissionInfo(); 3287 pi.name = bp.name; 3288 pi.packageName = bp.sourcePackage; 3289 pi.nonLocalizedLabel = bp.name; 3290 pi.protectionLevel = bp.protectionLevel; 3291 return pi; 3292 } 3293 3294 @Override 3295 public PermissionInfo getPermissionInfo(String name, int flags) { 3296 // reader 3297 synchronized (mPackages) { 3298 final BasePermission p = mSettings.mPermissions.get(name); 3299 if (p != null) { 3300 return generatePermissionInfo(p, flags); 3301 } 3302 return null; 3303 } 3304 } 3305 3306 @Override 3307 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3308 int flags) { 3309 // reader 3310 synchronized (mPackages) { 3311 if (group != null && !mPermissionGroups.containsKey(group)) { 3312 // This is thrown as NameNotFoundException 3313 return null; 3314 } 3315 3316 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3317 for (BasePermission p : mSettings.mPermissions.values()) { 3318 if (group == null) { 3319 if (p.perm == null || p.perm.info.group == null) { 3320 out.add(generatePermissionInfo(p, flags)); 3321 } 3322 } else { 3323 if (p.perm != null && group.equals(p.perm.info.group)) { 3324 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3325 } 3326 } 3327 } 3328 return new ParceledListSlice<>(out); 3329 } 3330 } 3331 3332 @Override 3333 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3334 // reader 3335 synchronized (mPackages) { 3336 return PackageParser.generatePermissionGroupInfo( 3337 mPermissionGroups.get(name), flags); 3338 } 3339 } 3340 3341 @Override 3342 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3343 // reader 3344 synchronized (mPackages) { 3345 final int N = mPermissionGroups.size(); 3346 ArrayList<PermissionGroupInfo> out 3347 = new ArrayList<PermissionGroupInfo>(N); 3348 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3349 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3350 } 3351 return new ParceledListSlice<>(out); 3352 } 3353 } 3354 3355 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3356 int userId) { 3357 if (!sUserManager.exists(userId)) return null; 3358 PackageSetting ps = mSettings.mPackages.get(packageName); 3359 if (ps != null) { 3360 if (ps.pkg == null) { 3361 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3362 if (pInfo != null) { 3363 return pInfo.applicationInfo; 3364 } 3365 return null; 3366 } 3367 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3368 ps.readUserState(userId), userId); 3369 } 3370 return null; 3371 } 3372 3373 @Override 3374 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3375 if (!sUserManager.exists(userId)) return null; 3376 flags = updateFlagsForApplication(flags, userId, packageName); 3377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3378 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3379 // writer 3380 synchronized (mPackages) { 3381 PackageParser.Package p = mPackages.get(packageName); 3382 if (DEBUG_PACKAGE_INFO) Log.v( 3383 TAG, "getApplicationInfo " + packageName 3384 + ": " + p); 3385 if (p != null) { 3386 PackageSetting ps = mSettings.mPackages.get(packageName); 3387 if (ps == null) return null; 3388 // Note: isEnabledLP() does not apply here - always return info 3389 return PackageParser.generateApplicationInfo( 3390 p, flags, ps.readUserState(userId), userId); 3391 } 3392 if ("android".equals(packageName)||"system".equals(packageName)) { 3393 return mAndroidApplication; 3394 } 3395 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3396 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3397 } 3398 } 3399 return null; 3400 } 3401 3402 @Override 3403 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3404 final IPackageDataObserver observer) { 3405 mContext.enforceCallingOrSelfPermission( 3406 android.Manifest.permission.CLEAR_APP_CACHE, null); 3407 // Queue up an async operation since clearing cache may take a little while. 3408 mHandler.post(new Runnable() { 3409 public void run() { 3410 mHandler.removeCallbacks(this); 3411 boolean success = true; 3412 synchronized (mInstallLock) { 3413 try { 3414 mInstaller.freeCache(volumeUuid, freeStorageSize); 3415 } catch (InstallerException e) { 3416 Slog.w(TAG, "Couldn't clear application caches: " + e); 3417 success = false; 3418 } 3419 } 3420 if (observer != null) { 3421 try { 3422 observer.onRemoveCompleted(null, success); 3423 } catch (RemoteException e) { 3424 Slog.w(TAG, "RemoveException when invoking call back"); 3425 } 3426 } 3427 } 3428 }); 3429 } 3430 3431 @Override 3432 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3433 final IntentSender pi) { 3434 mContext.enforceCallingOrSelfPermission( 3435 android.Manifest.permission.CLEAR_APP_CACHE, null); 3436 // Queue up an async operation since clearing cache may take a little while. 3437 mHandler.post(new Runnable() { 3438 public void run() { 3439 mHandler.removeCallbacks(this); 3440 boolean success = true; 3441 synchronized (mInstallLock) { 3442 try { 3443 mInstaller.freeCache(volumeUuid, freeStorageSize); 3444 } catch (InstallerException e) { 3445 Slog.w(TAG, "Couldn't clear application caches: " + e); 3446 success = false; 3447 } 3448 } 3449 if(pi != null) { 3450 try { 3451 // Callback via pending intent 3452 int code = success ? 1 : 0; 3453 pi.sendIntent(null, code, null, 3454 null, null); 3455 } catch (SendIntentException e1) { 3456 Slog.i(TAG, "Failed to send pending intent"); 3457 } 3458 } 3459 } 3460 }); 3461 } 3462 3463 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3464 synchronized (mInstallLock) { 3465 try { 3466 mInstaller.freeCache(volumeUuid, freeStorageSize); 3467 } catch (InstallerException e) { 3468 throw new IOException("Failed to free enough space", e); 3469 } 3470 } 3471 } 3472 3473 /** 3474 * Update given flags based on encryption status of current user. 3475 */ 3476 private int updateFlags(int flags, int userId) { 3477 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3478 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3479 // Caller expressed an explicit opinion about what encryption 3480 // aware/unaware components they want to see, so fall through and 3481 // give them what they want 3482 } else { 3483 // Caller expressed no opinion, so match based on user state 3484 if (StorageManager.isUserKeyUnlocked(userId)) { 3485 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3486 } else { 3487 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3488 } 3489 } 3490 return flags; 3491 } 3492 3493 /** 3494 * Update given flags when being used to request {@link PackageInfo}. 3495 */ 3496 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3497 boolean triaged = true; 3498 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3499 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3500 // Caller is asking for component details, so they'd better be 3501 // asking for specific encryption matching behavior, or be triaged 3502 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3503 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3504 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3505 triaged = false; 3506 } 3507 } 3508 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3509 | PackageManager.MATCH_SYSTEM_ONLY 3510 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3511 triaged = false; 3512 } 3513 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3514 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3515 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3516 } 3517 return updateFlags(flags, userId); 3518 } 3519 3520 /** 3521 * Update given flags when being used to request {@link ApplicationInfo}. 3522 */ 3523 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3524 return updateFlagsForPackage(flags, userId, cookie); 3525 } 3526 3527 /** 3528 * Update given flags when being used to request {@link ComponentInfo}. 3529 */ 3530 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3531 if (cookie instanceof Intent) { 3532 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3533 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3534 } 3535 } 3536 3537 boolean triaged = true; 3538 // Caller is asking for component details, so they'd better be 3539 // asking for specific encryption matching behavior, or be triaged 3540 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3541 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3542 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3543 triaged = false; 3544 } 3545 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3546 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3547 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3548 } 3549 3550 return updateFlags(flags, userId); 3551 } 3552 3553 /** 3554 * Update given flags when being used to request {@link ResolveInfo}. 3555 */ 3556 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3557 // Safe mode means we shouldn't match any third-party components 3558 if (mSafeMode) { 3559 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3560 } 3561 3562 return updateFlagsForComponent(flags, userId, cookie); 3563 } 3564 3565 @Override 3566 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3567 if (!sUserManager.exists(userId)) return null; 3568 flags = updateFlagsForComponent(flags, userId, component); 3569 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3570 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3571 synchronized (mPackages) { 3572 PackageParser.Activity a = mActivities.mActivities.get(component); 3573 3574 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3575 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3576 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3577 if (ps == null) return null; 3578 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3579 userId); 3580 } 3581 if (mResolveComponentName.equals(component)) { 3582 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3583 new PackageUserState(), userId); 3584 } 3585 } 3586 return null; 3587 } 3588 3589 @Override 3590 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3591 String resolvedType) { 3592 synchronized (mPackages) { 3593 if (component.equals(mResolveComponentName)) { 3594 // The resolver supports EVERYTHING! 3595 return true; 3596 } 3597 PackageParser.Activity a = mActivities.mActivities.get(component); 3598 if (a == null) { 3599 return false; 3600 } 3601 for (int i=0; i<a.intents.size(); i++) { 3602 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3603 intent.getData(), intent.getCategories(), TAG) >= 0) { 3604 return true; 3605 } 3606 } 3607 return false; 3608 } 3609 } 3610 3611 @Override 3612 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3613 if (!sUserManager.exists(userId)) return null; 3614 flags = updateFlagsForComponent(flags, userId, component); 3615 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3616 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3617 synchronized (mPackages) { 3618 PackageParser.Activity a = mReceivers.mActivities.get(component); 3619 if (DEBUG_PACKAGE_INFO) Log.v( 3620 TAG, "getReceiverInfo " + component + ": " + a); 3621 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3622 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3623 if (ps == null) return null; 3624 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3625 userId); 3626 } 3627 } 3628 return null; 3629 } 3630 3631 @Override 3632 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3633 if (!sUserManager.exists(userId)) return null; 3634 flags = updateFlagsForComponent(flags, userId, component); 3635 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3636 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3637 synchronized (mPackages) { 3638 PackageParser.Service s = mServices.mServices.get(component); 3639 if (DEBUG_PACKAGE_INFO) Log.v( 3640 TAG, "getServiceInfo " + component + ": " + s); 3641 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3642 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3643 if (ps == null) return null; 3644 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3645 userId); 3646 } 3647 } 3648 return null; 3649 } 3650 3651 @Override 3652 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3653 if (!sUserManager.exists(userId)) return null; 3654 flags = updateFlagsForComponent(flags, userId, component); 3655 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3656 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3657 synchronized (mPackages) { 3658 PackageParser.Provider p = mProviders.mProviders.get(component); 3659 if (DEBUG_PACKAGE_INFO) Log.v( 3660 TAG, "getProviderInfo " + component + ": " + p); 3661 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3662 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3663 if (ps == null) return null; 3664 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3665 userId); 3666 } 3667 } 3668 return null; 3669 } 3670 3671 @Override 3672 public String[] getSystemSharedLibraryNames() { 3673 Set<String> libSet; 3674 synchronized (mPackages) { 3675 libSet = mSharedLibraries.keySet(); 3676 int size = libSet.size(); 3677 if (size > 0) { 3678 String[] libs = new String[size]; 3679 libSet.toArray(libs); 3680 return libs; 3681 } 3682 } 3683 return null; 3684 } 3685 3686 @Override 3687 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3688 synchronized (mPackages) { 3689 return mServicesSystemSharedLibraryPackageName; 3690 } 3691 } 3692 3693 @Override 3694 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3695 synchronized (mPackages) { 3696 return mSharedSystemSharedLibraryPackageName; 3697 } 3698 } 3699 3700 @Override 3701 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3702 synchronized (mPackages) { 3703 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3704 3705 final FeatureInfo fi = new FeatureInfo(); 3706 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3707 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3708 res.add(fi); 3709 3710 return new ParceledListSlice<>(res); 3711 } 3712 } 3713 3714 @Override 3715 public boolean hasSystemFeature(String name, int version) { 3716 synchronized (mPackages) { 3717 final FeatureInfo feat = mAvailableFeatures.get(name); 3718 if (feat == null) { 3719 return false; 3720 } else { 3721 return feat.version >= version; 3722 } 3723 } 3724 } 3725 3726 @Override 3727 public int checkPermission(String permName, String pkgName, int userId) { 3728 if (!sUserManager.exists(userId)) { 3729 return PackageManager.PERMISSION_DENIED; 3730 } 3731 3732 synchronized (mPackages) { 3733 final PackageParser.Package p = mPackages.get(pkgName); 3734 if (p != null && p.mExtras != null) { 3735 final PackageSetting ps = (PackageSetting) p.mExtras; 3736 final PermissionsState permissionsState = ps.getPermissionsState(); 3737 if (permissionsState.hasPermission(permName, userId)) { 3738 return PackageManager.PERMISSION_GRANTED; 3739 } 3740 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3741 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3742 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3743 return PackageManager.PERMISSION_GRANTED; 3744 } 3745 } 3746 } 3747 3748 return PackageManager.PERMISSION_DENIED; 3749 } 3750 3751 @Override 3752 public int checkUidPermission(String permName, int uid) { 3753 final int userId = UserHandle.getUserId(uid); 3754 3755 if (!sUserManager.exists(userId)) { 3756 return PackageManager.PERMISSION_DENIED; 3757 } 3758 3759 synchronized (mPackages) { 3760 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3761 if (obj != null) { 3762 final SettingBase ps = (SettingBase) obj; 3763 final PermissionsState permissionsState = ps.getPermissionsState(); 3764 if (permissionsState.hasPermission(permName, userId)) { 3765 return PackageManager.PERMISSION_GRANTED; 3766 } 3767 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3768 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3769 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3770 return PackageManager.PERMISSION_GRANTED; 3771 } 3772 } else { 3773 ArraySet<String> perms = mSystemPermissions.get(uid); 3774 if (perms != null) { 3775 if (perms.contains(permName)) { 3776 return PackageManager.PERMISSION_GRANTED; 3777 } 3778 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3779 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3780 return PackageManager.PERMISSION_GRANTED; 3781 } 3782 } 3783 } 3784 } 3785 3786 return PackageManager.PERMISSION_DENIED; 3787 } 3788 3789 @Override 3790 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3791 if (UserHandle.getCallingUserId() != userId) { 3792 mContext.enforceCallingPermission( 3793 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3794 "isPermissionRevokedByPolicy for user " + userId); 3795 } 3796 3797 if (checkPermission(permission, packageName, userId) 3798 == PackageManager.PERMISSION_GRANTED) { 3799 return false; 3800 } 3801 3802 final long identity = Binder.clearCallingIdentity(); 3803 try { 3804 final int flags = getPermissionFlags(permission, packageName, userId); 3805 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3806 } finally { 3807 Binder.restoreCallingIdentity(identity); 3808 } 3809 } 3810 3811 @Override 3812 public String getPermissionControllerPackageName() { 3813 synchronized (mPackages) { 3814 return mRequiredInstallerPackage; 3815 } 3816 } 3817 3818 /** 3819 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3820 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3821 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3822 * @param message the message to log on security exception 3823 */ 3824 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3825 boolean checkShell, String message) { 3826 if (userId < 0) { 3827 throw new IllegalArgumentException("Invalid userId " + userId); 3828 } 3829 if (checkShell) { 3830 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3831 } 3832 if (userId == UserHandle.getUserId(callingUid)) return; 3833 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3834 if (requireFullPermission) { 3835 mContext.enforceCallingOrSelfPermission( 3836 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3837 } else { 3838 try { 3839 mContext.enforceCallingOrSelfPermission( 3840 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3841 } catch (SecurityException se) { 3842 mContext.enforceCallingOrSelfPermission( 3843 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3844 } 3845 } 3846 } 3847 } 3848 3849 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3850 if (callingUid == Process.SHELL_UID) { 3851 if (userHandle >= 0 3852 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3853 throw new SecurityException("Shell does not have permission to access user " 3854 + userHandle); 3855 } else if (userHandle < 0) { 3856 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3857 + Debug.getCallers(3)); 3858 } 3859 } 3860 } 3861 3862 private BasePermission findPermissionTreeLP(String permName) { 3863 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3864 if (permName.startsWith(bp.name) && 3865 permName.length() > bp.name.length() && 3866 permName.charAt(bp.name.length()) == '.') { 3867 return bp; 3868 } 3869 } 3870 return null; 3871 } 3872 3873 private BasePermission checkPermissionTreeLP(String permName) { 3874 if (permName != null) { 3875 BasePermission bp = findPermissionTreeLP(permName); 3876 if (bp != null) { 3877 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3878 return bp; 3879 } 3880 throw new SecurityException("Calling uid " 3881 + Binder.getCallingUid() 3882 + " is not allowed to add to permission tree " 3883 + bp.name + " owned by uid " + bp.uid); 3884 } 3885 } 3886 throw new SecurityException("No permission tree found for " + permName); 3887 } 3888 3889 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3890 if (s1 == null) { 3891 return s2 == null; 3892 } 3893 if (s2 == null) { 3894 return false; 3895 } 3896 if (s1.getClass() != s2.getClass()) { 3897 return false; 3898 } 3899 return s1.equals(s2); 3900 } 3901 3902 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3903 if (pi1.icon != pi2.icon) return false; 3904 if (pi1.logo != pi2.logo) return false; 3905 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3906 if (!compareStrings(pi1.name, pi2.name)) return false; 3907 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3908 // We'll take care of setting this one. 3909 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3910 // These are not currently stored in settings. 3911 //if (!compareStrings(pi1.group, pi2.group)) return false; 3912 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3913 //if (pi1.labelRes != pi2.labelRes) return false; 3914 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3915 return true; 3916 } 3917 3918 int permissionInfoFootprint(PermissionInfo info) { 3919 int size = info.name.length(); 3920 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3921 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3922 return size; 3923 } 3924 3925 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3926 int size = 0; 3927 for (BasePermission perm : mSettings.mPermissions.values()) { 3928 if (perm.uid == tree.uid) { 3929 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3930 } 3931 } 3932 return size; 3933 } 3934 3935 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3936 // We calculate the max size of permissions defined by this uid and throw 3937 // if that plus the size of 'info' would exceed our stated maximum. 3938 if (tree.uid != Process.SYSTEM_UID) { 3939 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3940 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3941 throw new SecurityException("Permission tree size cap exceeded"); 3942 } 3943 } 3944 } 3945 3946 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3947 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3948 throw new SecurityException("Label must be specified in permission"); 3949 } 3950 BasePermission tree = checkPermissionTreeLP(info.name); 3951 BasePermission bp = mSettings.mPermissions.get(info.name); 3952 boolean added = bp == null; 3953 boolean changed = true; 3954 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3955 if (added) { 3956 enforcePermissionCapLocked(info, tree); 3957 bp = new BasePermission(info.name, tree.sourcePackage, 3958 BasePermission.TYPE_DYNAMIC); 3959 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3960 throw new SecurityException( 3961 "Not allowed to modify non-dynamic permission " 3962 + info.name); 3963 } else { 3964 if (bp.protectionLevel == fixedLevel 3965 && bp.perm.owner.equals(tree.perm.owner) 3966 && bp.uid == tree.uid 3967 && comparePermissionInfos(bp.perm.info, info)) { 3968 changed = false; 3969 } 3970 } 3971 bp.protectionLevel = fixedLevel; 3972 info = new PermissionInfo(info); 3973 info.protectionLevel = fixedLevel; 3974 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3975 bp.perm.info.packageName = tree.perm.info.packageName; 3976 bp.uid = tree.uid; 3977 if (added) { 3978 mSettings.mPermissions.put(info.name, bp); 3979 } 3980 if (changed) { 3981 if (!async) { 3982 mSettings.writeLPr(); 3983 } else { 3984 scheduleWriteSettingsLocked(); 3985 } 3986 } 3987 return added; 3988 } 3989 3990 @Override 3991 public boolean addPermission(PermissionInfo info) { 3992 synchronized (mPackages) { 3993 return addPermissionLocked(info, false); 3994 } 3995 } 3996 3997 @Override 3998 public boolean addPermissionAsync(PermissionInfo info) { 3999 synchronized (mPackages) { 4000 return addPermissionLocked(info, true); 4001 } 4002 } 4003 4004 @Override 4005 public void removePermission(String name) { 4006 synchronized (mPackages) { 4007 checkPermissionTreeLP(name); 4008 BasePermission bp = mSettings.mPermissions.get(name); 4009 if (bp != null) { 4010 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4011 throw new SecurityException( 4012 "Not allowed to modify non-dynamic permission " 4013 + name); 4014 } 4015 mSettings.mPermissions.remove(name); 4016 mSettings.writeLPr(); 4017 } 4018 } 4019 } 4020 4021 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4022 BasePermission bp) { 4023 int index = pkg.requestedPermissions.indexOf(bp.name); 4024 if (index == -1) { 4025 throw new SecurityException("Package " + pkg.packageName 4026 + " has not requested permission " + bp.name); 4027 } 4028 if (!bp.isRuntime() && !bp.isDevelopment()) { 4029 throw new SecurityException("Permission " + bp.name 4030 + " is not a changeable permission type"); 4031 } 4032 } 4033 4034 @Override 4035 public void grantRuntimePermission(String packageName, String name, final int userId) { 4036 if (!sUserManager.exists(userId)) { 4037 Log.e(TAG, "No such user:" + userId); 4038 return; 4039 } 4040 4041 mContext.enforceCallingOrSelfPermission( 4042 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4043 "grantRuntimePermission"); 4044 4045 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4046 true /* requireFullPermission */, true /* checkShell */, 4047 "grantRuntimePermission"); 4048 4049 final int uid; 4050 final SettingBase sb; 4051 4052 synchronized (mPackages) { 4053 final PackageParser.Package pkg = mPackages.get(packageName); 4054 if (pkg == null) { 4055 throw new IllegalArgumentException("Unknown package: " + packageName); 4056 } 4057 4058 final BasePermission bp = mSettings.mPermissions.get(name); 4059 if (bp == null) { 4060 throw new IllegalArgumentException("Unknown permission: " + name); 4061 } 4062 4063 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4064 4065 // If a permission review is required for legacy apps we represent 4066 // their permissions as always granted runtime ones since we need 4067 // to keep the review required permission flag per user while an 4068 // install permission's state is shared across all users. 4069 if (Build.PERMISSIONS_REVIEW_REQUIRED 4070 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4071 && bp.isRuntime()) { 4072 return; 4073 } 4074 4075 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4076 sb = (SettingBase) pkg.mExtras; 4077 if (sb == null) { 4078 throw new IllegalArgumentException("Unknown package: " + packageName); 4079 } 4080 4081 final PermissionsState permissionsState = sb.getPermissionsState(); 4082 4083 final int flags = permissionsState.getPermissionFlags(name, userId); 4084 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4085 throw new SecurityException("Cannot grant system fixed permission " 4086 + name + " for package " + packageName); 4087 } 4088 4089 if (bp.isDevelopment()) { 4090 // Development permissions must be handled specially, since they are not 4091 // normal runtime permissions. For now they apply to all users. 4092 if (permissionsState.grantInstallPermission(bp) != 4093 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4094 scheduleWriteSettingsLocked(); 4095 } 4096 return; 4097 } 4098 4099 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4100 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4101 return; 4102 } 4103 4104 final int result = permissionsState.grantRuntimePermission(bp, userId); 4105 switch (result) { 4106 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4107 return; 4108 } 4109 4110 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4111 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4112 mHandler.post(new Runnable() { 4113 @Override 4114 public void run() { 4115 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4116 } 4117 }); 4118 } 4119 break; 4120 } 4121 4122 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4123 4124 // Not critical if that is lost - app has to request again. 4125 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4126 } 4127 4128 // Only need to do this if user is initialized. Otherwise it's a new user 4129 // and there are no processes running as the user yet and there's no need 4130 // to make an expensive call to remount processes for the changed permissions. 4131 if (READ_EXTERNAL_STORAGE.equals(name) 4132 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4133 final long token = Binder.clearCallingIdentity(); 4134 try { 4135 if (sUserManager.isInitialized(userId)) { 4136 MountServiceInternal mountServiceInternal = LocalServices.getService( 4137 MountServiceInternal.class); 4138 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4139 } 4140 } finally { 4141 Binder.restoreCallingIdentity(token); 4142 } 4143 } 4144 } 4145 4146 @Override 4147 public void revokeRuntimePermission(String packageName, String name, int userId) { 4148 if (!sUserManager.exists(userId)) { 4149 Log.e(TAG, "No such user:" + userId); 4150 return; 4151 } 4152 4153 mContext.enforceCallingOrSelfPermission( 4154 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4155 "revokeRuntimePermission"); 4156 4157 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4158 true /* requireFullPermission */, true /* checkShell */, 4159 "revokeRuntimePermission"); 4160 4161 final int appId; 4162 4163 synchronized (mPackages) { 4164 final PackageParser.Package pkg = mPackages.get(packageName); 4165 if (pkg == null) { 4166 throw new IllegalArgumentException("Unknown package: " + packageName); 4167 } 4168 4169 final BasePermission bp = mSettings.mPermissions.get(name); 4170 if (bp == null) { 4171 throw new IllegalArgumentException("Unknown permission: " + name); 4172 } 4173 4174 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4175 4176 // If a permission review is required for legacy apps we represent 4177 // their permissions as always granted runtime ones since we need 4178 // to keep the review required permission flag per user while an 4179 // install permission's state is shared across all users. 4180 if (Build.PERMISSIONS_REVIEW_REQUIRED 4181 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4182 && bp.isRuntime()) { 4183 return; 4184 } 4185 4186 SettingBase sb = (SettingBase) pkg.mExtras; 4187 if (sb == null) { 4188 throw new IllegalArgumentException("Unknown package: " + packageName); 4189 } 4190 4191 final PermissionsState permissionsState = sb.getPermissionsState(); 4192 4193 final int flags = permissionsState.getPermissionFlags(name, userId); 4194 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4195 throw new SecurityException("Cannot revoke system fixed permission " 4196 + name + " for package " + packageName); 4197 } 4198 4199 if (bp.isDevelopment()) { 4200 // Development permissions must be handled specially, since they are not 4201 // normal runtime permissions. For now they apply to all users. 4202 if (permissionsState.revokeInstallPermission(bp) != 4203 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4204 scheduleWriteSettingsLocked(); 4205 } 4206 return; 4207 } 4208 4209 if (permissionsState.revokeRuntimePermission(bp, userId) == 4210 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4211 return; 4212 } 4213 4214 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4215 4216 // Critical, after this call app should never have the permission. 4217 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4218 4219 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4220 } 4221 4222 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4223 } 4224 4225 @Override 4226 public void resetRuntimePermissions() { 4227 mContext.enforceCallingOrSelfPermission( 4228 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4229 "revokeRuntimePermission"); 4230 4231 int callingUid = Binder.getCallingUid(); 4232 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4233 mContext.enforceCallingOrSelfPermission( 4234 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4235 "resetRuntimePermissions"); 4236 } 4237 4238 synchronized (mPackages) { 4239 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4240 for (int userId : UserManagerService.getInstance().getUserIds()) { 4241 final int packageCount = mPackages.size(); 4242 for (int i = 0; i < packageCount; i++) { 4243 PackageParser.Package pkg = mPackages.valueAt(i); 4244 if (!(pkg.mExtras instanceof PackageSetting)) { 4245 continue; 4246 } 4247 PackageSetting ps = (PackageSetting) pkg.mExtras; 4248 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4249 } 4250 } 4251 } 4252 } 4253 4254 @Override 4255 public int getPermissionFlags(String name, String packageName, int userId) { 4256 if (!sUserManager.exists(userId)) { 4257 return 0; 4258 } 4259 4260 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4261 4262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4263 true /* requireFullPermission */, false /* checkShell */, 4264 "getPermissionFlags"); 4265 4266 synchronized (mPackages) { 4267 final PackageParser.Package pkg = mPackages.get(packageName); 4268 if (pkg == null) { 4269 throw new IllegalArgumentException("Unknown package: " + packageName); 4270 } 4271 4272 final BasePermission bp = mSettings.mPermissions.get(name); 4273 if (bp == null) { 4274 throw new IllegalArgumentException("Unknown permission: " + name); 4275 } 4276 4277 SettingBase sb = (SettingBase) pkg.mExtras; 4278 if (sb == null) { 4279 throw new IllegalArgumentException("Unknown package: " + packageName); 4280 } 4281 4282 PermissionsState permissionsState = sb.getPermissionsState(); 4283 return permissionsState.getPermissionFlags(name, userId); 4284 } 4285 } 4286 4287 @Override 4288 public void updatePermissionFlags(String name, String packageName, int flagMask, 4289 int flagValues, int userId) { 4290 if (!sUserManager.exists(userId)) { 4291 return; 4292 } 4293 4294 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4295 4296 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4297 true /* requireFullPermission */, true /* checkShell */, 4298 "updatePermissionFlags"); 4299 4300 // Only the system can change these flags and nothing else. 4301 if (getCallingUid() != Process.SYSTEM_UID) { 4302 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4303 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4304 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4305 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4306 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4307 } 4308 4309 synchronized (mPackages) { 4310 final PackageParser.Package pkg = mPackages.get(packageName); 4311 if (pkg == null) { 4312 throw new IllegalArgumentException("Unknown package: " + packageName); 4313 } 4314 4315 final BasePermission bp = mSettings.mPermissions.get(name); 4316 if (bp == null) { 4317 throw new IllegalArgumentException("Unknown permission: " + name); 4318 } 4319 4320 SettingBase sb = (SettingBase) pkg.mExtras; 4321 if (sb == null) { 4322 throw new IllegalArgumentException("Unknown package: " + packageName); 4323 } 4324 4325 PermissionsState permissionsState = sb.getPermissionsState(); 4326 4327 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4328 4329 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4330 // Install and runtime permissions are stored in different places, 4331 // so figure out what permission changed and persist the change. 4332 if (permissionsState.getInstallPermissionState(name) != null) { 4333 scheduleWriteSettingsLocked(); 4334 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4335 || hadState) { 4336 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4337 } 4338 } 4339 } 4340 } 4341 4342 /** 4343 * Update the permission flags for all packages and runtime permissions of a user in order 4344 * to allow device or profile owner to remove POLICY_FIXED. 4345 */ 4346 @Override 4347 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4348 if (!sUserManager.exists(userId)) { 4349 return; 4350 } 4351 4352 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4353 4354 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4355 true /* requireFullPermission */, true /* checkShell */, 4356 "updatePermissionFlagsForAllApps"); 4357 4358 // Only the system can change system fixed flags. 4359 if (getCallingUid() != Process.SYSTEM_UID) { 4360 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4361 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4362 } 4363 4364 synchronized (mPackages) { 4365 boolean changed = false; 4366 final int packageCount = mPackages.size(); 4367 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4368 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4369 SettingBase sb = (SettingBase) pkg.mExtras; 4370 if (sb == null) { 4371 continue; 4372 } 4373 PermissionsState permissionsState = sb.getPermissionsState(); 4374 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4375 userId, flagMask, flagValues); 4376 } 4377 if (changed) { 4378 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4379 } 4380 } 4381 } 4382 4383 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4384 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4385 != PackageManager.PERMISSION_GRANTED 4386 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4387 != PackageManager.PERMISSION_GRANTED) { 4388 throw new SecurityException(message + " requires " 4389 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4390 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4391 } 4392 } 4393 4394 @Override 4395 public boolean shouldShowRequestPermissionRationale(String permissionName, 4396 String packageName, int userId) { 4397 if (UserHandle.getCallingUserId() != userId) { 4398 mContext.enforceCallingPermission( 4399 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4400 "canShowRequestPermissionRationale for user " + userId); 4401 } 4402 4403 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4404 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4405 return false; 4406 } 4407 4408 if (checkPermission(permissionName, packageName, userId) 4409 == PackageManager.PERMISSION_GRANTED) { 4410 return false; 4411 } 4412 4413 final int flags; 4414 4415 final long identity = Binder.clearCallingIdentity(); 4416 try { 4417 flags = getPermissionFlags(permissionName, 4418 packageName, userId); 4419 } finally { 4420 Binder.restoreCallingIdentity(identity); 4421 } 4422 4423 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4424 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4425 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4426 4427 if ((flags & fixedFlags) != 0) { 4428 return false; 4429 } 4430 4431 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4432 } 4433 4434 @Override 4435 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4436 mContext.enforceCallingOrSelfPermission( 4437 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4438 "addOnPermissionsChangeListener"); 4439 4440 synchronized (mPackages) { 4441 mOnPermissionChangeListeners.addListenerLocked(listener); 4442 } 4443 } 4444 4445 @Override 4446 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4447 synchronized (mPackages) { 4448 mOnPermissionChangeListeners.removeListenerLocked(listener); 4449 } 4450 } 4451 4452 @Override 4453 public boolean isProtectedBroadcast(String actionName) { 4454 synchronized (mPackages) { 4455 if (mProtectedBroadcasts.contains(actionName)) { 4456 return true; 4457 } else if (actionName != null) { 4458 // TODO: remove these terrible hacks 4459 if (actionName.startsWith("android.net.netmon.lingerExpired") 4460 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4461 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4462 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4463 return true; 4464 } 4465 } 4466 } 4467 return false; 4468 } 4469 4470 @Override 4471 public int checkSignatures(String pkg1, String pkg2) { 4472 synchronized (mPackages) { 4473 final PackageParser.Package p1 = mPackages.get(pkg1); 4474 final PackageParser.Package p2 = mPackages.get(pkg2); 4475 if (p1 == null || p1.mExtras == null 4476 || p2 == null || p2.mExtras == null) { 4477 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4478 } 4479 return compareSignatures(p1.mSignatures, p2.mSignatures); 4480 } 4481 } 4482 4483 @Override 4484 public int checkUidSignatures(int uid1, int uid2) { 4485 // Map to base uids. 4486 uid1 = UserHandle.getAppId(uid1); 4487 uid2 = UserHandle.getAppId(uid2); 4488 // reader 4489 synchronized (mPackages) { 4490 Signature[] s1; 4491 Signature[] s2; 4492 Object obj = mSettings.getUserIdLPr(uid1); 4493 if (obj != null) { 4494 if (obj instanceof SharedUserSetting) { 4495 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4496 } else if (obj instanceof PackageSetting) { 4497 s1 = ((PackageSetting)obj).signatures.mSignatures; 4498 } else { 4499 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4500 } 4501 } else { 4502 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4503 } 4504 obj = mSettings.getUserIdLPr(uid2); 4505 if (obj != null) { 4506 if (obj instanceof SharedUserSetting) { 4507 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4508 } else if (obj instanceof PackageSetting) { 4509 s2 = ((PackageSetting)obj).signatures.mSignatures; 4510 } else { 4511 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4512 } 4513 } else { 4514 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4515 } 4516 return compareSignatures(s1, s2); 4517 } 4518 } 4519 4520 /** 4521 * This method should typically only be used when granting or revoking 4522 * permissions, since the app may immediately restart after this call. 4523 * <p> 4524 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4525 * guard your work against the app being relaunched. 4526 */ 4527 private void killUid(int appId, int userId, String reason) { 4528 final long identity = Binder.clearCallingIdentity(); 4529 try { 4530 IActivityManager am = ActivityManagerNative.getDefault(); 4531 if (am != null) { 4532 try { 4533 am.killUid(appId, userId, reason); 4534 } catch (RemoteException e) { 4535 /* ignore - same process */ 4536 } 4537 } 4538 } finally { 4539 Binder.restoreCallingIdentity(identity); 4540 } 4541 } 4542 4543 /** 4544 * Compares two sets of signatures. Returns: 4545 * <br /> 4546 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4547 * <br /> 4548 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4549 * <br /> 4550 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4551 * <br /> 4552 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4553 * <br /> 4554 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4555 */ 4556 static int compareSignatures(Signature[] s1, Signature[] s2) { 4557 if (s1 == null) { 4558 return s2 == null 4559 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4560 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4561 } 4562 4563 if (s2 == null) { 4564 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4565 } 4566 4567 if (s1.length != s2.length) { 4568 return PackageManager.SIGNATURE_NO_MATCH; 4569 } 4570 4571 // Since both signature sets are of size 1, we can compare without HashSets. 4572 if (s1.length == 1) { 4573 return s1[0].equals(s2[0]) ? 4574 PackageManager.SIGNATURE_MATCH : 4575 PackageManager.SIGNATURE_NO_MATCH; 4576 } 4577 4578 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4579 for (Signature sig : s1) { 4580 set1.add(sig); 4581 } 4582 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4583 for (Signature sig : s2) { 4584 set2.add(sig); 4585 } 4586 // Make sure s2 contains all signatures in s1. 4587 if (set1.equals(set2)) { 4588 return PackageManager.SIGNATURE_MATCH; 4589 } 4590 return PackageManager.SIGNATURE_NO_MATCH; 4591 } 4592 4593 /** 4594 * If the database version for this type of package (internal storage or 4595 * external storage) is less than the version where package signatures 4596 * were updated, return true. 4597 */ 4598 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4599 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4600 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4601 } 4602 4603 /** 4604 * Used for backward compatibility to make sure any packages with 4605 * certificate chains get upgraded to the new style. {@code existingSigs} 4606 * will be in the old format (since they were stored on disk from before the 4607 * system upgrade) and {@code scannedSigs} will be in the newer format. 4608 */ 4609 private int compareSignaturesCompat(PackageSignatures existingSigs, 4610 PackageParser.Package scannedPkg) { 4611 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4612 return PackageManager.SIGNATURE_NO_MATCH; 4613 } 4614 4615 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4616 for (Signature sig : existingSigs.mSignatures) { 4617 existingSet.add(sig); 4618 } 4619 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4620 for (Signature sig : scannedPkg.mSignatures) { 4621 try { 4622 Signature[] chainSignatures = sig.getChainSignatures(); 4623 for (Signature chainSig : chainSignatures) { 4624 scannedCompatSet.add(chainSig); 4625 } 4626 } catch (CertificateEncodingException e) { 4627 scannedCompatSet.add(sig); 4628 } 4629 } 4630 /* 4631 * Make sure the expanded scanned set contains all signatures in the 4632 * existing one. 4633 */ 4634 if (scannedCompatSet.equals(existingSet)) { 4635 // Migrate the old signatures to the new scheme. 4636 existingSigs.assignSignatures(scannedPkg.mSignatures); 4637 // The new KeySets will be re-added later in the scanning process. 4638 synchronized (mPackages) { 4639 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4640 } 4641 return PackageManager.SIGNATURE_MATCH; 4642 } 4643 return PackageManager.SIGNATURE_NO_MATCH; 4644 } 4645 4646 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4647 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4648 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4649 } 4650 4651 private int compareSignaturesRecover(PackageSignatures existingSigs, 4652 PackageParser.Package scannedPkg) { 4653 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4654 return PackageManager.SIGNATURE_NO_MATCH; 4655 } 4656 4657 String msg = null; 4658 try { 4659 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4660 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4661 + scannedPkg.packageName); 4662 return PackageManager.SIGNATURE_MATCH; 4663 } 4664 } catch (CertificateException e) { 4665 msg = e.getMessage(); 4666 } 4667 4668 logCriticalInfo(Log.INFO, 4669 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4670 return PackageManager.SIGNATURE_NO_MATCH; 4671 } 4672 4673 @Override 4674 public List<String> getAllPackages() { 4675 synchronized (mPackages) { 4676 return new ArrayList<String>(mPackages.keySet()); 4677 } 4678 } 4679 4680 @Override 4681 public String[] getPackagesForUid(int uid) { 4682 uid = UserHandle.getAppId(uid); 4683 // reader 4684 synchronized (mPackages) { 4685 Object obj = mSettings.getUserIdLPr(uid); 4686 if (obj instanceof SharedUserSetting) { 4687 final SharedUserSetting sus = (SharedUserSetting) obj; 4688 final int N = sus.packages.size(); 4689 final String[] res = new String[N]; 4690 final Iterator<PackageSetting> it = sus.packages.iterator(); 4691 int i = 0; 4692 while (it.hasNext()) { 4693 res[i++] = it.next().name; 4694 } 4695 return res; 4696 } else if (obj instanceof PackageSetting) { 4697 final PackageSetting ps = (PackageSetting) obj; 4698 return new String[] { ps.name }; 4699 } 4700 } 4701 return null; 4702 } 4703 4704 @Override 4705 public String getNameForUid(int uid) { 4706 // reader 4707 synchronized (mPackages) { 4708 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4709 if (obj instanceof SharedUserSetting) { 4710 final SharedUserSetting sus = (SharedUserSetting) obj; 4711 return sus.name + ":" + sus.userId; 4712 } else if (obj instanceof PackageSetting) { 4713 final PackageSetting ps = (PackageSetting) obj; 4714 return ps.name; 4715 } 4716 } 4717 return null; 4718 } 4719 4720 @Override 4721 public int getUidForSharedUser(String sharedUserName) { 4722 if(sharedUserName == null) { 4723 return -1; 4724 } 4725 // reader 4726 synchronized (mPackages) { 4727 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4728 if (suid == null) { 4729 return -1; 4730 } 4731 return suid.userId; 4732 } 4733 } 4734 4735 @Override 4736 public int getFlagsForUid(int uid) { 4737 synchronized (mPackages) { 4738 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4739 if (obj instanceof SharedUserSetting) { 4740 final SharedUserSetting sus = (SharedUserSetting) obj; 4741 return sus.pkgFlags; 4742 } else if (obj instanceof PackageSetting) { 4743 final PackageSetting ps = (PackageSetting) obj; 4744 return ps.pkgFlags; 4745 } 4746 } 4747 return 0; 4748 } 4749 4750 @Override 4751 public int getPrivateFlagsForUid(int uid) { 4752 synchronized (mPackages) { 4753 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4754 if (obj instanceof SharedUserSetting) { 4755 final SharedUserSetting sus = (SharedUserSetting) obj; 4756 return sus.pkgPrivateFlags; 4757 } else if (obj instanceof PackageSetting) { 4758 final PackageSetting ps = (PackageSetting) obj; 4759 return ps.pkgPrivateFlags; 4760 } 4761 } 4762 return 0; 4763 } 4764 4765 @Override 4766 public boolean isUidPrivileged(int uid) { 4767 uid = UserHandle.getAppId(uid); 4768 // reader 4769 synchronized (mPackages) { 4770 Object obj = mSettings.getUserIdLPr(uid); 4771 if (obj instanceof SharedUserSetting) { 4772 final SharedUserSetting sus = (SharedUserSetting) obj; 4773 final Iterator<PackageSetting> it = sus.packages.iterator(); 4774 while (it.hasNext()) { 4775 if (it.next().isPrivileged()) { 4776 return true; 4777 } 4778 } 4779 } else if (obj instanceof PackageSetting) { 4780 final PackageSetting ps = (PackageSetting) obj; 4781 return ps.isPrivileged(); 4782 } 4783 } 4784 return false; 4785 } 4786 4787 @Override 4788 public String[] getAppOpPermissionPackages(String permissionName) { 4789 synchronized (mPackages) { 4790 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4791 if (pkgs == null) { 4792 return null; 4793 } 4794 return pkgs.toArray(new String[pkgs.size()]); 4795 } 4796 } 4797 4798 @Override 4799 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4800 int flags, int userId) { 4801 try { 4802 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4803 4804 if (!sUserManager.exists(userId)) return null; 4805 flags = updateFlagsForResolve(flags, userId, intent); 4806 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4807 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4808 4809 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4810 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4811 flags, userId); 4812 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4813 4814 final ResolveInfo bestChoice = 4815 chooseBestActivity(intent, resolvedType, flags, query, userId); 4816 4817 if (isEphemeralAllowed(intent, query, userId)) { 4818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4819 final EphemeralResolveInfo ai = 4820 getEphemeralResolveInfo(intent, resolvedType, userId); 4821 if (ai != null) { 4822 if (DEBUG_EPHEMERAL) { 4823 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4824 } 4825 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4826 bestChoice.ephemeralResolveInfo = ai; 4827 } 4828 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4829 } 4830 return bestChoice; 4831 } finally { 4832 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4833 } 4834 } 4835 4836 @Override 4837 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4838 IntentFilter filter, int match, ComponentName activity) { 4839 final int userId = UserHandle.getCallingUserId(); 4840 if (DEBUG_PREFERRED) { 4841 Log.v(TAG, "setLastChosenActivity intent=" + intent 4842 + " resolvedType=" + resolvedType 4843 + " flags=" + flags 4844 + " filter=" + filter 4845 + " match=" + match 4846 + " activity=" + activity); 4847 filter.dump(new PrintStreamPrinter(System.out), " "); 4848 } 4849 intent.setComponent(null); 4850 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4851 userId); 4852 // Find any earlier preferred or last chosen entries and nuke them 4853 findPreferredActivity(intent, resolvedType, 4854 flags, query, 0, false, true, false, userId); 4855 // Add the new activity as the last chosen for this filter 4856 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4857 "Setting last chosen"); 4858 } 4859 4860 @Override 4861 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4862 final int userId = UserHandle.getCallingUserId(); 4863 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4864 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4865 userId); 4866 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4867 false, false, false, userId); 4868 } 4869 4870 4871 private boolean isEphemeralAllowed( 4872 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4873 // Short circuit and return early if possible. 4874 if (DISABLE_EPHEMERAL_APPS) { 4875 return false; 4876 } 4877 final int callingUser = UserHandle.getCallingUserId(); 4878 if (callingUser != UserHandle.USER_SYSTEM) { 4879 return false; 4880 } 4881 if (mEphemeralResolverConnection == null) { 4882 return false; 4883 } 4884 if (intent.getComponent() != null) { 4885 return false; 4886 } 4887 if (intent.getPackage() != null) { 4888 return false; 4889 } 4890 final boolean isWebUri = hasWebURI(intent); 4891 if (!isWebUri) { 4892 return false; 4893 } 4894 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4895 synchronized (mPackages) { 4896 final int count = resolvedActivites.size(); 4897 for (int n = 0; n < count; n++) { 4898 ResolveInfo info = resolvedActivites.get(n); 4899 String packageName = info.activityInfo.packageName; 4900 PackageSetting ps = mSettings.mPackages.get(packageName); 4901 if (ps != null) { 4902 // Try to get the status from User settings first 4903 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4904 int status = (int) (packedStatus >> 32); 4905 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4906 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4907 if (DEBUG_EPHEMERAL) { 4908 Slog.v(TAG, "DENY ephemeral apps;" 4909 + " pkg: " + packageName + ", status: " + status); 4910 } 4911 return false; 4912 } 4913 } 4914 } 4915 } 4916 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4917 return true; 4918 } 4919 4920 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4921 int userId) { 4922 MessageDigest digest = null; 4923 try { 4924 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4925 } catch (NoSuchAlgorithmException e) { 4926 // If we can't create a digest, ignore ephemeral apps. 4927 return null; 4928 } 4929 4930 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4931 final byte[] digestBytes = digest.digest(hostBytes); 4932 int shaPrefix = 4933 digestBytes[0] << 24 4934 | digestBytes[1] << 16 4935 | digestBytes[2] << 8 4936 | digestBytes[3] << 0; 4937 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4938 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4939 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4940 // No hash prefix match; there are no ephemeral apps for this domain. 4941 return null; 4942 } 4943 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4944 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4945 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4946 continue; 4947 } 4948 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4949 // No filters; this should never happen. 4950 if (filters.isEmpty()) { 4951 continue; 4952 } 4953 // We have a domain match; resolve the filters to see if anything matches. 4954 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4955 for (int j = filters.size() - 1; j >= 0; --j) { 4956 final EphemeralResolveIntentInfo intentInfo = 4957 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4958 ephemeralResolver.addFilter(intentInfo); 4959 } 4960 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4961 intent, resolvedType, false /*defaultOnly*/, userId); 4962 if (!matchedResolveInfoList.isEmpty()) { 4963 return matchedResolveInfoList.get(0); 4964 } 4965 } 4966 // Hash or filter mis-match; no ephemeral apps for this domain. 4967 return null; 4968 } 4969 4970 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4971 int flags, List<ResolveInfo> query, int userId) { 4972 if (query != null) { 4973 final int N = query.size(); 4974 if (N == 1) { 4975 return query.get(0); 4976 } else if (N > 1) { 4977 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4978 // If there is more than one activity with the same priority, 4979 // then let the user decide between them. 4980 ResolveInfo r0 = query.get(0); 4981 ResolveInfo r1 = query.get(1); 4982 if (DEBUG_INTENT_MATCHING || debug) { 4983 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4984 + r1.activityInfo.name + "=" + r1.priority); 4985 } 4986 // If the first activity has a higher priority, or a different 4987 // default, then it is always desirable to pick it. 4988 if (r0.priority != r1.priority 4989 || r0.preferredOrder != r1.preferredOrder 4990 || r0.isDefault != r1.isDefault) { 4991 return query.get(0); 4992 } 4993 // If we have saved a preference for a preferred activity for 4994 // this Intent, use that. 4995 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4996 flags, query, r0.priority, true, false, debug, userId); 4997 if (ri != null) { 4998 return ri; 4999 } 5000 ri = new ResolveInfo(mResolveInfo); 5001 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5002 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5003 ri.activityInfo.applicationInfo = new ApplicationInfo( 5004 ri.activityInfo.applicationInfo); 5005 if (userId != 0) { 5006 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5007 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5008 } 5009 // Make sure that the resolver is displayable in car mode 5010 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5011 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5012 return ri; 5013 } 5014 } 5015 return null; 5016 } 5017 5018 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5019 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5020 final int N = query.size(); 5021 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5022 .get(userId); 5023 // Get the list of persistent preferred activities that handle the intent 5024 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5025 List<PersistentPreferredActivity> pprefs = ppir != null 5026 ? ppir.queryIntent(intent, resolvedType, 5027 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5028 : null; 5029 if (pprefs != null && pprefs.size() > 0) { 5030 final int M = pprefs.size(); 5031 for (int i=0; i<M; i++) { 5032 final PersistentPreferredActivity ppa = pprefs.get(i); 5033 if (DEBUG_PREFERRED || debug) { 5034 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5035 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5036 + "\n component=" + ppa.mComponent); 5037 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5038 } 5039 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5040 flags | MATCH_DISABLED_COMPONENTS, userId); 5041 if (DEBUG_PREFERRED || debug) { 5042 Slog.v(TAG, "Found persistent preferred activity:"); 5043 if (ai != null) { 5044 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5045 } else { 5046 Slog.v(TAG, " null"); 5047 } 5048 } 5049 if (ai == null) { 5050 // This previously registered persistent preferred activity 5051 // component is no longer known. Ignore it and do NOT remove it. 5052 continue; 5053 } 5054 for (int j=0; j<N; j++) { 5055 final ResolveInfo ri = query.get(j); 5056 if (!ri.activityInfo.applicationInfo.packageName 5057 .equals(ai.applicationInfo.packageName)) { 5058 continue; 5059 } 5060 if (!ri.activityInfo.name.equals(ai.name)) { 5061 continue; 5062 } 5063 // Found a persistent preference that can handle the intent. 5064 if (DEBUG_PREFERRED || debug) { 5065 Slog.v(TAG, "Returning persistent preferred activity: " + 5066 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5067 } 5068 return ri; 5069 } 5070 } 5071 } 5072 return null; 5073 } 5074 5075 // TODO: handle preferred activities missing while user has amnesia 5076 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5077 List<ResolveInfo> query, int priority, boolean always, 5078 boolean removeMatches, boolean debug, int userId) { 5079 if (!sUserManager.exists(userId)) return null; 5080 flags = updateFlagsForResolve(flags, userId, intent); 5081 // writer 5082 synchronized (mPackages) { 5083 if (intent.getSelector() != null) { 5084 intent = intent.getSelector(); 5085 } 5086 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5087 5088 // Try to find a matching persistent preferred activity. 5089 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5090 debug, userId); 5091 5092 // If a persistent preferred activity matched, use it. 5093 if (pri != null) { 5094 return pri; 5095 } 5096 5097 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5098 // Get the list of preferred activities that handle the intent 5099 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5100 List<PreferredActivity> prefs = pir != null 5101 ? pir.queryIntent(intent, resolvedType, 5102 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5103 : null; 5104 if (prefs != null && prefs.size() > 0) { 5105 boolean changed = false; 5106 try { 5107 // First figure out how good the original match set is. 5108 // We will only allow preferred activities that came 5109 // from the same match quality. 5110 int match = 0; 5111 5112 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5113 5114 final int N = query.size(); 5115 for (int j=0; j<N; j++) { 5116 final ResolveInfo ri = query.get(j); 5117 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5118 + ": 0x" + Integer.toHexString(match)); 5119 if (ri.match > match) { 5120 match = ri.match; 5121 } 5122 } 5123 5124 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5125 + Integer.toHexString(match)); 5126 5127 match &= IntentFilter.MATCH_CATEGORY_MASK; 5128 final int M = prefs.size(); 5129 for (int i=0; i<M; i++) { 5130 final PreferredActivity pa = prefs.get(i); 5131 if (DEBUG_PREFERRED || debug) { 5132 Slog.v(TAG, "Checking PreferredActivity ds=" 5133 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5134 + "\n component=" + pa.mPref.mComponent); 5135 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5136 } 5137 if (pa.mPref.mMatch != match) { 5138 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5139 + Integer.toHexString(pa.mPref.mMatch)); 5140 continue; 5141 } 5142 // If it's not an "always" type preferred activity and that's what we're 5143 // looking for, skip it. 5144 if (always && !pa.mPref.mAlways) { 5145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5146 continue; 5147 } 5148 final ActivityInfo ai = getActivityInfo( 5149 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5150 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5151 userId); 5152 if (DEBUG_PREFERRED || debug) { 5153 Slog.v(TAG, "Found preferred activity:"); 5154 if (ai != null) { 5155 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5156 } else { 5157 Slog.v(TAG, " null"); 5158 } 5159 } 5160 if (ai == null) { 5161 // This previously registered preferred activity 5162 // component is no longer known. Most likely an update 5163 // to the app was installed and in the new version this 5164 // component no longer exists. Clean it up by removing 5165 // it from the preferred activities list, and skip it. 5166 Slog.w(TAG, "Removing dangling preferred activity: " 5167 + pa.mPref.mComponent); 5168 pir.removeFilter(pa); 5169 changed = true; 5170 continue; 5171 } 5172 for (int j=0; j<N; j++) { 5173 final ResolveInfo ri = query.get(j); 5174 if (!ri.activityInfo.applicationInfo.packageName 5175 .equals(ai.applicationInfo.packageName)) { 5176 continue; 5177 } 5178 if (!ri.activityInfo.name.equals(ai.name)) { 5179 continue; 5180 } 5181 5182 if (removeMatches) { 5183 pir.removeFilter(pa); 5184 changed = true; 5185 if (DEBUG_PREFERRED) { 5186 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5187 } 5188 break; 5189 } 5190 5191 // Okay we found a previously set preferred or last chosen app. 5192 // If the result set is different from when this 5193 // was created, we need to clear it and re-ask the 5194 // user their preference, if we're looking for an "always" type entry. 5195 if (always && !pa.mPref.sameSet(query)) { 5196 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5197 + intent + " type " + resolvedType); 5198 if (DEBUG_PREFERRED) { 5199 Slog.v(TAG, "Removing preferred activity since set changed " 5200 + pa.mPref.mComponent); 5201 } 5202 pir.removeFilter(pa); 5203 // Re-add the filter as a "last chosen" entry (!always) 5204 PreferredActivity lastChosen = new PreferredActivity( 5205 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5206 pir.addFilter(lastChosen); 5207 changed = true; 5208 return null; 5209 } 5210 5211 // Yay! Either the set matched or we're looking for the last chosen 5212 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5213 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5214 return ri; 5215 } 5216 } 5217 } finally { 5218 if (changed) { 5219 if (DEBUG_PREFERRED) { 5220 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5221 } 5222 scheduleWritePackageRestrictionsLocked(userId); 5223 } 5224 } 5225 } 5226 } 5227 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5228 return null; 5229 } 5230 5231 /* 5232 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5233 */ 5234 @Override 5235 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5236 int targetUserId) { 5237 mContext.enforceCallingOrSelfPermission( 5238 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5239 List<CrossProfileIntentFilter> matches = 5240 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5241 if (matches != null) { 5242 int size = matches.size(); 5243 for (int i = 0; i < size; i++) { 5244 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5245 } 5246 } 5247 if (hasWebURI(intent)) { 5248 // cross-profile app linking works only towards the parent. 5249 final UserInfo parent = getProfileParent(sourceUserId); 5250 synchronized(mPackages) { 5251 int flags = updateFlagsForResolve(0, parent.id, intent); 5252 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5253 intent, resolvedType, flags, sourceUserId, parent.id); 5254 return xpDomainInfo != null; 5255 } 5256 } 5257 return false; 5258 } 5259 5260 private UserInfo getProfileParent(int userId) { 5261 final long identity = Binder.clearCallingIdentity(); 5262 try { 5263 return sUserManager.getProfileParent(userId); 5264 } finally { 5265 Binder.restoreCallingIdentity(identity); 5266 } 5267 } 5268 5269 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5270 String resolvedType, int userId) { 5271 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5272 if (resolver != null) { 5273 return resolver.queryIntent(intent, resolvedType, false, userId); 5274 } 5275 return null; 5276 } 5277 5278 @Override 5279 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5280 String resolvedType, int flags, int userId) { 5281 try { 5282 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5283 5284 return new ParceledListSlice<>( 5285 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5286 } finally { 5287 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5288 } 5289 } 5290 5291 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5292 String resolvedType, int flags, int userId) { 5293 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5294 flags = updateFlagsForResolve(flags, userId, intent); 5295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5296 false /* requireFullPermission */, false /* checkShell */, 5297 "query intent activities"); 5298 ComponentName comp = intent.getComponent(); 5299 if (comp == null) { 5300 if (intent.getSelector() != null) { 5301 intent = intent.getSelector(); 5302 comp = intent.getComponent(); 5303 } 5304 } 5305 5306 if (comp != null) { 5307 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5308 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5309 if (ai != null) { 5310 final ResolveInfo ri = new ResolveInfo(); 5311 ri.activityInfo = ai; 5312 list.add(ri); 5313 } 5314 return list; 5315 } 5316 5317 // reader 5318 synchronized (mPackages) { 5319 final String pkgName = intent.getPackage(); 5320 if (pkgName == null) { 5321 List<CrossProfileIntentFilter> matchingFilters = 5322 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5323 // Check for results that need to skip the current profile. 5324 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5325 resolvedType, flags, userId); 5326 if (xpResolveInfo != null) { 5327 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5328 result.add(xpResolveInfo); 5329 return filterIfNotSystemUser(result, userId); 5330 } 5331 5332 // Check for results in the current profile. 5333 List<ResolveInfo> result = mActivities.queryIntent( 5334 intent, resolvedType, flags, userId); 5335 result = filterIfNotSystemUser(result, userId); 5336 5337 // Check for cross profile results. 5338 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5339 xpResolveInfo = queryCrossProfileIntents( 5340 matchingFilters, intent, resolvedType, flags, userId, 5341 hasNonNegativePriorityResult); 5342 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5343 boolean isVisibleToUser = filterIfNotSystemUser( 5344 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5345 if (isVisibleToUser) { 5346 result.add(xpResolveInfo); 5347 Collections.sort(result, mResolvePrioritySorter); 5348 } 5349 } 5350 if (hasWebURI(intent)) { 5351 CrossProfileDomainInfo xpDomainInfo = null; 5352 final UserInfo parent = getProfileParent(userId); 5353 if (parent != null) { 5354 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5355 flags, userId, parent.id); 5356 } 5357 if (xpDomainInfo != null) { 5358 if (xpResolveInfo != null) { 5359 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5360 // in the result. 5361 result.remove(xpResolveInfo); 5362 } 5363 if (result.size() == 0) { 5364 result.add(xpDomainInfo.resolveInfo); 5365 return result; 5366 } 5367 } else if (result.size() <= 1) { 5368 return result; 5369 } 5370 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5371 xpDomainInfo, userId); 5372 Collections.sort(result, mResolvePrioritySorter); 5373 } 5374 return result; 5375 } 5376 final PackageParser.Package pkg = mPackages.get(pkgName); 5377 if (pkg != null) { 5378 return filterIfNotSystemUser( 5379 mActivities.queryIntentForPackage( 5380 intent, resolvedType, flags, pkg.activities, userId), 5381 userId); 5382 } 5383 return new ArrayList<ResolveInfo>(); 5384 } 5385 } 5386 5387 private static class CrossProfileDomainInfo { 5388 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5389 ResolveInfo resolveInfo; 5390 /* Best domain verification status of the activities found in the other profile */ 5391 int bestDomainVerificationStatus; 5392 } 5393 5394 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5395 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5396 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5397 sourceUserId)) { 5398 return null; 5399 } 5400 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5401 resolvedType, flags, parentUserId); 5402 5403 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5404 return null; 5405 } 5406 CrossProfileDomainInfo result = null; 5407 int size = resultTargetUser.size(); 5408 for (int i = 0; i < size; i++) { 5409 ResolveInfo riTargetUser = resultTargetUser.get(i); 5410 // Intent filter verification is only for filters that specify a host. So don't return 5411 // those that handle all web uris. 5412 if (riTargetUser.handleAllWebDataURI) { 5413 continue; 5414 } 5415 String packageName = riTargetUser.activityInfo.packageName; 5416 PackageSetting ps = mSettings.mPackages.get(packageName); 5417 if (ps == null) { 5418 continue; 5419 } 5420 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5421 int status = (int)(verificationState >> 32); 5422 if (result == null) { 5423 result = new CrossProfileDomainInfo(); 5424 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5425 sourceUserId, parentUserId); 5426 result.bestDomainVerificationStatus = status; 5427 } else { 5428 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5429 result.bestDomainVerificationStatus); 5430 } 5431 } 5432 // Don't consider matches with status NEVER across profiles. 5433 if (result != null && result.bestDomainVerificationStatus 5434 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5435 return null; 5436 } 5437 return result; 5438 } 5439 5440 /** 5441 * Verification statuses are ordered from the worse to the best, except for 5442 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5443 */ 5444 private int bestDomainVerificationStatus(int status1, int status2) { 5445 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5446 return status2; 5447 } 5448 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5449 return status1; 5450 } 5451 return (int) MathUtils.max(status1, status2); 5452 } 5453 5454 private boolean isUserEnabled(int userId) { 5455 long callingId = Binder.clearCallingIdentity(); 5456 try { 5457 UserInfo userInfo = sUserManager.getUserInfo(userId); 5458 return userInfo != null && userInfo.isEnabled(); 5459 } finally { 5460 Binder.restoreCallingIdentity(callingId); 5461 } 5462 } 5463 5464 /** 5465 * Filter out activities with systemUserOnly flag set, when current user is not System. 5466 * 5467 * @return filtered list 5468 */ 5469 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5470 if (userId == UserHandle.USER_SYSTEM) { 5471 return resolveInfos; 5472 } 5473 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5474 ResolveInfo info = resolveInfos.get(i); 5475 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5476 resolveInfos.remove(i); 5477 } 5478 } 5479 return resolveInfos; 5480 } 5481 5482 /** 5483 * @param resolveInfos list of resolve infos in descending priority order 5484 * @return if the list contains a resolve info with non-negative priority 5485 */ 5486 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5487 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5488 } 5489 5490 private static boolean hasWebURI(Intent intent) { 5491 if (intent.getData() == null) { 5492 return false; 5493 } 5494 final String scheme = intent.getScheme(); 5495 if (TextUtils.isEmpty(scheme)) { 5496 return false; 5497 } 5498 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5499 } 5500 5501 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5502 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5503 int userId) { 5504 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5505 5506 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5507 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5508 candidates.size()); 5509 } 5510 5511 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5512 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5513 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5514 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5515 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5516 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5517 5518 synchronized (mPackages) { 5519 final int count = candidates.size(); 5520 // First, try to use linked apps. Partition the candidates into four lists: 5521 // one for the final results, one for the "do not use ever", one for "undefined status" 5522 // and finally one for "browser app type". 5523 for (int n=0; n<count; n++) { 5524 ResolveInfo info = candidates.get(n); 5525 String packageName = info.activityInfo.packageName; 5526 PackageSetting ps = mSettings.mPackages.get(packageName); 5527 if (ps != null) { 5528 // Add to the special match all list (Browser use case) 5529 if (info.handleAllWebDataURI) { 5530 matchAllList.add(info); 5531 continue; 5532 } 5533 // Try to get the status from User settings first 5534 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5535 int status = (int)(packedStatus >> 32); 5536 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5537 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5538 if (DEBUG_DOMAIN_VERIFICATION) { 5539 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5540 + " : linkgen=" + linkGeneration); 5541 } 5542 // Use link-enabled generation as preferredOrder, i.e. 5543 // prefer newly-enabled over earlier-enabled. 5544 info.preferredOrder = linkGeneration; 5545 alwaysList.add(info); 5546 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5547 if (DEBUG_DOMAIN_VERIFICATION) { 5548 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5549 } 5550 neverList.add(info); 5551 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5552 if (DEBUG_DOMAIN_VERIFICATION) { 5553 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5554 } 5555 alwaysAskList.add(info); 5556 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5557 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5558 if (DEBUG_DOMAIN_VERIFICATION) { 5559 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5560 } 5561 undefinedList.add(info); 5562 } 5563 } 5564 } 5565 5566 // We'll want to include browser possibilities in a few cases 5567 boolean includeBrowser = false; 5568 5569 // First try to add the "always" resolution(s) for the current user, if any 5570 if (alwaysList.size() > 0) { 5571 result.addAll(alwaysList); 5572 } else { 5573 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5574 result.addAll(undefinedList); 5575 // Maybe add one for the other profile. 5576 if (xpDomainInfo != null && ( 5577 xpDomainInfo.bestDomainVerificationStatus 5578 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5579 result.add(xpDomainInfo.resolveInfo); 5580 } 5581 includeBrowser = true; 5582 } 5583 5584 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5585 // If there were 'always' entries their preferred order has been set, so we also 5586 // back that off to make the alternatives equivalent 5587 if (alwaysAskList.size() > 0) { 5588 for (ResolveInfo i : result) { 5589 i.preferredOrder = 0; 5590 } 5591 result.addAll(alwaysAskList); 5592 includeBrowser = true; 5593 } 5594 5595 if (includeBrowser) { 5596 // Also add browsers (all of them or only the default one) 5597 if (DEBUG_DOMAIN_VERIFICATION) { 5598 Slog.v(TAG, " ...including browsers in candidate set"); 5599 } 5600 if ((matchFlags & MATCH_ALL) != 0) { 5601 result.addAll(matchAllList); 5602 } else { 5603 // Browser/generic handling case. If there's a default browser, go straight 5604 // to that (but only if there is no other higher-priority match). 5605 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5606 int maxMatchPrio = 0; 5607 ResolveInfo defaultBrowserMatch = null; 5608 final int numCandidates = matchAllList.size(); 5609 for (int n = 0; n < numCandidates; n++) { 5610 ResolveInfo info = matchAllList.get(n); 5611 // track the highest overall match priority... 5612 if (info.priority > maxMatchPrio) { 5613 maxMatchPrio = info.priority; 5614 } 5615 // ...and the highest-priority default browser match 5616 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5617 if (defaultBrowserMatch == null 5618 || (defaultBrowserMatch.priority < info.priority)) { 5619 if (debug) { 5620 Slog.v(TAG, "Considering default browser match " + info); 5621 } 5622 defaultBrowserMatch = info; 5623 } 5624 } 5625 } 5626 if (defaultBrowserMatch != null 5627 && defaultBrowserMatch.priority >= maxMatchPrio 5628 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5629 { 5630 if (debug) { 5631 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5632 } 5633 result.add(defaultBrowserMatch); 5634 } else { 5635 result.addAll(matchAllList); 5636 } 5637 } 5638 5639 // If there is nothing selected, add all candidates and remove the ones that the user 5640 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5641 if (result.size() == 0) { 5642 result.addAll(candidates); 5643 result.removeAll(neverList); 5644 } 5645 } 5646 } 5647 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5648 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5649 result.size()); 5650 for (ResolveInfo info : result) { 5651 Slog.v(TAG, " + " + info.activityInfo); 5652 } 5653 } 5654 return result; 5655 } 5656 5657 // Returns a packed value as a long: 5658 // 5659 // high 'int'-sized word: link status: undefined/ask/never/always. 5660 // low 'int'-sized word: relative priority among 'always' results. 5661 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5662 long result = ps.getDomainVerificationStatusForUser(userId); 5663 // if none available, get the master status 5664 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5665 if (ps.getIntentFilterVerificationInfo() != null) { 5666 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5667 } 5668 } 5669 return result; 5670 } 5671 5672 private ResolveInfo querySkipCurrentProfileIntents( 5673 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5674 int flags, int sourceUserId) { 5675 if (matchingFilters != null) { 5676 int size = matchingFilters.size(); 5677 for (int i = 0; i < size; i ++) { 5678 CrossProfileIntentFilter filter = matchingFilters.get(i); 5679 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5680 // Checking if there are activities in the target user that can handle the 5681 // intent. 5682 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5683 resolvedType, flags, sourceUserId); 5684 if (resolveInfo != null) { 5685 return resolveInfo; 5686 } 5687 } 5688 } 5689 } 5690 return null; 5691 } 5692 5693 // Return matching ResolveInfo in target user if any. 5694 private ResolveInfo queryCrossProfileIntents( 5695 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5696 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5697 if (matchingFilters != null) { 5698 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5699 // match the same intent. For performance reasons, it is better not to 5700 // run queryIntent twice for the same userId 5701 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5702 int size = matchingFilters.size(); 5703 for (int i = 0; i < size; i++) { 5704 CrossProfileIntentFilter filter = matchingFilters.get(i); 5705 int targetUserId = filter.getTargetUserId(); 5706 boolean skipCurrentProfile = 5707 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5708 boolean skipCurrentProfileIfNoMatchFound = 5709 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5710 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5711 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5712 // Checking if there are activities in the target user that can handle the 5713 // intent. 5714 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5715 resolvedType, flags, sourceUserId); 5716 if (resolveInfo != null) return resolveInfo; 5717 alreadyTriedUserIds.put(targetUserId, true); 5718 } 5719 } 5720 } 5721 return null; 5722 } 5723 5724 /** 5725 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5726 * will forward the intent to the filter's target user. 5727 * Otherwise, returns null. 5728 */ 5729 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5730 String resolvedType, int flags, int sourceUserId) { 5731 int targetUserId = filter.getTargetUserId(); 5732 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5733 resolvedType, flags, targetUserId); 5734 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5735 // If all the matches in the target profile are suspended, return null. 5736 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5737 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5738 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5739 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5740 targetUserId); 5741 } 5742 } 5743 } 5744 return null; 5745 } 5746 5747 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5748 int sourceUserId, int targetUserId) { 5749 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5750 long ident = Binder.clearCallingIdentity(); 5751 boolean targetIsProfile; 5752 try { 5753 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5754 } finally { 5755 Binder.restoreCallingIdentity(ident); 5756 } 5757 String className; 5758 if (targetIsProfile) { 5759 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5760 } else { 5761 className = FORWARD_INTENT_TO_PARENT; 5762 } 5763 ComponentName forwardingActivityComponentName = new ComponentName( 5764 mAndroidApplication.packageName, className); 5765 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5766 sourceUserId); 5767 if (!targetIsProfile) { 5768 forwardingActivityInfo.showUserIcon = targetUserId; 5769 forwardingResolveInfo.noResourceId = true; 5770 } 5771 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5772 forwardingResolveInfo.priority = 0; 5773 forwardingResolveInfo.preferredOrder = 0; 5774 forwardingResolveInfo.match = 0; 5775 forwardingResolveInfo.isDefault = true; 5776 forwardingResolveInfo.filter = filter; 5777 forwardingResolveInfo.targetUserId = targetUserId; 5778 return forwardingResolveInfo; 5779 } 5780 5781 @Override 5782 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5783 Intent[] specifics, String[] specificTypes, Intent intent, 5784 String resolvedType, int flags, int userId) { 5785 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5786 specificTypes, intent, resolvedType, flags, userId)); 5787 } 5788 5789 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5790 Intent[] specifics, String[] specificTypes, Intent intent, 5791 String resolvedType, int flags, int userId) { 5792 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5793 flags = updateFlagsForResolve(flags, userId, intent); 5794 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5795 false /* requireFullPermission */, false /* checkShell */, 5796 "query intent activity options"); 5797 final String resultsAction = intent.getAction(); 5798 5799 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5800 | PackageManager.GET_RESOLVED_FILTER, userId); 5801 5802 if (DEBUG_INTENT_MATCHING) { 5803 Log.v(TAG, "Query " + intent + ": " + results); 5804 } 5805 5806 int specificsPos = 0; 5807 int N; 5808 5809 // todo: note that the algorithm used here is O(N^2). This 5810 // isn't a problem in our current environment, but if we start running 5811 // into situations where we have more than 5 or 10 matches then this 5812 // should probably be changed to something smarter... 5813 5814 // First we go through and resolve each of the specific items 5815 // that were supplied, taking care of removing any corresponding 5816 // duplicate items in the generic resolve list. 5817 if (specifics != null) { 5818 for (int i=0; i<specifics.length; i++) { 5819 final Intent sintent = specifics[i]; 5820 if (sintent == null) { 5821 continue; 5822 } 5823 5824 if (DEBUG_INTENT_MATCHING) { 5825 Log.v(TAG, "Specific #" + i + ": " + sintent); 5826 } 5827 5828 String action = sintent.getAction(); 5829 if (resultsAction != null && resultsAction.equals(action)) { 5830 // If this action was explicitly requested, then don't 5831 // remove things that have it. 5832 action = null; 5833 } 5834 5835 ResolveInfo ri = null; 5836 ActivityInfo ai = null; 5837 5838 ComponentName comp = sintent.getComponent(); 5839 if (comp == null) { 5840 ri = resolveIntent( 5841 sintent, 5842 specificTypes != null ? specificTypes[i] : null, 5843 flags, userId); 5844 if (ri == null) { 5845 continue; 5846 } 5847 if (ri == mResolveInfo) { 5848 // ACK! Must do something better with this. 5849 } 5850 ai = ri.activityInfo; 5851 comp = new ComponentName(ai.applicationInfo.packageName, 5852 ai.name); 5853 } else { 5854 ai = getActivityInfo(comp, flags, userId); 5855 if (ai == null) { 5856 continue; 5857 } 5858 } 5859 5860 // Look for any generic query activities that are duplicates 5861 // of this specific one, and remove them from the results. 5862 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5863 N = results.size(); 5864 int j; 5865 for (j=specificsPos; j<N; j++) { 5866 ResolveInfo sri = results.get(j); 5867 if ((sri.activityInfo.name.equals(comp.getClassName()) 5868 && sri.activityInfo.applicationInfo.packageName.equals( 5869 comp.getPackageName())) 5870 || (action != null && sri.filter.matchAction(action))) { 5871 results.remove(j); 5872 if (DEBUG_INTENT_MATCHING) Log.v( 5873 TAG, "Removing duplicate item from " + j 5874 + " due to specific " + specificsPos); 5875 if (ri == null) { 5876 ri = sri; 5877 } 5878 j--; 5879 N--; 5880 } 5881 } 5882 5883 // Add this specific item to its proper place. 5884 if (ri == null) { 5885 ri = new ResolveInfo(); 5886 ri.activityInfo = ai; 5887 } 5888 results.add(specificsPos, ri); 5889 ri.specificIndex = i; 5890 specificsPos++; 5891 } 5892 } 5893 5894 // Now we go through the remaining generic results and remove any 5895 // duplicate actions that are found here. 5896 N = results.size(); 5897 for (int i=specificsPos; i<N-1; i++) { 5898 final ResolveInfo rii = results.get(i); 5899 if (rii.filter == null) { 5900 continue; 5901 } 5902 5903 // Iterate over all of the actions of this result's intent 5904 // filter... typically this should be just one. 5905 final Iterator<String> it = rii.filter.actionsIterator(); 5906 if (it == null) { 5907 continue; 5908 } 5909 while (it.hasNext()) { 5910 final String action = it.next(); 5911 if (resultsAction != null && resultsAction.equals(action)) { 5912 // If this action was explicitly requested, then don't 5913 // remove things that have it. 5914 continue; 5915 } 5916 for (int j=i+1; j<N; j++) { 5917 final ResolveInfo rij = results.get(j); 5918 if (rij.filter != null && rij.filter.hasAction(action)) { 5919 results.remove(j); 5920 if (DEBUG_INTENT_MATCHING) Log.v( 5921 TAG, "Removing duplicate item from " + j 5922 + " due to action " + action + " at " + i); 5923 j--; 5924 N--; 5925 } 5926 } 5927 } 5928 5929 // If the caller didn't request filter information, drop it now 5930 // so we don't have to marshall/unmarshall it. 5931 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5932 rii.filter = null; 5933 } 5934 } 5935 5936 // Filter out the caller activity if so requested. 5937 if (caller != null) { 5938 N = results.size(); 5939 for (int i=0; i<N; i++) { 5940 ActivityInfo ainfo = results.get(i).activityInfo; 5941 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5942 && caller.getClassName().equals(ainfo.name)) { 5943 results.remove(i); 5944 break; 5945 } 5946 } 5947 } 5948 5949 // If the caller didn't request filter information, 5950 // drop them now so we don't have to 5951 // marshall/unmarshall it. 5952 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5953 N = results.size(); 5954 for (int i=0; i<N; i++) { 5955 results.get(i).filter = null; 5956 } 5957 } 5958 5959 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5960 return results; 5961 } 5962 5963 @Override 5964 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5965 String resolvedType, int flags, int userId) { 5966 return new ParceledListSlice<>( 5967 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5968 } 5969 5970 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5971 String resolvedType, int flags, int userId) { 5972 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5973 flags = updateFlagsForResolve(flags, userId, intent); 5974 ComponentName comp = intent.getComponent(); 5975 if (comp == null) { 5976 if (intent.getSelector() != null) { 5977 intent = intent.getSelector(); 5978 comp = intent.getComponent(); 5979 } 5980 } 5981 if (comp != null) { 5982 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5983 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5984 if (ai != null) { 5985 ResolveInfo ri = new ResolveInfo(); 5986 ri.activityInfo = ai; 5987 list.add(ri); 5988 } 5989 return list; 5990 } 5991 5992 // reader 5993 synchronized (mPackages) { 5994 String pkgName = intent.getPackage(); 5995 if (pkgName == null) { 5996 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5997 } 5998 final PackageParser.Package pkg = mPackages.get(pkgName); 5999 if (pkg != null) { 6000 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6001 userId); 6002 } 6003 return Collections.emptyList(); 6004 } 6005 } 6006 6007 @Override 6008 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6009 if (!sUserManager.exists(userId)) return null; 6010 flags = updateFlagsForResolve(flags, userId, intent); 6011 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6012 if (query != null) { 6013 if (query.size() >= 1) { 6014 // If there is more than one service with the same priority, 6015 // just arbitrarily pick the first one. 6016 return query.get(0); 6017 } 6018 } 6019 return null; 6020 } 6021 6022 @Override 6023 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6024 String resolvedType, int flags, int userId) { 6025 return new ParceledListSlice<>( 6026 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6027 } 6028 6029 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6030 String resolvedType, int flags, int userId) { 6031 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6032 flags = updateFlagsForResolve(flags, userId, intent); 6033 ComponentName comp = intent.getComponent(); 6034 if (comp == null) { 6035 if (intent.getSelector() != null) { 6036 intent = intent.getSelector(); 6037 comp = intent.getComponent(); 6038 } 6039 } 6040 if (comp != null) { 6041 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6042 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6043 if (si != null) { 6044 final ResolveInfo ri = new ResolveInfo(); 6045 ri.serviceInfo = si; 6046 list.add(ri); 6047 } 6048 return list; 6049 } 6050 6051 // reader 6052 synchronized (mPackages) { 6053 String pkgName = intent.getPackage(); 6054 if (pkgName == null) { 6055 return mServices.queryIntent(intent, resolvedType, flags, userId); 6056 } 6057 final PackageParser.Package pkg = mPackages.get(pkgName); 6058 if (pkg != null) { 6059 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6060 userId); 6061 } 6062 return Collections.emptyList(); 6063 } 6064 } 6065 6066 @Override 6067 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6068 String resolvedType, int flags, int userId) { 6069 return new ParceledListSlice<>( 6070 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6071 } 6072 6073 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6074 Intent intent, String resolvedType, int flags, int userId) { 6075 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6076 flags = updateFlagsForResolve(flags, userId, intent); 6077 ComponentName comp = intent.getComponent(); 6078 if (comp == null) { 6079 if (intent.getSelector() != null) { 6080 intent = intent.getSelector(); 6081 comp = intent.getComponent(); 6082 } 6083 } 6084 if (comp != null) { 6085 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6086 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6087 if (pi != null) { 6088 final ResolveInfo ri = new ResolveInfo(); 6089 ri.providerInfo = pi; 6090 list.add(ri); 6091 } 6092 return list; 6093 } 6094 6095 // reader 6096 synchronized (mPackages) { 6097 String pkgName = intent.getPackage(); 6098 if (pkgName == null) { 6099 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6100 } 6101 final PackageParser.Package pkg = mPackages.get(pkgName); 6102 if (pkg != null) { 6103 return mProviders.queryIntentForPackage( 6104 intent, resolvedType, flags, pkg.providers, userId); 6105 } 6106 return Collections.emptyList(); 6107 } 6108 } 6109 6110 @Override 6111 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6112 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6113 flags = updateFlagsForPackage(flags, userId, null); 6114 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6115 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6116 true /* requireFullPermission */, false /* checkShell */, 6117 "get installed packages"); 6118 6119 // writer 6120 synchronized (mPackages) { 6121 ArrayList<PackageInfo> list; 6122 if (listUninstalled) { 6123 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6124 for (PackageSetting ps : mSettings.mPackages.values()) { 6125 final PackageInfo pi; 6126 if (ps.pkg != null) { 6127 pi = generatePackageInfo(ps, flags, userId); 6128 } else { 6129 pi = generatePackageInfo(ps, flags, userId); 6130 } 6131 if (pi != null) { 6132 list.add(pi); 6133 } 6134 } 6135 } else { 6136 list = new ArrayList<PackageInfo>(mPackages.size()); 6137 for (PackageParser.Package p : mPackages.values()) { 6138 final PackageInfo pi = 6139 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6140 if (pi != null) { 6141 list.add(pi); 6142 } 6143 } 6144 } 6145 6146 return new ParceledListSlice<PackageInfo>(list); 6147 } 6148 } 6149 6150 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6151 String[] permissions, boolean[] tmp, int flags, int userId) { 6152 int numMatch = 0; 6153 final PermissionsState permissionsState = ps.getPermissionsState(); 6154 for (int i=0; i<permissions.length; i++) { 6155 final String permission = permissions[i]; 6156 if (permissionsState.hasPermission(permission, userId)) { 6157 tmp[i] = true; 6158 numMatch++; 6159 } else { 6160 tmp[i] = false; 6161 } 6162 } 6163 if (numMatch == 0) { 6164 return; 6165 } 6166 final PackageInfo pi; 6167 if (ps.pkg != null) { 6168 pi = generatePackageInfo(ps, flags, userId); 6169 } else { 6170 pi = generatePackageInfo(ps, flags, userId); 6171 } 6172 // The above might return null in cases of uninstalled apps or install-state 6173 // skew across users/profiles. 6174 if (pi != null) { 6175 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6176 if (numMatch == permissions.length) { 6177 pi.requestedPermissions = permissions; 6178 } else { 6179 pi.requestedPermissions = new String[numMatch]; 6180 numMatch = 0; 6181 for (int i=0; i<permissions.length; i++) { 6182 if (tmp[i]) { 6183 pi.requestedPermissions[numMatch] = permissions[i]; 6184 numMatch++; 6185 } 6186 } 6187 } 6188 } 6189 list.add(pi); 6190 } 6191 } 6192 6193 @Override 6194 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6195 String[] permissions, int flags, int userId) { 6196 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6197 flags = updateFlagsForPackage(flags, userId, permissions); 6198 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6199 6200 // writer 6201 synchronized (mPackages) { 6202 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6203 boolean[] tmpBools = new boolean[permissions.length]; 6204 if (listUninstalled) { 6205 for (PackageSetting ps : mSettings.mPackages.values()) { 6206 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6207 } 6208 } else { 6209 for (PackageParser.Package pkg : mPackages.values()) { 6210 PackageSetting ps = (PackageSetting)pkg.mExtras; 6211 if (ps != null) { 6212 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6213 userId); 6214 } 6215 } 6216 } 6217 6218 return new ParceledListSlice<PackageInfo>(list); 6219 } 6220 } 6221 6222 @Override 6223 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6224 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6225 flags = updateFlagsForApplication(flags, userId, null); 6226 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6227 6228 // writer 6229 synchronized (mPackages) { 6230 ArrayList<ApplicationInfo> list; 6231 if (listUninstalled) { 6232 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6233 for (PackageSetting ps : mSettings.mPackages.values()) { 6234 ApplicationInfo ai; 6235 if (ps.pkg != null) { 6236 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6237 ps.readUserState(userId), userId); 6238 } else { 6239 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6240 } 6241 if (ai != null) { 6242 list.add(ai); 6243 } 6244 } 6245 } else { 6246 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6247 for (PackageParser.Package p : mPackages.values()) { 6248 if (p.mExtras != null) { 6249 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6250 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6251 if (ai != null) { 6252 list.add(ai); 6253 } 6254 } 6255 } 6256 } 6257 6258 return new ParceledListSlice<ApplicationInfo>(list); 6259 } 6260 } 6261 6262 @Override 6263 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6264 if (DISABLE_EPHEMERAL_APPS) { 6265 return null; 6266 } 6267 6268 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6269 "getEphemeralApplications"); 6270 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6271 true /* requireFullPermission */, false /* checkShell */, 6272 "getEphemeralApplications"); 6273 synchronized (mPackages) { 6274 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6275 .getEphemeralApplicationsLPw(userId); 6276 if (ephemeralApps != null) { 6277 return new ParceledListSlice<>(ephemeralApps); 6278 } 6279 } 6280 return null; 6281 } 6282 6283 @Override 6284 public boolean isEphemeralApplication(String packageName, int userId) { 6285 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6286 true /* requireFullPermission */, false /* checkShell */, 6287 "isEphemeral"); 6288 if (DISABLE_EPHEMERAL_APPS) { 6289 return false; 6290 } 6291 6292 if (!isCallerSameApp(packageName)) { 6293 return false; 6294 } 6295 synchronized (mPackages) { 6296 PackageParser.Package pkg = mPackages.get(packageName); 6297 if (pkg != null) { 6298 return pkg.applicationInfo.isEphemeralApp(); 6299 } 6300 } 6301 return false; 6302 } 6303 6304 @Override 6305 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6306 if (DISABLE_EPHEMERAL_APPS) { 6307 return null; 6308 } 6309 6310 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6311 true /* requireFullPermission */, false /* checkShell */, 6312 "getCookie"); 6313 if (!isCallerSameApp(packageName)) { 6314 return null; 6315 } 6316 synchronized (mPackages) { 6317 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6318 packageName, userId); 6319 } 6320 } 6321 6322 @Override 6323 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6324 if (DISABLE_EPHEMERAL_APPS) { 6325 return true; 6326 } 6327 6328 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6329 true /* requireFullPermission */, true /* checkShell */, 6330 "setCookie"); 6331 if (!isCallerSameApp(packageName)) { 6332 return false; 6333 } 6334 synchronized (mPackages) { 6335 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6336 packageName, cookie, userId); 6337 } 6338 } 6339 6340 @Override 6341 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6342 if (DISABLE_EPHEMERAL_APPS) { 6343 return null; 6344 } 6345 6346 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6347 "getEphemeralApplicationIcon"); 6348 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6349 true /* requireFullPermission */, false /* checkShell */, 6350 "getEphemeralApplicationIcon"); 6351 synchronized (mPackages) { 6352 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6353 packageName, userId); 6354 } 6355 } 6356 6357 private boolean isCallerSameApp(String packageName) { 6358 PackageParser.Package pkg = mPackages.get(packageName); 6359 return pkg != null 6360 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6361 } 6362 6363 @Override 6364 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6365 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6366 } 6367 6368 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6369 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6370 6371 // reader 6372 synchronized (mPackages) { 6373 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6374 final int userId = UserHandle.getCallingUserId(); 6375 while (i.hasNext()) { 6376 final PackageParser.Package p = i.next(); 6377 if (p.applicationInfo == null) continue; 6378 6379 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6380 && !p.applicationInfo.isDirectBootAware(); 6381 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6382 && p.applicationInfo.isDirectBootAware(); 6383 6384 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6385 && (!mSafeMode || isSystemApp(p)) 6386 && (matchesUnaware || matchesAware)) { 6387 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6388 if (ps != null) { 6389 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6390 ps.readUserState(userId), userId); 6391 if (ai != null) { 6392 finalList.add(ai); 6393 } 6394 } 6395 } 6396 } 6397 } 6398 6399 return finalList; 6400 } 6401 6402 @Override 6403 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6404 if (!sUserManager.exists(userId)) return null; 6405 flags = updateFlagsForComponent(flags, userId, name); 6406 // reader 6407 synchronized (mPackages) { 6408 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6409 PackageSetting ps = provider != null 6410 ? mSettings.mPackages.get(provider.owner.packageName) 6411 : null; 6412 return ps != null 6413 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6414 ? PackageParser.generateProviderInfo(provider, flags, 6415 ps.readUserState(userId), userId) 6416 : null; 6417 } 6418 } 6419 6420 /** 6421 * @deprecated 6422 */ 6423 @Deprecated 6424 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6425 // reader 6426 synchronized (mPackages) { 6427 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6428 .entrySet().iterator(); 6429 final int userId = UserHandle.getCallingUserId(); 6430 while (i.hasNext()) { 6431 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6432 PackageParser.Provider p = entry.getValue(); 6433 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6434 6435 if (ps != null && p.syncable 6436 && (!mSafeMode || (p.info.applicationInfo.flags 6437 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6438 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6439 ps.readUserState(userId), userId); 6440 if (info != null) { 6441 outNames.add(entry.getKey()); 6442 outInfo.add(info); 6443 } 6444 } 6445 } 6446 } 6447 } 6448 6449 @Override 6450 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6451 int uid, int flags) { 6452 final int userId = processName != null ? UserHandle.getUserId(uid) 6453 : UserHandle.getCallingUserId(); 6454 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6455 flags = updateFlagsForComponent(flags, userId, processName); 6456 6457 ArrayList<ProviderInfo> finalList = null; 6458 // reader 6459 synchronized (mPackages) { 6460 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6461 while (i.hasNext()) { 6462 final PackageParser.Provider p = i.next(); 6463 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6464 if (ps != null && p.info.authority != null 6465 && (processName == null 6466 || (p.info.processName.equals(processName) 6467 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6468 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6469 if (finalList == null) { 6470 finalList = new ArrayList<ProviderInfo>(3); 6471 } 6472 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6473 ps.readUserState(userId), userId); 6474 if (info != null) { 6475 finalList.add(info); 6476 } 6477 } 6478 } 6479 } 6480 6481 if (finalList != null) { 6482 Collections.sort(finalList, mProviderInitOrderSorter); 6483 return new ParceledListSlice<ProviderInfo>(finalList); 6484 } 6485 6486 return ParceledListSlice.emptyList(); 6487 } 6488 6489 @Override 6490 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6491 // reader 6492 synchronized (mPackages) { 6493 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6494 return PackageParser.generateInstrumentationInfo(i, flags); 6495 } 6496 } 6497 6498 @Override 6499 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6500 String targetPackage, int flags) { 6501 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6502 } 6503 6504 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6505 int flags) { 6506 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6507 6508 // reader 6509 synchronized (mPackages) { 6510 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6511 while (i.hasNext()) { 6512 final PackageParser.Instrumentation p = i.next(); 6513 if (targetPackage == null 6514 || targetPackage.equals(p.info.targetPackage)) { 6515 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6516 flags); 6517 if (ii != null) { 6518 finalList.add(ii); 6519 } 6520 } 6521 } 6522 } 6523 6524 return finalList; 6525 } 6526 6527 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6528 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6529 if (overlays == null) { 6530 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6531 return; 6532 } 6533 for (PackageParser.Package opkg : overlays.values()) { 6534 // Not much to do if idmap fails: we already logged the error 6535 // and we certainly don't want to abort installation of pkg simply 6536 // because an overlay didn't fit properly. For these reasons, 6537 // ignore the return value of createIdmapForPackagePairLI. 6538 createIdmapForPackagePairLI(pkg, opkg); 6539 } 6540 } 6541 6542 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6543 PackageParser.Package opkg) { 6544 if (!opkg.mTrustedOverlay) { 6545 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6546 opkg.baseCodePath + ": overlay not trusted"); 6547 return false; 6548 } 6549 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6550 if (overlaySet == null) { 6551 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6552 opkg.baseCodePath + " but target package has no known overlays"); 6553 return false; 6554 } 6555 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6556 // TODO: generate idmap for split APKs 6557 try { 6558 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6559 } catch (InstallerException e) { 6560 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6561 + opkg.baseCodePath); 6562 return false; 6563 } 6564 PackageParser.Package[] overlayArray = 6565 overlaySet.values().toArray(new PackageParser.Package[0]); 6566 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6567 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6568 return p1.mOverlayPriority - p2.mOverlayPriority; 6569 } 6570 }; 6571 Arrays.sort(overlayArray, cmp); 6572 6573 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6574 int i = 0; 6575 for (PackageParser.Package p : overlayArray) { 6576 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6577 } 6578 return true; 6579 } 6580 6581 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6582 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6583 try { 6584 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6585 } finally { 6586 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6587 } 6588 } 6589 6590 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6591 final File[] files = dir.listFiles(); 6592 if (ArrayUtils.isEmpty(files)) { 6593 Log.d(TAG, "No files in app dir " + dir); 6594 return; 6595 } 6596 6597 if (DEBUG_PACKAGE_SCANNING) { 6598 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6599 + " flags=0x" + Integer.toHexString(parseFlags)); 6600 } 6601 6602 for (File file : files) { 6603 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6604 && !PackageInstallerService.isStageName(file.getName()); 6605 if (!isPackage) { 6606 // Ignore entries which are not packages 6607 continue; 6608 } 6609 try { 6610 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6611 scanFlags, currentTime, null); 6612 } catch (PackageManagerException e) { 6613 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6614 6615 // Delete invalid userdata apps 6616 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6617 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6618 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6619 removeCodePathLI(file); 6620 } 6621 } 6622 } 6623 } 6624 6625 private static File getSettingsProblemFile() { 6626 File dataDir = Environment.getDataDirectory(); 6627 File systemDir = new File(dataDir, "system"); 6628 File fname = new File(systemDir, "uiderrors.txt"); 6629 return fname; 6630 } 6631 6632 static void reportSettingsProblem(int priority, String msg) { 6633 logCriticalInfo(priority, msg); 6634 } 6635 6636 static void logCriticalInfo(int priority, String msg) { 6637 Slog.println(priority, TAG, msg); 6638 EventLogTags.writePmCriticalInfo(msg); 6639 try { 6640 File fname = getSettingsProblemFile(); 6641 FileOutputStream out = new FileOutputStream(fname, true); 6642 PrintWriter pw = new FastPrintWriter(out); 6643 SimpleDateFormat formatter = new SimpleDateFormat(); 6644 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6645 pw.println(dateString + ": " + msg); 6646 pw.close(); 6647 FileUtils.setPermissions( 6648 fname.toString(), 6649 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6650 -1, -1); 6651 } catch (java.io.IOException e) { 6652 } 6653 } 6654 6655 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6656 final int policyFlags) throws PackageManagerException { 6657 if (ps != null 6658 && ps.codePath.equals(srcFile) 6659 && ps.timeStamp == srcFile.lastModified() 6660 && !isCompatSignatureUpdateNeeded(pkg) 6661 && !isRecoverSignatureUpdateNeeded(pkg)) { 6662 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6663 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6664 ArraySet<PublicKey> signingKs; 6665 synchronized (mPackages) { 6666 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6667 } 6668 if (ps.signatures.mSignatures != null 6669 && ps.signatures.mSignatures.length != 0 6670 && signingKs != null) { 6671 // Optimization: reuse the existing cached certificates 6672 // if the package appears to be unchanged. 6673 pkg.mSignatures = ps.signatures.mSignatures; 6674 pkg.mSigningKeys = signingKs; 6675 return; 6676 } 6677 6678 Slog.w(TAG, "PackageSetting for " + ps.name 6679 + " is missing signatures. Collecting certs again to recover them."); 6680 } else { 6681 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6682 } 6683 6684 try { 6685 PackageParser.collectCertificates(pkg, policyFlags); 6686 } catch (PackageParserException e) { 6687 throw PackageManagerException.from(e); 6688 } 6689 } 6690 6691 /** 6692 * Traces a package scan. 6693 * @see #scanPackageLI(File, int, int, long, UserHandle) 6694 */ 6695 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6696 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6697 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6698 try { 6699 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6700 } finally { 6701 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6702 } 6703 } 6704 6705 /** 6706 * Scans a package and returns the newly parsed package. 6707 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6708 */ 6709 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6710 long currentTime, UserHandle user) throws PackageManagerException { 6711 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6712 PackageParser pp = new PackageParser(); 6713 pp.setSeparateProcesses(mSeparateProcesses); 6714 pp.setOnlyCoreApps(mOnlyCore); 6715 pp.setDisplayMetrics(mMetrics); 6716 6717 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6718 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6719 } 6720 6721 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6722 final PackageParser.Package pkg; 6723 try { 6724 pkg = pp.parsePackage(scanFile, parseFlags); 6725 } catch (PackageParserException e) { 6726 throw PackageManagerException.from(e); 6727 } finally { 6728 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6729 } 6730 6731 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6732 } 6733 6734 /** 6735 * Scans a package and returns the newly parsed package. 6736 * @throws PackageManagerException on a parse error. 6737 */ 6738 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6739 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6740 throws PackageManagerException { 6741 // If the package has children and this is the first dive in the function 6742 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6743 // packages (parent and children) would be successfully scanned before the 6744 // actual scan since scanning mutates internal state and we want to atomically 6745 // install the package and its children. 6746 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6747 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6748 scanFlags |= SCAN_CHECK_ONLY; 6749 } 6750 } else { 6751 scanFlags &= ~SCAN_CHECK_ONLY; 6752 } 6753 6754 // Scan the parent 6755 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6756 scanFlags, currentTime, user); 6757 6758 // Scan the children 6759 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6760 for (int i = 0; i < childCount; i++) { 6761 PackageParser.Package childPackage = pkg.childPackages.get(i); 6762 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6763 currentTime, user); 6764 } 6765 6766 6767 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6768 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6769 } 6770 6771 return scannedPkg; 6772 } 6773 6774 /** 6775 * Scans a package and returns the newly parsed package. 6776 * @throws PackageManagerException on a parse error. 6777 */ 6778 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6779 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6780 throws PackageManagerException { 6781 PackageSetting ps = null; 6782 PackageSetting updatedPkg; 6783 // reader 6784 synchronized (mPackages) { 6785 // Look to see if we already know about this package. 6786 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6787 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6788 // This package has been renamed to its original name. Let's 6789 // use that. 6790 ps = mSettings.peekPackageLPr(oldName); 6791 } 6792 // If there was no original package, see one for the real package name. 6793 if (ps == null) { 6794 ps = mSettings.peekPackageLPr(pkg.packageName); 6795 } 6796 // Check to see if this package could be hiding/updating a system 6797 // package. Must look for it either under the original or real 6798 // package name depending on our state. 6799 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6800 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6801 6802 // If this is a package we don't know about on the system partition, we 6803 // may need to remove disabled child packages on the system partition 6804 // or may need to not add child packages if the parent apk is updated 6805 // on the data partition and no longer defines this child package. 6806 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6807 // If this is a parent package for an updated system app and this system 6808 // app got an OTA update which no longer defines some of the child packages 6809 // we have to prune them from the disabled system packages. 6810 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6811 if (disabledPs != null) { 6812 final int scannedChildCount = (pkg.childPackages != null) 6813 ? pkg.childPackages.size() : 0; 6814 final int disabledChildCount = disabledPs.childPackageNames != null 6815 ? disabledPs.childPackageNames.size() : 0; 6816 for (int i = 0; i < disabledChildCount; i++) { 6817 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6818 boolean disabledPackageAvailable = false; 6819 for (int j = 0; j < scannedChildCount; j++) { 6820 PackageParser.Package childPkg = pkg.childPackages.get(j); 6821 if (childPkg.packageName.equals(disabledChildPackageName)) { 6822 disabledPackageAvailable = true; 6823 break; 6824 } 6825 } 6826 if (!disabledPackageAvailable) { 6827 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6828 } 6829 } 6830 } 6831 } 6832 } 6833 6834 boolean updatedPkgBetter = false; 6835 // First check if this is a system package that may involve an update 6836 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6837 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6838 // it needs to drop FLAG_PRIVILEGED. 6839 if (locationIsPrivileged(scanFile)) { 6840 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6841 } else { 6842 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6843 } 6844 6845 if (ps != null && !ps.codePath.equals(scanFile)) { 6846 // The path has changed from what was last scanned... check the 6847 // version of the new path against what we have stored to determine 6848 // what to do. 6849 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6850 if (pkg.mVersionCode <= ps.versionCode) { 6851 // The system package has been updated and the code path does not match 6852 // Ignore entry. Skip it. 6853 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6854 + " ignored: updated version " + ps.versionCode 6855 + " better than this " + pkg.mVersionCode); 6856 if (!updatedPkg.codePath.equals(scanFile)) { 6857 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6858 + ps.name + " changing from " + updatedPkg.codePathString 6859 + " to " + scanFile); 6860 updatedPkg.codePath = scanFile; 6861 updatedPkg.codePathString = scanFile.toString(); 6862 updatedPkg.resourcePath = scanFile; 6863 updatedPkg.resourcePathString = scanFile.toString(); 6864 } 6865 updatedPkg.pkg = pkg; 6866 updatedPkg.versionCode = pkg.mVersionCode; 6867 6868 // Update the disabled system child packages to point to the package too. 6869 final int childCount = updatedPkg.childPackageNames != null 6870 ? updatedPkg.childPackageNames.size() : 0; 6871 for (int i = 0; i < childCount; i++) { 6872 String childPackageName = updatedPkg.childPackageNames.get(i); 6873 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6874 childPackageName); 6875 if (updatedChildPkg != null) { 6876 updatedChildPkg.pkg = pkg; 6877 updatedChildPkg.versionCode = pkg.mVersionCode; 6878 } 6879 } 6880 6881 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6882 + scanFile + " ignored: updated version " + ps.versionCode 6883 + " better than this " + pkg.mVersionCode); 6884 } else { 6885 // The current app on the system partition is better than 6886 // what we have updated to on the data partition; switch 6887 // back to the system partition version. 6888 // At this point, its safely assumed that package installation for 6889 // apps in system partition will go through. If not there won't be a working 6890 // version of the app 6891 // writer 6892 synchronized (mPackages) { 6893 // Just remove the loaded entries from package lists. 6894 mPackages.remove(ps.name); 6895 } 6896 6897 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6898 + " reverting from " + ps.codePathString 6899 + ": new version " + pkg.mVersionCode 6900 + " better than installed " + ps.versionCode); 6901 6902 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6903 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6904 synchronized (mInstallLock) { 6905 args.cleanUpResourcesLI(); 6906 } 6907 synchronized (mPackages) { 6908 mSettings.enableSystemPackageLPw(ps.name); 6909 } 6910 updatedPkgBetter = true; 6911 } 6912 } 6913 } 6914 6915 if (updatedPkg != null) { 6916 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6917 // initially 6918 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6919 6920 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6921 // flag set initially 6922 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6923 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6924 } 6925 } 6926 6927 // Verify certificates against what was last scanned 6928 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6929 6930 /* 6931 * A new system app appeared, but we already had a non-system one of the 6932 * same name installed earlier. 6933 */ 6934 boolean shouldHideSystemApp = false; 6935 if (updatedPkg == null && ps != null 6936 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6937 /* 6938 * Check to make sure the signatures match first. If they don't, 6939 * wipe the installed application and its data. 6940 */ 6941 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6942 != PackageManager.SIGNATURE_MATCH) { 6943 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6944 + " signatures don't match existing userdata copy; removing"); 6945 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6946 "scanPackageInternalLI")) { 6947 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6948 } 6949 ps = null; 6950 } else { 6951 /* 6952 * If the newly-added system app is an older version than the 6953 * already installed version, hide it. It will be scanned later 6954 * and re-added like an update. 6955 */ 6956 if (pkg.mVersionCode <= ps.versionCode) { 6957 shouldHideSystemApp = true; 6958 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6959 + " but new version " + pkg.mVersionCode + " better than installed " 6960 + ps.versionCode + "; hiding system"); 6961 } else { 6962 /* 6963 * The newly found system app is a newer version that the 6964 * one previously installed. Simply remove the 6965 * already-installed application and replace it with our own 6966 * while keeping the application data. 6967 */ 6968 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6969 + " reverting from " + ps.codePathString + ": new version " 6970 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6971 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6972 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6973 synchronized (mInstallLock) { 6974 args.cleanUpResourcesLI(); 6975 } 6976 } 6977 } 6978 } 6979 6980 // The apk is forward locked (not public) if its code and resources 6981 // are kept in different files. (except for app in either system or 6982 // vendor path). 6983 // TODO grab this value from PackageSettings 6984 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6985 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6986 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6987 } 6988 } 6989 6990 // TODO: extend to support forward-locked splits 6991 String resourcePath = null; 6992 String baseResourcePath = null; 6993 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6994 if (ps != null && ps.resourcePathString != null) { 6995 resourcePath = ps.resourcePathString; 6996 baseResourcePath = ps.resourcePathString; 6997 } else { 6998 // Should not happen at all. Just log an error. 6999 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7000 } 7001 } else { 7002 resourcePath = pkg.codePath; 7003 baseResourcePath = pkg.baseCodePath; 7004 } 7005 7006 // Set application objects path explicitly. 7007 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7008 pkg.setApplicationInfoCodePath(pkg.codePath); 7009 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7010 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7011 pkg.setApplicationInfoResourcePath(resourcePath); 7012 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7013 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7014 7015 // Note that we invoke the following method only if we are about to unpack an application 7016 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7017 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7018 7019 /* 7020 * If the system app should be overridden by a previously installed 7021 * data, hide the system app now and let the /data/app scan pick it up 7022 * again. 7023 */ 7024 if (shouldHideSystemApp) { 7025 synchronized (mPackages) { 7026 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7027 } 7028 } 7029 7030 return scannedPkg; 7031 } 7032 7033 private static String fixProcessName(String defProcessName, 7034 String processName, int uid) { 7035 if (processName == null) { 7036 return defProcessName; 7037 } 7038 return processName; 7039 } 7040 7041 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7042 throws PackageManagerException { 7043 if (pkgSetting.signatures.mSignatures != null) { 7044 // Already existing package. Make sure signatures match 7045 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7046 == PackageManager.SIGNATURE_MATCH; 7047 if (!match) { 7048 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7049 == PackageManager.SIGNATURE_MATCH; 7050 } 7051 if (!match) { 7052 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7053 == PackageManager.SIGNATURE_MATCH; 7054 } 7055 if (!match) { 7056 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7057 + pkg.packageName + " signatures do not match the " 7058 + "previously installed version; ignoring!"); 7059 } 7060 } 7061 7062 // Check for shared user signatures 7063 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7064 // Already existing package. Make sure signatures match 7065 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7066 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7067 if (!match) { 7068 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7069 == PackageManager.SIGNATURE_MATCH; 7070 } 7071 if (!match) { 7072 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7073 == PackageManager.SIGNATURE_MATCH; 7074 } 7075 if (!match) { 7076 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7077 "Package " + pkg.packageName 7078 + " has no signatures that match those in shared user " 7079 + pkgSetting.sharedUser.name + "; ignoring!"); 7080 } 7081 } 7082 } 7083 7084 /** 7085 * Enforces that only the system UID or root's UID can call a method exposed 7086 * via Binder. 7087 * 7088 * @param message used as message if SecurityException is thrown 7089 * @throws SecurityException if the caller is not system or root 7090 */ 7091 private static final void enforceSystemOrRoot(String message) { 7092 final int uid = Binder.getCallingUid(); 7093 if (uid != Process.SYSTEM_UID && uid != 0) { 7094 throw new SecurityException(message); 7095 } 7096 } 7097 7098 @Override 7099 public void performFstrimIfNeeded() { 7100 enforceSystemOrRoot("Only the system can request fstrim"); 7101 7102 // Before everything else, see whether we need to fstrim. 7103 try { 7104 IMountService ms = PackageHelper.getMountService(); 7105 if (ms != null) { 7106 final boolean isUpgrade = isUpgrade(); 7107 boolean doTrim = isUpgrade; 7108 if (doTrim) { 7109 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7110 } else { 7111 final long interval = android.provider.Settings.Global.getLong( 7112 mContext.getContentResolver(), 7113 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7114 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7115 if (interval > 0) { 7116 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7117 if (timeSinceLast > interval) { 7118 doTrim = true; 7119 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7120 + "; running immediately"); 7121 } 7122 } 7123 } 7124 if (doTrim) { 7125 if (!isFirstBoot()) { 7126 try { 7127 ActivityManagerNative.getDefault().showBootMessage( 7128 mContext.getResources().getString( 7129 R.string.android_upgrading_fstrim), true); 7130 } catch (RemoteException e) { 7131 } 7132 } 7133 ms.runMaintenance(); 7134 } 7135 } else { 7136 Slog.e(TAG, "Mount service unavailable!"); 7137 } 7138 } catch (RemoteException e) { 7139 // Can't happen; MountService is local 7140 } 7141 } 7142 7143 @Override 7144 public void updatePackagesIfNeeded() { 7145 enforceSystemOrRoot("Only the system can request package update"); 7146 7147 // We need to re-extract after an OTA. 7148 boolean causeUpgrade = isUpgrade(); 7149 7150 // First boot or factory reset. 7151 // Note: we also handle devices that are upgrading to N right now as if it is their 7152 // first boot, as they do not have profile data. 7153 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7154 7155 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7156 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7157 7158 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7159 return; 7160 } 7161 7162 List<PackageParser.Package> pkgs; 7163 synchronized (mPackages) { 7164 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7165 } 7166 7167 int numberOfPackagesVisited = 0; 7168 int numberOfPackagesOptimized = 0; 7169 int numberOfPackagesSkipped = 0; 7170 int numberOfPackagesFailed = 0; 7171 final int numberOfPackagesToDexopt = pkgs.size(); 7172 final long startTime = System.nanoTime(); 7173 7174 for (PackageParser.Package pkg : pkgs) { 7175 numberOfPackagesVisited++; 7176 7177 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7178 if (DEBUG_DEXOPT) { 7179 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7180 } 7181 numberOfPackagesSkipped++; 7182 continue; 7183 } 7184 7185 if (DEBUG_DEXOPT) { 7186 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7187 numberOfPackagesToDexopt + ": " + pkg.packageName); 7188 } 7189 7190 if (mIsPreNUpgrade) { 7191 try { 7192 ActivityManagerNative.getDefault().showBootMessage( 7193 mContext.getResources().getString(R.string.android_upgrading_apk, 7194 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7195 } catch (RemoteException e) { 7196 } 7197 } 7198 7199 int dexOptStatus = performDexOptTraced(pkg.packageName, 7200 null /* instructionSet */, 7201 true /* checkProfiles */, 7202 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7203 false /* force */); 7204 switch (dexOptStatus) { 7205 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7206 numberOfPackagesOptimized++; 7207 break; 7208 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7209 numberOfPackagesSkipped++; 7210 break; 7211 case PackageDexOptimizer.DEX_OPT_FAILED: 7212 numberOfPackagesFailed++; 7213 break; 7214 default: 7215 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7216 break; 7217 } 7218 } 7219 7220 final int elapsedTime = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); 7221 MetricsLogger.action(mContext, 7222 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_DEXOPTED, numberOfPackagesOptimized); 7223 MetricsLogger.action(mContext, 7224 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_SKIPPED, numberOfPackagesSkipped); 7225 MetricsLogger.action(mContext, 7226 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_FAILED, numberOfPackagesFailed); 7227 MetricsLogger.action(mContext, 7228 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_TOTAL, getOptimizablePackages().size()); 7229 MetricsLogger.action(mContext, 7230 MetricsEvent.OPTIMIZING_APPS_TOTAL_TIME_MS, elapsedTime); 7231 } 7232 7233 @Override 7234 public void notifyPackageUse(String packageName, int reason) { 7235 synchronized (mPackages) { 7236 PackageParser.Package p = mPackages.get(packageName); 7237 if (p == null) { 7238 return; 7239 } 7240 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7241 } 7242 } 7243 7244 // TODO: this is not used nor needed. Delete it. 7245 @Override 7246 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7247 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7248 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7249 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7250 } 7251 7252 @Override 7253 public boolean performDexOpt(String packageName, String instructionSet, 7254 boolean checkProfiles, int compileReason, boolean force) { 7255 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7256 getCompilerFilterForReason(compileReason), force); 7257 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7258 } 7259 7260 @Override 7261 public boolean performDexOptMode(String packageName, String instructionSet, 7262 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7263 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7264 targetCompilerFilter, force); 7265 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7266 } 7267 7268 private int performDexOptTraced(String packageName, String instructionSet, 7269 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7270 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7271 try { 7272 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7273 targetCompilerFilter, force); 7274 } finally { 7275 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7276 } 7277 } 7278 7279 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7280 // if the package can now be considered up to date for the given filter. 7281 private int performDexOptInternal(String packageName, String instructionSet, 7282 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7283 PackageParser.Package p; 7284 final String targetInstructionSet; 7285 synchronized (mPackages) { 7286 p = mPackages.get(packageName); 7287 if (p == null) { 7288 // Package could not be found. Report failure. 7289 return PackageDexOptimizer.DEX_OPT_FAILED; 7290 } 7291 mPackageUsage.write(false); 7292 7293 targetInstructionSet = instructionSet != null ? instructionSet : 7294 getPrimaryInstructionSet(p.applicationInfo); 7295 } 7296 long callingId = Binder.clearCallingIdentity(); 7297 try { 7298 synchronized (mInstallLock) { 7299 final String[] instructionSets = new String[] { targetInstructionSet }; 7300 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7301 targetCompilerFilter, force); 7302 } 7303 } finally { 7304 Binder.restoreCallingIdentity(callingId); 7305 } 7306 } 7307 7308 public ArraySet<String> getOptimizablePackages() { 7309 ArraySet<String> pkgs = new ArraySet<String>(); 7310 synchronized (mPackages) { 7311 for (PackageParser.Package p : mPackages.values()) { 7312 if (PackageDexOptimizer.canOptimizePackage(p)) { 7313 pkgs.add(p.packageName); 7314 } 7315 } 7316 } 7317 return pkgs; 7318 } 7319 7320 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7321 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7322 boolean force) { 7323 // Select the dex optimizer based on the force parameter. 7324 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7325 // allocate an object here. 7326 PackageDexOptimizer pdo = force 7327 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7328 : mPackageDexOptimizer; 7329 7330 // Optimize all dependencies first. Note: we ignore the return value and march on 7331 // on errors. 7332 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7333 if (!deps.isEmpty()) { 7334 for (PackageParser.Package depPackage : deps) { 7335 // TODO: Analyze and investigate if we (should) profile libraries. 7336 // Currently this will do a full compilation of the library by default. 7337 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7338 false /* checkProfiles */, 7339 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7340 } 7341 } 7342 7343 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7344 targetCompilerFilter); 7345 } 7346 7347 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7348 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7349 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7350 Set<String> collectedNames = new HashSet<>(); 7351 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7352 7353 retValue.remove(p); 7354 7355 return retValue; 7356 } else { 7357 return Collections.emptyList(); 7358 } 7359 } 7360 7361 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7362 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7363 if (!collectedNames.contains(p.packageName)) { 7364 collectedNames.add(p.packageName); 7365 collected.add(p); 7366 7367 if (p.usesLibraries != null) { 7368 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7369 } 7370 if (p.usesOptionalLibraries != null) { 7371 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7372 collectedNames); 7373 } 7374 } 7375 } 7376 7377 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7378 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7379 for (String libName : libs) { 7380 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7381 if (libPkg != null) { 7382 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7383 } 7384 } 7385 } 7386 7387 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7388 synchronized (mPackages) { 7389 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7390 if (lib != null && lib.apk != null) { 7391 return mPackages.get(lib.apk); 7392 } 7393 } 7394 return null; 7395 } 7396 7397 public void shutdown() { 7398 mPackageUsage.write(true); 7399 } 7400 7401 @Override 7402 public void forceDexOpt(String packageName) { 7403 enforceSystemOrRoot("forceDexOpt"); 7404 7405 PackageParser.Package pkg; 7406 synchronized (mPackages) { 7407 pkg = mPackages.get(packageName); 7408 if (pkg == null) { 7409 throw new IllegalArgumentException("Unknown package: " + packageName); 7410 } 7411 } 7412 7413 synchronized (mInstallLock) { 7414 final String[] instructionSets = new String[] { 7415 getPrimaryInstructionSet(pkg.applicationInfo) }; 7416 7417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7418 7419 // Whoever is calling forceDexOpt wants a fully compiled package. 7420 // Don't use profiles since that may cause compilation to be skipped. 7421 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7422 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7423 true /* force */); 7424 7425 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7426 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7427 throw new IllegalStateException("Failed to dexopt: " + res); 7428 } 7429 } 7430 } 7431 7432 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7433 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7434 Slog.w(TAG, "Unable to update from " + oldPkg.name 7435 + " to " + newPkg.packageName 7436 + ": old package not in system partition"); 7437 return false; 7438 } else if (mPackages.get(oldPkg.name) != null) { 7439 Slog.w(TAG, "Unable to update from " + oldPkg.name 7440 + " to " + newPkg.packageName 7441 + ": old package still exists"); 7442 return false; 7443 } 7444 return true; 7445 } 7446 7447 void removeCodePathLI(File codePath) { 7448 if (codePath.isDirectory()) { 7449 try { 7450 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7451 } catch (InstallerException e) { 7452 Slog.w(TAG, "Failed to remove code path", e); 7453 } 7454 } else { 7455 codePath.delete(); 7456 } 7457 } 7458 7459 private int[] resolveUserIds(int userId) { 7460 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7461 } 7462 7463 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7464 if (pkg == null) { 7465 Slog.wtf(TAG, "Package was null!", new Throwable()); 7466 return; 7467 } 7468 clearAppDataLeafLIF(pkg, userId, flags); 7469 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7470 for (int i = 0; i < childCount; i++) { 7471 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7472 } 7473 } 7474 7475 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7476 final PackageSetting ps; 7477 synchronized (mPackages) { 7478 ps = mSettings.mPackages.get(pkg.packageName); 7479 } 7480 for (int realUserId : resolveUserIds(userId)) { 7481 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7482 try { 7483 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7484 ceDataInode); 7485 } catch (InstallerException e) { 7486 Slog.w(TAG, String.valueOf(e)); 7487 } 7488 } 7489 } 7490 7491 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7492 if (pkg == null) { 7493 Slog.wtf(TAG, "Package was null!", new Throwable()); 7494 return; 7495 } 7496 destroyAppDataLeafLIF(pkg, userId, flags); 7497 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7498 for (int i = 0; i < childCount; i++) { 7499 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7500 } 7501 } 7502 7503 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7504 final PackageSetting ps; 7505 synchronized (mPackages) { 7506 ps = mSettings.mPackages.get(pkg.packageName); 7507 } 7508 for (int realUserId : resolveUserIds(userId)) { 7509 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7510 try { 7511 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7512 ceDataInode); 7513 } catch (InstallerException e) { 7514 Slog.w(TAG, String.valueOf(e)); 7515 } 7516 } 7517 } 7518 7519 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7520 if (pkg == null) { 7521 Slog.wtf(TAG, "Package was null!", new Throwable()); 7522 return; 7523 } 7524 destroyAppProfilesLeafLIF(pkg); 7525 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7526 for (int i = 0; i < childCount; i++) { 7527 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7528 } 7529 } 7530 7531 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7532 try { 7533 mInstaller.destroyAppProfiles(pkg.packageName); 7534 } catch (InstallerException e) { 7535 Slog.w(TAG, String.valueOf(e)); 7536 } 7537 } 7538 7539 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7540 if (pkg == null) { 7541 Slog.wtf(TAG, "Package was null!", new Throwable()); 7542 return; 7543 } 7544 clearAppProfilesLeafLIF(pkg); 7545 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7546 for (int i = 0; i < childCount; i++) { 7547 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7548 } 7549 } 7550 7551 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7552 try { 7553 mInstaller.clearAppProfiles(pkg.packageName); 7554 } catch (InstallerException e) { 7555 Slog.w(TAG, String.valueOf(e)); 7556 } 7557 } 7558 7559 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7560 long lastUpdateTime) { 7561 // Set parent install/update time 7562 PackageSetting ps = (PackageSetting) pkg.mExtras; 7563 if (ps != null) { 7564 ps.firstInstallTime = firstInstallTime; 7565 ps.lastUpdateTime = lastUpdateTime; 7566 } 7567 // Set children install/update time 7568 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7569 for (int i = 0; i < childCount; i++) { 7570 PackageParser.Package childPkg = pkg.childPackages.get(i); 7571 ps = (PackageSetting) childPkg.mExtras; 7572 if (ps != null) { 7573 ps.firstInstallTime = firstInstallTime; 7574 ps.lastUpdateTime = lastUpdateTime; 7575 } 7576 } 7577 } 7578 7579 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7580 PackageParser.Package changingLib) { 7581 if (file.path != null) { 7582 usesLibraryFiles.add(file.path); 7583 return; 7584 } 7585 PackageParser.Package p = mPackages.get(file.apk); 7586 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7587 // If we are doing this while in the middle of updating a library apk, 7588 // then we need to make sure to use that new apk for determining the 7589 // dependencies here. (We haven't yet finished committing the new apk 7590 // to the package manager state.) 7591 if (p == null || p.packageName.equals(changingLib.packageName)) { 7592 p = changingLib; 7593 } 7594 } 7595 if (p != null) { 7596 usesLibraryFiles.addAll(p.getAllCodePaths()); 7597 } 7598 } 7599 7600 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7601 PackageParser.Package changingLib) throws PackageManagerException { 7602 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7603 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7604 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7605 for (int i=0; i<N; i++) { 7606 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7607 if (file == null) { 7608 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7609 "Package " + pkg.packageName + " requires unavailable shared library " 7610 + pkg.usesLibraries.get(i) + "; failing!"); 7611 } 7612 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7613 } 7614 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7615 for (int i=0; i<N; i++) { 7616 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7617 if (file == null) { 7618 Slog.w(TAG, "Package " + pkg.packageName 7619 + " desires unavailable shared library " 7620 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7621 } else { 7622 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7623 } 7624 } 7625 N = usesLibraryFiles.size(); 7626 if (N > 0) { 7627 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7628 } else { 7629 pkg.usesLibraryFiles = null; 7630 } 7631 } 7632 } 7633 7634 private static boolean hasString(List<String> list, List<String> which) { 7635 if (list == null) { 7636 return false; 7637 } 7638 for (int i=list.size()-1; i>=0; i--) { 7639 for (int j=which.size()-1; j>=0; j--) { 7640 if (which.get(j).equals(list.get(i))) { 7641 return true; 7642 } 7643 } 7644 } 7645 return false; 7646 } 7647 7648 private void updateAllSharedLibrariesLPw() { 7649 for (PackageParser.Package pkg : mPackages.values()) { 7650 try { 7651 updateSharedLibrariesLPw(pkg, null); 7652 } catch (PackageManagerException e) { 7653 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7654 } 7655 } 7656 } 7657 7658 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7659 PackageParser.Package changingPkg) { 7660 ArrayList<PackageParser.Package> res = null; 7661 for (PackageParser.Package pkg : mPackages.values()) { 7662 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7663 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7664 if (res == null) { 7665 res = new ArrayList<PackageParser.Package>(); 7666 } 7667 res.add(pkg); 7668 try { 7669 updateSharedLibrariesLPw(pkg, changingPkg); 7670 } catch (PackageManagerException e) { 7671 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7672 } 7673 } 7674 } 7675 return res; 7676 } 7677 7678 /** 7679 * Derive the value of the {@code cpuAbiOverride} based on the provided 7680 * value and an optional stored value from the package settings. 7681 */ 7682 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7683 String cpuAbiOverride = null; 7684 7685 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7686 cpuAbiOverride = null; 7687 } else if (abiOverride != null) { 7688 cpuAbiOverride = abiOverride; 7689 } else if (settings != null) { 7690 cpuAbiOverride = settings.cpuAbiOverrideString; 7691 } 7692 7693 return cpuAbiOverride; 7694 } 7695 7696 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7697 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7698 throws PackageManagerException { 7699 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7700 // If the package has children and this is the first dive in the function 7701 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7702 // whether all packages (parent and children) would be successfully scanned 7703 // before the actual scan since scanning mutates internal state and we want 7704 // to atomically install the package and its children. 7705 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7706 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7707 scanFlags |= SCAN_CHECK_ONLY; 7708 } 7709 } else { 7710 scanFlags &= ~SCAN_CHECK_ONLY; 7711 } 7712 7713 final PackageParser.Package scannedPkg; 7714 try { 7715 // Scan the parent 7716 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7717 // Scan the children 7718 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7719 for (int i = 0; i < childCount; i++) { 7720 PackageParser.Package childPkg = pkg.childPackages.get(i); 7721 scanPackageLI(childPkg, policyFlags, 7722 scanFlags, currentTime, user); 7723 } 7724 } finally { 7725 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7726 } 7727 7728 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7729 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7730 } 7731 7732 return scannedPkg; 7733 } 7734 7735 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7736 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7737 boolean success = false; 7738 try { 7739 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7740 currentTime, user); 7741 success = true; 7742 return res; 7743 } finally { 7744 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7745 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7746 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7747 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7748 destroyAppProfilesLIF(pkg); 7749 } 7750 } 7751 } 7752 7753 /** 7754 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7755 */ 7756 private static boolean apkHasCode(String fileName) { 7757 StrictJarFile jarFile = null; 7758 try { 7759 jarFile = new StrictJarFile(fileName, 7760 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7761 return jarFile.findEntry("classes.dex") != null; 7762 } catch (IOException ignore) { 7763 } finally { 7764 try { 7765 jarFile.close(); 7766 } catch (IOException ignore) {} 7767 } 7768 return false; 7769 } 7770 7771 /** 7772 * Enforces code policy for the package. This ensures that if an APK has 7773 * declared hasCode="true" in its manifest that the APK actually contains 7774 * code. 7775 * 7776 * @throws PackageManagerException If bytecode could not be found when it should exist 7777 */ 7778 private static void enforceCodePolicy(PackageParser.Package pkg) 7779 throws PackageManagerException { 7780 final boolean shouldHaveCode = 7781 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7782 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7783 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7784 "Package " + pkg.baseCodePath + " code is missing"); 7785 } 7786 7787 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7788 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7789 final boolean splitShouldHaveCode = 7790 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7791 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7792 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7793 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7794 } 7795 } 7796 } 7797 } 7798 7799 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7800 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7801 throws PackageManagerException { 7802 final File scanFile = new File(pkg.codePath); 7803 if (pkg.applicationInfo.getCodePath() == null || 7804 pkg.applicationInfo.getResourcePath() == null) { 7805 // Bail out. The resource and code paths haven't been set. 7806 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7807 "Code and resource paths haven't been set correctly"); 7808 } 7809 7810 // Apply policy 7811 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7812 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7813 if (pkg.applicationInfo.isDirectBootAware()) { 7814 // we're direct boot aware; set for all components 7815 for (PackageParser.Service s : pkg.services) { 7816 s.info.encryptionAware = s.info.directBootAware = true; 7817 } 7818 for (PackageParser.Provider p : pkg.providers) { 7819 p.info.encryptionAware = p.info.directBootAware = true; 7820 } 7821 for (PackageParser.Activity a : pkg.activities) { 7822 a.info.encryptionAware = a.info.directBootAware = true; 7823 } 7824 for (PackageParser.Activity r : pkg.receivers) { 7825 r.info.encryptionAware = r.info.directBootAware = true; 7826 } 7827 } 7828 } else { 7829 // Only allow system apps to be flagged as core apps. 7830 pkg.coreApp = false; 7831 // clear flags not applicable to regular apps 7832 pkg.applicationInfo.privateFlags &= 7833 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7834 pkg.applicationInfo.privateFlags &= 7835 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7836 } 7837 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7838 7839 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7840 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7841 } 7842 7843 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7844 enforceCodePolicy(pkg); 7845 } 7846 7847 if (mCustomResolverComponentName != null && 7848 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7849 setUpCustomResolverActivity(pkg); 7850 } 7851 7852 if (pkg.packageName.equals("android")) { 7853 synchronized (mPackages) { 7854 if (mAndroidApplication != null) { 7855 Slog.w(TAG, "*************************************************"); 7856 Slog.w(TAG, "Core android package being redefined. Skipping."); 7857 Slog.w(TAG, " file=" + scanFile); 7858 Slog.w(TAG, "*************************************************"); 7859 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7860 "Core android package being redefined. Skipping."); 7861 } 7862 7863 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7864 // Set up information for our fall-back user intent resolution activity. 7865 mPlatformPackage = pkg; 7866 pkg.mVersionCode = mSdkVersion; 7867 mAndroidApplication = pkg.applicationInfo; 7868 7869 if (!mResolverReplaced) { 7870 mResolveActivity.applicationInfo = mAndroidApplication; 7871 mResolveActivity.name = ResolverActivity.class.getName(); 7872 mResolveActivity.packageName = mAndroidApplication.packageName; 7873 mResolveActivity.processName = "system:ui"; 7874 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7875 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7876 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7877 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7878 mResolveActivity.exported = true; 7879 mResolveActivity.enabled = true; 7880 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7881 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7882 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7883 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7884 | ActivityInfo.CONFIG_ORIENTATION 7885 | ActivityInfo.CONFIG_KEYBOARD 7886 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7887 mResolveInfo.activityInfo = mResolveActivity; 7888 mResolveInfo.priority = 0; 7889 mResolveInfo.preferredOrder = 0; 7890 mResolveInfo.match = 0; 7891 mResolveComponentName = new ComponentName( 7892 mAndroidApplication.packageName, mResolveActivity.name); 7893 } 7894 } 7895 } 7896 } 7897 7898 if (DEBUG_PACKAGE_SCANNING) { 7899 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7900 Log.d(TAG, "Scanning package " + pkg.packageName); 7901 } 7902 7903 synchronized (mPackages) { 7904 if (mPackages.containsKey(pkg.packageName) 7905 || mSharedLibraries.containsKey(pkg.packageName)) { 7906 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7907 "Application package " + pkg.packageName 7908 + " already installed. Skipping duplicate."); 7909 } 7910 7911 // If we're only installing presumed-existing packages, require that the 7912 // scanned APK is both already known and at the path previously established 7913 // for it. Previously unknown packages we pick up normally, but if we have an 7914 // a priori expectation about this package's install presence, enforce it. 7915 // With a singular exception for new system packages. When an OTA contains 7916 // a new system package, we allow the codepath to change from a system location 7917 // to the user-installed location. If we don't allow this change, any newer, 7918 // user-installed version of the application will be ignored. 7919 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7920 if (mExpectingBetter.containsKey(pkg.packageName)) { 7921 logCriticalInfo(Log.WARN, 7922 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7923 } else { 7924 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7925 if (known != null) { 7926 if (DEBUG_PACKAGE_SCANNING) { 7927 Log.d(TAG, "Examining " + pkg.codePath 7928 + " and requiring known paths " + known.codePathString 7929 + " & " + known.resourcePathString); 7930 } 7931 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7932 || !pkg.applicationInfo.getResourcePath().equals( 7933 known.resourcePathString)) { 7934 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7935 "Application package " + pkg.packageName 7936 + " found at " + pkg.applicationInfo.getCodePath() 7937 + " but expected at " + known.codePathString 7938 + "; ignoring."); 7939 } 7940 } 7941 } 7942 } 7943 } 7944 7945 // Initialize package source and resource directories 7946 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7947 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7948 7949 SharedUserSetting suid = null; 7950 PackageSetting pkgSetting = null; 7951 7952 if (!isSystemApp(pkg)) { 7953 // Only system apps can use these features. 7954 pkg.mOriginalPackages = null; 7955 pkg.mRealPackage = null; 7956 pkg.mAdoptPermissions = null; 7957 } 7958 7959 // Getting the package setting may have a side-effect, so if we 7960 // are only checking if scan would succeed, stash a copy of the 7961 // old setting to restore at the end. 7962 PackageSetting nonMutatedPs = null; 7963 7964 // writer 7965 synchronized (mPackages) { 7966 if (pkg.mSharedUserId != null) { 7967 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7968 if (suid == null) { 7969 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7970 "Creating application package " + pkg.packageName 7971 + " for shared user failed"); 7972 } 7973 if (DEBUG_PACKAGE_SCANNING) { 7974 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7975 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7976 + "): packages=" + suid.packages); 7977 } 7978 } 7979 7980 // Check if we are renaming from an original package name. 7981 PackageSetting origPackage = null; 7982 String realName = null; 7983 if (pkg.mOriginalPackages != null) { 7984 // This package may need to be renamed to a previously 7985 // installed name. Let's check on that... 7986 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7987 if (pkg.mOriginalPackages.contains(renamed)) { 7988 // This package had originally been installed as the 7989 // original name, and we have already taken care of 7990 // transitioning to the new one. Just update the new 7991 // one to continue using the old name. 7992 realName = pkg.mRealPackage; 7993 if (!pkg.packageName.equals(renamed)) { 7994 // Callers into this function may have already taken 7995 // care of renaming the package; only do it here if 7996 // it is not already done. 7997 pkg.setPackageName(renamed); 7998 } 7999 8000 } else { 8001 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8002 if ((origPackage = mSettings.peekPackageLPr( 8003 pkg.mOriginalPackages.get(i))) != null) { 8004 // We do have the package already installed under its 8005 // original name... should we use it? 8006 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8007 // New package is not compatible with original. 8008 origPackage = null; 8009 continue; 8010 } else if (origPackage.sharedUser != null) { 8011 // Make sure uid is compatible between packages. 8012 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8013 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8014 + " to " + pkg.packageName + ": old uid " 8015 + origPackage.sharedUser.name 8016 + " differs from " + pkg.mSharedUserId); 8017 origPackage = null; 8018 continue; 8019 } 8020 // TODO: Add case when shared user id is added [b/28144775] 8021 } else { 8022 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8023 + pkg.packageName + " to old name " + origPackage.name); 8024 } 8025 break; 8026 } 8027 } 8028 } 8029 } 8030 8031 if (mTransferedPackages.contains(pkg.packageName)) { 8032 Slog.w(TAG, "Package " + pkg.packageName 8033 + " was transferred to another, but its .apk remains"); 8034 } 8035 8036 // See comments in nonMutatedPs declaration 8037 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8038 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8039 if (foundPs != null) { 8040 nonMutatedPs = new PackageSetting(foundPs); 8041 } 8042 } 8043 8044 // Just create the setting, don't add it yet. For already existing packages 8045 // the PkgSetting exists already and doesn't have to be created. 8046 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8047 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8048 pkg.applicationInfo.primaryCpuAbi, 8049 pkg.applicationInfo.secondaryCpuAbi, 8050 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8051 user, false); 8052 if (pkgSetting == null) { 8053 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8054 "Creating application package " + pkg.packageName + " failed"); 8055 } 8056 8057 if (pkgSetting.origPackage != null) { 8058 // If we are first transitioning from an original package, 8059 // fix up the new package's name now. We need to do this after 8060 // looking up the package under its new name, so getPackageLP 8061 // can take care of fiddling things correctly. 8062 pkg.setPackageName(origPackage.name); 8063 8064 // File a report about this. 8065 String msg = "New package " + pkgSetting.realName 8066 + " renamed to replace old package " + pkgSetting.name; 8067 reportSettingsProblem(Log.WARN, msg); 8068 8069 // Make a note of it. 8070 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8071 mTransferedPackages.add(origPackage.name); 8072 } 8073 8074 // No longer need to retain this. 8075 pkgSetting.origPackage = null; 8076 } 8077 8078 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8079 // Make a note of it. 8080 mTransferedPackages.add(pkg.packageName); 8081 } 8082 8083 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8084 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8085 } 8086 8087 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8088 // Check all shared libraries and map to their actual file path. 8089 // We only do this here for apps not on a system dir, because those 8090 // are the only ones that can fail an install due to this. We 8091 // will take care of the system apps by updating all of their 8092 // library paths after the scan is done. 8093 updateSharedLibrariesLPw(pkg, null); 8094 } 8095 8096 if (mFoundPolicyFile) { 8097 SELinuxMMAC.assignSeinfoValue(pkg); 8098 } 8099 8100 pkg.applicationInfo.uid = pkgSetting.appId; 8101 pkg.mExtras = pkgSetting; 8102 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8103 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8104 // We just determined the app is signed correctly, so bring 8105 // over the latest parsed certs. 8106 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8107 } else { 8108 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8109 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8110 "Package " + pkg.packageName + " upgrade keys do not match the " 8111 + "previously installed version"); 8112 } else { 8113 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8114 String msg = "System package " + pkg.packageName 8115 + " signature changed; retaining data."; 8116 reportSettingsProblem(Log.WARN, msg); 8117 } 8118 } 8119 } else { 8120 try { 8121 verifySignaturesLP(pkgSetting, pkg); 8122 // We just determined the app is signed correctly, so bring 8123 // over the latest parsed certs. 8124 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8125 } catch (PackageManagerException e) { 8126 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8127 throw e; 8128 } 8129 // The signature has changed, but this package is in the system 8130 // image... let's recover! 8131 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8132 // However... if this package is part of a shared user, but it 8133 // doesn't match the signature of the shared user, let's fail. 8134 // What this means is that you can't change the signatures 8135 // associated with an overall shared user, which doesn't seem all 8136 // that unreasonable. 8137 if (pkgSetting.sharedUser != null) { 8138 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8139 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8140 throw new PackageManagerException( 8141 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8142 "Signature mismatch for shared user: " 8143 + pkgSetting.sharedUser); 8144 } 8145 } 8146 // File a report about this. 8147 String msg = "System package " + pkg.packageName 8148 + " signature changed; retaining data."; 8149 reportSettingsProblem(Log.WARN, msg); 8150 } 8151 } 8152 // Verify that this new package doesn't have any content providers 8153 // that conflict with existing packages. Only do this if the 8154 // package isn't already installed, since we don't want to break 8155 // things that are installed. 8156 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8157 final int N = pkg.providers.size(); 8158 int i; 8159 for (i=0; i<N; i++) { 8160 PackageParser.Provider p = pkg.providers.get(i); 8161 if (p.info.authority != null) { 8162 String names[] = p.info.authority.split(";"); 8163 for (int j = 0; j < names.length; j++) { 8164 if (mProvidersByAuthority.containsKey(names[j])) { 8165 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8166 final String otherPackageName = 8167 ((other != null && other.getComponentName() != null) ? 8168 other.getComponentName().getPackageName() : "?"); 8169 throw new PackageManagerException( 8170 INSTALL_FAILED_CONFLICTING_PROVIDER, 8171 "Can't install because provider name " + names[j] 8172 + " (in package " + pkg.applicationInfo.packageName 8173 + ") is already used by " + otherPackageName); 8174 } 8175 } 8176 } 8177 } 8178 } 8179 8180 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8181 // This package wants to adopt ownership of permissions from 8182 // another package. 8183 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8184 final String origName = pkg.mAdoptPermissions.get(i); 8185 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8186 if (orig != null) { 8187 if (verifyPackageUpdateLPr(orig, pkg)) { 8188 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8189 + pkg.packageName); 8190 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8191 } 8192 } 8193 } 8194 } 8195 } 8196 8197 final String pkgName = pkg.packageName; 8198 8199 final long scanFileTime = scanFile.lastModified(); 8200 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8201 pkg.applicationInfo.processName = fixProcessName( 8202 pkg.applicationInfo.packageName, 8203 pkg.applicationInfo.processName, 8204 pkg.applicationInfo.uid); 8205 8206 if (pkg != mPlatformPackage) { 8207 // Get all of our default paths setup 8208 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8209 } 8210 8211 final String path = scanFile.getPath(); 8212 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8213 8214 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8215 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8216 8217 // Some system apps still use directory structure for native libraries 8218 // in which case we might end up not detecting abi solely based on apk 8219 // structure. Try to detect abi based on directory structure. 8220 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8221 pkg.applicationInfo.primaryCpuAbi == null) { 8222 setBundledAppAbisAndRoots(pkg, pkgSetting); 8223 setNativeLibraryPaths(pkg); 8224 } 8225 8226 } else { 8227 if ((scanFlags & SCAN_MOVE) != 0) { 8228 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8229 // but we already have this packages package info in the PackageSetting. We just 8230 // use that and derive the native library path based on the new codepath. 8231 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8232 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8233 } 8234 8235 // Set native library paths again. For moves, the path will be updated based on the 8236 // ABIs we've determined above. For non-moves, the path will be updated based on the 8237 // ABIs we determined during compilation, but the path will depend on the final 8238 // package path (after the rename away from the stage path). 8239 setNativeLibraryPaths(pkg); 8240 } 8241 8242 // This is a special case for the "system" package, where the ABI is 8243 // dictated by the zygote configuration (and init.rc). We should keep track 8244 // of this ABI so that we can deal with "normal" applications that run under 8245 // the same UID correctly. 8246 if (mPlatformPackage == pkg) { 8247 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8248 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8249 } 8250 8251 // If there's a mismatch between the abi-override in the package setting 8252 // and the abiOverride specified for the install. Warn about this because we 8253 // would've already compiled the app without taking the package setting into 8254 // account. 8255 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8256 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8257 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8258 " for package " + pkg.packageName); 8259 } 8260 } 8261 8262 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8263 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8264 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8265 8266 // Copy the derived override back to the parsed package, so that we can 8267 // update the package settings accordingly. 8268 pkg.cpuAbiOverride = cpuAbiOverride; 8269 8270 if (DEBUG_ABI_SELECTION) { 8271 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8272 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8273 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8274 } 8275 8276 // Push the derived path down into PackageSettings so we know what to 8277 // clean up at uninstall time. 8278 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8279 8280 if (DEBUG_ABI_SELECTION) { 8281 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8282 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8283 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8284 } 8285 8286 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8287 // We don't do this here during boot because we can do it all 8288 // at once after scanning all existing packages. 8289 // 8290 // We also do this *before* we perform dexopt on this package, so that 8291 // we can avoid redundant dexopts, and also to make sure we've got the 8292 // code and package path correct. 8293 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8294 pkg, true /* boot complete */); 8295 } 8296 8297 if (mFactoryTest && pkg.requestedPermissions.contains( 8298 android.Manifest.permission.FACTORY_TEST)) { 8299 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8300 } 8301 8302 ArrayList<PackageParser.Package> clientLibPkgs = null; 8303 8304 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8305 if (nonMutatedPs != null) { 8306 synchronized (mPackages) { 8307 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8308 } 8309 } 8310 return pkg; 8311 } 8312 8313 // Only privileged apps and updated privileged apps can add child packages. 8314 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8315 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8316 throw new PackageManagerException("Only privileged apps and updated " 8317 + "privileged apps can add child packages. Ignoring package " 8318 + pkg.packageName); 8319 } 8320 final int childCount = pkg.childPackages.size(); 8321 for (int i = 0; i < childCount; i++) { 8322 PackageParser.Package childPkg = pkg.childPackages.get(i); 8323 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8324 childPkg.packageName)) { 8325 throw new PackageManagerException("Cannot override a child package of " 8326 + "another disabled system app. Ignoring package " + pkg.packageName); 8327 } 8328 } 8329 } 8330 8331 // writer 8332 synchronized (mPackages) { 8333 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8334 // Only system apps can add new shared libraries. 8335 if (pkg.libraryNames != null) { 8336 for (int i=0; i<pkg.libraryNames.size(); i++) { 8337 String name = pkg.libraryNames.get(i); 8338 boolean allowed = false; 8339 if (pkg.isUpdatedSystemApp()) { 8340 // New library entries can only be added through the 8341 // system image. This is important to get rid of a lot 8342 // of nasty edge cases: for example if we allowed a non- 8343 // system update of the app to add a library, then uninstalling 8344 // the update would make the library go away, and assumptions 8345 // we made such as through app install filtering would now 8346 // have allowed apps on the device which aren't compatible 8347 // with it. Better to just have the restriction here, be 8348 // conservative, and create many fewer cases that can negatively 8349 // impact the user experience. 8350 final PackageSetting sysPs = mSettings 8351 .getDisabledSystemPkgLPr(pkg.packageName); 8352 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8353 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8354 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8355 allowed = true; 8356 break; 8357 } 8358 } 8359 } 8360 } else { 8361 allowed = true; 8362 } 8363 if (allowed) { 8364 if (!mSharedLibraries.containsKey(name)) { 8365 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8366 } else if (!name.equals(pkg.packageName)) { 8367 Slog.w(TAG, "Package " + pkg.packageName + " library " 8368 + name + " already exists; skipping"); 8369 } 8370 } else { 8371 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8372 + name + " that is not declared on system image; skipping"); 8373 } 8374 } 8375 if ((scanFlags & SCAN_BOOTING) == 0) { 8376 // If we are not booting, we need to update any applications 8377 // that are clients of our shared library. If we are booting, 8378 // this will all be done once the scan is complete. 8379 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8380 } 8381 } 8382 } 8383 } 8384 8385 if ((scanFlags & SCAN_BOOTING) != 0) { 8386 // No apps can run during boot scan, so they don't need to be frozen 8387 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8388 // Caller asked to not kill app, so it's probably not frozen 8389 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8390 // Caller asked us to ignore frozen check for some reason; they 8391 // probably didn't know the package name 8392 } else { 8393 // We're doing major surgery on this package, so it better be frozen 8394 // right now to keep it from launching 8395 checkPackageFrozen(pkgName); 8396 } 8397 8398 // Also need to kill any apps that are dependent on the library. 8399 if (clientLibPkgs != null) { 8400 for (int i=0; i<clientLibPkgs.size(); i++) { 8401 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8402 killApplication(clientPkg.applicationInfo.packageName, 8403 clientPkg.applicationInfo.uid, "update lib"); 8404 } 8405 } 8406 8407 // Make sure we're not adding any bogus keyset info 8408 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8409 ksms.assertScannedPackageValid(pkg); 8410 8411 // writer 8412 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8413 8414 boolean createIdmapFailed = false; 8415 synchronized (mPackages) { 8416 // We don't expect installation to fail beyond this point 8417 8418 // Add the new setting to mSettings 8419 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8420 // Add the new setting to mPackages 8421 mPackages.put(pkg.applicationInfo.packageName, pkg); 8422 // Make sure we don't accidentally delete its data. 8423 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8424 while (iter.hasNext()) { 8425 PackageCleanItem item = iter.next(); 8426 if (pkgName.equals(item.packageName)) { 8427 iter.remove(); 8428 } 8429 } 8430 8431 // Take care of first install / last update times. 8432 if (currentTime != 0) { 8433 if (pkgSetting.firstInstallTime == 0) { 8434 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8435 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8436 pkgSetting.lastUpdateTime = currentTime; 8437 } 8438 } else if (pkgSetting.firstInstallTime == 0) { 8439 // We need *something*. Take time time stamp of the file. 8440 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8441 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8442 if (scanFileTime != pkgSetting.timeStamp) { 8443 // A package on the system image has changed; consider this 8444 // to be an update. 8445 pkgSetting.lastUpdateTime = scanFileTime; 8446 } 8447 } 8448 8449 // Add the package's KeySets to the global KeySetManagerService 8450 ksms.addScannedPackageLPw(pkg); 8451 8452 int N = pkg.providers.size(); 8453 StringBuilder r = null; 8454 int i; 8455 for (i=0; i<N; i++) { 8456 PackageParser.Provider p = pkg.providers.get(i); 8457 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8458 p.info.processName, pkg.applicationInfo.uid); 8459 mProviders.addProvider(p); 8460 p.syncable = p.info.isSyncable; 8461 if (p.info.authority != null) { 8462 String names[] = p.info.authority.split(";"); 8463 p.info.authority = null; 8464 for (int j = 0; j < names.length; j++) { 8465 if (j == 1 && p.syncable) { 8466 // We only want the first authority for a provider to possibly be 8467 // syncable, so if we already added this provider using a different 8468 // authority clear the syncable flag. We copy the provider before 8469 // changing it because the mProviders object contains a reference 8470 // to a provider that we don't want to change. 8471 // Only do this for the second authority since the resulting provider 8472 // object can be the same for all future authorities for this provider. 8473 p = new PackageParser.Provider(p); 8474 p.syncable = false; 8475 } 8476 if (!mProvidersByAuthority.containsKey(names[j])) { 8477 mProvidersByAuthority.put(names[j], p); 8478 if (p.info.authority == null) { 8479 p.info.authority = names[j]; 8480 } else { 8481 p.info.authority = p.info.authority + ";" + names[j]; 8482 } 8483 if (DEBUG_PACKAGE_SCANNING) { 8484 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8485 Log.d(TAG, "Registered content provider: " + names[j] 8486 + ", className = " + p.info.name + ", isSyncable = " 8487 + p.info.isSyncable); 8488 } 8489 } else { 8490 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8491 Slog.w(TAG, "Skipping provider name " + names[j] + 8492 " (in package " + pkg.applicationInfo.packageName + 8493 "): name already used by " 8494 + ((other != null && other.getComponentName() != null) 8495 ? other.getComponentName().getPackageName() : "?")); 8496 } 8497 } 8498 } 8499 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8500 if (r == null) { 8501 r = new StringBuilder(256); 8502 } else { 8503 r.append(' '); 8504 } 8505 r.append(p.info.name); 8506 } 8507 } 8508 if (r != null) { 8509 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8510 } 8511 8512 N = pkg.services.size(); 8513 r = null; 8514 for (i=0; i<N; i++) { 8515 PackageParser.Service s = pkg.services.get(i); 8516 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8517 s.info.processName, pkg.applicationInfo.uid); 8518 mServices.addService(s); 8519 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8520 if (r == null) { 8521 r = new StringBuilder(256); 8522 } else { 8523 r.append(' '); 8524 } 8525 r.append(s.info.name); 8526 } 8527 } 8528 if (r != null) { 8529 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8530 } 8531 8532 N = pkg.receivers.size(); 8533 r = null; 8534 for (i=0; i<N; i++) { 8535 PackageParser.Activity a = pkg.receivers.get(i); 8536 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8537 a.info.processName, pkg.applicationInfo.uid); 8538 mReceivers.addActivity(a, "receiver"); 8539 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8540 if (r == null) { 8541 r = new StringBuilder(256); 8542 } else { 8543 r.append(' '); 8544 } 8545 r.append(a.info.name); 8546 } 8547 } 8548 if (r != null) { 8549 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8550 } 8551 8552 N = pkg.activities.size(); 8553 r = null; 8554 for (i=0; i<N; i++) { 8555 PackageParser.Activity a = pkg.activities.get(i); 8556 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8557 a.info.processName, pkg.applicationInfo.uid); 8558 mActivities.addActivity(a, "activity"); 8559 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8560 if (r == null) { 8561 r = new StringBuilder(256); 8562 } else { 8563 r.append(' '); 8564 } 8565 r.append(a.info.name); 8566 } 8567 } 8568 if (r != null) { 8569 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8570 } 8571 8572 N = pkg.permissionGroups.size(); 8573 r = null; 8574 for (i=0; i<N; i++) { 8575 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8576 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8577 if (cur == null) { 8578 mPermissionGroups.put(pg.info.name, pg); 8579 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8580 if (r == null) { 8581 r = new StringBuilder(256); 8582 } else { 8583 r.append(' '); 8584 } 8585 r.append(pg.info.name); 8586 } 8587 } else { 8588 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8589 + pg.info.packageName + " ignored: original from " 8590 + cur.info.packageName); 8591 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8592 if (r == null) { 8593 r = new StringBuilder(256); 8594 } else { 8595 r.append(' '); 8596 } 8597 r.append("DUP:"); 8598 r.append(pg.info.name); 8599 } 8600 } 8601 } 8602 if (r != null) { 8603 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8604 } 8605 8606 N = pkg.permissions.size(); 8607 r = null; 8608 for (i=0; i<N; i++) { 8609 PackageParser.Permission p = pkg.permissions.get(i); 8610 8611 // Assume by default that we did not install this permission into the system. 8612 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8613 8614 // Now that permission groups have a special meaning, we ignore permission 8615 // groups for legacy apps to prevent unexpected behavior. In particular, 8616 // permissions for one app being granted to someone just becase they happen 8617 // to be in a group defined by another app (before this had no implications). 8618 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8619 p.group = mPermissionGroups.get(p.info.group); 8620 // Warn for a permission in an unknown group. 8621 if (p.info.group != null && p.group == null) { 8622 Slog.w(TAG, "Permission " + p.info.name + " from package " 8623 + p.info.packageName + " in an unknown group " + p.info.group); 8624 } 8625 } 8626 8627 ArrayMap<String, BasePermission> permissionMap = 8628 p.tree ? mSettings.mPermissionTrees 8629 : mSettings.mPermissions; 8630 BasePermission bp = permissionMap.get(p.info.name); 8631 8632 // Allow system apps to redefine non-system permissions 8633 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8634 final boolean currentOwnerIsSystem = (bp.perm != null 8635 && isSystemApp(bp.perm.owner)); 8636 if (isSystemApp(p.owner)) { 8637 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8638 // It's a built-in permission and no owner, take ownership now 8639 bp.packageSetting = pkgSetting; 8640 bp.perm = p; 8641 bp.uid = pkg.applicationInfo.uid; 8642 bp.sourcePackage = p.info.packageName; 8643 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8644 } else if (!currentOwnerIsSystem) { 8645 String msg = "New decl " + p.owner + " of permission " 8646 + p.info.name + " is system; overriding " + bp.sourcePackage; 8647 reportSettingsProblem(Log.WARN, msg); 8648 bp = null; 8649 } 8650 } 8651 } 8652 8653 if (bp == null) { 8654 bp = new BasePermission(p.info.name, p.info.packageName, 8655 BasePermission.TYPE_NORMAL); 8656 permissionMap.put(p.info.name, bp); 8657 } 8658 8659 if (bp.perm == null) { 8660 if (bp.sourcePackage == null 8661 || bp.sourcePackage.equals(p.info.packageName)) { 8662 BasePermission tree = findPermissionTreeLP(p.info.name); 8663 if (tree == null 8664 || tree.sourcePackage.equals(p.info.packageName)) { 8665 bp.packageSetting = pkgSetting; 8666 bp.perm = p; 8667 bp.uid = pkg.applicationInfo.uid; 8668 bp.sourcePackage = p.info.packageName; 8669 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8670 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8671 if (r == null) { 8672 r = new StringBuilder(256); 8673 } else { 8674 r.append(' '); 8675 } 8676 r.append(p.info.name); 8677 } 8678 } else { 8679 Slog.w(TAG, "Permission " + p.info.name + " from package " 8680 + p.info.packageName + " ignored: base tree " 8681 + tree.name + " is from package " 8682 + tree.sourcePackage); 8683 } 8684 } else { 8685 Slog.w(TAG, "Permission " + p.info.name + " from package " 8686 + p.info.packageName + " ignored: original from " 8687 + bp.sourcePackage); 8688 } 8689 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8690 if (r == null) { 8691 r = new StringBuilder(256); 8692 } else { 8693 r.append(' '); 8694 } 8695 r.append("DUP:"); 8696 r.append(p.info.name); 8697 } 8698 if (bp.perm == p) { 8699 bp.protectionLevel = p.info.protectionLevel; 8700 } 8701 } 8702 8703 if (r != null) { 8704 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8705 } 8706 8707 N = pkg.instrumentation.size(); 8708 r = null; 8709 for (i=0; i<N; i++) { 8710 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8711 a.info.packageName = pkg.applicationInfo.packageName; 8712 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8713 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8714 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8715 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8716 a.info.dataDir = pkg.applicationInfo.dataDir; 8717 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8718 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8719 8720 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8721 // need other information about the application, like the ABI and what not ? 8722 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8723 mInstrumentation.put(a.getComponentName(), a); 8724 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8725 if (r == null) { 8726 r = new StringBuilder(256); 8727 } else { 8728 r.append(' '); 8729 } 8730 r.append(a.info.name); 8731 } 8732 } 8733 if (r != null) { 8734 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8735 } 8736 8737 if (pkg.protectedBroadcasts != null) { 8738 N = pkg.protectedBroadcasts.size(); 8739 for (i=0; i<N; i++) { 8740 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8741 } 8742 } 8743 8744 pkgSetting.setTimeStamp(scanFileTime); 8745 8746 // Create idmap files for pairs of (packages, overlay packages). 8747 // Note: "android", ie framework-res.apk, is handled by native layers. 8748 if (pkg.mOverlayTarget != null) { 8749 // This is an overlay package. 8750 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8751 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8752 mOverlays.put(pkg.mOverlayTarget, 8753 new ArrayMap<String, PackageParser.Package>()); 8754 } 8755 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8756 map.put(pkg.packageName, pkg); 8757 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8758 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8759 createIdmapFailed = true; 8760 } 8761 } 8762 } else if (mOverlays.containsKey(pkg.packageName) && 8763 !pkg.packageName.equals("android")) { 8764 // This is a regular package, with one or more known overlay packages. 8765 createIdmapsForPackageLI(pkg); 8766 } 8767 } 8768 8769 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8770 8771 if (createIdmapFailed) { 8772 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8773 "scanPackageLI failed to createIdmap"); 8774 } 8775 return pkg; 8776 } 8777 8778 /** 8779 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8780 * is derived purely on the basis of the contents of {@code scanFile} and 8781 * {@code cpuAbiOverride}. 8782 * 8783 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8784 */ 8785 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8786 String cpuAbiOverride, boolean extractLibs) 8787 throws PackageManagerException { 8788 // TODO: We can probably be smarter about this stuff. For installed apps, 8789 // we can calculate this information at install time once and for all. For 8790 // system apps, we can probably assume that this information doesn't change 8791 // after the first boot scan. As things stand, we do lots of unnecessary work. 8792 8793 // Give ourselves some initial paths; we'll come back for another 8794 // pass once we've determined ABI below. 8795 setNativeLibraryPaths(pkg); 8796 8797 // We would never need to extract libs for forward-locked and external packages, 8798 // since the container service will do it for us. We shouldn't attempt to 8799 // extract libs from system app when it was not updated. 8800 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8801 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8802 extractLibs = false; 8803 } 8804 8805 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8806 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8807 8808 NativeLibraryHelper.Handle handle = null; 8809 try { 8810 handle = NativeLibraryHelper.Handle.create(pkg); 8811 // TODO(multiArch): This can be null for apps that didn't go through the 8812 // usual installation process. We can calculate it again, like we 8813 // do during install time. 8814 // 8815 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8816 // unnecessary. 8817 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8818 8819 // Null out the abis so that they can be recalculated. 8820 pkg.applicationInfo.primaryCpuAbi = null; 8821 pkg.applicationInfo.secondaryCpuAbi = null; 8822 if (isMultiArch(pkg.applicationInfo)) { 8823 // Warn if we've set an abiOverride for multi-lib packages.. 8824 // By definition, we need to copy both 32 and 64 bit libraries for 8825 // such packages. 8826 if (pkg.cpuAbiOverride != null 8827 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8828 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8829 } 8830 8831 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8832 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8833 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8834 if (extractLibs) { 8835 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8836 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8837 useIsaSpecificSubdirs); 8838 } else { 8839 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8840 } 8841 } 8842 8843 maybeThrowExceptionForMultiArchCopy( 8844 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8845 8846 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8847 if (extractLibs) { 8848 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8849 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8850 useIsaSpecificSubdirs); 8851 } else { 8852 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8853 } 8854 } 8855 8856 maybeThrowExceptionForMultiArchCopy( 8857 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8858 8859 if (abi64 >= 0) { 8860 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8861 } 8862 8863 if (abi32 >= 0) { 8864 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8865 if (abi64 >= 0) { 8866 if (pkg.use32bitAbi) { 8867 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8868 pkg.applicationInfo.primaryCpuAbi = abi; 8869 } else { 8870 pkg.applicationInfo.secondaryCpuAbi = abi; 8871 } 8872 } else { 8873 pkg.applicationInfo.primaryCpuAbi = abi; 8874 } 8875 } 8876 8877 } else { 8878 String[] abiList = (cpuAbiOverride != null) ? 8879 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8880 8881 // Enable gross and lame hacks for apps that are built with old 8882 // SDK tools. We must scan their APKs for renderscript bitcode and 8883 // not launch them if it's present. Don't bother checking on devices 8884 // that don't have 64 bit support. 8885 boolean needsRenderScriptOverride = false; 8886 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8887 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8888 abiList = Build.SUPPORTED_32_BIT_ABIS; 8889 needsRenderScriptOverride = true; 8890 } 8891 8892 final int copyRet; 8893 if (extractLibs) { 8894 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8895 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8896 } else { 8897 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8898 } 8899 8900 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8901 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8902 "Error unpackaging native libs for app, errorCode=" + copyRet); 8903 } 8904 8905 if (copyRet >= 0) { 8906 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8907 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8908 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8909 } else if (needsRenderScriptOverride) { 8910 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8911 } 8912 } 8913 } catch (IOException ioe) { 8914 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8915 } finally { 8916 IoUtils.closeQuietly(handle); 8917 } 8918 8919 // Now that we've calculated the ABIs and determined if it's an internal app, 8920 // we will go ahead and populate the nativeLibraryPath. 8921 setNativeLibraryPaths(pkg); 8922 } 8923 8924 /** 8925 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8926 * i.e, so that all packages can be run inside a single process if required. 8927 * 8928 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8929 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8930 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8931 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8932 * updating a package that belongs to a shared user. 8933 * 8934 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8935 * adds unnecessary complexity. 8936 */ 8937 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8938 PackageParser.Package scannedPackage, boolean bootComplete) { 8939 String requiredInstructionSet = null; 8940 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8941 requiredInstructionSet = VMRuntime.getInstructionSet( 8942 scannedPackage.applicationInfo.primaryCpuAbi); 8943 } 8944 8945 PackageSetting requirer = null; 8946 for (PackageSetting ps : packagesForUser) { 8947 // If packagesForUser contains scannedPackage, we skip it. This will happen 8948 // when scannedPackage is an update of an existing package. Without this check, 8949 // we will never be able to change the ABI of any package belonging to a shared 8950 // user, even if it's compatible with other packages. 8951 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8952 if (ps.primaryCpuAbiString == null) { 8953 continue; 8954 } 8955 8956 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8957 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8958 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8959 // this but there's not much we can do. 8960 String errorMessage = "Instruction set mismatch, " 8961 + ((requirer == null) ? "[caller]" : requirer) 8962 + " requires " + requiredInstructionSet + " whereas " + ps 8963 + " requires " + instructionSet; 8964 Slog.w(TAG, errorMessage); 8965 } 8966 8967 if (requiredInstructionSet == null) { 8968 requiredInstructionSet = instructionSet; 8969 requirer = ps; 8970 } 8971 } 8972 } 8973 8974 if (requiredInstructionSet != null) { 8975 String adjustedAbi; 8976 if (requirer != null) { 8977 // requirer != null implies that either scannedPackage was null or that scannedPackage 8978 // did not require an ABI, in which case we have to adjust scannedPackage to match 8979 // the ABI of the set (which is the same as requirer's ABI) 8980 adjustedAbi = requirer.primaryCpuAbiString; 8981 if (scannedPackage != null) { 8982 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8983 } 8984 } else { 8985 // requirer == null implies that we're updating all ABIs in the set to 8986 // match scannedPackage. 8987 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8988 } 8989 8990 for (PackageSetting ps : packagesForUser) { 8991 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8992 if (ps.primaryCpuAbiString != null) { 8993 continue; 8994 } 8995 8996 ps.primaryCpuAbiString = adjustedAbi; 8997 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8998 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8999 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9000 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9001 + " (requirer=" 9002 + (requirer == null ? "null" : requirer.pkg.packageName) 9003 + ", scannedPackage=" 9004 + (scannedPackage != null ? scannedPackage.packageName : "null") 9005 + ")"); 9006 try { 9007 mInstaller.rmdex(ps.codePathString, 9008 getDexCodeInstructionSet(getPreferredInstructionSet())); 9009 } catch (InstallerException ignored) { 9010 } 9011 } 9012 } 9013 } 9014 } 9015 } 9016 9017 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9018 synchronized (mPackages) { 9019 mResolverReplaced = true; 9020 // Set up information for custom user intent resolution activity. 9021 mResolveActivity.applicationInfo = pkg.applicationInfo; 9022 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9023 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9024 mResolveActivity.processName = pkg.applicationInfo.packageName; 9025 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9026 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9027 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9028 mResolveActivity.theme = 0; 9029 mResolveActivity.exported = true; 9030 mResolveActivity.enabled = true; 9031 mResolveInfo.activityInfo = mResolveActivity; 9032 mResolveInfo.priority = 0; 9033 mResolveInfo.preferredOrder = 0; 9034 mResolveInfo.match = 0; 9035 mResolveComponentName = mCustomResolverComponentName; 9036 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9037 mResolveComponentName); 9038 } 9039 } 9040 9041 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9042 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9043 9044 // Set up information for ephemeral installer activity 9045 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9046 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9047 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9048 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9049 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9050 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9051 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9052 mEphemeralInstallerActivity.theme = 0; 9053 mEphemeralInstallerActivity.exported = true; 9054 mEphemeralInstallerActivity.enabled = true; 9055 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9056 mEphemeralInstallerInfo.priority = 0; 9057 mEphemeralInstallerInfo.preferredOrder = 0; 9058 mEphemeralInstallerInfo.match = 0; 9059 9060 if (DEBUG_EPHEMERAL) { 9061 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9062 } 9063 } 9064 9065 private static String calculateBundledApkRoot(final String codePathString) { 9066 final File codePath = new File(codePathString); 9067 final File codeRoot; 9068 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9069 codeRoot = Environment.getRootDirectory(); 9070 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9071 codeRoot = Environment.getOemDirectory(); 9072 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9073 codeRoot = Environment.getVendorDirectory(); 9074 } else { 9075 // Unrecognized code path; take its top real segment as the apk root: 9076 // e.g. /something/app/blah.apk => /something 9077 try { 9078 File f = codePath.getCanonicalFile(); 9079 File parent = f.getParentFile(); // non-null because codePath is a file 9080 File tmp; 9081 while ((tmp = parent.getParentFile()) != null) { 9082 f = parent; 9083 parent = tmp; 9084 } 9085 codeRoot = f; 9086 Slog.w(TAG, "Unrecognized code path " 9087 + codePath + " - using " + codeRoot); 9088 } catch (IOException e) { 9089 // Can't canonicalize the code path -- shenanigans? 9090 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9091 return Environment.getRootDirectory().getPath(); 9092 } 9093 } 9094 return codeRoot.getPath(); 9095 } 9096 9097 /** 9098 * Derive and set the location of native libraries for the given package, 9099 * which varies depending on where and how the package was installed. 9100 */ 9101 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9102 final ApplicationInfo info = pkg.applicationInfo; 9103 final String codePath = pkg.codePath; 9104 final File codeFile = new File(codePath); 9105 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9106 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9107 9108 info.nativeLibraryRootDir = null; 9109 info.nativeLibraryRootRequiresIsa = false; 9110 info.nativeLibraryDir = null; 9111 info.secondaryNativeLibraryDir = null; 9112 9113 if (isApkFile(codeFile)) { 9114 // Monolithic install 9115 if (bundledApp) { 9116 // If "/system/lib64/apkname" exists, assume that is the per-package 9117 // native library directory to use; otherwise use "/system/lib/apkname". 9118 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9119 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9120 getPrimaryInstructionSet(info)); 9121 9122 // This is a bundled system app so choose the path based on the ABI. 9123 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9124 // is just the default path. 9125 final String apkName = deriveCodePathName(codePath); 9126 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9127 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9128 apkName).getAbsolutePath(); 9129 9130 if (info.secondaryCpuAbi != null) { 9131 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9132 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9133 secondaryLibDir, apkName).getAbsolutePath(); 9134 } 9135 } else if (asecApp) { 9136 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9137 .getAbsolutePath(); 9138 } else { 9139 final String apkName = deriveCodePathName(codePath); 9140 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9141 .getAbsolutePath(); 9142 } 9143 9144 info.nativeLibraryRootRequiresIsa = false; 9145 info.nativeLibraryDir = info.nativeLibraryRootDir; 9146 } else { 9147 // Cluster install 9148 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9149 info.nativeLibraryRootRequiresIsa = true; 9150 9151 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9152 getPrimaryInstructionSet(info)).getAbsolutePath(); 9153 9154 if (info.secondaryCpuAbi != null) { 9155 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9156 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9157 } 9158 } 9159 } 9160 9161 /** 9162 * Calculate the abis and roots for a bundled app. These can uniquely 9163 * be determined from the contents of the system partition, i.e whether 9164 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9165 * of this information, and instead assume that the system was built 9166 * sensibly. 9167 */ 9168 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9169 PackageSetting pkgSetting) { 9170 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9171 9172 // If "/system/lib64/apkname" exists, assume that is the per-package 9173 // native library directory to use; otherwise use "/system/lib/apkname". 9174 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9175 setBundledAppAbi(pkg, apkRoot, apkName); 9176 // pkgSetting might be null during rescan following uninstall of updates 9177 // to a bundled app, so accommodate that possibility. The settings in 9178 // that case will be established later from the parsed package. 9179 // 9180 // If the settings aren't null, sync them up with what we've just derived. 9181 // note that apkRoot isn't stored in the package settings. 9182 if (pkgSetting != null) { 9183 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9184 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9185 } 9186 } 9187 9188 /** 9189 * Deduces the ABI of a bundled app and sets the relevant fields on the 9190 * parsed pkg object. 9191 * 9192 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9193 * under which system libraries are installed. 9194 * @param apkName the name of the installed package. 9195 */ 9196 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9197 final File codeFile = new File(pkg.codePath); 9198 9199 final boolean has64BitLibs; 9200 final boolean has32BitLibs; 9201 if (isApkFile(codeFile)) { 9202 // Monolithic install 9203 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9204 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9205 } else { 9206 // Cluster install 9207 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9208 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9209 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9210 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9211 has64BitLibs = (new File(rootDir, isa)).exists(); 9212 } else { 9213 has64BitLibs = false; 9214 } 9215 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9216 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9217 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9218 has32BitLibs = (new File(rootDir, isa)).exists(); 9219 } else { 9220 has32BitLibs = false; 9221 } 9222 } 9223 9224 if (has64BitLibs && !has32BitLibs) { 9225 // The package has 64 bit libs, but not 32 bit libs. Its primary 9226 // ABI should be 64 bit. We can safely assume here that the bundled 9227 // native libraries correspond to the most preferred ABI in the list. 9228 9229 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9230 pkg.applicationInfo.secondaryCpuAbi = null; 9231 } else if (has32BitLibs && !has64BitLibs) { 9232 // The package has 32 bit libs but not 64 bit libs. Its primary 9233 // ABI should be 32 bit. 9234 9235 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9236 pkg.applicationInfo.secondaryCpuAbi = null; 9237 } else if (has32BitLibs && has64BitLibs) { 9238 // The application has both 64 and 32 bit bundled libraries. We check 9239 // here that the app declares multiArch support, and warn if it doesn't. 9240 // 9241 // We will be lenient here and record both ABIs. The primary will be the 9242 // ABI that's higher on the list, i.e, a device that's configured to prefer 9243 // 64 bit apps will see a 64 bit primary ABI, 9244 9245 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9246 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9247 } 9248 9249 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9250 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9251 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9252 } else { 9253 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9254 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9255 } 9256 } else { 9257 pkg.applicationInfo.primaryCpuAbi = null; 9258 pkg.applicationInfo.secondaryCpuAbi = null; 9259 } 9260 } 9261 9262 private void killApplication(String pkgName, int appId, String reason) { 9263 // Request the ActivityManager to kill the process(only for existing packages) 9264 // so that we do not end up in a confused state while the user is still using the older 9265 // version of the application while the new one gets installed. 9266 final long token = Binder.clearCallingIdentity(); 9267 try { 9268 IActivityManager am = ActivityManagerNative.getDefault(); 9269 if (am != null) { 9270 try { 9271 am.killApplicationWithAppId(pkgName, appId, reason); 9272 } catch (RemoteException e) { 9273 } 9274 } 9275 } finally { 9276 Binder.restoreCallingIdentity(token); 9277 } 9278 } 9279 9280 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9281 // Remove the parent package setting 9282 PackageSetting ps = (PackageSetting) pkg.mExtras; 9283 if (ps != null) { 9284 removePackageLI(ps, chatty); 9285 } 9286 // Remove the child package setting 9287 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9288 for (int i = 0; i < childCount; i++) { 9289 PackageParser.Package childPkg = pkg.childPackages.get(i); 9290 ps = (PackageSetting) childPkg.mExtras; 9291 if (ps != null) { 9292 removePackageLI(ps, chatty); 9293 } 9294 } 9295 } 9296 9297 void removePackageLI(PackageSetting ps, boolean chatty) { 9298 if (DEBUG_INSTALL) { 9299 if (chatty) 9300 Log.d(TAG, "Removing package " + ps.name); 9301 } 9302 9303 // writer 9304 synchronized (mPackages) { 9305 mPackages.remove(ps.name); 9306 final PackageParser.Package pkg = ps.pkg; 9307 if (pkg != null) { 9308 cleanPackageDataStructuresLILPw(pkg, chatty); 9309 } 9310 } 9311 } 9312 9313 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9314 if (DEBUG_INSTALL) { 9315 if (chatty) 9316 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9317 } 9318 9319 // writer 9320 synchronized (mPackages) { 9321 // Remove the parent package 9322 mPackages.remove(pkg.applicationInfo.packageName); 9323 cleanPackageDataStructuresLILPw(pkg, chatty); 9324 9325 // Remove the child packages 9326 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9327 for (int i = 0; i < childCount; i++) { 9328 PackageParser.Package childPkg = pkg.childPackages.get(i); 9329 mPackages.remove(childPkg.applicationInfo.packageName); 9330 cleanPackageDataStructuresLILPw(childPkg, chatty); 9331 } 9332 } 9333 } 9334 9335 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9336 int N = pkg.providers.size(); 9337 StringBuilder r = null; 9338 int i; 9339 for (i=0; i<N; i++) { 9340 PackageParser.Provider p = pkg.providers.get(i); 9341 mProviders.removeProvider(p); 9342 if (p.info.authority == null) { 9343 9344 /* There was another ContentProvider with this authority when 9345 * this app was installed so this authority is null, 9346 * Ignore it as we don't have to unregister the provider. 9347 */ 9348 continue; 9349 } 9350 String names[] = p.info.authority.split(";"); 9351 for (int j = 0; j < names.length; j++) { 9352 if (mProvidersByAuthority.get(names[j]) == p) { 9353 mProvidersByAuthority.remove(names[j]); 9354 if (DEBUG_REMOVE) { 9355 if (chatty) 9356 Log.d(TAG, "Unregistered content provider: " + names[j] 9357 + ", className = " + p.info.name + ", isSyncable = " 9358 + p.info.isSyncable); 9359 } 9360 } 9361 } 9362 if (DEBUG_REMOVE && chatty) { 9363 if (r == null) { 9364 r = new StringBuilder(256); 9365 } else { 9366 r.append(' '); 9367 } 9368 r.append(p.info.name); 9369 } 9370 } 9371 if (r != null) { 9372 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9373 } 9374 9375 N = pkg.services.size(); 9376 r = null; 9377 for (i=0; i<N; i++) { 9378 PackageParser.Service s = pkg.services.get(i); 9379 mServices.removeService(s); 9380 if (chatty) { 9381 if (r == null) { 9382 r = new StringBuilder(256); 9383 } else { 9384 r.append(' '); 9385 } 9386 r.append(s.info.name); 9387 } 9388 } 9389 if (r != null) { 9390 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9391 } 9392 9393 N = pkg.receivers.size(); 9394 r = null; 9395 for (i=0; i<N; i++) { 9396 PackageParser.Activity a = pkg.receivers.get(i); 9397 mReceivers.removeActivity(a, "receiver"); 9398 if (DEBUG_REMOVE && chatty) { 9399 if (r == null) { 9400 r = new StringBuilder(256); 9401 } else { 9402 r.append(' '); 9403 } 9404 r.append(a.info.name); 9405 } 9406 } 9407 if (r != null) { 9408 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9409 } 9410 9411 N = pkg.activities.size(); 9412 r = null; 9413 for (i=0; i<N; i++) { 9414 PackageParser.Activity a = pkg.activities.get(i); 9415 mActivities.removeActivity(a, "activity"); 9416 if (DEBUG_REMOVE && chatty) { 9417 if (r == null) { 9418 r = new StringBuilder(256); 9419 } else { 9420 r.append(' '); 9421 } 9422 r.append(a.info.name); 9423 } 9424 } 9425 if (r != null) { 9426 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9427 } 9428 9429 N = pkg.permissions.size(); 9430 r = null; 9431 for (i=0; i<N; i++) { 9432 PackageParser.Permission p = pkg.permissions.get(i); 9433 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9434 if (bp == null) { 9435 bp = mSettings.mPermissionTrees.get(p.info.name); 9436 } 9437 if (bp != null && bp.perm == p) { 9438 bp.perm = null; 9439 if (DEBUG_REMOVE && chatty) { 9440 if (r == null) { 9441 r = new StringBuilder(256); 9442 } else { 9443 r.append(' '); 9444 } 9445 r.append(p.info.name); 9446 } 9447 } 9448 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9449 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9450 if (appOpPkgs != null) { 9451 appOpPkgs.remove(pkg.packageName); 9452 } 9453 } 9454 } 9455 if (r != null) { 9456 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9457 } 9458 9459 N = pkg.requestedPermissions.size(); 9460 r = null; 9461 for (i=0; i<N; i++) { 9462 String perm = pkg.requestedPermissions.get(i); 9463 BasePermission bp = mSettings.mPermissions.get(perm); 9464 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9465 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9466 if (appOpPkgs != null) { 9467 appOpPkgs.remove(pkg.packageName); 9468 if (appOpPkgs.isEmpty()) { 9469 mAppOpPermissionPackages.remove(perm); 9470 } 9471 } 9472 } 9473 } 9474 if (r != null) { 9475 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9476 } 9477 9478 N = pkg.instrumentation.size(); 9479 r = null; 9480 for (i=0; i<N; i++) { 9481 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9482 mInstrumentation.remove(a.getComponentName()); 9483 if (DEBUG_REMOVE && chatty) { 9484 if (r == null) { 9485 r = new StringBuilder(256); 9486 } else { 9487 r.append(' '); 9488 } 9489 r.append(a.info.name); 9490 } 9491 } 9492 if (r != null) { 9493 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9494 } 9495 9496 r = null; 9497 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9498 // Only system apps can hold shared libraries. 9499 if (pkg.libraryNames != null) { 9500 for (i=0; i<pkg.libraryNames.size(); i++) { 9501 String name = pkg.libraryNames.get(i); 9502 SharedLibraryEntry cur = mSharedLibraries.get(name); 9503 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9504 mSharedLibraries.remove(name); 9505 if (DEBUG_REMOVE && chatty) { 9506 if (r == null) { 9507 r = new StringBuilder(256); 9508 } else { 9509 r.append(' '); 9510 } 9511 r.append(name); 9512 } 9513 } 9514 } 9515 } 9516 } 9517 if (r != null) { 9518 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9519 } 9520 } 9521 9522 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9523 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9524 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9525 return true; 9526 } 9527 } 9528 return false; 9529 } 9530 9531 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9532 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9533 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9534 9535 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9536 // Update the parent permissions 9537 updatePermissionsLPw(pkg.packageName, pkg, flags); 9538 // Update the child permissions 9539 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9540 for (int i = 0; i < childCount; i++) { 9541 PackageParser.Package childPkg = pkg.childPackages.get(i); 9542 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9543 } 9544 } 9545 9546 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9547 int flags) { 9548 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9549 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9550 } 9551 9552 private void updatePermissionsLPw(String changingPkg, 9553 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9554 // Make sure there are no dangling permission trees. 9555 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9556 while (it.hasNext()) { 9557 final BasePermission bp = it.next(); 9558 if (bp.packageSetting == null) { 9559 // We may not yet have parsed the package, so just see if 9560 // we still know about its settings. 9561 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9562 } 9563 if (bp.packageSetting == null) { 9564 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9565 + " from package " + bp.sourcePackage); 9566 it.remove(); 9567 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9568 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9569 Slog.i(TAG, "Removing old permission tree: " + bp.name 9570 + " from package " + bp.sourcePackage); 9571 flags |= UPDATE_PERMISSIONS_ALL; 9572 it.remove(); 9573 } 9574 } 9575 } 9576 9577 // Make sure all dynamic permissions have been assigned to a package, 9578 // and make sure there are no dangling permissions. 9579 it = mSettings.mPermissions.values().iterator(); 9580 while (it.hasNext()) { 9581 final BasePermission bp = it.next(); 9582 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9583 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9584 + bp.name + " pkg=" + bp.sourcePackage 9585 + " info=" + bp.pendingInfo); 9586 if (bp.packageSetting == null && bp.pendingInfo != null) { 9587 final BasePermission tree = findPermissionTreeLP(bp.name); 9588 if (tree != null && tree.perm != null) { 9589 bp.packageSetting = tree.packageSetting; 9590 bp.perm = new PackageParser.Permission(tree.perm.owner, 9591 new PermissionInfo(bp.pendingInfo)); 9592 bp.perm.info.packageName = tree.perm.info.packageName; 9593 bp.perm.info.name = bp.name; 9594 bp.uid = tree.uid; 9595 } 9596 } 9597 } 9598 if (bp.packageSetting == null) { 9599 // We may not yet have parsed the package, so just see if 9600 // we still know about its settings. 9601 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9602 } 9603 if (bp.packageSetting == null) { 9604 Slog.w(TAG, "Removing dangling permission: " + bp.name 9605 + " from package " + bp.sourcePackage); 9606 it.remove(); 9607 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9608 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9609 Slog.i(TAG, "Removing old permission: " + bp.name 9610 + " from package " + bp.sourcePackage); 9611 flags |= UPDATE_PERMISSIONS_ALL; 9612 it.remove(); 9613 } 9614 } 9615 } 9616 9617 // Now update the permissions for all packages, in particular 9618 // replace the granted permissions of the system packages. 9619 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9620 for (PackageParser.Package pkg : mPackages.values()) { 9621 if (pkg != pkgInfo) { 9622 // Only replace for packages on requested volume 9623 final String volumeUuid = getVolumeUuidForPackage(pkg); 9624 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9625 && Objects.equals(replaceVolumeUuid, volumeUuid); 9626 grantPermissionsLPw(pkg, replace, changingPkg); 9627 } 9628 } 9629 } 9630 9631 if (pkgInfo != null) { 9632 // Only replace for packages on requested volume 9633 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9634 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9635 && Objects.equals(replaceVolumeUuid, volumeUuid); 9636 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9637 } 9638 } 9639 9640 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9641 String packageOfInterest) { 9642 // IMPORTANT: There are two types of permissions: install and runtime. 9643 // Install time permissions are granted when the app is installed to 9644 // all device users and users added in the future. Runtime permissions 9645 // are granted at runtime explicitly to specific users. Normal and signature 9646 // protected permissions are install time permissions. Dangerous permissions 9647 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9648 // otherwise they are runtime permissions. This function does not manage 9649 // runtime permissions except for the case an app targeting Lollipop MR1 9650 // being upgraded to target a newer SDK, in which case dangerous permissions 9651 // are transformed from install time to runtime ones. 9652 9653 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9654 if (ps == null) { 9655 return; 9656 } 9657 9658 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9659 9660 PermissionsState permissionsState = ps.getPermissionsState(); 9661 PermissionsState origPermissions = permissionsState; 9662 9663 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9664 9665 boolean runtimePermissionsRevoked = false; 9666 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9667 9668 boolean changedInstallPermission = false; 9669 9670 if (replace) { 9671 ps.installPermissionsFixed = false; 9672 if (!ps.isSharedUser()) { 9673 origPermissions = new PermissionsState(permissionsState); 9674 permissionsState.reset(); 9675 } else { 9676 // We need to know only about runtime permission changes since the 9677 // calling code always writes the install permissions state but 9678 // the runtime ones are written only if changed. The only cases of 9679 // changed runtime permissions here are promotion of an install to 9680 // runtime and revocation of a runtime from a shared user. 9681 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9682 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9683 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9684 runtimePermissionsRevoked = true; 9685 } 9686 } 9687 } 9688 9689 permissionsState.setGlobalGids(mGlobalGids); 9690 9691 final int N = pkg.requestedPermissions.size(); 9692 for (int i=0; i<N; i++) { 9693 final String name = pkg.requestedPermissions.get(i); 9694 final BasePermission bp = mSettings.mPermissions.get(name); 9695 9696 if (DEBUG_INSTALL) { 9697 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9698 } 9699 9700 if (bp == null || bp.packageSetting == null) { 9701 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9702 Slog.w(TAG, "Unknown permission " + name 9703 + " in package " + pkg.packageName); 9704 } 9705 continue; 9706 } 9707 9708 final String perm = bp.name; 9709 boolean allowedSig = false; 9710 int grant = GRANT_DENIED; 9711 9712 // Keep track of app op permissions. 9713 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9714 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9715 if (pkgs == null) { 9716 pkgs = new ArraySet<>(); 9717 mAppOpPermissionPackages.put(bp.name, pkgs); 9718 } 9719 pkgs.add(pkg.packageName); 9720 } 9721 9722 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9723 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9724 >= Build.VERSION_CODES.M; 9725 switch (level) { 9726 case PermissionInfo.PROTECTION_NORMAL: { 9727 // For all apps normal permissions are install time ones. 9728 grant = GRANT_INSTALL; 9729 } break; 9730 9731 case PermissionInfo.PROTECTION_DANGEROUS: { 9732 // If a permission review is required for legacy apps we represent 9733 // their permissions as always granted runtime ones since we need 9734 // to keep the review required permission flag per user while an 9735 // install permission's state is shared across all users. 9736 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9737 // For legacy apps dangerous permissions are install time ones. 9738 grant = GRANT_INSTALL; 9739 } else if (origPermissions.hasInstallPermission(bp.name)) { 9740 // For legacy apps that became modern, install becomes runtime. 9741 grant = GRANT_UPGRADE; 9742 } else if (mPromoteSystemApps 9743 && isSystemApp(ps) 9744 && mExistingSystemPackages.contains(ps.name)) { 9745 // For legacy system apps, install becomes runtime. 9746 // We cannot check hasInstallPermission() for system apps since those 9747 // permissions were granted implicitly and not persisted pre-M. 9748 grant = GRANT_UPGRADE; 9749 } else { 9750 // For modern apps keep runtime permissions unchanged. 9751 grant = GRANT_RUNTIME; 9752 } 9753 } break; 9754 9755 case PermissionInfo.PROTECTION_SIGNATURE: { 9756 // For all apps signature permissions are install time ones. 9757 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9758 if (allowedSig) { 9759 grant = GRANT_INSTALL; 9760 } 9761 } break; 9762 } 9763 9764 if (DEBUG_INSTALL) { 9765 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9766 } 9767 9768 if (grant != GRANT_DENIED) { 9769 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9770 // If this is an existing, non-system package, then 9771 // we can't add any new permissions to it. 9772 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9773 // Except... if this is a permission that was added 9774 // to the platform (note: need to only do this when 9775 // updating the platform). 9776 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9777 grant = GRANT_DENIED; 9778 } 9779 } 9780 } 9781 9782 switch (grant) { 9783 case GRANT_INSTALL: { 9784 // Revoke this as runtime permission to handle the case of 9785 // a runtime permission being downgraded to an install one. 9786 // Also in permission review mode we keep dangerous permissions 9787 // for legacy apps 9788 for (int userId : UserManagerService.getInstance().getUserIds()) { 9789 if (origPermissions.getRuntimePermissionState( 9790 bp.name, userId) != null) { 9791 // Revoke the runtime permission and clear the flags. 9792 origPermissions.revokeRuntimePermission(bp, userId); 9793 origPermissions.updatePermissionFlags(bp, userId, 9794 PackageManager.MASK_PERMISSION_FLAGS, 0); 9795 // If we revoked a permission permission, we have to write. 9796 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9797 changedRuntimePermissionUserIds, userId); 9798 } 9799 } 9800 // Grant an install permission. 9801 if (permissionsState.grantInstallPermission(bp) != 9802 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9803 changedInstallPermission = true; 9804 } 9805 } break; 9806 9807 case GRANT_RUNTIME: { 9808 // Grant previously granted runtime permissions. 9809 for (int userId : UserManagerService.getInstance().getUserIds()) { 9810 PermissionState permissionState = origPermissions 9811 .getRuntimePermissionState(bp.name, userId); 9812 int flags = permissionState != null 9813 ? permissionState.getFlags() : 0; 9814 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9815 if (permissionsState.grantRuntimePermission(bp, userId) == 9816 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9817 // If we cannot put the permission as it was, we have to write. 9818 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9819 changedRuntimePermissionUserIds, userId); 9820 } 9821 // If the app supports runtime permissions no need for a review. 9822 if (Build.PERMISSIONS_REVIEW_REQUIRED 9823 && appSupportsRuntimePermissions 9824 && (flags & PackageManager 9825 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9826 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9827 // Since we changed the flags, we have to write. 9828 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9829 changedRuntimePermissionUserIds, userId); 9830 } 9831 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9832 && !appSupportsRuntimePermissions) { 9833 // For legacy apps that need a permission review, every new 9834 // runtime permission is granted but it is pending a review. 9835 // We also need to review only platform defined runtime 9836 // permissions as these are the only ones the platform knows 9837 // how to disable the API to simulate revocation as legacy 9838 // apps don't expect to run with revoked permissions. 9839 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9840 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9841 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9842 // We changed the flags, hence have to write. 9843 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9844 changedRuntimePermissionUserIds, userId); 9845 } 9846 } 9847 if (permissionsState.grantRuntimePermission(bp, userId) 9848 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9849 // We changed the permission, hence have to write. 9850 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9851 changedRuntimePermissionUserIds, userId); 9852 } 9853 } 9854 // Propagate the permission flags. 9855 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9856 } 9857 } break; 9858 9859 case GRANT_UPGRADE: { 9860 // Grant runtime permissions for a previously held install permission. 9861 PermissionState permissionState = origPermissions 9862 .getInstallPermissionState(bp.name); 9863 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9864 9865 if (origPermissions.revokeInstallPermission(bp) 9866 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9867 // We will be transferring the permission flags, so clear them. 9868 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9869 PackageManager.MASK_PERMISSION_FLAGS, 0); 9870 changedInstallPermission = true; 9871 } 9872 9873 // If the permission is not to be promoted to runtime we ignore it and 9874 // also its other flags as they are not applicable to install permissions. 9875 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9876 for (int userId : currentUserIds) { 9877 if (permissionsState.grantRuntimePermission(bp, userId) != 9878 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9879 // Transfer the permission flags. 9880 permissionsState.updatePermissionFlags(bp, userId, 9881 flags, flags); 9882 // If we granted the permission, we have to write. 9883 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9884 changedRuntimePermissionUserIds, userId); 9885 } 9886 } 9887 } 9888 } break; 9889 9890 default: { 9891 if (packageOfInterest == null 9892 || packageOfInterest.equals(pkg.packageName)) { 9893 Slog.w(TAG, "Not granting permission " + perm 9894 + " to package " + pkg.packageName 9895 + " because it was previously installed without"); 9896 } 9897 } break; 9898 } 9899 } else { 9900 if (permissionsState.revokeInstallPermission(bp) != 9901 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9902 // Also drop the permission flags. 9903 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9904 PackageManager.MASK_PERMISSION_FLAGS, 0); 9905 changedInstallPermission = true; 9906 Slog.i(TAG, "Un-granting permission " + perm 9907 + " from package " + pkg.packageName 9908 + " (protectionLevel=" + bp.protectionLevel 9909 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9910 + ")"); 9911 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9912 // Don't print warning for app op permissions, since it is fine for them 9913 // not to be granted, there is a UI for the user to decide. 9914 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9915 Slog.w(TAG, "Not granting permission " + perm 9916 + " to package " + pkg.packageName 9917 + " (protectionLevel=" + bp.protectionLevel 9918 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9919 + ")"); 9920 } 9921 } 9922 } 9923 } 9924 9925 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9926 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9927 // This is the first that we have heard about this package, so the 9928 // permissions we have now selected are fixed until explicitly 9929 // changed. 9930 ps.installPermissionsFixed = true; 9931 } 9932 9933 // Persist the runtime permissions state for users with changes. If permissions 9934 // were revoked because no app in the shared user declares them we have to 9935 // write synchronously to avoid losing runtime permissions state. 9936 for (int userId : changedRuntimePermissionUserIds) { 9937 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9938 } 9939 9940 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9941 } 9942 9943 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9944 boolean allowed = false; 9945 final int NP = PackageParser.NEW_PERMISSIONS.length; 9946 for (int ip=0; ip<NP; ip++) { 9947 final PackageParser.NewPermissionInfo npi 9948 = PackageParser.NEW_PERMISSIONS[ip]; 9949 if (npi.name.equals(perm) 9950 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9951 allowed = true; 9952 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9953 + pkg.packageName); 9954 break; 9955 } 9956 } 9957 return allowed; 9958 } 9959 9960 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9961 BasePermission bp, PermissionsState origPermissions) { 9962 boolean allowed; 9963 allowed = (compareSignatures( 9964 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9965 == PackageManager.SIGNATURE_MATCH) 9966 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9967 == PackageManager.SIGNATURE_MATCH); 9968 if (!allowed && (bp.protectionLevel 9969 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9970 if (isSystemApp(pkg)) { 9971 // For updated system applications, a system permission 9972 // is granted only if it had been defined by the original application. 9973 if (pkg.isUpdatedSystemApp()) { 9974 final PackageSetting sysPs = mSettings 9975 .getDisabledSystemPkgLPr(pkg.packageName); 9976 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9977 // If the original was granted this permission, we take 9978 // that grant decision as read and propagate it to the 9979 // update. 9980 if (sysPs.isPrivileged()) { 9981 allowed = true; 9982 } 9983 } else { 9984 // The system apk may have been updated with an older 9985 // version of the one on the data partition, but which 9986 // granted a new system permission that it didn't have 9987 // before. In this case we do want to allow the app to 9988 // now get the new permission if the ancestral apk is 9989 // privileged to get it. 9990 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9991 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9992 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9993 allowed = true; 9994 break; 9995 } 9996 } 9997 } 9998 // Also if a privileged parent package on the system image or any of 9999 // its children requested a privileged permission, the updated child 10000 // packages can also get the permission. 10001 if (pkg.parentPackage != null) { 10002 final PackageSetting disabledSysParentPs = mSettings 10003 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10004 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10005 && disabledSysParentPs.isPrivileged()) { 10006 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10007 allowed = true; 10008 } else if (disabledSysParentPs.pkg.childPackages != null) { 10009 final int count = disabledSysParentPs.pkg.childPackages.size(); 10010 for (int i = 0; i < count; i++) { 10011 PackageParser.Package disabledSysChildPkg = 10012 disabledSysParentPs.pkg.childPackages.get(i); 10013 if (isPackageRequestingPermission(disabledSysChildPkg, 10014 perm)) { 10015 allowed = true; 10016 break; 10017 } 10018 } 10019 } 10020 } 10021 } 10022 } 10023 } else { 10024 allowed = isPrivilegedApp(pkg); 10025 } 10026 } 10027 } 10028 if (!allowed) { 10029 if (!allowed && (bp.protectionLevel 10030 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10031 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10032 // If this was a previously normal/dangerous permission that got moved 10033 // to a system permission as part of the runtime permission redesign, then 10034 // we still want to blindly grant it to old apps. 10035 allowed = true; 10036 } 10037 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10038 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10039 // If this permission is to be granted to the system installer and 10040 // this app is an installer, then it gets the permission. 10041 allowed = true; 10042 } 10043 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10044 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10045 // If this permission is to be granted to the system verifier and 10046 // this app is a verifier, then it gets the permission. 10047 allowed = true; 10048 } 10049 if (!allowed && (bp.protectionLevel 10050 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10051 && isSystemApp(pkg)) { 10052 // Any pre-installed system app is allowed to get this permission. 10053 allowed = true; 10054 } 10055 if (!allowed && (bp.protectionLevel 10056 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10057 // For development permissions, a development permission 10058 // is granted only if it was already granted. 10059 allowed = origPermissions.hasInstallPermission(perm); 10060 } 10061 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10062 && pkg.packageName.equals(mSetupWizardPackage)) { 10063 // If this permission is to be granted to the system setup wizard and 10064 // this app is a setup wizard, then it gets the permission. 10065 allowed = true; 10066 } 10067 } 10068 return allowed; 10069 } 10070 10071 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10072 final int permCount = pkg.requestedPermissions.size(); 10073 for (int j = 0; j < permCount; j++) { 10074 String requestedPermission = pkg.requestedPermissions.get(j); 10075 if (permission.equals(requestedPermission)) { 10076 return true; 10077 } 10078 } 10079 return false; 10080 } 10081 10082 final class ActivityIntentResolver 10083 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10084 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10085 boolean defaultOnly, int userId) { 10086 if (!sUserManager.exists(userId)) return null; 10087 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10088 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10089 } 10090 10091 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10092 int userId) { 10093 if (!sUserManager.exists(userId)) return null; 10094 mFlags = flags; 10095 return super.queryIntent(intent, resolvedType, 10096 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10097 } 10098 10099 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10100 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10101 if (!sUserManager.exists(userId)) return null; 10102 if (packageActivities == null) { 10103 return null; 10104 } 10105 mFlags = flags; 10106 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10107 final int N = packageActivities.size(); 10108 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10109 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10110 10111 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10112 for (int i = 0; i < N; ++i) { 10113 intentFilters = packageActivities.get(i).intents; 10114 if (intentFilters != null && intentFilters.size() > 0) { 10115 PackageParser.ActivityIntentInfo[] array = 10116 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10117 intentFilters.toArray(array); 10118 listCut.add(array); 10119 } 10120 } 10121 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10122 } 10123 10124 /** 10125 * Finds a privileged activity that matches the specified activity names. 10126 */ 10127 private PackageParser.Activity findMatchingActivity( 10128 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10129 for (PackageParser.Activity sysActivity : activityList) { 10130 if (sysActivity.info.name.equals(activityInfo.name)) { 10131 return sysActivity; 10132 } 10133 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10134 return sysActivity; 10135 } 10136 if (sysActivity.info.targetActivity != null) { 10137 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10138 return sysActivity; 10139 } 10140 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10141 return sysActivity; 10142 } 10143 } 10144 } 10145 return null; 10146 } 10147 10148 public class IterGenerator<E> { 10149 public Iterator<E> generate(ActivityIntentInfo info) { 10150 return null; 10151 } 10152 } 10153 10154 public class ActionIterGenerator extends IterGenerator<String> { 10155 @Override 10156 public Iterator<String> generate(ActivityIntentInfo info) { 10157 return info.actionsIterator(); 10158 } 10159 } 10160 10161 public class CategoriesIterGenerator extends IterGenerator<String> { 10162 @Override 10163 public Iterator<String> generate(ActivityIntentInfo info) { 10164 return info.categoriesIterator(); 10165 } 10166 } 10167 10168 public class SchemesIterGenerator extends IterGenerator<String> { 10169 @Override 10170 public Iterator<String> generate(ActivityIntentInfo info) { 10171 return info.schemesIterator(); 10172 } 10173 } 10174 10175 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10176 @Override 10177 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10178 return info.authoritiesIterator(); 10179 } 10180 } 10181 10182 /** 10183 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10184 * MODIFIED. Do not pass in a list that should not be changed. 10185 */ 10186 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10187 IterGenerator<T> generator, Iterator<T> searchIterator) { 10188 // loop through the set of actions; every one must be found in the intent filter 10189 while (searchIterator.hasNext()) { 10190 // we must have at least one filter in the list to consider a match 10191 if (intentList.size() == 0) { 10192 break; 10193 } 10194 10195 final T searchAction = searchIterator.next(); 10196 10197 // loop through the set of intent filters 10198 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10199 while (intentIter.hasNext()) { 10200 final ActivityIntentInfo intentInfo = intentIter.next(); 10201 boolean selectionFound = false; 10202 10203 // loop through the intent filter's selection criteria; at least one 10204 // of them must match the searched criteria 10205 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10206 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10207 final T intentSelection = intentSelectionIter.next(); 10208 if (intentSelection != null && intentSelection.equals(searchAction)) { 10209 selectionFound = true; 10210 break; 10211 } 10212 } 10213 10214 // the selection criteria wasn't found in this filter's set; this filter 10215 // is not a potential match 10216 if (!selectionFound) { 10217 intentIter.remove(); 10218 } 10219 } 10220 } 10221 } 10222 10223 private boolean isProtectedAction(ActivityIntentInfo filter) { 10224 final Iterator<String> actionsIter = filter.actionsIterator(); 10225 while (actionsIter != null && actionsIter.hasNext()) { 10226 final String filterAction = actionsIter.next(); 10227 if (PROTECTED_ACTIONS.contains(filterAction)) { 10228 return true; 10229 } 10230 } 10231 return false; 10232 } 10233 10234 /** 10235 * Adjusts the priority of the given intent filter according to policy. 10236 * <p> 10237 * <ul> 10238 * <li>The priority for non privileged applications is capped to '0'</li> 10239 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10240 * <li>The priority for unbundled updates to privileged applications is capped to the 10241 * priority defined on the system partition</li> 10242 * </ul> 10243 * <p> 10244 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10245 * allowed to obtain any priority on any action. 10246 */ 10247 private void adjustPriority( 10248 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10249 // nothing to do; priority is fine as-is 10250 if (intent.getPriority() <= 0) { 10251 return; 10252 } 10253 10254 final ActivityInfo activityInfo = intent.activity.info; 10255 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10256 10257 final boolean privilegedApp = 10258 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10259 if (!privilegedApp) { 10260 // non-privileged applications can never define a priority >0 10261 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10262 + " package: " + applicationInfo.packageName 10263 + " activity: " + intent.activity.className 10264 + " origPrio: " + intent.getPriority()); 10265 intent.setPriority(0); 10266 return; 10267 } 10268 10269 if (systemActivities == null) { 10270 // the system package is not disabled; we're parsing the system partition 10271 if (isProtectedAction(intent)) { 10272 if (mDeferProtectedFilters) { 10273 // We can't deal with these just yet. No component should ever obtain a 10274 // >0 priority for a protected actions, with ONE exception -- the setup 10275 // wizard. The setup wizard, however, cannot be known until we're able to 10276 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10277 // until all intent filters have been processed. Chicken, meet egg. 10278 // Let the filter temporarily have a high priority and rectify the 10279 // priorities after all system packages have been scanned. 10280 mProtectedFilters.add(intent); 10281 if (DEBUG_FILTERS) { 10282 Slog.i(TAG, "Protected action; save for later;" 10283 + " package: " + applicationInfo.packageName 10284 + " activity: " + intent.activity.className 10285 + " origPrio: " + intent.getPriority()); 10286 } 10287 return; 10288 } else { 10289 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10290 Slog.i(TAG, "No setup wizard;" 10291 + " All protected intents capped to priority 0"); 10292 } 10293 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10294 if (DEBUG_FILTERS) { 10295 Slog.i(TAG, "Found setup wizard;" 10296 + " allow priority " + intent.getPriority() + ";" 10297 + " package: " + intent.activity.info.packageName 10298 + " activity: " + intent.activity.className 10299 + " priority: " + intent.getPriority()); 10300 } 10301 // setup wizard gets whatever it wants 10302 return; 10303 } 10304 Slog.w(TAG, "Protected action; cap priority to 0;" 10305 + " package: " + intent.activity.info.packageName 10306 + " activity: " + intent.activity.className 10307 + " origPrio: " + intent.getPriority()); 10308 intent.setPriority(0); 10309 return; 10310 } 10311 } 10312 // privileged apps on the system image get whatever priority they request 10313 return; 10314 } 10315 10316 // privileged app unbundled update ... try to find the same activity 10317 final PackageParser.Activity foundActivity = 10318 findMatchingActivity(systemActivities, activityInfo); 10319 if (foundActivity == null) { 10320 // this is a new activity; it cannot obtain >0 priority 10321 if (DEBUG_FILTERS) { 10322 Slog.i(TAG, "New activity; cap priority to 0;" 10323 + " package: " + applicationInfo.packageName 10324 + " activity: " + intent.activity.className 10325 + " origPrio: " + intent.getPriority()); 10326 } 10327 intent.setPriority(0); 10328 return; 10329 } 10330 10331 // found activity, now check for filter equivalence 10332 10333 // a shallow copy is enough; we modify the list, not its contents 10334 final List<ActivityIntentInfo> intentListCopy = 10335 new ArrayList<>(foundActivity.intents); 10336 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10337 10338 // find matching action subsets 10339 final Iterator<String> actionsIterator = intent.actionsIterator(); 10340 if (actionsIterator != null) { 10341 getIntentListSubset( 10342 intentListCopy, new ActionIterGenerator(), actionsIterator); 10343 if (intentListCopy.size() == 0) { 10344 // no more intents to match; we're not equivalent 10345 if (DEBUG_FILTERS) { 10346 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10347 + " package: " + applicationInfo.packageName 10348 + " activity: " + intent.activity.className 10349 + " origPrio: " + intent.getPriority()); 10350 } 10351 intent.setPriority(0); 10352 return; 10353 } 10354 } 10355 10356 // find matching category subsets 10357 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10358 if (categoriesIterator != null) { 10359 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10360 categoriesIterator); 10361 if (intentListCopy.size() == 0) { 10362 // no more intents to match; we're not equivalent 10363 if (DEBUG_FILTERS) { 10364 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10365 + " package: " + applicationInfo.packageName 10366 + " activity: " + intent.activity.className 10367 + " origPrio: " + intent.getPriority()); 10368 } 10369 intent.setPriority(0); 10370 return; 10371 } 10372 } 10373 10374 // find matching schemes subsets 10375 final Iterator<String> schemesIterator = intent.schemesIterator(); 10376 if (schemesIterator != null) { 10377 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10378 schemesIterator); 10379 if (intentListCopy.size() == 0) { 10380 // no more intents to match; we're not equivalent 10381 if (DEBUG_FILTERS) { 10382 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10383 + " package: " + applicationInfo.packageName 10384 + " activity: " + intent.activity.className 10385 + " origPrio: " + intent.getPriority()); 10386 } 10387 intent.setPriority(0); 10388 return; 10389 } 10390 } 10391 10392 // find matching authorities subsets 10393 final Iterator<IntentFilter.AuthorityEntry> 10394 authoritiesIterator = intent.authoritiesIterator(); 10395 if (authoritiesIterator != null) { 10396 getIntentListSubset(intentListCopy, 10397 new AuthoritiesIterGenerator(), 10398 authoritiesIterator); 10399 if (intentListCopy.size() == 0) { 10400 // no more intents to match; we're not equivalent 10401 if (DEBUG_FILTERS) { 10402 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10403 + " package: " + applicationInfo.packageName 10404 + " activity: " + intent.activity.className 10405 + " origPrio: " + intent.getPriority()); 10406 } 10407 intent.setPriority(0); 10408 return; 10409 } 10410 } 10411 10412 // we found matching filter(s); app gets the max priority of all intents 10413 int cappedPriority = 0; 10414 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10415 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10416 } 10417 if (intent.getPriority() > cappedPriority) { 10418 if (DEBUG_FILTERS) { 10419 Slog.i(TAG, "Found matching filter(s);" 10420 + " cap priority to " + cappedPriority + ";" 10421 + " package: " + applicationInfo.packageName 10422 + " activity: " + intent.activity.className 10423 + " origPrio: " + intent.getPriority()); 10424 } 10425 intent.setPriority(cappedPriority); 10426 return; 10427 } 10428 // all this for nothing; the requested priority was <= what was on the system 10429 } 10430 10431 public final void addActivity(PackageParser.Activity a, String type) { 10432 mActivities.put(a.getComponentName(), a); 10433 if (DEBUG_SHOW_INFO) 10434 Log.v( 10435 TAG, " " + type + " " + 10436 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10437 if (DEBUG_SHOW_INFO) 10438 Log.v(TAG, " Class=" + a.info.name); 10439 final int NI = a.intents.size(); 10440 for (int j=0; j<NI; j++) { 10441 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10442 if ("activity".equals(type)) { 10443 final PackageSetting ps = 10444 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10445 final List<PackageParser.Activity> systemActivities = 10446 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10447 adjustPriority(systemActivities, intent); 10448 } 10449 if (DEBUG_SHOW_INFO) { 10450 Log.v(TAG, " IntentFilter:"); 10451 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10452 } 10453 if (!intent.debugCheck()) { 10454 Log.w(TAG, "==> For Activity " + a.info.name); 10455 } 10456 addFilter(intent); 10457 } 10458 } 10459 10460 public final void removeActivity(PackageParser.Activity a, String type) { 10461 mActivities.remove(a.getComponentName()); 10462 if (DEBUG_SHOW_INFO) { 10463 Log.v(TAG, " " + type + " " 10464 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10465 : a.info.name) + ":"); 10466 Log.v(TAG, " Class=" + a.info.name); 10467 } 10468 final int NI = a.intents.size(); 10469 for (int j=0; j<NI; j++) { 10470 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10471 if (DEBUG_SHOW_INFO) { 10472 Log.v(TAG, " IntentFilter:"); 10473 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10474 } 10475 removeFilter(intent); 10476 } 10477 } 10478 10479 @Override 10480 protected boolean allowFilterResult( 10481 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10482 ActivityInfo filterAi = filter.activity.info; 10483 for (int i=dest.size()-1; i>=0; i--) { 10484 ActivityInfo destAi = dest.get(i).activityInfo; 10485 if (destAi.name == filterAi.name 10486 && destAi.packageName == filterAi.packageName) { 10487 return false; 10488 } 10489 } 10490 return true; 10491 } 10492 10493 @Override 10494 protected ActivityIntentInfo[] newArray(int size) { 10495 return new ActivityIntentInfo[size]; 10496 } 10497 10498 @Override 10499 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10500 if (!sUserManager.exists(userId)) return true; 10501 PackageParser.Package p = filter.activity.owner; 10502 if (p != null) { 10503 PackageSetting ps = (PackageSetting)p.mExtras; 10504 if (ps != null) { 10505 // System apps are never considered stopped for purposes of 10506 // filtering, because there may be no way for the user to 10507 // actually re-launch them. 10508 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10509 && ps.getStopped(userId); 10510 } 10511 } 10512 return false; 10513 } 10514 10515 @Override 10516 protected boolean isPackageForFilter(String packageName, 10517 PackageParser.ActivityIntentInfo info) { 10518 return packageName.equals(info.activity.owner.packageName); 10519 } 10520 10521 @Override 10522 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10523 int match, int userId) { 10524 if (!sUserManager.exists(userId)) return null; 10525 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10526 return null; 10527 } 10528 final PackageParser.Activity activity = info.activity; 10529 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10530 if (ps == null) { 10531 return null; 10532 } 10533 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10534 ps.readUserState(userId), userId); 10535 if (ai == null) { 10536 return null; 10537 } 10538 final ResolveInfo res = new ResolveInfo(); 10539 res.activityInfo = ai; 10540 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10541 res.filter = info; 10542 } 10543 if (info != null) { 10544 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10545 } 10546 res.priority = info.getPriority(); 10547 res.preferredOrder = activity.owner.mPreferredOrder; 10548 //System.out.println("Result: " + res.activityInfo.className + 10549 // " = " + res.priority); 10550 res.match = match; 10551 res.isDefault = info.hasDefault; 10552 res.labelRes = info.labelRes; 10553 res.nonLocalizedLabel = info.nonLocalizedLabel; 10554 if (userNeedsBadging(userId)) { 10555 res.noResourceId = true; 10556 } else { 10557 res.icon = info.icon; 10558 } 10559 res.iconResourceId = info.icon; 10560 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10561 return res; 10562 } 10563 10564 @Override 10565 protected void sortResults(List<ResolveInfo> results) { 10566 Collections.sort(results, mResolvePrioritySorter); 10567 } 10568 10569 @Override 10570 protected void dumpFilter(PrintWriter out, String prefix, 10571 PackageParser.ActivityIntentInfo filter) { 10572 out.print(prefix); out.print( 10573 Integer.toHexString(System.identityHashCode(filter.activity))); 10574 out.print(' '); 10575 filter.activity.printComponentShortName(out); 10576 out.print(" filter "); 10577 out.println(Integer.toHexString(System.identityHashCode(filter))); 10578 } 10579 10580 @Override 10581 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10582 return filter.activity; 10583 } 10584 10585 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10586 PackageParser.Activity activity = (PackageParser.Activity)label; 10587 out.print(prefix); out.print( 10588 Integer.toHexString(System.identityHashCode(activity))); 10589 out.print(' '); 10590 activity.printComponentShortName(out); 10591 if (count > 1) { 10592 out.print(" ("); out.print(count); out.print(" filters)"); 10593 } 10594 out.println(); 10595 } 10596 10597 // Keys are String (activity class name), values are Activity. 10598 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10599 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10600 private int mFlags; 10601 } 10602 10603 private final class ServiceIntentResolver 10604 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10605 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10606 boolean defaultOnly, int userId) { 10607 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10608 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10609 } 10610 10611 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10612 int userId) { 10613 if (!sUserManager.exists(userId)) return null; 10614 mFlags = flags; 10615 return super.queryIntent(intent, resolvedType, 10616 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10617 } 10618 10619 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10620 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10621 if (!sUserManager.exists(userId)) return null; 10622 if (packageServices == null) { 10623 return null; 10624 } 10625 mFlags = flags; 10626 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10627 final int N = packageServices.size(); 10628 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10629 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10630 10631 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10632 for (int i = 0; i < N; ++i) { 10633 intentFilters = packageServices.get(i).intents; 10634 if (intentFilters != null && intentFilters.size() > 0) { 10635 PackageParser.ServiceIntentInfo[] array = 10636 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10637 intentFilters.toArray(array); 10638 listCut.add(array); 10639 } 10640 } 10641 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10642 } 10643 10644 public final void addService(PackageParser.Service s) { 10645 mServices.put(s.getComponentName(), s); 10646 if (DEBUG_SHOW_INFO) { 10647 Log.v(TAG, " " 10648 + (s.info.nonLocalizedLabel != null 10649 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10650 Log.v(TAG, " Class=" + s.info.name); 10651 } 10652 final int NI = s.intents.size(); 10653 int j; 10654 for (j=0; j<NI; j++) { 10655 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10656 if (DEBUG_SHOW_INFO) { 10657 Log.v(TAG, " IntentFilter:"); 10658 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10659 } 10660 if (!intent.debugCheck()) { 10661 Log.w(TAG, "==> For Service " + s.info.name); 10662 } 10663 addFilter(intent); 10664 } 10665 } 10666 10667 public final void removeService(PackageParser.Service s) { 10668 mServices.remove(s.getComponentName()); 10669 if (DEBUG_SHOW_INFO) { 10670 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10671 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10672 Log.v(TAG, " Class=" + s.info.name); 10673 } 10674 final int NI = s.intents.size(); 10675 int j; 10676 for (j=0; j<NI; j++) { 10677 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10678 if (DEBUG_SHOW_INFO) { 10679 Log.v(TAG, " IntentFilter:"); 10680 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10681 } 10682 removeFilter(intent); 10683 } 10684 } 10685 10686 @Override 10687 protected boolean allowFilterResult( 10688 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10689 ServiceInfo filterSi = filter.service.info; 10690 for (int i=dest.size()-1; i>=0; i--) { 10691 ServiceInfo destAi = dest.get(i).serviceInfo; 10692 if (destAi.name == filterSi.name 10693 && destAi.packageName == filterSi.packageName) { 10694 return false; 10695 } 10696 } 10697 return true; 10698 } 10699 10700 @Override 10701 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10702 return new PackageParser.ServiceIntentInfo[size]; 10703 } 10704 10705 @Override 10706 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10707 if (!sUserManager.exists(userId)) return true; 10708 PackageParser.Package p = filter.service.owner; 10709 if (p != null) { 10710 PackageSetting ps = (PackageSetting)p.mExtras; 10711 if (ps != null) { 10712 // System apps are never considered stopped for purposes of 10713 // filtering, because there may be no way for the user to 10714 // actually re-launch them. 10715 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10716 && ps.getStopped(userId); 10717 } 10718 } 10719 return false; 10720 } 10721 10722 @Override 10723 protected boolean isPackageForFilter(String packageName, 10724 PackageParser.ServiceIntentInfo info) { 10725 return packageName.equals(info.service.owner.packageName); 10726 } 10727 10728 @Override 10729 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10730 int match, int userId) { 10731 if (!sUserManager.exists(userId)) return null; 10732 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10733 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10734 return null; 10735 } 10736 final PackageParser.Service service = info.service; 10737 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10738 if (ps == null) { 10739 return null; 10740 } 10741 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10742 ps.readUserState(userId), userId); 10743 if (si == null) { 10744 return null; 10745 } 10746 final ResolveInfo res = new ResolveInfo(); 10747 res.serviceInfo = si; 10748 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10749 res.filter = filter; 10750 } 10751 res.priority = info.getPriority(); 10752 res.preferredOrder = service.owner.mPreferredOrder; 10753 res.match = match; 10754 res.isDefault = info.hasDefault; 10755 res.labelRes = info.labelRes; 10756 res.nonLocalizedLabel = info.nonLocalizedLabel; 10757 res.icon = info.icon; 10758 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10759 return res; 10760 } 10761 10762 @Override 10763 protected void sortResults(List<ResolveInfo> results) { 10764 Collections.sort(results, mResolvePrioritySorter); 10765 } 10766 10767 @Override 10768 protected void dumpFilter(PrintWriter out, String prefix, 10769 PackageParser.ServiceIntentInfo filter) { 10770 out.print(prefix); out.print( 10771 Integer.toHexString(System.identityHashCode(filter.service))); 10772 out.print(' '); 10773 filter.service.printComponentShortName(out); 10774 out.print(" filter "); 10775 out.println(Integer.toHexString(System.identityHashCode(filter))); 10776 } 10777 10778 @Override 10779 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10780 return filter.service; 10781 } 10782 10783 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10784 PackageParser.Service service = (PackageParser.Service)label; 10785 out.print(prefix); out.print( 10786 Integer.toHexString(System.identityHashCode(service))); 10787 out.print(' '); 10788 service.printComponentShortName(out); 10789 if (count > 1) { 10790 out.print(" ("); out.print(count); out.print(" filters)"); 10791 } 10792 out.println(); 10793 } 10794 10795// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10796// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10797// final List<ResolveInfo> retList = Lists.newArrayList(); 10798// while (i.hasNext()) { 10799// final ResolveInfo resolveInfo = (ResolveInfo) i; 10800// if (isEnabledLP(resolveInfo.serviceInfo)) { 10801// retList.add(resolveInfo); 10802// } 10803// } 10804// return retList; 10805// } 10806 10807 // Keys are String (activity class name), values are Activity. 10808 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10809 = new ArrayMap<ComponentName, PackageParser.Service>(); 10810 private int mFlags; 10811 }; 10812 10813 private final class ProviderIntentResolver 10814 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10815 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10816 boolean defaultOnly, int userId) { 10817 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10818 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10819 } 10820 10821 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10822 int userId) { 10823 if (!sUserManager.exists(userId)) 10824 return null; 10825 mFlags = flags; 10826 return super.queryIntent(intent, resolvedType, 10827 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10828 } 10829 10830 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10831 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10832 if (!sUserManager.exists(userId)) 10833 return null; 10834 if (packageProviders == null) { 10835 return null; 10836 } 10837 mFlags = flags; 10838 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10839 final int N = packageProviders.size(); 10840 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10841 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10842 10843 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10844 for (int i = 0; i < N; ++i) { 10845 intentFilters = packageProviders.get(i).intents; 10846 if (intentFilters != null && intentFilters.size() > 0) { 10847 PackageParser.ProviderIntentInfo[] array = 10848 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10849 intentFilters.toArray(array); 10850 listCut.add(array); 10851 } 10852 } 10853 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10854 } 10855 10856 public final void addProvider(PackageParser.Provider p) { 10857 if (mProviders.containsKey(p.getComponentName())) { 10858 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10859 return; 10860 } 10861 10862 mProviders.put(p.getComponentName(), p); 10863 if (DEBUG_SHOW_INFO) { 10864 Log.v(TAG, " " 10865 + (p.info.nonLocalizedLabel != null 10866 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10867 Log.v(TAG, " Class=" + p.info.name); 10868 } 10869 final int NI = p.intents.size(); 10870 int j; 10871 for (j = 0; j < NI; j++) { 10872 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10873 if (DEBUG_SHOW_INFO) { 10874 Log.v(TAG, " IntentFilter:"); 10875 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10876 } 10877 if (!intent.debugCheck()) { 10878 Log.w(TAG, "==> For Provider " + p.info.name); 10879 } 10880 addFilter(intent); 10881 } 10882 } 10883 10884 public final void removeProvider(PackageParser.Provider p) { 10885 mProviders.remove(p.getComponentName()); 10886 if (DEBUG_SHOW_INFO) { 10887 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10888 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10889 Log.v(TAG, " Class=" + p.info.name); 10890 } 10891 final int NI = p.intents.size(); 10892 int j; 10893 for (j = 0; j < NI; j++) { 10894 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10895 if (DEBUG_SHOW_INFO) { 10896 Log.v(TAG, " IntentFilter:"); 10897 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10898 } 10899 removeFilter(intent); 10900 } 10901 } 10902 10903 @Override 10904 protected boolean allowFilterResult( 10905 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10906 ProviderInfo filterPi = filter.provider.info; 10907 for (int i = dest.size() - 1; i >= 0; i--) { 10908 ProviderInfo destPi = dest.get(i).providerInfo; 10909 if (destPi.name == filterPi.name 10910 && destPi.packageName == filterPi.packageName) { 10911 return false; 10912 } 10913 } 10914 return true; 10915 } 10916 10917 @Override 10918 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10919 return new PackageParser.ProviderIntentInfo[size]; 10920 } 10921 10922 @Override 10923 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10924 if (!sUserManager.exists(userId)) 10925 return true; 10926 PackageParser.Package p = filter.provider.owner; 10927 if (p != null) { 10928 PackageSetting ps = (PackageSetting) p.mExtras; 10929 if (ps != null) { 10930 // System apps are never considered stopped for purposes of 10931 // filtering, because there may be no way for the user to 10932 // actually re-launch them. 10933 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10934 && ps.getStopped(userId); 10935 } 10936 } 10937 return false; 10938 } 10939 10940 @Override 10941 protected boolean isPackageForFilter(String packageName, 10942 PackageParser.ProviderIntentInfo info) { 10943 return packageName.equals(info.provider.owner.packageName); 10944 } 10945 10946 @Override 10947 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10948 int match, int userId) { 10949 if (!sUserManager.exists(userId)) 10950 return null; 10951 final PackageParser.ProviderIntentInfo info = filter; 10952 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10953 return null; 10954 } 10955 final PackageParser.Provider provider = info.provider; 10956 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10957 if (ps == null) { 10958 return null; 10959 } 10960 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10961 ps.readUserState(userId), userId); 10962 if (pi == null) { 10963 return null; 10964 } 10965 final ResolveInfo res = new ResolveInfo(); 10966 res.providerInfo = pi; 10967 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10968 res.filter = filter; 10969 } 10970 res.priority = info.getPriority(); 10971 res.preferredOrder = provider.owner.mPreferredOrder; 10972 res.match = match; 10973 res.isDefault = info.hasDefault; 10974 res.labelRes = info.labelRes; 10975 res.nonLocalizedLabel = info.nonLocalizedLabel; 10976 res.icon = info.icon; 10977 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10978 return res; 10979 } 10980 10981 @Override 10982 protected void sortResults(List<ResolveInfo> results) { 10983 Collections.sort(results, mResolvePrioritySorter); 10984 } 10985 10986 @Override 10987 protected void dumpFilter(PrintWriter out, String prefix, 10988 PackageParser.ProviderIntentInfo filter) { 10989 out.print(prefix); 10990 out.print( 10991 Integer.toHexString(System.identityHashCode(filter.provider))); 10992 out.print(' '); 10993 filter.provider.printComponentShortName(out); 10994 out.print(" filter "); 10995 out.println(Integer.toHexString(System.identityHashCode(filter))); 10996 } 10997 10998 @Override 10999 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11000 return filter.provider; 11001 } 11002 11003 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11004 PackageParser.Provider provider = (PackageParser.Provider)label; 11005 out.print(prefix); out.print( 11006 Integer.toHexString(System.identityHashCode(provider))); 11007 out.print(' '); 11008 provider.printComponentShortName(out); 11009 if (count > 1) { 11010 out.print(" ("); out.print(count); out.print(" filters)"); 11011 } 11012 out.println(); 11013 } 11014 11015 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11016 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11017 private int mFlags; 11018 } 11019 11020 private static final class EphemeralIntentResolver 11021 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11022 @Override 11023 protected EphemeralResolveIntentInfo[] newArray(int size) { 11024 return new EphemeralResolveIntentInfo[size]; 11025 } 11026 11027 @Override 11028 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11029 return true; 11030 } 11031 11032 @Override 11033 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11034 int userId) { 11035 if (!sUserManager.exists(userId)) { 11036 return null; 11037 } 11038 return info.getEphemeralResolveInfo(); 11039 } 11040 } 11041 11042 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11043 new Comparator<ResolveInfo>() { 11044 public int compare(ResolveInfo r1, ResolveInfo r2) { 11045 int v1 = r1.priority; 11046 int v2 = r2.priority; 11047 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11048 if (v1 != v2) { 11049 return (v1 > v2) ? -1 : 1; 11050 } 11051 v1 = r1.preferredOrder; 11052 v2 = r2.preferredOrder; 11053 if (v1 != v2) { 11054 return (v1 > v2) ? -1 : 1; 11055 } 11056 if (r1.isDefault != r2.isDefault) { 11057 return r1.isDefault ? -1 : 1; 11058 } 11059 v1 = r1.match; 11060 v2 = r2.match; 11061 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11062 if (v1 != v2) { 11063 return (v1 > v2) ? -1 : 1; 11064 } 11065 if (r1.system != r2.system) { 11066 return r1.system ? -1 : 1; 11067 } 11068 if (r1.activityInfo != null) { 11069 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11070 } 11071 if (r1.serviceInfo != null) { 11072 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11073 } 11074 if (r1.providerInfo != null) { 11075 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11076 } 11077 return 0; 11078 } 11079 }; 11080 11081 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11082 new Comparator<ProviderInfo>() { 11083 public int compare(ProviderInfo p1, ProviderInfo p2) { 11084 final int v1 = p1.initOrder; 11085 final int v2 = p2.initOrder; 11086 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11087 } 11088 }; 11089 11090 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11091 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11092 final int[] userIds) { 11093 mHandler.post(new Runnable() { 11094 @Override 11095 public void run() { 11096 try { 11097 final IActivityManager am = ActivityManagerNative.getDefault(); 11098 if (am == null) return; 11099 final int[] resolvedUserIds; 11100 if (userIds == null) { 11101 resolvedUserIds = am.getRunningUserIds(); 11102 } else { 11103 resolvedUserIds = userIds; 11104 } 11105 for (int id : resolvedUserIds) { 11106 final Intent intent = new Intent(action, 11107 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11108 if (extras != null) { 11109 intent.putExtras(extras); 11110 } 11111 if (targetPkg != null) { 11112 intent.setPackage(targetPkg); 11113 } 11114 // Modify the UID when posting to other users 11115 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11116 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11117 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11118 intent.putExtra(Intent.EXTRA_UID, uid); 11119 } 11120 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11121 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11122 if (DEBUG_BROADCASTS) { 11123 RuntimeException here = new RuntimeException("here"); 11124 here.fillInStackTrace(); 11125 Slog.d(TAG, "Sending to user " + id + ": " 11126 + intent.toShortString(false, true, false, false) 11127 + " " + intent.getExtras(), here); 11128 } 11129 am.broadcastIntent(null, intent, null, finishedReceiver, 11130 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11131 null, finishedReceiver != null, false, id); 11132 } 11133 } catch (RemoteException ex) { 11134 } 11135 } 11136 }); 11137 } 11138 11139 /** 11140 * Check if the external storage media is available. This is true if there 11141 * is a mounted external storage medium or if the external storage is 11142 * emulated. 11143 */ 11144 private boolean isExternalMediaAvailable() { 11145 return mMediaMounted || Environment.isExternalStorageEmulated(); 11146 } 11147 11148 @Override 11149 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11150 // writer 11151 synchronized (mPackages) { 11152 if (!isExternalMediaAvailable()) { 11153 // If the external storage is no longer mounted at this point, 11154 // the caller may not have been able to delete all of this 11155 // packages files and can not delete any more. Bail. 11156 return null; 11157 } 11158 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11159 if (lastPackage != null) { 11160 pkgs.remove(lastPackage); 11161 } 11162 if (pkgs.size() > 0) { 11163 return pkgs.get(0); 11164 } 11165 } 11166 return null; 11167 } 11168 11169 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11170 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11171 userId, andCode ? 1 : 0, packageName); 11172 if (mSystemReady) { 11173 msg.sendToTarget(); 11174 } else { 11175 if (mPostSystemReadyMessages == null) { 11176 mPostSystemReadyMessages = new ArrayList<>(); 11177 } 11178 mPostSystemReadyMessages.add(msg); 11179 } 11180 } 11181 11182 void startCleaningPackages() { 11183 // reader 11184 if (!isExternalMediaAvailable()) { 11185 return; 11186 } 11187 synchronized (mPackages) { 11188 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11189 return; 11190 } 11191 } 11192 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11193 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11194 IActivityManager am = ActivityManagerNative.getDefault(); 11195 if (am != null) { 11196 try { 11197 am.startService(null, intent, null, mContext.getOpPackageName(), 11198 UserHandle.USER_SYSTEM); 11199 } catch (RemoteException e) { 11200 } 11201 } 11202 } 11203 11204 @Override 11205 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11206 int installFlags, String installerPackageName, int userId) { 11207 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11208 11209 final int callingUid = Binder.getCallingUid(); 11210 enforceCrossUserPermission(callingUid, userId, 11211 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11212 11213 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11214 try { 11215 if (observer != null) { 11216 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11217 } 11218 } catch (RemoteException re) { 11219 } 11220 return; 11221 } 11222 11223 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11224 installFlags |= PackageManager.INSTALL_FROM_ADB; 11225 11226 } else { 11227 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11228 // about installerPackageName. 11229 11230 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11231 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11232 } 11233 11234 UserHandle user; 11235 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11236 user = UserHandle.ALL; 11237 } else { 11238 user = new UserHandle(userId); 11239 } 11240 11241 // Only system components can circumvent runtime permissions when installing. 11242 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11243 && mContext.checkCallingOrSelfPermission(Manifest.permission 11244 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11245 throw new SecurityException("You need the " 11246 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11247 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11248 } 11249 11250 final File originFile = new File(originPath); 11251 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11252 11253 final Message msg = mHandler.obtainMessage(INIT_COPY); 11254 final VerificationInfo verificationInfo = new VerificationInfo( 11255 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11256 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11257 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11258 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11259 null /*certificates*/); 11260 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11261 msg.obj = params; 11262 11263 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11264 System.identityHashCode(msg.obj)); 11265 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11266 System.identityHashCode(msg.obj)); 11267 11268 mHandler.sendMessage(msg); 11269 } 11270 11271 void installStage(String packageName, File stagedDir, String stagedCid, 11272 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11273 String installerPackageName, int installerUid, UserHandle user, 11274 Certificate[][] certificates) { 11275 if (DEBUG_EPHEMERAL) { 11276 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11277 Slog.d(TAG, "Ephemeral install of " + packageName); 11278 } 11279 } 11280 final VerificationInfo verificationInfo = new VerificationInfo( 11281 sessionParams.originatingUri, sessionParams.referrerUri, 11282 sessionParams.originatingUid, installerUid); 11283 11284 final OriginInfo origin; 11285 if (stagedDir != null) { 11286 origin = OriginInfo.fromStagedFile(stagedDir); 11287 } else { 11288 origin = OriginInfo.fromStagedContainer(stagedCid); 11289 } 11290 11291 final Message msg = mHandler.obtainMessage(INIT_COPY); 11292 final InstallParams params = new InstallParams(origin, null, observer, 11293 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11294 verificationInfo, user, sessionParams.abiOverride, 11295 sessionParams.grantedRuntimePermissions, certificates); 11296 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11297 msg.obj = params; 11298 11299 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11300 System.identityHashCode(msg.obj)); 11301 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11302 System.identityHashCode(msg.obj)); 11303 11304 mHandler.sendMessage(msg); 11305 } 11306 11307 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11308 int userId) { 11309 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11310 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11311 } 11312 11313 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11314 int appId, int userId) { 11315 Bundle extras = new Bundle(1); 11316 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11317 11318 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11319 packageName, extras, 0, null, null, new int[] {userId}); 11320 try { 11321 IActivityManager am = ActivityManagerNative.getDefault(); 11322 if (isSystem && am.isUserRunning(userId, 0)) { 11323 // The just-installed/enabled app is bundled on the system, so presumed 11324 // to be able to run automatically without needing an explicit launch. 11325 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11326 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11327 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11328 .setPackage(packageName); 11329 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11330 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11331 } 11332 } catch (RemoteException e) { 11333 // shouldn't happen 11334 Slog.w(TAG, "Unable to bootstrap installed package", e); 11335 } 11336 } 11337 11338 @Override 11339 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11340 int userId) { 11341 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11342 PackageSetting pkgSetting; 11343 final int uid = Binder.getCallingUid(); 11344 enforceCrossUserPermission(uid, userId, 11345 true /* requireFullPermission */, true /* checkShell */, 11346 "setApplicationHiddenSetting for user " + userId); 11347 11348 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11349 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11350 return false; 11351 } 11352 11353 long callingId = Binder.clearCallingIdentity(); 11354 try { 11355 boolean sendAdded = false; 11356 boolean sendRemoved = false; 11357 // writer 11358 synchronized (mPackages) { 11359 pkgSetting = mSettings.mPackages.get(packageName); 11360 if (pkgSetting == null) { 11361 return false; 11362 } 11363 if (pkgSetting.getHidden(userId) != hidden) { 11364 pkgSetting.setHidden(hidden, userId); 11365 mSettings.writePackageRestrictionsLPr(userId); 11366 if (hidden) { 11367 sendRemoved = true; 11368 } else { 11369 sendAdded = true; 11370 } 11371 } 11372 } 11373 if (sendAdded) { 11374 sendPackageAddedForUser(packageName, pkgSetting, userId); 11375 return true; 11376 } 11377 if (sendRemoved) { 11378 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11379 "hiding pkg"); 11380 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11381 return true; 11382 } 11383 } finally { 11384 Binder.restoreCallingIdentity(callingId); 11385 } 11386 return false; 11387 } 11388 11389 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11390 int userId) { 11391 final PackageRemovedInfo info = new PackageRemovedInfo(); 11392 info.removedPackage = packageName; 11393 info.removedUsers = new int[] {userId}; 11394 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11395 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11396 } 11397 11398 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11399 if (pkgList.length > 0) { 11400 Bundle extras = new Bundle(1); 11401 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11402 11403 sendPackageBroadcast( 11404 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11405 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11406 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11407 new int[] {userId}); 11408 } 11409 } 11410 11411 /** 11412 * Returns true if application is not found or there was an error. Otherwise it returns 11413 * the hidden state of the package for the given user. 11414 */ 11415 @Override 11416 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11417 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11418 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11419 true /* requireFullPermission */, false /* checkShell */, 11420 "getApplicationHidden for user " + userId); 11421 PackageSetting pkgSetting; 11422 long callingId = Binder.clearCallingIdentity(); 11423 try { 11424 // writer 11425 synchronized (mPackages) { 11426 pkgSetting = mSettings.mPackages.get(packageName); 11427 if (pkgSetting == null) { 11428 return true; 11429 } 11430 return pkgSetting.getHidden(userId); 11431 } 11432 } finally { 11433 Binder.restoreCallingIdentity(callingId); 11434 } 11435 } 11436 11437 /** 11438 * @hide 11439 */ 11440 @Override 11441 public int installExistingPackageAsUser(String packageName, int userId) { 11442 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11443 null); 11444 PackageSetting pkgSetting; 11445 final int uid = Binder.getCallingUid(); 11446 enforceCrossUserPermission(uid, userId, 11447 true /* requireFullPermission */, true /* checkShell */, 11448 "installExistingPackage for user " + userId); 11449 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11450 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11451 } 11452 11453 long callingId = Binder.clearCallingIdentity(); 11454 try { 11455 boolean installed = false; 11456 11457 // writer 11458 synchronized (mPackages) { 11459 pkgSetting = mSettings.mPackages.get(packageName); 11460 if (pkgSetting == null) { 11461 return PackageManager.INSTALL_FAILED_INVALID_URI; 11462 } 11463 if (!pkgSetting.getInstalled(userId)) { 11464 pkgSetting.setInstalled(true, userId); 11465 pkgSetting.setHidden(false, userId); 11466 mSettings.writePackageRestrictionsLPr(userId); 11467 installed = true; 11468 } 11469 } 11470 11471 if (installed) { 11472 if (pkgSetting.pkg != null) { 11473 synchronized (mInstallLock) { 11474 // We don't need to freeze for a brand new install 11475 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11476 } 11477 } 11478 sendPackageAddedForUser(packageName, pkgSetting, userId); 11479 } 11480 } finally { 11481 Binder.restoreCallingIdentity(callingId); 11482 } 11483 11484 return PackageManager.INSTALL_SUCCEEDED; 11485 } 11486 11487 boolean isUserRestricted(int userId, String restrictionKey) { 11488 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11489 if (restrictions.getBoolean(restrictionKey, false)) { 11490 Log.w(TAG, "User is restricted: " + restrictionKey); 11491 return true; 11492 } 11493 return false; 11494 } 11495 11496 @Override 11497 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11498 int userId) { 11499 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11500 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11501 true /* requireFullPermission */, true /* checkShell */, 11502 "setPackagesSuspended for user " + userId); 11503 11504 if (ArrayUtils.isEmpty(packageNames)) { 11505 return packageNames; 11506 } 11507 11508 // List of package names for whom the suspended state has changed. 11509 List<String> changedPackages = new ArrayList<>(packageNames.length); 11510 // List of package names for whom the suspended state is not set as requested in this 11511 // method. 11512 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11513 long callingId = Binder.clearCallingIdentity(); 11514 try { 11515 for (int i = 0; i < packageNames.length; i++) { 11516 String packageName = packageNames[i]; 11517 boolean changed = false; 11518 final int appId; 11519 synchronized (mPackages) { 11520 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11521 if (pkgSetting == null) { 11522 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11523 + "\". Skipping suspending/un-suspending."); 11524 unactionedPackages.add(packageName); 11525 continue; 11526 } 11527 appId = pkgSetting.appId; 11528 if (pkgSetting.getSuspended(userId) != suspended) { 11529 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11530 unactionedPackages.add(packageName); 11531 continue; 11532 } 11533 pkgSetting.setSuspended(suspended, userId); 11534 mSettings.writePackageRestrictionsLPr(userId); 11535 changed = true; 11536 changedPackages.add(packageName); 11537 } 11538 } 11539 11540 if (changed && suspended) { 11541 killApplication(packageName, UserHandle.getUid(userId, appId), 11542 "suspending package"); 11543 } 11544 } 11545 } finally { 11546 Binder.restoreCallingIdentity(callingId); 11547 } 11548 11549 if (!changedPackages.isEmpty()) { 11550 sendPackagesSuspendedForUser(changedPackages.toArray( 11551 new String[changedPackages.size()]), userId, suspended); 11552 } 11553 11554 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11555 } 11556 11557 @Override 11558 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11559 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11560 true /* requireFullPermission */, false /* checkShell */, 11561 "isPackageSuspendedForUser for user " + userId); 11562 synchronized (mPackages) { 11563 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11564 if (pkgSetting == null) { 11565 throw new IllegalArgumentException("Unknown target package: " + packageName); 11566 } 11567 return pkgSetting.getSuspended(userId); 11568 } 11569 } 11570 11571 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11572 if (isPackageDeviceAdmin(packageName, userId)) { 11573 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11574 + "\": has an active device admin"); 11575 return false; 11576 } 11577 11578 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11579 if (packageName.equals(activeLauncherPackageName)) { 11580 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11581 + "\": contains the active launcher"); 11582 return false; 11583 } 11584 11585 if (packageName.equals(mRequiredInstallerPackage)) { 11586 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11587 + "\": required for package installation"); 11588 return false; 11589 } 11590 11591 if (packageName.equals(mRequiredVerifierPackage)) { 11592 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11593 + "\": required for package verification"); 11594 return false; 11595 } 11596 11597 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11598 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11599 + "\": is the default dialer"); 11600 return false; 11601 } 11602 11603 return true; 11604 } 11605 11606 private String getActiveLauncherPackageName(int userId) { 11607 Intent intent = new Intent(Intent.ACTION_MAIN); 11608 intent.addCategory(Intent.CATEGORY_HOME); 11609 ResolveInfo resolveInfo = resolveIntent( 11610 intent, 11611 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11612 PackageManager.MATCH_DEFAULT_ONLY, 11613 userId); 11614 11615 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11616 } 11617 11618 private String getDefaultDialerPackageName(int userId) { 11619 synchronized (mPackages) { 11620 return mSettings.getDefaultDialerPackageNameLPw(userId); 11621 } 11622 } 11623 11624 @Override 11625 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11626 mContext.enforceCallingOrSelfPermission( 11627 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11628 "Only package verification agents can verify applications"); 11629 11630 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11631 final PackageVerificationResponse response = new PackageVerificationResponse( 11632 verificationCode, Binder.getCallingUid()); 11633 msg.arg1 = id; 11634 msg.obj = response; 11635 mHandler.sendMessage(msg); 11636 } 11637 11638 @Override 11639 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11640 long millisecondsToDelay) { 11641 mContext.enforceCallingOrSelfPermission( 11642 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11643 "Only package verification agents can extend verification timeouts"); 11644 11645 final PackageVerificationState state = mPendingVerification.get(id); 11646 final PackageVerificationResponse response = new PackageVerificationResponse( 11647 verificationCodeAtTimeout, Binder.getCallingUid()); 11648 11649 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11650 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11651 } 11652 if (millisecondsToDelay < 0) { 11653 millisecondsToDelay = 0; 11654 } 11655 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11656 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11657 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11658 } 11659 11660 if ((state != null) && !state.timeoutExtended()) { 11661 state.extendTimeout(); 11662 11663 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11664 msg.arg1 = id; 11665 msg.obj = response; 11666 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11667 } 11668 } 11669 11670 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11671 int verificationCode, UserHandle user) { 11672 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11673 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11674 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11675 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11676 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11677 11678 mContext.sendBroadcastAsUser(intent, user, 11679 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11680 } 11681 11682 private ComponentName matchComponentForVerifier(String packageName, 11683 List<ResolveInfo> receivers) { 11684 ActivityInfo targetReceiver = null; 11685 11686 final int NR = receivers.size(); 11687 for (int i = 0; i < NR; i++) { 11688 final ResolveInfo info = receivers.get(i); 11689 if (info.activityInfo == null) { 11690 continue; 11691 } 11692 11693 if (packageName.equals(info.activityInfo.packageName)) { 11694 targetReceiver = info.activityInfo; 11695 break; 11696 } 11697 } 11698 11699 if (targetReceiver == null) { 11700 return null; 11701 } 11702 11703 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11704 } 11705 11706 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11707 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11708 if (pkgInfo.verifiers.length == 0) { 11709 return null; 11710 } 11711 11712 final int N = pkgInfo.verifiers.length; 11713 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11714 for (int i = 0; i < N; i++) { 11715 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11716 11717 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11718 receivers); 11719 if (comp == null) { 11720 continue; 11721 } 11722 11723 final int verifierUid = getUidForVerifier(verifierInfo); 11724 if (verifierUid == -1) { 11725 continue; 11726 } 11727 11728 if (DEBUG_VERIFY) { 11729 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11730 + " with the correct signature"); 11731 } 11732 sufficientVerifiers.add(comp); 11733 verificationState.addSufficientVerifier(verifierUid); 11734 } 11735 11736 return sufficientVerifiers; 11737 } 11738 11739 private int getUidForVerifier(VerifierInfo verifierInfo) { 11740 synchronized (mPackages) { 11741 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11742 if (pkg == null) { 11743 return -1; 11744 } else if (pkg.mSignatures.length != 1) { 11745 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11746 + " has more than one signature; ignoring"); 11747 return -1; 11748 } 11749 11750 /* 11751 * If the public key of the package's signature does not match 11752 * our expected public key, then this is a different package and 11753 * we should skip. 11754 */ 11755 11756 final byte[] expectedPublicKey; 11757 try { 11758 final Signature verifierSig = pkg.mSignatures[0]; 11759 final PublicKey publicKey = verifierSig.getPublicKey(); 11760 expectedPublicKey = publicKey.getEncoded(); 11761 } catch (CertificateException e) { 11762 return -1; 11763 } 11764 11765 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11766 11767 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11768 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11769 + " does not have the expected public key; ignoring"); 11770 return -1; 11771 } 11772 11773 return pkg.applicationInfo.uid; 11774 } 11775 } 11776 11777 @Override 11778 public void finishPackageInstall(int token, boolean didLaunch) { 11779 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11780 11781 if (DEBUG_INSTALL) { 11782 Slog.v(TAG, "BM finishing package install for " + token); 11783 } 11784 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11785 11786 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11787 mHandler.sendMessage(msg); 11788 } 11789 11790 /** 11791 * Get the verification agent timeout. 11792 * 11793 * @return verification timeout in milliseconds 11794 */ 11795 private long getVerificationTimeout() { 11796 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11797 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11798 DEFAULT_VERIFICATION_TIMEOUT); 11799 } 11800 11801 /** 11802 * Get the default verification agent response code. 11803 * 11804 * @return default verification response code 11805 */ 11806 private int getDefaultVerificationResponse() { 11807 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11808 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11809 DEFAULT_VERIFICATION_RESPONSE); 11810 } 11811 11812 /** 11813 * Check whether or not package verification has been enabled. 11814 * 11815 * @return true if verification should be performed 11816 */ 11817 private boolean isVerificationEnabled(int userId, int installFlags) { 11818 if (!DEFAULT_VERIFY_ENABLE) { 11819 return false; 11820 } 11821 // Ephemeral apps don't get the full verification treatment 11822 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11823 if (DEBUG_EPHEMERAL) { 11824 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11825 } 11826 return false; 11827 } 11828 11829 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11830 11831 // Check if installing from ADB 11832 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11833 // Do not run verification in a test harness environment 11834 if (ActivityManager.isRunningInTestHarness()) { 11835 return false; 11836 } 11837 if (ensureVerifyAppsEnabled) { 11838 return true; 11839 } 11840 // Check if the developer does not want package verification for ADB installs 11841 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11842 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11843 return false; 11844 } 11845 } 11846 11847 if (ensureVerifyAppsEnabled) { 11848 return true; 11849 } 11850 11851 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11852 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11853 } 11854 11855 @Override 11856 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11857 throws RemoteException { 11858 mContext.enforceCallingOrSelfPermission( 11859 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11860 "Only intentfilter verification agents can verify applications"); 11861 11862 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11863 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11864 Binder.getCallingUid(), verificationCode, failedDomains); 11865 msg.arg1 = id; 11866 msg.obj = response; 11867 mHandler.sendMessage(msg); 11868 } 11869 11870 @Override 11871 public int getIntentVerificationStatus(String packageName, int userId) { 11872 synchronized (mPackages) { 11873 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11874 } 11875 } 11876 11877 @Override 11878 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11879 mContext.enforceCallingOrSelfPermission( 11880 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11881 11882 boolean result = false; 11883 synchronized (mPackages) { 11884 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11885 } 11886 if (result) { 11887 scheduleWritePackageRestrictionsLocked(userId); 11888 } 11889 return result; 11890 } 11891 11892 @Override 11893 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11894 String packageName) { 11895 synchronized (mPackages) { 11896 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11897 } 11898 } 11899 11900 @Override 11901 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11902 if (TextUtils.isEmpty(packageName)) { 11903 return ParceledListSlice.emptyList(); 11904 } 11905 synchronized (mPackages) { 11906 PackageParser.Package pkg = mPackages.get(packageName); 11907 if (pkg == null || pkg.activities == null) { 11908 return ParceledListSlice.emptyList(); 11909 } 11910 final int count = pkg.activities.size(); 11911 ArrayList<IntentFilter> result = new ArrayList<>(); 11912 for (int n=0; n<count; n++) { 11913 PackageParser.Activity activity = pkg.activities.get(n); 11914 if (activity.intents != null && activity.intents.size() > 0) { 11915 result.addAll(activity.intents); 11916 } 11917 } 11918 return new ParceledListSlice<>(result); 11919 } 11920 } 11921 11922 @Override 11923 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11924 mContext.enforceCallingOrSelfPermission( 11925 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11926 11927 synchronized (mPackages) { 11928 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11929 if (packageName != null) { 11930 result |= updateIntentVerificationStatus(packageName, 11931 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11932 userId); 11933 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11934 packageName, userId); 11935 } 11936 return result; 11937 } 11938 } 11939 11940 @Override 11941 public String getDefaultBrowserPackageName(int userId) { 11942 synchronized (mPackages) { 11943 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11944 } 11945 } 11946 11947 /** 11948 * Get the "allow unknown sources" setting. 11949 * 11950 * @return the current "allow unknown sources" setting 11951 */ 11952 private int getUnknownSourcesSettings() { 11953 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11954 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11955 -1); 11956 } 11957 11958 @Override 11959 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11960 final int uid = Binder.getCallingUid(); 11961 // writer 11962 synchronized (mPackages) { 11963 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11964 if (targetPackageSetting == null) { 11965 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11966 } 11967 11968 PackageSetting installerPackageSetting; 11969 if (installerPackageName != null) { 11970 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11971 if (installerPackageSetting == null) { 11972 throw new IllegalArgumentException("Unknown installer package: " 11973 + installerPackageName); 11974 } 11975 } else { 11976 installerPackageSetting = null; 11977 } 11978 11979 Signature[] callerSignature; 11980 Object obj = mSettings.getUserIdLPr(uid); 11981 if (obj != null) { 11982 if (obj instanceof SharedUserSetting) { 11983 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11984 } else if (obj instanceof PackageSetting) { 11985 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11986 } else { 11987 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11988 } 11989 } else { 11990 throw new SecurityException("Unknown calling UID: " + uid); 11991 } 11992 11993 // Verify: can't set installerPackageName to a package that is 11994 // not signed with the same cert as the caller. 11995 if (installerPackageSetting != null) { 11996 if (compareSignatures(callerSignature, 11997 installerPackageSetting.signatures.mSignatures) 11998 != PackageManager.SIGNATURE_MATCH) { 11999 throw new SecurityException( 12000 "Caller does not have same cert as new installer package " 12001 + installerPackageName); 12002 } 12003 } 12004 12005 // Verify: if target already has an installer package, it must 12006 // be signed with the same cert as the caller. 12007 if (targetPackageSetting.installerPackageName != null) { 12008 PackageSetting setting = mSettings.mPackages.get( 12009 targetPackageSetting.installerPackageName); 12010 // If the currently set package isn't valid, then it's always 12011 // okay to change it. 12012 if (setting != null) { 12013 if (compareSignatures(callerSignature, 12014 setting.signatures.mSignatures) 12015 != PackageManager.SIGNATURE_MATCH) { 12016 throw new SecurityException( 12017 "Caller does not have same cert as old installer package " 12018 + targetPackageSetting.installerPackageName); 12019 } 12020 } 12021 } 12022 12023 // Okay! 12024 targetPackageSetting.installerPackageName = installerPackageName; 12025 if (installerPackageName != null) { 12026 mSettings.mInstallerPackages.add(installerPackageName); 12027 } 12028 scheduleWriteSettingsLocked(); 12029 } 12030 } 12031 12032 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12033 // Queue up an async operation since the package installation may take a little while. 12034 mHandler.post(new Runnable() { 12035 public void run() { 12036 mHandler.removeCallbacks(this); 12037 // Result object to be returned 12038 PackageInstalledInfo res = new PackageInstalledInfo(); 12039 res.setReturnCode(currentStatus); 12040 res.uid = -1; 12041 res.pkg = null; 12042 res.removedInfo = null; 12043 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12044 args.doPreInstall(res.returnCode); 12045 synchronized (mInstallLock) { 12046 installPackageTracedLI(args, res); 12047 } 12048 args.doPostInstall(res.returnCode, res.uid); 12049 } 12050 12051 // A restore should be performed at this point if (a) the install 12052 // succeeded, (b) the operation is not an update, and (c) the new 12053 // package has not opted out of backup participation. 12054 final boolean update = res.removedInfo != null 12055 && res.removedInfo.removedPackage != null; 12056 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12057 boolean doRestore = !update 12058 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12059 12060 // Set up the post-install work request bookkeeping. This will be used 12061 // and cleaned up by the post-install event handling regardless of whether 12062 // there's a restore pass performed. Token values are >= 1. 12063 int token; 12064 if (mNextInstallToken < 0) mNextInstallToken = 1; 12065 token = mNextInstallToken++; 12066 12067 PostInstallData data = new PostInstallData(args, res); 12068 mRunningInstalls.put(token, data); 12069 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12070 12071 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12072 // Pass responsibility to the Backup Manager. It will perform a 12073 // restore if appropriate, then pass responsibility back to the 12074 // Package Manager to run the post-install observer callbacks 12075 // and broadcasts. 12076 IBackupManager bm = IBackupManager.Stub.asInterface( 12077 ServiceManager.getService(Context.BACKUP_SERVICE)); 12078 if (bm != null) { 12079 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12080 + " to BM for possible restore"); 12081 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12082 try { 12083 // TODO: http://b/22388012 12084 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12085 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12086 } else { 12087 doRestore = false; 12088 } 12089 } catch (RemoteException e) { 12090 // can't happen; the backup manager is local 12091 } catch (Exception e) { 12092 Slog.e(TAG, "Exception trying to enqueue restore", e); 12093 doRestore = false; 12094 } 12095 } else { 12096 Slog.e(TAG, "Backup Manager not found!"); 12097 doRestore = false; 12098 } 12099 } 12100 12101 if (!doRestore) { 12102 // No restore possible, or the Backup Manager was mysteriously not 12103 // available -- just fire the post-install work request directly. 12104 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12105 12106 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12107 12108 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12109 mHandler.sendMessage(msg); 12110 } 12111 } 12112 }); 12113 } 12114 12115 /** 12116 * Callback from PackageSettings whenever an app is first transitioned out of the 12117 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12118 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12119 * here whether the app is the target of an ongoing install, and only send the 12120 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12121 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12122 * handling. 12123 */ 12124 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12125 // Serialize this with the rest of the install-process message chain. In the 12126 // restore-at-install case, this Runnable will necessarily run before the 12127 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12128 // are coherent. In the non-restore case, the app has already completed install 12129 // and been launched through some other means, so it is not in a problematic 12130 // state for observers to see the FIRST_LAUNCH signal. 12131 mHandler.post(new Runnable() { 12132 @Override 12133 public void run() { 12134 for (int i = 0; i < mRunningInstalls.size(); i++) { 12135 final PostInstallData data = mRunningInstalls.valueAt(i); 12136 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12137 // right package; but is it for the right user? 12138 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12139 if (userId == data.res.newUsers[uIndex]) { 12140 if (DEBUG_BACKUP) { 12141 Slog.i(TAG, "Package " + pkgName 12142 + " being restored so deferring FIRST_LAUNCH"); 12143 } 12144 return; 12145 } 12146 } 12147 } 12148 } 12149 // didn't find it, so not being restored 12150 if (DEBUG_BACKUP) { 12151 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12152 } 12153 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12154 } 12155 }); 12156 } 12157 12158 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12159 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12160 installerPkg, null, userIds); 12161 } 12162 12163 private abstract class HandlerParams { 12164 private static final int MAX_RETRIES = 4; 12165 12166 /** 12167 * Number of times startCopy() has been attempted and had a non-fatal 12168 * error. 12169 */ 12170 private int mRetries = 0; 12171 12172 /** User handle for the user requesting the information or installation. */ 12173 private final UserHandle mUser; 12174 String traceMethod; 12175 int traceCookie; 12176 12177 HandlerParams(UserHandle user) { 12178 mUser = user; 12179 } 12180 12181 UserHandle getUser() { 12182 return mUser; 12183 } 12184 12185 HandlerParams setTraceMethod(String traceMethod) { 12186 this.traceMethod = traceMethod; 12187 return this; 12188 } 12189 12190 HandlerParams setTraceCookie(int traceCookie) { 12191 this.traceCookie = traceCookie; 12192 return this; 12193 } 12194 12195 final boolean startCopy() { 12196 boolean res; 12197 try { 12198 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12199 12200 if (++mRetries > MAX_RETRIES) { 12201 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12202 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12203 handleServiceError(); 12204 return false; 12205 } else { 12206 handleStartCopy(); 12207 res = true; 12208 } 12209 } catch (RemoteException e) { 12210 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12211 mHandler.sendEmptyMessage(MCS_RECONNECT); 12212 res = false; 12213 } 12214 handleReturnCode(); 12215 return res; 12216 } 12217 12218 final void serviceError() { 12219 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12220 handleServiceError(); 12221 handleReturnCode(); 12222 } 12223 12224 abstract void handleStartCopy() throws RemoteException; 12225 abstract void handleServiceError(); 12226 abstract void handleReturnCode(); 12227 } 12228 12229 class MeasureParams extends HandlerParams { 12230 private final PackageStats mStats; 12231 private boolean mSuccess; 12232 12233 private final IPackageStatsObserver mObserver; 12234 12235 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12236 super(new UserHandle(stats.userHandle)); 12237 mObserver = observer; 12238 mStats = stats; 12239 } 12240 12241 @Override 12242 public String toString() { 12243 return "MeasureParams{" 12244 + Integer.toHexString(System.identityHashCode(this)) 12245 + " " + mStats.packageName + "}"; 12246 } 12247 12248 @Override 12249 void handleStartCopy() throws RemoteException { 12250 synchronized (mInstallLock) { 12251 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12252 } 12253 12254 if (mSuccess) { 12255 final boolean mounted; 12256 if (Environment.isExternalStorageEmulated()) { 12257 mounted = true; 12258 } else { 12259 final String status = Environment.getExternalStorageState(); 12260 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12261 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12262 } 12263 12264 if (mounted) { 12265 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12266 12267 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12268 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12269 12270 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12271 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12272 12273 // Always subtract cache size, since it's a subdirectory 12274 mStats.externalDataSize -= mStats.externalCacheSize; 12275 12276 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12277 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12278 12279 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12280 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12281 } 12282 } 12283 } 12284 12285 @Override 12286 void handleReturnCode() { 12287 if (mObserver != null) { 12288 try { 12289 mObserver.onGetStatsCompleted(mStats, mSuccess); 12290 } catch (RemoteException e) { 12291 Slog.i(TAG, "Observer no longer exists."); 12292 } 12293 } 12294 } 12295 12296 @Override 12297 void handleServiceError() { 12298 Slog.e(TAG, "Could not measure application " + mStats.packageName 12299 + " external storage"); 12300 } 12301 } 12302 12303 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12304 throws RemoteException { 12305 long result = 0; 12306 for (File path : paths) { 12307 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12308 } 12309 return result; 12310 } 12311 12312 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12313 for (File path : paths) { 12314 try { 12315 mcs.clearDirectory(path.getAbsolutePath()); 12316 } catch (RemoteException e) { 12317 } 12318 } 12319 } 12320 12321 static class OriginInfo { 12322 /** 12323 * Location where install is coming from, before it has been 12324 * copied/renamed into place. This could be a single monolithic APK 12325 * file, or a cluster directory. This location may be untrusted. 12326 */ 12327 final File file; 12328 final String cid; 12329 12330 /** 12331 * Flag indicating that {@link #file} or {@link #cid} has already been 12332 * staged, meaning downstream users don't need to defensively copy the 12333 * contents. 12334 */ 12335 final boolean staged; 12336 12337 /** 12338 * Flag indicating that {@link #file} or {@link #cid} is an already 12339 * installed app that is being moved. 12340 */ 12341 final boolean existing; 12342 12343 final String resolvedPath; 12344 final File resolvedFile; 12345 12346 static OriginInfo fromNothing() { 12347 return new OriginInfo(null, null, false, false); 12348 } 12349 12350 static OriginInfo fromUntrustedFile(File file) { 12351 return new OriginInfo(file, null, false, false); 12352 } 12353 12354 static OriginInfo fromExistingFile(File file) { 12355 return new OriginInfo(file, null, false, true); 12356 } 12357 12358 static OriginInfo fromStagedFile(File file) { 12359 return new OriginInfo(file, null, true, false); 12360 } 12361 12362 static OriginInfo fromStagedContainer(String cid) { 12363 return new OriginInfo(null, cid, true, false); 12364 } 12365 12366 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12367 this.file = file; 12368 this.cid = cid; 12369 this.staged = staged; 12370 this.existing = existing; 12371 12372 if (cid != null) { 12373 resolvedPath = PackageHelper.getSdDir(cid); 12374 resolvedFile = new File(resolvedPath); 12375 } else if (file != null) { 12376 resolvedPath = file.getAbsolutePath(); 12377 resolvedFile = file; 12378 } else { 12379 resolvedPath = null; 12380 resolvedFile = null; 12381 } 12382 } 12383 } 12384 12385 static class MoveInfo { 12386 final int moveId; 12387 final String fromUuid; 12388 final String toUuid; 12389 final String packageName; 12390 final String dataAppName; 12391 final int appId; 12392 final String seinfo; 12393 final int targetSdkVersion; 12394 12395 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12396 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12397 this.moveId = moveId; 12398 this.fromUuid = fromUuid; 12399 this.toUuid = toUuid; 12400 this.packageName = packageName; 12401 this.dataAppName = dataAppName; 12402 this.appId = appId; 12403 this.seinfo = seinfo; 12404 this.targetSdkVersion = targetSdkVersion; 12405 } 12406 } 12407 12408 static class VerificationInfo { 12409 /** A constant used to indicate that a uid value is not present. */ 12410 public static final int NO_UID = -1; 12411 12412 /** URI referencing where the package was downloaded from. */ 12413 final Uri originatingUri; 12414 12415 /** HTTP referrer URI associated with the originatingURI. */ 12416 final Uri referrer; 12417 12418 /** UID of the application that the install request originated from. */ 12419 final int originatingUid; 12420 12421 /** UID of application requesting the install */ 12422 final int installerUid; 12423 12424 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12425 this.originatingUri = originatingUri; 12426 this.referrer = referrer; 12427 this.originatingUid = originatingUid; 12428 this.installerUid = installerUid; 12429 } 12430 } 12431 12432 class InstallParams extends HandlerParams { 12433 final OriginInfo origin; 12434 final MoveInfo move; 12435 final IPackageInstallObserver2 observer; 12436 int installFlags; 12437 final String installerPackageName; 12438 final String volumeUuid; 12439 private InstallArgs mArgs; 12440 private int mRet; 12441 final String packageAbiOverride; 12442 final String[] grantedRuntimePermissions; 12443 final VerificationInfo verificationInfo; 12444 final Certificate[][] certificates; 12445 12446 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12447 int installFlags, String installerPackageName, String volumeUuid, 12448 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12449 String[] grantedPermissions, Certificate[][] certificates) { 12450 super(user); 12451 this.origin = origin; 12452 this.move = move; 12453 this.observer = observer; 12454 this.installFlags = installFlags; 12455 this.installerPackageName = installerPackageName; 12456 this.volumeUuid = volumeUuid; 12457 this.verificationInfo = verificationInfo; 12458 this.packageAbiOverride = packageAbiOverride; 12459 this.grantedRuntimePermissions = grantedPermissions; 12460 this.certificates = certificates; 12461 } 12462 12463 @Override 12464 public String toString() { 12465 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12466 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12467 } 12468 12469 private int installLocationPolicy(PackageInfoLite pkgLite) { 12470 String packageName = pkgLite.packageName; 12471 int installLocation = pkgLite.installLocation; 12472 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12473 // reader 12474 synchronized (mPackages) { 12475 // Currently installed package which the new package is attempting to replace or 12476 // null if no such package is installed. 12477 PackageParser.Package installedPkg = mPackages.get(packageName); 12478 // Package which currently owns the data which the new package will own if installed. 12479 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12480 // will be null whereas dataOwnerPkg will contain information about the package 12481 // which was uninstalled while keeping its data. 12482 PackageParser.Package dataOwnerPkg = installedPkg; 12483 if (dataOwnerPkg == null) { 12484 PackageSetting ps = mSettings.mPackages.get(packageName); 12485 if (ps != null) { 12486 dataOwnerPkg = ps.pkg; 12487 } 12488 } 12489 12490 if (dataOwnerPkg != null) { 12491 // If installed, the package will get access to data left on the device by its 12492 // predecessor. As a security measure, this is permited only if this is not a 12493 // version downgrade or if the predecessor package is marked as debuggable and 12494 // a downgrade is explicitly requested. 12495 // 12496 // On debuggable platform builds, downgrades are permitted even for 12497 // non-debuggable packages to make testing easier. Debuggable platform builds do 12498 // not offer security guarantees and thus it's OK to disable some security 12499 // mechanisms to make debugging/testing easier on those builds. However, even on 12500 // debuggable builds downgrades of packages are permitted only if requested via 12501 // installFlags. This is because we aim to keep the behavior of debuggable 12502 // platform builds as close as possible to the behavior of non-debuggable 12503 // platform builds. 12504 final boolean downgradeRequested = 12505 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12506 final boolean packageDebuggable = 12507 (dataOwnerPkg.applicationInfo.flags 12508 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12509 final boolean downgradePermitted = 12510 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12511 if (!downgradePermitted) { 12512 try { 12513 checkDowngrade(dataOwnerPkg, pkgLite); 12514 } catch (PackageManagerException e) { 12515 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12516 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12517 } 12518 } 12519 } 12520 12521 if (installedPkg != null) { 12522 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12523 // Check for updated system application. 12524 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12525 if (onSd) { 12526 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12527 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12528 } 12529 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12530 } else { 12531 if (onSd) { 12532 // Install flag overrides everything. 12533 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12534 } 12535 // If current upgrade specifies particular preference 12536 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12537 // Application explicitly specified internal. 12538 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12539 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12540 // App explictly prefers external. Let policy decide 12541 } else { 12542 // Prefer previous location 12543 if (isExternal(installedPkg)) { 12544 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12545 } 12546 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12547 } 12548 } 12549 } else { 12550 // Invalid install. Return error code 12551 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12552 } 12553 } 12554 } 12555 // All the special cases have been taken care of. 12556 // Return result based on recommended install location. 12557 if (onSd) { 12558 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12559 } 12560 return pkgLite.recommendedInstallLocation; 12561 } 12562 12563 /* 12564 * Invoke remote method to get package information and install 12565 * location values. Override install location based on default 12566 * policy if needed and then create install arguments based 12567 * on the install location. 12568 */ 12569 public void handleStartCopy() throws RemoteException { 12570 int ret = PackageManager.INSTALL_SUCCEEDED; 12571 12572 // If we're already staged, we've firmly committed to an install location 12573 if (origin.staged) { 12574 if (origin.file != null) { 12575 installFlags |= PackageManager.INSTALL_INTERNAL; 12576 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12577 } else if (origin.cid != null) { 12578 installFlags |= PackageManager.INSTALL_EXTERNAL; 12579 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12580 } else { 12581 throw new IllegalStateException("Invalid stage location"); 12582 } 12583 } 12584 12585 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12586 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12587 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12588 PackageInfoLite pkgLite = null; 12589 12590 if (onInt && onSd) { 12591 // Check if both bits are set. 12592 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12593 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12594 } else if (onSd && ephemeral) { 12595 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12596 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12597 } else { 12598 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12599 packageAbiOverride); 12600 12601 if (DEBUG_EPHEMERAL && ephemeral) { 12602 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12603 } 12604 12605 /* 12606 * If we have too little free space, try to free cache 12607 * before giving up. 12608 */ 12609 if (!origin.staged && pkgLite.recommendedInstallLocation 12610 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12611 // TODO: focus freeing disk space on the target device 12612 final StorageManager storage = StorageManager.from(mContext); 12613 final long lowThreshold = storage.getStorageLowBytes( 12614 Environment.getDataDirectory()); 12615 12616 final long sizeBytes = mContainerService.calculateInstalledSize( 12617 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12618 12619 try { 12620 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12621 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12622 installFlags, packageAbiOverride); 12623 } catch (InstallerException e) { 12624 Slog.w(TAG, "Failed to free cache", e); 12625 } 12626 12627 /* 12628 * The cache free must have deleted the file we 12629 * downloaded to install. 12630 * 12631 * TODO: fix the "freeCache" call to not delete 12632 * the file we care about. 12633 */ 12634 if (pkgLite.recommendedInstallLocation 12635 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12636 pkgLite.recommendedInstallLocation 12637 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12638 } 12639 } 12640 } 12641 12642 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12643 int loc = pkgLite.recommendedInstallLocation; 12644 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12645 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12646 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12647 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12648 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12649 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12650 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12651 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12652 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12653 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12654 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12655 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12656 } else { 12657 // Override with defaults if needed. 12658 loc = installLocationPolicy(pkgLite); 12659 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12660 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12661 } else if (!onSd && !onInt) { 12662 // Override install location with flags 12663 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12664 // Set the flag to install on external media. 12665 installFlags |= PackageManager.INSTALL_EXTERNAL; 12666 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12667 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12668 if (DEBUG_EPHEMERAL) { 12669 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12670 } 12671 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12672 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12673 |PackageManager.INSTALL_INTERNAL); 12674 } else { 12675 // Make sure the flag for installing on external 12676 // media is unset 12677 installFlags |= PackageManager.INSTALL_INTERNAL; 12678 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12679 } 12680 } 12681 } 12682 } 12683 12684 final InstallArgs args = createInstallArgs(this); 12685 mArgs = args; 12686 12687 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12688 // TODO: http://b/22976637 12689 // Apps installed for "all" users use the device owner to verify the app 12690 UserHandle verifierUser = getUser(); 12691 if (verifierUser == UserHandle.ALL) { 12692 verifierUser = UserHandle.SYSTEM; 12693 } 12694 12695 /* 12696 * Determine if we have any installed package verifiers. If we 12697 * do, then we'll defer to them to verify the packages. 12698 */ 12699 final int requiredUid = mRequiredVerifierPackage == null ? -1 12700 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12701 verifierUser.getIdentifier()); 12702 if (!origin.existing && requiredUid != -1 12703 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12704 final Intent verification = new Intent( 12705 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12706 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12707 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12708 PACKAGE_MIME_TYPE); 12709 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12710 12711 // Query all live verifiers based on current user state 12712 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12713 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12714 12715 if (DEBUG_VERIFY) { 12716 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12717 + verification.toString() + " with " + pkgLite.verifiers.length 12718 + " optional verifiers"); 12719 } 12720 12721 final int verificationId = mPendingVerificationToken++; 12722 12723 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12724 12725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12726 installerPackageName); 12727 12728 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12729 installFlags); 12730 12731 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12732 pkgLite.packageName); 12733 12734 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12735 pkgLite.versionCode); 12736 12737 if (verificationInfo != null) { 12738 if (verificationInfo.originatingUri != null) { 12739 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12740 verificationInfo.originatingUri); 12741 } 12742 if (verificationInfo.referrer != null) { 12743 verification.putExtra(Intent.EXTRA_REFERRER, 12744 verificationInfo.referrer); 12745 } 12746 if (verificationInfo.originatingUid >= 0) { 12747 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12748 verificationInfo.originatingUid); 12749 } 12750 if (verificationInfo.installerUid >= 0) { 12751 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12752 verificationInfo.installerUid); 12753 } 12754 } 12755 12756 final PackageVerificationState verificationState = new PackageVerificationState( 12757 requiredUid, args); 12758 12759 mPendingVerification.append(verificationId, verificationState); 12760 12761 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12762 receivers, verificationState); 12763 12764 /* 12765 * If any sufficient verifiers were listed in the package 12766 * manifest, attempt to ask them. 12767 */ 12768 if (sufficientVerifiers != null) { 12769 final int N = sufficientVerifiers.size(); 12770 if (N == 0) { 12771 Slog.i(TAG, "Additional verifiers required, but none installed."); 12772 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12773 } else { 12774 for (int i = 0; i < N; i++) { 12775 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12776 12777 final Intent sufficientIntent = new Intent(verification); 12778 sufficientIntent.setComponent(verifierComponent); 12779 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12780 } 12781 } 12782 } 12783 12784 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12785 mRequiredVerifierPackage, receivers); 12786 if (ret == PackageManager.INSTALL_SUCCEEDED 12787 && mRequiredVerifierPackage != null) { 12788 Trace.asyncTraceBegin( 12789 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12790 /* 12791 * Send the intent to the required verification agent, 12792 * but only start the verification timeout after the 12793 * target BroadcastReceivers have run. 12794 */ 12795 verification.setComponent(requiredVerifierComponent); 12796 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12797 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12798 new BroadcastReceiver() { 12799 @Override 12800 public void onReceive(Context context, Intent intent) { 12801 final Message msg = mHandler 12802 .obtainMessage(CHECK_PENDING_VERIFICATION); 12803 msg.arg1 = verificationId; 12804 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12805 } 12806 }, null, 0, null, null); 12807 12808 /* 12809 * We don't want the copy to proceed until verification 12810 * succeeds, so null out this field. 12811 */ 12812 mArgs = null; 12813 } 12814 } else { 12815 /* 12816 * No package verification is enabled, so immediately start 12817 * the remote call to initiate copy using temporary file. 12818 */ 12819 ret = args.copyApk(mContainerService, true); 12820 } 12821 } 12822 12823 mRet = ret; 12824 } 12825 12826 @Override 12827 void handleReturnCode() { 12828 // If mArgs is null, then MCS couldn't be reached. When it 12829 // reconnects, it will try again to install. At that point, this 12830 // will succeed. 12831 if (mArgs != null) { 12832 processPendingInstall(mArgs, mRet); 12833 } 12834 } 12835 12836 @Override 12837 void handleServiceError() { 12838 mArgs = createInstallArgs(this); 12839 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12840 } 12841 12842 public boolean isForwardLocked() { 12843 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12844 } 12845 } 12846 12847 /** 12848 * Used during creation of InstallArgs 12849 * 12850 * @param installFlags package installation flags 12851 * @return true if should be installed on external storage 12852 */ 12853 private static boolean installOnExternalAsec(int installFlags) { 12854 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12855 return false; 12856 } 12857 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12858 return true; 12859 } 12860 return false; 12861 } 12862 12863 /** 12864 * Used during creation of InstallArgs 12865 * 12866 * @param installFlags package installation flags 12867 * @return true if should be installed as forward locked 12868 */ 12869 private static boolean installForwardLocked(int installFlags) { 12870 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12871 } 12872 12873 private InstallArgs createInstallArgs(InstallParams params) { 12874 if (params.move != null) { 12875 return new MoveInstallArgs(params); 12876 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12877 return new AsecInstallArgs(params); 12878 } else { 12879 return new FileInstallArgs(params); 12880 } 12881 } 12882 12883 /** 12884 * Create args that describe an existing installed package. Typically used 12885 * when cleaning up old installs, or used as a move source. 12886 */ 12887 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12888 String resourcePath, String[] instructionSets) { 12889 final boolean isInAsec; 12890 if (installOnExternalAsec(installFlags)) { 12891 /* Apps on SD card are always in ASEC containers. */ 12892 isInAsec = true; 12893 } else if (installForwardLocked(installFlags) 12894 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12895 /* 12896 * Forward-locked apps are only in ASEC containers if they're the 12897 * new style 12898 */ 12899 isInAsec = true; 12900 } else { 12901 isInAsec = false; 12902 } 12903 12904 if (isInAsec) { 12905 return new AsecInstallArgs(codePath, instructionSets, 12906 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12907 } else { 12908 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12909 } 12910 } 12911 12912 static abstract class InstallArgs { 12913 /** @see InstallParams#origin */ 12914 final OriginInfo origin; 12915 /** @see InstallParams#move */ 12916 final MoveInfo move; 12917 12918 final IPackageInstallObserver2 observer; 12919 // Always refers to PackageManager flags only 12920 final int installFlags; 12921 final String installerPackageName; 12922 final String volumeUuid; 12923 final UserHandle user; 12924 final String abiOverride; 12925 final String[] installGrantPermissions; 12926 /** If non-null, drop an async trace when the install completes */ 12927 final String traceMethod; 12928 final int traceCookie; 12929 final Certificate[][] certificates; 12930 12931 // The list of instruction sets supported by this app. This is currently 12932 // only used during the rmdex() phase to clean up resources. We can get rid of this 12933 // if we move dex files under the common app path. 12934 /* nullable */ String[] instructionSets; 12935 12936 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12937 int installFlags, String installerPackageName, String volumeUuid, 12938 UserHandle user, String[] instructionSets, 12939 String abiOverride, String[] installGrantPermissions, 12940 String traceMethod, int traceCookie, Certificate[][] certificates) { 12941 this.origin = origin; 12942 this.move = move; 12943 this.installFlags = installFlags; 12944 this.observer = observer; 12945 this.installerPackageName = installerPackageName; 12946 this.volumeUuid = volumeUuid; 12947 this.user = user; 12948 this.instructionSets = instructionSets; 12949 this.abiOverride = abiOverride; 12950 this.installGrantPermissions = installGrantPermissions; 12951 this.traceMethod = traceMethod; 12952 this.traceCookie = traceCookie; 12953 this.certificates = certificates; 12954 } 12955 12956 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12957 abstract int doPreInstall(int status); 12958 12959 /** 12960 * Rename package into final resting place. All paths on the given 12961 * scanned package should be updated to reflect the rename. 12962 */ 12963 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12964 abstract int doPostInstall(int status, int uid); 12965 12966 /** @see PackageSettingBase#codePathString */ 12967 abstract String getCodePath(); 12968 /** @see PackageSettingBase#resourcePathString */ 12969 abstract String getResourcePath(); 12970 12971 // Need installer lock especially for dex file removal. 12972 abstract void cleanUpResourcesLI(); 12973 abstract boolean doPostDeleteLI(boolean delete); 12974 12975 /** 12976 * Called before the source arguments are copied. This is used mostly 12977 * for MoveParams when it needs to read the source file to put it in the 12978 * destination. 12979 */ 12980 int doPreCopy() { 12981 return PackageManager.INSTALL_SUCCEEDED; 12982 } 12983 12984 /** 12985 * Called after the source arguments are copied. This is used mostly for 12986 * MoveParams when it needs to read the source file to put it in the 12987 * destination. 12988 */ 12989 int doPostCopy(int uid) { 12990 return PackageManager.INSTALL_SUCCEEDED; 12991 } 12992 12993 protected boolean isFwdLocked() { 12994 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12995 } 12996 12997 protected boolean isExternalAsec() { 12998 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12999 } 13000 13001 protected boolean isEphemeral() { 13002 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13003 } 13004 13005 UserHandle getUser() { 13006 return user; 13007 } 13008 } 13009 13010 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13011 if (!allCodePaths.isEmpty()) { 13012 if (instructionSets == null) { 13013 throw new IllegalStateException("instructionSet == null"); 13014 } 13015 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13016 for (String codePath : allCodePaths) { 13017 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13018 try { 13019 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13020 } catch (InstallerException ignored) { 13021 } 13022 } 13023 } 13024 } 13025 } 13026 13027 /** 13028 * Logic to handle installation of non-ASEC applications, including copying 13029 * and renaming logic. 13030 */ 13031 class FileInstallArgs extends InstallArgs { 13032 private File codeFile; 13033 private File resourceFile; 13034 13035 // Example topology: 13036 // /data/app/com.example/base.apk 13037 // /data/app/com.example/split_foo.apk 13038 // /data/app/com.example/lib/arm/libfoo.so 13039 // /data/app/com.example/lib/arm64/libfoo.so 13040 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13041 13042 /** New install */ 13043 FileInstallArgs(InstallParams params) { 13044 super(params.origin, params.move, params.observer, params.installFlags, 13045 params.installerPackageName, params.volumeUuid, 13046 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13047 params.grantedRuntimePermissions, 13048 params.traceMethod, params.traceCookie, params.certificates); 13049 if (isFwdLocked()) { 13050 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13051 } 13052 } 13053 13054 /** Existing install */ 13055 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13056 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13057 null, null, null, 0, null /*certificates*/); 13058 this.codeFile = (codePath != null) ? new File(codePath) : null; 13059 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13060 } 13061 13062 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13063 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13064 try { 13065 return doCopyApk(imcs, temp); 13066 } finally { 13067 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13068 } 13069 } 13070 13071 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13072 if (origin.staged) { 13073 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13074 codeFile = origin.file; 13075 resourceFile = origin.file; 13076 return PackageManager.INSTALL_SUCCEEDED; 13077 } 13078 13079 try { 13080 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13081 final File tempDir = 13082 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13083 codeFile = tempDir; 13084 resourceFile = tempDir; 13085 } catch (IOException e) { 13086 Slog.w(TAG, "Failed to create copy file: " + e); 13087 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13088 } 13089 13090 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13091 @Override 13092 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13093 if (!FileUtils.isValidExtFilename(name)) { 13094 throw new IllegalArgumentException("Invalid filename: " + name); 13095 } 13096 try { 13097 final File file = new File(codeFile, name); 13098 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13099 O_RDWR | O_CREAT, 0644); 13100 Os.chmod(file.getAbsolutePath(), 0644); 13101 return new ParcelFileDescriptor(fd); 13102 } catch (ErrnoException e) { 13103 throw new RemoteException("Failed to open: " + e.getMessage()); 13104 } 13105 } 13106 }; 13107 13108 int ret = PackageManager.INSTALL_SUCCEEDED; 13109 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13110 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13111 Slog.e(TAG, "Failed to copy package"); 13112 return ret; 13113 } 13114 13115 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13116 NativeLibraryHelper.Handle handle = null; 13117 try { 13118 handle = NativeLibraryHelper.Handle.create(codeFile); 13119 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13120 abiOverride); 13121 } catch (IOException e) { 13122 Slog.e(TAG, "Copying native libraries failed", e); 13123 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13124 } finally { 13125 IoUtils.closeQuietly(handle); 13126 } 13127 13128 return ret; 13129 } 13130 13131 int doPreInstall(int status) { 13132 if (status != PackageManager.INSTALL_SUCCEEDED) { 13133 cleanUp(); 13134 } 13135 return status; 13136 } 13137 13138 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13139 if (status != PackageManager.INSTALL_SUCCEEDED) { 13140 cleanUp(); 13141 return false; 13142 } 13143 13144 final File targetDir = codeFile.getParentFile(); 13145 final File beforeCodeFile = codeFile; 13146 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13147 13148 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13149 try { 13150 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13151 } catch (ErrnoException e) { 13152 Slog.w(TAG, "Failed to rename", e); 13153 return false; 13154 } 13155 13156 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13157 Slog.w(TAG, "Failed to restorecon"); 13158 return false; 13159 } 13160 13161 // Reflect the rename internally 13162 codeFile = afterCodeFile; 13163 resourceFile = afterCodeFile; 13164 13165 // Reflect the rename in scanned details 13166 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13167 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13168 afterCodeFile, pkg.baseCodePath)); 13169 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13170 afterCodeFile, pkg.splitCodePaths)); 13171 13172 // Reflect the rename in app info 13173 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13174 pkg.setApplicationInfoCodePath(pkg.codePath); 13175 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13176 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13177 pkg.setApplicationInfoResourcePath(pkg.codePath); 13178 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13179 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13180 13181 return true; 13182 } 13183 13184 int doPostInstall(int status, int uid) { 13185 if (status != PackageManager.INSTALL_SUCCEEDED) { 13186 cleanUp(); 13187 } 13188 return status; 13189 } 13190 13191 @Override 13192 String getCodePath() { 13193 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13194 } 13195 13196 @Override 13197 String getResourcePath() { 13198 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13199 } 13200 13201 private boolean cleanUp() { 13202 if (codeFile == null || !codeFile.exists()) { 13203 return false; 13204 } 13205 13206 removeCodePathLI(codeFile); 13207 13208 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13209 resourceFile.delete(); 13210 } 13211 13212 return true; 13213 } 13214 13215 void cleanUpResourcesLI() { 13216 // Try enumerating all code paths before deleting 13217 List<String> allCodePaths = Collections.EMPTY_LIST; 13218 if (codeFile != null && codeFile.exists()) { 13219 try { 13220 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13221 allCodePaths = pkg.getAllCodePaths(); 13222 } catch (PackageParserException e) { 13223 // Ignored; we tried our best 13224 } 13225 } 13226 13227 cleanUp(); 13228 removeDexFiles(allCodePaths, instructionSets); 13229 } 13230 13231 boolean doPostDeleteLI(boolean delete) { 13232 // XXX err, shouldn't we respect the delete flag? 13233 cleanUpResourcesLI(); 13234 return true; 13235 } 13236 } 13237 13238 private boolean isAsecExternal(String cid) { 13239 final String asecPath = PackageHelper.getSdFilesystem(cid); 13240 return !asecPath.startsWith(mAsecInternalPath); 13241 } 13242 13243 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13244 PackageManagerException { 13245 if (copyRet < 0) { 13246 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13247 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13248 throw new PackageManagerException(copyRet, message); 13249 } 13250 } 13251 } 13252 13253 /** 13254 * Extract the MountService "container ID" from the full code path of an 13255 * .apk. 13256 */ 13257 static String cidFromCodePath(String fullCodePath) { 13258 int eidx = fullCodePath.lastIndexOf("/"); 13259 String subStr1 = fullCodePath.substring(0, eidx); 13260 int sidx = subStr1.lastIndexOf("/"); 13261 return subStr1.substring(sidx+1, eidx); 13262 } 13263 13264 /** 13265 * Logic to handle installation of ASEC applications, including copying and 13266 * renaming logic. 13267 */ 13268 class AsecInstallArgs extends InstallArgs { 13269 static final String RES_FILE_NAME = "pkg.apk"; 13270 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13271 13272 String cid; 13273 String packagePath; 13274 String resourcePath; 13275 13276 /** New install */ 13277 AsecInstallArgs(InstallParams params) { 13278 super(params.origin, params.move, params.observer, params.installFlags, 13279 params.installerPackageName, params.volumeUuid, 13280 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13281 params.grantedRuntimePermissions, 13282 params.traceMethod, params.traceCookie, params.certificates); 13283 } 13284 13285 /** Existing install */ 13286 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13287 boolean isExternal, boolean isForwardLocked) { 13288 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13289 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13290 instructionSets, null, null, null, 0, null /*certificates*/); 13291 // Hackily pretend we're still looking at a full code path 13292 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13293 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13294 } 13295 13296 // Extract cid from fullCodePath 13297 int eidx = fullCodePath.lastIndexOf("/"); 13298 String subStr1 = fullCodePath.substring(0, eidx); 13299 int sidx = subStr1.lastIndexOf("/"); 13300 cid = subStr1.substring(sidx+1, eidx); 13301 setMountPath(subStr1); 13302 } 13303 13304 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13305 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13306 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13307 instructionSets, null, null, null, 0, null /*certificates*/); 13308 this.cid = cid; 13309 setMountPath(PackageHelper.getSdDir(cid)); 13310 } 13311 13312 void createCopyFile() { 13313 cid = mInstallerService.allocateExternalStageCidLegacy(); 13314 } 13315 13316 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13317 if (origin.staged && origin.cid != null) { 13318 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13319 cid = origin.cid; 13320 setMountPath(PackageHelper.getSdDir(cid)); 13321 return PackageManager.INSTALL_SUCCEEDED; 13322 } 13323 13324 if (temp) { 13325 createCopyFile(); 13326 } else { 13327 /* 13328 * Pre-emptively destroy the container since it's destroyed if 13329 * copying fails due to it existing anyway. 13330 */ 13331 PackageHelper.destroySdDir(cid); 13332 } 13333 13334 final String newMountPath = imcs.copyPackageToContainer( 13335 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13336 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13337 13338 if (newMountPath != null) { 13339 setMountPath(newMountPath); 13340 return PackageManager.INSTALL_SUCCEEDED; 13341 } else { 13342 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13343 } 13344 } 13345 13346 @Override 13347 String getCodePath() { 13348 return packagePath; 13349 } 13350 13351 @Override 13352 String getResourcePath() { 13353 return resourcePath; 13354 } 13355 13356 int doPreInstall(int status) { 13357 if (status != PackageManager.INSTALL_SUCCEEDED) { 13358 // Destroy container 13359 PackageHelper.destroySdDir(cid); 13360 } else { 13361 boolean mounted = PackageHelper.isContainerMounted(cid); 13362 if (!mounted) { 13363 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13364 Process.SYSTEM_UID); 13365 if (newMountPath != null) { 13366 setMountPath(newMountPath); 13367 } else { 13368 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13369 } 13370 } 13371 } 13372 return status; 13373 } 13374 13375 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13376 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13377 String newMountPath = null; 13378 if (PackageHelper.isContainerMounted(cid)) { 13379 // Unmount the container 13380 if (!PackageHelper.unMountSdDir(cid)) { 13381 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13382 return false; 13383 } 13384 } 13385 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13386 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13387 " which might be stale. Will try to clean up."); 13388 // Clean up the stale container and proceed to recreate. 13389 if (!PackageHelper.destroySdDir(newCacheId)) { 13390 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13391 return false; 13392 } 13393 // Successfully cleaned up stale container. Try to rename again. 13394 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13395 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13396 + " inspite of cleaning it up."); 13397 return false; 13398 } 13399 } 13400 if (!PackageHelper.isContainerMounted(newCacheId)) { 13401 Slog.w(TAG, "Mounting container " + newCacheId); 13402 newMountPath = PackageHelper.mountSdDir(newCacheId, 13403 getEncryptKey(), Process.SYSTEM_UID); 13404 } else { 13405 newMountPath = PackageHelper.getSdDir(newCacheId); 13406 } 13407 if (newMountPath == null) { 13408 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13409 return false; 13410 } 13411 Log.i(TAG, "Succesfully renamed " + cid + 13412 " to " + newCacheId + 13413 " at new path: " + newMountPath); 13414 cid = newCacheId; 13415 13416 final File beforeCodeFile = new File(packagePath); 13417 setMountPath(newMountPath); 13418 final File afterCodeFile = new File(packagePath); 13419 13420 // Reflect the rename in scanned details 13421 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13422 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13423 afterCodeFile, pkg.baseCodePath)); 13424 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13425 afterCodeFile, pkg.splitCodePaths)); 13426 13427 // Reflect the rename in app info 13428 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13429 pkg.setApplicationInfoCodePath(pkg.codePath); 13430 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13431 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13432 pkg.setApplicationInfoResourcePath(pkg.codePath); 13433 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13434 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13435 13436 return true; 13437 } 13438 13439 private void setMountPath(String mountPath) { 13440 final File mountFile = new File(mountPath); 13441 13442 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13443 if (monolithicFile.exists()) { 13444 packagePath = monolithicFile.getAbsolutePath(); 13445 if (isFwdLocked()) { 13446 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13447 } else { 13448 resourcePath = packagePath; 13449 } 13450 } else { 13451 packagePath = mountFile.getAbsolutePath(); 13452 resourcePath = packagePath; 13453 } 13454 } 13455 13456 int doPostInstall(int status, int uid) { 13457 if (status != PackageManager.INSTALL_SUCCEEDED) { 13458 cleanUp(); 13459 } else { 13460 final int groupOwner; 13461 final String protectedFile; 13462 if (isFwdLocked()) { 13463 groupOwner = UserHandle.getSharedAppGid(uid); 13464 protectedFile = RES_FILE_NAME; 13465 } else { 13466 groupOwner = -1; 13467 protectedFile = null; 13468 } 13469 13470 if (uid < Process.FIRST_APPLICATION_UID 13471 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13472 Slog.e(TAG, "Failed to finalize " + cid); 13473 PackageHelper.destroySdDir(cid); 13474 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13475 } 13476 13477 boolean mounted = PackageHelper.isContainerMounted(cid); 13478 if (!mounted) { 13479 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13480 } 13481 } 13482 return status; 13483 } 13484 13485 private void cleanUp() { 13486 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13487 13488 // Destroy secure container 13489 PackageHelper.destroySdDir(cid); 13490 } 13491 13492 private List<String> getAllCodePaths() { 13493 final File codeFile = new File(getCodePath()); 13494 if (codeFile != null && codeFile.exists()) { 13495 try { 13496 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13497 return pkg.getAllCodePaths(); 13498 } catch (PackageParserException e) { 13499 // Ignored; we tried our best 13500 } 13501 } 13502 return Collections.EMPTY_LIST; 13503 } 13504 13505 void cleanUpResourcesLI() { 13506 // Enumerate all code paths before deleting 13507 cleanUpResourcesLI(getAllCodePaths()); 13508 } 13509 13510 private void cleanUpResourcesLI(List<String> allCodePaths) { 13511 cleanUp(); 13512 removeDexFiles(allCodePaths, instructionSets); 13513 } 13514 13515 String getPackageName() { 13516 return getAsecPackageName(cid); 13517 } 13518 13519 boolean doPostDeleteLI(boolean delete) { 13520 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13521 final List<String> allCodePaths = getAllCodePaths(); 13522 boolean mounted = PackageHelper.isContainerMounted(cid); 13523 if (mounted) { 13524 // Unmount first 13525 if (PackageHelper.unMountSdDir(cid)) { 13526 mounted = false; 13527 } 13528 } 13529 if (!mounted && delete) { 13530 cleanUpResourcesLI(allCodePaths); 13531 } 13532 return !mounted; 13533 } 13534 13535 @Override 13536 int doPreCopy() { 13537 if (isFwdLocked()) { 13538 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13539 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13540 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13541 } 13542 } 13543 13544 return PackageManager.INSTALL_SUCCEEDED; 13545 } 13546 13547 @Override 13548 int doPostCopy(int uid) { 13549 if (isFwdLocked()) { 13550 if (uid < Process.FIRST_APPLICATION_UID 13551 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13552 RES_FILE_NAME)) { 13553 Slog.e(TAG, "Failed to finalize " + cid); 13554 PackageHelper.destroySdDir(cid); 13555 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13556 } 13557 } 13558 13559 return PackageManager.INSTALL_SUCCEEDED; 13560 } 13561 } 13562 13563 /** 13564 * Logic to handle movement of existing installed applications. 13565 */ 13566 class MoveInstallArgs extends InstallArgs { 13567 private File codeFile; 13568 private File resourceFile; 13569 13570 /** New install */ 13571 MoveInstallArgs(InstallParams params) { 13572 super(params.origin, params.move, params.observer, params.installFlags, 13573 params.installerPackageName, params.volumeUuid, 13574 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13575 params.grantedRuntimePermissions, 13576 params.traceMethod, params.traceCookie, params.certificates); 13577 } 13578 13579 int copyApk(IMediaContainerService imcs, boolean temp) { 13580 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13581 + move.fromUuid + " to " + move.toUuid); 13582 synchronized (mInstaller) { 13583 try { 13584 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13585 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13586 } catch (InstallerException e) { 13587 Slog.w(TAG, "Failed to move app", e); 13588 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13589 } 13590 } 13591 13592 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13593 resourceFile = codeFile; 13594 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13595 13596 return PackageManager.INSTALL_SUCCEEDED; 13597 } 13598 13599 int doPreInstall(int status) { 13600 if (status != PackageManager.INSTALL_SUCCEEDED) { 13601 cleanUp(move.toUuid); 13602 } 13603 return status; 13604 } 13605 13606 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13607 if (status != PackageManager.INSTALL_SUCCEEDED) { 13608 cleanUp(move.toUuid); 13609 return false; 13610 } 13611 13612 // Reflect the move in app info 13613 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13614 pkg.setApplicationInfoCodePath(pkg.codePath); 13615 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13616 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13617 pkg.setApplicationInfoResourcePath(pkg.codePath); 13618 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13619 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13620 13621 return true; 13622 } 13623 13624 int doPostInstall(int status, int uid) { 13625 if (status == PackageManager.INSTALL_SUCCEEDED) { 13626 cleanUp(move.fromUuid); 13627 } else { 13628 cleanUp(move.toUuid); 13629 } 13630 return status; 13631 } 13632 13633 @Override 13634 String getCodePath() { 13635 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13636 } 13637 13638 @Override 13639 String getResourcePath() { 13640 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13641 } 13642 13643 private boolean cleanUp(String volumeUuid) { 13644 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13645 move.dataAppName); 13646 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13647 final int[] userIds = sUserManager.getUserIds(); 13648 synchronized (mInstallLock) { 13649 // Clean up both app data and code 13650 // All package moves are frozen until finished 13651 for (int userId : userIds) { 13652 try { 13653 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13654 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13655 } catch (InstallerException e) { 13656 Slog.w(TAG, String.valueOf(e)); 13657 } 13658 } 13659 removeCodePathLI(codeFile); 13660 } 13661 return true; 13662 } 13663 13664 void cleanUpResourcesLI() { 13665 throw new UnsupportedOperationException(); 13666 } 13667 13668 boolean doPostDeleteLI(boolean delete) { 13669 throw new UnsupportedOperationException(); 13670 } 13671 } 13672 13673 static String getAsecPackageName(String packageCid) { 13674 int idx = packageCid.lastIndexOf("-"); 13675 if (idx == -1) { 13676 return packageCid; 13677 } 13678 return packageCid.substring(0, idx); 13679 } 13680 13681 // Utility method used to create code paths based on package name and available index. 13682 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13683 String idxStr = ""; 13684 int idx = 1; 13685 // Fall back to default value of idx=1 if prefix is not 13686 // part of oldCodePath 13687 if (oldCodePath != null) { 13688 String subStr = oldCodePath; 13689 // Drop the suffix right away 13690 if (suffix != null && subStr.endsWith(suffix)) { 13691 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13692 } 13693 // If oldCodePath already contains prefix find out the 13694 // ending index to either increment or decrement. 13695 int sidx = subStr.lastIndexOf(prefix); 13696 if (sidx != -1) { 13697 subStr = subStr.substring(sidx + prefix.length()); 13698 if (subStr != null) { 13699 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13700 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13701 } 13702 try { 13703 idx = Integer.parseInt(subStr); 13704 if (idx <= 1) { 13705 idx++; 13706 } else { 13707 idx--; 13708 } 13709 } catch(NumberFormatException e) { 13710 } 13711 } 13712 } 13713 } 13714 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13715 return prefix + idxStr; 13716 } 13717 13718 private File getNextCodePath(File targetDir, String packageName) { 13719 int suffix = 1; 13720 File result; 13721 do { 13722 result = new File(targetDir, packageName + "-" + suffix); 13723 suffix++; 13724 } while (result.exists()); 13725 return result; 13726 } 13727 13728 // Utility method that returns the relative package path with respect 13729 // to the installation directory. Like say for /data/data/com.test-1.apk 13730 // string com.test-1 is returned. 13731 static String deriveCodePathName(String codePath) { 13732 if (codePath == null) { 13733 return null; 13734 } 13735 final File codeFile = new File(codePath); 13736 final String name = codeFile.getName(); 13737 if (codeFile.isDirectory()) { 13738 return name; 13739 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13740 final int lastDot = name.lastIndexOf('.'); 13741 return name.substring(0, lastDot); 13742 } else { 13743 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13744 return null; 13745 } 13746 } 13747 13748 static class PackageInstalledInfo { 13749 String name; 13750 int uid; 13751 // The set of users that originally had this package installed. 13752 int[] origUsers; 13753 // The set of users that now have this package installed. 13754 int[] newUsers; 13755 PackageParser.Package pkg; 13756 int returnCode; 13757 String returnMsg; 13758 PackageRemovedInfo removedInfo; 13759 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13760 13761 public void setError(int code, String msg) { 13762 setReturnCode(code); 13763 setReturnMessage(msg); 13764 Slog.w(TAG, msg); 13765 } 13766 13767 public void setError(String msg, PackageParserException e) { 13768 setReturnCode(e.error); 13769 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13770 Slog.w(TAG, msg, e); 13771 } 13772 13773 public void setError(String msg, PackageManagerException e) { 13774 returnCode = e.error; 13775 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13776 Slog.w(TAG, msg, e); 13777 } 13778 13779 public void setReturnCode(int returnCode) { 13780 this.returnCode = returnCode; 13781 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13782 for (int i = 0; i < childCount; i++) { 13783 addedChildPackages.valueAt(i).returnCode = returnCode; 13784 } 13785 } 13786 13787 private void setReturnMessage(String returnMsg) { 13788 this.returnMsg = returnMsg; 13789 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13790 for (int i = 0; i < childCount; i++) { 13791 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13792 } 13793 } 13794 13795 // In some error cases we want to convey more info back to the observer 13796 String origPackage; 13797 String origPermission; 13798 } 13799 13800 /* 13801 * Install a non-existing package. 13802 */ 13803 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13804 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13805 PackageInstalledInfo res) { 13806 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13807 13808 // Remember this for later, in case we need to rollback this install 13809 String pkgName = pkg.packageName; 13810 13811 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13812 13813 synchronized(mPackages) { 13814 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13815 // A package with the same name is already installed, though 13816 // it has been renamed to an older name. The package we 13817 // are trying to install should be installed as an update to 13818 // the existing one, but that has not been requested, so bail. 13819 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13820 + " without first uninstalling package running as " 13821 + mSettings.mRenamedPackages.get(pkgName)); 13822 return; 13823 } 13824 if (mPackages.containsKey(pkgName)) { 13825 // Don't allow installation over an existing package with the same name. 13826 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13827 + " without first uninstalling."); 13828 return; 13829 } 13830 } 13831 13832 try { 13833 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13834 System.currentTimeMillis(), user); 13835 13836 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13837 13838 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13839 prepareAppDataAfterInstallLIF(newPackage); 13840 13841 } else { 13842 // Remove package from internal structures, but keep around any 13843 // data that might have already existed 13844 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13845 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13846 } 13847 } catch (PackageManagerException e) { 13848 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13849 } 13850 13851 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13852 } 13853 13854 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13855 // Can't rotate keys during boot or if sharedUser. 13856 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13857 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13858 return false; 13859 } 13860 // app is using upgradeKeySets; make sure all are valid 13861 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13862 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13863 for (int i = 0; i < upgradeKeySets.length; i++) { 13864 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13865 Slog.wtf(TAG, "Package " 13866 + (oldPs.name != null ? oldPs.name : "<null>") 13867 + " contains upgrade-key-set reference to unknown key-set: " 13868 + upgradeKeySets[i] 13869 + " reverting to signatures check."); 13870 return false; 13871 } 13872 } 13873 return true; 13874 } 13875 13876 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13877 // Upgrade keysets are being used. Determine if new package has a superset of the 13878 // required keys. 13879 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13880 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13881 for (int i = 0; i < upgradeKeySets.length; i++) { 13882 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13883 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13884 return true; 13885 } 13886 } 13887 return false; 13888 } 13889 13890 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13891 try (DigestInputStream digestStream = 13892 new DigestInputStream(new FileInputStream(file), digest)) { 13893 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13894 } 13895 } 13896 13897 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13898 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13899 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13900 13901 final PackageParser.Package oldPackage; 13902 final String pkgName = pkg.packageName; 13903 final int[] allUsers; 13904 final int[] installedUsers; 13905 13906 synchronized(mPackages) { 13907 oldPackage = mPackages.get(pkgName); 13908 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13909 13910 // don't allow upgrade to target a release SDK from a pre-release SDK 13911 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13912 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13913 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13914 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13915 if (oldTargetsPreRelease 13916 && !newTargetsPreRelease 13917 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13918 Slog.w(TAG, "Can't install package targeting released sdk"); 13919 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13920 return; 13921 } 13922 13923 // don't allow an upgrade from full to ephemeral 13924 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13925 if (isEphemeral && !oldIsEphemeral) { 13926 // can't downgrade from full to ephemeral 13927 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13928 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13929 return; 13930 } 13931 13932 // verify signatures are valid 13933 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13934 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13935 if (!checkUpgradeKeySetLP(ps, pkg)) { 13936 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13937 "New package not signed by keys specified by upgrade-keysets: " 13938 + pkgName); 13939 return; 13940 } 13941 } else { 13942 // default to original signature matching 13943 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13944 != PackageManager.SIGNATURE_MATCH) { 13945 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13946 "New package has a different signature: " + pkgName); 13947 return; 13948 } 13949 } 13950 13951 // don't allow a system upgrade unless the upgrade hash matches 13952 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13953 byte[] digestBytes = null; 13954 try { 13955 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13956 updateDigest(digest, new File(pkg.baseCodePath)); 13957 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13958 for (String path : pkg.splitCodePaths) { 13959 updateDigest(digest, new File(path)); 13960 } 13961 } 13962 digestBytes = digest.digest(); 13963 } catch (NoSuchAlgorithmException | IOException e) { 13964 res.setError(INSTALL_FAILED_INVALID_APK, 13965 "Could not compute hash: " + pkgName); 13966 return; 13967 } 13968 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13969 res.setError(INSTALL_FAILED_INVALID_APK, 13970 "New package fails restrict-update check: " + pkgName); 13971 return; 13972 } 13973 // retain upgrade restriction 13974 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13975 } 13976 13977 // Check for shared user id changes 13978 String invalidPackageName = 13979 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13980 if (invalidPackageName != null) { 13981 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13982 "Package " + invalidPackageName + " tried to change user " 13983 + oldPackage.mSharedUserId); 13984 return; 13985 } 13986 13987 // In case of rollback, remember per-user/profile install state 13988 allUsers = sUserManager.getUserIds(); 13989 installedUsers = ps.queryInstalledUsers(allUsers, true); 13990 } 13991 13992 // Update what is removed 13993 res.removedInfo = new PackageRemovedInfo(); 13994 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13995 res.removedInfo.removedPackage = oldPackage.packageName; 13996 res.removedInfo.isUpdate = true; 13997 res.removedInfo.origUsers = installedUsers; 13998 final int childCount = (oldPackage.childPackages != null) 13999 ? oldPackage.childPackages.size() : 0; 14000 for (int i = 0; i < childCount; i++) { 14001 boolean childPackageUpdated = false; 14002 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14003 if (res.addedChildPackages != null) { 14004 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14005 if (childRes != null) { 14006 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14007 childRes.removedInfo.removedPackage = childPkg.packageName; 14008 childRes.removedInfo.isUpdate = true; 14009 childPackageUpdated = true; 14010 } 14011 } 14012 if (!childPackageUpdated) { 14013 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14014 childRemovedRes.removedPackage = childPkg.packageName; 14015 childRemovedRes.isUpdate = false; 14016 childRemovedRes.dataRemoved = true; 14017 synchronized (mPackages) { 14018 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14019 if (childPs != null) { 14020 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14021 } 14022 } 14023 if (res.removedInfo.removedChildPackages == null) { 14024 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14025 } 14026 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14027 } 14028 } 14029 14030 boolean sysPkg = (isSystemApp(oldPackage)); 14031 if (sysPkg) { 14032 // Set the system/privileged flags as needed 14033 final boolean privileged = 14034 (oldPackage.applicationInfo.privateFlags 14035 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14036 final int systemPolicyFlags = policyFlags 14037 | PackageParser.PARSE_IS_SYSTEM 14038 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14039 14040 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14041 user, allUsers, installerPackageName, res); 14042 } else { 14043 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14044 user, allUsers, installerPackageName, res); 14045 } 14046 } 14047 14048 public List<String> getPreviousCodePaths(String packageName) { 14049 final PackageSetting ps = mSettings.mPackages.get(packageName); 14050 final List<String> result = new ArrayList<String>(); 14051 if (ps != null && ps.oldCodePaths != null) { 14052 result.addAll(ps.oldCodePaths); 14053 } 14054 return result; 14055 } 14056 14057 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14058 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14059 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14060 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14061 + deletedPackage); 14062 14063 String pkgName = deletedPackage.packageName; 14064 boolean deletedPkg = true; 14065 boolean addedPkg = false; 14066 boolean updatedSettings = false; 14067 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14068 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14069 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14070 14071 final long origUpdateTime = (pkg.mExtras != null) 14072 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14073 14074 // First delete the existing package while retaining the data directory 14075 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14076 res.removedInfo, true, pkg)) { 14077 // If the existing package wasn't successfully deleted 14078 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14079 deletedPkg = false; 14080 } else { 14081 // Successfully deleted the old package; proceed with replace. 14082 14083 // If deleted package lived in a container, give users a chance to 14084 // relinquish resources before killing. 14085 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14086 if (DEBUG_INSTALL) { 14087 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14088 } 14089 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14090 final ArrayList<String> pkgList = new ArrayList<String>(1); 14091 pkgList.add(deletedPackage.applicationInfo.packageName); 14092 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14093 } 14094 14095 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14096 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14097 clearAppProfilesLIF(pkg); 14098 14099 try { 14100 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14101 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14102 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14103 14104 // Update the in-memory copy of the previous code paths. 14105 PackageSetting ps = mSettings.mPackages.get(pkgName); 14106 if (!killApp) { 14107 if (ps.oldCodePaths == null) { 14108 ps.oldCodePaths = new ArraySet<>(); 14109 } 14110 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14111 if (deletedPackage.splitCodePaths != null) { 14112 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14113 } 14114 } else { 14115 ps.oldCodePaths = null; 14116 } 14117 if (ps.childPackageNames != null) { 14118 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14119 final String childPkgName = ps.childPackageNames.get(i); 14120 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14121 childPs.oldCodePaths = ps.oldCodePaths; 14122 } 14123 } 14124 prepareAppDataAfterInstallLIF(newPackage); 14125 addedPkg = true; 14126 } catch (PackageManagerException e) { 14127 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14128 } 14129 } 14130 14131 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14132 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14133 14134 // Revert all internal state mutations and added folders for the failed install 14135 if (addedPkg) { 14136 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14137 res.removedInfo, true, null); 14138 } 14139 14140 // Restore the old package 14141 if (deletedPkg) { 14142 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14143 File restoreFile = new File(deletedPackage.codePath); 14144 // Parse old package 14145 boolean oldExternal = isExternal(deletedPackage); 14146 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14147 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14148 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14149 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14150 try { 14151 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14152 null); 14153 } catch (PackageManagerException e) { 14154 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14155 + e.getMessage()); 14156 return; 14157 } 14158 14159 synchronized (mPackages) { 14160 // Ensure the installer package name up to date 14161 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14162 14163 // Update permissions for restored package 14164 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14165 14166 mSettings.writeLPr(); 14167 } 14168 14169 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14170 } 14171 } else { 14172 synchronized (mPackages) { 14173 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14174 if (ps != null) { 14175 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14176 if (res.removedInfo.removedChildPackages != null) { 14177 final int childCount = res.removedInfo.removedChildPackages.size(); 14178 // Iterate in reverse as we may modify the collection 14179 for (int i = childCount - 1; i >= 0; i--) { 14180 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14181 if (res.addedChildPackages.containsKey(childPackageName)) { 14182 res.removedInfo.removedChildPackages.removeAt(i); 14183 } else { 14184 PackageRemovedInfo childInfo = res.removedInfo 14185 .removedChildPackages.valueAt(i); 14186 childInfo.removedForAllUsers = mPackages.get( 14187 childInfo.removedPackage) == null; 14188 } 14189 } 14190 } 14191 } 14192 } 14193 } 14194 } 14195 14196 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14197 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14198 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14199 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14200 + ", old=" + deletedPackage); 14201 14202 final boolean disabledSystem; 14203 14204 // Remove existing system package 14205 removePackageLI(deletedPackage, true); 14206 14207 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14208 if (!disabledSystem) { 14209 // We didn't need to disable the .apk as a current system package, 14210 // which means we are replacing another update that is already 14211 // installed. We need to make sure to delete the older one's .apk. 14212 res.removedInfo.args = createInstallArgsForExisting(0, 14213 deletedPackage.applicationInfo.getCodePath(), 14214 deletedPackage.applicationInfo.getResourcePath(), 14215 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14216 } else { 14217 res.removedInfo.args = null; 14218 } 14219 14220 // Successfully disabled the old package. Now proceed with re-installation 14221 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14222 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14223 clearAppProfilesLIF(pkg); 14224 14225 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14226 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14227 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14228 14229 PackageParser.Package newPackage = null; 14230 try { 14231 // Add the package to the internal data structures 14232 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14233 14234 // Set the update and install times 14235 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14236 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14237 System.currentTimeMillis()); 14238 14239 // Update the package dynamic state if succeeded 14240 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14241 // Now that the install succeeded make sure we remove data 14242 // directories for any child package the update removed. 14243 final int deletedChildCount = (deletedPackage.childPackages != null) 14244 ? deletedPackage.childPackages.size() : 0; 14245 final int newChildCount = (newPackage.childPackages != null) 14246 ? newPackage.childPackages.size() : 0; 14247 for (int i = 0; i < deletedChildCount; i++) { 14248 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14249 boolean childPackageDeleted = true; 14250 for (int j = 0; j < newChildCount; j++) { 14251 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14252 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14253 childPackageDeleted = false; 14254 break; 14255 } 14256 } 14257 if (childPackageDeleted) { 14258 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14259 deletedChildPkg.packageName); 14260 if (ps != null && res.removedInfo.removedChildPackages != null) { 14261 PackageRemovedInfo removedChildRes = res.removedInfo 14262 .removedChildPackages.get(deletedChildPkg.packageName); 14263 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14264 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14265 } 14266 } 14267 } 14268 14269 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14270 prepareAppDataAfterInstallLIF(newPackage); 14271 } 14272 } catch (PackageManagerException e) { 14273 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14274 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14275 } 14276 14277 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14278 // Re installation failed. Restore old information 14279 // Remove new pkg information 14280 if (newPackage != null) { 14281 removeInstalledPackageLI(newPackage, true); 14282 } 14283 // Add back the old system package 14284 try { 14285 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14286 } catch (PackageManagerException e) { 14287 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14288 } 14289 14290 synchronized (mPackages) { 14291 if (disabledSystem) { 14292 enableSystemPackageLPw(deletedPackage); 14293 } 14294 14295 // Ensure the installer package name up to date 14296 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14297 14298 // Update permissions for restored package 14299 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14300 14301 mSettings.writeLPr(); 14302 } 14303 14304 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14305 + " after failed upgrade"); 14306 } 14307 } 14308 14309 /** 14310 * Checks whether the parent or any of the child packages have a change shared 14311 * user. For a package to be a valid update the shred users of the parent and 14312 * the children should match. We may later support changing child shared users. 14313 * @param oldPkg The updated package. 14314 * @param newPkg The update package. 14315 * @return The shared user that change between the versions. 14316 */ 14317 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14318 PackageParser.Package newPkg) { 14319 // Check parent shared user 14320 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14321 return newPkg.packageName; 14322 } 14323 // Check child shared users 14324 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14325 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14326 for (int i = 0; i < newChildCount; i++) { 14327 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14328 // If this child was present, did it have the same shared user? 14329 for (int j = 0; j < oldChildCount; j++) { 14330 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14331 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14332 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14333 return newChildPkg.packageName; 14334 } 14335 } 14336 } 14337 return null; 14338 } 14339 14340 private void removeNativeBinariesLI(PackageSetting ps) { 14341 // Remove the lib path for the parent package 14342 if (ps != null) { 14343 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14344 // Remove the lib path for the child packages 14345 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14346 for (int i = 0; i < childCount; i++) { 14347 PackageSetting childPs = null; 14348 synchronized (mPackages) { 14349 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14350 } 14351 if (childPs != null) { 14352 NativeLibraryHelper.removeNativeBinariesLI(childPs 14353 .legacyNativeLibraryPathString); 14354 } 14355 } 14356 } 14357 } 14358 14359 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14360 // Enable the parent package 14361 mSettings.enableSystemPackageLPw(pkg.packageName); 14362 // Enable the child packages 14363 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14364 for (int i = 0; i < childCount; i++) { 14365 PackageParser.Package childPkg = pkg.childPackages.get(i); 14366 mSettings.enableSystemPackageLPw(childPkg.packageName); 14367 } 14368 } 14369 14370 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14371 PackageParser.Package newPkg) { 14372 // Disable the parent package (parent always replaced) 14373 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14374 // Disable the child packages 14375 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14376 for (int i = 0; i < childCount; i++) { 14377 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14378 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14379 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14380 } 14381 return disabled; 14382 } 14383 14384 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14385 String installerPackageName) { 14386 // Enable the parent package 14387 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14388 // Enable the child packages 14389 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14390 for (int i = 0; i < childCount; i++) { 14391 PackageParser.Package childPkg = pkg.childPackages.get(i); 14392 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14393 } 14394 } 14395 14396 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14397 // Collect all used permissions in the UID 14398 ArraySet<String> usedPermissions = new ArraySet<>(); 14399 final int packageCount = su.packages.size(); 14400 for (int i = 0; i < packageCount; i++) { 14401 PackageSetting ps = su.packages.valueAt(i); 14402 if (ps.pkg == null) { 14403 continue; 14404 } 14405 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14406 for (int j = 0; j < requestedPermCount; j++) { 14407 String permission = ps.pkg.requestedPermissions.get(j); 14408 BasePermission bp = mSettings.mPermissions.get(permission); 14409 if (bp != null) { 14410 usedPermissions.add(permission); 14411 } 14412 } 14413 } 14414 14415 PermissionsState permissionsState = su.getPermissionsState(); 14416 // Prune install permissions 14417 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14418 final int installPermCount = installPermStates.size(); 14419 for (int i = installPermCount - 1; i >= 0; i--) { 14420 PermissionState permissionState = installPermStates.get(i); 14421 if (!usedPermissions.contains(permissionState.getName())) { 14422 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14423 if (bp != null) { 14424 permissionsState.revokeInstallPermission(bp); 14425 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14426 PackageManager.MASK_PERMISSION_FLAGS, 0); 14427 } 14428 } 14429 } 14430 14431 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14432 14433 // Prune runtime permissions 14434 for (int userId : allUserIds) { 14435 List<PermissionState> runtimePermStates = permissionsState 14436 .getRuntimePermissionStates(userId); 14437 final int runtimePermCount = runtimePermStates.size(); 14438 for (int i = runtimePermCount - 1; i >= 0; i--) { 14439 PermissionState permissionState = runtimePermStates.get(i); 14440 if (!usedPermissions.contains(permissionState.getName())) { 14441 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14442 if (bp != null) { 14443 permissionsState.revokeRuntimePermission(bp, userId); 14444 permissionsState.updatePermissionFlags(bp, userId, 14445 PackageManager.MASK_PERMISSION_FLAGS, 0); 14446 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14447 runtimePermissionChangedUserIds, userId); 14448 } 14449 } 14450 } 14451 } 14452 14453 return runtimePermissionChangedUserIds; 14454 } 14455 14456 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14457 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14458 // Update the parent package setting 14459 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14460 res, user); 14461 // Update the child packages setting 14462 final int childCount = (newPackage.childPackages != null) 14463 ? newPackage.childPackages.size() : 0; 14464 for (int i = 0; i < childCount; i++) { 14465 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14466 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14467 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14468 childRes.origUsers, childRes, user); 14469 } 14470 } 14471 14472 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14473 String installerPackageName, int[] allUsers, int[] installedForUsers, 14474 PackageInstalledInfo res, UserHandle user) { 14475 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14476 14477 String pkgName = newPackage.packageName; 14478 synchronized (mPackages) { 14479 //write settings. the installStatus will be incomplete at this stage. 14480 //note that the new package setting would have already been 14481 //added to mPackages. It hasn't been persisted yet. 14482 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14483 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14484 mSettings.writeLPr(); 14485 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14486 } 14487 14488 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14489 synchronized (mPackages) { 14490 updatePermissionsLPw(newPackage.packageName, newPackage, 14491 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14492 ? UPDATE_PERMISSIONS_ALL : 0)); 14493 // For system-bundled packages, we assume that installing an upgraded version 14494 // of the package implies that the user actually wants to run that new code, 14495 // so we enable the package. 14496 PackageSetting ps = mSettings.mPackages.get(pkgName); 14497 final int userId = user.getIdentifier(); 14498 if (ps != null) { 14499 if (isSystemApp(newPackage)) { 14500 if (DEBUG_INSTALL) { 14501 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14502 } 14503 // Enable system package for requested users 14504 if (res.origUsers != null) { 14505 for (int origUserId : res.origUsers) { 14506 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14507 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14508 origUserId, installerPackageName); 14509 } 14510 } 14511 } 14512 // Also convey the prior install/uninstall state 14513 if (allUsers != null && installedForUsers != null) { 14514 for (int currentUserId : allUsers) { 14515 final boolean installed = ArrayUtils.contains( 14516 installedForUsers, currentUserId); 14517 if (DEBUG_INSTALL) { 14518 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14519 } 14520 ps.setInstalled(installed, currentUserId); 14521 } 14522 // these install state changes will be persisted in the 14523 // upcoming call to mSettings.writeLPr(). 14524 } 14525 } 14526 // It's implied that when a user requests installation, they want the app to be 14527 // installed and enabled. 14528 if (userId != UserHandle.USER_ALL) { 14529 ps.setInstalled(true, userId); 14530 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14531 } 14532 } 14533 res.name = pkgName; 14534 res.uid = newPackage.applicationInfo.uid; 14535 res.pkg = newPackage; 14536 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14537 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14538 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14539 //to update install status 14540 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14541 mSettings.writeLPr(); 14542 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14543 } 14544 14545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14546 } 14547 14548 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14549 try { 14550 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14551 installPackageLI(args, res); 14552 } finally { 14553 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14554 } 14555 } 14556 14557 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14558 final int installFlags = args.installFlags; 14559 final String installerPackageName = args.installerPackageName; 14560 final String volumeUuid = args.volumeUuid; 14561 final File tmpPackageFile = new File(args.getCodePath()); 14562 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14563 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14564 || (args.volumeUuid != null)); 14565 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14566 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14567 boolean replace = false; 14568 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14569 if (args.move != null) { 14570 // moving a complete application; perform an initial scan on the new install location 14571 scanFlags |= SCAN_INITIAL; 14572 } 14573 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14574 scanFlags |= SCAN_DONT_KILL_APP; 14575 } 14576 14577 // Result object to be returned 14578 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14579 14580 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14581 14582 // Sanity check 14583 if (ephemeral && (forwardLocked || onExternal)) { 14584 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14585 + " external=" + onExternal); 14586 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14587 return; 14588 } 14589 14590 // Retrieve PackageSettings and parse package 14591 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14592 | PackageParser.PARSE_ENFORCE_CODE 14593 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14594 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14595 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14596 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14597 PackageParser pp = new PackageParser(); 14598 pp.setSeparateProcesses(mSeparateProcesses); 14599 pp.setDisplayMetrics(mMetrics); 14600 14601 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14602 final PackageParser.Package pkg; 14603 try { 14604 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14605 } catch (PackageParserException e) { 14606 res.setError("Failed parse during installPackageLI", e); 14607 return; 14608 } finally { 14609 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14610 } 14611 14612 // If we are installing a clustered package add results for the children 14613 if (pkg.childPackages != null) { 14614 synchronized (mPackages) { 14615 final int childCount = pkg.childPackages.size(); 14616 for (int i = 0; i < childCount; i++) { 14617 PackageParser.Package childPkg = pkg.childPackages.get(i); 14618 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14619 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14620 childRes.pkg = childPkg; 14621 childRes.name = childPkg.packageName; 14622 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14623 if (childPs != null) { 14624 childRes.origUsers = childPs.queryInstalledUsers( 14625 sUserManager.getUserIds(), true); 14626 } 14627 if ((mPackages.containsKey(childPkg.packageName))) { 14628 childRes.removedInfo = new PackageRemovedInfo(); 14629 childRes.removedInfo.removedPackage = childPkg.packageName; 14630 } 14631 if (res.addedChildPackages == null) { 14632 res.addedChildPackages = new ArrayMap<>(); 14633 } 14634 res.addedChildPackages.put(childPkg.packageName, childRes); 14635 } 14636 } 14637 } 14638 14639 // If package doesn't declare API override, mark that we have an install 14640 // time CPU ABI override. 14641 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14642 pkg.cpuAbiOverride = args.abiOverride; 14643 } 14644 14645 String pkgName = res.name = pkg.packageName; 14646 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14647 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14648 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14649 return; 14650 } 14651 } 14652 14653 try { 14654 // either use what we've been given or parse directly from the APK 14655 if (args.certificates != null) { 14656 try { 14657 PackageParser.populateCertificates(pkg, args.certificates); 14658 } catch (PackageParserException e) { 14659 // there was something wrong with the certificates we were given; 14660 // try to pull them from the APK 14661 PackageParser.collectCertificates(pkg, parseFlags); 14662 } 14663 } else { 14664 PackageParser.collectCertificates(pkg, parseFlags); 14665 } 14666 } catch (PackageParserException e) { 14667 res.setError("Failed collect during installPackageLI", e); 14668 return; 14669 } 14670 14671 // Get rid of all references to package scan path via parser. 14672 pp = null; 14673 String oldCodePath = null; 14674 boolean systemApp = false; 14675 synchronized (mPackages) { 14676 // Check if installing already existing package 14677 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14678 String oldName = mSettings.mRenamedPackages.get(pkgName); 14679 if (pkg.mOriginalPackages != null 14680 && pkg.mOriginalPackages.contains(oldName) 14681 && mPackages.containsKey(oldName)) { 14682 // This package is derived from an original package, 14683 // and this device has been updating from that original 14684 // name. We must continue using the original name, so 14685 // rename the new package here. 14686 pkg.setPackageName(oldName); 14687 pkgName = pkg.packageName; 14688 replace = true; 14689 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14690 + oldName + " pkgName=" + pkgName); 14691 } else if (mPackages.containsKey(pkgName)) { 14692 // This package, under its official name, already exists 14693 // on the device; we should replace it. 14694 replace = true; 14695 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14696 } 14697 14698 // Child packages are installed through the parent package 14699 if (pkg.parentPackage != null) { 14700 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14701 "Package " + pkg.packageName + " is child of package " 14702 + pkg.parentPackage.parentPackage + ". Child packages " 14703 + "can be updated only through the parent package."); 14704 return; 14705 } 14706 14707 if (replace) { 14708 // Prevent apps opting out from runtime permissions 14709 PackageParser.Package oldPackage = mPackages.get(pkgName); 14710 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14711 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14712 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14713 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14714 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14715 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14716 + " doesn't support runtime permissions but the old" 14717 + " target SDK " + oldTargetSdk + " does."); 14718 return; 14719 } 14720 14721 // Prevent installing of child packages 14722 if (oldPackage.parentPackage != null) { 14723 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14724 "Package " + pkg.packageName + " is child of package " 14725 + oldPackage.parentPackage + ". Child packages " 14726 + "can be updated only through the parent package."); 14727 return; 14728 } 14729 } 14730 } 14731 14732 PackageSetting ps = mSettings.mPackages.get(pkgName); 14733 if (ps != null) { 14734 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14735 14736 // Quick sanity check that we're signed correctly if updating; 14737 // we'll check this again later when scanning, but we want to 14738 // bail early here before tripping over redefined permissions. 14739 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14740 if (!checkUpgradeKeySetLP(ps, pkg)) { 14741 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14742 + pkg.packageName + " upgrade keys do not match the " 14743 + "previously installed version"); 14744 return; 14745 } 14746 } else { 14747 try { 14748 verifySignaturesLP(ps, pkg); 14749 } catch (PackageManagerException e) { 14750 res.setError(e.error, e.getMessage()); 14751 return; 14752 } 14753 } 14754 14755 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14756 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14757 systemApp = (ps.pkg.applicationInfo.flags & 14758 ApplicationInfo.FLAG_SYSTEM) != 0; 14759 } 14760 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14761 } 14762 14763 // Check whether the newly-scanned package wants to define an already-defined perm 14764 int N = pkg.permissions.size(); 14765 for (int i = N-1; i >= 0; i--) { 14766 PackageParser.Permission perm = pkg.permissions.get(i); 14767 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14768 if (bp != null) { 14769 // If the defining package is signed with our cert, it's okay. This 14770 // also includes the "updating the same package" case, of course. 14771 // "updating same package" could also involve key-rotation. 14772 final boolean sigsOk; 14773 if (bp.sourcePackage.equals(pkg.packageName) 14774 && (bp.packageSetting instanceof PackageSetting) 14775 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14776 scanFlags))) { 14777 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14778 } else { 14779 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14780 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14781 } 14782 if (!sigsOk) { 14783 // If the owning package is the system itself, we log but allow 14784 // install to proceed; we fail the install on all other permission 14785 // redefinitions. 14786 if (!bp.sourcePackage.equals("android")) { 14787 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14788 + pkg.packageName + " attempting to redeclare permission " 14789 + perm.info.name + " already owned by " + bp.sourcePackage); 14790 res.origPermission = perm.info.name; 14791 res.origPackage = bp.sourcePackage; 14792 return; 14793 } else { 14794 Slog.w(TAG, "Package " + pkg.packageName 14795 + " attempting to redeclare system permission " 14796 + perm.info.name + "; ignoring new declaration"); 14797 pkg.permissions.remove(i); 14798 } 14799 } 14800 } 14801 } 14802 } 14803 14804 if (systemApp) { 14805 if (onExternal) { 14806 // Abort update; system app can't be replaced with app on sdcard 14807 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14808 "Cannot install updates to system apps on sdcard"); 14809 return; 14810 } else if (ephemeral) { 14811 // Abort update; system app can't be replaced with an ephemeral app 14812 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14813 "Cannot update a system app with an ephemeral app"); 14814 return; 14815 } 14816 } 14817 14818 if (args.move != null) { 14819 // We did an in-place move, so dex is ready to roll 14820 scanFlags |= SCAN_NO_DEX; 14821 scanFlags |= SCAN_MOVE; 14822 14823 synchronized (mPackages) { 14824 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14825 if (ps == null) { 14826 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14827 "Missing settings for moved package " + pkgName); 14828 } 14829 14830 // We moved the entire application as-is, so bring over the 14831 // previously derived ABI information. 14832 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14833 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14834 } 14835 14836 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14837 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14838 scanFlags |= SCAN_NO_DEX; 14839 14840 try { 14841 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14842 args.abiOverride : pkg.cpuAbiOverride); 14843 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14844 true /* extract libs */); 14845 } catch (PackageManagerException pme) { 14846 Slog.e(TAG, "Error deriving application ABI", pme); 14847 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14848 return; 14849 } 14850 14851 // Shared libraries for the package need to be updated. 14852 synchronized (mPackages) { 14853 try { 14854 updateSharedLibrariesLPw(pkg, null); 14855 } catch (PackageManagerException e) { 14856 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14857 } 14858 } 14859 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14860 // Do not run PackageDexOptimizer through the local performDexOpt 14861 // method because `pkg` is not in `mPackages` yet. 14862 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14863 null /* instructionSets */, false /* checkProfiles */, 14864 getCompilerFilterForReason(REASON_INSTALL)); 14865 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14866 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14867 String msg = "Extracting package failed for " + pkgName; 14868 res.setError(INSTALL_FAILED_DEXOPT, msg); 14869 return; 14870 } 14871 14872 // Notify BackgroundDexOptService that the package has been changed. 14873 // If this is an update of a package which used to fail to compile, 14874 // BDOS will remove it from its blacklist. 14875 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14876 } 14877 14878 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14879 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14880 return; 14881 } 14882 14883 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14884 14885 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14886 "installPackageLI")) { 14887 if (replace) { 14888 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14889 installerPackageName, res); 14890 } else { 14891 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14892 args.user, installerPackageName, volumeUuid, res); 14893 } 14894 } 14895 synchronized (mPackages) { 14896 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14897 if (ps != null) { 14898 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14899 } 14900 14901 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14902 for (int i = 0; i < childCount; i++) { 14903 PackageParser.Package childPkg = pkg.childPackages.get(i); 14904 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14905 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14906 if (childPs != null) { 14907 childRes.newUsers = childPs.queryInstalledUsers( 14908 sUserManager.getUserIds(), true); 14909 } 14910 } 14911 } 14912 } 14913 14914 private void startIntentFilterVerifications(int userId, boolean replacing, 14915 PackageParser.Package pkg) { 14916 if (mIntentFilterVerifierComponent == null) { 14917 Slog.w(TAG, "No IntentFilter verification will not be done as " 14918 + "there is no IntentFilterVerifier available!"); 14919 return; 14920 } 14921 14922 final int verifierUid = getPackageUid( 14923 mIntentFilterVerifierComponent.getPackageName(), 14924 MATCH_DEBUG_TRIAGED_MISSING, 14925 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14926 14927 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14928 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14929 mHandler.sendMessage(msg); 14930 14931 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14932 for (int i = 0; i < childCount; i++) { 14933 PackageParser.Package childPkg = pkg.childPackages.get(i); 14934 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14935 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14936 mHandler.sendMessage(msg); 14937 } 14938 } 14939 14940 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14941 PackageParser.Package pkg) { 14942 int size = pkg.activities.size(); 14943 if (size == 0) { 14944 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14945 "No activity, so no need to verify any IntentFilter!"); 14946 return; 14947 } 14948 14949 final boolean hasDomainURLs = hasDomainURLs(pkg); 14950 if (!hasDomainURLs) { 14951 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14952 "No domain URLs, so no need to verify any IntentFilter!"); 14953 return; 14954 } 14955 14956 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14957 + " if any IntentFilter from the " + size 14958 + " Activities needs verification ..."); 14959 14960 int count = 0; 14961 final String packageName = pkg.packageName; 14962 14963 synchronized (mPackages) { 14964 // If this is a new install and we see that we've already run verification for this 14965 // package, we have nothing to do: it means the state was restored from backup. 14966 if (!replacing) { 14967 IntentFilterVerificationInfo ivi = 14968 mSettings.getIntentFilterVerificationLPr(packageName); 14969 if (ivi != null) { 14970 if (DEBUG_DOMAIN_VERIFICATION) { 14971 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14972 + ivi.getStatusString()); 14973 } 14974 return; 14975 } 14976 } 14977 14978 // If any filters need to be verified, then all need to be. 14979 boolean needToVerify = false; 14980 for (PackageParser.Activity a : pkg.activities) { 14981 for (ActivityIntentInfo filter : a.intents) { 14982 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14983 if (DEBUG_DOMAIN_VERIFICATION) { 14984 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14985 } 14986 needToVerify = true; 14987 break; 14988 } 14989 } 14990 } 14991 14992 if (needToVerify) { 14993 final int verificationId = mIntentFilterVerificationToken++; 14994 for (PackageParser.Activity a : pkg.activities) { 14995 for (ActivityIntentInfo filter : a.intents) { 14996 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14997 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14998 "Verification needed for IntentFilter:" + filter.toString()); 14999 mIntentFilterVerifier.addOneIntentFilterVerification( 15000 verifierUid, userId, verificationId, filter, packageName); 15001 count++; 15002 } 15003 } 15004 } 15005 } 15006 } 15007 15008 if (count > 0) { 15009 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15010 + " IntentFilter verification" + (count > 1 ? "s" : "") 15011 + " for userId:" + userId); 15012 mIntentFilterVerifier.startVerifications(userId); 15013 } else { 15014 if (DEBUG_DOMAIN_VERIFICATION) { 15015 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15016 } 15017 } 15018 } 15019 15020 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15021 final ComponentName cn = filter.activity.getComponentName(); 15022 final String packageName = cn.getPackageName(); 15023 15024 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15025 packageName); 15026 if (ivi == null) { 15027 return true; 15028 } 15029 int status = ivi.getStatus(); 15030 switch (status) { 15031 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15032 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15033 return true; 15034 15035 default: 15036 // Nothing to do 15037 return false; 15038 } 15039 } 15040 15041 private static boolean isMultiArch(ApplicationInfo info) { 15042 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15043 } 15044 15045 private static boolean isExternal(PackageParser.Package pkg) { 15046 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15047 } 15048 15049 private static boolean isExternal(PackageSetting ps) { 15050 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15051 } 15052 15053 private static boolean isEphemeral(PackageParser.Package pkg) { 15054 return pkg.applicationInfo.isEphemeralApp(); 15055 } 15056 15057 private static boolean isEphemeral(PackageSetting ps) { 15058 return ps.pkg != null && isEphemeral(ps.pkg); 15059 } 15060 15061 private static boolean isSystemApp(PackageParser.Package pkg) { 15062 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15063 } 15064 15065 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15066 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15067 } 15068 15069 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15070 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15071 } 15072 15073 private static boolean isSystemApp(PackageSetting ps) { 15074 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15075 } 15076 15077 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15078 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15079 } 15080 15081 private int packageFlagsToInstallFlags(PackageSetting ps) { 15082 int installFlags = 0; 15083 if (isEphemeral(ps)) { 15084 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15085 } 15086 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15087 // This existing package was an external ASEC install when we have 15088 // the external flag without a UUID 15089 installFlags |= PackageManager.INSTALL_EXTERNAL; 15090 } 15091 if (ps.isForwardLocked()) { 15092 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15093 } 15094 return installFlags; 15095 } 15096 15097 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15098 if (isExternal(pkg)) { 15099 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15100 return StorageManager.UUID_PRIMARY_PHYSICAL; 15101 } else { 15102 return pkg.volumeUuid; 15103 } 15104 } else { 15105 return StorageManager.UUID_PRIVATE_INTERNAL; 15106 } 15107 } 15108 15109 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15110 if (isExternal(pkg)) { 15111 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15112 return mSettings.getExternalVersion(); 15113 } else { 15114 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15115 } 15116 } else { 15117 return mSettings.getInternalVersion(); 15118 } 15119 } 15120 15121 private void deleteTempPackageFiles() { 15122 final FilenameFilter filter = new FilenameFilter() { 15123 public boolean accept(File dir, String name) { 15124 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15125 } 15126 }; 15127 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15128 file.delete(); 15129 } 15130 } 15131 15132 @Override 15133 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15134 int flags) { 15135 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15136 flags); 15137 } 15138 15139 @Override 15140 public void deletePackage(final String packageName, 15141 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15142 mContext.enforceCallingOrSelfPermission( 15143 android.Manifest.permission.DELETE_PACKAGES, null); 15144 Preconditions.checkNotNull(packageName); 15145 Preconditions.checkNotNull(observer); 15146 final int uid = Binder.getCallingUid(); 15147 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15148 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15149 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15150 mContext.enforceCallingOrSelfPermission( 15151 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15152 "deletePackage for user " + userId); 15153 } 15154 15155 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15156 try { 15157 observer.onPackageDeleted(packageName, 15158 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15159 } catch (RemoteException re) { 15160 } 15161 return; 15162 } 15163 15164 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15165 try { 15166 observer.onPackageDeleted(packageName, 15167 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15168 } catch (RemoteException re) { 15169 } 15170 return; 15171 } 15172 15173 if (DEBUG_REMOVE) { 15174 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15175 + " deleteAllUsers: " + deleteAllUsers ); 15176 } 15177 // Queue up an async operation since the package deletion may take a little while. 15178 mHandler.post(new Runnable() { 15179 public void run() { 15180 mHandler.removeCallbacks(this); 15181 int returnCode; 15182 if (!deleteAllUsers) { 15183 returnCode = deletePackageX(packageName, userId, deleteFlags); 15184 } else { 15185 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15186 // If nobody is blocking uninstall, proceed with delete for all users 15187 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15188 returnCode = deletePackageX(packageName, userId, deleteFlags); 15189 } else { 15190 // Otherwise uninstall individually for users with blockUninstalls=false 15191 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15192 for (int userId : users) { 15193 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15194 returnCode = deletePackageX(packageName, userId, userFlags); 15195 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15196 Slog.w(TAG, "Package delete failed for user " + userId 15197 + ", returnCode " + returnCode); 15198 } 15199 } 15200 } 15201 // The app has only been marked uninstalled for certain users. 15202 // We still need to report that delete was blocked 15203 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15204 } 15205 } 15206 try { 15207 observer.onPackageDeleted(packageName, returnCode, null); 15208 } catch (RemoteException e) { 15209 Log.i(TAG, "Observer no longer exists."); 15210 } //end catch 15211 } //end run 15212 }); 15213 } 15214 15215 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15216 int[] result = EMPTY_INT_ARRAY; 15217 for (int userId : userIds) { 15218 if (getBlockUninstallForUser(packageName, userId)) { 15219 result = ArrayUtils.appendInt(result, userId); 15220 } 15221 } 15222 return result; 15223 } 15224 15225 @Override 15226 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15227 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15228 } 15229 15230 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15231 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15232 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15233 try { 15234 if (dpm != null) { 15235 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15236 /* callingUserOnly =*/ false); 15237 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15238 : deviceOwnerComponentName.getPackageName(); 15239 // Does the package contains the device owner? 15240 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15241 // this check is probably not needed, since DO should be registered as a device 15242 // admin on some user too. (Original bug for this: b/17657954) 15243 if (packageName.equals(deviceOwnerPackageName)) { 15244 return true; 15245 } 15246 // Does it contain a device admin for any user? 15247 int[] users; 15248 if (userId == UserHandle.USER_ALL) { 15249 users = sUserManager.getUserIds(); 15250 } else { 15251 users = new int[]{userId}; 15252 } 15253 for (int i = 0; i < users.length; ++i) { 15254 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15255 return true; 15256 } 15257 } 15258 } 15259 } catch (RemoteException e) { 15260 } 15261 return false; 15262 } 15263 15264 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15265 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15266 } 15267 15268 /** 15269 * This method is an internal method that could be get invoked either 15270 * to delete an installed package or to clean up a failed installation. 15271 * After deleting an installed package, a broadcast is sent to notify any 15272 * listeners that the package has been removed. For cleaning up a failed 15273 * installation, the broadcast is not necessary since the package's 15274 * installation wouldn't have sent the initial broadcast either 15275 * The key steps in deleting a package are 15276 * deleting the package information in internal structures like mPackages, 15277 * deleting the packages base directories through installd 15278 * updating mSettings to reflect current status 15279 * persisting settings for later use 15280 * sending a broadcast if necessary 15281 */ 15282 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15283 final PackageRemovedInfo info = new PackageRemovedInfo(); 15284 final boolean res; 15285 15286 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15287 ? UserHandle.ALL : new UserHandle(userId); 15288 15289 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15290 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15291 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15292 } 15293 15294 PackageSetting uninstalledPs = null; 15295 15296 // for the uninstall-updates case and restricted profiles, remember the per- 15297 // user handle installed state 15298 int[] allUsers; 15299 synchronized (mPackages) { 15300 uninstalledPs = mSettings.mPackages.get(packageName); 15301 if (uninstalledPs == null) { 15302 Slog.w(TAG, "Not removing non-existent package " + packageName); 15303 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15304 } 15305 allUsers = sUserManager.getUserIds(); 15306 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15307 } 15308 15309 synchronized (mInstallLock) { 15310 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15311 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15312 "deletePackageX")) { 15313 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15314 deleteFlags | REMOVE_CHATTY, info, true, null); 15315 } 15316 synchronized (mPackages) { 15317 if (res) { 15318 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15319 } 15320 } 15321 } 15322 15323 if (res) { 15324 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15325 info.sendPackageRemovedBroadcasts(killApp); 15326 info.sendSystemPackageUpdatedBroadcasts(); 15327 info.sendSystemPackageAppearedBroadcasts(); 15328 } 15329 // Force a gc here. 15330 Runtime.getRuntime().gc(); 15331 // Delete the resources here after sending the broadcast to let 15332 // other processes clean up before deleting resources. 15333 if (info.args != null) { 15334 synchronized (mInstallLock) { 15335 info.args.doPostDeleteLI(true); 15336 } 15337 } 15338 15339 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15340 } 15341 15342 class PackageRemovedInfo { 15343 String removedPackage; 15344 int uid = -1; 15345 int removedAppId = -1; 15346 int[] origUsers; 15347 int[] removedUsers = null; 15348 boolean isRemovedPackageSystemUpdate = false; 15349 boolean isUpdate; 15350 boolean dataRemoved; 15351 boolean removedForAllUsers; 15352 // Clean up resources deleted packages. 15353 InstallArgs args = null; 15354 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15355 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15356 15357 void sendPackageRemovedBroadcasts(boolean killApp) { 15358 sendPackageRemovedBroadcastInternal(killApp); 15359 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15360 for (int i = 0; i < childCount; i++) { 15361 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15362 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15363 } 15364 } 15365 15366 void sendSystemPackageUpdatedBroadcasts() { 15367 if (isRemovedPackageSystemUpdate) { 15368 sendSystemPackageUpdatedBroadcastsInternal(); 15369 final int childCount = (removedChildPackages != null) 15370 ? removedChildPackages.size() : 0; 15371 for (int i = 0; i < childCount; i++) { 15372 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15373 if (childInfo.isRemovedPackageSystemUpdate) { 15374 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15375 } 15376 } 15377 } 15378 } 15379 15380 void sendSystemPackageAppearedBroadcasts() { 15381 final int packageCount = (appearedChildPackages != null) 15382 ? appearedChildPackages.size() : 0; 15383 for (int i = 0; i < packageCount; i++) { 15384 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15385 for (int userId : installedInfo.newUsers) { 15386 sendPackageAddedForUser(installedInfo.name, true, 15387 UserHandle.getAppId(installedInfo.uid), userId); 15388 } 15389 } 15390 } 15391 15392 private void sendSystemPackageUpdatedBroadcastsInternal() { 15393 Bundle extras = new Bundle(2); 15394 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15395 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15396 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15397 extras, 0, null, null, null); 15398 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15399 extras, 0, null, null, null); 15400 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15401 null, 0, removedPackage, null, null); 15402 } 15403 15404 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15405 Bundle extras = new Bundle(2); 15406 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15407 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15408 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15409 if (isUpdate || isRemovedPackageSystemUpdate) { 15410 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15411 } 15412 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15413 if (removedPackage != null) { 15414 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15415 extras, 0, null, null, removedUsers); 15416 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15417 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15418 removedPackage, extras, 0, null, null, removedUsers); 15419 } 15420 } 15421 if (removedAppId >= 0) { 15422 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15423 removedUsers); 15424 } 15425 } 15426 } 15427 15428 /* 15429 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15430 * flag is not set, the data directory is removed as well. 15431 * make sure this flag is set for partially installed apps. If not its meaningless to 15432 * delete a partially installed application. 15433 */ 15434 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15435 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15436 String packageName = ps.name; 15437 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15438 // Retrieve object to delete permissions for shared user later on 15439 final PackageParser.Package deletedPkg; 15440 final PackageSetting deletedPs; 15441 // reader 15442 synchronized (mPackages) { 15443 deletedPkg = mPackages.get(packageName); 15444 deletedPs = mSettings.mPackages.get(packageName); 15445 if (outInfo != null) { 15446 outInfo.removedPackage = packageName; 15447 outInfo.removedUsers = deletedPs != null 15448 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15449 : null; 15450 } 15451 } 15452 15453 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15454 15455 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15456 final PackageParser.Package resolvedPkg; 15457 if (deletedPkg != null) { 15458 resolvedPkg = deletedPkg; 15459 } else { 15460 // We don't have a parsed package when it lives on an ejected 15461 // adopted storage device, so fake something together 15462 resolvedPkg = new PackageParser.Package(ps.name); 15463 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15464 } 15465 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15466 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15467 destroyAppProfilesLIF(resolvedPkg); 15468 if (outInfo != null) { 15469 outInfo.dataRemoved = true; 15470 } 15471 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15472 } 15473 15474 // writer 15475 synchronized (mPackages) { 15476 if (deletedPs != null) { 15477 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15478 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15479 clearDefaultBrowserIfNeeded(packageName); 15480 if (outInfo != null) { 15481 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15482 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15483 } 15484 updatePermissionsLPw(deletedPs.name, null, 0); 15485 if (deletedPs.sharedUser != null) { 15486 // Remove permissions associated with package. Since runtime 15487 // permissions are per user we have to kill the removed package 15488 // or packages running under the shared user of the removed 15489 // package if revoking the permissions requested only by the removed 15490 // package is successful and this causes a change in gids. 15491 for (int userId : UserManagerService.getInstance().getUserIds()) { 15492 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15493 userId); 15494 if (userIdToKill == UserHandle.USER_ALL 15495 || userIdToKill >= UserHandle.USER_SYSTEM) { 15496 // If gids changed for this user, kill all affected packages. 15497 mHandler.post(new Runnable() { 15498 @Override 15499 public void run() { 15500 // This has to happen with no lock held. 15501 killApplication(deletedPs.name, deletedPs.appId, 15502 KILL_APP_REASON_GIDS_CHANGED); 15503 } 15504 }); 15505 break; 15506 } 15507 } 15508 } 15509 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15510 } 15511 // make sure to preserve per-user disabled state if this removal was just 15512 // a downgrade of a system app to the factory package 15513 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15514 if (DEBUG_REMOVE) { 15515 Slog.d(TAG, "Propagating install state across downgrade"); 15516 } 15517 for (int userId : allUserHandles) { 15518 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15519 if (DEBUG_REMOVE) { 15520 Slog.d(TAG, " user " + userId + " => " + installed); 15521 } 15522 ps.setInstalled(installed, userId); 15523 } 15524 } 15525 } 15526 // can downgrade to reader 15527 if (writeSettings) { 15528 // Save settings now 15529 mSettings.writeLPr(); 15530 } 15531 } 15532 if (outInfo != null) { 15533 // A user ID was deleted here. Go through all users and remove it 15534 // from KeyStore. 15535 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15536 } 15537 } 15538 15539 static boolean locationIsPrivileged(File path) { 15540 try { 15541 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15542 .getCanonicalPath(); 15543 return path.getCanonicalPath().startsWith(privilegedAppDir); 15544 } catch (IOException e) { 15545 Slog.e(TAG, "Unable to access code path " + path); 15546 } 15547 return false; 15548 } 15549 15550 /* 15551 * Tries to delete system package. 15552 */ 15553 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15554 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15555 boolean writeSettings) { 15556 if (deletedPs.parentPackageName != null) { 15557 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15558 return false; 15559 } 15560 15561 final boolean applyUserRestrictions 15562 = (allUserHandles != null) && (outInfo.origUsers != null); 15563 final PackageSetting disabledPs; 15564 // Confirm if the system package has been updated 15565 // An updated system app can be deleted. This will also have to restore 15566 // the system pkg from system partition 15567 // reader 15568 synchronized (mPackages) { 15569 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15570 } 15571 15572 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15573 + " disabledPs=" + disabledPs); 15574 15575 if (disabledPs == null) { 15576 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15577 return false; 15578 } else if (DEBUG_REMOVE) { 15579 Slog.d(TAG, "Deleting system pkg from data partition"); 15580 } 15581 15582 if (DEBUG_REMOVE) { 15583 if (applyUserRestrictions) { 15584 Slog.d(TAG, "Remembering install states:"); 15585 for (int userId : allUserHandles) { 15586 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15587 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15588 } 15589 } 15590 } 15591 15592 // Delete the updated package 15593 outInfo.isRemovedPackageSystemUpdate = true; 15594 if (outInfo.removedChildPackages != null) { 15595 final int childCount = (deletedPs.childPackageNames != null) 15596 ? deletedPs.childPackageNames.size() : 0; 15597 for (int i = 0; i < childCount; i++) { 15598 String childPackageName = deletedPs.childPackageNames.get(i); 15599 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15600 .contains(childPackageName)) { 15601 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15602 childPackageName); 15603 if (childInfo != null) { 15604 childInfo.isRemovedPackageSystemUpdate = true; 15605 } 15606 } 15607 } 15608 } 15609 15610 if (disabledPs.versionCode < deletedPs.versionCode) { 15611 // Delete data for downgrades 15612 flags &= ~PackageManager.DELETE_KEEP_DATA; 15613 } else { 15614 // Preserve data by setting flag 15615 flags |= PackageManager.DELETE_KEEP_DATA; 15616 } 15617 15618 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15619 outInfo, writeSettings, disabledPs.pkg); 15620 if (!ret) { 15621 return false; 15622 } 15623 15624 // writer 15625 synchronized (mPackages) { 15626 // Reinstate the old system package 15627 enableSystemPackageLPw(disabledPs.pkg); 15628 // Remove any native libraries from the upgraded package. 15629 removeNativeBinariesLI(deletedPs); 15630 } 15631 15632 // Install the system package 15633 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15634 int parseFlags = mDefParseFlags 15635 | PackageParser.PARSE_MUST_BE_APK 15636 | PackageParser.PARSE_IS_SYSTEM 15637 | PackageParser.PARSE_IS_SYSTEM_DIR; 15638 if (locationIsPrivileged(disabledPs.codePath)) { 15639 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15640 } 15641 15642 final PackageParser.Package newPkg; 15643 try { 15644 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15645 } catch (PackageManagerException e) { 15646 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15647 + e.getMessage()); 15648 return false; 15649 } 15650 15651 prepareAppDataAfterInstallLIF(newPkg); 15652 15653 // writer 15654 synchronized (mPackages) { 15655 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15656 15657 // Propagate the permissions state as we do not want to drop on the floor 15658 // runtime permissions. The update permissions method below will take 15659 // care of removing obsolete permissions and grant install permissions. 15660 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15661 updatePermissionsLPw(newPkg.packageName, newPkg, 15662 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15663 15664 if (applyUserRestrictions) { 15665 if (DEBUG_REMOVE) { 15666 Slog.d(TAG, "Propagating install state across reinstall"); 15667 } 15668 for (int userId : allUserHandles) { 15669 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15670 if (DEBUG_REMOVE) { 15671 Slog.d(TAG, " user " + userId + " => " + installed); 15672 } 15673 ps.setInstalled(installed, userId); 15674 15675 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15676 } 15677 // Regardless of writeSettings we need to ensure that this restriction 15678 // state propagation is persisted 15679 mSettings.writeAllUsersPackageRestrictionsLPr(); 15680 } 15681 // can downgrade to reader here 15682 if (writeSettings) { 15683 mSettings.writeLPr(); 15684 } 15685 } 15686 return true; 15687 } 15688 15689 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15690 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15691 PackageRemovedInfo outInfo, boolean writeSettings, 15692 PackageParser.Package replacingPackage) { 15693 synchronized (mPackages) { 15694 if (outInfo != null) { 15695 outInfo.uid = ps.appId; 15696 } 15697 15698 if (outInfo != null && outInfo.removedChildPackages != null) { 15699 final int childCount = (ps.childPackageNames != null) 15700 ? ps.childPackageNames.size() : 0; 15701 for (int i = 0; i < childCount; i++) { 15702 String childPackageName = ps.childPackageNames.get(i); 15703 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15704 if (childPs == null) { 15705 return false; 15706 } 15707 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15708 childPackageName); 15709 if (childInfo != null) { 15710 childInfo.uid = childPs.appId; 15711 } 15712 } 15713 } 15714 } 15715 15716 // Delete package data from internal structures and also remove data if flag is set 15717 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15718 15719 // Delete the child packages data 15720 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15721 for (int i = 0; i < childCount; i++) { 15722 PackageSetting childPs; 15723 synchronized (mPackages) { 15724 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15725 } 15726 if (childPs != null) { 15727 PackageRemovedInfo childOutInfo = (outInfo != null 15728 && outInfo.removedChildPackages != null) 15729 ? outInfo.removedChildPackages.get(childPs.name) : null; 15730 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15731 && (replacingPackage != null 15732 && !replacingPackage.hasChildPackage(childPs.name)) 15733 ? flags & ~DELETE_KEEP_DATA : flags; 15734 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15735 deleteFlags, writeSettings); 15736 } 15737 } 15738 15739 // Delete application code and resources only for parent packages 15740 if (ps.parentPackageName == null) { 15741 if (deleteCodeAndResources && (outInfo != null)) { 15742 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15743 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15744 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15745 } 15746 } 15747 15748 return true; 15749 } 15750 15751 @Override 15752 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15753 int userId) { 15754 mContext.enforceCallingOrSelfPermission( 15755 android.Manifest.permission.DELETE_PACKAGES, null); 15756 synchronized (mPackages) { 15757 PackageSetting ps = mSettings.mPackages.get(packageName); 15758 if (ps == null) { 15759 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15760 return false; 15761 } 15762 if (!ps.getInstalled(userId)) { 15763 // Can't block uninstall for an app that is not installed or enabled. 15764 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15765 return false; 15766 } 15767 ps.setBlockUninstall(blockUninstall, userId); 15768 mSettings.writePackageRestrictionsLPr(userId); 15769 } 15770 return true; 15771 } 15772 15773 @Override 15774 public boolean getBlockUninstallForUser(String packageName, int userId) { 15775 synchronized (mPackages) { 15776 PackageSetting ps = mSettings.mPackages.get(packageName); 15777 if (ps == null) { 15778 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15779 return false; 15780 } 15781 return ps.getBlockUninstall(userId); 15782 } 15783 } 15784 15785 @Override 15786 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15787 int callingUid = Binder.getCallingUid(); 15788 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15789 throw new SecurityException( 15790 "setRequiredForSystemUser can only be run by the system or root"); 15791 } 15792 synchronized (mPackages) { 15793 PackageSetting ps = mSettings.mPackages.get(packageName); 15794 if (ps == null) { 15795 Log.w(TAG, "Package doesn't exist: " + packageName); 15796 return false; 15797 } 15798 if (systemUserApp) { 15799 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15800 } else { 15801 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15802 } 15803 mSettings.writeLPr(); 15804 } 15805 return true; 15806 } 15807 15808 /* 15809 * This method handles package deletion in general 15810 */ 15811 private boolean deletePackageLIF(String packageName, UserHandle user, 15812 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15813 PackageRemovedInfo outInfo, boolean writeSettings, 15814 PackageParser.Package replacingPackage) { 15815 if (packageName == null) { 15816 Slog.w(TAG, "Attempt to delete null packageName."); 15817 return false; 15818 } 15819 15820 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15821 15822 PackageSetting ps; 15823 15824 synchronized (mPackages) { 15825 ps = mSettings.mPackages.get(packageName); 15826 if (ps == null) { 15827 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15828 return false; 15829 } 15830 15831 if (ps.parentPackageName != null && (!isSystemApp(ps) 15832 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15833 if (DEBUG_REMOVE) { 15834 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15835 + ((user == null) ? UserHandle.USER_ALL : user)); 15836 } 15837 final int removedUserId = (user != null) ? user.getIdentifier() 15838 : UserHandle.USER_ALL; 15839 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15840 return false; 15841 } 15842 markPackageUninstalledForUserLPw(ps, user); 15843 scheduleWritePackageRestrictionsLocked(user); 15844 return true; 15845 } 15846 } 15847 15848 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15849 && user.getIdentifier() != UserHandle.USER_ALL)) { 15850 // The caller is asking that the package only be deleted for a single 15851 // user. To do this, we just mark its uninstalled state and delete 15852 // its data. If this is a system app, we only allow this to happen if 15853 // they have set the special DELETE_SYSTEM_APP which requests different 15854 // semantics than normal for uninstalling system apps. 15855 markPackageUninstalledForUserLPw(ps, user); 15856 15857 if (!isSystemApp(ps)) { 15858 // Do not uninstall the APK if an app should be cached 15859 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15860 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15861 // Other user still have this package installed, so all 15862 // we need to do is clear this user's data and save that 15863 // it is uninstalled. 15864 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15865 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15866 return false; 15867 } 15868 scheduleWritePackageRestrictionsLocked(user); 15869 return true; 15870 } else { 15871 // We need to set it back to 'installed' so the uninstall 15872 // broadcasts will be sent correctly. 15873 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15874 ps.setInstalled(true, user.getIdentifier()); 15875 } 15876 } else { 15877 // This is a system app, so we assume that the 15878 // other users still have this package installed, so all 15879 // we need to do is clear this user's data and save that 15880 // it is uninstalled. 15881 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15882 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15883 return false; 15884 } 15885 scheduleWritePackageRestrictionsLocked(user); 15886 return true; 15887 } 15888 } 15889 15890 // If we are deleting a composite package for all users, keep track 15891 // of result for each child. 15892 if (ps.childPackageNames != null && outInfo != null) { 15893 synchronized (mPackages) { 15894 final int childCount = ps.childPackageNames.size(); 15895 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15896 for (int i = 0; i < childCount; i++) { 15897 String childPackageName = ps.childPackageNames.get(i); 15898 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15899 childInfo.removedPackage = childPackageName; 15900 outInfo.removedChildPackages.put(childPackageName, childInfo); 15901 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15902 if (childPs != null) { 15903 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15904 } 15905 } 15906 } 15907 } 15908 15909 boolean ret = false; 15910 if (isSystemApp(ps)) { 15911 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15912 // When an updated system application is deleted we delete the existing resources 15913 // as well and fall back to existing code in system partition 15914 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15915 } else { 15916 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15917 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15918 outInfo, writeSettings, replacingPackage); 15919 } 15920 15921 // Take a note whether we deleted the package for all users 15922 if (outInfo != null) { 15923 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15924 if (outInfo.removedChildPackages != null) { 15925 synchronized (mPackages) { 15926 final int childCount = outInfo.removedChildPackages.size(); 15927 for (int i = 0; i < childCount; i++) { 15928 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15929 if (childInfo != null) { 15930 childInfo.removedForAllUsers = mPackages.get( 15931 childInfo.removedPackage) == null; 15932 } 15933 } 15934 } 15935 } 15936 // If we uninstalled an update to a system app there may be some 15937 // child packages that appeared as they are declared in the system 15938 // app but were not declared in the update. 15939 if (isSystemApp(ps)) { 15940 synchronized (mPackages) { 15941 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15942 final int childCount = (updatedPs.childPackageNames != null) 15943 ? updatedPs.childPackageNames.size() : 0; 15944 for (int i = 0; i < childCount; i++) { 15945 String childPackageName = updatedPs.childPackageNames.get(i); 15946 if (outInfo.removedChildPackages == null 15947 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15948 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15949 if (childPs == null) { 15950 continue; 15951 } 15952 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15953 installRes.name = childPackageName; 15954 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15955 installRes.pkg = mPackages.get(childPackageName); 15956 installRes.uid = childPs.pkg.applicationInfo.uid; 15957 if (outInfo.appearedChildPackages == null) { 15958 outInfo.appearedChildPackages = new ArrayMap<>(); 15959 } 15960 outInfo.appearedChildPackages.put(childPackageName, installRes); 15961 } 15962 } 15963 } 15964 } 15965 } 15966 15967 return ret; 15968 } 15969 15970 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15971 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15972 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15973 for (int nextUserId : userIds) { 15974 if (DEBUG_REMOVE) { 15975 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15976 } 15977 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15978 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15979 false /*hidden*/, false /*suspended*/, null, null, null, 15980 false /*blockUninstall*/, 15981 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15982 } 15983 } 15984 15985 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15986 PackageRemovedInfo outInfo) { 15987 final PackageParser.Package pkg; 15988 synchronized (mPackages) { 15989 pkg = mPackages.get(ps.name); 15990 } 15991 15992 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15993 : new int[] {userId}; 15994 for (int nextUserId : userIds) { 15995 if (DEBUG_REMOVE) { 15996 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15997 + nextUserId); 15998 } 15999 16000 destroyAppDataLIF(pkg, userId, 16001 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16002 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16003 schedulePackageCleaning(ps.name, nextUserId, false); 16004 synchronized (mPackages) { 16005 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16006 scheduleWritePackageRestrictionsLocked(nextUserId); 16007 } 16008 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16009 } 16010 } 16011 16012 if (outInfo != null) { 16013 outInfo.removedPackage = ps.name; 16014 outInfo.removedAppId = ps.appId; 16015 outInfo.removedUsers = userIds; 16016 } 16017 16018 return true; 16019 } 16020 16021 private final class ClearStorageConnection implements ServiceConnection { 16022 IMediaContainerService mContainerService; 16023 16024 @Override 16025 public void onServiceConnected(ComponentName name, IBinder service) { 16026 synchronized (this) { 16027 mContainerService = IMediaContainerService.Stub.asInterface(service); 16028 notifyAll(); 16029 } 16030 } 16031 16032 @Override 16033 public void onServiceDisconnected(ComponentName name) { 16034 } 16035 } 16036 16037 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16038 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16039 16040 final boolean mounted; 16041 if (Environment.isExternalStorageEmulated()) { 16042 mounted = true; 16043 } else { 16044 final String status = Environment.getExternalStorageState(); 16045 16046 mounted = status.equals(Environment.MEDIA_MOUNTED) 16047 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16048 } 16049 16050 if (!mounted) { 16051 return; 16052 } 16053 16054 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16055 int[] users; 16056 if (userId == UserHandle.USER_ALL) { 16057 users = sUserManager.getUserIds(); 16058 } else { 16059 users = new int[] { userId }; 16060 } 16061 final ClearStorageConnection conn = new ClearStorageConnection(); 16062 if (mContext.bindServiceAsUser( 16063 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16064 try { 16065 for (int curUser : users) { 16066 long timeout = SystemClock.uptimeMillis() + 5000; 16067 synchronized (conn) { 16068 long now = SystemClock.uptimeMillis(); 16069 while (conn.mContainerService == null && now < timeout) { 16070 try { 16071 conn.wait(timeout - now); 16072 } catch (InterruptedException e) { 16073 } 16074 } 16075 } 16076 if (conn.mContainerService == null) { 16077 return; 16078 } 16079 16080 final UserEnvironment userEnv = new UserEnvironment(curUser); 16081 clearDirectory(conn.mContainerService, 16082 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16083 if (allData) { 16084 clearDirectory(conn.mContainerService, 16085 userEnv.buildExternalStorageAppDataDirs(packageName)); 16086 clearDirectory(conn.mContainerService, 16087 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16088 } 16089 } 16090 } finally { 16091 mContext.unbindService(conn); 16092 } 16093 } 16094 } 16095 16096 @Override 16097 public void clearApplicationProfileData(String packageName) { 16098 enforceSystemOrRoot("Only the system can clear all profile data"); 16099 16100 final PackageParser.Package pkg; 16101 synchronized (mPackages) { 16102 pkg = mPackages.get(packageName); 16103 } 16104 16105 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16106 synchronized (mInstallLock) { 16107 clearAppProfilesLIF(pkg); 16108 } 16109 } 16110 } 16111 16112 @Override 16113 public void clearApplicationUserData(final String packageName, 16114 final IPackageDataObserver observer, final int userId) { 16115 mContext.enforceCallingOrSelfPermission( 16116 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16117 16118 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16119 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16120 16121 final DevicePolicyManagerInternal dpmi = LocalServices 16122 .getService(DevicePolicyManagerInternal.class); 16123 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16124 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16125 } 16126 // Queue up an async operation since the package deletion may take a little while. 16127 mHandler.post(new Runnable() { 16128 public void run() { 16129 mHandler.removeCallbacks(this); 16130 final boolean succeeded; 16131 try (PackageFreezer freezer = freezePackage(packageName, 16132 "clearApplicationUserData")) { 16133 synchronized (mInstallLock) { 16134 succeeded = clearApplicationUserDataLIF(packageName, userId); 16135 } 16136 clearExternalStorageDataSync(packageName, userId, true); 16137 } 16138 if (succeeded) { 16139 // invoke DeviceStorageMonitor's update method to clear any notifications 16140 DeviceStorageMonitorInternal dsm = LocalServices 16141 .getService(DeviceStorageMonitorInternal.class); 16142 if (dsm != null) { 16143 dsm.checkMemory(); 16144 } 16145 } 16146 if(observer != null) { 16147 try { 16148 observer.onRemoveCompleted(packageName, succeeded); 16149 } catch (RemoteException e) { 16150 Log.i(TAG, "Observer no longer exists."); 16151 } 16152 } //end if observer 16153 } //end run 16154 }); 16155 } 16156 16157 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16158 if (packageName == null) { 16159 Slog.w(TAG, "Attempt to delete null packageName."); 16160 return false; 16161 } 16162 16163 // Try finding details about the requested package 16164 PackageParser.Package pkg; 16165 synchronized (mPackages) { 16166 pkg = mPackages.get(packageName); 16167 if (pkg == null) { 16168 final PackageSetting ps = mSettings.mPackages.get(packageName); 16169 if (ps != null) { 16170 pkg = ps.pkg; 16171 } 16172 } 16173 16174 if (pkg == null) { 16175 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16176 return false; 16177 } 16178 16179 PackageSetting ps = (PackageSetting) pkg.mExtras; 16180 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16181 } 16182 16183 clearAppDataLIF(pkg, userId, 16184 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16185 16186 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16187 removeKeystoreDataIfNeeded(userId, appId); 16188 16189 final UserManager um = mContext.getSystemService(UserManager.class); 16190 final int flags; 16191 if (um.isUserUnlockingOrUnlocked(userId)) { 16192 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16193 } else if (um.isUserRunning(userId)) { 16194 flags = StorageManager.FLAG_STORAGE_DE; 16195 } else { 16196 flags = 0; 16197 } 16198 prepareAppDataContentsLIF(pkg, userId, flags); 16199 16200 return true; 16201 } 16202 16203 /** 16204 * Reverts user permission state changes (permissions and flags) in 16205 * all packages for a given user. 16206 * 16207 * @param userId The device user for which to do a reset. 16208 */ 16209 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16210 final int packageCount = mPackages.size(); 16211 for (int i = 0; i < packageCount; i++) { 16212 PackageParser.Package pkg = mPackages.valueAt(i); 16213 PackageSetting ps = (PackageSetting) pkg.mExtras; 16214 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16215 } 16216 } 16217 16218 private void resetNetworkPolicies(int userId) { 16219 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16220 } 16221 16222 /** 16223 * Reverts user permission state changes (permissions and flags). 16224 * 16225 * @param ps The package for which to reset. 16226 * @param userId The device user for which to do a reset. 16227 */ 16228 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16229 final PackageSetting ps, final int userId) { 16230 if (ps.pkg == null) { 16231 return; 16232 } 16233 16234 // These are flags that can change base on user actions. 16235 final int userSettableMask = FLAG_PERMISSION_USER_SET 16236 | FLAG_PERMISSION_USER_FIXED 16237 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16238 | FLAG_PERMISSION_REVIEW_REQUIRED; 16239 16240 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16241 | FLAG_PERMISSION_POLICY_FIXED; 16242 16243 boolean writeInstallPermissions = false; 16244 boolean writeRuntimePermissions = false; 16245 16246 final int permissionCount = ps.pkg.requestedPermissions.size(); 16247 for (int i = 0; i < permissionCount; i++) { 16248 String permission = ps.pkg.requestedPermissions.get(i); 16249 16250 BasePermission bp = mSettings.mPermissions.get(permission); 16251 if (bp == null) { 16252 continue; 16253 } 16254 16255 // If shared user we just reset the state to which only this app contributed. 16256 if (ps.sharedUser != null) { 16257 boolean used = false; 16258 final int packageCount = ps.sharedUser.packages.size(); 16259 for (int j = 0; j < packageCount; j++) { 16260 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16261 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16262 && pkg.pkg.requestedPermissions.contains(permission)) { 16263 used = true; 16264 break; 16265 } 16266 } 16267 if (used) { 16268 continue; 16269 } 16270 } 16271 16272 PermissionsState permissionsState = ps.getPermissionsState(); 16273 16274 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16275 16276 // Always clear the user settable flags. 16277 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16278 bp.name) != null; 16279 // If permission review is enabled and this is a legacy app, mark the 16280 // permission as requiring a review as this is the initial state. 16281 int flags = 0; 16282 if (Build.PERMISSIONS_REVIEW_REQUIRED 16283 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16284 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16285 } 16286 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16287 if (hasInstallState) { 16288 writeInstallPermissions = true; 16289 } else { 16290 writeRuntimePermissions = true; 16291 } 16292 } 16293 16294 // Below is only runtime permission handling. 16295 if (!bp.isRuntime()) { 16296 continue; 16297 } 16298 16299 // Never clobber system or policy. 16300 if ((oldFlags & policyOrSystemFlags) != 0) { 16301 continue; 16302 } 16303 16304 // If this permission was granted by default, make sure it is. 16305 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16306 if (permissionsState.grantRuntimePermission(bp, userId) 16307 != PERMISSION_OPERATION_FAILURE) { 16308 writeRuntimePermissions = true; 16309 } 16310 // If permission review is enabled the permissions for a legacy apps 16311 // are represented as constantly granted runtime ones, so don't revoke. 16312 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16313 // Otherwise, reset the permission. 16314 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16315 switch (revokeResult) { 16316 case PERMISSION_OPERATION_SUCCESS: 16317 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16318 writeRuntimePermissions = true; 16319 final int appId = ps.appId; 16320 mHandler.post(new Runnable() { 16321 @Override 16322 public void run() { 16323 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16324 } 16325 }); 16326 } break; 16327 } 16328 } 16329 } 16330 16331 // Synchronously write as we are taking permissions away. 16332 if (writeRuntimePermissions) { 16333 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16334 } 16335 16336 // Synchronously write as we are taking permissions away. 16337 if (writeInstallPermissions) { 16338 mSettings.writeLPr(); 16339 } 16340 } 16341 16342 /** 16343 * Remove entries from the keystore daemon. Will only remove it if the 16344 * {@code appId} is valid. 16345 */ 16346 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16347 if (appId < 0) { 16348 return; 16349 } 16350 16351 final KeyStore keyStore = KeyStore.getInstance(); 16352 if (keyStore != null) { 16353 if (userId == UserHandle.USER_ALL) { 16354 for (final int individual : sUserManager.getUserIds()) { 16355 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16356 } 16357 } else { 16358 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16359 } 16360 } else { 16361 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16362 } 16363 } 16364 16365 @Override 16366 public void deleteApplicationCacheFiles(final String packageName, 16367 final IPackageDataObserver observer) { 16368 final int userId = UserHandle.getCallingUserId(); 16369 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16370 } 16371 16372 @Override 16373 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16374 final IPackageDataObserver observer) { 16375 mContext.enforceCallingOrSelfPermission( 16376 android.Manifest.permission.DELETE_CACHE_FILES, null); 16377 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16378 /* requireFullPermission= */ true, /* checkShell= */ false, 16379 "delete application cache files"); 16380 16381 final PackageParser.Package pkg; 16382 synchronized (mPackages) { 16383 pkg = mPackages.get(packageName); 16384 } 16385 16386 // Queue up an async operation since the package deletion may take a little while. 16387 mHandler.post(new Runnable() { 16388 public void run() { 16389 synchronized (mInstallLock) { 16390 final int flags = StorageManager.FLAG_STORAGE_DE 16391 | StorageManager.FLAG_STORAGE_CE; 16392 // We're only clearing cache files, so we don't care if the 16393 // app is unfrozen and still able to run 16394 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16395 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16396 } 16397 clearExternalStorageDataSync(packageName, userId, false); 16398 if (observer != null) { 16399 try { 16400 observer.onRemoveCompleted(packageName, true); 16401 } catch (RemoteException e) { 16402 Log.i(TAG, "Observer no longer exists."); 16403 } 16404 } 16405 } 16406 }); 16407 } 16408 16409 @Override 16410 public void getPackageSizeInfo(final String packageName, int userHandle, 16411 final IPackageStatsObserver observer) { 16412 mContext.enforceCallingOrSelfPermission( 16413 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16414 if (packageName == null) { 16415 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16416 } 16417 16418 PackageStats stats = new PackageStats(packageName, userHandle); 16419 16420 /* 16421 * Queue up an async operation since the package measurement may take a 16422 * little while. 16423 */ 16424 Message msg = mHandler.obtainMessage(INIT_COPY); 16425 msg.obj = new MeasureParams(stats, observer); 16426 mHandler.sendMessage(msg); 16427 } 16428 16429 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16430 final PackageSetting ps; 16431 synchronized (mPackages) { 16432 ps = mSettings.mPackages.get(packageName); 16433 if (ps == null) { 16434 Slog.w(TAG, "Failed to find settings for " + packageName); 16435 return false; 16436 } 16437 } 16438 try { 16439 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16440 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16441 ps.getCeDataInode(userId), ps.codePathString, stats); 16442 } catch (InstallerException e) { 16443 Slog.w(TAG, String.valueOf(e)); 16444 return false; 16445 } 16446 16447 // For now, ignore code size of packages on system partition 16448 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16449 stats.codeSize = 0; 16450 } 16451 16452 return true; 16453 } 16454 16455 private int getUidTargetSdkVersionLockedLPr(int uid) { 16456 Object obj = mSettings.getUserIdLPr(uid); 16457 if (obj instanceof SharedUserSetting) { 16458 final SharedUserSetting sus = (SharedUserSetting) obj; 16459 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16460 final Iterator<PackageSetting> it = sus.packages.iterator(); 16461 while (it.hasNext()) { 16462 final PackageSetting ps = it.next(); 16463 if (ps.pkg != null) { 16464 int v = ps.pkg.applicationInfo.targetSdkVersion; 16465 if (v < vers) vers = v; 16466 } 16467 } 16468 return vers; 16469 } else if (obj instanceof PackageSetting) { 16470 final PackageSetting ps = (PackageSetting) obj; 16471 if (ps.pkg != null) { 16472 return ps.pkg.applicationInfo.targetSdkVersion; 16473 } 16474 } 16475 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16476 } 16477 16478 @Override 16479 public void addPreferredActivity(IntentFilter filter, int match, 16480 ComponentName[] set, ComponentName activity, int userId) { 16481 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16482 "Adding preferred"); 16483 } 16484 16485 private void addPreferredActivityInternal(IntentFilter filter, int match, 16486 ComponentName[] set, ComponentName activity, boolean always, int userId, 16487 String opname) { 16488 // writer 16489 int callingUid = Binder.getCallingUid(); 16490 enforceCrossUserPermission(callingUid, userId, 16491 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16492 if (filter.countActions() == 0) { 16493 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16494 return; 16495 } 16496 synchronized (mPackages) { 16497 if (mContext.checkCallingOrSelfPermission( 16498 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16499 != PackageManager.PERMISSION_GRANTED) { 16500 if (getUidTargetSdkVersionLockedLPr(callingUid) 16501 < Build.VERSION_CODES.FROYO) { 16502 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16503 + callingUid); 16504 return; 16505 } 16506 mContext.enforceCallingOrSelfPermission( 16507 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16508 } 16509 16510 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16511 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16512 + userId + ":"); 16513 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16514 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16515 scheduleWritePackageRestrictionsLocked(userId); 16516 } 16517 } 16518 16519 @Override 16520 public void replacePreferredActivity(IntentFilter filter, int match, 16521 ComponentName[] set, ComponentName activity, int userId) { 16522 if (filter.countActions() != 1) { 16523 throw new IllegalArgumentException( 16524 "replacePreferredActivity expects filter to have only 1 action."); 16525 } 16526 if (filter.countDataAuthorities() != 0 16527 || filter.countDataPaths() != 0 16528 || filter.countDataSchemes() > 1 16529 || filter.countDataTypes() != 0) { 16530 throw new IllegalArgumentException( 16531 "replacePreferredActivity expects filter to have no data authorities, " + 16532 "paths, or types; and at most one scheme."); 16533 } 16534 16535 final int callingUid = Binder.getCallingUid(); 16536 enforceCrossUserPermission(callingUid, userId, 16537 true /* requireFullPermission */, false /* checkShell */, 16538 "replace preferred activity"); 16539 synchronized (mPackages) { 16540 if (mContext.checkCallingOrSelfPermission( 16541 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16542 != PackageManager.PERMISSION_GRANTED) { 16543 if (getUidTargetSdkVersionLockedLPr(callingUid) 16544 < Build.VERSION_CODES.FROYO) { 16545 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16546 + Binder.getCallingUid()); 16547 return; 16548 } 16549 mContext.enforceCallingOrSelfPermission( 16550 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16551 } 16552 16553 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16554 if (pir != null) { 16555 // Get all of the existing entries that exactly match this filter. 16556 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16557 if (existing != null && existing.size() == 1) { 16558 PreferredActivity cur = existing.get(0); 16559 if (DEBUG_PREFERRED) { 16560 Slog.i(TAG, "Checking replace of preferred:"); 16561 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16562 if (!cur.mPref.mAlways) { 16563 Slog.i(TAG, " -- CUR; not mAlways!"); 16564 } else { 16565 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16566 Slog.i(TAG, " -- CUR: mSet=" 16567 + Arrays.toString(cur.mPref.mSetComponents)); 16568 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16569 Slog.i(TAG, " -- NEW: mMatch=" 16570 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16571 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16572 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16573 } 16574 } 16575 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16576 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16577 && cur.mPref.sameSet(set)) { 16578 // Setting the preferred activity to what it happens to be already 16579 if (DEBUG_PREFERRED) { 16580 Slog.i(TAG, "Replacing with same preferred activity " 16581 + cur.mPref.mShortComponent + " for user " 16582 + userId + ":"); 16583 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16584 } 16585 return; 16586 } 16587 } 16588 16589 if (existing != null) { 16590 if (DEBUG_PREFERRED) { 16591 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16592 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16593 } 16594 for (int i = 0; i < existing.size(); i++) { 16595 PreferredActivity pa = existing.get(i); 16596 if (DEBUG_PREFERRED) { 16597 Slog.i(TAG, "Removing existing preferred activity " 16598 + pa.mPref.mComponent + ":"); 16599 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16600 } 16601 pir.removeFilter(pa); 16602 } 16603 } 16604 } 16605 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16606 "Replacing preferred"); 16607 } 16608 } 16609 16610 @Override 16611 public void clearPackagePreferredActivities(String packageName) { 16612 final int uid = Binder.getCallingUid(); 16613 // writer 16614 synchronized (mPackages) { 16615 PackageParser.Package pkg = mPackages.get(packageName); 16616 if (pkg == null || pkg.applicationInfo.uid != uid) { 16617 if (mContext.checkCallingOrSelfPermission( 16618 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16619 != PackageManager.PERMISSION_GRANTED) { 16620 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16621 < Build.VERSION_CODES.FROYO) { 16622 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16623 + Binder.getCallingUid()); 16624 return; 16625 } 16626 mContext.enforceCallingOrSelfPermission( 16627 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16628 } 16629 } 16630 16631 int user = UserHandle.getCallingUserId(); 16632 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16633 scheduleWritePackageRestrictionsLocked(user); 16634 } 16635 } 16636 } 16637 16638 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16639 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16640 ArrayList<PreferredActivity> removed = null; 16641 boolean changed = false; 16642 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16643 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16644 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16645 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16646 continue; 16647 } 16648 Iterator<PreferredActivity> it = pir.filterIterator(); 16649 while (it.hasNext()) { 16650 PreferredActivity pa = it.next(); 16651 // Mark entry for removal only if it matches the package name 16652 // and the entry is of type "always". 16653 if (packageName == null || 16654 (pa.mPref.mComponent.getPackageName().equals(packageName) 16655 && pa.mPref.mAlways)) { 16656 if (removed == null) { 16657 removed = new ArrayList<PreferredActivity>(); 16658 } 16659 removed.add(pa); 16660 } 16661 } 16662 if (removed != null) { 16663 for (int j=0; j<removed.size(); j++) { 16664 PreferredActivity pa = removed.get(j); 16665 pir.removeFilter(pa); 16666 } 16667 changed = true; 16668 } 16669 } 16670 return changed; 16671 } 16672 16673 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16674 private void clearIntentFilterVerificationsLPw(int userId) { 16675 final int packageCount = mPackages.size(); 16676 for (int i = 0; i < packageCount; i++) { 16677 PackageParser.Package pkg = mPackages.valueAt(i); 16678 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16679 } 16680 } 16681 16682 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16683 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16684 if (userId == UserHandle.USER_ALL) { 16685 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16686 sUserManager.getUserIds())) { 16687 for (int oneUserId : sUserManager.getUserIds()) { 16688 scheduleWritePackageRestrictionsLocked(oneUserId); 16689 } 16690 } 16691 } else { 16692 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16693 scheduleWritePackageRestrictionsLocked(userId); 16694 } 16695 } 16696 } 16697 16698 void clearDefaultBrowserIfNeeded(String packageName) { 16699 for (int oneUserId : sUserManager.getUserIds()) { 16700 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16701 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16702 if (packageName.equals(defaultBrowserPackageName)) { 16703 setDefaultBrowserPackageName(null, oneUserId); 16704 } 16705 } 16706 } 16707 16708 @Override 16709 public void resetApplicationPreferences(int userId) { 16710 mContext.enforceCallingOrSelfPermission( 16711 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16712 final long identity = Binder.clearCallingIdentity(); 16713 // writer 16714 try { 16715 synchronized (mPackages) { 16716 clearPackagePreferredActivitiesLPw(null, userId); 16717 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16718 // TODO: We have to reset the default SMS and Phone. This requires 16719 // significant refactoring to keep all default apps in the package 16720 // manager (cleaner but more work) or have the services provide 16721 // callbacks to the package manager to request a default app reset. 16722 applyFactoryDefaultBrowserLPw(userId); 16723 clearIntentFilterVerificationsLPw(userId); 16724 primeDomainVerificationsLPw(userId); 16725 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16726 scheduleWritePackageRestrictionsLocked(userId); 16727 } 16728 resetNetworkPolicies(userId); 16729 } finally { 16730 Binder.restoreCallingIdentity(identity); 16731 } 16732 } 16733 16734 @Override 16735 public int getPreferredActivities(List<IntentFilter> outFilters, 16736 List<ComponentName> outActivities, String packageName) { 16737 16738 int num = 0; 16739 final int userId = UserHandle.getCallingUserId(); 16740 // reader 16741 synchronized (mPackages) { 16742 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16743 if (pir != null) { 16744 final Iterator<PreferredActivity> it = pir.filterIterator(); 16745 while (it.hasNext()) { 16746 final PreferredActivity pa = it.next(); 16747 if (packageName == null 16748 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16749 && pa.mPref.mAlways)) { 16750 if (outFilters != null) { 16751 outFilters.add(new IntentFilter(pa)); 16752 } 16753 if (outActivities != null) { 16754 outActivities.add(pa.mPref.mComponent); 16755 } 16756 } 16757 } 16758 } 16759 } 16760 16761 return num; 16762 } 16763 16764 @Override 16765 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16766 int userId) { 16767 int callingUid = Binder.getCallingUid(); 16768 if (callingUid != Process.SYSTEM_UID) { 16769 throw new SecurityException( 16770 "addPersistentPreferredActivity can only be run by the system"); 16771 } 16772 if (filter.countActions() == 0) { 16773 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16774 return; 16775 } 16776 synchronized (mPackages) { 16777 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16778 ":"); 16779 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16780 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16781 new PersistentPreferredActivity(filter, activity)); 16782 scheduleWritePackageRestrictionsLocked(userId); 16783 } 16784 } 16785 16786 @Override 16787 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16788 int callingUid = Binder.getCallingUid(); 16789 if (callingUid != Process.SYSTEM_UID) { 16790 throw new SecurityException( 16791 "clearPackagePersistentPreferredActivities can only be run by the system"); 16792 } 16793 ArrayList<PersistentPreferredActivity> removed = null; 16794 boolean changed = false; 16795 synchronized (mPackages) { 16796 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16797 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16798 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16799 .valueAt(i); 16800 if (userId != thisUserId) { 16801 continue; 16802 } 16803 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16804 while (it.hasNext()) { 16805 PersistentPreferredActivity ppa = it.next(); 16806 // Mark entry for removal only if it matches the package name. 16807 if (ppa.mComponent.getPackageName().equals(packageName)) { 16808 if (removed == null) { 16809 removed = new ArrayList<PersistentPreferredActivity>(); 16810 } 16811 removed.add(ppa); 16812 } 16813 } 16814 if (removed != null) { 16815 for (int j=0; j<removed.size(); j++) { 16816 PersistentPreferredActivity ppa = removed.get(j); 16817 ppir.removeFilter(ppa); 16818 } 16819 changed = true; 16820 } 16821 } 16822 16823 if (changed) { 16824 scheduleWritePackageRestrictionsLocked(userId); 16825 } 16826 } 16827 } 16828 16829 /** 16830 * Common machinery for picking apart a restored XML blob and passing 16831 * it to a caller-supplied functor to be applied to the running system. 16832 */ 16833 private void restoreFromXml(XmlPullParser parser, int userId, 16834 String expectedStartTag, BlobXmlRestorer functor) 16835 throws IOException, XmlPullParserException { 16836 int type; 16837 while ((type = parser.next()) != XmlPullParser.START_TAG 16838 && type != XmlPullParser.END_DOCUMENT) { 16839 } 16840 if (type != XmlPullParser.START_TAG) { 16841 // oops didn't find a start tag?! 16842 if (DEBUG_BACKUP) { 16843 Slog.e(TAG, "Didn't find start tag during restore"); 16844 } 16845 return; 16846 } 16847Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16848 // this is supposed to be TAG_PREFERRED_BACKUP 16849 if (!expectedStartTag.equals(parser.getName())) { 16850 if (DEBUG_BACKUP) { 16851 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16852 } 16853 return; 16854 } 16855 16856 // skip interfering stuff, then we're aligned with the backing implementation 16857 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16858Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16859 functor.apply(parser, userId); 16860 } 16861 16862 private interface BlobXmlRestorer { 16863 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16864 } 16865 16866 /** 16867 * Non-Binder method, support for the backup/restore mechanism: write the 16868 * full set of preferred activities in its canonical XML format. Returns the 16869 * XML output as a byte array, or null if there is none. 16870 */ 16871 @Override 16872 public byte[] getPreferredActivityBackup(int userId) { 16873 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16874 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16875 } 16876 16877 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16878 try { 16879 final XmlSerializer serializer = new FastXmlSerializer(); 16880 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16881 serializer.startDocument(null, true); 16882 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16883 16884 synchronized (mPackages) { 16885 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16886 } 16887 16888 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16889 serializer.endDocument(); 16890 serializer.flush(); 16891 } catch (Exception e) { 16892 if (DEBUG_BACKUP) { 16893 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16894 } 16895 return null; 16896 } 16897 16898 return dataStream.toByteArray(); 16899 } 16900 16901 @Override 16902 public void restorePreferredActivities(byte[] backup, int userId) { 16903 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16904 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16905 } 16906 16907 try { 16908 final XmlPullParser parser = Xml.newPullParser(); 16909 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16910 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16911 new BlobXmlRestorer() { 16912 @Override 16913 public void apply(XmlPullParser parser, int userId) 16914 throws XmlPullParserException, IOException { 16915 synchronized (mPackages) { 16916 mSettings.readPreferredActivitiesLPw(parser, userId); 16917 } 16918 } 16919 } ); 16920 } catch (Exception e) { 16921 if (DEBUG_BACKUP) { 16922 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16923 } 16924 } 16925 } 16926 16927 /** 16928 * Non-Binder method, support for the backup/restore mechanism: write the 16929 * default browser (etc) settings in its canonical XML format. Returns the default 16930 * browser XML representation as a byte array, or null if there is none. 16931 */ 16932 @Override 16933 public byte[] getDefaultAppsBackup(int userId) { 16934 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16935 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16936 } 16937 16938 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16939 try { 16940 final XmlSerializer serializer = new FastXmlSerializer(); 16941 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16942 serializer.startDocument(null, true); 16943 serializer.startTag(null, TAG_DEFAULT_APPS); 16944 16945 synchronized (mPackages) { 16946 mSettings.writeDefaultAppsLPr(serializer, userId); 16947 } 16948 16949 serializer.endTag(null, TAG_DEFAULT_APPS); 16950 serializer.endDocument(); 16951 serializer.flush(); 16952 } catch (Exception e) { 16953 if (DEBUG_BACKUP) { 16954 Slog.e(TAG, "Unable to write default apps for backup", e); 16955 } 16956 return null; 16957 } 16958 16959 return dataStream.toByteArray(); 16960 } 16961 16962 @Override 16963 public void restoreDefaultApps(byte[] backup, int userId) { 16964 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16965 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16966 } 16967 16968 try { 16969 final XmlPullParser parser = Xml.newPullParser(); 16970 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16971 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16972 new BlobXmlRestorer() { 16973 @Override 16974 public void apply(XmlPullParser parser, int userId) 16975 throws XmlPullParserException, IOException { 16976 synchronized (mPackages) { 16977 mSettings.readDefaultAppsLPw(parser, userId); 16978 } 16979 } 16980 } ); 16981 } catch (Exception e) { 16982 if (DEBUG_BACKUP) { 16983 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16984 } 16985 } 16986 } 16987 16988 @Override 16989 public byte[] getIntentFilterVerificationBackup(int userId) { 16990 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16991 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16992 } 16993 16994 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16995 try { 16996 final XmlSerializer serializer = new FastXmlSerializer(); 16997 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16998 serializer.startDocument(null, true); 16999 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17000 17001 synchronized (mPackages) { 17002 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17003 } 17004 17005 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17006 serializer.endDocument(); 17007 serializer.flush(); 17008 } catch (Exception e) { 17009 if (DEBUG_BACKUP) { 17010 Slog.e(TAG, "Unable to write default apps for backup", e); 17011 } 17012 return null; 17013 } 17014 17015 return dataStream.toByteArray(); 17016 } 17017 17018 @Override 17019 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17020 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17021 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17022 } 17023 17024 try { 17025 final XmlPullParser parser = Xml.newPullParser(); 17026 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17027 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17028 new BlobXmlRestorer() { 17029 @Override 17030 public void apply(XmlPullParser parser, int userId) 17031 throws XmlPullParserException, IOException { 17032 synchronized (mPackages) { 17033 mSettings.readAllDomainVerificationsLPr(parser, userId); 17034 mSettings.writeLPr(); 17035 } 17036 } 17037 } ); 17038 } catch (Exception e) { 17039 if (DEBUG_BACKUP) { 17040 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17041 } 17042 } 17043 } 17044 17045 @Override 17046 public byte[] getPermissionGrantBackup(int userId) { 17047 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17048 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17049 } 17050 17051 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17052 try { 17053 final XmlSerializer serializer = new FastXmlSerializer(); 17054 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17055 serializer.startDocument(null, true); 17056 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17057 17058 synchronized (mPackages) { 17059 serializeRuntimePermissionGrantsLPr(serializer, userId); 17060 } 17061 17062 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17063 serializer.endDocument(); 17064 serializer.flush(); 17065 } catch (Exception e) { 17066 if (DEBUG_BACKUP) { 17067 Slog.e(TAG, "Unable to write default apps for backup", e); 17068 } 17069 return null; 17070 } 17071 17072 return dataStream.toByteArray(); 17073 } 17074 17075 @Override 17076 public void restorePermissionGrants(byte[] backup, int userId) { 17077 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17078 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17079 } 17080 17081 try { 17082 final XmlPullParser parser = Xml.newPullParser(); 17083 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17084 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17085 new BlobXmlRestorer() { 17086 @Override 17087 public void apply(XmlPullParser parser, int userId) 17088 throws XmlPullParserException, IOException { 17089 synchronized (mPackages) { 17090 processRestoredPermissionGrantsLPr(parser, userId); 17091 } 17092 } 17093 } ); 17094 } catch (Exception e) { 17095 if (DEBUG_BACKUP) { 17096 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17097 } 17098 } 17099 } 17100 17101 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17102 throws IOException { 17103 serializer.startTag(null, TAG_ALL_GRANTS); 17104 17105 final int N = mSettings.mPackages.size(); 17106 for (int i = 0; i < N; i++) { 17107 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17108 boolean pkgGrantsKnown = false; 17109 17110 PermissionsState packagePerms = ps.getPermissionsState(); 17111 17112 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17113 final int grantFlags = state.getFlags(); 17114 // only look at grants that are not system/policy fixed 17115 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17116 final boolean isGranted = state.isGranted(); 17117 // And only back up the user-twiddled state bits 17118 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17119 final String packageName = mSettings.mPackages.keyAt(i); 17120 if (!pkgGrantsKnown) { 17121 serializer.startTag(null, TAG_GRANT); 17122 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17123 pkgGrantsKnown = true; 17124 } 17125 17126 final boolean userSet = 17127 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17128 final boolean userFixed = 17129 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17130 final boolean revoke = 17131 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17132 17133 serializer.startTag(null, TAG_PERMISSION); 17134 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17135 if (isGranted) { 17136 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17137 } 17138 if (userSet) { 17139 serializer.attribute(null, ATTR_USER_SET, "true"); 17140 } 17141 if (userFixed) { 17142 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17143 } 17144 if (revoke) { 17145 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17146 } 17147 serializer.endTag(null, TAG_PERMISSION); 17148 } 17149 } 17150 } 17151 17152 if (pkgGrantsKnown) { 17153 serializer.endTag(null, TAG_GRANT); 17154 } 17155 } 17156 17157 serializer.endTag(null, TAG_ALL_GRANTS); 17158 } 17159 17160 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17161 throws XmlPullParserException, IOException { 17162 String pkgName = null; 17163 int outerDepth = parser.getDepth(); 17164 int type; 17165 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17166 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17167 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17168 continue; 17169 } 17170 17171 final String tagName = parser.getName(); 17172 if (tagName.equals(TAG_GRANT)) { 17173 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17174 if (DEBUG_BACKUP) { 17175 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17176 } 17177 } else if (tagName.equals(TAG_PERMISSION)) { 17178 17179 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17180 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17181 17182 int newFlagSet = 0; 17183 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17184 newFlagSet |= FLAG_PERMISSION_USER_SET; 17185 } 17186 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17187 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17188 } 17189 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17190 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17191 } 17192 if (DEBUG_BACKUP) { 17193 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17194 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17195 } 17196 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17197 if (ps != null) { 17198 // Already installed so we apply the grant immediately 17199 if (DEBUG_BACKUP) { 17200 Slog.v(TAG, " + already installed; applying"); 17201 } 17202 PermissionsState perms = ps.getPermissionsState(); 17203 BasePermission bp = mSettings.mPermissions.get(permName); 17204 if (bp != null) { 17205 if (isGranted) { 17206 perms.grantRuntimePermission(bp, userId); 17207 } 17208 if (newFlagSet != 0) { 17209 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17210 } 17211 } 17212 } else { 17213 // Need to wait for post-restore install to apply the grant 17214 if (DEBUG_BACKUP) { 17215 Slog.v(TAG, " - not yet installed; saving for later"); 17216 } 17217 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17218 isGranted, newFlagSet, userId); 17219 } 17220 } else { 17221 PackageManagerService.reportSettingsProblem(Log.WARN, 17222 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17223 XmlUtils.skipCurrentTag(parser); 17224 } 17225 } 17226 17227 scheduleWriteSettingsLocked(); 17228 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17229 } 17230 17231 @Override 17232 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17233 int sourceUserId, int targetUserId, int flags) { 17234 mContext.enforceCallingOrSelfPermission( 17235 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17236 int callingUid = Binder.getCallingUid(); 17237 enforceOwnerRights(ownerPackage, callingUid); 17238 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17239 if (intentFilter.countActions() == 0) { 17240 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17241 return; 17242 } 17243 synchronized (mPackages) { 17244 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17245 ownerPackage, targetUserId, flags); 17246 CrossProfileIntentResolver resolver = 17247 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17248 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17249 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17250 if (existing != null) { 17251 int size = existing.size(); 17252 for (int i = 0; i < size; i++) { 17253 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17254 return; 17255 } 17256 } 17257 } 17258 resolver.addFilter(newFilter); 17259 scheduleWritePackageRestrictionsLocked(sourceUserId); 17260 } 17261 } 17262 17263 @Override 17264 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17265 mContext.enforceCallingOrSelfPermission( 17266 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17267 int callingUid = Binder.getCallingUid(); 17268 enforceOwnerRights(ownerPackage, callingUid); 17269 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17270 synchronized (mPackages) { 17271 CrossProfileIntentResolver resolver = 17272 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17273 ArraySet<CrossProfileIntentFilter> set = 17274 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17275 for (CrossProfileIntentFilter filter : set) { 17276 if (filter.getOwnerPackage().equals(ownerPackage)) { 17277 resolver.removeFilter(filter); 17278 } 17279 } 17280 scheduleWritePackageRestrictionsLocked(sourceUserId); 17281 } 17282 } 17283 17284 // Enforcing that callingUid is owning pkg on userId 17285 private void enforceOwnerRights(String pkg, int callingUid) { 17286 // The system owns everything. 17287 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17288 return; 17289 } 17290 int callingUserId = UserHandle.getUserId(callingUid); 17291 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17292 if (pi == null) { 17293 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17294 + callingUserId); 17295 } 17296 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17297 throw new SecurityException("Calling uid " + callingUid 17298 + " does not own package " + pkg); 17299 } 17300 } 17301 17302 @Override 17303 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17304 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17305 } 17306 17307 private Intent getHomeIntent() { 17308 Intent intent = new Intent(Intent.ACTION_MAIN); 17309 intent.addCategory(Intent.CATEGORY_HOME); 17310 return intent; 17311 } 17312 17313 private IntentFilter getHomeFilter() { 17314 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17315 filter.addCategory(Intent.CATEGORY_HOME); 17316 filter.addCategory(Intent.CATEGORY_DEFAULT); 17317 return filter; 17318 } 17319 17320 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17321 int userId) { 17322 Intent intent = getHomeIntent(); 17323 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17324 PackageManager.GET_META_DATA, userId); 17325 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17326 true, false, false, userId); 17327 17328 allHomeCandidates.clear(); 17329 if (list != null) { 17330 for (ResolveInfo ri : list) { 17331 allHomeCandidates.add(ri); 17332 } 17333 } 17334 return (preferred == null || preferred.activityInfo == null) 17335 ? null 17336 : new ComponentName(preferred.activityInfo.packageName, 17337 preferred.activityInfo.name); 17338 } 17339 17340 @Override 17341 public void setHomeActivity(ComponentName comp, int userId) { 17342 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17343 getHomeActivitiesAsUser(homeActivities, userId); 17344 17345 boolean found = false; 17346 17347 final int size = homeActivities.size(); 17348 final ComponentName[] set = new ComponentName[size]; 17349 for (int i = 0; i < size; i++) { 17350 final ResolveInfo candidate = homeActivities.get(i); 17351 final ActivityInfo info = candidate.activityInfo; 17352 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17353 set[i] = activityName; 17354 if (!found && activityName.equals(comp)) { 17355 found = true; 17356 } 17357 } 17358 if (!found) { 17359 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17360 + userId); 17361 } 17362 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17363 set, comp, userId); 17364 } 17365 17366 private @Nullable String getSetupWizardPackageName() { 17367 final Intent intent = new Intent(Intent.ACTION_MAIN); 17368 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17369 17370 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17371 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17372 | MATCH_DISABLED_COMPONENTS, 17373 UserHandle.myUserId()); 17374 if (matches.size() == 1) { 17375 return matches.get(0).getComponentInfo().packageName; 17376 } else { 17377 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17378 + ": matches=" + matches); 17379 return null; 17380 } 17381 } 17382 17383 @Override 17384 public void setApplicationEnabledSetting(String appPackageName, 17385 int newState, int flags, int userId, String callingPackage) { 17386 if (!sUserManager.exists(userId)) return; 17387 if (callingPackage == null) { 17388 callingPackage = Integer.toString(Binder.getCallingUid()); 17389 } 17390 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17391 } 17392 17393 @Override 17394 public void setComponentEnabledSetting(ComponentName componentName, 17395 int newState, int flags, int userId) { 17396 if (!sUserManager.exists(userId)) return; 17397 setEnabledSetting(componentName.getPackageName(), 17398 componentName.getClassName(), newState, flags, userId, null); 17399 } 17400 17401 private void setEnabledSetting(final String packageName, String className, int newState, 17402 final int flags, int userId, String callingPackage) { 17403 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17404 || newState == COMPONENT_ENABLED_STATE_ENABLED 17405 || newState == COMPONENT_ENABLED_STATE_DISABLED 17406 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17407 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17408 throw new IllegalArgumentException("Invalid new component state: " 17409 + newState); 17410 } 17411 PackageSetting pkgSetting; 17412 final int uid = Binder.getCallingUid(); 17413 final int permission; 17414 if (uid == Process.SYSTEM_UID) { 17415 permission = PackageManager.PERMISSION_GRANTED; 17416 } else { 17417 permission = mContext.checkCallingOrSelfPermission( 17418 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17419 } 17420 enforceCrossUserPermission(uid, userId, 17421 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17422 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17423 boolean sendNow = false; 17424 boolean isApp = (className == null); 17425 String componentName = isApp ? packageName : className; 17426 int packageUid = -1; 17427 ArrayList<String> components; 17428 17429 // writer 17430 synchronized (mPackages) { 17431 pkgSetting = mSettings.mPackages.get(packageName); 17432 if (pkgSetting == null) { 17433 if (className == null) { 17434 throw new IllegalArgumentException("Unknown package: " + packageName); 17435 } 17436 throw new IllegalArgumentException( 17437 "Unknown component: " + packageName + "/" + className); 17438 } 17439 // Allow root and verify that userId is not being specified by a different user 17440 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17441 throw new SecurityException( 17442 "Permission Denial: attempt to change component state from pid=" 17443 + Binder.getCallingPid() 17444 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17445 } 17446 if (className == null) { 17447 // We're dealing with an application/package level state change 17448 if (pkgSetting.getEnabled(userId) == newState) { 17449 // Nothing to do 17450 return; 17451 } 17452 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17453 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17454 // Don't care about who enables an app. 17455 callingPackage = null; 17456 } 17457 pkgSetting.setEnabled(newState, userId, callingPackage); 17458 // pkgSetting.pkg.mSetEnabled = newState; 17459 } else { 17460 // We're dealing with a component level state change 17461 // First, verify that this is a valid class name. 17462 PackageParser.Package pkg = pkgSetting.pkg; 17463 if (pkg == null || !pkg.hasComponentClassName(className)) { 17464 if (pkg != null && 17465 pkg.applicationInfo.targetSdkVersion >= 17466 Build.VERSION_CODES.JELLY_BEAN) { 17467 throw new IllegalArgumentException("Component class " + className 17468 + " does not exist in " + packageName); 17469 } else { 17470 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17471 + className + " does not exist in " + packageName); 17472 } 17473 } 17474 switch (newState) { 17475 case COMPONENT_ENABLED_STATE_ENABLED: 17476 if (!pkgSetting.enableComponentLPw(className, userId)) { 17477 return; 17478 } 17479 break; 17480 case COMPONENT_ENABLED_STATE_DISABLED: 17481 if (!pkgSetting.disableComponentLPw(className, userId)) { 17482 return; 17483 } 17484 break; 17485 case COMPONENT_ENABLED_STATE_DEFAULT: 17486 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17487 return; 17488 } 17489 break; 17490 default: 17491 Slog.e(TAG, "Invalid new component state: " + newState); 17492 return; 17493 } 17494 } 17495 scheduleWritePackageRestrictionsLocked(userId); 17496 components = mPendingBroadcasts.get(userId, packageName); 17497 final boolean newPackage = components == null; 17498 if (newPackage) { 17499 components = new ArrayList<String>(); 17500 } 17501 if (!components.contains(componentName)) { 17502 components.add(componentName); 17503 } 17504 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17505 sendNow = true; 17506 // Purge entry from pending broadcast list if another one exists already 17507 // since we are sending one right away. 17508 mPendingBroadcasts.remove(userId, packageName); 17509 } else { 17510 if (newPackage) { 17511 mPendingBroadcasts.put(userId, packageName, components); 17512 } 17513 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17514 // Schedule a message 17515 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17516 } 17517 } 17518 } 17519 17520 long callingId = Binder.clearCallingIdentity(); 17521 try { 17522 if (sendNow) { 17523 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17524 sendPackageChangedBroadcast(packageName, 17525 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17526 } 17527 } finally { 17528 Binder.restoreCallingIdentity(callingId); 17529 } 17530 } 17531 17532 @Override 17533 public void flushPackageRestrictionsAsUser(int userId) { 17534 if (!sUserManager.exists(userId)) { 17535 return; 17536 } 17537 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17538 false /* checkShell */, "flushPackageRestrictions"); 17539 synchronized (mPackages) { 17540 mSettings.writePackageRestrictionsLPr(userId); 17541 mDirtyUsers.remove(userId); 17542 if (mDirtyUsers.isEmpty()) { 17543 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17544 } 17545 } 17546 } 17547 17548 private void sendPackageChangedBroadcast(String packageName, 17549 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17550 if (DEBUG_INSTALL) 17551 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17552 + componentNames); 17553 Bundle extras = new Bundle(4); 17554 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17555 String nameList[] = new String[componentNames.size()]; 17556 componentNames.toArray(nameList); 17557 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17558 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17559 extras.putInt(Intent.EXTRA_UID, packageUid); 17560 // If this is not reporting a change of the overall package, then only send it 17561 // to registered receivers. We don't want to launch a swath of apps for every 17562 // little component state change. 17563 final int flags = !componentNames.contains(packageName) 17564 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17565 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17566 new int[] {UserHandle.getUserId(packageUid)}); 17567 } 17568 17569 @Override 17570 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17571 if (!sUserManager.exists(userId)) return; 17572 final int uid = Binder.getCallingUid(); 17573 final int permission = mContext.checkCallingOrSelfPermission( 17574 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17575 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17576 enforceCrossUserPermission(uid, userId, 17577 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17578 // writer 17579 synchronized (mPackages) { 17580 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17581 allowedByPermission, uid, userId)) { 17582 scheduleWritePackageRestrictionsLocked(userId); 17583 } 17584 } 17585 } 17586 17587 @Override 17588 public String getInstallerPackageName(String packageName) { 17589 // reader 17590 synchronized (mPackages) { 17591 return mSettings.getInstallerPackageNameLPr(packageName); 17592 } 17593 } 17594 17595 public boolean isOrphaned(String packageName) { 17596 // reader 17597 synchronized (mPackages) { 17598 return mSettings.isOrphaned(packageName); 17599 } 17600 } 17601 17602 @Override 17603 public int getApplicationEnabledSetting(String packageName, int userId) { 17604 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17605 int uid = Binder.getCallingUid(); 17606 enforceCrossUserPermission(uid, userId, 17607 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17608 // reader 17609 synchronized (mPackages) { 17610 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17611 } 17612 } 17613 17614 @Override 17615 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17616 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17617 int uid = Binder.getCallingUid(); 17618 enforceCrossUserPermission(uid, userId, 17619 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17620 // reader 17621 synchronized (mPackages) { 17622 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17623 } 17624 } 17625 17626 @Override 17627 public void enterSafeMode() { 17628 enforceSystemOrRoot("Only the system can request entering safe mode"); 17629 17630 if (!mSystemReady) { 17631 mSafeMode = true; 17632 } 17633 } 17634 17635 @Override 17636 public void systemReady() { 17637 mSystemReady = true; 17638 17639 // Read the compatibilty setting when the system is ready. 17640 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17641 mContext.getContentResolver(), 17642 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17643 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17644 if (DEBUG_SETTINGS) { 17645 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17646 } 17647 17648 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17649 17650 synchronized (mPackages) { 17651 // Verify that all of the preferred activity components actually 17652 // exist. It is possible for applications to be updated and at 17653 // that point remove a previously declared activity component that 17654 // had been set as a preferred activity. We try to clean this up 17655 // the next time we encounter that preferred activity, but it is 17656 // possible for the user flow to never be able to return to that 17657 // situation so here we do a sanity check to make sure we haven't 17658 // left any junk around. 17659 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17660 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17661 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17662 removed.clear(); 17663 for (PreferredActivity pa : pir.filterSet()) { 17664 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17665 removed.add(pa); 17666 } 17667 } 17668 if (removed.size() > 0) { 17669 for (int r=0; r<removed.size(); r++) { 17670 PreferredActivity pa = removed.get(r); 17671 Slog.w(TAG, "Removing dangling preferred activity: " 17672 + pa.mPref.mComponent); 17673 pir.removeFilter(pa); 17674 } 17675 mSettings.writePackageRestrictionsLPr( 17676 mSettings.mPreferredActivities.keyAt(i)); 17677 } 17678 } 17679 17680 for (int userId : UserManagerService.getInstance().getUserIds()) { 17681 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17682 grantPermissionsUserIds = ArrayUtils.appendInt( 17683 grantPermissionsUserIds, userId); 17684 } 17685 } 17686 } 17687 sUserManager.systemReady(); 17688 17689 // If we upgraded grant all default permissions before kicking off. 17690 for (int userId : grantPermissionsUserIds) { 17691 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17692 } 17693 17694 // Kick off any messages waiting for system ready 17695 if (mPostSystemReadyMessages != null) { 17696 for (Message msg : mPostSystemReadyMessages) { 17697 msg.sendToTarget(); 17698 } 17699 mPostSystemReadyMessages = null; 17700 } 17701 17702 // Watch for external volumes that come and go over time 17703 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17704 storage.registerListener(mStorageListener); 17705 17706 mInstallerService.systemReady(); 17707 mPackageDexOptimizer.systemReady(); 17708 17709 MountServiceInternal mountServiceInternal = LocalServices.getService( 17710 MountServiceInternal.class); 17711 mountServiceInternal.addExternalStoragePolicy( 17712 new MountServiceInternal.ExternalStorageMountPolicy() { 17713 @Override 17714 public int getMountMode(int uid, String packageName) { 17715 if (Process.isIsolated(uid)) { 17716 return Zygote.MOUNT_EXTERNAL_NONE; 17717 } 17718 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17719 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17720 } 17721 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17722 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17723 } 17724 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17725 return Zygote.MOUNT_EXTERNAL_READ; 17726 } 17727 return Zygote.MOUNT_EXTERNAL_WRITE; 17728 } 17729 17730 @Override 17731 public boolean hasExternalStorage(int uid, String packageName) { 17732 return true; 17733 } 17734 }); 17735 17736 // Now that we're mostly running, clean up stale users and apps 17737 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17738 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17739 } 17740 17741 @Override 17742 public boolean isSafeMode() { 17743 return mSafeMode; 17744 } 17745 17746 @Override 17747 public boolean hasSystemUidErrors() { 17748 return mHasSystemUidErrors; 17749 } 17750 17751 static String arrayToString(int[] array) { 17752 StringBuffer buf = new StringBuffer(128); 17753 buf.append('['); 17754 if (array != null) { 17755 for (int i=0; i<array.length; i++) { 17756 if (i > 0) buf.append(", "); 17757 buf.append(array[i]); 17758 } 17759 } 17760 buf.append(']'); 17761 return buf.toString(); 17762 } 17763 17764 static class DumpState { 17765 public static final int DUMP_LIBS = 1 << 0; 17766 public static final int DUMP_FEATURES = 1 << 1; 17767 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17768 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17769 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17770 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17771 public static final int DUMP_PERMISSIONS = 1 << 6; 17772 public static final int DUMP_PACKAGES = 1 << 7; 17773 public static final int DUMP_SHARED_USERS = 1 << 8; 17774 public static final int DUMP_MESSAGES = 1 << 9; 17775 public static final int DUMP_PROVIDERS = 1 << 10; 17776 public static final int DUMP_VERIFIERS = 1 << 11; 17777 public static final int DUMP_PREFERRED = 1 << 12; 17778 public static final int DUMP_PREFERRED_XML = 1 << 13; 17779 public static final int DUMP_KEYSETS = 1 << 14; 17780 public static final int DUMP_VERSION = 1 << 15; 17781 public static final int DUMP_INSTALLS = 1 << 16; 17782 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17783 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17784 public static final int DUMP_FROZEN = 1 << 19; 17785 17786 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17787 17788 private int mTypes; 17789 17790 private int mOptions; 17791 17792 private boolean mTitlePrinted; 17793 17794 private SharedUserSetting mSharedUser; 17795 17796 public boolean isDumping(int type) { 17797 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17798 return true; 17799 } 17800 17801 return (mTypes & type) != 0; 17802 } 17803 17804 public void setDump(int type) { 17805 mTypes |= type; 17806 } 17807 17808 public boolean isOptionEnabled(int option) { 17809 return (mOptions & option) != 0; 17810 } 17811 17812 public void setOptionEnabled(int option) { 17813 mOptions |= option; 17814 } 17815 17816 public boolean onTitlePrinted() { 17817 final boolean printed = mTitlePrinted; 17818 mTitlePrinted = true; 17819 return printed; 17820 } 17821 17822 public boolean getTitlePrinted() { 17823 return mTitlePrinted; 17824 } 17825 17826 public void setTitlePrinted(boolean enabled) { 17827 mTitlePrinted = enabled; 17828 } 17829 17830 public SharedUserSetting getSharedUser() { 17831 return mSharedUser; 17832 } 17833 17834 public void setSharedUser(SharedUserSetting user) { 17835 mSharedUser = user; 17836 } 17837 } 17838 17839 @Override 17840 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17841 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17842 (new PackageManagerShellCommand(this)).exec( 17843 this, in, out, err, args, resultReceiver); 17844 } 17845 17846 @Override 17847 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17848 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17849 != PackageManager.PERMISSION_GRANTED) { 17850 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17851 + Binder.getCallingPid() 17852 + ", uid=" + Binder.getCallingUid() 17853 + " without permission " 17854 + android.Manifest.permission.DUMP); 17855 return; 17856 } 17857 17858 DumpState dumpState = new DumpState(); 17859 boolean fullPreferred = false; 17860 boolean checkin = false; 17861 17862 String packageName = null; 17863 ArraySet<String> permissionNames = null; 17864 17865 int opti = 0; 17866 while (opti < args.length) { 17867 String opt = args[opti]; 17868 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17869 break; 17870 } 17871 opti++; 17872 17873 if ("-a".equals(opt)) { 17874 // Right now we only know how to print all. 17875 } else if ("-h".equals(opt)) { 17876 pw.println("Package manager dump options:"); 17877 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17878 pw.println(" --checkin: dump for a checkin"); 17879 pw.println(" -f: print details of intent filters"); 17880 pw.println(" -h: print this help"); 17881 pw.println(" cmd may be one of:"); 17882 pw.println(" l[ibraries]: list known shared libraries"); 17883 pw.println(" f[eatures]: list device features"); 17884 pw.println(" k[eysets]: print known keysets"); 17885 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17886 pw.println(" perm[issions]: dump permissions"); 17887 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17888 pw.println(" pref[erred]: print preferred package settings"); 17889 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17890 pw.println(" prov[iders]: dump content providers"); 17891 pw.println(" p[ackages]: dump installed packages"); 17892 pw.println(" s[hared-users]: dump shared user IDs"); 17893 pw.println(" m[essages]: print collected runtime messages"); 17894 pw.println(" v[erifiers]: print package verifier info"); 17895 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17896 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17897 pw.println(" version: print database version info"); 17898 pw.println(" write: write current settings now"); 17899 pw.println(" installs: details about install sessions"); 17900 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17901 pw.println(" <package.name>: info about given package"); 17902 return; 17903 } else if ("--checkin".equals(opt)) { 17904 checkin = true; 17905 } else if ("-f".equals(opt)) { 17906 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17907 } else { 17908 pw.println("Unknown argument: " + opt + "; use -h for help"); 17909 } 17910 } 17911 17912 // Is the caller requesting to dump a particular piece of data? 17913 if (opti < args.length) { 17914 String cmd = args[opti]; 17915 opti++; 17916 // Is this a package name? 17917 if ("android".equals(cmd) || cmd.contains(".")) { 17918 packageName = cmd; 17919 // When dumping a single package, we always dump all of its 17920 // filter information since the amount of data will be reasonable. 17921 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17922 } else if ("check-permission".equals(cmd)) { 17923 if (opti >= args.length) { 17924 pw.println("Error: check-permission missing permission argument"); 17925 return; 17926 } 17927 String perm = args[opti]; 17928 opti++; 17929 if (opti >= args.length) { 17930 pw.println("Error: check-permission missing package argument"); 17931 return; 17932 } 17933 String pkg = args[opti]; 17934 opti++; 17935 int user = UserHandle.getUserId(Binder.getCallingUid()); 17936 if (opti < args.length) { 17937 try { 17938 user = Integer.parseInt(args[opti]); 17939 } catch (NumberFormatException e) { 17940 pw.println("Error: check-permission user argument is not a number: " 17941 + args[opti]); 17942 return; 17943 } 17944 } 17945 pw.println(checkPermission(perm, pkg, user)); 17946 return; 17947 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17948 dumpState.setDump(DumpState.DUMP_LIBS); 17949 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17950 dumpState.setDump(DumpState.DUMP_FEATURES); 17951 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17952 if (opti >= args.length) { 17953 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17954 | DumpState.DUMP_SERVICE_RESOLVERS 17955 | DumpState.DUMP_RECEIVER_RESOLVERS 17956 | DumpState.DUMP_CONTENT_RESOLVERS); 17957 } else { 17958 while (opti < args.length) { 17959 String name = args[opti]; 17960 if ("a".equals(name) || "activity".equals(name)) { 17961 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17962 } else if ("s".equals(name) || "service".equals(name)) { 17963 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17964 } else if ("r".equals(name) || "receiver".equals(name)) { 17965 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17966 } else if ("c".equals(name) || "content".equals(name)) { 17967 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17968 } else { 17969 pw.println("Error: unknown resolver table type: " + name); 17970 return; 17971 } 17972 opti++; 17973 } 17974 } 17975 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17976 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17977 } else if ("permission".equals(cmd)) { 17978 if (opti >= args.length) { 17979 pw.println("Error: permission requires permission name"); 17980 return; 17981 } 17982 permissionNames = new ArraySet<>(); 17983 while (opti < args.length) { 17984 permissionNames.add(args[opti]); 17985 opti++; 17986 } 17987 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17988 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17989 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17990 dumpState.setDump(DumpState.DUMP_PREFERRED); 17991 } else if ("preferred-xml".equals(cmd)) { 17992 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17993 if (opti < args.length && "--full".equals(args[opti])) { 17994 fullPreferred = true; 17995 opti++; 17996 } 17997 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17998 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17999 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18000 dumpState.setDump(DumpState.DUMP_PACKAGES); 18001 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18002 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18003 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18004 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18005 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18006 dumpState.setDump(DumpState.DUMP_MESSAGES); 18007 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18008 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18009 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18010 || "intent-filter-verifiers".equals(cmd)) { 18011 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18012 } else if ("version".equals(cmd)) { 18013 dumpState.setDump(DumpState.DUMP_VERSION); 18014 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18015 dumpState.setDump(DumpState.DUMP_KEYSETS); 18016 } else if ("installs".equals(cmd)) { 18017 dumpState.setDump(DumpState.DUMP_INSTALLS); 18018 } else if ("frozen".equals(cmd)) { 18019 dumpState.setDump(DumpState.DUMP_FROZEN); 18020 } else if ("write".equals(cmd)) { 18021 synchronized (mPackages) { 18022 mSettings.writeLPr(); 18023 pw.println("Settings written."); 18024 return; 18025 } 18026 } 18027 } 18028 18029 if (checkin) { 18030 pw.println("vers,1"); 18031 } 18032 18033 // reader 18034 synchronized (mPackages) { 18035 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18036 if (!checkin) { 18037 if (dumpState.onTitlePrinted()) 18038 pw.println(); 18039 pw.println("Database versions:"); 18040 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18041 } 18042 } 18043 18044 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18045 if (!checkin) { 18046 if (dumpState.onTitlePrinted()) 18047 pw.println(); 18048 pw.println("Verifiers:"); 18049 pw.print(" Required: "); 18050 pw.print(mRequiredVerifierPackage); 18051 pw.print(" (uid="); 18052 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18053 UserHandle.USER_SYSTEM)); 18054 pw.println(")"); 18055 } else if (mRequiredVerifierPackage != null) { 18056 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18057 pw.print(","); 18058 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18059 UserHandle.USER_SYSTEM)); 18060 } 18061 } 18062 18063 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18064 packageName == null) { 18065 if (mIntentFilterVerifierComponent != null) { 18066 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18067 if (!checkin) { 18068 if (dumpState.onTitlePrinted()) 18069 pw.println(); 18070 pw.println("Intent Filter Verifier:"); 18071 pw.print(" Using: "); 18072 pw.print(verifierPackageName); 18073 pw.print(" (uid="); 18074 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18075 UserHandle.USER_SYSTEM)); 18076 pw.println(")"); 18077 } else if (verifierPackageName != null) { 18078 pw.print("ifv,"); pw.print(verifierPackageName); 18079 pw.print(","); 18080 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18081 UserHandle.USER_SYSTEM)); 18082 } 18083 } else { 18084 pw.println(); 18085 pw.println("No Intent Filter Verifier available!"); 18086 } 18087 } 18088 18089 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18090 boolean printedHeader = false; 18091 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18092 while (it.hasNext()) { 18093 String name = it.next(); 18094 SharedLibraryEntry ent = mSharedLibraries.get(name); 18095 if (!checkin) { 18096 if (!printedHeader) { 18097 if (dumpState.onTitlePrinted()) 18098 pw.println(); 18099 pw.println("Libraries:"); 18100 printedHeader = true; 18101 } 18102 pw.print(" "); 18103 } else { 18104 pw.print("lib,"); 18105 } 18106 pw.print(name); 18107 if (!checkin) { 18108 pw.print(" -> "); 18109 } 18110 if (ent.path != null) { 18111 if (!checkin) { 18112 pw.print("(jar) "); 18113 pw.print(ent.path); 18114 } else { 18115 pw.print(",jar,"); 18116 pw.print(ent.path); 18117 } 18118 } else { 18119 if (!checkin) { 18120 pw.print("(apk) "); 18121 pw.print(ent.apk); 18122 } else { 18123 pw.print(",apk,"); 18124 pw.print(ent.apk); 18125 } 18126 } 18127 pw.println(); 18128 } 18129 } 18130 18131 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18132 if (dumpState.onTitlePrinted()) 18133 pw.println(); 18134 if (!checkin) { 18135 pw.println("Features:"); 18136 } 18137 18138 for (FeatureInfo feat : mAvailableFeatures.values()) { 18139 if (checkin) { 18140 pw.print("feat,"); 18141 pw.print(feat.name); 18142 pw.print(","); 18143 pw.println(feat.version); 18144 } else { 18145 pw.print(" "); 18146 pw.print(feat.name); 18147 if (feat.version > 0) { 18148 pw.print(" version="); 18149 pw.print(feat.version); 18150 } 18151 pw.println(); 18152 } 18153 } 18154 } 18155 18156 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18157 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18158 : "Activity Resolver Table:", " ", packageName, 18159 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18160 dumpState.setTitlePrinted(true); 18161 } 18162 } 18163 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18164 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18165 : "Receiver Resolver Table:", " ", packageName, 18166 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18167 dumpState.setTitlePrinted(true); 18168 } 18169 } 18170 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18171 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18172 : "Service Resolver Table:", " ", packageName, 18173 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18174 dumpState.setTitlePrinted(true); 18175 } 18176 } 18177 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18178 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18179 : "Provider Resolver Table:", " ", packageName, 18180 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18181 dumpState.setTitlePrinted(true); 18182 } 18183 } 18184 18185 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18186 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18187 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18188 int user = mSettings.mPreferredActivities.keyAt(i); 18189 if (pir.dump(pw, 18190 dumpState.getTitlePrinted() 18191 ? "\nPreferred Activities User " + user + ":" 18192 : "Preferred Activities User " + user + ":", " ", 18193 packageName, true, false)) { 18194 dumpState.setTitlePrinted(true); 18195 } 18196 } 18197 } 18198 18199 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18200 pw.flush(); 18201 FileOutputStream fout = new FileOutputStream(fd); 18202 BufferedOutputStream str = new BufferedOutputStream(fout); 18203 XmlSerializer serializer = new FastXmlSerializer(); 18204 try { 18205 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18206 serializer.startDocument(null, true); 18207 serializer.setFeature( 18208 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18209 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18210 serializer.endDocument(); 18211 serializer.flush(); 18212 } catch (IllegalArgumentException e) { 18213 pw.println("Failed writing: " + e); 18214 } catch (IllegalStateException e) { 18215 pw.println("Failed writing: " + e); 18216 } catch (IOException e) { 18217 pw.println("Failed writing: " + e); 18218 } 18219 } 18220 18221 if (!checkin 18222 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18223 && packageName == null) { 18224 pw.println(); 18225 int count = mSettings.mPackages.size(); 18226 if (count == 0) { 18227 pw.println("No applications!"); 18228 pw.println(); 18229 } else { 18230 final String prefix = " "; 18231 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18232 if (allPackageSettings.size() == 0) { 18233 pw.println("No domain preferred apps!"); 18234 pw.println(); 18235 } else { 18236 pw.println("App verification status:"); 18237 pw.println(); 18238 count = 0; 18239 for (PackageSetting ps : allPackageSettings) { 18240 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18241 if (ivi == null || ivi.getPackageName() == null) continue; 18242 pw.println(prefix + "Package: " + ivi.getPackageName()); 18243 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18244 pw.println(prefix + "Status: " + ivi.getStatusString()); 18245 pw.println(); 18246 count++; 18247 } 18248 if (count == 0) { 18249 pw.println(prefix + "No app verification established."); 18250 pw.println(); 18251 } 18252 for (int userId : sUserManager.getUserIds()) { 18253 pw.println("App linkages for user " + userId + ":"); 18254 pw.println(); 18255 count = 0; 18256 for (PackageSetting ps : allPackageSettings) { 18257 final long status = ps.getDomainVerificationStatusForUser(userId); 18258 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18259 continue; 18260 } 18261 pw.println(prefix + "Package: " + ps.name); 18262 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18263 String statusStr = IntentFilterVerificationInfo. 18264 getStatusStringFromValue(status); 18265 pw.println(prefix + "Status: " + statusStr); 18266 pw.println(); 18267 count++; 18268 } 18269 if (count == 0) { 18270 pw.println(prefix + "No configured app linkages."); 18271 pw.println(); 18272 } 18273 } 18274 } 18275 } 18276 } 18277 18278 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18279 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18280 if (packageName == null && permissionNames == null) { 18281 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18282 if (iperm == 0) { 18283 if (dumpState.onTitlePrinted()) 18284 pw.println(); 18285 pw.println("AppOp Permissions:"); 18286 } 18287 pw.print(" AppOp Permission "); 18288 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18289 pw.println(":"); 18290 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18291 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18292 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18293 } 18294 } 18295 } 18296 } 18297 18298 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18299 boolean printedSomething = false; 18300 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18301 if (packageName != null && !packageName.equals(p.info.packageName)) { 18302 continue; 18303 } 18304 if (!printedSomething) { 18305 if (dumpState.onTitlePrinted()) 18306 pw.println(); 18307 pw.println("Registered ContentProviders:"); 18308 printedSomething = true; 18309 } 18310 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18311 pw.print(" "); pw.println(p.toString()); 18312 } 18313 printedSomething = false; 18314 for (Map.Entry<String, PackageParser.Provider> entry : 18315 mProvidersByAuthority.entrySet()) { 18316 PackageParser.Provider p = entry.getValue(); 18317 if (packageName != null && !packageName.equals(p.info.packageName)) { 18318 continue; 18319 } 18320 if (!printedSomething) { 18321 if (dumpState.onTitlePrinted()) 18322 pw.println(); 18323 pw.println("ContentProvider Authorities:"); 18324 printedSomething = true; 18325 } 18326 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18327 pw.print(" "); pw.println(p.toString()); 18328 if (p.info != null && p.info.applicationInfo != null) { 18329 final String appInfo = p.info.applicationInfo.toString(); 18330 pw.print(" applicationInfo="); pw.println(appInfo); 18331 } 18332 } 18333 } 18334 18335 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18336 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18337 } 18338 18339 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18340 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18341 } 18342 18343 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18344 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18345 } 18346 18347 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18348 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18349 } 18350 18351 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18352 // XXX should handle packageName != null by dumping only install data that 18353 // the given package is involved with. 18354 if (dumpState.onTitlePrinted()) pw.println(); 18355 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18356 } 18357 18358 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18359 // XXX should handle packageName != null by dumping only install data that 18360 // the given package is involved with. 18361 if (dumpState.onTitlePrinted()) pw.println(); 18362 18363 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18364 ipw.println(); 18365 ipw.println("Frozen packages:"); 18366 ipw.increaseIndent(); 18367 if (mFrozenPackages.size() == 0) { 18368 ipw.println("(none)"); 18369 } else { 18370 for (int i = 0; i < mFrozenPackages.size(); i++) { 18371 ipw.println(mFrozenPackages.valueAt(i)); 18372 } 18373 } 18374 ipw.decreaseIndent(); 18375 } 18376 18377 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18378 if (dumpState.onTitlePrinted()) pw.println(); 18379 mSettings.dumpReadMessagesLPr(pw, dumpState); 18380 18381 pw.println(); 18382 pw.println("Package warning messages:"); 18383 BufferedReader in = null; 18384 String line = null; 18385 try { 18386 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18387 while ((line = in.readLine()) != null) { 18388 if (line.contains("ignored: updated version")) continue; 18389 pw.println(line); 18390 } 18391 } catch (IOException ignored) { 18392 } finally { 18393 IoUtils.closeQuietly(in); 18394 } 18395 } 18396 18397 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18398 BufferedReader in = null; 18399 String line = null; 18400 try { 18401 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18402 while ((line = in.readLine()) != null) { 18403 if (line.contains("ignored: updated version")) continue; 18404 pw.print("msg,"); 18405 pw.println(line); 18406 } 18407 } catch (IOException ignored) { 18408 } finally { 18409 IoUtils.closeQuietly(in); 18410 } 18411 } 18412 } 18413 } 18414 18415 private String dumpDomainString(String packageName) { 18416 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18417 .getList(); 18418 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18419 18420 ArraySet<String> result = new ArraySet<>(); 18421 if (iviList.size() > 0) { 18422 for (IntentFilterVerificationInfo ivi : iviList) { 18423 for (String host : ivi.getDomains()) { 18424 result.add(host); 18425 } 18426 } 18427 } 18428 if (filters != null && filters.size() > 0) { 18429 for (IntentFilter filter : filters) { 18430 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18431 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18432 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18433 result.addAll(filter.getHostsList()); 18434 } 18435 } 18436 } 18437 18438 StringBuilder sb = new StringBuilder(result.size() * 16); 18439 for (String domain : result) { 18440 if (sb.length() > 0) sb.append(" "); 18441 sb.append(domain); 18442 } 18443 return sb.toString(); 18444 } 18445 18446 // ------- apps on sdcard specific code ------- 18447 static final boolean DEBUG_SD_INSTALL = false; 18448 18449 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18450 18451 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18452 18453 private boolean mMediaMounted = false; 18454 18455 static String getEncryptKey() { 18456 try { 18457 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18458 SD_ENCRYPTION_KEYSTORE_NAME); 18459 if (sdEncKey == null) { 18460 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18461 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18462 if (sdEncKey == null) { 18463 Slog.e(TAG, "Failed to create encryption keys"); 18464 return null; 18465 } 18466 } 18467 return sdEncKey; 18468 } catch (NoSuchAlgorithmException nsae) { 18469 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18470 return null; 18471 } catch (IOException ioe) { 18472 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18473 return null; 18474 } 18475 } 18476 18477 /* 18478 * Update media status on PackageManager. 18479 */ 18480 @Override 18481 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18482 int callingUid = Binder.getCallingUid(); 18483 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18484 throw new SecurityException("Media status can only be updated by the system"); 18485 } 18486 // reader; this apparently protects mMediaMounted, but should probably 18487 // be a different lock in that case. 18488 synchronized (mPackages) { 18489 Log.i(TAG, "Updating external media status from " 18490 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18491 + (mediaStatus ? "mounted" : "unmounted")); 18492 if (DEBUG_SD_INSTALL) 18493 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18494 + ", mMediaMounted=" + mMediaMounted); 18495 if (mediaStatus == mMediaMounted) { 18496 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18497 : 0, -1); 18498 mHandler.sendMessage(msg); 18499 return; 18500 } 18501 mMediaMounted = mediaStatus; 18502 } 18503 // Queue up an async operation since the package installation may take a 18504 // little while. 18505 mHandler.post(new Runnable() { 18506 public void run() { 18507 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18508 } 18509 }); 18510 } 18511 18512 /** 18513 * Called by MountService when the initial ASECs to scan are available. 18514 * Should block until all the ASEC containers are finished being scanned. 18515 */ 18516 public void scanAvailableAsecs() { 18517 updateExternalMediaStatusInner(true, false, false); 18518 } 18519 18520 /* 18521 * Collect information of applications on external media, map them against 18522 * existing containers and update information based on current mount status. 18523 * Please note that we always have to report status if reportStatus has been 18524 * set to true especially when unloading packages. 18525 */ 18526 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18527 boolean externalStorage) { 18528 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18529 int[] uidArr = EmptyArray.INT; 18530 18531 final String[] list = PackageHelper.getSecureContainerList(); 18532 if (ArrayUtils.isEmpty(list)) { 18533 Log.i(TAG, "No secure containers found"); 18534 } else { 18535 // Process list of secure containers and categorize them 18536 // as active or stale based on their package internal state. 18537 18538 // reader 18539 synchronized (mPackages) { 18540 for (String cid : list) { 18541 // Leave stages untouched for now; installer service owns them 18542 if (PackageInstallerService.isStageName(cid)) continue; 18543 18544 if (DEBUG_SD_INSTALL) 18545 Log.i(TAG, "Processing container " + cid); 18546 String pkgName = getAsecPackageName(cid); 18547 if (pkgName == null) { 18548 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18549 continue; 18550 } 18551 if (DEBUG_SD_INSTALL) 18552 Log.i(TAG, "Looking for pkg : " + pkgName); 18553 18554 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18555 if (ps == null) { 18556 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18557 continue; 18558 } 18559 18560 /* 18561 * Skip packages that are not external if we're unmounting 18562 * external storage. 18563 */ 18564 if (externalStorage && !isMounted && !isExternal(ps)) { 18565 continue; 18566 } 18567 18568 final AsecInstallArgs args = new AsecInstallArgs(cid, 18569 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18570 // The package status is changed only if the code path 18571 // matches between settings and the container id. 18572 if (ps.codePathString != null 18573 && ps.codePathString.startsWith(args.getCodePath())) { 18574 if (DEBUG_SD_INSTALL) { 18575 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18576 + " at code path: " + ps.codePathString); 18577 } 18578 18579 // We do have a valid package installed on sdcard 18580 processCids.put(args, ps.codePathString); 18581 final int uid = ps.appId; 18582 if (uid != -1) { 18583 uidArr = ArrayUtils.appendInt(uidArr, uid); 18584 } 18585 } else { 18586 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18587 + ps.codePathString); 18588 } 18589 } 18590 } 18591 18592 Arrays.sort(uidArr); 18593 } 18594 18595 // Process packages with valid entries. 18596 if (isMounted) { 18597 if (DEBUG_SD_INSTALL) 18598 Log.i(TAG, "Loading packages"); 18599 loadMediaPackages(processCids, uidArr, externalStorage); 18600 startCleaningPackages(); 18601 mInstallerService.onSecureContainersAvailable(); 18602 } else { 18603 if (DEBUG_SD_INSTALL) 18604 Log.i(TAG, "Unloading packages"); 18605 unloadMediaPackages(processCids, uidArr, reportStatus); 18606 } 18607 } 18608 18609 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18610 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18611 final int size = infos.size(); 18612 final String[] packageNames = new String[size]; 18613 final int[] packageUids = new int[size]; 18614 for (int i = 0; i < size; i++) { 18615 final ApplicationInfo info = infos.get(i); 18616 packageNames[i] = info.packageName; 18617 packageUids[i] = info.uid; 18618 } 18619 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18620 finishedReceiver); 18621 } 18622 18623 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18624 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18625 sendResourcesChangedBroadcast(mediaStatus, replacing, 18626 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18627 } 18628 18629 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18630 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18631 int size = pkgList.length; 18632 if (size > 0) { 18633 // Send broadcasts here 18634 Bundle extras = new Bundle(); 18635 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18636 if (uidArr != null) { 18637 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18638 } 18639 if (replacing) { 18640 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18641 } 18642 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18643 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18644 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18645 } 18646 } 18647 18648 /* 18649 * Look at potentially valid container ids from processCids If package 18650 * information doesn't match the one on record or package scanning fails, 18651 * the cid is added to list of removeCids. We currently don't delete stale 18652 * containers. 18653 */ 18654 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18655 boolean externalStorage) { 18656 ArrayList<String> pkgList = new ArrayList<String>(); 18657 Set<AsecInstallArgs> keys = processCids.keySet(); 18658 18659 for (AsecInstallArgs args : keys) { 18660 String codePath = processCids.get(args); 18661 if (DEBUG_SD_INSTALL) 18662 Log.i(TAG, "Loading container : " + args.cid); 18663 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18664 try { 18665 // Make sure there are no container errors first. 18666 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18667 Slog.e(TAG, "Failed to mount cid : " + args.cid 18668 + " when installing from sdcard"); 18669 continue; 18670 } 18671 // Check code path here. 18672 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18673 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18674 + " does not match one in settings " + codePath); 18675 continue; 18676 } 18677 // Parse package 18678 int parseFlags = mDefParseFlags; 18679 if (args.isExternalAsec()) { 18680 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18681 } 18682 if (args.isFwdLocked()) { 18683 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18684 } 18685 18686 synchronized (mInstallLock) { 18687 PackageParser.Package pkg = null; 18688 try { 18689 // Sadly we don't know the package name yet to freeze it 18690 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18691 SCAN_IGNORE_FROZEN, 0, null); 18692 } catch (PackageManagerException e) { 18693 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18694 } 18695 // Scan the package 18696 if (pkg != null) { 18697 /* 18698 * TODO why is the lock being held? doPostInstall is 18699 * called in other places without the lock. This needs 18700 * to be straightened out. 18701 */ 18702 // writer 18703 synchronized (mPackages) { 18704 retCode = PackageManager.INSTALL_SUCCEEDED; 18705 pkgList.add(pkg.packageName); 18706 // Post process args 18707 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18708 pkg.applicationInfo.uid); 18709 } 18710 } else { 18711 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18712 } 18713 } 18714 18715 } finally { 18716 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18717 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18718 } 18719 } 18720 } 18721 // writer 18722 synchronized (mPackages) { 18723 // If the platform SDK has changed since the last time we booted, 18724 // we need to re-grant app permission to catch any new ones that 18725 // appear. This is really a hack, and means that apps can in some 18726 // cases get permissions that the user didn't initially explicitly 18727 // allow... it would be nice to have some better way to handle 18728 // this situation. 18729 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18730 : mSettings.getInternalVersion(); 18731 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18732 : StorageManager.UUID_PRIVATE_INTERNAL; 18733 18734 int updateFlags = UPDATE_PERMISSIONS_ALL; 18735 if (ver.sdkVersion != mSdkVersion) { 18736 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18737 + mSdkVersion + "; regranting permissions for external"); 18738 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18739 } 18740 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18741 18742 // Yay, everything is now upgraded 18743 ver.forceCurrent(); 18744 18745 // can downgrade to reader 18746 // Persist settings 18747 mSettings.writeLPr(); 18748 } 18749 // Send a broadcast to let everyone know we are done processing 18750 if (pkgList.size() > 0) { 18751 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18752 } 18753 } 18754 18755 /* 18756 * Utility method to unload a list of specified containers 18757 */ 18758 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18759 // Just unmount all valid containers. 18760 for (AsecInstallArgs arg : cidArgs) { 18761 synchronized (mInstallLock) { 18762 arg.doPostDeleteLI(false); 18763 } 18764 } 18765 } 18766 18767 /* 18768 * Unload packages mounted on external media. This involves deleting package 18769 * data from internal structures, sending broadcasts about disabled packages, 18770 * gc'ing to free up references, unmounting all secure containers 18771 * corresponding to packages on external media, and posting a 18772 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18773 * that we always have to post this message if status has been requested no 18774 * matter what. 18775 */ 18776 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18777 final boolean reportStatus) { 18778 if (DEBUG_SD_INSTALL) 18779 Log.i(TAG, "unloading media packages"); 18780 ArrayList<String> pkgList = new ArrayList<String>(); 18781 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18782 final Set<AsecInstallArgs> keys = processCids.keySet(); 18783 for (AsecInstallArgs args : keys) { 18784 String pkgName = args.getPackageName(); 18785 if (DEBUG_SD_INSTALL) 18786 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18787 // Delete package internally 18788 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18789 synchronized (mInstallLock) { 18790 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18791 final boolean res; 18792 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18793 "unloadMediaPackages")) { 18794 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18795 null); 18796 } 18797 if (res) { 18798 pkgList.add(pkgName); 18799 } else { 18800 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18801 failedList.add(args); 18802 } 18803 } 18804 } 18805 18806 // reader 18807 synchronized (mPackages) { 18808 // We didn't update the settings after removing each package; 18809 // write them now for all packages. 18810 mSettings.writeLPr(); 18811 } 18812 18813 // We have to absolutely send UPDATED_MEDIA_STATUS only 18814 // after confirming that all the receivers processed the ordered 18815 // broadcast when packages get disabled, force a gc to clean things up. 18816 // and unload all the containers. 18817 if (pkgList.size() > 0) { 18818 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18819 new IIntentReceiver.Stub() { 18820 public void performReceive(Intent intent, int resultCode, String data, 18821 Bundle extras, boolean ordered, boolean sticky, 18822 int sendingUser) throws RemoteException { 18823 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18824 reportStatus ? 1 : 0, 1, keys); 18825 mHandler.sendMessage(msg); 18826 } 18827 }); 18828 } else { 18829 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18830 keys); 18831 mHandler.sendMessage(msg); 18832 } 18833 } 18834 18835 private void loadPrivatePackages(final VolumeInfo vol) { 18836 mHandler.post(new Runnable() { 18837 @Override 18838 public void run() { 18839 loadPrivatePackagesInner(vol); 18840 } 18841 }); 18842 } 18843 18844 private void loadPrivatePackagesInner(VolumeInfo vol) { 18845 final String volumeUuid = vol.fsUuid; 18846 if (TextUtils.isEmpty(volumeUuid)) { 18847 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18848 return; 18849 } 18850 18851 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18852 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18853 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18854 18855 final VersionInfo ver; 18856 final List<PackageSetting> packages; 18857 synchronized (mPackages) { 18858 ver = mSettings.findOrCreateVersion(volumeUuid); 18859 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18860 } 18861 18862 for (PackageSetting ps : packages) { 18863 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18864 synchronized (mInstallLock) { 18865 final PackageParser.Package pkg; 18866 try { 18867 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18868 loaded.add(pkg.applicationInfo); 18869 18870 } catch (PackageManagerException e) { 18871 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18872 } 18873 18874 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18875 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18876 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18877 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18878 } 18879 } 18880 } 18881 18882 // Reconcile app data for all started/unlocked users 18883 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18884 final UserManager um = mContext.getSystemService(UserManager.class); 18885 for (UserInfo user : um.getUsers()) { 18886 final int flags; 18887 if (um.isUserUnlockingOrUnlocked(user.id)) { 18888 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18889 } else if (um.isUserRunning(user.id)) { 18890 flags = StorageManager.FLAG_STORAGE_DE; 18891 } else { 18892 continue; 18893 } 18894 18895 try { 18896 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18897 synchronized (mInstallLock) { 18898 reconcileAppsDataLI(volumeUuid, user.id, flags); 18899 } 18900 } catch (IllegalStateException e) { 18901 // Device was probably ejected, and we'll process that event momentarily 18902 Slog.w(TAG, "Failed to prepare storage: " + e); 18903 } 18904 } 18905 18906 synchronized (mPackages) { 18907 int updateFlags = UPDATE_PERMISSIONS_ALL; 18908 if (ver.sdkVersion != mSdkVersion) { 18909 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18910 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18911 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18912 } 18913 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18914 18915 // Yay, everything is now upgraded 18916 ver.forceCurrent(); 18917 18918 mSettings.writeLPr(); 18919 } 18920 18921 for (PackageFreezer freezer : freezers) { 18922 freezer.close(); 18923 } 18924 18925 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18926 sendResourcesChangedBroadcast(true, false, loaded, null); 18927 } 18928 18929 private void unloadPrivatePackages(final VolumeInfo vol) { 18930 mHandler.post(new Runnable() { 18931 @Override 18932 public void run() { 18933 unloadPrivatePackagesInner(vol); 18934 } 18935 }); 18936 } 18937 18938 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18939 final String volumeUuid = vol.fsUuid; 18940 if (TextUtils.isEmpty(volumeUuid)) { 18941 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18942 return; 18943 } 18944 18945 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18946 synchronized (mInstallLock) { 18947 synchronized (mPackages) { 18948 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18949 for (PackageSetting ps : packages) { 18950 if (ps.pkg == null) continue; 18951 18952 final ApplicationInfo info = ps.pkg.applicationInfo; 18953 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18954 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18955 18956 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18957 "unloadPrivatePackagesInner")) { 18958 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18959 false, null)) { 18960 unloaded.add(info); 18961 } else { 18962 Slog.w(TAG, "Failed to unload " + ps.codePath); 18963 } 18964 } 18965 } 18966 18967 mSettings.writeLPr(); 18968 } 18969 } 18970 18971 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18972 sendResourcesChangedBroadcast(false, false, unloaded, null); 18973 } 18974 18975 /** 18976 * Prepare storage areas for given user on all mounted devices. 18977 */ 18978 void prepareUserData(int userId, int userSerial, int flags) { 18979 synchronized (mInstallLock) { 18980 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18981 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18982 final String volumeUuid = vol.getFsUuid(); 18983 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18984 } 18985 } 18986 } 18987 18988 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18989 boolean allowRecover) { 18990 // Prepare storage and verify that serial numbers are consistent; if 18991 // there's a mismatch we need to destroy to avoid leaking data 18992 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18993 try { 18994 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18995 18996 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18997 UserManagerService.enforceSerialNumber( 18998 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18999 } 19000 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19001 UserManagerService.enforceSerialNumber( 19002 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19003 } 19004 19005 synchronized (mInstallLock) { 19006 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19007 } 19008 } catch (Exception e) { 19009 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19010 + " because we failed to prepare: " + e); 19011 destroyUserDataLI(volumeUuid, userId, 19012 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19013 19014 if (allowRecover) { 19015 // Try one last time; if we fail again we're really in trouble 19016 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19017 } 19018 } 19019 } 19020 19021 /** 19022 * Destroy storage areas for given user on all mounted devices. 19023 */ 19024 void destroyUserData(int userId, int flags) { 19025 synchronized (mInstallLock) { 19026 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19027 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19028 final String volumeUuid = vol.getFsUuid(); 19029 destroyUserDataLI(volumeUuid, userId, flags); 19030 } 19031 } 19032 } 19033 19034 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19035 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19036 try { 19037 // Clean up app data, profile data, and media data 19038 mInstaller.destroyUserData(volumeUuid, userId, flags); 19039 19040 // Clean up system data 19041 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19042 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19043 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19044 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19045 } 19046 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19047 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19048 } 19049 } 19050 19051 // Data with special labels is now gone, so finish the job 19052 storage.destroyUserStorage(volumeUuid, userId, flags); 19053 19054 } catch (Exception e) { 19055 logCriticalInfo(Log.WARN, 19056 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19057 } 19058 } 19059 19060 /** 19061 * Examine all users present on given mounted volume, and destroy data 19062 * belonging to users that are no longer valid, or whose user ID has been 19063 * recycled. 19064 */ 19065 private void reconcileUsers(String volumeUuid) { 19066 final List<File> files = new ArrayList<>(); 19067 Collections.addAll(files, FileUtils 19068 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19069 Collections.addAll(files, FileUtils 19070 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19071 for (File file : files) { 19072 if (!file.isDirectory()) continue; 19073 19074 final int userId; 19075 final UserInfo info; 19076 try { 19077 userId = Integer.parseInt(file.getName()); 19078 info = sUserManager.getUserInfo(userId); 19079 } catch (NumberFormatException e) { 19080 Slog.w(TAG, "Invalid user directory " + file); 19081 continue; 19082 } 19083 19084 boolean destroyUser = false; 19085 if (info == null) { 19086 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19087 + " because no matching user was found"); 19088 destroyUser = true; 19089 } else if (!mOnlyCore) { 19090 try { 19091 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19092 } catch (IOException e) { 19093 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19094 + " because we failed to enforce serial number: " + e); 19095 destroyUser = true; 19096 } 19097 } 19098 19099 if (destroyUser) { 19100 synchronized (mInstallLock) { 19101 destroyUserDataLI(volumeUuid, userId, 19102 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19103 } 19104 } 19105 } 19106 } 19107 19108 private void assertPackageKnown(String volumeUuid, String packageName) 19109 throws PackageManagerException { 19110 synchronized (mPackages) { 19111 final PackageSetting ps = mSettings.mPackages.get(packageName); 19112 if (ps == null) { 19113 throw new PackageManagerException("Package " + packageName + " is unknown"); 19114 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19115 throw new PackageManagerException( 19116 "Package " + packageName + " found on unknown volume " + volumeUuid 19117 + "; expected volume " + ps.volumeUuid); 19118 } 19119 } 19120 } 19121 19122 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19123 throws PackageManagerException { 19124 synchronized (mPackages) { 19125 final PackageSetting ps = mSettings.mPackages.get(packageName); 19126 if (ps == null) { 19127 throw new PackageManagerException("Package " + packageName + " is unknown"); 19128 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19129 throw new PackageManagerException( 19130 "Package " + packageName + " found on unknown volume " + volumeUuid 19131 + "; expected volume " + ps.volumeUuid); 19132 } else if (!ps.getInstalled(userId)) { 19133 throw new PackageManagerException( 19134 "Package " + packageName + " not installed for user " + userId); 19135 } 19136 } 19137 } 19138 19139 /** 19140 * Examine all apps present on given mounted volume, and destroy apps that 19141 * aren't expected, either due to uninstallation or reinstallation on 19142 * another volume. 19143 */ 19144 private void reconcileApps(String volumeUuid) { 19145 final File[] files = FileUtils 19146 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19147 for (File file : files) { 19148 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19149 && !PackageInstallerService.isStageName(file.getName()); 19150 if (!isPackage) { 19151 // Ignore entries which are not packages 19152 continue; 19153 } 19154 19155 try { 19156 final PackageLite pkg = PackageParser.parsePackageLite(file, 19157 PackageParser.PARSE_MUST_BE_APK); 19158 assertPackageKnown(volumeUuid, pkg.packageName); 19159 19160 } catch (PackageParserException | PackageManagerException e) { 19161 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19162 synchronized (mInstallLock) { 19163 removeCodePathLI(file); 19164 } 19165 } 19166 } 19167 } 19168 19169 /** 19170 * Reconcile all app data for the given user. 19171 * <p> 19172 * Verifies that directories exist and that ownership and labeling is 19173 * correct for all installed apps on all mounted volumes. 19174 */ 19175 void reconcileAppsData(int userId, int flags) { 19176 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19177 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19178 final String volumeUuid = vol.getFsUuid(); 19179 synchronized (mInstallLock) { 19180 reconcileAppsDataLI(volumeUuid, userId, flags); 19181 } 19182 } 19183 } 19184 19185 /** 19186 * Reconcile all app data on given mounted volume. 19187 * <p> 19188 * Destroys app data that isn't expected, either due to uninstallation or 19189 * reinstallation on another volume. 19190 * <p> 19191 * Verifies that directories exist and that ownership and labeling is 19192 * correct for all installed apps. 19193 */ 19194 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19195 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19196 + Integer.toHexString(flags)); 19197 19198 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19199 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19200 19201 boolean restoreconNeeded = false; 19202 19203 // First look for stale data that doesn't belong, and check if things 19204 // have changed since we did our last restorecon 19205 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19206 if (StorageManager.isFileEncryptedNativeOrEmulated() 19207 && !StorageManager.isUserKeyUnlocked(userId)) { 19208 throw new RuntimeException( 19209 "Yikes, someone asked us to reconcile CE storage while " + userId 19210 + " was still locked; this would have caused massive data loss!"); 19211 } 19212 19213 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19214 19215 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19216 for (File file : files) { 19217 final String packageName = file.getName(); 19218 try { 19219 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19220 } catch (PackageManagerException e) { 19221 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19222 try { 19223 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19224 StorageManager.FLAG_STORAGE_CE, 0); 19225 } catch (InstallerException e2) { 19226 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19227 } 19228 } 19229 } 19230 } 19231 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19232 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19233 19234 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19235 for (File file : files) { 19236 final String packageName = file.getName(); 19237 try { 19238 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19239 } catch (PackageManagerException e) { 19240 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19241 try { 19242 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19243 StorageManager.FLAG_STORAGE_DE, 0); 19244 } catch (InstallerException e2) { 19245 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19246 } 19247 } 19248 } 19249 } 19250 19251 // Ensure that data directories are ready to roll for all packages 19252 // installed for this volume and user 19253 final List<PackageSetting> packages; 19254 synchronized (mPackages) { 19255 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19256 } 19257 int preparedCount = 0; 19258 for (PackageSetting ps : packages) { 19259 final String packageName = ps.name; 19260 if (ps.pkg == null) { 19261 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19262 // TODO: might be due to legacy ASEC apps; we should circle back 19263 // and reconcile again once they're scanned 19264 continue; 19265 } 19266 19267 if (ps.getInstalled(userId)) { 19268 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19269 19270 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19271 // We may have just shuffled around app data directories, so 19272 // prepare them one more time 19273 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19274 } 19275 19276 preparedCount++; 19277 } 19278 } 19279 19280 if (restoreconNeeded) { 19281 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19282 SELinuxMMAC.setRestoreconDone(ceDir); 19283 } 19284 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19285 SELinuxMMAC.setRestoreconDone(deDir); 19286 } 19287 } 19288 19289 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19290 + " packages; restoreconNeeded was " + restoreconNeeded); 19291 } 19292 19293 /** 19294 * Prepare app data for the given app just after it was installed or 19295 * upgraded. This method carefully only touches users that it's installed 19296 * for, and it forces a restorecon to handle any seinfo changes. 19297 * <p> 19298 * Verifies that directories exist and that ownership and labeling is 19299 * correct for all installed apps. If there is an ownership mismatch, it 19300 * will try recovering system apps by wiping data; third-party app data is 19301 * left intact. 19302 * <p> 19303 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19304 */ 19305 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19306 final PackageSetting ps; 19307 synchronized (mPackages) { 19308 ps = mSettings.mPackages.get(pkg.packageName); 19309 mSettings.writeKernelMappingLPr(ps); 19310 } 19311 19312 final UserManager um = mContext.getSystemService(UserManager.class); 19313 for (UserInfo user : um.getUsers()) { 19314 final int flags; 19315 if (um.isUserUnlockingOrUnlocked(user.id)) { 19316 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19317 } else if (um.isUserRunning(user.id)) { 19318 flags = StorageManager.FLAG_STORAGE_DE; 19319 } else { 19320 continue; 19321 } 19322 19323 if (ps.getInstalled(user.id)) { 19324 // Whenever an app changes, force a restorecon of its data 19325 // TODO: when user data is locked, mark that we're still dirty 19326 prepareAppDataLIF(pkg, user.id, flags, true); 19327 } 19328 } 19329 } 19330 19331 /** 19332 * Prepare app data for the given app. 19333 * <p> 19334 * Verifies that directories exist and that ownership and labeling is 19335 * correct for all installed apps. If there is an ownership mismatch, this 19336 * will try recovering system apps by wiping data; third-party app data is 19337 * left intact. 19338 */ 19339 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19340 boolean restoreconNeeded) { 19341 if (pkg == null) { 19342 Slog.wtf(TAG, "Package was null!", new Throwable()); 19343 return; 19344 } 19345 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19346 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19347 for (int i = 0; i < childCount; i++) { 19348 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19349 } 19350 } 19351 19352 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19353 boolean restoreconNeeded) { 19354 if (DEBUG_APP_DATA) { 19355 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19356 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19357 } 19358 19359 final String volumeUuid = pkg.volumeUuid; 19360 final String packageName = pkg.packageName; 19361 final ApplicationInfo app = pkg.applicationInfo; 19362 final int appId = UserHandle.getAppId(app.uid); 19363 19364 Preconditions.checkNotNull(app.seinfo); 19365 19366 try { 19367 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19368 appId, app.seinfo, app.targetSdkVersion); 19369 } catch (InstallerException e) { 19370 if (app.isSystemApp()) { 19371 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19372 + ", but trying to recover: " + e); 19373 destroyAppDataLeafLIF(pkg, userId, flags); 19374 try { 19375 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19376 appId, app.seinfo, app.targetSdkVersion); 19377 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19378 } catch (InstallerException e2) { 19379 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19380 } 19381 } else { 19382 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19383 } 19384 } 19385 19386 if (restoreconNeeded) { 19387 try { 19388 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19389 app.seinfo); 19390 } catch (InstallerException e) { 19391 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19392 } 19393 } 19394 19395 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19396 try { 19397 // CE storage is unlocked right now, so read out the inode and 19398 // remember for use later when it's locked 19399 // TODO: mark this structure as dirty so we persist it! 19400 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19401 StorageManager.FLAG_STORAGE_CE); 19402 synchronized (mPackages) { 19403 final PackageSetting ps = mSettings.mPackages.get(packageName); 19404 if (ps != null) { 19405 ps.setCeDataInode(ceDataInode, userId); 19406 } 19407 } 19408 } catch (InstallerException e) { 19409 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19410 } 19411 } 19412 19413 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19414 } 19415 19416 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19417 if (pkg == null) { 19418 Slog.wtf(TAG, "Package was null!", new Throwable()); 19419 return; 19420 } 19421 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19422 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19423 for (int i = 0; i < childCount; i++) { 19424 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19425 } 19426 } 19427 19428 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19429 final String volumeUuid = pkg.volumeUuid; 19430 final String packageName = pkg.packageName; 19431 final ApplicationInfo app = pkg.applicationInfo; 19432 19433 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19434 // Create a native library symlink only if we have native libraries 19435 // and if the native libraries are 32 bit libraries. We do not provide 19436 // this symlink for 64 bit libraries. 19437 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19438 final String nativeLibPath = app.nativeLibraryDir; 19439 try { 19440 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19441 nativeLibPath, userId); 19442 } catch (InstallerException e) { 19443 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19444 } 19445 } 19446 } 19447 } 19448 19449 /** 19450 * For system apps on non-FBE devices, this method migrates any existing 19451 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19452 * requested by the app. 19453 */ 19454 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19455 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19456 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19457 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19458 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19459 try { 19460 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19461 storageTarget); 19462 } catch (InstallerException e) { 19463 logCriticalInfo(Log.WARN, 19464 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19465 } 19466 return true; 19467 } else { 19468 return false; 19469 } 19470 } 19471 19472 public PackageFreezer freezePackage(String packageName, String killReason) { 19473 return new PackageFreezer(packageName, killReason); 19474 } 19475 19476 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19477 String killReason) { 19478 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19479 return new PackageFreezer(); 19480 } else { 19481 return freezePackage(packageName, killReason); 19482 } 19483 } 19484 19485 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19486 String killReason) { 19487 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19488 return new PackageFreezer(); 19489 } else { 19490 return freezePackage(packageName, killReason); 19491 } 19492 } 19493 19494 /** 19495 * Class that freezes and kills the given package upon creation, and 19496 * unfreezes it upon closing. This is typically used when doing surgery on 19497 * app code/data to prevent the app from running while you're working. 19498 */ 19499 private class PackageFreezer implements AutoCloseable { 19500 private final String mPackageName; 19501 private final PackageFreezer[] mChildren; 19502 19503 private final boolean mWeFroze; 19504 19505 private final AtomicBoolean mClosed = new AtomicBoolean(); 19506 private final CloseGuard mCloseGuard = CloseGuard.get(); 19507 19508 /** 19509 * Create and return a stub freezer that doesn't actually do anything, 19510 * typically used when someone requested 19511 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19512 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19513 */ 19514 public PackageFreezer() { 19515 mPackageName = null; 19516 mChildren = null; 19517 mWeFroze = false; 19518 mCloseGuard.open("close"); 19519 } 19520 19521 public PackageFreezer(String packageName, String killReason) { 19522 synchronized (mPackages) { 19523 mPackageName = packageName; 19524 mWeFroze = mFrozenPackages.add(mPackageName); 19525 19526 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19527 if (ps != null) { 19528 killApplication(ps.name, ps.appId, killReason); 19529 } 19530 19531 final PackageParser.Package p = mPackages.get(packageName); 19532 if (p != null && p.childPackages != null) { 19533 final int N = p.childPackages.size(); 19534 mChildren = new PackageFreezer[N]; 19535 for (int i = 0; i < N; i++) { 19536 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19537 killReason); 19538 } 19539 } else { 19540 mChildren = null; 19541 } 19542 } 19543 mCloseGuard.open("close"); 19544 } 19545 19546 @Override 19547 protected void finalize() throws Throwable { 19548 try { 19549 mCloseGuard.warnIfOpen(); 19550 close(); 19551 } finally { 19552 super.finalize(); 19553 } 19554 } 19555 19556 @Override 19557 public void close() { 19558 mCloseGuard.close(); 19559 if (mClosed.compareAndSet(false, true)) { 19560 synchronized (mPackages) { 19561 if (mWeFroze) { 19562 mFrozenPackages.remove(mPackageName); 19563 } 19564 19565 if (mChildren != null) { 19566 for (PackageFreezer freezer : mChildren) { 19567 freezer.close(); 19568 } 19569 } 19570 } 19571 } 19572 } 19573 } 19574 19575 /** 19576 * Verify that given package is currently frozen. 19577 */ 19578 private void checkPackageFrozen(String packageName) { 19579 synchronized (mPackages) { 19580 if (!mFrozenPackages.contains(packageName)) { 19581 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19582 } 19583 } 19584 } 19585 19586 @Override 19587 public int movePackage(final String packageName, final String volumeUuid) { 19588 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19589 19590 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19591 final int moveId = mNextMoveId.getAndIncrement(); 19592 mHandler.post(new Runnable() { 19593 @Override 19594 public void run() { 19595 try { 19596 movePackageInternal(packageName, volumeUuid, moveId, user); 19597 } catch (PackageManagerException e) { 19598 Slog.w(TAG, "Failed to move " + packageName, e); 19599 mMoveCallbacks.notifyStatusChanged(moveId, 19600 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19601 } 19602 } 19603 }); 19604 return moveId; 19605 } 19606 19607 private void movePackageInternal(final String packageName, final String volumeUuid, 19608 final int moveId, UserHandle user) throws PackageManagerException { 19609 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19610 final PackageManager pm = mContext.getPackageManager(); 19611 19612 final boolean currentAsec; 19613 final String currentVolumeUuid; 19614 final File codeFile; 19615 final String installerPackageName; 19616 final String packageAbiOverride; 19617 final int appId; 19618 final String seinfo; 19619 final String label; 19620 final int targetSdkVersion; 19621 final PackageFreezer freezer; 19622 final int[] installedUserIds; 19623 19624 // reader 19625 synchronized (mPackages) { 19626 final PackageParser.Package pkg = mPackages.get(packageName); 19627 final PackageSetting ps = mSettings.mPackages.get(packageName); 19628 if (pkg == null || ps == null) { 19629 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19630 } 19631 19632 if (pkg.applicationInfo.isSystemApp()) { 19633 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19634 "Cannot move system application"); 19635 } 19636 19637 if (pkg.applicationInfo.isExternalAsec()) { 19638 currentAsec = true; 19639 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19640 } else if (pkg.applicationInfo.isForwardLocked()) { 19641 currentAsec = true; 19642 currentVolumeUuid = "forward_locked"; 19643 } else { 19644 currentAsec = false; 19645 currentVolumeUuid = ps.volumeUuid; 19646 19647 final File probe = new File(pkg.codePath); 19648 final File probeOat = new File(probe, "oat"); 19649 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19650 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19651 "Move only supported for modern cluster style installs"); 19652 } 19653 } 19654 19655 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19656 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19657 "Package already moved to " + volumeUuid); 19658 } 19659 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19660 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19661 "Device admin cannot be moved"); 19662 } 19663 19664 if (mFrozenPackages.contains(packageName)) { 19665 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19666 "Failed to move already frozen package"); 19667 } 19668 19669 codeFile = new File(pkg.codePath); 19670 installerPackageName = ps.installerPackageName; 19671 packageAbiOverride = ps.cpuAbiOverrideString; 19672 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19673 seinfo = pkg.applicationInfo.seinfo; 19674 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19675 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19676 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19677 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19678 } 19679 19680 final Bundle extras = new Bundle(); 19681 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19682 extras.putString(Intent.EXTRA_TITLE, label); 19683 mMoveCallbacks.notifyCreated(moveId, extras); 19684 19685 int installFlags; 19686 final boolean moveCompleteApp; 19687 final File measurePath; 19688 19689 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19690 installFlags = INSTALL_INTERNAL; 19691 moveCompleteApp = !currentAsec; 19692 measurePath = Environment.getDataAppDirectory(volumeUuid); 19693 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19694 installFlags = INSTALL_EXTERNAL; 19695 moveCompleteApp = false; 19696 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19697 } else { 19698 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19699 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19700 || !volume.isMountedWritable()) { 19701 freezer.close(); 19702 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19703 "Move location not mounted private volume"); 19704 } 19705 19706 Preconditions.checkState(!currentAsec); 19707 19708 installFlags = INSTALL_INTERNAL; 19709 moveCompleteApp = true; 19710 measurePath = Environment.getDataAppDirectory(volumeUuid); 19711 } 19712 19713 final PackageStats stats = new PackageStats(null, -1); 19714 synchronized (mInstaller) { 19715 for (int userId : installedUserIds) { 19716 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19717 freezer.close(); 19718 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19719 "Failed to measure package size"); 19720 } 19721 } 19722 } 19723 19724 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19725 + stats.dataSize); 19726 19727 final long startFreeBytes = measurePath.getFreeSpace(); 19728 final long sizeBytes; 19729 if (moveCompleteApp) { 19730 sizeBytes = stats.codeSize + stats.dataSize; 19731 } else { 19732 sizeBytes = stats.codeSize; 19733 } 19734 19735 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19736 freezer.close(); 19737 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19738 "Not enough free space to move"); 19739 } 19740 19741 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19742 19743 final CountDownLatch installedLatch = new CountDownLatch(1); 19744 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19745 @Override 19746 public void onUserActionRequired(Intent intent) throws RemoteException { 19747 throw new IllegalStateException(); 19748 } 19749 19750 @Override 19751 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19752 Bundle extras) throws RemoteException { 19753 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19754 + PackageManager.installStatusToString(returnCode, msg)); 19755 19756 installedLatch.countDown(); 19757 freezer.close(); 19758 19759 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19760 switch (status) { 19761 case PackageInstaller.STATUS_SUCCESS: 19762 mMoveCallbacks.notifyStatusChanged(moveId, 19763 PackageManager.MOVE_SUCCEEDED); 19764 break; 19765 case PackageInstaller.STATUS_FAILURE_STORAGE: 19766 mMoveCallbacks.notifyStatusChanged(moveId, 19767 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19768 break; 19769 default: 19770 mMoveCallbacks.notifyStatusChanged(moveId, 19771 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19772 break; 19773 } 19774 } 19775 }; 19776 19777 final MoveInfo move; 19778 if (moveCompleteApp) { 19779 // Kick off a thread to report progress estimates 19780 new Thread() { 19781 @Override 19782 public void run() { 19783 while (true) { 19784 try { 19785 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19786 break; 19787 } 19788 } catch (InterruptedException ignored) { 19789 } 19790 19791 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19792 final int progress = 10 + (int) MathUtils.constrain( 19793 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19794 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19795 } 19796 } 19797 }.start(); 19798 19799 final String dataAppName = codeFile.getName(); 19800 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19801 dataAppName, appId, seinfo, targetSdkVersion); 19802 } else { 19803 move = null; 19804 } 19805 19806 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19807 19808 final Message msg = mHandler.obtainMessage(INIT_COPY); 19809 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19810 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19811 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19812 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19813 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19814 msg.obj = params; 19815 19816 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19817 System.identityHashCode(msg.obj)); 19818 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19819 System.identityHashCode(msg.obj)); 19820 19821 mHandler.sendMessage(msg); 19822 } 19823 19824 @Override 19825 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19826 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19827 19828 final int realMoveId = mNextMoveId.getAndIncrement(); 19829 final Bundle extras = new Bundle(); 19830 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19831 mMoveCallbacks.notifyCreated(realMoveId, extras); 19832 19833 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19834 @Override 19835 public void onCreated(int moveId, Bundle extras) { 19836 // Ignored 19837 } 19838 19839 @Override 19840 public void onStatusChanged(int moveId, int status, long estMillis) { 19841 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19842 } 19843 }; 19844 19845 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19846 storage.setPrimaryStorageUuid(volumeUuid, callback); 19847 return realMoveId; 19848 } 19849 19850 @Override 19851 public int getMoveStatus(int moveId) { 19852 mContext.enforceCallingOrSelfPermission( 19853 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19854 return mMoveCallbacks.mLastStatus.get(moveId); 19855 } 19856 19857 @Override 19858 public void registerMoveCallback(IPackageMoveObserver callback) { 19859 mContext.enforceCallingOrSelfPermission( 19860 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19861 mMoveCallbacks.register(callback); 19862 } 19863 19864 @Override 19865 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19866 mContext.enforceCallingOrSelfPermission( 19867 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19868 mMoveCallbacks.unregister(callback); 19869 } 19870 19871 @Override 19872 public boolean setInstallLocation(int loc) { 19873 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19874 null); 19875 if (getInstallLocation() == loc) { 19876 return true; 19877 } 19878 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19879 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19880 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19881 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19882 return true; 19883 } 19884 return false; 19885 } 19886 19887 @Override 19888 public int getInstallLocation() { 19889 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19890 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19891 PackageHelper.APP_INSTALL_AUTO); 19892 } 19893 19894 /** Called by UserManagerService */ 19895 void cleanUpUser(UserManagerService userManager, int userHandle) { 19896 synchronized (mPackages) { 19897 mDirtyUsers.remove(userHandle); 19898 mUserNeedsBadging.delete(userHandle); 19899 mSettings.removeUserLPw(userHandle); 19900 mPendingBroadcasts.remove(userHandle); 19901 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19902 removeUnusedPackagesLPw(userManager, userHandle); 19903 } 19904 } 19905 19906 /** 19907 * We're removing userHandle and would like to remove any downloaded packages 19908 * that are no longer in use by any other user. 19909 * @param userHandle the user being removed 19910 */ 19911 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19912 final boolean DEBUG_CLEAN_APKS = false; 19913 int [] users = userManager.getUserIds(); 19914 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19915 while (psit.hasNext()) { 19916 PackageSetting ps = psit.next(); 19917 if (ps.pkg == null) { 19918 continue; 19919 } 19920 final String packageName = ps.pkg.packageName; 19921 // Skip over if system app 19922 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19923 continue; 19924 } 19925 if (DEBUG_CLEAN_APKS) { 19926 Slog.i(TAG, "Checking package " + packageName); 19927 } 19928 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19929 if (keep) { 19930 if (DEBUG_CLEAN_APKS) { 19931 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19932 } 19933 } else { 19934 for (int i = 0; i < users.length; i++) { 19935 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19936 keep = true; 19937 if (DEBUG_CLEAN_APKS) { 19938 Slog.i(TAG, " Keeping package " + packageName + " for user " 19939 + users[i]); 19940 } 19941 break; 19942 } 19943 } 19944 } 19945 if (!keep) { 19946 if (DEBUG_CLEAN_APKS) { 19947 Slog.i(TAG, " Removing package " + packageName); 19948 } 19949 mHandler.post(new Runnable() { 19950 public void run() { 19951 deletePackageX(packageName, userHandle, 0); 19952 } //end run 19953 }); 19954 } 19955 } 19956 } 19957 19958 /** Called by UserManagerService */ 19959 void createNewUser(int userHandle) { 19960 synchronized (mInstallLock) { 19961 mSettings.createNewUserLI(this, mInstaller, userHandle); 19962 } 19963 synchronized (mPackages) { 19964 applyFactoryDefaultBrowserLPw(userHandle); 19965 primeDomainVerificationsLPw(userHandle); 19966 } 19967 } 19968 19969 void newUserCreated(final int userHandle) { 19970 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19971 // If permission review for legacy apps is required, we represent 19972 // dagerous permissions for such apps as always granted runtime 19973 // permissions to keep per user flag state whether review is needed. 19974 // Hence, if a new user is added we have to propagate dangerous 19975 // permission grants for these legacy apps. 19976 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19977 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19978 | UPDATE_PERMISSIONS_REPLACE_ALL); 19979 } 19980 } 19981 19982 @Override 19983 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19984 mContext.enforceCallingOrSelfPermission( 19985 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19986 "Only package verification agents can read the verifier device identity"); 19987 19988 synchronized (mPackages) { 19989 return mSettings.getVerifierDeviceIdentityLPw(); 19990 } 19991 } 19992 19993 @Override 19994 public void setPermissionEnforced(String permission, boolean enforced) { 19995 // TODO: Now that we no longer change GID for storage, this should to away. 19996 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19997 "setPermissionEnforced"); 19998 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19999 synchronized (mPackages) { 20000 if (mSettings.mReadExternalStorageEnforced == null 20001 || mSettings.mReadExternalStorageEnforced != enforced) { 20002 mSettings.mReadExternalStorageEnforced = enforced; 20003 mSettings.writeLPr(); 20004 } 20005 } 20006 // kill any non-foreground processes so we restart them and 20007 // grant/revoke the GID. 20008 final IActivityManager am = ActivityManagerNative.getDefault(); 20009 if (am != null) { 20010 final long token = Binder.clearCallingIdentity(); 20011 try { 20012 am.killProcessesBelowForeground("setPermissionEnforcement"); 20013 } catch (RemoteException e) { 20014 } finally { 20015 Binder.restoreCallingIdentity(token); 20016 } 20017 } 20018 } else { 20019 throw new IllegalArgumentException("No selective enforcement for " + permission); 20020 } 20021 } 20022 20023 @Override 20024 @Deprecated 20025 public boolean isPermissionEnforced(String permission) { 20026 return true; 20027 } 20028 20029 @Override 20030 public boolean isStorageLow() { 20031 final long token = Binder.clearCallingIdentity(); 20032 try { 20033 final DeviceStorageMonitorInternal 20034 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20035 if (dsm != null) { 20036 return dsm.isMemoryLow(); 20037 } else { 20038 return false; 20039 } 20040 } finally { 20041 Binder.restoreCallingIdentity(token); 20042 } 20043 } 20044 20045 @Override 20046 public IPackageInstaller getPackageInstaller() { 20047 return mInstallerService; 20048 } 20049 20050 private boolean userNeedsBadging(int userId) { 20051 int index = mUserNeedsBadging.indexOfKey(userId); 20052 if (index < 0) { 20053 final UserInfo userInfo; 20054 final long token = Binder.clearCallingIdentity(); 20055 try { 20056 userInfo = sUserManager.getUserInfo(userId); 20057 } finally { 20058 Binder.restoreCallingIdentity(token); 20059 } 20060 final boolean b; 20061 if (userInfo != null && userInfo.isManagedProfile()) { 20062 b = true; 20063 } else { 20064 b = false; 20065 } 20066 mUserNeedsBadging.put(userId, b); 20067 return b; 20068 } 20069 return mUserNeedsBadging.valueAt(index); 20070 } 20071 20072 @Override 20073 public KeySet getKeySetByAlias(String packageName, String alias) { 20074 if (packageName == null || alias == null) { 20075 return null; 20076 } 20077 synchronized(mPackages) { 20078 final PackageParser.Package pkg = mPackages.get(packageName); 20079 if (pkg == null) { 20080 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20081 throw new IllegalArgumentException("Unknown package: " + packageName); 20082 } 20083 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20084 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20085 } 20086 } 20087 20088 @Override 20089 public KeySet getSigningKeySet(String packageName) { 20090 if (packageName == null) { 20091 return null; 20092 } 20093 synchronized(mPackages) { 20094 final PackageParser.Package pkg = mPackages.get(packageName); 20095 if (pkg == null) { 20096 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20097 throw new IllegalArgumentException("Unknown package: " + packageName); 20098 } 20099 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20100 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20101 throw new SecurityException("May not access signing KeySet of other apps."); 20102 } 20103 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20104 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20105 } 20106 } 20107 20108 @Override 20109 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20110 if (packageName == null || ks == null) { 20111 return false; 20112 } 20113 synchronized(mPackages) { 20114 final PackageParser.Package pkg = mPackages.get(packageName); 20115 if (pkg == null) { 20116 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20117 throw new IllegalArgumentException("Unknown package: " + packageName); 20118 } 20119 IBinder ksh = ks.getToken(); 20120 if (ksh instanceof KeySetHandle) { 20121 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20122 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20123 } 20124 return false; 20125 } 20126 } 20127 20128 @Override 20129 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20130 if (packageName == null || ks == null) { 20131 return false; 20132 } 20133 synchronized(mPackages) { 20134 final PackageParser.Package pkg = mPackages.get(packageName); 20135 if (pkg == null) { 20136 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20137 throw new IllegalArgumentException("Unknown package: " + packageName); 20138 } 20139 IBinder ksh = ks.getToken(); 20140 if (ksh instanceof KeySetHandle) { 20141 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20142 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20143 } 20144 return false; 20145 } 20146 } 20147 20148 private void deletePackageIfUnusedLPr(final String packageName) { 20149 PackageSetting ps = mSettings.mPackages.get(packageName); 20150 if (ps == null) { 20151 return; 20152 } 20153 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20154 // TODO Implement atomic delete if package is unused 20155 // It is currently possible that the package will be deleted even if it is installed 20156 // after this method returns. 20157 mHandler.post(new Runnable() { 20158 public void run() { 20159 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20160 } 20161 }); 20162 } 20163 } 20164 20165 /** 20166 * Check and throw if the given before/after packages would be considered a 20167 * downgrade. 20168 */ 20169 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20170 throws PackageManagerException { 20171 if (after.versionCode < before.mVersionCode) { 20172 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20173 "Update version code " + after.versionCode + " is older than current " 20174 + before.mVersionCode); 20175 } else if (after.versionCode == before.mVersionCode) { 20176 if (after.baseRevisionCode < before.baseRevisionCode) { 20177 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20178 "Update base revision code " + after.baseRevisionCode 20179 + " is older than current " + before.baseRevisionCode); 20180 } 20181 20182 if (!ArrayUtils.isEmpty(after.splitNames)) { 20183 for (int i = 0; i < after.splitNames.length; i++) { 20184 final String splitName = after.splitNames[i]; 20185 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20186 if (j != -1) { 20187 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20188 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20189 "Update split " + splitName + " revision code " 20190 + after.splitRevisionCodes[i] + " is older than current " 20191 + before.splitRevisionCodes[j]); 20192 } 20193 } 20194 } 20195 } 20196 } 20197 } 20198 20199 private static class MoveCallbacks extends Handler { 20200 private static final int MSG_CREATED = 1; 20201 private static final int MSG_STATUS_CHANGED = 2; 20202 20203 private final RemoteCallbackList<IPackageMoveObserver> 20204 mCallbacks = new RemoteCallbackList<>(); 20205 20206 private final SparseIntArray mLastStatus = new SparseIntArray(); 20207 20208 public MoveCallbacks(Looper looper) { 20209 super(looper); 20210 } 20211 20212 public void register(IPackageMoveObserver callback) { 20213 mCallbacks.register(callback); 20214 } 20215 20216 public void unregister(IPackageMoveObserver callback) { 20217 mCallbacks.unregister(callback); 20218 } 20219 20220 @Override 20221 public void handleMessage(Message msg) { 20222 final SomeArgs args = (SomeArgs) msg.obj; 20223 final int n = mCallbacks.beginBroadcast(); 20224 for (int i = 0; i < n; i++) { 20225 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20226 try { 20227 invokeCallback(callback, msg.what, args); 20228 } catch (RemoteException ignored) { 20229 } 20230 } 20231 mCallbacks.finishBroadcast(); 20232 args.recycle(); 20233 } 20234 20235 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20236 throws RemoteException { 20237 switch (what) { 20238 case MSG_CREATED: { 20239 callback.onCreated(args.argi1, (Bundle) args.arg2); 20240 break; 20241 } 20242 case MSG_STATUS_CHANGED: { 20243 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20244 break; 20245 } 20246 } 20247 } 20248 20249 private void notifyCreated(int moveId, Bundle extras) { 20250 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20251 20252 final SomeArgs args = SomeArgs.obtain(); 20253 args.argi1 = moveId; 20254 args.arg2 = extras; 20255 obtainMessage(MSG_CREATED, args).sendToTarget(); 20256 } 20257 20258 private void notifyStatusChanged(int moveId, int status) { 20259 notifyStatusChanged(moveId, status, -1); 20260 } 20261 20262 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20263 Slog.v(TAG, "Move " + moveId + " status " + status); 20264 20265 final SomeArgs args = SomeArgs.obtain(); 20266 args.argi1 = moveId; 20267 args.argi2 = status; 20268 args.arg3 = estMillis; 20269 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20270 20271 synchronized (mLastStatus) { 20272 mLastStatus.put(moveId, status); 20273 } 20274 } 20275 } 20276 20277 private final static class OnPermissionChangeListeners extends Handler { 20278 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20279 20280 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20281 new RemoteCallbackList<>(); 20282 20283 public OnPermissionChangeListeners(Looper looper) { 20284 super(looper); 20285 } 20286 20287 @Override 20288 public void handleMessage(Message msg) { 20289 switch (msg.what) { 20290 case MSG_ON_PERMISSIONS_CHANGED: { 20291 final int uid = msg.arg1; 20292 handleOnPermissionsChanged(uid); 20293 } break; 20294 } 20295 } 20296 20297 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20298 mPermissionListeners.register(listener); 20299 20300 } 20301 20302 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20303 mPermissionListeners.unregister(listener); 20304 } 20305 20306 public void onPermissionsChanged(int uid) { 20307 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20308 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20309 } 20310 } 20311 20312 private void handleOnPermissionsChanged(int uid) { 20313 final int count = mPermissionListeners.beginBroadcast(); 20314 try { 20315 for (int i = 0; i < count; i++) { 20316 IOnPermissionsChangeListener callback = mPermissionListeners 20317 .getBroadcastItem(i); 20318 try { 20319 callback.onPermissionsChanged(uid); 20320 } catch (RemoteException e) { 20321 Log.e(TAG, "Permission listener is dead", e); 20322 } 20323 } 20324 } finally { 20325 mPermissionListeners.finishBroadcast(); 20326 } 20327 } 20328 } 20329 20330 private class PackageManagerInternalImpl extends PackageManagerInternal { 20331 @Override 20332 public void setLocationPackagesProvider(PackagesProvider provider) { 20333 synchronized (mPackages) { 20334 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20335 } 20336 } 20337 20338 @Override 20339 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20340 synchronized (mPackages) { 20341 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20342 } 20343 } 20344 20345 @Override 20346 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20347 synchronized (mPackages) { 20348 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20349 } 20350 } 20351 20352 @Override 20353 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20354 synchronized (mPackages) { 20355 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20356 } 20357 } 20358 20359 @Override 20360 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20361 synchronized (mPackages) { 20362 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20363 } 20364 } 20365 20366 @Override 20367 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20368 synchronized (mPackages) { 20369 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20370 } 20371 } 20372 20373 @Override 20374 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20375 synchronized (mPackages) { 20376 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20377 packageName, userId); 20378 } 20379 } 20380 20381 @Override 20382 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20383 synchronized (mPackages) { 20384 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20385 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20386 packageName, userId); 20387 } 20388 } 20389 20390 @Override 20391 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20392 synchronized (mPackages) { 20393 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20394 packageName, userId); 20395 } 20396 } 20397 20398 @Override 20399 public void setKeepUninstalledPackages(final List<String> packageList) { 20400 Preconditions.checkNotNull(packageList); 20401 List<String> removedFromList = null; 20402 synchronized (mPackages) { 20403 if (mKeepUninstalledPackages != null) { 20404 final int packagesCount = mKeepUninstalledPackages.size(); 20405 for (int i = 0; i < packagesCount; i++) { 20406 String oldPackage = mKeepUninstalledPackages.get(i); 20407 if (packageList != null && packageList.contains(oldPackage)) { 20408 continue; 20409 } 20410 if (removedFromList == null) { 20411 removedFromList = new ArrayList<>(); 20412 } 20413 removedFromList.add(oldPackage); 20414 } 20415 } 20416 mKeepUninstalledPackages = new ArrayList<>(packageList); 20417 if (removedFromList != null) { 20418 final int removedCount = removedFromList.size(); 20419 for (int i = 0; i < removedCount; i++) { 20420 deletePackageIfUnusedLPr(removedFromList.get(i)); 20421 } 20422 } 20423 } 20424 } 20425 20426 @Override 20427 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20428 synchronized (mPackages) { 20429 // If we do not support permission review, done. 20430 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20431 return false; 20432 } 20433 20434 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20435 if (packageSetting == null) { 20436 return false; 20437 } 20438 20439 // Permission review applies only to apps not supporting the new permission model. 20440 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20441 return false; 20442 } 20443 20444 // Legacy apps have the permission and get user consent on launch. 20445 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20446 return permissionsState.isPermissionReviewRequired(userId); 20447 } 20448 } 20449 20450 @Override 20451 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20452 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20453 } 20454 20455 @Override 20456 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20457 int userId) { 20458 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20459 } 20460 } 20461 20462 @Override 20463 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20464 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20465 synchronized (mPackages) { 20466 final long identity = Binder.clearCallingIdentity(); 20467 try { 20468 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20469 packageNames, userId); 20470 } finally { 20471 Binder.restoreCallingIdentity(identity); 20472 } 20473 } 20474 } 20475 20476 private static void enforceSystemOrPhoneCaller(String tag) { 20477 int callingUid = Binder.getCallingUid(); 20478 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20479 throw new SecurityException( 20480 "Cannot call " + tag + " from UID " + callingUid); 20481 } 20482 } 20483 20484 boolean isHistoricalPackageUsageAvailable() { 20485 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20486 } 20487 20488 /** 20489 * Return a <b>copy</b> of the collection of packages known to the package manager. 20490 * @return A copy of the values of mPackages. 20491 */ 20492 Collection<PackageParser.Package> getPackages() { 20493 synchronized (mPackages) { 20494 return new ArrayList<>(mPackages.values()); 20495 } 20496 } 20497 20498 /** 20499 * Logs process start information (including base APK hash) to the security log. 20500 * @hide 20501 */ 20502 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20503 String apkFile, int pid) { 20504 if (!SecurityLog.isLoggingEnabled()) { 20505 return; 20506 } 20507 Bundle data = new Bundle(); 20508 data.putLong("startTimestamp", System.currentTimeMillis()); 20509 data.putString("processName", processName); 20510 data.putInt("uid", uid); 20511 data.putString("seinfo", seinfo); 20512 data.putString("apkFile", apkFile); 20513 data.putInt("pid", pid); 20514 Message msg = mProcessLoggingHandler.obtainMessage( 20515 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20516 msg.setData(data); 20517 mProcessLoggingHandler.sendMessage(msg); 20518 } 20519} 20520