PackageManagerService.java revision 8412cf4daaa437003f4a79a82aa35465c4f0d418
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 // checkProfiles is false to avoid merging profiles during boot which 7200 // might interfere with background compilation (b/28612421). 7201 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7202 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7203 // trade-off worth doing to save boot time work. 7204 int dexOptStatus = performDexOptTraced(pkg.packageName, 7205 null /* instructionSet */, 7206 false /* checkProfiles */, 7207 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7208 false /* force */); 7209 switch (dexOptStatus) { 7210 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7211 numberOfPackagesOptimized++; 7212 break; 7213 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7214 numberOfPackagesSkipped++; 7215 break; 7216 case PackageDexOptimizer.DEX_OPT_FAILED: 7217 numberOfPackagesFailed++; 7218 break; 7219 default: 7220 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7221 break; 7222 } 7223 } 7224 7225 final int elapsedTime = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); 7226 MetricsLogger.action(mContext, 7227 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_DEXOPTED, numberOfPackagesOptimized); 7228 MetricsLogger.action(mContext, 7229 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_SKIPPED, numberOfPackagesSkipped); 7230 MetricsLogger.action(mContext, 7231 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_FAILED, numberOfPackagesFailed); 7232 MetricsLogger.action(mContext, 7233 MetricsEvent.OPTIMIZING_APPS_NUM_PKGS_TOTAL, getOptimizablePackages().size()); 7234 MetricsLogger.action(mContext, 7235 MetricsEvent.OPTIMIZING_APPS_TOTAL_TIME_MS, elapsedTime); 7236 } 7237 7238 @Override 7239 public void notifyPackageUse(String packageName, int reason) { 7240 synchronized (mPackages) { 7241 PackageParser.Package p = mPackages.get(packageName); 7242 if (p == null) { 7243 return; 7244 } 7245 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7246 } 7247 } 7248 7249 // TODO: this is not used nor needed. Delete it. 7250 @Override 7251 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7252 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7253 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7254 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7255 } 7256 7257 @Override 7258 public boolean performDexOpt(String packageName, String instructionSet, 7259 boolean checkProfiles, int compileReason, boolean force) { 7260 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7261 getCompilerFilterForReason(compileReason), force); 7262 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7263 } 7264 7265 @Override 7266 public boolean performDexOptMode(String packageName, String instructionSet, 7267 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7268 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7269 targetCompilerFilter, force); 7270 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7271 } 7272 7273 private int performDexOptTraced(String packageName, String instructionSet, 7274 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7275 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7276 try { 7277 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7278 targetCompilerFilter, force); 7279 } finally { 7280 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7281 } 7282 } 7283 7284 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7285 // if the package can now be considered up to date for the given filter. 7286 private int performDexOptInternal(String packageName, String instructionSet, 7287 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7288 PackageParser.Package p; 7289 final String targetInstructionSet; 7290 synchronized (mPackages) { 7291 p = mPackages.get(packageName); 7292 if (p == null) { 7293 // Package could not be found. Report failure. 7294 return PackageDexOptimizer.DEX_OPT_FAILED; 7295 } 7296 mPackageUsage.write(false); 7297 7298 targetInstructionSet = instructionSet != null ? instructionSet : 7299 getPrimaryInstructionSet(p.applicationInfo); 7300 } 7301 long callingId = Binder.clearCallingIdentity(); 7302 try { 7303 synchronized (mInstallLock) { 7304 final String[] instructionSets = new String[] { targetInstructionSet }; 7305 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7306 targetCompilerFilter, force); 7307 } 7308 } finally { 7309 Binder.restoreCallingIdentity(callingId); 7310 } 7311 } 7312 7313 public ArraySet<String> getOptimizablePackages() { 7314 ArraySet<String> pkgs = new ArraySet<String>(); 7315 synchronized (mPackages) { 7316 for (PackageParser.Package p : mPackages.values()) { 7317 if (PackageDexOptimizer.canOptimizePackage(p)) { 7318 pkgs.add(p.packageName); 7319 } 7320 } 7321 } 7322 return pkgs; 7323 } 7324 7325 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7326 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7327 boolean force) { 7328 // Select the dex optimizer based on the force parameter. 7329 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7330 // allocate an object here. 7331 PackageDexOptimizer pdo = force 7332 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7333 : mPackageDexOptimizer; 7334 7335 // Optimize all dependencies first. Note: we ignore the return value and march on 7336 // on errors. 7337 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7338 if (!deps.isEmpty()) { 7339 for (PackageParser.Package depPackage : deps) { 7340 // TODO: Analyze and investigate if we (should) profile libraries. 7341 // Currently this will do a full compilation of the library by default. 7342 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7343 false /* checkProfiles */, 7344 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7345 } 7346 } 7347 7348 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7349 targetCompilerFilter); 7350 } 7351 7352 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7353 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7354 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7355 Set<String> collectedNames = new HashSet<>(); 7356 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7357 7358 retValue.remove(p); 7359 7360 return retValue; 7361 } else { 7362 return Collections.emptyList(); 7363 } 7364 } 7365 7366 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7367 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7368 if (!collectedNames.contains(p.packageName)) { 7369 collectedNames.add(p.packageName); 7370 collected.add(p); 7371 7372 if (p.usesLibraries != null) { 7373 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7374 } 7375 if (p.usesOptionalLibraries != null) { 7376 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7377 collectedNames); 7378 } 7379 } 7380 } 7381 7382 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7383 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7384 for (String libName : libs) { 7385 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7386 if (libPkg != null) { 7387 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7388 } 7389 } 7390 } 7391 7392 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7393 synchronized (mPackages) { 7394 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7395 if (lib != null && lib.apk != null) { 7396 return mPackages.get(lib.apk); 7397 } 7398 } 7399 return null; 7400 } 7401 7402 public void shutdown() { 7403 mPackageUsage.write(true); 7404 } 7405 7406 @Override 7407 public void forceDexOpt(String packageName) { 7408 enforceSystemOrRoot("forceDexOpt"); 7409 7410 PackageParser.Package pkg; 7411 synchronized (mPackages) { 7412 pkg = mPackages.get(packageName); 7413 if (pkg == null) { 7414 throw new IllegalArgumentException("Unknown package: " + packageName); 7415 } 7416 } 7417 7418 synchronized (mInstallLock) { 7419 final String[] instructionSets = new String[] { 7420 getPrimaryInstructionSet(pkg.applicationInfo) }; 7421 7422 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7423 7424 // Whoever is calling forceDexOpt wants a fully compiled package. 7425 // Don't use profiles since that may cause compilation to be skipped. 7426 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7427 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7428 true /* force */); 7429 7430 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7431 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7432 throw new IllegalStateException("Failed to dexopt: " + res); 7433 } 7434 } 7435 } 7436 7437 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7438 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7439 Slog.w(TAG, "Unable to update from " + oldPkg.name 7440 + " to " + newPkg.packageName 7441 + ": old package not in system partition"); 7442 return false; 7443 } else if (mPackages.get(oldPkg.name) != null) { 7444 Slog.w(TAG, "Unable to update from " + oldPkg.name 7445 + " to " + newPkg.packageName 7446 + ": old package still exists"); 7447 return false; 7448 } 7449 return true; 7450 } 7451 7452 void removeCodePathLI(File codePath) { 7453 if (codePath.isDirectory()) { 7454 try { 7455 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7456 } catch (InstallerException e) { 7457 Slog.w(TAG, "Failed to remove code path", e); 7458 } 7459 } else { 7460 codePath.delete(); 7461 } 7462 } 7463 7464 private int[] resolveUserIds(int userId) { 7465 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7466 } 7467 7468 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7469 if (pkg == null) { 7470 Slog.wtf(TAG, "Package was null!", new Throwable()); 7471 return; 7472 } 7473 clearAppDataLeafLIF(pkg, userId, flags); 7474 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7475 for (int i = 0; i < childCount; i++) { 7476 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7477 } 7478 } 7479 7480 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7481 final PackageSetting ps; 7482 synchronized (mPackages) { 7483 ps = mSettings.mPackages.get(pkg.packageName); 7484 } 7485 for (int realUserId : resolveUserIds(userId)) { 7486 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7487 try { 7488 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7489 ceDataInode); 7490 } catch (InstallerException e) { 7491 Slog.w(TAG, String.valueOf(e)); 7492 } 7493 } 7494 } 7495 7496 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7497 if (pkg == null) { 7498 Slog.wtf(TAG, "Package was null!", new Throwable()); 7499 return; 7500 } 7501 destroyAppDataLeafLIF(pkg, userId, flags); 7502 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7503 for (int i = 0; i < childCount; i++) { 7504 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7505 } 7506 } 7507 7508 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7509 final PackageSetting ps; 7510 synchronized (mPackages) { 7511 ps = mSettings.mPackages.get(pkg.packageName); 7512 } 7513 for (int realUserId : resolveUserIds(userId)) { 7514 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7515 try { 7516 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7517 ceDataInode); 7518 } catch (InstallerException e) { 7519 Slog.w(TAG, String.valueOf(e)); 7520 } 7521 } 7522 } 7523 7524 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7525 if (pkg == null) { 7526 Slog.wtf(TAG, "Package was null!", new Throwable()); 7527 return; 7528 } 7529 destroyAppProfilesLeafLIF(pkg); 7530 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7531 for (int i = 0; i < childCount; i++) { 7532 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7533 } 7534 } 7535 7536 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7537 try { 7538 mInstaller.destroyAppProfiles(pkg.packageName); 7539 } catch (InstallerException e) { 7540 Slog.w(TAG, String.valueOf(e)); 7541 } 7542 } 7543 7544 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7545 if (pkg == null) { 7546 Slog.wtf(TAG, "Package was null!", new Throwable()); 7547 return; 7548 } 7549 clearAppProfilesLeafLIF(pkg); 7550 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7551 for (int i = 0; i < childCount; i++) { 7552 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7553 } 7554 } 7555 7556 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7557 try { 7558 mInstaller.clearAppProfiles(pkg.packageName); 7559 } catch (InstallerException e) { 7560 Slog.w(TAG, String.valueOf(e)); 7561 } 7562 } 7563 7564 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7565 long lastUpdateTime) { 7566 // Set parent install/update time 7567 PackageSetting ps = (PackageSetting) pkg.mExtras; 7568 if (ps != null) { 7569 ps.firstInstallTime = firstInstallTime; 7570 ps.lastUpdateTime = lastUpdateTime; 7571 } 7572 // Set children install/update time 7573 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7574 for (int i = 0; i < childCount; i++) { 7575 PackageParser.Package childPkg = pkg.childPackages.get(i); 7576 ps = (PackageSetting) childPkg.mExtras; 7577 if (ps != null) { 7578 ps.firstInstallTime = firstInstallTime; 7579 ps.lastUpdateTime = lastUpdateTime; 7580 } 7581 } 7582 } 7583 7584 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7585 PackageParser.Package changingLib) { 7586 if (file.path != null) { 7587 usesLibraryFiles.add(file.path); 7588 return; 7589 } 7590 PackageParser.Package p = mPackages.get(file.apk); 7591 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7592 // If we are doing this while in the middle of updating a library apk, 7593 // then we need to make sure to use that new apk for determining the 7594 // dependencies here. (We haven't yet finished committing the new apk 7595 // to the package manager state.) 7596 if (p == null || p.packageName.equals(changingLib.packageName)) { 7597 p = changingLib; 7598 } 7599 } 7600 if (p != null) { 7601 usesLibraryFiles.addAll(p.getAllCodePaths()); 7602 } 7603 } 7604 7605 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7606 PackageParser.Package changingLib) throws PackageManagerException { 7607 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7608 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7609 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7610 for (int i=0; i<N; i++) { 7611 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7612 if (file == null) { 7613 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7614 "Package " + pkg.packageName + " requires unavailable shared library " 7615 + pkg.usesLibraries.get(i) + "; failing!"); 7616 } 7617 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7618 } 7619 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7620 for (int i=0; i<N; i++) { 7621 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7622 if (file == null) { 7623 Slog.w(TAG, "Package " + pkg.packageName 7624 + " desires unavailable shared library " 7625 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7626 } else { 7627 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7628 } 7629 } 7630 N = usesLibraryFiles.size(); 7631 if (N > 0) { 7632 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7633 } else { 7634 pkg.usesLibraryFiles = null; 7635 } 7636 } 7637 } 7638 7639 private static boolean hasString(List<String> list, List<String> which) { 7640 if (list == null) { 7641 return false; 7642 } 7643 for (int i=list.size()-1; i>=0; i--) { 7644 for (int j=which.size()-1; j>=0; j--) { 7645 if (which.get(j).equals(list.get(i))) { 7646 return true; 7647 } 7648 } 7649 } 7650 return false; 7651 } 7652 7653 private void updateAllSharedLibrariesLPw() { 7654 for (PackageParser.Package pkg : mPackages.values()) { 7655 try { 7656 updateSharedLibrariesLPw(pkg, null); 7657 } catch (PackageManagerException e) { 7658 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7659 } 7660 } 7661 } 7662 7663 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7664 PackageParser.Package changingPkg) { 7665 ArrayList<PackageParser.Package> res = null; 7666 for (PackageParser.Package pkg : mPackages.values()) { 7667 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7668 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7669 if (res == null) { 7670 res = new ArrayList<PackageParser.Package>(); 7671 } 7672 res.add(pkg); 7673 try { 7674 updateSharedLibrariesLPw(pkg, changingPkg); 7675 } catch (PackageManagerException e) { 7676 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7677 } 7678 } 7679 } 7680 return res; 7681 } 7682 7683 /** 7684 * Derive the value of the {@code cpuAbiOverride} based on the provided 7685 * value and an optional stored value from the package settings. 7686 */ 7687 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7688 String cpuAbiOverride = null; 7689 7690 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7691 cpuAbiOverride = null; 7692 } else if (abiOverride != null) { 7693 cpuAbiOverride = abiOverride; 7694 } else if (settings != null) { 7695 cpuAbiOverride = settings.cpuAbiOverrideString; 7696 } 7697 7698 return cpuAbiOverride; 7699 } 7700 7701 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7702 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7703 throws PackageManagerException { 7704 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7705 // If the package has children and this is the first dive in the function 7706 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7707 // whether all packages (parent and children) would be successfully scanned 7708 // before the actual scan since scanning mutates internal state and we want 7709 // to atomically install the package and its children. 7710 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7711 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7712 scanFlags |= SCAN_CHECK_ONLY; 7713 } 7714 } else { 7715 scanFlags &= ~SCAN_CHECK_ONLY; 7716 } 7717 7718 final PackageParser.Package scannedPkg; 7719 try { 7720 // Scan the parent 7721 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7722 // Scan the children 7723 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7724 for (int i = 0; i < childCount; i++) { 7725 PackageParser.Package childPkg = pkg.childPackages.get(i); 7726 scanPackageLI(childPkg, policyFlags, 7727 scanFlags, currentTime, user); 7728 } 7729 } finally { 7730 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7731 } 7732 7733 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7734 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7735 } 7736 7737 return scannedPkg; 7738 } 7739 7740 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7741 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7742 boolean success = false; 7743 try { 7744 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7745 currentTime, user); 7746 success = true; 7747 return res; 7748 } finally { 7749 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7750 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7751 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7752 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7753 destroyAppProfilesLIF(pkg); 7754 } 7755 } 7756 } 7757 7758 /** 7759 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7760 */ 7761 private static boolean apkHasCode(String fileName) { 7762 StrictJarFile jarFile = null; 7763 try { 7764 jarFile = new StrictJarFile(fileName, 7765 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7766 return jarFile.findEntry("classes.dex") != null; 7767 } catch (IOException ignore) { 7768 } finally { 7769 try { 7770 jarFile.close(); 7771 } catch (IOException ignore) {} 7772 } 7773 return false; 7774 } 7775 7776 /** 7777 * Enforces code policy for the package. This ensures that if an APK has 7778 * declared hasCode="true" in its manifest that the APK actually contains 7779 * code. 7780 * 7781 * @throws PackageManagerException If bytecode could not be found when it should exist 7782 */ 7783 private static void enforceCodePolicy(PackageParser.Package pkg) 7784 throws PackageManagerException { 7785 final boolean shouldHaveCode = 7786 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7787 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7788 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7789 "Package " + pkg.baseCodePath + " code is missing"); 7790 } 7791 7792 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7793 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7794 final boolean splitShouldHaveCode = 7795 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7796 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7797 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7798 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7799 } 7800 } 7801 } 7802 } 7803 7804 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7805 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7806 throws PackageManagerException { 7807 final File scanFile = new File(pkg.codePath); 7808 if (pkg.applicationInfo.getCodePath() == null || 7809 pkg.applicationInfo.getResourcePath() == null) { 7810 // Bail out. The resource and code paths haven't been set. 7811 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7812 "Code and resource paths haven't been set correctly"); 7813 } 7814 7815 // Apply policy 7816 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7817 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7818 if (pkg.applicationInfo.isDirectBootAware()) { 7819 // we're direct boot aware; set for all components 7820 for (PackageParser.Service s : pkg.services) { 7821 s.info.encryptionAware = s.info.directBootAware = true; 7822 } 7823 for (PackageParser.Provider p : pkg.providers) { 7824 p.info.encryptionAware = p.info.directBootAware = true; 7825 } 7826 for (PackageParser.Activity a : pkg.activities) { 7827 a.info.encryptionAware = a.info.directBootAware = true; 7828 } 7829 for (PackageParser.Activity r : pkg.receivers) { 7830 r.info.encryptionAware = r.info.directBootAware = true; 7831 } 7832 } 7833 } else { 7834 // Only allow system apps to be flagged as core apps. 7835 pkg.coreApp = false; 7836 // clear flags not applicable to regular apps 7837 pkg.applicationInfo.privateFlags &= 7838 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7839 pkg.applicationInfo.privateFlags &= 7840 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7841 } 7842 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7843 7844 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7845 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7846 } 7847 7848 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7849 enforceCodePolicy(pkg); 7850 } 7851 7852 if (mCustomResolverComponentName != null && 7853 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7854 setUpCustomResolverActivity(pkg); 7855 } 7856 7857 if (pkg.packageName.equals("android")) { 7858 synchronized (mPackages) { 7859 if (mAndroidApplication != null) { 7860 Slog.w(TAG, "*************************************************"); 7861 Slog.w(TAG, "Core android package being redefined. Skipping."); 7862 Slog.w(TAG, " file=" + scanFile); 7863 Slog.w(TAG, "*************************************************"); 7864 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7865 "Core android package being redefined. Skipping."); 7866 } 7867 7868 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7869 // Set up information for our fall-back user intent resolution activity. 7870 mPlatformPackage = pkg; 7871 pkg.mVersionCode = mSdkVersion; 7872 mAndroidApplication = pkg.applicationInfo; 7873 7874 if (!mResolverReplaced) { 7875 mResolveActivity.applicationInfo = mAndroidApplication; 7876 mResolveActivity.name = ResolverActivity.class.getName(); 7877 mResolveActivity.packageName = mAndroidApplication.packageName; 7878 mResolveActivity.processName = "system:ui"; 7879 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7880 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7881 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7882 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7883 mResolveActivity.exported = true; 7884 mResolveActivity.enabled = true; 7885 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7886 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7887 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7888 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7889 | ActivityInfo.CONFIG_ORIENTATION 7890 | ActivityInfo.CONFIG_KEYBOARD 7891 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7892 mResolveInfo.activityInfo = mResolveActivity; 7893 mResolveInfo.priority = 0; 7894 mResolveInfo.preferredOrder = 0; 7895 mResolveInfo.match = 0; 7896 mResolveComponentName = new ComponentName( 7897 mAndroidApplication.packageName, mResolveActivity.name); 7898 } 7899 } 7900 } 7901 } 7902 7903 if (DEBUG_PACKAGE_SCANNING) { 7904 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7905 Log.d(TAG, "Scanning package " + pkg.packageName); 7906 } 7907 7908 synchronized (mPackages) { 7909 if (mPackages.containsKey(pkg.packageName) 7910 || mSharedLibraries.containsKey(pkg.packageName)) { 7911 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7912 "Application package " + pkg.packageName 7913 + " already installed. Skipping duplicate."); 7914 } 7915 7916 // If we're only installing presumed-existing packages, require that the 7917 // scanned APK is both already known and at the path previously established 7918 // for it. Previously unknown packages we pick up normally, but if we have an 7919 // a priori expectation about this package's install presence, enforce it. 7920 // With a singular exception for new system packages. When an OTA contains 7921 // a new system package, we allow the codepath to change from a system location 7922 // to the user-installed location. If we don't allow this change, any newer, 7923 // user-installed version of the application will be ignored. 7924 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7925 if (mExpectingBetter.containsKey(pkg.packageName)) { 7926 logCriticalInfo(Log.WARN, 7927 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7928 } else { 7929 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7930 if (known != null) { 7931 if (DEBUG_PACKAGE_SCANNING) { 7932 Log.d(TAG, "Examining " + pkg.codePath 7933 + " and requiring known paths " + known.codePathString 7934 + " & " + known.resourcePathString); 7935 } 7936 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7937 || !pkg.applicationInfo.getResourcePath().equals( 7938 known.resourcePathString)) { 7939 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7940 "Application package " + pkg.packageName 7941 + " found at " + pkg.applicationInfo.getCodePath() 7942 + " but expected at " + known.codePathString 7943 + "; ignoring."); 7944 } 7945 } 7946 } 7947 } 7948 } 7949 7950 // Initialize package source and resource directories 7951 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7952 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7953 7954 SharedUserSetting suid = null; 7955 PackageSetting pkgSetting = null; 7956 7957 if (!isSystemApp(pkg)) { 7958 // Only system apps can use these features. 7959 pkg.mOriginalPackages = null; 7960 pkg.mRealPackage = null; 7961 pkg.mAdoptPermissions = null; 7962 } 7963 7964 // Getting the package setting may have a side-effect, so if we 7965 // are only checking if scan would succeed, stash a copy of the 7966 // old setting to restore at the end. 7967 PackageSetting nonMutatedPs = null; 7968 7969 // writer 7970 synchronized (mPackages) { 7971 if (pkg.mSharedUserId != null) { 7972 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7973 if (suid == null) { 7974 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7975 "Creating application package " + pkg.packageName 7976 + " for shared user failed"); 7977 } 7978 if (DEBUG_PACKAGE_SCANNING) { 7979 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7980 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7981 + "): packages=" + suid.packages); 7982 } 7983 } 7984 7985 // Check if we are renaming from an original package name. 7986 PackageSetting origPackage = null; 7987 String realName = null; 7988 if (pkg.mOriginalPackages != null) { 7989 // This package may need to be renamed to a previously 7990 // installed name. Let's check on that... 7991 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7992 if (pkg.mOriginalPackages.contains(renamed)) { 7993 // This package had originally been installed as the 7994 // original name, and we have already taken care of 7995 // transitioning to the new one. Just update the new 7996 // one to continue using the old name. 7997 realName = pkg.mRealPackage; 7998 if (!pkg.packageName.equals(renamed)) { 7999 // Callers into this function may have already taken 8000 // care of renaming the package; only do it here if 8001 // it is not already done. 8002 pkg.setPackageName(renamed); 8003 } 8004 8005 } else { 8006 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8007 if ((origPackage = mSettings.peekPackageLPr( 8008 pkg.mOriginalPackages.get(i))) != null) { 8009 // We do have the package already installed under its 8010 // original name... should we use it? 8011 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8012 // New package is not compatible with original. 8013 origPackage = null; 8014 continue; 8015 } else if (origPackage.sharedUser != null) { 8016 // Make sure uid is compatible between packages. 8017 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8018 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8019 + " to " + pkg.packageName + ": old uid " 8020 + origPackage.sharedUser.name 8021 + " differs from " + pkg.mSharedUserId); 8022 origPackage = null; 8023 continue; 8024 } 8025 // TODO: Add case when shared user id is added [b/28144775] 8026 } else { 8027 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8028 + pkg.packageName + " to old name " + origPackage.name); 8029 } 8030 break; 8031 } 8032 } 8033 } 8034 } 8035 8036 if (mTransferedPackages.contains(pkg.packageName)) { 8037 Slog.w(TAG, "Package " + pkg.packageName 8038 + " was transferred to another, but its .apk remains"); 8039 } 8040 8041 // See comments in nonMutatedPs declaration 8042 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8043 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8044 if (foundPs != null) { 8045 nonMutatedPs = new PackageSetting(foundPs); 8046 } 8047 } 8048 8049 // Just create the setting, don't add it yet. For already existing packages 8050 // the PkgSetting exists already and doesn't have to be created. 8051 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8052 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8053 pkg.applicationInfo.primaryCpuAbi, 8054 pkg.applicationInfo.secondaryCpuAbi, 8055 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8056 user, false); 8057 if (pkgSetting == null) { 8058 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8059 "Creating application package " + pkg.packageName + " failed"); 8060 } 8061 8062 if (pkgSetting.origPackage != null) { 8063 // If we are first transitioning from an original package, 8064 // fix up the new package's name now. We need to do this after 8065 // looking up the package under its new name, so getPackageLP 8066 // can take care of fiddling things correctly. 8067 pkg.setPackageName(origPackage.name); 8068 8069 // File a report about this. 8070 String msg = "New package " + pkgSetting.realName 8071 + " renamed to replace old package " + pkgSetting.name; 8072 reportSettingsProblem(Log.WARN, msg); 8073 8074 // Make a note of it. 8075 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8076 mTransferedPackages.add(origPackage.name); 8077 } 8078 8079 // No longer need to retain this. 8080 pkgSetting.origPackage = null; 8081 } 8082 8083 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8084 // Make a note of it. 8085 mTransferedPackages.add(pkg.packageName); 8086 } 8087 8088 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8089 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8090 } 8091 8092 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8093 // Check all shared libraries and map to their actual file path. 8094 // We only do this here for apps not on a system dir, because those 8095 // are the only ones that can fail an install due to this. We 8096 // will take care of the system apps by updating all of their 8097 // library paths after the scan is done. 8098 updateSharedLibrariesLPw(pkg, null); 8099 } 8100 8101 if (mFoundPolicyFile) { 8102 SELinuxMMAC.assignSeinfoValue(pkg); 8103 } 8104 8105 pkg.applicationInfo.uid = pkgSetting.appId; 8106 pkg.mExtras = pkgSetting; 8107 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8108 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8109 // We just determined the app is signed correctly, so bring 8110 // over the latest parsed certs. 8111 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8112 } else { 8113 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8114 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8115 "Package " + pkg.packageName + " upgrade keys do not match the " 8116 + "previously installed version"); 8117 } else { 8118 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8119 String msg = "System package " + pkg.packageName 8120 + " signature changed; retaining data."; 8121 reportSettingsProblem(Log.WARN, msg); 8122 } 8123 } 8124 } else { 8125 try { 8126 verifySignaturesLP(pkgSetting, pkg); 8127 // We just determined the app is signed correctly, so bring 8128 // over the latest parsed certs. 8129 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8130 } catch (PackageManagerException e) { 8131 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8132 throw e; 8133 } 8134 // The signature has changed, but this package is in the system 8135 // image... let's recover! 8136 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8137 // However... if this package is part of a shared user, but it 8138 // doesn't match the signature of the shared user, let's fail. 8139 // What this means is that you can't change the signatures 8140 // associated with an overall shared user, which doesn't seem all 8141 // that unreasonable. 8142 if (pkgSetting.sharedUser != null) { 8143 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8144 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8145 throw new PackageManagerException( 8146 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8147 "Signature mismatch for shared user: " 8148 + pkgSetting.sharedUser); 8149 } 8150 } 8151 // File a report about this. 8152 String msg = "System package " + pkg.packageName 8153 + " signature changed; retaining data."; 8154 reportSettingsProblem(Log.WARN, msg); 8155 } 8156 } 8157 // Verify that this new package doesn't have any content providers 8158 // that conflict with existing packages. Only do this if the 8159 // package isn't already installed, since we don't want to break 8160 // things that are installed. 8161 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8162 final int N = pkg.providers.size(); 8163 int i; 8164 for (i=0; i<N; i++) { 8165 PackageParser.Provider p = pkg.providers.get(i); 8166 if (p.info.authority != null) { 8167 String names[] = p.info.authority.split(";"); 8168 for (int j = 0; j < names.length; j++) { 8169 if (mProvidersByAuthority.containsKey(names[j])) { 8170 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8171 final String otherPackageName = 8172 ((other != null && other.getComponentName() != null) ? 8173 other.getComponentName().getPackageName() : "?"); 8174 throw new PackageManagerException( 8175 INSTALL_FAILED_CONFLICTING_PROVIDER, 8176 "Can't install because provider name " + names[j] 8177 + " (in package " + pkg.applicationInfo.packageName 8178 + ") is already used by " + otherPackageName); 8179 } 8180 } 8181 } 8182 } 8183 } 8184 8185 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8186 // This package wants to adopt ownership of permissions from 8187 // another package. 8188 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8189 final String origName = pkg.mAdoptPermissions.get(i); 8190 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8191 if (orig != null) { 8192 if (verifyPackageUpdateLPr(orig, pkg)) { 8193 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8194 + pkg.packageName); 8195 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8196 } 8197 } 8198 } 8199 } 8200 } 8201 8202 final String pkgName = pkg.packageName; 8203 8204 final long scanFileTime = scanFile.lastModified(); 8205 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8206 pkg.applicationInfo.processName = fixProcessName( 8207 pkg.applicationInfo.packageName, 8208 pkg.applicationInfo.processName, 8209 pkg.applicationInfo.uid); 8210 8211 if (pkg != mPlatformPackage) { 8212 // Get all of our default paths setup 8213 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8214 } 8215 8216 final String path = scanFile.getPath(); 8217 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8218 8219 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8220 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8221 8222 // Some system apps still use directory structure for native libraries 8223 // in which case we might end up not detecting abi solely based on apk 8224 // structure. Try to detect abi based on directory structure. 8225 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8226 pkg.applicationInfo.primaryCpuAbi == null) { 8227 setBundledAppAbisAndRoots(pkg, pkgSetting); 8228 setNativeLibraryPaths(pkg); 8229 } 8230 8231 } else { 8232 if ((scanFlags & SCAN_MOVE) != 0) { 8233 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8234 // but we already have this packages package info in the PackageSetting. We just 8235 // use that and derive the native library path based on the new codepath. 8236 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8237 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8238 } 8239 8240 // Set native library paths again. For moves, the path will be updated based on the 8241 // ABIs we've determined above. For non-moves, the path will be updated based on the 8242 // ABIs we determined during compilation, but the path will depend on the final 8243 // package path (after the rename away from the stage path). 8244 setNativeLibraryPaths(pkg); 8245 } 8246 8247 // This is a special case for the "system" package, where the ABI is 8248 // dictated by the zygote configuration (and init.rc). We should keep track 8249 // of this ABI so that we can deal with "normal" applications that run under 8250 // the same UID correctly. 8251 if (mPlatformPackage == pkg) { 8252 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8253 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8254 } 8255 8256 // If there's a mismatch between the abi-override in the package setting 8257 // and the abiOverride specified for the install. Warn about this because we 8258 // would've already compiled the app without taking the package setting into 8259 // account. 8260 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8261 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8262 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8263 " for package " + pkg.packageName); 8264 } 8265 } 8266 8267 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8268 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8269 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8270 8271 // Copy the derived override back to the parsed package, so that we can 8272 // update the package settings accordingly. 8273 pkg.cpuAbiOverride = cpuAbiOverride; 8274 8275 if (DEBUG_ABI_SELECTION) { 8276 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8277 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8278 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8279 } 8280 8281 // Push the derived path down into PackageSettings so we know what to 8282 // clean up at uninstall time. 8283 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8284 8285 if (DEBUG_ABI_SELECTION) { 8286 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8287 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8288 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8289 } 8290 8291 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8292 // We don't do this here during boot because we can do it all 8293 // at once after scanning all existing packages. 8294 // 8295 // We also do this *before* we perform dexopt on this package, so that 8296 // we can avoid redundant dexopts, and also to make sure we've got the 8297 // code and package path correct. 8298 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8299 pkg, true /* boot complete */); 8300 } 8301 8302 if (mFactoryTest && pkg.requestedPermissions.contains( 8303 android.Manifest.permission.FACTORY_TEST)) { 8304 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8305 } 8306 8307 ArrayList<PackageParser.Package> clientLibPkgs = null; 8308 8309 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8310 if (nonMutatedPs != null) { 8311 synchronized (mPackages) { 8312 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8313 } 8314 } 8315 return pkg; 8316 } 8317 8318 // Only privileged apps and updated privileged apps can add child packages. 8319 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8320 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8321 throw new PackageManagerException("Only privileged apps and updated " 8322 + "privileged apps can add child packages. Ignoring package " 8323 + pkg.packageName); 8324 } 8325 final int childCount = pkg.childPackages.size(); 8326 for (int i = 0; i < childCount; i++) { 8327 PackageParser.Package childPkg = pkg.childPackages.get(i); 8328 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8329 childPkg.packageName)) { 8330 throw new PackageManagerException("Cannot override a child package of " 8331 + "another disabled system app. Ignoring package " + pkg.packageName); 8332 } 8333 } 8334 } 8335 8336 // writer 8337 synchronized (mPackages) { 8338 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8339 // Only system apps can add new shared libraries. 8340 if (pkg.libraryNames != null) { 8341 for (int i=0; i<pkg.libraryNames.size(); i++) { 8342 String name = pkg.libraryNames.get(i); 8343 boolean allowed = false; 8344 if (pkg.isUpdatedSystemApp()) { 8345 // New library entries can only be added through the 8346 // system image. This is important to get rid of a lot 8347 // of nasty edge cases: for example if we allowed a non- 8348 // system update of the app to add a library, then uninstalling 8349 // the update would make the library go away, and assumptions 8350 // we made such as through app install filtering would now 8351 // have allowed apps on the device which aren't compatible 8352 // with it. Better to just have the restriction here, be 8353 // conservative, and create many fewer cases that can negatively 8354 // impact the user experience. 8355 final PackageSetting sysPs = mSettings 8356 .getDisabledSystemPkgLPr(pkg.packageName); 8357 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8358 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8359 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8360 allowed = true; 8361 break; 8362 } 8363 } 8364 } 8365 } else { 8366 allowed = true; 8367 } 8368 if (allowed) { 8369 if (!mSharedLibraries.containsKey(name)) { 8370 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8371 } else if (!name.equals(pkg.packageName)) { 8372 Slog.w(TAG, "Package " + pkg.packageName + " library " 8373 + name + " already exists; skipping"); 8374 } 8375 } else { 8376 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8377 + name + " that is not declared on system image; skipping"); 8378 } 8379 } 8380 if ((scanFlags & SCAN_BOOTING) == 0) { 8381 // If we are not booting, we need to update any applications 8382 // that are clients of our shared library. If we are booting, 8383 // this will all be done once the scan is complete. 8384 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8385 } 8386 } 8387 } 8388 } 8389 8390 if ((scanFlags & SCAN_BOOTING) != 0) { 8391 // No apps can run during boot scan, so they don't need to be frozen 8392 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8393 // Caller asked to not kill app, so it's probably not frozen 8394 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8395 // Caller asked us to ignore frozen check for some reason; they 8396 // probably didn't know the package name 8397 } else { 8398 // We're doing major surgery on this package, so it better be frozen 8399 // right now to keep it from launching 8400 checkPackageFrozen(pkgName); 8401 } 8402 8403 // Also need to kill any apps that are dependent on the library. 8404 if (clientLibPkgs != null) { 8405 for (int i=0; i<clientLibPkgs.size(); i++) { 8406 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8407 killApplication(clientPkg.applicationInfo.packageName, 8408 clientPkg.applicationInfo.uid, "update lib"); 8409 } 8410 } 8411 8412 // Make sure we're not adding any bogus keyset info 8413 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8414 ksms.assertScannedPackageValid(pkg); 8415 8416 // writer 8417 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8418 8419 boolean createIdmapFailed = false; 8420 synchronized (mPackages) { 8421 // We don't expect installation to fail beyond this point 8422 8423 // Add the new setting to mSettings 8424 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8425 // Add the new setting to mPackages 8426 mPackages.put(pkg.applicationInfo.packageName, pkg); 8427 // Make sure we don't accidentally delete its data. 8428 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8429 while (iter.hasNext()) { 8430 PackageCleanItem item = iter.next(); 8431 if (pkgName.equals(item.packageName)) { 8432 iter.remove(); 8433 } 8434 } 8435 8436 // Take care of first install / last update times. 8437 if (currentTime != 0) { 8438 if (pkgSetting.firstInstallTime == 0) { 8439 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8440 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8441 pkgSetting.lastUpdateTime = currentTime; 8442 } 8443 } else if (pkgSetting.firstInstallTime == 0) { 8444 // We need *something*. Take time time stamp of the file. 8445 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8446 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8447 if (scanFileTime != pkgSetting.timeStamp) { 8448 // A package on the system image has changed; consider this 8449 // to be an update. 8450 pkgSetting.lastUpdateTime = scanFileTime; 8451 } 8452 } 8453 8454 // Add the package's KeySets to the global KeySetManagerService 8455 ksms.addScannedPackageLPw(pkg); 8456 8457 int N = pkg.providers.size(); 8458 StringBuilder r = null; 8459 int i; 8460 for (i=0; i<N; i++) { 8461 PackageParser.Provider p = pkg.providers.get(i); 8462 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8463 p.info.processName, pkg.applicationInfo.uid); 8464 mProviders.addProvider(p); 8465 p.syncable = p.info.isSyncable; 8466 if (p.info.authority != null) { 8467 String names[] = p.info.authority.split(";"); 8468 p.info.authority = null; 8469 for (int j = 0; j < names.length; j++) { 8470 if (j == 1 && p.syncable) { 8471 // We only want the first authority for a provider to possibly be 8472 // syncable, so if we already added this provider using a different 8473 // authority clear the syncable flag. We copy the provider before 8474 // changing it because the mProviders object contains a reference 8475 // to a provider that we don't want to change. 8476 // Only do this for the second authority since the resulting provider 8477 // object can be the same for all future authorities for this provider. 8478 p = new PackageParser.Provider(p); 8479 p.syncable = false; 8480 } 8481 if (!mProvidersByAuthority.containsKey(names[j])) { 8482 mProvidersByAuthority.put(names[j], p); 8483 if (p.info.authority == null) { 8484 p.info.authority = names[j]; 8485 } else { 8486 p.info.authority = p.info.authority + ";" + names[j]; 8487 } 8488 if (DEBUG_PACKAGE_SCANNING) { 8489 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8490 Log.d(TAG, "Registered content provider: " + names[j] 8491 + ", className = " + p.info.name + ", isSyncable = " 8492 + p.info.isSyncable); 8493 } 8494 } else { 8495 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8496 Slog.w(TAG, "Skipping provider name " + names[j] + 8497 " (in package " + pkg.applicationInfo.packageName + 8498 "): name already used by " 8499 + ((other != null && other.getComponentName() != null) 8500 ? other.getComponentName().getPackageName() : "?")); 8501 } 8502 } 8503 } 8504 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8505 if (r == null) { 8506 r = new StringBuilder(256); 8507 } else { 8508 r.append(' '); 8509 } 8510 r.append(p.info.name); 8511 } 8512 } 8513 if (r != null) { 8514 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8515 } 8516 8517 N = pkg.services.size(); 8518 r = null; 8519 for (i=0; i<N; i++) { 8520 PackageParser.Service s = pkg.services.get(i); 8521 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8522 s.info.processName, pkg.applicationInfo.uid); 8523 mServices.addService(s); 8524 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8525 if (r == null) { 8526 r = new StringBuilder(256); 8527 } else { 8528 r.append(' '); 8529 } 8530 r.append(s.info.name); 8531 } 8532 } 8533 if (r != null) { 8534 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8535 } 8536 8537 N = pkg.receivers.size(); 8538 r = null; 8539 for (i=0; i<N; i++) { 8540 PackageParser.Activity a = pkg.receivers.get(i); 8541 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8542 a.info.processName, pkg.applicationInfo.uid); 8543 mReceivers.addActivity(a, "receiver"); 8544 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8545 if (r == null) { 8546 r = new StringBuilder(256); 8547 } else { 8548 r.append(' '); 8549 } 8550 r.append(a.info.name); 8551 } 8552 } 8553 if (r != null) { 8554 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8555 } 8556 8557 N = pkg.activities.size(); 8558 r = null; 8559 for (i=0; i<N; i++) { 8560 PackageParser.Activity a = pkg.activities.get(i); 8561 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8562 a.info.processName, pkg.applicationInfo.uid); 8563 mActivities.addActivity(a, "activity"); 8564 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8565 if (r == null) { 8566 r = new StringBuilder(256); 8567 } else { 8568 r.append(' '); 8569 } 8570 r.append(a.info.name); 8571 } 8572 } 8573 if (r != null) { 8574 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8575 } 8576 8577 N = pkg.permissionGroups.size(); 8578 r = null; 8579 for (i=0; i<N; i++) { 8580 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8581 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8582 if (cur == null) { 8583 mPermissionGroups.put(pg.info.name, pg); 8584 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8585 if (r == null) { 8586 r = new StringBuilder(256); 8587 } else { 8588 r.append(' '); 8589 } 8590 r.append(pg.info.name); 8591 } 8592 } else { 8593 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8594 + pg.info.packageName + " ignored: original from " 8595 + cur.info.packageName); 8596 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8597 if (r == null) { 8598 r = new StringBuilder(256); 8599 } else { 8600 r.append(' '); 8601 } 8602 r.append("DUP:"); 8603 r.append(pg.info.name); 8604 } 8605 } 8606 } 8607 if (r != null) { 8608 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8609 } 8610 8611 N = pkg.permissions.size(); 8612 r = null; 8613 for (i=0; i<N; i++) { 8614 PackageParser.Permission p = pkg.permissions.get(i); 8615 8616 // Assume by default that we did not install this permission into the system. 8617 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8618 8619 // Now that permission groups have a special meaning, we ignore permission 8620 // groups for legacy apps to prevent unexpected behavior. In particular, 8621 // permissions for one app being granted to someone just becase they happen 8622 // to be in a group defined by another app (before this had no implications). 8623 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8624 p.group = mPermissionGroups.get(p.info.group); 8625 // Warn for a permission in an unknown group. 8626 if (p.info.group != null && p.group == null) { 8627 Slog.w(TAG, "Permission " + p.info.name + " from package " 8628 + p.info.packageName + " in an unknown group " + p.info.group); 8629 } 8630 } 8631 8632 ArrayMap<String, BasePermission> permissionMap = 8633 p.tree ? mSettings.mPermissionTrees 8634 : mSettings.mPermissions; 8635 BasePermission bp = permissionMap.get(p.info.name); 8636 8637 // Allow system apps to redefine non-system permissions 8638 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8639 final boolean currentOwnerIsSystem = (bp.perm != null 8640 && isSystemApp(bp.perm.owner)); 8641 if (isSystemApp(p.owner)) { 8642 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8643 // It's a built-in permission and no owner, take ownership now 8644 bp.packageSetting = pkgSetting; 8645 bp.perm = p; 8646 bp.uid = pkg.applicationInfo.uid; 8647 bp.sourcePackage = p.info.packageName; 8648 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8649 } else if (!currentOwnerIsSystem) { 8650 String msg = "New decl " + p.owner + " of permission " 8651 + p.info.name + " is system; overriding " + bp.sourcePackage; 8652 reportSettingsProblem(Log.WARN, msg); 8653 bp = null; 8654 } 8655 } 8656 } 8657 8658 if (bp == null) { 8659 bp = new BasePermission(p.info.name, p.info.packageName, 8660 BasePermission.TYPE_NORMAL); 8661 permissionMap.put(p.info.name, bp); 8662 } 8663 8664 if (bp.perm == null) { 8665 if (bp.sourcePackage == null 8666 || bp.sourcePackage.equals(p.info.packageName)) { 8667 BasePermission tree = findPermissionTreeLP(p.info.name); 8668 if (tree == null 8669 || tree.sourcePackage.equals(p.info.packageName)) { 8670 bp.packageSetting = pkgSetting; 8671 bp.perm = p; 8672 bp.uid = pkg.applicationInfo.uid; 8673 bp.sourcePackage = p.info.packageName; 8674 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8675 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8676 if (r == null) { 8677 r = new StringBuilder(256); 8678 } else { 8679 r.append(' '); 8680 } 8681 r.append(p.info.name); 8682 } 8683 } else { 8684 Slog.w(TAG, "Permission " + p.info.name + " from package " 8685 + p.info.packageName + " ignored: base tree " 8686 + tree.name + " is from package " 8687 + tree.sourcePackage); 8688 } 8689 } else { 8690 Slog.w(TAG, "Permission " + p.info.name + " from package " 8691 + p.info.packageName + " ignored: original from " 8692 + bp.sourcePackage); 8693 } 8694 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8695 if (r == null) { 8696 r = new StringBuilder(256); 8697 } else { 8698 r.append(' '); 8699 } 8700 r.append("DUP:"); 8701 r.append(p.info.name); 8702 } 8703 if (bp.perm == p) { 8704 bp.protectionLevel = p.info.protectionLevel; 8705 } 8706 } 8707 8708 if (r != null) { 8709 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8710 } 8711 8712 N = pkg.instrumentation.size(); 8713 r = null; 8714 for (i=0; i<N; i++) { 8715 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8716 a.info.packageName = pkg.applicationInfo.packageName; 8717 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8718 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8719 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8720 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8721 a.info.dataDir = pkg.applicationInfo.dataDir; 8722 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8723 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8724 8725 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8726 // need other information about the application, like the ABI and what not ? 8727 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8728 mInstrumentation.put(a.getComponentName(), a); 8729 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8730 if (r == null) { 8731 r = new StringBuilder(256); 8732 } else { 8733 r.append(' '); 8734 } 8735 r.append(a.info.name); 8736 } 8737 } 8738 if (r != null) { 8739 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8740 } 8741 8742 if (pkg.protectedBroadcasts != null) { 8743 N = pkg.protectedBroadcasts.size(); 8744 for (i=0; i<N; i++) { 8745 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8746 } 8747 } 8748 8749 pkgSetting.setTimeStamp(scanFileTime); 8750 8751 // Create idmap files for pairs of (packages, overlay packages). 8752 // Note: "android", ie framework-res.apk, is handled by native layers. 8753 if (pkg.mOverlayTarget != null) { 8754 // This is an overlay package. 8755 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8756 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8757 mOverlays.put(pkg.mOverlayTarget, 8758 new ArrayMap<String, PackageParser.Package>()); 8759 } 8760 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8761 map.put(pkg.packageName, pkg); 8762 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8763 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8764 createIdmapFailed = true; 8765 } 8766 } 8767 } else if (mOverlays.containsKey(pkg.packageName) && 8768 !pkg.packageName.equals("android")) { 8769 // This is a regular package, with one or more known overlay packages. 8770 createIdmapsForPackageLI(pkg); 8771 } 8772 } 8773 8774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8775 8776 if (createIdmapFailed) { 8777 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8778 "scanPackageLI failed to createIdmap"); 8779 } 8780 return pkg; 8781 } 8782 8783 /** 8784 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8785 * is derived purely on the basis of the contents of {@code scanFile} and 8786 * {@code cpuAbiOverride}. 8787 * 8788 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8789 */ 8790 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8791 String cpuAbiOverride, boolean extractLibs) 8792 throws PackageManagerException { 8793 // TODO: We can probably be smarter about this stuff. For installed apps, 8794 // we can calculate this information at install time once and for all. For 8795 // system apps, we can probably assume that this information doesn't change 8796 // after the first boot scan. As things stand, we do lots of unnecessary work. 8797 8798 // Give ourselves some initial paths; we'll come back for another 8799 // pass once we've determined ABI below. 8800 setNativeLibraryPaths(pkg); 8801 8802 // We would never need to extract libs for forward-locked and external packages, 8803 // since the container service will do it for us. We shouldn't attempt to 8804 // extract libs from system app when it was not updated. 8805 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8806 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8807 extractLibs = false; 8808 } 8809 8810 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8811 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8812 8813 NativeLibraryHelper.Handle handle = null; 8814 try { 8815 handle = NativeLibraryHelper.Handle.create(pkg); 8816 // TODO(multiArch): This can be null for apps that didn't go through the 8817 // usual installation process. We can calculate it again, like we 8818 // do during install time. 8819 // 8820 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8821 // unnecessary. 8822 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8823 8824 // Null out the abis so that they can be recalculated. 8825 pkg.applicationInfo.primaryCpuAbi = null; 8826 pkg.applicationInfo.secondaryCpuAbi = null; 8827 if (isMultiArch(pkg.applicationInfo)) { 8828 // Warn if we've set an abiOverride for multi-lib packages.. 8829 // By definition, we need to copy both 32 and 64 bit libraries for 8830 // such packages. 8831 if (pkg.cpuAbiOverride != null 8832 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8833 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8834 } 8835 8836 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8837 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8838 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8839 if (extractLibs) { 8840 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8841 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8842 useIsaSpecificSubdirs); 8843 } else { 8844 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8845 } 8846 } 8847 8848 maybeThrowExceptionForMultiArchCopy( 8849 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8850 8851 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8852 if (extractLibs) { 8853 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8854 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8855 useIsaSpecificSubdirs); 8856 } else { 8857 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8858 } 8859 } 8860 8861 maybeThrowExceptionForMultiArchCopy( 8862 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8863 8864 if (abi64 >= 0) { 8865 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8866 } 8867 8868 if (abi32 >= 0) { 8869 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8870 if (abi64 >= 0) { 8871 if (pkg.use32bitAbi) { 8872 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8873 pkg.applicationInfo.primaryCpuAbi = abi; 8874 } else { 8875 pkg.applicationInfo.secondaryCpuAbi = abi; 8876 } 8877 } else { 8878 pkg.applicationInfo.primaryCpuAbi = abi; 8879 } 8880 } 8881 8882 } else { 8883 String[] abiList = (cpuAbiOverride != null) ? 8884 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8885 8886 // Enable gross and lame hacks for apps that are built with old 8887 // SDK tools. We must scan their APKs for renderscript bitcode and 8888 // not launch them if it's present. Don't bother checking on devices 8889 // that don't have 64 bit support. 8890 boolean needsRenderScriptOverride = false; 8891 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8892 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8893 abiList = Build.SUPPORTED_32_BIT_ABIS; 8894 needsRenderScriptOverride = true; 8895 } 8896 8897 final int copyRet; 8898 if (extractLibs) { 8899 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8900 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8901 } else { 8902 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8903 } 8904 8905 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8906 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8907 "Error unpackaging native libs for app, errorCode=" + copyRet); 8908 } 8909 8910 if (copyRet >= 0) { 8911 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8912 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8913 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8914 } else if (needsRenderScriptOverride) { 8915 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8916 } 8917 } 8918 } catch (IOException ioe) { 8919 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8920 } finally { 8921 IoUtils.closeQuietly(handle); 8922 } 8923 8924 // Now that we've calculated the ABIs and determined if it's an internal app, 8925 // we will go ahead and populate the nativeLibraryPath. 8926 setNativeLibraryPaths(pkg); 8927 } 8928 8929 /** 8930 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8931 * i.e, so that all packages can be run inside a single process if required. 8932 * 8933 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8934 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8935 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8936 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8937 * updating a package that belongs to a shared user. 8938 * 8939 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8940 * adds unnecessary complexity. 8941 */ 8942 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8943 PackageParser.Package scannedPackage, boolean bootComplete) { 8944 String requiredInstructionSet = null; 8945 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8946 requiredInstructionSet = VMRuntime.getInstructionSet( 8947 scannedPackage.applicationInfo.primaryCpuAbi); 8948 } 8949 8950 PackageSetting requirer = null; 8951 for (PackageSetting ps : packagesForUser) { 8952 // If packagesForUser contains scannedPackage, we skip it. This will happen 8953 // when scannedPackage is an update of an existing package. Without this check, 8954 // we will never be able to change the ABI of any package belonging to a shared 8955 // user, even if it's compatible with other packages. 8956 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8957 if (ps.primaryCpuAbiString == null) { 8958 continue; 8959 } 8960 8961 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8962 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8963 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8964 // this but there's not much we can do. 8965 String errorMessage = "Instruction set mismatch, " 8966 + ((requirer == null) ? "[caller]" : requirer) 8967 + " requires " + requiredInstructionSet + " whereas " + ps 8968 + " requires " + instructionSet; 8969 Slog.w(TAG, errorMessage); 8970 } 8971 8972 if (requiredInstructionSet == null) { 8973 requiredInstructionSet = instructionSet; 8974 requirer = ps; 8975 } 8976 } 8977 } 8978 8979 if (requiredInstructionSet != null) { 8980 String adjustedAbi; 8981 if (requirer != null) { 8982 // requirer != null implies that either scannedPackage was null or that scannedPackage 8983 // did not require an ABI, in which case we have to adjust scannedPackage to match 8984 // the ABI of the set (which is the same as requirer's ABI) 8985 adjustedAbi = requirer.primaryCpuAbiString; 8986 if (scannedPackage != null) { 8987 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8988 } 8989 } else { 8990 // requirer == null implies that we're updating all ABIs in the set to 8991 // match scannedPackage. 8992 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8993 } 8994 8995 for (PackageSetting ps : packagesForUser) { 8996 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8997 if (ps.primaryCpuAbiString != null) { 8998 continue; 8999 } 9000 9001 ps.primaryCpuAbiString = adjustedAbi; 9002 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9003 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9004 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9005 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9006 + " (requirer=" 9007 + (requirer == null ? "null" : requirer.pkg.packageName) 9008 + ", scannedPackage=" 9009 + (scannedPackage != null ? scannedPackage.packageName : "null") 9010 + ")"); 9011 try { 9012 mInstaller.rmdex(ps.codePathString, 9013 getDexCodeInstructionSet(getPreferredInstructionSet())); 9014 } catch (InstallerException ignored) { 9015 } 9016 } 9017 } 9018 } 9019 } 9020 } 9021 9022 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9023 synchronized (mPackages) { 9024 mResolverReplaced = true; 9025 // Set up information for custom user intent resolution activity. 9026 mResolveActivity.applicationInfo = pkg.applicationInfo; 9027 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9028 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9029 mResolveActivity.processName = pkg.applicationInfo.packageName; 9030 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9031 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9032 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9033 mResolveActivity.theme = 0; 9034 mResolveActivity.exported = true; 9035 mResolveActivity.enabled = true; 9036 mResolveInfo.activityInfo = mResolveActivity; 9037 mResolveInfo.priority = 0; 9038 mResolveInfo.preferredOrder = 0; 9039 mResolveInfo.match = 0; 9040 mResolveComponentName = mCustomResolverComponentName; 9041 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9042 mResolveComponentName); 9043 } 9044 } 9045 9046 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9047 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9048 9049 // Set up information for ephemeral installer activity 9050 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9051 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9052 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9053 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9054 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9055 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9056 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9057 mEphemeralInstallerActivity.theme = 0; 9058 mEphemeralInstallerActivity.exported = true; 9059 mEphemeralInstallerActivity.enabled = true; 9060 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9061 mEphemeralInstallerInfo.priority = 0; 9062 mEphemeralInstallerInfo.preferredOrder = 0; 9063 mEphemeralInstallerInfo.match = 0; 9064 9065 if (DEBUG_EPHEMERAL) { 9066 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9067 } 9068 } 9069 9070 private static String calculateBundledApkRoot(final String codePathString) { 9071 final File codePath = new File(codePathString); 9072 final File codeRoot; 9073 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9074 codeRoot = Environment.getRootDirectory(); 9075 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9076 codeRoot = Environment.getOemDirectory(); 9077 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9078 codeRoot = Environment.getVendorDirectory(); 9079 } else { 9080 // Unrecognized code path; take its top real segment as the apk root: 9081 // e.g. /something/app/blah.apk => /something 9082 try { 9083 File f = codePath.getCanonicalFile(); 9084 File parent = f.getParentFile(); // non-null because codePath is a file 9085 File tmp; 9086 while ((tmp = parent.getParentFile()) != null) { 9087 f = parent; 9088 parent = tmp; 9089 } 9090 codeRoot = f; 9091 Slog.w(TAG, "Unrecognized code path " 9092 + codePath + " - using " + codeRoot); 9093 } catch (IOException e) { 9094 // Can't canonicalize the code path -- shenanigans? 9095 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9096 return Environment.getRootDirectory().getPath(); 9097 } 9098 } 9099 return codeRoot.getPath(); 9100 } 9101 9102 /** 9103 * Derive and set the location of native libraries for the given package, 9104 * which varies depending on where and how the package was installed. 9105 */ 9106 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9107 final ApplicationInfo info = pkg.applicationInfo; 9108 final String codePath = pkg.codePath; 9109 final File codeFile = new File(codePath); 9110 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9111 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9112 9113 info.nativeLibraryRootDir = null; 9114 info.nativeLibraryRootRequiresIsa = false; 9115 info.nativeLibraryDir = null; 9116 info.secondaryNativeLibraryDir = null; 9117 9118 if (isApkFile(codeFile)) { 9119 // Monolithic install 9120 if (bundledApp) { 9121 // If "/system/lib64/apkname" exists, assume that is the per-package 9122 // native library directory to use; otherwise use "/system/lib/apkname". 9123 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9124 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9125 getPrimaryInstructionSet(info)); 9126 9127 // This is a bundled system app so choose the path based on the ABI. 9128 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9129 // is just the default path. 9130 final String apkName = deriveCodePathName(codePath); 9131 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9132 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9133 apkName).getAbsolutePath(); 9134 9135 if (info.secondaryCpuAbi != null) { 9136 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9137 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9138 secondaryLibDir, apkName).getAbsolutePath(); 9139 } 9140 } else if (asecApp) { 9141 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9142 .getAbsolutePath(); 9143 } else { 9144 final String apkName = deriveCodePathName(codePath); 9145 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9146 .getAbsolutePath(); 9147 } 9148 9149 info.nativeLibraryRootRequiresIsa = false; 9150 info.nativeLibraryDir = info.nativeLibraryRootDir; 9151 } else { 9152 // Cluster install 9153 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9154 info.nativeLibraryRootRequiresIsa = true; 9155 9156 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9157 getPrimaryInstructionSet(info)).getAbsolutePath(); 9158 9159 if (info.secondaryCpuAbi != null) { 9160 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9161 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9162 } 9163 } 9164 } 9165 9166 /** 9167 * Calculate the abis and roots for a bundled app. These can uniquely 9168 * be determined from the contents of the system partition, i.e whether 9169 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9170 * of this information, and instead assume that the system was built 9171 * sensibly. 9172 */ 9173 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9174 PackageSetting pkgSetting) { 9175 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9176 9177 // If "/system/lib64/apkname" exists, assume that is the per-package 9178 // native library directory to use; otherwise use "/system/lib/apkname". 9179 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9180 setBundledAppAbi(pkg, apkRoot, apkName); 9181 // pkgSetting might be null during rescan following uninstall of updates 9182 // to a bundled app, so accommodate that possibility. The settings in 9183 // that case will be established later from the parsed package. 9184 // 9185 // If the settings aren't null, sync them up with what we've just derived. 9186 // note that apkRoot isn't stored in the package settings. 9187 if (pkgSetting != null) { 9188 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9189 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9190 } 9191 } 9192 9193 /** 9194 * Deduces the ABI of a bundled app and sets the relevant fields on the 9195 * parsed pkg object. 9196 * 9197 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9198 * under which system libraries are installed. 9199 * @param apkName the name of the installed package. 9200 */ 9201 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9202 final File codeFile = new File(pkg.codePath); 9203 9204 final boolean has64BitLibs; 9205 final boolean has32BitLibs; 9206 if (isApkFile(codeFile)) { 9207 // Monolithic install 9208 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9209 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9210 } else { 9211 // Cluster install 9212 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9213 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9214 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9215 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9216 has64BitLibs = (new File(rootDir, isa)).exists(); 9217 } else { 9218 has64BitLibs = false; 9219 } 9220 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9221 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9222 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9223 has32BitLibs = (new File(rootDir, isa)).exists(); 9224 } else { 9225 has32BitLibs = false; 9226 } 9227 } 9228 9229 if (has64BitLibs && !has32BitLibs) { 9230 // The package has 64 bit libs, but not 32 bit libs. Its primary 9231 // ABI should be 64 bit. We can safely assume here that the bundled 9232 // native libraries correspond to the most preferred ABI in the list. 9233 9234 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9235 pkg.applicationInfo.secondaryCpuAbi = null; 9236 } else if (has32BitLibs && !has64BitLibs) { 9237 // The package has 32 bit libs but not 64 bit libs. Its primary 9238 // ABI should be 32 bit. 9239 9240 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9241 pkg.applicationInfo.secondaryCpuAbi = null; 9242 } else if (has32BitLibs && has64BitLibs) { 9243 // The application has both 64 and 32 bit bundled libraries. We check 9244 // here that the app declares multiArch support, and warn if it doesn't. 9245 // 9246 // We will be lenient here and record both ABIs. The primary will be the 9247 // ABI that's higher on the list, i.e, a device that's configured to prefer 9248 // 64 bit apps will see a 64 bit primary ABI, 9249 9250 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9251 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9252 } 9253 9254 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9255 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9256 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9257 } else { 9258 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9259 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9260 } 9261 } else { 9262 pkg.applicationInfo.primaryCpuAbi = null; 9263 pkg.applicationInfo.secondaryCpuAbi = null; 9264 } 9265 } 9266 9267 private void killApplication(String pkgName, int appId, String reason) { 9268 // Request the ActivityManager to kill the process(only for existing packages) 9269 // so that we do not end up in a confused state while the user is still using the older 9270 // version of the application while the new one gets installed. 9271 final long token = Binder.clearCallingIdentity(); 9272 try { 9273 IActivityManager am = ActivityManagerNative.getDefault(); 9274 if (am != null) { 9275 try { 9276 am.killApplicationWithAppId(pkgName, appId, reason); 9277 } catch (RemoteException e) { 9278 } 9279 } 9280 } finally { 9281 Binder.restoreCallingIdentity(token); 9282 } 9283 } 9284 9285 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9286 // Remove the parent package setting 9287 PackageSetting ps = (PackageSetting) pkg.mExtras; 9288 if (ps != null) { 9289 removePackageLI(ps, chatty); 9290 } 9291 // Remove the child package setting 9292 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9293 for (int i = 0; i < childCount; i++) { 9294 PackageParser.Package childPkg = pkg.childPackages.get(i); 9295 ps = (PackageSetting) childPkg.mExtras; 9296 if (ps != null) { 9297 removePackageLI(ps, chatty); 9298 } 9299 } 9300 } 9301 9302 void removePackageLI(PackageSetting ps, boolean chatty) { 9303 if (DEBUG_INSTALL) { 9304 if (chatty) 9305 Log.d(TAG, "Removing package " + ps.name); 9306 } 9307 9308 // writer 9309 synchronized (mPackages) { 9310 mPackages.remove(ps.name); 9311 final PackageParser.Package pkg = ps.pkg; 9312 if (pkg != null) { 9313 cleanPackageDataStructuresLILPw(pkg, chatty); 9314 } 9315 } 9316 } 9317 9318 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9319 if (DEBUG_INSTALL) { 9320 if (chatty) 9321 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9322 } 9323 9324 // writer 9325 synchronized (mPackages) { 9326 // Remove the parent package 9327 mPackages.remove(pkg.applicationInfo.packageName); 9328 cleanPackageDataStructuresLILPw(pkg, chatty); 9329 9330 // Remove the child packages 9331 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9332 for (int i = 0; i < childCount; i++) { 9333 PackageParser.Package childPkg = pkg.childPackages.get(i); 9334 mPackages.remove(childPkg.applicationInfo.packageName); 9335 cleanPackageDataStructuresLILPw(childPkg, chatty); 9336 } 9337 } 9338 } 9339 9340 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9341 int N = pkg.providers.size(); 9342 StringBuilder r = null; 9343 int i; 9344 for (i=0; i<N; i++) { 9345 PackageParser.Provider p = pkg.providers.get(i); 9346 mProviders.removeProvider(p); 9347 if (p.info.authority == null) { 9348 9349 /* There was another ContentProvider with this authority when 9350 * this app was installed so this authority is null, 9351 * Ignore it as we don't have to unregister the provider. 9352 */ 9353 continue; 9354 } 9355 String names[] = p.info.authority.split(";"); 9356 for (int j = 0; j < names.length; j++) { 9357 if (mProvidersByAuthority.get(names[j]) == p) { 9358 mProvidersByAuthority.remove(names[j]); 9359 if (DEBUG_REMOVE) { 9360 if (chatty) 9361 Log.d(TAG, "Unregistered content provider: " + names[j] 9362 + ", className = " + p.info.name + ", isSyncable = " 9363 + p.info.isSyncable); 9364 } 9365 } 9366 } 9367 if (DEBUG_REMOVE && chatty) { 9368 if (r == null) { 9369 r = new StringBuilder(256); 9370 } else { 9371 r.append(' '); 9372 } 9373 r.append(p.info.name); 9374 } 9375 } 9376 if (r != null) { 9377 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9378 } 9379 9380 N = pkg.services.size(); 9381 r = null; 9382 for (i=0; i<N; i++) { 9383 PackageParser.Service s = pkg.services.get(i); 9384 mServices.removeService(s); 9385 if (chatty) { 9386 if (r == null) { 9387 r = new StringBuilder(256); 9388 } else { 9389 r.append(' '); 9390 } 9391 r.append(s.info.name); 9392 } 9393 } 9394 if (r != null) { 9395 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9396 } 9397 9398 N = pkg.receivers.size(); 9399 r = null; 9400 for (i=0; i<N; i++) { 9401 PackageParser.Activity a = pkg.receivers.get(i); 9402 mReceivers.removeActivity(a, "receiver"); 9403 if (DEBUG_REMOVE && chatty) { 9404 if (r == null) { 9405 r = new StringBuilder(256); 9406 } else { 9407 r.append(' '); 9408 } 9409 r.append(a.info.name); 9410 } 9411 } 9412 if (r != null) { 9413 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9414 } 9415 9416 N = pkg.activities.size(); 9417 r = null; 9418 for (i=0; i<N; i++) { 9419 PackageParser.Activity a = pkg.activities.get(i); 9420 mActivities.removeActivity(a, "activity"); 9421 if (DEBUG_REMOVE && chatty) { 9422 if (r == null) { 9423 r = new StringBuilder(256); 9424 } else { 9425 r.append(' '); 9426 } 9427 r.append(a.info.name); 9428 } 9429 } 9430 if (r != null) { 9431 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9432 } 9433 9434 N = pkg.permissions.size(); 9435 r = null; 9436 for (i=0; i<N; i++) { 9437 PackageParser.Permission p = pkg.permissions.get(i); 9438 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9439 if (bp == null) { 9440 bp = mSettings.mPermissionTrees.get(p.info.name); 9441 } 9442 if (bp != null && bp.perm == p) { 9443 bp.perm = null; 9444 if (DEBUG_REMOVE && chatty) { 9445 if (r == null) { 9446 r = new StringBuilder(256); 9447 } else { 9448 r.append(' '); 9449 } 9450 r.append(p.info.name); 9451 } 9452 } 9453 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9454 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9455 if (appOpPkgs != null) { 9456 appOpPkgs.remove(pkg.packageName); 9457 } 9458 } 9459 } 9460 if (r != null) { 9461 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9462 } 9463 9464 N = pkg.requestedPermissions.size(); 9465 r = null; 9466 for (i=0; i<N; i++) { 9467 String perm = pkg.requestedPermissions.get(i); 9468 BasePermission bp = mSettings.mPermissions.get(perm); 9469 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9470 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9471 if (appOpPkgs != null) { 9472 appOpPkgs.remove(pkg.packageName); 9473 if (appOpPkgs.isEmpty()) { 9474 mAppOpPermissionPackages.remove(perm); 9475 } 9476 } 9477 } 9478 } 9479 if (r != null) { 9480 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9481 } 9482 9483 N = pkg.instrumentation.size(); 9484 r = null; 9485 for (i=0; i<N; i++) { 9486 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9487 mInstrumentation.remove(a.getComponentName()); 9488 if (DEBUG_REMOVE && chatty) { 9489 if (r == null) { 9490 r = new StringBuilder(256); 9491 } else { 9492 r.append(' '); 9493 } 9494 r.append(a.info.name); 9495 } 9496 } 9497 if (r != null) { 9498 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9499 } 9500 9501 r = null; 9502 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9503 // Only system apps can hold shared libraries. 9504 if (pkg.libraryNames != null) { 9505 for (i=0; i<pkg.libraryNames.size(); i++) { 9506 String name = pkg.libraryNames.get(i); 9507 SharedLibraryEntry cur = mSharedLibraries.get(name); 9508 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9509 mSharedLibraries.remove(name); 9510 if (DEBUG_REMOVE && chatty) { 9511 if (r == null) { 9512 r = new StringBuilder(256); 9513 } else { 9514 r.append(' '); 9515 } 9516 r.append(name); 9517 } 9518 } 9519 } 9520 } 9521 } 9522 if (r != null) { 9523 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9524 } 9525 } 9526 9527 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9528 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9529 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9530 return true; 9531 } 9532 } 9533 return false; 9534 } 9535 9536 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9537 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9538 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9539 9540 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9541 // Update the parent permissions 9542 updatePermissionsLPw(pkg.packageName, pkg, flags); 9543 // Update the child permissions 9544 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9545 for (int i = 0; i < childCount; i++) { 9546 PackageParser.Package childPkg = pkg.childPackages.get(i); 9547 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9548 } 9549 } 9550 9551 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9552 int flags) { 9553 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9554 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9555 } 9556 9557 private void updatePermissionsLPw(String changingPkg, 9558 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9559 // Make sure there are no dangling permission trees. 9560 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9561 while (it.hasNext()) { 9562 final BasePermission bp = it.next(); 9563 if (bp.packageSetting == null) { 9564 // We may not yet have parsed the package, so just see if 9565 // we still know about its settings. 9566 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9567 } 9568 if (bp.packageSetting == null) { 9569 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9570 + " from package " + bp.sourcePackage); 9571 it.remove(); 9572 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9573 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9574 Slog.i(TAG, "Removing old permission tree: " + bp.name 9575 + " from package " + bp.sourcePackage); 9576 flags |= UPDATE_PERMISSIONS_ALL; 9577 it.remove(); 9578 } 9579 } 9580 } 9581 9582 // Make sure all dynamic permissions have been assigned to a package, 9583 // and make sure there are no dangling permissions. 9584 it = mSettings.mPermissions.values().iterator(); 9585 while (it.hasNext()) { 9586 final BasePermission bp = it.next(); 9587 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9588 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9589 + bp.name + " pkg=" + bp.sourcePackage 9590 + " info=" + bp.pendingInfo); 9591 if (bp.packageSetting == null && bp.pendingInfo != null) { 9592 final BasePermission tree = findPermissionTreeLP(bp.name); 9593 if (tree != null && tree.perm != null) { 9594 bp.packageSetting = tree.packageSetting; 9595 bp.perm = new PackageParser.Permission(tree.perm.owner, 9596 new PermissionInfo(bp.pendingInfo)); 9597 bp.perm.info.packageName = tree.perm.info.packageName; 9598 bp.perm.info.name = bp.name; 9599 bp.uid = tree.uid; 9600 } 9601 } 9602 } 9603 if (bp.packageSetting == null) { 9604 // We may not yet have parsed the package, so just see if 9605 // we still know about its settings. 9606 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9607 } 9608 if (bp.packageSetting == null) { 9609 Slog.w(TAG, "Removing dangling permission: " + bp.name 9610 + " from package " + bp.sourcePackage); 9611 it.remove(); 9612 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9613 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9614 Slog.i(TAG, "Removing old permission: " + bp.name 9615 + " from package " + bp.sourcePackage); 9616 flags |= UPDATE_PERMISSIONS_ALL; 9617 it.remove(); 9618 } 9619 } 9620 } 9621 9622 // Now update the permissions for all packages, in particular 9623 // replace the granted permissions of the system packages. 9624 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9625 for (PackageParser.Package pkg : mPackages.values()) { 9626 if (pkg != pkgInfo) { 9627 // Only replace for packages on requested volume 9628 final String volumeUuid = getVolumeUuidForPackage(pkg); 9629 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9630 && Objects.equals(replaceVolumeUuid, volumeUuid); 9631 grantPermissionsLPw(pkg, replace, changingPkg); 9632 } 9633 } 9634 } 9635 9636 if (pkgInfo != null) { 9637 // Only replace for packages on requested volume 9638 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9639 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9640 && Objects.equals(replaceVolumeUuid, volumeUuid); 9641 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9642 } 9643 } 9644 9645 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9646 String packageOfInterest) { 9647 // IMPORTANT: There are two types of permissions: install and runtime. 9648 // Install time permissions are granted when the app is installed to 9649 // all device users and users added in the future. Runtime permissions 9650 // are granted at runtime explicitly to specific users. Normal and signature 9651 // protected permissions are install time permissions. Dangerous permissions 9652 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9653 // otherwise they are runtime permissions. This function does not manage 9654 // runtime permissions except for the case an app targeting Lollipop MR1 9655 // being upgraded to target a newer SDK, in which case dangerous permissions 9656 // are transformed from install time to runtime ones. 9657 9658 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9659 if (ps == null) { 9660 return; 9661 } 9662 9663 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9664 9665 PermissionsState permissionsState = ps.getPermissionsState(); 9666 PermissionsState origPermissions = permissionsState; 9667 9668 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9669 9670 boolean runtimePermissionsRevoked = false; 9671 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9672 9673 boolean changedInstallPermission = false; 9674 9675 if (replace) { 9676 ps.installPermissionsFixed = false; 9677 if (!ps.isSharedUser()) { 9678 origPermissions = new PermissionsState(permissionsState); 9679 permissionsState.reset(); 9680 } else { 9681 // We need to know only about runtime permission changes since the 9682 // calling code always writes the install permissions state but 9683 // the runtime ones are written only if changed. The only cases of 9684 // changed runtime permissions here are promotion of an install to 9685 // runtime and revocation of a runtime from a shared user. 9686 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9687 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9688 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9689 runtimePermissionsRevoked = true; 9690 } 9691 } 9692 } 9693 9694 permissionsState.setGlobalGids(mGlobalGids); 9695 9696 final int N = pkg.requestedPermissions.size(); 9697 for (int i=0; i<N; i++) { 9698 final String name = pkg.requestedPermissions.get(i); 9699 final BasePermission bp = mSettings.mPermissions.get(name); 9700 9701 if (DEBUG_INSTALL) { 9702 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9703 } 9704 9705 if (bp == null || bp.packageSetting == null) { 9706 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9707 Slog.w(TAG, "Unknown permission " + name 9708 + " in package " + pkg.packageName); 9709 } 9710 continue; 9711 } 9712 9713 final String perm = bp.name; 9714 boolean allowedSig = false; 9715 int grant = GRANT_DENIED; 9716 9717 // Keep track of app op permissions. 9718 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9719 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9720 if (pkgs == null) { 9721 pkgs = new ArraySet<>(); 9722 mAppOpPermissionPackages.put(bp.name, pkgs); 9723 } 9724 pkgs.add(pkg.packageName); 9725 } 9726 9727 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9728 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9729 >= Build.VERSION_CODES.M; 9730 switch (level) { 9731 case PermissionInfo.PROTECTION_NORMAL: { 9732 // For all apps normal permissions are install time ones. 9733 grant = GRANT_INSTALL; 9734 } break; 9735 9736 case PermissionInfo.PROTECTION_DANGEROUS: { 9737 // If a permission review is required for legacy apps we represent 9738 // their permissions as always granted runtime ones since we need 9739 // to keep the review required permission flag per user while an 9740 // install permission's state is shared across all users. 9741 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9742 // For legacy apps dangerous permissions are install time ones. 9743 grant = GRANT_INSTALL; 9744 } else if (origPermissions.hasInstallPermission(bp.name)) { 9745 // For legacy apps that became modern, install becomes runtime. 9746 grant = GRANT_UPGRADE; 9747 } else if (mPromoteSystemApps 9748 && isSystemApp(ps) 9749 && mExistingSystemPackages.contains(ps.name)) { 9750 // For legacy system apps, install becomes runtime. 9751 // We cannot check hasInstallPermission() for system apps since those 9752 // permissions were granted implicitly and not persisted pre-M. 9753 grant = GRANT_UPGRADE; 9754 } else { 9755 // For modern apps keep runtime permissions unchanged. 9756 grant = GRANT_RUNTIME; 9757 } 9758 } break; 9759 9760 case PermissionInfo.PROTECTION_SIGNATURE: { 9761 // For all apps signature permissions are install time ones. 9762 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9763 if (allowedSig) { 9764 grant = GRANT_INSTALL; 9765 } 9766 } break; 9767 } 9768 9769 if (DEBUG_INSTALL) { 9770 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9771 } 9772 9773 if (grant != GRANT_DENIED) { 9774 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9775 // If this is an existing, non-system package, then 9776 // we can't add any new permissions to it. 9777 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9778 // Except... if this is a permission that was added 9779 // to the platform (note: need to only do this when 9780 // updating the platform). 9781 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9782 grant = GRANT_DENIED; 9783 } 9784 } 9785 } 9786 9787 switch (grant) { 9788 case GRANT_INSTALL: { 9789 // Revoke this as runtime permission to handle the case of 9790 // a runtime permission being downgraded to an install one. 9791 // Also in permission review mode we keep dangerous permissions 9792 // for legacy apps 9793 for (int userId : UserManagerService.getInstance().getUserIds()) { 9794 if (origPermissions.getRuntimePermissionState( 9795 bp.name, userId) != null) { 9796 // Revoke the runtime permission and clear the flags. 9797 origPermissions.revokeRuntimePermission(bp, userId); 9798 origPermissions.updatePermissionFlags(bp, userId, 9799 PackageManager.MASK_PERMISSION_FLAGS, 0); 9800 // If we revoked a permission permission, we have to write. 9801 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9802 changedRuntimePermissionUserIds, userId); 9803 } 9804 } 9805 // Grant an install permission. 9806 if (permissionsState.grantInstallPermission(bp) != 9807 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9808 changedInstallPermission = true; 9809 } 9810 } break; 9811 9812 case GRANT_RUNTIME: { 9813 // Grant previously granted runtime permissions. 9814 for (int userId : UserManagerService.getInstance().getUserIds()) { 9815 PermissionState permissionState = origPermissions 9816 .getRuntimePermissionState(bp.name, userId); 9817 int flags = permissionState != null 9818 ? permissionState.getFlags() : 0; 9819 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9820 if (permissionsState.grantRuntimePermission(bp, userId) == 9821 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9822 // If we cannot put the permission as it was, we have to write. 9823 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9824 changedRuntimePermissionUserIds, userId); 9825 } 9826 // If the app supports runtime permissions no need for a review. 9827 if (Build.PERMISSIONS_REVIEW_REQUIRED 9828 && appSupportsRuntimePermissions 9829 && (flags & PackageManager 9830 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9831 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9832 // Since we changed the flags, we have to write. 9833 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9834 changedRuntimePermissionUserIds, userId); 9835 } 9836 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9837 && !appSupportsRuntimePermissions) { 9838 // For legacy apps that need a permission review, every new 9839 // runtime permission is granted but it is pending a review. 9840 // We also need to review only platform defined runtime 9841 // permissions as these are the only ones the platform knows 9842 // how to disable the API to simulate revocation as legacy 9843 // apps don't expect to run with revoked permissions. 9844 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9845 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9846 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9847 // We changed the flags, hence have to write. 9848 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9849 changedRuntimePermissionUserIds, userId); 9850 } 9851 } 9852 if (permissionsState.grantRuntimePermission(bp, userId) 9853 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9854 // We changed the permission, hence have to write. 9855 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9856 changedRuntimePermissionUserIds, userId); 9857 } 9858 } 9859 // Propagate the permission flags. 9860 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9861 } 9862 } break; 9863 9864 case GRANT_UPGRADE: { 9865 // Grant runtime permissions for a previously held install permission. 9866 PermissionState permissionState = origPermissions 9867 .getInstallPermissionState(bp.name); 9868 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9869 9870 if (origPermissions.revokeInstallPermission(bp) 9871 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9872 // We will be transferring the permission flags, so clear them. 9873 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9874 PackageManager.MASK_PERMISSION_FLAGS, 0); 9875 changedInstallPermission = true; 9876 } 9877 9878 // If the permission is not to be promoted to runtime we ignore it and 9879 // also its other flags as they are not applicable to install permissions. 9880 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9881 for (int userId : currentUserIds) { 9882 if (permissionsState.grantRuntimePermission(bp, userId) != 9883 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9884 // Transfer the permission flags. 9885 permissionsState.updatePermissionFlags(bp, userId, 9886 flags, flags); 9887 // If we granted the permission, we have to write. 9888 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9889 changedRuntimePermissionUserIds, userId); 9890 } 9891 } 9892 } 9893 } break; 9894 9895 default: { 9896 if (packageOfInterest == null 9897 || packageOfInterest.equals(pkg.packageName)) { 9898 Slog.w(TAG, "Not granting permission " + perm 9899 + " to package " + pkg.packageName 9900 + " because it was previously installed without"); 9901 } 9902 } break; 9903 } 9904 } else { 9905 if (permissionsState.revokeInstallPermission(bp) != 9906 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9907 // Also drop the permission flags. 9908 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9909 PackageManager.MASK_PERMISSION_FLAGS, 0); 9910 changedInstallPermission = true; 9911 Slog.i(TAG, "Un-granting permission " + perm 9912 + " from package " + pkg.packageName 9913 + " (protectionLevel=" + bp.protectionLevel 9914 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9915 + ")"); 9916 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9917 // Don't print warning for app op permissions, since it is fine for them 9918 // not to be granted, there is a UI for the user to decide. 9919 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9920 Slog.w(TAG, "Not granting permission " + perm 9921 + " to package " + pkg.packageName 9922 + " (protectionLevel=" + bp.protectionLevel 9923 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9924 + ")"); 9925 } 9926 } 9927 } 9928 } 9929 9930 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9931 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9932 // This is the first that we have heard about this package, so the 9933 // permissions we have now selected are fixed until explicitly 9934 // changed. 9935 ps.installPermissionsFixed = true; 9936 } 9937 9938 // Persist the runtime permissions state for users with changes. If permissions 9939 // were revoked because no app in the shared user declares them we have to 9940 // write synchronously to avoid losing runtime permissions state. 9941 for (int userId : changedRuntimePermissionUserIds) { 9942 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9943 } 9944 9945 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9946 } 9947 9948 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9949 boolean allowed = false; 9950 final int NP = PackageParser.NEW_PERMISSIONS.length; 9951 for (int ip=0; ip<NP; ip++) { 9952 final PackageParser.NewPermissionInfo npi 9953 = PackageParser.NEW_PERMISSIONS[ip]; 9954 if (npi.name.equals(perm) 9955 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9956 allowed = true; 9957 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9958 + pkg.packageName); 9959 break; 9960 } 9961 } 9962 return allowed; 9963 } 9964 9965 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9966 BasePermission bp, PermissionsState origPermissions) { 9967 boolean allowed; 9968 allowed = (compareSignatures( 9969 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9970 == PackageManager.SIGNATURE_MATCH) 9971 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9972 == PackageManager.SIGNATURE_MATCH); 9973 if (!allowed && (bp.protectionLevel 9974 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9975 if (isSystemApp(pkg)) { 9976 // For updated system applications, a system permission 9977 // is granted only if it had been defined by the original application. 9978 if (pkg.isUpdatedSystemApp()) { 9979 final PackageSetting sysPs = mSettings 9980 .getDisabledSystemPkgLPr(pkg.packageName); 9981 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9982 // If the original was granted this permission, we take 9983 // that grant decision as read and propagate it to the 9984 // update. 9985 if (sysPs.isPrivileged()) { 9986 allowed = true; 9987 } 9988 } else { 9989 // The system apk may have been updated with an older 9990 // version of the one on the data partition, but which 9991 // granted a new system permission that it didn't have 9992 // before. In this case we do want to allow the app to 9993 // now get the new permission if the ancestral apk is 9994 // privileged to get it. 9995 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9996 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9997 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9998 allowed = true; 9999 break; 10000 } 10001 } 10002 } 10003 // Also if a privileged parent package on the system image or any of 10004 // its children requested a privileged permission, the updated child 10005 // packages can also get the permission. 10006 if (pkg.parentPackage != null) { 10007 final PackageSetting disabledSysParentPs = mSettings 10008 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10009 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10010 && disabledSysParentPs.isPrivileged()) { 10011 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10012 allowed = true; 10013 } else if (disabledSysParentPs.pkg.childPackages != null) { 10014 final int count = disabledSysParentPs.pkg.childPackages.size(); 10015 for (int i = 0; i < count; i++) { 10016 PackageParser.Package disabledSysChildPkg = 10017 disabledSysParentPs.pkg.childPackages.get(i); 10018 if (isPackageRequestingPermission(disabledSysChildPkg, 10019 perm)) { 10020 allowed = true; 10021 break; 10022 } 10023 } 10024 } 10025 } 10026 } 10027 } 10028 } else { 10029 allowed = isPrivilegedApp(pkg); 10030 } 10031 } 10032 } 10033 if (!allowed) { 10034 if (!allowed && (bp.protectionLevel 10035 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10036 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10037 // If this was a previously normal/dangerous permission that got moved 10038 // to a system permission as part of the runtime permission redesign, then 10039 // we still want to blindly grant it to old apps. 10040 allowed = true; 10041 } 10042 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10043 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10044 // If this permission is to be granted to the system installer and 10045 // this app is an installer, then it gets the permission. 10046 allowed = true; 10047 } 10048 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10049 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10050 // If this permission is to be granted to the system verifier and 10051 // this app is a verifier, then it gets the permission. 10052 allowed = true; 10053 } 10054 if (!allowed && (bp.protectionLevel 10055 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10056 && isSystemApp(pkg)) { 10057 // Any pre-installed system app is allowed to get this permission. 10058 allowed = true; 10059 } 10060 if (!allowed && (bp.protectionLevel 10061 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10062 // For development permissions, a development permission 10063 // is granted only if it was already granted. 10064 allowed = origPermissions.hasInstallPermission(perm); 10065 } 10066 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10067 && pkg.packageName.equals(mSetupWizardPackage)) { 10068 // If this permission is to be granted to the system setup wizard and 10069 // this app is a setup wizard, then it gets the permission. 10070 allowed = true; 10071 } 10072 } 10073 return allowed; 10074 } 10075 10076 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10077 final int permCount = pkg.requestedPermissions.size(); 10078 for (int j = 0; j < permCount; j++) { 10079 String requestedPermission = pkg.requestedPermissions.get(j); 10080 if (permission.equals(requestedPermission)) { 10081 return true; 10082 } 10083 } 10084 return false; 10085 } 10086 10087 final class ActivityIntentResolver 10088 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10089 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10090 boolean defaultOnly, int userId) { 10091 if (!sUserManager.exists(userId)) return null; 10092 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10093 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10094 } 10095 10096 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10097 int userId) { 10098 if (!sUserManager.exists(userId)) return null; 10099 mFlags = flags; 10100 return super.queryIntent(intent, resolvedType, 10101 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10102 } 10103 10104 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10105 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10106 if (!sUserManager.exists(userId)) return null; 10107 if (packageActivities == null) { 10108 return null; 10109 } 10110 mFlags = flags; 10111 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10112 final int N = packageActivities.size(); 10113 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10114 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10115 10116 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10117 for (int i = 0; i < N; ++i) { 10118 intentFilters = packageActivities.get(i).intents; 10119 if (intentFilters != null && intentFilters.size() > 0) { 10120 PackageParser.ActivityIntentInfo[] array = 10121 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10122 intentFilters.toArray(array); 10123 listCut.add(array); 10124 } 10125 } 10126 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10127 } 10128 10129 /** 10130 * Finds a privileged activity that matches the specified activity names. 10131 */ 10132 private PackageParser.Activity findMatchingActivity( 10133 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10134 for (PackageParser.Activity sysActivity : activityList) { 10135 if (sysActivity.info.name.equals(activityInfo.name)) { 10136 return sysActivity; 10137 } 10138 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10139 return sysActivity; 10140 } 10141 if (sysActivity.info.targetActivity != null) { 10142 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10143 return sysActivity; 10144 } 10145 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10146 return sysActivity; 10147 } 10148 } 10149 } 10150 return null; 10151 } 10152 10153 public class IterGenerator<E> { 10154 public Iterator<E> generate(ActivityIntentInfo info) { 10155 return null; 10156 } 10157 } 10158 10159 public class ActionIterGenerator extends IterGenerator<String> { 10160 @Override 10161 public Iterator<String> generate(ActivityIntentInfo info) { 10162 return info.actionsIterator(); 10163 } 10164 } 10165 10166 public class CategoriesIterGenerator extends IterGenerator<String> { 10167 @Override 10168 public Iterator<String> generate(ActivityIntentInfo info) { 10169 return info.categoriesIterator(); 10170 } 10171 } 10172 10173 public class SchemesIterGenerator extends IterGenerator<String> { 10174 @Override 10175 public Iterator<String> generate(ActivityIntentInfo info) { 10176 return info.schemesIterator(); 10177 } 10178 } 10179 10180 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10181 @Override 10182 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10183 return info.authoritiesIterator(); 10184 } 10185 } 10186 10187 /** 10188 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10189 * MODIFIED. Do not pass in a list that should not be changed. 10190 */ 10191 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10192 IterGenerator<T> generator, Iterator<T> searchIterator) { 10193 // loop through the set of actions; every one must be found in the intent filter 10194 while (searchIterator.hasNext()) { 10195 // we must have at least one filter in the list to consider a match 10196 if (intentList.size() == 0) { 10197 break; 10198 } 10199 10200 final T searchAction = searchIterator.next(); 10201 10202 // loop through the set of intent filters 10203 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10204 while (intentIter.hasNext()) { 10205 final ActivityIntentInfo intentInfo = intentIter.next(); 10206 boolean selectionFound = false; 10207 10208 // loop through the intent filter's selection criteria; at least one 10209 // of them must match the searched criteria 10210 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10211 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10212 final T intentSelection = intentSelectionIter.next(); 10213 if (intentSelection != null && intentSelection.equals(searchAction)) { 10214 selectionFound = true; 10215 break; 10216 } 10217 } 10218 10219 // the selection criteria wasn't found in this filter's set; this filter 10220 // is not a potential match 10221 if (!selectionFound) { 10222 intentIter.remove(); 10223 } 10224 } 10225 } 10226 } 10227 10228 private boolean isProtectedAction(ActivityIntentInfo filter) { 10229 final Iterator<String> actionsIter = filter.actionsIterator(); 10230 while (actionsIter != null && actionsIter.hasNext()) { 10231 final String filterAction = actionsIter.next(); 10232 if (PROTECTED_ACTIONS.contains(filterAction)) { 10233 return true; 10234 } 10235 } 10236 return false; 10237 } 10238 10239 /** 10240 * Adjusts the priority of the given intent filter according to policy. 10241 * <p> 10242 * <ul> 10243 * <li>The priority for non privileged applications is capped to '0'</li> 10244 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10245 * <li>The priority for unbundled updates to privileged applications is capped to the 10246 * priority defined on the system partition</li> 10247 * </ul> 10248 * <p> 10249 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10250 * allowed to obtain any priority on any action. 10251 */ 10252 private void adjustPriority( 10253 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10254 // nothing to do; priority is fine as-is 10255 if (intent.getPriority() <= 0) { 10256 return; 10257 } 10258 10259 final ActivityInfo activityInfo = intent.activity.info; 10260 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10261 10262 final boolean privilegedApp = 10263 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10264 if (!privilegedApp) { 10265 // non-privileged applications can never define a priority >0 10266 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10267 + " package: " + applicationInfo.packageName 10268 + " activity: " + intent.activity.className 10269 + " origPrio: " + intent.getPriority()); 10270 intent.setPriority(0); 10271 return; 10272 } 10273 10274 if (systemActivities == null) { 10275 // the system package is not disabled; we're parsing the system partition 10276 if (isProtectedAction(intent)) { 10277 if (mDeferProtectedFilters) { 10278 // We can't deal with these just yet. No component should ever obtain a 10279 // >0 priority for a protected actions, with ONE exception -- the setup 10280 // wizard. The setup wizard, however, cannot be known until we're able to 10281 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10282 // until all intent filters have been processed. Chicken, meet egg. 10283 // Let the filter temporarily have a high priority and rectify the 10284 // priorities after all system packages have been scanned. 10285 mProtectedFilters.add(intent); 10286 if (DEBUG_FILTERS) { 10287 Slog.i(TAG, "Protected action; save for later;" 10288 + " package: " + applicationInfo.packageName 10289 + " activity: " + intent.activity.className 10290 + " origPrio: " + intent.getPriority()); 10291 } 10292 return; 10293 } else { 10294 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10295 Slog.i(TAG, "No setup wizard;" 10296 + " All protected intents capped to priority 0"); 10297 } 10298 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10299 if (DEBUG_FILTERS) { 10300 Slog.i(TAG, "Found setup wizard;" 10301 + " allow priority " + intent.getPriority() + ";" 10302 + " package: " + intent.activity.info.packageName 10303 + " activity: " + intent.activity.className 10304 + " priority: " + intent.getPriority()); 10305 } 10306 // setup wizard gets whatever it wants 10307 return; 10308 } 10309 Slog.w(TAG, "Protected action; cap priority to 0;" 10310 + " package: " + intent.activity.info.packageName 10311 + " activity: " + intent.activity.className 10312 + " origPrio: " + intent.getPriority()); 10313 intent.setPriority(0); 10314 return; 10315 } 10316 } 10317 // privileged apps on the system image get whatever priority they request 10318 return; 10319 } 10320 10321 // privileged app unbundled update ... try to find the same activity 10322 final PackageParser.Activity foundActivity = 10323 findMatchingActivity(systemActivities, activityInfo); 10324 if (foundActivity == null) { 10325 // this is a new activity; it cannot obtain >0 priority 10326 if (DEBUG_FILTERS) { 10327 Slog.i(TAG, "New activity; cap priority to 0;" 10328 + " package: " + applicationInfo.packageName 10329 + " activity: " + intent.activity.className 10330 + " origPrio: " + intent.getPriority()); 10331 } 10332 intent.setPriority(0); 10333 return; 10334 } 10335 10336 // found activity, now check for filter equivalence 10337 10338 // a shallow copy is enough; we modify the list, not its contents 10339 final List<ActivityIntentInfo> intentListCopy = 10340 new ArrayList<>(foundActivity.intents); 10341 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10342 10343 // find matching action subsets 10344 final Iterator<String> actionsIterator = intent.actionsIterator(); 10345 if (actionsIterator != null) { 10346 getIntentListSubset( 10347 intentListCopy, new ActionIterGenerator(), actionsIterator); 10348 if (intentListCopy.size() == 0) { 10349 // no more intents to match; we're not equivalent 10350 if (DEBUG_FILTERS) { 10351 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10352 + " package: " + applicationInfo.packageName 10353 + " activity: " + intent.activity.className 10354 + " origPrio: " + intent.getPriority()); 10355 } 10356 intent.setPriority(0); 10357 return; 10358 } 10359 } 10360 10361 // find matching category subsets 10362 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10363 if (categoriesIterator != null) { 10364 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10365 categoriesIterator); 10366 if (intentListCopy.size() == 0) { 10367 // no more intents to match; we're not equivalent 10368 if (DEBUG_FILTERS) { 10369 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10370 + " package: " + applicationInfo.packageName 10371 + " activity: " + intent.activity.className 10372 + " origPrio: " + intent.getPriority()); 10373 } 10374 intent.setPriority(0); 10375 return; 10376 } 10377 } 10378 10379 // find matching schemes subsets 10380 final Iterator<String> schemesIterator = intent.schemesIterator(); 10381 if (schemesIterator != null) { 10382 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10383 schemesIterator); 10384 if (intentListCopy.size() == 0) { 10385 // no more intents to match; we're not equivalent 10386 if (DEBUG_FILTERS) { 10387 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10388 + " package: " + applicationInfo.packageName 10389 + " activity: " + intent.activity.className 10390 + " origPrio: " + intent.getPriority()); 10391 } 10392 intent.setPriority(0); 10393 return; 10394 } 10395 } 10396 10397 // find matching authorities subsets 10398 final Iterator<IntentFilter.AuthorityEntry> 10399 authoritiesIterator = intent.authoritiesIterator(); 10400 if (authoritiesIterator != null) { 10401 getIntentListSubset(intentListCopy, 10402 new AuthoritiesIterGenerator(), 10403 authoritiesIterator); 10404 if (intentListCopy.size() == 0) { 10405 // no more intents to match; we're not equivalent 10406 if (DEBUG_FILTERS) { 10407 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10408 + " package: " + applicationInfo.packageName 10409 + " activity: " + intent.activity.className 10410 + " origPrio: " + intent.getPriority()); 10411 } 10412 intent.setPriority(0); 10413 return; 10414 } 10415 } 10416 10417 // we found matching filter(s); app gets the max priority of all intents 10418 int cappedPriority = 0; 10419 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10420 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10421 } 10422 if (intent.getPriority() > cappedPriority) { 10423 if (DEBUG_FILTERS) { 10424 Slog.i(TAG, "Found matching filter(s);" 10425 + " cap priority to " + cappedPriority + ";" 10426 + " package: " + applicationInfo.packageName 10427 + " activity: " + intent.activity.className 10428 + " origPrio: " + intent.getPriority()); 10429 } 10430 intent.setPriority(cappedPriority); 10431 return; 10432 } 10433 // all this for nothing; the requested priority was <= what was on the system 10434 } 10435 10436 public final void addActivity(PackageParser.Activity a, String type) { 10437 mActivities.put(a.getComponentName(), a); 10438 if (DEBUG_SHOW_INFO) 10439 Log.v( 10440 TAG, " " + type + " " + 10441 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10442 if (DEBUG_SHOW_INFO) 10443 Log.v(TAG, " Class=" + a.info.name); 10444 final int NI = a.intents.size(); 10445 for (int j=0; j<NI; j++) { 10446 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10447 if ("activity".equals(type)) { 10448 final PackageSetting ps = 10449 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10450 final List<PackageParser.Activity> systemActivities = 10451 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10452 adjustPriority(systemActivities, intent); 10453 } 10454 if (DEBUG_SHOW_INFO) { 10455 Log.v(TAG, " IntentFilter:"); 10456 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10457 } 10458 if (!intent.debugCheck()) { 10459 Log.w(TAG, "==> For Activity " + a.info.name); 10460 } 10461 addFilter(intent); 10462 } 10463 } 10464 10465 public final void removeActivity(PackageParser.Activity a, String type) { 10466 mActivities.remove(a.getComponentName()); 10467 if (DEBUG_SHOW_INFO) { 10468 Log.v(TAG, " " + type + " " 10469 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10470 : a.info.name) + ":"); 10471 Log.v(TAG, " Class=" + a.info.name); 10472 } 10473 final int NI = a.intents.size(); 10474 for (int j=0; j<NI; j++) { 10475 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10476 if (DEBUG_SHOW_INFO) { 10477 Log.v(TAG, " IntentFilter:"); 10478 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10479 } 10480 removeFilter(intent); 10481 } 10482 } 10483 10484 @Override 10485 protected boolean allowFilterResult( 10486 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10487 ActivityInfo filterAi = filter.activity.info; 10488 for (int i=dest.size()-1; i>=0; i--) { 10489 ActivityInfo destAi = dest.get(i).activityInfo; 10490 if (destAi.name == filterAi.name 10491 && destAi.packageName == filterAi.packageName) { 10492 return false; 10493 } 10494 } 10495 return true; 10496 } 10497 10498 @Override 10499 protected ActivityIntentInfo[] newArray(int size) { 10500 return new ActivityIntentInfo[size]; 10501 } 10502 10503 @Override 10504 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10505 if (!sUserManager.exists(userId)) return true; 10506 PackageParser.Package p = filter.activity.owner; 10507 if (p != null) { 10508 PackageSetting ps = (PackageSetting)p.mExtras; 10509 if (ps != null) { 10510 // System apps are never considered stopped for purposes of 10511 // filtering, because there may be no way for the user to 10512 // actually re-launch them. 10513 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10514 && ps.getStopped(userId); 10515 } 10516 } 10517 return false; 10518 } 10519 10520 @Override 10521 protected boolean isPackageForFilter(String packageName, 10522 PackageParser.ActivityIntentInfo info) { 10523 return packageName.equals(info.activity.owner.packageName); 10524 } 10525 10526 @Override 10527 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10528 int match, int userId) { 10529 if (!sUserManager.exists(userId)) return null; 10530 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10531 return null; 10532 } 10533 final PackageParser.Activity activity = info.activity; 10534 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10535 if (ps == null) { 10536 return null; 10537 } 10538 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10539 ps.readUserState(userId), userId); 10540 if (ai == null) { 10541 return null; 10542 } 10543 final ResolveInfo res = new ResolveInfo(); 10544 res.activityInfo = ai; 10545 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10546 res.filter = info; 10547 } 10548 if (info != null) { 10549 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10550 } 10551 res.priority = info.getPriority(); 10552 res.preferredOrder = activity.owner.mPreferredOrder; 10553 //System.out.println("Result: " + res.activityInfo.className + 10554 // " = " + res.priority); 10555 res.match = match; 10556 res.isDefault = info.hasDefault; 10557 res.labelRes = info.labelRes; 10558 res.nonLocalizedLabel = info.nonLocalizedLabel; 10559 if (userNeedsBadging(userId)) { 10560 res.noResourceId = true; 10561 } else { 10562 res.icon = info.icon; 10563 } 10564 res.iconResourceId = info.icon; 10565 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10566 return res; 10567 } 10568 10569 @Override 10570 protected void sortResults(List<ResolveInfo> results) { 10571 Collections.sort(results, mResolvePrioritySorter); 10572 } 10573 10574 @Override 10575 protected void dumpFilter(PrintWriter out, String prefix, 10576 PackageParser.ActivityIntentInfo filter) { 10577 out.print(prefix); out.print( 10578 Integer.toHexString(System.identityHashCode(filter.activity))); 10579 out.print(' '); 10580 filter.activity.printComponentShortName(out); 10581 out.print(" filter "); 10582 out.println(Integer.toHexString(System.identityHashCode(filter))); 10583 } 10584 10585 @Override 10586 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10587 return filter.activity; 10588 } 10589 10590 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10591 PackageParser.Activity activity = (PackageParser.Activity)label; 10592 out.print(prefix); out.print( 10593 Integer.toHexString(System.identityHashCode(activity))); 10594 out.print(' '); 10595 activity.printComponentShortName(out); 10596 if (count > 1) { 10597 out.print(" ("); out.print(count); out.print(" filters)"); 10598 } 10599 out.println(); 10600 } 10601 10602 // Keys are String (activity class name), values are Activity. 10603 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10604 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10605 private int mFlags; 10606 } 10607 10608 private final class ServiceIntentResolver 10609 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10610 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10611 boolean defaultOnly, int userId) { 10612 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10613 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10614 } 10615 10616 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10617 int userId) { 10618 if (!sUserManager.exists(userId)) return null; 10619 mFlags = flags; 10620 return super.queryIntent(intent, resolvedType, 10621 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10622 } 10623 10624 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10625 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10626 if (!sUserManager.exists(userId)) return null; 10627 if (packageServices == null) { 10628 return null; 10629 } 10630 mFlags = flags; 10631 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10632 final int N = packageServices.size(); 10633 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10634 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10635 10636 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10637 for (int i = 0; i < N; ++i) { 10638 intentFilters = packageServices.get(i).intents; 10639 if (intentFilters != null && intentFilters.size() > 0) { 10640 PackageParser.ServiceIntentInfo[] array = 10641 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10642 intentFilters.toArray(array); 10643 listCut.add(array); 10644 } 10645 } 10646 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10647 } 10648 10649 public final void addService(PackageParser.Service s) { 10650 mServices.put(s.getComponentName(), s); 10651 if (DEBUG_SHOW_INFO) { 10652 Log.v(TAG, " " 10653 + (s.info.nonLocalizedLabel != null 10654 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10655 Log.v(TAG, " Class=" + s.info.name); 10656 } 10657 final int NI = s.intents.size(); 10658 int j; 10659 for (j=0; j<NI; j++) { 10660 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10661 if (DEBUG_SHOW_INFO) { 10662 Log.v(TAG, " IntentFilter:"); 10663 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10664 } 10665 if (!intent.debugCheck()) { 10666 Log.w(TAG, "==> For Service " + s.info.name); 10667 } 10668 addFilter(intent); 10669 } 10670 } 10671 10672 public final void removeService(PackageParser.Service s) { 10673 mServices.remove(s.getComponentName()); 10674 if (DEBUG_SHOW_INFO) { 10675 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10676 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10677 Log.v(TAG, " Class=" + s.info.name); 10678 } 10679 final int NI = s.intents.size(); 10680 int j; 10681 for (j=0; j<NI; j++) { 10682 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10683 if (DEBUG_SHOW_INFO) { 10684 Log.v(TAG, " IntentFilter:"); 10685 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10686 } 10687 removeFilter(intent); 10688 } 10689 } 10690 10691 @Override 10692 protected boolean allowFilterResult( 10693 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10694 ServiceInfo filterSi = filter.service.info; 10695 for (int i=dest.size()-1; i>=0; i--) { 10696 ServiceInfo destAi = dest.get(i).serviceInfo; 10697 if (destAi.name == filterSi.name 10698 && destAi.packageName == filterSi.packageName) { 10699 return false; 10700 } 10701 } 10702 return true; 10703 } 10704 10705 @Override 10706 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10707 return new PackageParser.ServiceIntentInfo[size]; 10708 } 10709 10710 @Override 10711 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10712 if (!sUserManager.exists(userId)) return true; 10713 PackageParser.Package p = filter.service.owner; 10714 if (p != null) { 10715 PackageSetting ps = (PackageSetting)p.mExtras; 10716 if (ps != null) { 10717 // System apps are never considered stopped for purposes of 10718 // filtering, because there may be no way for the user to 10719 // actually re-launch them. 10720 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10721 && ps.getStopped(userId); 10722 } 10723 } 10724 return false; 10725 } 10726 10727 @Override 10728 protected boolean isPackageForFilter(String packageName, 10729 PackageParser.ServiceIntentInfo info) { 10730 return packageName.equals(info.service.owner.packageName); 10731 } 10732 10733 @Override 10734 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10735 int match, int userId) { 10736 if (!sUserManager.exists(userId)) return null; 10737 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10738 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10739 return null; 10740 } 10741 final PackageParser.Service service = info.service; 10742 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10743 if (ps == null) { 10744 return null; 10745 } 10746 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10747 ps.readUserState(userId), userId); 10748 if (si == null) { 10749 return null; 10750 } 10751 final ResolveInfo res = new ResolveInfo(); 10752 res.serviceInfo = si; 10753 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10754 res.filter = filter; 10755 } 10756 res.priority = info.getPriority(); 10757 res.preferredOrder = service.owner.mPreferredOrder; 10758 res.match = match; 10759 res.isDefault = info.hasDefault; 10760 res.labelRes = info.labelRes; 10761 res.nonLocalizedLabel = info.nonLocalizedLabel; 10762 res.icon = info.icon; 10763 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10764 return res; 10765 } 10766 10767 @Override 10768 protected void sortResults(List<ResolveInfo> results) { 10769 Collections.sort(results, mResolvePrioritySorter); 10770 } 10771 10772 @Override 10773 protected void dumpFilter(PrintWriter out, String prefix, 10774 PackageParser.ServiceIntentInfo filter) { 10775 out.print(prefix); out.print( 10776 Integer.toHexString(System.identityHashCode(filter.service))); 10777 out.print(' '); 10778 filter.service.printComponentShortName(out); 10779 out.print(" filter "); 10780 out.println(Integer.toHexString(System.identityHashCode(filter))); 10781 } 10782 10783 @Override 10784 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10785 return filter.service; 10786 } 10787 10788 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10789 PackageParser.Service service = (PackageParser.Service)label; 10790 out.print(prefix); out.print( 10791 Integer.toHexString(System.identityHashCode(service))); 10792 out.print(' '); 10793 service.printComponentShortName(out); 10794 if (count > 1) { 10795 out.print(" ("); out.print(count); out.print(" filters)"); 10796 } 10797 out.println(); 10798 } 10799 10800// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10801// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10802// final List<ResolveInfo> retList = Lists.newArrayList(); 10803// while (i.hasNext()) { 10804// final ResolveInfo resolveInfo = (ResolveInfo) i; 10805// if (isEnabledLP(resolveInfo.serviceInfo)) { 10806// retList.add(resolveInfo); 10807// } 10808// } 10809// return retList; 10810// } 10811 10812 // Keys are String (activity class name), values are Activity. 10813 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10814 = new ArrayMap<ComponentName, PackageParser.Service>(); 10815 private int mFlags; 10816 }; 10817 10818 private final class ProviderIntentResolver 10819 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10820 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10821 boolean defaultOnly, int userId) { 10822 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10823 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10824 } 10825 10826 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10827 int userId) { 10828 if (!sUserManager.exists(userId)) 10829 return null; 10830 mFlags = flags; 10831 return super.queryIntent(intent, resolvedType, 10832 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10833 } 10834 10835 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10836 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10837 if (!sUserManager.exists(userId)) 10838 return null; 10839 if (packageProviders == null) { 10840 return null; 10841 } 10842 mFlags = flags; 10843 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10844 final int N = packageProviders.size(); 10845 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10846 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10847 10848 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10849 for (int i = 0; i < N; ++i) { 10850 intentFilters = packageProviders.get(i).intents; 10851 if (intentFilters != null && intentFilters.size() > 0) { 10852 PackageParser.ProviderIntentInfo[] array = 10853 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10854 intentFilters.toArray(array); 10855 listCut.add(array); 10856 } 10857 } 10858 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10859 } 10860 10861 public final void addProvider(PackageParser.Provider p) { 10862 if (mProviders.containsKey(p.getComponentName())) { 10863 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10864 return; 10865 } 10866 10867 mProviders.put(p.getComponentName(), p); 10868 if (DEBUG_SHOW_INFO) { 10869 Log.v(TAG, " " 10870 + (p.info.nonLocalizedLabel != null 10871 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10872 Log.v(TAG, " Class=" + p.info.name); 10873 } 10874 final int NI = p.intents.size(); 10875 int j; 10876 for (j = 0; j < NI; j++) { 10877 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10878 if (DEBUG_SHOW_INFO) { 10879 Log.v(TAG, " IntentFilter:"); 10880 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10881 } 10882 if (!intent.debugCheck()) { 10883 Log.w(TAG, "==> For Provider " + p.info.name); 10884 } 10885 addFilter(intent); 10886 } 10887 } 10888 10889 public final void removeProvider(PackageParser.Provider p) { 10890 mProviders.remove(p.getComponentName()); 10891 if (DEBUG_SHOW_INFO) { 10892 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10893 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10894 Log.v(TAG, " Class=" + p.info.name); 10895 } 10896 final int NI = p.intents.size(); 10897 int j; 10898 for (j = 0; j < NI; j++) { 10899 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10900 if (DEBUG_SHOW_INFO) { 10901 Log.v(TAG, " IntentFilter:"); 10902 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10903 } 10904 removeFilter(intent); 10905 } 10906 } 10907 10908 @Override 10909 protected boolean allowFilterResult( 10910 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10911 ProviderInfo filterPi = filter.provider.info; 10912 for (int i = dest.size() - 1; i >= 0; i--) { 10913 ProviderInfo destPi = dest.get(i).providerInfo; 10914 if (destPi.name == filterPi.name 10915 && destPi.packageName == filterPi.packageName) { 10916 return false; 10917 } 10918 } 10919 return true; 10920 } 10921 10922 @Override 10923 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10924 return new PackageParser.ProviderIntentInfo[size]; 10925 } 10926 10927 @Override 10928 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10929 if (!sUserManager.exists(userId)) 10930 return true; 10931 PackageParser.Package p = filter.provider.owner; 10932 if (p != null) { 10933 PackageSetting ps = (PackageSetting) p.mExtras; 10934 if (ps != null) { 10935 // System apps are never considered stopped for purposes of 10936 // filtering, because there may be no way for the user to 10937 // actually re-launch them. 10938 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10939 && ps.getStopped(userId); 10940 } 10941 } 10942 return false; 10943 } 10944 10945 @Override 10946 protected boolean isPackageForFilter(String packageName, 10947 PackageParser.ProviderIntentInfo info) { 10948 return packageName.equals(info.provider.owner.packageName); 10949 } 10950 10951 @Override 10952 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10953 int match, int userId) { 10954 if (!sUserManager.exists(userId)) 10955 return null; 10956 final PackageParser.ProviderIntentInfo info = filter; 10957 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10958 return null; 10959 } 10960 final PackageParser.Provider provider = info.provider; 10961 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10962 if (ps == null) { 10963 return null; 10964 } 10965 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10966 ps.readUserState(userId), userId); 10967 if (pi == null) { 10968 return null; 10969 } 10970 final ResolveInfo res = new ResolveInfo(); 10971 res.providerInfo = pi; 10972 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10973 res.filter = filter; 10974 } 10975 res.priority = info.getPriority(); 10976 res.preferredOrder = provider.owner.mPreferredOrder; 10977 res.match = match; 10978 res.isDefault = info.hasDefault; 10979 res.labelRes = info.labelRes; 10980 res.nonLocalizedLabel = info.nonLocalizedLabel; 10981 res.icon = info.icon; 10982 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10983 return res; 10984 } 10985 10986 @Override 10987 protected void sortResults(List<ResolveInfo> results) { 10988 Collections.sort(results, mResolvePrioritySorter); 10989 } 10990 10991 @Override 10992 protected void dumpFilter(PrintWriter out, String prefix, 10993 PackageParser.ProviderIntentInfo filter) { 10994 out.print(prefix); 10995 out.print( 10996 Integer.toHexString(System.identityHashCode(filter.provider))); 10997 out.print(' '); 10998 filter.provider.printComponentShortName(out); 10999 out.print(" filter "); 11000 out.println(Integer.toHexString(System.identityHashCode(filter))); 11001 } 11002 11003 @Override 11004 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11005 return filter.provider; 11006 } 11007 11008 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11009 PackageParser.Provider provider = (PackageParser.Provider)label; 11010 out.print(prefix); out.print( 11011 Integer.toHexString(System.identityHashCode(provider))); 11012 out.print(' '); 11013 provider.printComponentShortName(out); 11014 if (count > 1) { 11015 out.print(" ("); out.print(count); out.print(" filters)"); 11016 } 11017 out.println(); 11018 } 11019 11020 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11021 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11022 private int mFlags; 11023 } 11024 11025 private static final class EphemeralIntentResolver 11026 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11027 @Override 11028 protected EphemeralResolveIntentInfo[] newArray(int size) { 11029 return new EphemeralResolveIntentInfo[size]; 11030 } 11031 11032 @Override 11033 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11034 return true; 11035 } 11036 11037 @Override 11038 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11039 int userId) { 11040 if (!sUserManager.exists(userId)) { 11041 return null; 11042 } 11043 return info.getEphemeralResolveInfo(); 11044 } 11045 } 11046 11047 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11048 new Comparator<ResolveInfo>() { 11049 public int compare(ResolveInfo r1, ResolveInfo r2) { 11050 int v1 = r1.priority; 11051 int v2 = r2.priority; 11052 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11053 if (v1 != v2) { 11054 return (v1 > v2) ? -1 : 1; 11055 } 11056 v1 = r1.preferredOrder; 11057 v2 = r2.preferredOrder; 11058 if (v1 != v2) { 11059 return (v1 > v2) ? -1 : 1; 11060 } 11061 if (r1.isDefault != r2.isDefault) { 11062 return r1.isDefault ? -1 : 1; 11063 } 11064 v1 = r1.match; 11065 v2 = r2.match; 11066 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11067 if (v1 != v2) { 11068 return (v1 > v2) ? -1 : 1; 11069 } 11070 if (r1.system != r2.system) { 11071 return r1.system ? -1 : 1; 11072 } 11073 if (r1.activityInfo != null) { 11074 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11075 } 11076 if (r1.serviceInfo != null) { 11077 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11078 } 11079 if (r1.providerInfo != null) { 11080 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11081 } 11082 return 0; 11083 } 11084 }; 11085 11086 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11087 new Comparator<ProviderInfo>() { 11088 public int compare(ProviderInfo p1, ProviderInfo p2) { 11089 final int v1 = p1.initOrder; 11090 final int v2 = p2.initOrder; 11091 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11092 } 11093 }; 11094 11095 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11096 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11097 final int[] userIds) { 11098 mHandler.post(new Runnable() { 11099 @Override 11100 public void run() { 11101 try { 11102 final IActivityManager am = ActivityManagerNative.getDefault(); 11103 if (am == null) return; 11104 final int[] resolvedUserIds; 11105 if (userIds == null) { 11106 resolvedUserIds = am.getRunningUserIds(); 11107 } else { 11108 resolvedUserIds = userIds; 11109 } 11110 for (int id : resolvedUserIds) { 11111 final Intent intent = new Intent(action, 11112 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11113 if (extras != null) { 11114 intent.putExtras(extras); 11115 } 11116 if (targetPkg != null) { 11117 intent.setPackage(targetPkg); 11118 } 11119 // Modify the UID when posting to other users 11120 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11121 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11122 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11123 intent.putExtra(Intent.EXTRA_UID, uid); 11124 } 11125 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11126 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11127 if (DEBUG_BROADCASTS) { 11128 RuntimeException here = new RuntimeException("here"); 11129 here.fillInStackTrace(); 11130 Slog.d(TAG, "Sending to user " + id + ": " 11131 + intent.toShortString(false, true, false, false) 11132 + " " + intent.getExtras(), here); 11133 } 11134 am.broadcastIntent(null, intent, null, finishedReceiver, 11135 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11136 null, finishedReceiver != null, false, id); 11137 } 11138 } catch (RemoteException ex) { 11139 } 11140 } 11141 }); 11142 } 11143 11144 /** 11145 * Check if the external storage media is available. This is true if there 11146 * is a mounted external storage medium or if the external storage is 11147 * emulated. 11148 */ 11149 private boolean isExternalMediaAvailable() { 11150 return mMediaMounted || Environment.isExternalStorageEmulated(); 11151 } 11152 11153 @Override 11154 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11155 // writer 11156 synchronized (mPackages) { 11157 if (!isExternalMediaAvailable()) { 11158 // If the external storage is no longer mounted at this point, 11159 // the caller may not have been able to delete all of this 11160 // packages files and can not delete any more. Bail. 11161 return null; 11162 } 11163 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11164 if (lastPackage != null) { 11165 pkgs.remove(lastPackage); 11166 } 11167 if (pkgs.size() > 0) { 11168 return pkgs.get(0); 11169 } 11170 } 11171 return null; 11172 } 11173 11174 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11175 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11176 userId, andCode ? 1 : 0, packageName); 11177 if (mSystemReady) { 11178 msg.sendToTarget(); 11179 } else { 11180 if (mPostSystemReadyMessages == null) { 11181 mPostSystemReadyMessages = new ArrayList<>(); 11182 } 11183 mPostSystemReadyMessages.add(msg); 11184 } 11185 } 11186 11187 void startCleaningPackages() { 11188 // reader 11189 if (!isExternalMediaAvailable()) { 11190 return; 11191 } 11192 synchronized (mPackages) { 11193 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11194 return; 11195 } 11196 } 11197 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11198 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11199 IActivityManager am = ActivityManagerNative.getDefault(); 11200 if (am != null) { 11201 try { 11202 am.startService(null, intent, null, mContext.getOpPackageName(), 11203 UserHandle.USER_SYSTEM); 11204 } catch (RemoteException e) { 11205 } 11206 } 11207 } 11208 11209 @Override 11210 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11211 int installFlags, String installerPackageName, int userId) { 11212 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11213 11214 final int callingUid = Binder.getCallingUid(); 11215 enforceCrossUserPermission(callingUid, userId, 11216 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11217 11218 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11219 try { 11220 if (observer != null) { 11221 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11222 } 11223 } catch (RemoteException re) { 11224 } 11225 return; 11226 } 11227 11228 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11229 installFlags |= PackageManager.INSTALL_FROM_ADB; 11230 11231 } else { 11232 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11233 // about installerPackageName. 11234 11235 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11236 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11237 } 11238 11239 UserHandle user; 11240 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11241 user = UserHandle.ALL; 11242 } else { 11243 user = new UserHandle(userId); 11244 } 11245 11246 // Only system components can circumvent runtime permissions when installing. 11247 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11248 && mContext.checkCallingOrSelfPermission(Manifest.permission 11249 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11250 throw new SecurityException("You need the " 11251 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11252 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11253 } 11254 11255 final File originFile = new File(originPath); 11256 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11257 11258 final Message msg = mHandler.obtainMessage(INIT_COPY); 11259 final VerificationInfo verificationInfo = new VerificationInfo( 11260 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11261 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11262 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11263 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11264 null /*certificates*/); 11265 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11266 msg.obj = params; 11267 11268 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11269 System.identityHashCode(msg.obj)); 11270 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11271 System.identityHashCode(msg.obj)); 11272 11273 mHandler.sendMessage(msg); 11274 } 11275 11276 void installStage(String packageName, File stagedDir, String stagedCid, 11277 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11278 String installerPackageName, int installerUid, UserHandle user, 11279 Certificate[][] certificates) { 11280 if (DEBUG_EPHEMERAL) { 11281 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11282 Slog.d(TAG, "Ephemeral install of " + packageName); 11283 } 11284 } 11285 final VerificationInfo verificationInfo = new VerificationInfo( 11286 sessionParams.originatingUri, sessionParams.referrerUri, 11287 sessionParams.originatingUid, installerUid); 11288 11289 final OriginInfo origin; 11290 if (stagedDir != null) { 11291 origin = OriginInfo.fromStagedFile(stagedDir); 11292 } else { 11293 origin = OriginInfo.fromStagedContainer(stagedCid); 11294 } 11295 11296 final Message msg = mHandler.obtainMessage(INIT_COPY); 11297 final InstallParams params = new InstallParams(origin, null, observer, 11298 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11299 verificationInfo, user, sessionParams.abiOverride, 11300 sessionParams.grantedRuntimePermissions, certificates); 11301 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11302 msg.obj = params; 11303 11304 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11305 System.identityHashCode(msg.obj)); 11306 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11307 System.identityHashCode(msg.obj)); 11308 11309 mHandler.sendMessage(msg); 11310 } 11311 11312 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11313 int userId) { 11314 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11315 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11316 } 11317 11318 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11319 int appId, int userId) { 11320 Bundle extras = new Bundle(1); 11321 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11322 11323 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11324 packageName, extras, 0, null, null, new int[] {userId}); 11325 try { 11326 IActivityManager am = ActivityManagerNative.getDefault(); 11327 if (isSystem && am.isUserRunning(userId, 0)) { 11328 // The just-installed/enabled app is bundled on the system, so presumed 11329 // to be able to run automatically without needing an explicit launch. 11330 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11331 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11332 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11333 .setPackage(packageName); 11334 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11335 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11336 } 11337 } catch (RemoteException e) { 11338 // shouldn't happen 11339 Slog.w(TAG, "Unable to bootstrap installed package", e); 11340 } 11341 } 11342 11343 @Override 11344 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11345 int userId) { 11346 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11347 PackageSetting pkgSetting; 11348 final int uid = Binder.getCallingUid(); 11349 enforceCrossUserPermission(uid, userId, 11350 true /* requireFullPermission */, true /* checkShell */, 11351 "setApplicationHiddenSetting for user " + userId); 11352 11353 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11354 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11355 return false; 11356 } 11357 11358 long callingId = Binder.clearCallingIdentity(); 11359 try { 11360 boolean sendAdded = false; 11361 boolean sendRemoved = false; 11362 // writer 11363 synchronized (mPackages) { 11364 pkgSetting = mSettings.mPackages.get(packageName); 11365 if (pkgSetting == null) { 11366 return false; 11367 } 11368 if (pkgSetting.getHidden(userId) != hidden) { 11369 pkgSetting.setHidden(hidden, userId); 11370 mSettings.writePackageRestrictionsLPr(userId); 11371 if (hidden) { 11372 sendRemoved = true; 11373 } else { 11374 sendAdded = true; 11375 } 11376 } 11377 } 11378 if (sendAdded) { 11379 sendPackageAddedForUser(packageName, pkgSetting, userId); 11380 return true; 11381 } 11382 if (sendRemoved) { 11383 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11384 "hiding pkg"); 11385 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11386 return true; 11387 } 11388 } finally { 11389 Binder.restoreCallingIdentity(callingId); 11390 } 11391 return false; 11392 } 11393 11394 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11395 int userId) { 11396 final PackageRemovedInfo info = new PackageRemovedInfo(); 11397 info.removedPackage = packageName; 11398 info.removedUsers = new int[] {userId}; 11399 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11400 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11401 } 11402 11403 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11404 if (pkgList.length > 0) { 11405 Bundle extras = new Bundle(1); 11406 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11407 11408 sendPackageBroadcast( 11409 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11410 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11411 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11412 new int[] {userId}); 11413 } 11414 } 11415 11416 /** 11417 * Returns true if application is not found or there was an error. Otherwise it returns 11418 * the hidden state of the package for the given user. 11419 */ 11420 @Override 11421 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11422 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11423 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11424 true /* requireFullPermission */, false /* checkShell */, 11425 "getApplicationHidden for user " + userId); 11426 PackageSetting pkgSetting; 11427 long callingId = Binder.clearCallingIdentity(); 11428 try { 11429 // writer 11430 synchronized (mPackages) { 11431 pkgSetting = mSettings.mPackages.get(packageName); 11432 if (pkgSetting == null) { 11433 return true; 11434 } 11435 return pkgSetting.getHidden(userId); 11436 } 11437 } finally { 11438 Binder.restoreCallingIdentity(callingId); 11439 } 11440 } 11441 11442 /** 11443 * @hide 11444 */ 11445 @Override 11446 public int installExistingPackageAsUser(String packageName, int userId) { 11447 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11448 null); 11449 PackageSetting pkgSetting; 11450 final int uid = Binder.getCallingUid(); 11451 enforceCrossUserPermission(uid, userId, 11452 true /* requireFullPermission */, true /* checkShell */, 11453 "installExistingPackage for user " + userId); 11454 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11455 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11456 } 11457 11458 long callingId = Binder.clearCallingIdentity(); 11459 try { 11460 boolean installed = false; 11461 11462 // writer 11463 synchronized (mPackages) { 11464 pkgSetting = mSettings.mPackages.get(packageName); 11465 if (pkgSetting == null) { 11466 return PackageManager.INSTALL_FAILED_INVALID_URI; 11467 } 11468 if (!pkgSetting.getInstalled(userId)) { 11469 pkgSetting.setInstalled(true, userId); 11470 pkgSetting.setHidden(false, userId); 11471 mSettings.writePackageRestrictionsLPr(userId); 11472 installed = true; 11473 } 11474 } 11475 11476 if (installed) { 11477 if (pkgSetting.pkg != null) { 11478 synchronized (mInstallLock) { 11479 // We don't need to freeze for a brand new install 11480 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11481 } 11482 } 11483 sendPackageAddedForUser(packageName, pkgSetting, userId); 11484 } 11485 } finally { 11486 Binder.restoreCallingIdentity(callingId); 11487 } 11488 11489 return PackageManager.INSTALL_SUCCEEDED; 11490 } 11491 11492 boolean isUserRestricted(int userId, String restrictionKey) { 11493 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11494 if (restrictions.getBoolean(restrictionKey, false)) { 11495 Log.w(TAG, "User is restricted: " + restrictionKey); 11496 return true; 11497 } 11498 return false; 11499 } 11500 11501 @Override 11502 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11503 int userId) { 11504 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11505 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11506 true /* requireFullPermission */, true /* checkShell */, 11507 "setPackagesSuspended for user " + userId); 11508 11509 if (ArrayUtils.isEmpty(packageNames)) { 11510 return packageNames; 11511 } 11512 11513 // List of package names for whom the suspended state has changed. 11514 List<String> changedPackages = new ArrayList<>(packageNames.length); 11515 // List of package names for whom the suspended state is not set as requested in this 11516 // method. 11517 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11518 long callingId = Binder.clearCallingIdentity(); 11519 try { 11520 for (int i = 0; i < packageNames.length; i++) { 11521 String packageName = packageNames[i]; 11522 boolean changed = false; 11523 final int appId; 11524 synchronized (mPackages) { 11525 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11526 if (pkgSetting == null) { 11527 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11528 + "\". Skipping suspending/un-suspending."); 11529 unactionedPackages.add(packageName); 11530 continue; 11531 } 11532 appId = pkgSetting.appId; 11533 if (pkgSetting.getSuspended(userId) != suspended) { 11534 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11535 unactionedPackages.add(packageName); 11536 continue; 11537 } 11538 pkgSetting.setSuspended(suspended, userId); 11539 mSettings.writePackageRestrictionsLPr(userId); 11540 changed = true; 11541 changedPackages.add(packageName); 11542 } 11543 } 11544 11545 if (changed && suspended) { 11546 killApplication(packageName, UserHandle.getUid(userId, appId), 11547 "suspending package"); 11548 } 11549 } 11550 } finally { 11551 Binder.restoreCallingIdentity(callingId); 11552 } 11553 11554 if (!changedPackages.isEmpty()) { 11555 sendPackagesSuspendedForUser(changedPackages.toArray( 11556 new String[changedPackages.size()]), userId, suspended); 11557 } 11558 11559 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11560 } 11561 11562 @Override 11563 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11564 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11565 true /* requireFullPermission */, false /* checkShell */, 11566 "isPackageSuspendedForUser for user " + userId); 11567 synchronized (mPackages) { 11568 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11569 if (pkgSetting == null) { 11570 throw new IllegalArgumentException("Unknown target package: " + packageName); 11571 } 11572 return pkgSetting.getSuspended(userId); 11573 } 11574 } 11575 11576 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11577 if (isPackageDeviceAdmin(packageName, userId)) { 11578 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11579 + "\": has an active device admin"); 11580 return false; 11581 } 11582 11583 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11584 if (packageName.equals(activeLauncherPackageName)) { 11585 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11586 + "\": contains the active launcher"); 11587 return false; 11588 } 11589 11590 if (packageName.equals(mRequiredInstallerPackage)) { 11591 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11592 + "\": required for package installation"); 11593 return false; 11594 } 11595 11596 if (packageName.equals(mRequiredVerifierPackage)) { 11597 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11598 + "\": required for package verification"); 11599 return false; 11600 } 11601 11602 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11603 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11604 + "\": is the default dialer"); 11605 return false; 11606 } 11607 11608 return true; 11609 } 11610 11611 private String getActiveLauncherPackageName(int userId) { 11612 Intent intent = new Intent(Intent.ACTION_MAIN); 11613 intent.addCategory(Intent.CATEGORY_HOME); 11614 ResolveInfo resolveInfo = resolveIntent( 11615 intent, 11616 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11617 PackageManager.MATCH_DEFAULT_ONLY, 11618 userId); 11619 11620 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11621 } 11622 11623 private String getDefaultDialerPackageName(int userId) { 11624 synchronized (mPackages) { 11625 return mSettings.getDefaultDialerPackageNameLPw(userId); 11626 } 11627 } 11628 11629 @Override 11630 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11631 mContext.enforceCallingOrSelfPermission( 11632 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11633 "Only package verification agents can verify applications"); 11634 11635 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11636 final PackageVerificationResponse response = new PackageVerificationResponse( 11637 verificationCode, Binder.getCallingUid()); 11638 msg.arg1 = id; 11639 msg.obj = response; 11640 mHandler.sendMessage(msg); 11641 } 11642 11643 @Override 11644 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11645 long millisecondsToDelay) { 11646 mContext.enforceCallingOrSelfPermission( 11647 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11648 "Only package verification agents can extend verification timeouts"); 11649 11650 final PackageVerificationState state = mPendingVerification.get(id); 11651 final PackageVerificationResponse response = new PackageVerificationResponse( 11652 verificationCodeAtTimeout, Binder.getCallingUid()); 11653 11654 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11655 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11656 } 11657 if (millisecondsToDelay < 0) { 11658 millisecondsToDelay = 0; 11659 } 11660 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11661 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11662 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11663 } 11664 11665 if ((state != null) && !state.timeoutExtended()) { 11666 state.extendTimeout(); 11667 11668 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11669 msg.arg1 = id; 11670 msg.obj = response; 11671 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11672 } 11673 } 11674 11675 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11676 int verificationCode, UserHandle user) { 11677 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11678 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11679 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11680 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11681 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11682 11683 mContext.sendBroadcastAsUser(intent, user, 11684 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11685 } 11686 11687 private ComponentName matchComponentForVerifier(String packageName, 11688 List<ResolveInfo> receivers) { 11689 ActivityInfo targetReceiver = null; 11690 11691 final int NR = receivers.size(); 11692 for (int i = 0; i < NR; i++) { 11693 final ResolveInfo info = receivers.get(i); 11694 if (info.activityInfo == null) { 11695 continue; 11696 } 11697 11698 if (packageName.equals(info.activityInfo.packageName)) { 11699 targetReceiver = info.activityInfo; 11700 break; 11701 } 11702 } 11703 11704 if (targetReceiver == null) { 11705 return null; 11706 } 11707 11708 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11709 } 11710 11711 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11712 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11713 if (pkgInfo.verifiers.length == 0) { 11714 return null; 11715 } 11716 11717 final int N = pkgInfo.verifiers.length; 11718 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11719 for (int i = 0; i < N; i++) { 11720 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11721 11722 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11723 receivers); 11724 if (comp == null) { 11725 continue; 11726 } 11727 11728 final int verifierUid = getUidForVerifier(verifierInfo); 11729 if (verifierUid == -1) { 11730 continue; 11731 } 11732 11733 if (DEBUG_VERIFY) { 11734 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11735 + " with the correct signature"); 11736 } 11737 sufficientVerifiers.add(comp); 11738 verificationState.addSufficientVerifier(verifierUid); 11739 } 11740 11741 return sufficientVerifiers; 11742 } 11743 11744 private int getUidForVerifier(VerifierInfo verifierInfo) { 11745 synchronized (mPackages) { 11746 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11747 if (pkg == null) { 11748 return -1; 11749 } else if (pkg.mSignatures.length != 1) { 11750 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11751 + " has more than one signature; ignoring"); 11752 return -1; 11753 } 11754 11755 /* 11756 * If the public key of the package's signature does not match 11757 * our expected public key, then this is a different package and 11758 * we should skip. 11759 */ 11760 11761 final byte[] expectedPublicKey; 11762 try { 11763 final Signature verifierSig = pkg.mSignatures[0]; 11764 final PublicKey publicKey = verifierSig.getPublicKey(); 11765 expectedPublicKey = publicKey.getEncoded(); 11766 } catch (CertificateException e) { 11767 return -1; 11768 } 11769 11770 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11771 11772 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11773 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11774 + " does not have the expected public key; ignoring"); 11775 return -1; 11776 } 11777 11778 return pkg.applicationInfo.uid; 11779 } 11780 } 11781 11782 @Override 11783 public void finishPackageInstall(int token, boolean didLaunch) { 11784 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11785 11786 if (DEBUG_INSTALL) { 11787 Slog.v(TAG, "BM finishing package install for " + token); 11788 } 11789 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11790 11791 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11792 mHandler.sendMessage(msg); 11793 } 11794 11795 /** 11796 * Get the verification agent timeout. 11797 * 11798 * @return verification timeout in milliseconds 11799 */ 11800 private long getVerificationTimeout() { 11801 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11802 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11803 DEFAULT_VERIFICATION_TIMEOUT); 11804 } 11805 11806 /** 11807 * Get the default verification agent response code. 11808 * 11809 * @return default verification response code 11810 */ 11811 private int getDefaultVerificationResponse() { 11812 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11813 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11814 DEFAULT_VERIFICATION_RESPONSE); 11815 } 11816 11817 /** 11818 * Check whether or not package verification has been enabled. 11819 * 11820 * @return true if verification should be performed 11821 */ 11822 private boolean isVerificationEnabled(int userId, int installFlags) { 11823 if (!DEFAULT_VERIFY_ENABLE) { 11824 return false; 11825 } 11826 // Ephemeral apps don't get the full verification treatment 11827 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11828 if (DEBUG_EPHEMERAL) { 11829 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11830 } 11831 return false; 11832 } 11833 11834 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11835 11836 // Check if installing from ADB 11837 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11838 // Do not run verification in a test harness environment 11839 if (ActivityManager.isRunningInTestHarness()) { 11840 return false; 11841 } 11842 if (ensureVerifyAppsEnabled) { 11843 return true; 11844 } 11845 // Check if the developer does not want package verification for ADB installs 11846 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11847 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11848 return false; 11849 } 11850 } 11851 11852 if (ensureVerifyAppsEnabled) { 11853 return true; 11854 } 11855 11856 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11857 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11858 } 11859 11860 @Override 11861 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11862 throws RemoteException { 11863 mContext.enforceCallingOrSelfPermission( 11864 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11865 "Only intentfilter verification agents can verify applications"); 11866 11867 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11868 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11869 Binder.getCallingUid(), verificationCode, failedDomains); 11870 msg.arg1 = id; 11871 msg.obj = response; 11872 mHandler.sendMessage(msg); 11873 } 11874 11875 @Override 11876 public int getIntentVerificationStatus(String packageName, int userId) { 11877 synchronized (mPackages) { 11878 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11879 } 11880 } 11881 11882 @Override 11883 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11884 mContext.enforceCallingOrSelfPermission( 11885 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11886 11887 boolean result = false; 11888 synchronized (mPackages) { 11889 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11890 } 11891 if (result) { 11892 scheduleWritePackageRestrictionsLocked(userId); 11893 } 11894 return result; 11895 } 11896 11897 @Override 11898 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11899 String packageName) { 11900 synchronized (mPackages) { 11901 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11902 } 11903 } 11904 11905 @Override 11906 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11907 if (TextUtils.isEmpty(packageName)) { 11908 return ParceledListSlice.emptyList(); 11909 } 11910 synchronized (mPackages) { 11911 PackageParser.Package pkg = mPackages.get(packageName); 11912 if (pkg == null || pkg.activities == null) { 11913 return ParceledListSlice.emptyList(); 11914 } 11915 final int count = pkg.activities.size(); 11916 ArrayList<IntentFilter> result = new ArrayList<>(); 11917 for (int n=0; n<count; n++) { 11918 PackageParser.Activity activity = pkg.activities.get(n); 11919 if (activity.intents != null && activity.intents.size() > 0) { 11920 result.addAll(activity.intents); 11921 } 11922 } 11923 return new ParceledListSlice<>(result); 11924 } 11925 } 11926 11927 @Override 11928 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11929 mContext.enforceCallingOrSelfPermission( 11930 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11931 11932 synchronized (mPackages) { 11933 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11934 if (packageName != null) { 11935 result |= updateIntentVerificationStatus(packageName, 11936 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11937 userId); 11938 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11939 packageName, userId); 11940 } 11941 return result; 11942 } 11943 } 11944 11945 @Override 11946 public String getDefaultBrowserPackageName(int userId) { 11947 synchronized (mPackages) { 11948 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11949 } 11950 } 11951 11952 /** 11953 * Get the "allow unknown sources" setting. 11954 * 11955 * @return the current "allow unknown sources" setting 11956 */ 11957 private int getUnknownSourcesSettings() { 11958 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11959 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11960 -1); 11961 } 11962 11963 @Override 11964 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11965 final int uid = Binder.getCallingUid(); 11966 // writer 11967 synchronized (mPackages) { 11968 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11969 if (targetPackageSetting == null) { 11970 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11971 } 11972 11973 PackageSetting installerPackageSetting; 11974 if (installerPackageName != null) { 11975 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11976 if (installerPackageSetting == null) { 11977 throw new IllegalArgumentException("Unknown installer package: " 11978 + installerPackageName); 11979 } 11980 } else { 11981 installerPackageSetting = null; 11982 } 11983 11984 Signature[] callerSignature; 11985 Object obj = mSettings.getUserIdLPr(uid); 11986 if (obj != null) { 11987 if (obj instanceof SharedUserSetting) { 11988 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11989 } else if (obj instanceof PackageSetting) { 11990 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11991 } else { 11992 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11993 } 11994 } else { 11995 throw new SecurityException("Unknown calling UID: " + uid); 11996 } 11997 11998 // Verify: can't set installerPackageName to a package that is 11999 // not signed with the same cert as the caller. 12000 if (installerPackageSetting != null) { 12001 if (compareSignatures(callerSignature, 12002 installerPackageSetting.signatures.mSignatures) 12003 != PackageManager.SIGNATURE_MATCH) { 12004 throw new SecurityException( 12005 "Caller does not have same cert as new installer package " 12006 + installerPackageName); 12007 } 12008 } 12009 12010 // Verify: if target already has an installer package, it must 12011 // be signed with the same cert as the caller. 12012 if (targetPackageSetting.installerPackageName != null) { 12013 PackageSetting setting = mSettings.mPackages.get( 12014 targetPackageSetting.installerPackageName); 12015 // If the currently set package isn't valid, then it's always 12016 // okay to change it. 12017 if (setting != null) { 12018 if (compareSignatures(callerSignature, 12019 setting.signatures.mSignatures) 12020 != PackageManager.SIGNATURE_MATCH) { 12021 throw new SecurityException( 12022 "Caller does not have same cert as old installer package " 12023 + targetPackageSetting.installerPackageName); 12024 } 12025 } 12026 } 12027 12028 // Okay! 12029 targetPackageSetting.installerPackageName = installerPackageName; 12030 if (installerPackageName != null) { 12031 mSettings.mInstallerPackages.add(installerPackageName); 12032 } 12033 scheduleWriteSettingsLocked(); 12034 } 12035 } 12036 12037 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12038 // Queue up an async operation since the package installation may take a little while. 12039 mHandler.post(new Runnable() { 12040 public void run() { 12041 mHandler.removeCallbacks(this); 12042 // Result object to be returned 12043 PackageInstalledInfo res = new PackageInstalledInfo(); 12044 res.setReturnCode(currentStatus); 12045 res.uid = -1; 12046 res.pkg = null; 12047 res.removedInfo = null; 12048 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12049 args.doPreInstall(res.returnCode); 12050 synchronized (mInstallLock) { 12051 installPackageTracedLI(args, res); 12052 } 12053 args.doPostInstall(res.returnCode, res.uid); 12054 } 12055 12056 // A restore should be performed at this point if (a) the install 12057 // succeeded, (b) the operation is not an update, and (c) the new 12058 // package has not opted out of backup participation. 12059 final boolean update = res.removedInfo != null 12060 && res.removedInfo.removedPackage != null; 12061 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12062 boolean doRestore = !update 12063 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12064 12065 // Set up the post-install work request bookkeeping. This will be used 12066 // and cleaned up by the post-install event handling regardless of whether 12067 // there's a restore pass performed. Token values are >= 1. 12068 int token; 12069 if (mNextInstallToken < 0) mNextInstallToken = 1; 12070 token = mNextInstallToken++; 12071 12072 PostInstallData data = new PostInstallData(args, res); 12073 mRunningInstalls.put(token, data); 12074 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12075 12076 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12077 // Pass responsibility to the Backup Manager. It will perform a 12078 // restore if appropriate, then pass responsibility back to the 12079 // Package Manager to run the post-install observer callbacks 12080 // and broadcasts. 12081 IBackupManager bm = IBackupManager.Stub.asInterface( 12082 ServiceManager.getService(Context.BACKUP_SERVICE)); 12083 if (bm != null) { 12084 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12085 + " to BM for possible restore"); 12086 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12087 try { 12088 // TODO: http://b/22388012 12089 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12090 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12091 } else { 12092 doRestore = false; 12093 } 12094 } catch (RemoteException e) { 12095 // can't happen; the backup manager is local 12096 } catch (Exception e) { 12097 Slog.e(TAG, "Exception trying to enqueue restore", e); 12098 doRestore = false; 12099 } 12100 } else { 12101 Slog.e(TAG, "Backup Manager not found!"); 12102 doRestore = false; 12103 } 12104 } 12105 12106 if (!doRestore) { 12107 // No restore possible, or the Backup Manager was mysteriously not 12108 // available -- just fire the post-install work request directly. 12109 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12110 12111 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12112 12113 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12114 mHandler.sendMessage(msg); 12115 } 12116 } 12117 }); 12118 } 12119 12120 /** 12121 * Callback from PackageSettings whenever an app is first transitioned out of the 12122 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12123 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12124 * here whether the app is the target of an ongoing install, and only send the 12125 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12126 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12127 * handling. 12128 */ 12129 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12130 // Serialize this with the rest of the install-process message chain. In the 12131 // restore-at-install case, this Runnable will necessarily run before the 12132 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12133 // are coherent. In the non-restore case, the app has already completed install 12134 // and been launched through some other means, so it is not in a problematic 12135 // state for observers to see the FIRST_LAUNCH signal. 12136 mHandler.post(new Runnable() { 12137 @Override 12138 public void run() { 12139 for (int i = 0; i < mRunningInstalls.size(); i++) { 12140 final PostInstallData data = mRunningInstalls.valueAt(i); 12141 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12142 // right package; but is it for the right user? 12143 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12144 if (userId == data.res.newUsers[uIndex]) { 12145 if (DEBUG_BACKUP) { 12146 Slog.i(TAG, "Package " + pkgName 12147 + " being restored so deferring FIRST_LAUNCH"); 12148 } 12149 return; 12150 } 12151 } 12152 } 12153 } 12154 // didn't find it, so not being restored 12155 if (DEBUG_BACKUP) { 12156 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12157 } 12158 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12159 } 12160 }); 12161 } 12162 12163 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12164 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12165 installerPkg, null, userIds); 12166 } 12167 12168 private abstract class HandlerParams { 12169 private static final int MAX_RETRIES = 4; 12170 12171 /** 12172 * Number of times startCopy() has been attempted and had a non-fatal 12173 * error. 12174 */ 12175 private int mRetries = 0; 12176 12177 /** User handle for the user requesting the information or installation. */ 12178 private final UserHandle mUser; 12179 String traceMethod; 12180 int traceCookie; 12181 12182 HandlerParams(UserHandle user) { 12183 mUser = user; 12184 } 12185 12186 UserHandle getUser() { 12187 return mUser; 12188 } 12189 12190 HandlerParams setTraceMethod(String traceMethod) { 12191 this.traceMethod = traceMethod; 12192 return this; 12193 } 12194 12195 HandlerParams setTraceCookie(int traceCookie) { 12196 this.traceCookie = traceCookie; 12197 return this; 12198 } 12199 12200 final boolean startCopy() { 12201 boolean res; 12202 try { 12203 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12204 12205 if (++mRetries > MAX_RETRIES) { 12206 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12207 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12208 handleServiceError(); 12209 return false; 12210 } else { 12211 handleStartCopy(); 12212 res = true; 12213 } 12214 } catch (RemoteException e) { 12215 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12216 mHandler.sendEmptyMessage(MCS_RECONNECT); 12217 res = false; 12218 } 12219 handleReturnCode(); 12220 return res; 12221 } 12222 12223 final void serviceError() { 12224 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12225 handleServiceError(); 12226 handleReturnCode(); 12227 } 12228 12229 abstract void handleStartCopy() throws RemoteException; 12230 abstract void handleServiceError(); 12231 abstract void handleReturnCode(); 12232 } 12233 12234 class MeasureParams extends HandlerParams { 12235 private final PackageStats mStats; 12236 private boolean mSuccess; 12237 12238 private final IPackageStatsObserver mObserver; 12239 12240 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12241 super(new UserHandle(stats.userHandle)); 12242 mObserver = observer; 12243 mStats = stats; 12244 } 12245 12246 @Override 12247 public String toString() { 12248 return "MeasureParams{" 12249 + Integer.toHexString(System.identityHashCode(this)) 12250 + " " + mStats.packageName + "}"; 12251 } 12252 12253 @Override 12254 void handleStartCopy() throws RemoteException { 12255 synchronized (mInstallLock) { 12256 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12257 } 12258 12259 if (mSuccess) { 12260 final boolean mounted; 12261 if (Environment.isExternalStorageEmulated()) { 12262 mounted = true; 12263 } else { 12264 final String status = Environment.getExternalStorageState(); 12265 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12266 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12267 } 12268 12269 if (mounted) { 12270 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12271 12272 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12273 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12274 12275 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12276 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12277 12278 // Always subtract cache size, since it's a subdirectory 12279 mStats.externalDataSize -= mStats.externalCacheSize; 12280 12281 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12282 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12283 12284 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12285 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12286 } 12287 } 12288 } 12289 12290 @Override 12291 void handleReturnCode() { 12292 if (mObserver != null) { 12293 try { 12294 mObserver.onGetStatsCompleted(mStats, mSuccess); 12295 } catch (RemoteException e) { 12296 Slog.i(TAG, "Observer no longer exists."); 12297 } 12298 } 12299 } 12300 12301 @Override 12302 void handleServiceError() { 12303 Slog.e(TAG, "Could not measure application " + mStats.packageName 12304 + " external storage"); 12305 } 12306 } 12307 12308 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12309 throws RemoteException { 12310 long result = 0; 12311 for (File path : paths) { 12312 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12313 } 12314 return result; 12315 } 12316 12317 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12318 for (File path : paths) { 12319 try { 12320 mcs.clearDirectory(path.getAbsolutePath()); 12321 } catch (RemoteException e) { 12322 } 12323 } 12324 } 12325 12326 static class OriginInfo { 12327 /** 12328 * Location where install is coming from, before it has been 12329 * copied/renamed into place. This could be a single monolithic APK 12330 * file, or a cluster directory. This location may be untrusted. 12331 */ 12332 final File file; 12333 final String cid; 12334 12335 /** 12336 * Flag indicating that {@link #file} or {@link #cid} has already been 12337 * staged, meaning downstream users don't need to defensively copy the 12338 * contents. 12339 */ 12340 final boolean staged; 12341 12342 /** 12343 * Flag indicating that {@link #file} or {@link #cid} is an already 12344 * installed app that is being moved. 12345 */ 12346 final boolean existing; 12347 12348 final String resolvedPath; 12349 final File resolvedFile; 12350 12351 static OriginInfo fromNothing() { 12352 return new OriginInfo(null, null, false, false); 12353 } 12354 12355 static OriginInfo fromUntrustedFile(File file) { 12356 return new OriginInfo(file, null, false, false); 12357 } 12358 12359 static OriginInfo fromExistingFile(File file) { 12360 return new OriginInfo(file, null, false, true); 12361 } 12362 12363 static OriginInfo fromStagedFile(File file) { 12364 return new OriginInfo(file, null, true, false); 12365 } 12366 12367 static OriginInfo fromStagedContainer(String cid) { 12368 return new OriginInfo(null, cid, true, false); 12369 } 12370 12371 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12372 this.file = file; 12373 this.cid = cid; 12374 this.staged = staged; 12375 this.existing = existing; 12376 12377 if (cid != null) { 12378 resolvedPath = PackageHelper.getSdDir(cid); 12379 resolvedFile = new File(resolvedPath); 12380 } else if (file != null) { 12381 resolvedPath = file.getAbsolutePath(); 12382 resolvedFile = file; 12383 } else { 12384 resolvedPath = null; 12385 resolvedFile = null; 12386 } 12387 } 12388 } 12389 12390 static class MoveInfo { 12391 final int moveId; 12392 final String fromUuid; 12393 final String toUuid; 12394 final String packageName; 12395 final String dataAppName; 12396 final int appId; 12397 final String seinfo; 12398 final int targetSdkVersion; 12399 12400 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12401 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12402 this.moveId = moveId; 12403 this.fromUuid = fromUuid; 12404 this.toUuid = toUuid; 12405 this.packageName = packageName; 12406 this.dataAppName = dataAppName; 12407 this.appId = appId; 12408 this.seinfo = seinfo; 12409 this.targetSdkVersion = targetSdkVersion; 12410 } 12411 } 12412 12413 static class VerificationInfo { 12414 /** A constant used to indicate that a uid value is not present. */ 12415 public static final int NO_UID = -1; 12416 12417 /** URI referencing where the package was downloaded from. */ 12418 final Uri originatingUri; 12419 12420 /** HTTP referrer URI associated with the originatingURI. */ 12421 final Uri referrer; 12422 12423 /** UID of the application that the install request originated from. */ 12424 final int originatingUid; 12425 12426 /** UID of application requesting the install */ 12427 final int installerUid; 12428 12429 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12430 this.originatingUri = originatingUri; 12431 this.referrer = referrer; 12432 this.originatingUid = originatingUid; 12433 this.installerUid = installerUid; 12434 } 12435 } 12436 12437 class InstallParams extends HandlerParams { 12438 final OriginInfo origin; 12439 final MoveInfo move; 12440 final IPackageInstallObserver2 observer; 12441 int installFlags; 12442 final String installerPackageName; 12443 final String volumeUuid; 12444 private InstallArgs mArgs; 12445 private int mRet; 12446 final String packageAbiOverride; 12447 final String[] grantedRuntimePermissions; 12448 final VerificationInfo verificationInfo; 12449 final Certificate[][] certificates; 12450 12451 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12452 int installFlags, String installerPackageName, String volumeUuid, 12453 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12454 String[] grantedPermissions, Certificate[][] certificates) { 12455 super(user); 12456 this.origin = origin; 12457 this.move = move; 12458 this.observer = observer; 12459 this.installFlags = installFlags; 12460 this.installerPackageName = installerPackageName; 12461 this.volumeUuid = volumeUuid; 12462 this.verificationInfo = verificationInfo; 12463 this.packageAbiOverride = packageAbiOverride; 12464 this.grantedRuntimePermissions = grantedPermissions; 12465 this.certificates = certificates; 12466 } 12467 12468 @Override 12469 public String toString() { 12470 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12471 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12472 } 12473 12474 private int installLocationPolicy(PackageInfoLite pkgLite) { 12475 String packageName = pkgLite.packageName; 12476 int installLocation = pkgLite.installLocation; 12477 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12478 // reader 12479 synchronized (mPackages) { 12480 // Currently installed package which the new package is attempting to replace or 12481 // null if no such package is installed. 12482 PackageParser.Package installedPkg = mPackages.get(packageName); 12483 // Package which currently owns the data which the new package will own if installed. 12484 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12485 // will be null whereas dataOwnerPkg will contain information about the package 12486 // which was uninstalled while keeping its data. 12487 PackageParser.Package dataOwnerPkg = installedPkg; 12488 if (dataOwnerPkg == null) { 12489 PackageSetting ps = mSettings.mPackages.get(packageName); 12490 if (ps != null) { 12491 dataOwnerPkg = ps.pkg; 12492 } 12493 } 12494 12495 if (dataOwnerPkg != null) { 12496 // If installed, the package will get access to data left on the device by its 12497 // predecessor. As a security measure, this is permited only if this is not a 12498 // version downgrade or if the predecessor package is marked as debuggable and 12499 // a downgrade is explicitly requested. 12500 // 12501 // On debuggable platform builds, downgrades are permitted even for 12502 // non-debuggable packages to make testing easier. Debuggable platform builds do 12503 // not offer security guarantees and thus it's OK to disable some security 12504 // mechanisms to make debugging/testing easier on those builds. However, even on 12505 // debuggable builds downgrades of packages are permitted only if requested via 12506 // installFlags. This is because we aim to keep the behavior of debuggable 12507 // platform builds as close as possible to the behavior of non-debuggable 12508 // platform builds. 12509 final boolean downgradeRequested = 12510 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12511 final boolean packageDebuggable = 12512 (dataOwnerPkg.applicationInfo.flags 12513 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12514 final boolean downgradePermitted = 12515 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12516 if (!downgradePermitted) { 12517 try { 12518 checkDowngrade(dataOwnerPkg, pkgLite); 12519 } catch (PackageManagerException e) { 12520 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12521 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12522 } 12523 } 12524 } 12525 12526 if (installedPkg != null) { 12527 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12528 // Check for updated system application. 12529 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12530 if (onSd) { 12531 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12532 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12533 } 12534 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12535 } else { 12536 if (onSd) { 12537 // Install flag overrides everything. 12538 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12539 } 12540 // If current upgrade specifies particular preference 12541 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12542 // Application explicitly specified internal. 12543 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12544 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12545 // App explictly prefers external. Let policy decide 12546 } else { 12547 // Prefer previous location 12548 if (isExternal(installedPkg)) { 12549 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12550 } 12551 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12552 } 12553 } 12554 } else { 12555 // Invalid install. Return error code 12556 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12557 } 12558 } 12559 } 12560 // All the special cases have been taken care of. 12561 // Return result based on recommended install location. 12562 if (onSd) { 12563 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12564 } 12565 return pkgLite.recommendedInstallLocation; 12566 } 12567 12568 /* 12569 * Invoke remote method to get package information and install 12570 * location values. Override install location based on default 12571 * policy if needed and then create install arguments based 12572 * on the install location. 12573 */ 12574 public void handleStartCopy() throws RemoteException { 12575 int ret = PackageManager.INSTALL_SUCCEEDED; 12576 12577 // If we're already staged, we've firmly committed to an install location 12578 if (origin.staged) { 12579 if (origin.file != null) { 12580 installFlags |= PackageManager.INSTALL_INTERNAL; 12581 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12582 } else if (origin.cid != null) { 12583 installFlags |= PackageManager.INSTALL_EXTERNAL; 12584 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12585 } else { 12586 throw new IllegalStateException("Invalid stage location"); 12587 } 12588 } 12589 12590 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12591 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12592 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12593 PackageInfoLite pkgLite = null; 12594 12595 if (onInt && onSd) { 12596 // Check if both bits are set. 12597 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12598 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12599 } else if (onSd && ephemeral) { 12600 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12601 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12602 } else { 12603 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12604 packageAbiOverride); 12605 12606 if (DEBUG_EPHEMERAL && ephemeral) { 12607 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12608 } 12609 12610 /* 12611 * If we have too little free space, try to free cache 12612 * before giving up. 12613 */ 12614 if (!origin.staged && pkgLite.recommendedInstallLocation 12615 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12616 // TODO: focus freeing disk space on the target device 12617 final StorageManager storage = StorageManager.from(mContext); 12618 final long lowThreshold = storage.getStorageLowBytes( 12619 Environment.getDataDirectory()); 12620 12621 final long sizeBytes = mContainerService.calculateInstalledSize( 12622 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12623 12624 try { 12625 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12626 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12627 installFlags, packageAbiOverride); 12628 } catch (InstallerException e) { 12629 Slog.w(TAG, "Failed to free cache", e); 12630 } 12631 12632 /* 12633 * The cache free must have deleted the file we 12634 * downloaded to install. 12635 * 12636 * TODO: fix the "freeCache" call to not delete 12637 * the file we care about. 12638 */ 12639 if (pkgLite.recommendedInstallLocation 12640 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12641 pkgLite.recommendedInstallLocation 12642 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12643 } 12644 } 12645 } 12646 12647 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12648 int loc = pkgLite.recommendedInstallLocation; 12649 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12650 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12651 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12652 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12653 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12654 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12655 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12656 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12657 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12658 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12659 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12660 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12661 } else { 12662 // Override with defaults if needed. 12663 loc = installLocationPolicy(pkgLite); 12664 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12665 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12666 } else if (!onSd && !onInt) { 12667 // Override install location with flags 12668 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12669 // Set the flag to install on external media. 12670 installFlags |= PackageManager.INSTALL_EXTERNAL; 12671 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12672 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12673 if (DEBUG_EPHEMERAL) { 12674 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12675 } 12676 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12677 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12678 |PackageManager.INSTALL_INTERNAL); 12679 } else { 12680 // Make sure the flag for installing on external 12681 // media is unset 12682 installFlags |= PackageManager.INSTALL_INTERNAL; 12683 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12684 } 12685 } 12686 } 12687 } 12688 12689 final InstallArgs args = createInstallArgs(this); 12690 mArgs = args; 12691 12692 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12693 // TODO: http://b/22976637 12694 // Apps installed for "all" users use the device owner to verify the app 12695 UserHandle verifierUser = getUser(); 12696 if (verifierUser == UserHandle.ALL) { 12697 verifierUser = UserHandle.SYSTEM; 12698 } 12699 12700 /* 12701 * Determine if we have any installed package verifiers. If we 12702 * do, then we'll defer to them to verify the packages. 12703 */ 12704 final int requiredUid = mRequiredVerifierPackage == null ? -1 12705 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12706 verifierUser.getIdentifier()); 12707 if (!origin.existing && requiredUid != -1 12708 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12709 final Intent verification = new Intent( 12710 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12711 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12712 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12713 PACKAGE_MIME_TYPE); 12714 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12715 12716 // Query all live verifiers based on current user state 12717 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12718 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12719 12720 if (DEBUG_VERIFY) { 12721 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12722 + verification.toString() + " with " + pkgLite.verifiers.length 12723 + " optional verifiers"); 12724 } 12725 12726 final int verificationId = mPendingVerificationToken++; 12727 12728 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12729 12730 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12731 installerPackageName); 12732 12733 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12734 installFlags); 12735 12736 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12737 pkgLite.packageName); 12738 12739 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12740 pkgLite.versionCode); 12741 12742 if (verificationInfo != null) { 12743 if (verificationInfo.originatingUri != null) { 12744 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12745 verificationInfo.originatingUri); 12746 } 12747 if (verificationInfo.referrer != null) { 12748 verification.putExtra(Intent.EXTRA_REFERRER, 12749 verificationInfo.referrer); 12750 } 12751 if (verificationInfo.originatingUid >= 0) { 12752 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12753 verificationInfo.originatingUid); 12754 } 12755 if (verificationInfo.installerUid >= 0) { 12756 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12757 verificationInfo.installerUid); 12758 } 12759 } 12760 12761 final PackageVerificationState verificationState = new PackageVerificationState( 12762 requiredUid, args); 12763 12764 mPendingVerification.append(verificationId, verificationState); 12765 12766 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12767 receivers, verificationState); 12768 12769 /* 12770 * If any sufficient verifiers were listed in the package 12771 * manifest, attempt to ask them. 12772 */ 12773 if (sufficientVerifiers != null) { 12774 final int N = sufficientVerifiers.size(); 12775 if (N == 0) { 12776 Slog.i(TAG, "Additional verifiers required, but none installed."); 12777 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12778 } else { 12779 for (int i = 0; i < N; i++) { 12780 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12781 12782 final Intent sufficientIntent = new Intent(verification); 12783 sufficientIntent.setComponent(verifierComponent); 12784 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12785 } 12786 } 12787 } 12788 12789 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12790 mRequiredVerifierPackage, receivers); 12791 if (ret == PackageManager.INSTALL_SUCCEEDED 12792 && mRequiredVerifierPackage != null) { 12793 Trace.asyncTraceBegin( 12794 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12795 /* 12796 * Send the intent to the required verification agent, 12797 * but only start the verification timeout after the 12798 * target BroadcastReceivers have run. 12799 */ 12800 verification.setComponent(requiredVerifierComponent); 12801 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12802 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12803 new BroadcastReceiver() { 12804 @Override 12805 public void onReceive(Context context, Intent intent) { 12806 final Message msg = mHandler 12807 .obtainMessage(CHECK_PENDING_VERIFICATION); 12808 msg.arg1 = verificationId; 12809 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12810 } 12811 }, null, 0, null, null); 12812 12813 /* 12814 * We don't want the copy to proceed until verification 12815 * succeeds, so null out this field. 12816 */ 12817 mArgs = null; 12818 } 12819 } else { 12820 /* 12821 * No package verification is enabled, so immediately start 12822 * the remote call to initiate copy using temporary file. 12823 */ 12824 ret = args.copyApk(mContainerService, true); 12825 } 12826 } 12827 12828 mRet = ret; 12829 } 12830 12831 @Override 12832 void handleReturnCode() { 12833 // If mArgs is null, then MCS couldn't be reached. When it 12834 // reconnects, it will try again to install. At that point, this 12835 // will succeed. 12836 if (mArgs != null) { 12837 processPendingInstall(mArgs, mRet); 12838 } 12839 } 12840 12841 @Override 12842 void handleServiceError() { 12843 mArgs = createInstallArgs(this); 12844 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12845 } 12846 12847 public boolean isForwardLocked() { 12848 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12849 } 12850 } 12851 12852 /** 12853 * Used during creation of InstallArgs 12854 * 12855 * @param installFlags package installation flags 12856 * @return true if should be installed on external storage 12857 */ 12858 private static boolean installOnExternalAsec(int installFlags) { 12859 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12860 return false; 12861 } 12862 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12863 return true; 12864 } 12865 return false; 12866 } 12867 12868 /** 12869 * Used during creation of InstallArgs 12870 * 12871 * @param installFlags package installation flags 12872 * @return true if should be installed as forward locked 12873 */ 12874 private static boolean installForwardLocked(int installFlags) { 12875 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12876 } 12877 12878 private InstallArgs createInstallArgs(InstallParams params) { 12879 if (params.move != null) { 12880 return new MoveInstallArgs(params); 12881 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12882 return new AsecInstallArgs(params); 12883 } else { 12884 return new FileInstallArgs(params); 12885 } 12886 } 12887 12888 /** 12889 * Create args that describe an existing installed package. Typically used 12890 * when cleaning up old installs, or used as a move source. 12891 */ 12892 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12893 String resourcePath, String[] instructionSets) { 12894 final boolean isInAsec; 12895 if (installOnExternalAsec(installFlags)) { 12896 /* Apps on SD card are always in ASEC containers. */ 12897 isInAsec = true; 12898 } else if (installForwardLocked(installFlags) 12899 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12900 /* 12901 * Forward-locked apps are only in ASEC containers if they're the 12902 * new style 12903 */ 12904 isInAsec = true; 12905 } else { 12906 isInAsec = false; 12907 } 12908 12909 if (isInAsec) { 12910 return new AsecInstallArgs(codePath, instructionSets, 12911 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12912 } else { 12913 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12914 } 12915 } 12916 12917 static abstract class InstallArgs { 12918 /** @see InstallParams#origin */ 12919 final OriginInfo origin; 12920 /** @see InstallParams#move */ 12921 final MoveInfo move; 12922 12923 final IPackageInstallObserver2 observer; 12924 // Always refers to PackageManager flags only 12925 final int installFlags; 12926 final String installerPackageName; 12927 final String volumeUuid; 12928 final UserHandle user; 12929 final String abiOverride; 12930 final String[] installGrantPermissions; 12931 /** If non-null, drop an async trace when the install completes */ 12932 final String traceMethod; 12933 final int traceCookie; 12934 final Certificate[][] certificates; 12935 12936 // The list of instruction sets supported by this app. This is currently 12937 // only used during the rmdex() phase to clean up resources. We can get rid of this 12938 // if we move dex files under the common app path. 12939 /* nullable */ String[] instructionSets; 12940 12941 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12942 int installFlags, String installerPackageName, String volumeUuid, 12943 UserHandle user, String[] instructionSets, 12944 String abiOverride, String[] installGrantPermissions, 12945 String traceMethod, int traceCookie, Certificate[][] certificates) { 12946 this.origin = origin; 12947 this.move = move; 12948 this.installFlags = installFlags; 12949 this.observer = observer; 12950 this.installerPackageName = installerPackageName; 12951 this.volumeUuid = volumeUuid; 12952 this.user = user; 12953 this.instructionSets = instructionSets; 12954 this.abiOverride = abiOverride; 12955 this.installGrantPermissions = installGrantPermissions; 12956 this.traceMethod = traceMethod; 12957 this.traceCookie = traceCookie; 12958 this.certificates = certificates; 12959 } 12960 12961 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12962 abstract int doPreInstall(int status); 12963 12964 /** 12965 * Rename package into final resting place. All paths on the given 12966 * scanned package should be updated to reflect the rename. 12967 */ 12968 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12969 abstract int doPostInstall(int status, int uid); 12970 12971 /** @see PackageSettingBase#codePathString */ 12972 abstract String getCodePath(); 12973 /** @see PackageSettingBase#resourcePathString */ 12974 abstract String getResourcePath(); 12975 12976 // Need installer lock especially for dex file removal. 12977 abstract void cleanUpResourcesLI(); 12978 abstract boolean doPostDeleteLI(boolean delete); 12979 12980 /** 12981 * Called before the source arguments are copied. This is used mostly 12982 * for MoveParams when it needs to read the source file to put it in the 12983 * destination. 12984 */ 12985 int doPreCopy() { 12986 return PackageManager.INSTALL_SUCCEEDED; 12987 } 12988 12989 /** 12990 * Called after the source arguments are copied. This is used mostly for 12991 * MoveParams when it needs to read the source file to put it in the 12992 * destination. 12993 */ 12994 int doPostCopy(int uid) { 12995 return PackageManager.INSTALL_SUCCEEDED; 12996 } 12997 12998 protected boolean isFwdLocked() { 12999 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13000 } 13001 13002 protected boolean isExternalAsec() { 13003 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13004 } 13005 13006 protected boolean isEphemeral() { 13007 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13008 } 13009 13010 UserHandle getUser() { 13011 return user; 13012 } 13013 } 13014 13015 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13016 if (!allCodePaths.isEmpty()) { 13017 if (instructionSets == null) { 13018 throw new IllegalStateException("instructionSet == null"); 13019 } 13020 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13021 for (String codePath : allCodePaths) { 13022 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13023 try { 13024 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13025 } catch (InstallerException ignored) { 13026 } 13027 } 13028 } 13029 } 13030 } 13031 13032 /** 13033 * Logic to handle installation of non-ASEC applications, including copying 13034 * and renaming logic. 13035 */ 13036 class FileInstallArgs extends InstallArgs { 13037 private File codeFile; 13038 private File resourceFile; 13039 13040 // Example topology: 13041 // /data/app/com.example/base.apk 13042 // /data/app/com.example/split_foo.apk 13043 // /data/app/com.example/lib/arm/libfoo.so 13044 // /data/app/com.example/lib/arm64/libfoo.so 13045 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13046 13047 /** New install */ 13048 FileInstallArgs(InstallParams params) { 13049 super(params.origin, params.move, params.observer, params.installFlags, 13050 params.installerPackageName, params.volumeUuid, 13051 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13052 params.grantedRuntimePermissions, 13053 params.traceMethod, params.traceCookie, params.certificates); 13054 if (isFwdLocked()) { 13055 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13056 } 13057 } 13058 13059 /** Existing install */ 13060 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13061 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13062 null, null, null, 0, null /*certificates*/); 13063 this.codeFile = (codePath != null) ? new File(codePath) : null; 13064 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13065 } 13066 13067 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13068 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13069 try { 13070 return doCopyApk(imcs, temp); 13071 } finally { 13072 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13073 } 13074 } 13075 13076 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13077 if (origin.staged) { 13078 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13079 codeFile = origin.file; 13080 resourceFile = origin.file; 13081 return PackageManager.INSTALL_SUCCEEDED; 13082 } 13083 13084 try { 13085 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13086 final File tempDir = 13087 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13088 codeFile = tempDir; 13089 resourceFile = tempDir; 13090 } catch (IOException e) { 13091 Slog.w(TAG, "Failed to create copy file: " + e); 13092 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13093 } 13094 13095 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13096 @Override 13097 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13098 if (!FileUtils.isValidExtFilename(name)) { 13099 throw new IllegalArgumentException("Invalid filename: " + name); 13100 } 13101 try { 13102 final File file = new File(codeFile, name); 13103 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13104 O_RDWR | O_CREAT, 0644); 13105 Os.chmod(file.getAbsolutePath(), 0644); 13106 return new ParcelFileDescriptor(fd); 13107 } catch (ErrnoException e) { 13108 throw new RemoteException("Failed to open: " + e.getMessage()); 13109 } 13110 } 13111 }; 13112 13113 int ret = PackageManager.INSTALL_SUCCEEDED; 13114 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13115 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13116 Slog.e(TAG, "Failed to copy package"); 13117 return ret; 13118 } 13119 13120 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13121 NativeLibraryHelper.Handle handle = null; 13122 try { 13123 handle = NativeLibraryHelper.Handle.create(codeFile); 13124 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13125 abiOverride); 13126 } catch (IOException e) { 13127 Slog.e(TAG, "Copying native libraries failed", e); 13128 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13129 } finally { 13130 IoUtils.closeQuietly(handle); 13131 } 13132 13133 return ret; 13134 } 13135 13136 int doPreInstall(int status) { 13137 if (status != PackageManager.INSTALL_SUCCEEDED) { 13138 cleanUp(); 13139 } 13140 return status; 13141 } 13142 13143 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13144 if (status != PackageManager.INSTALL_SUCCEEDED) { 13145 cleanUp(); 13146 return false; 13147 } 13148 13149 final File targetDir = codeFile.getParentFile(); 13150 final File beforeCodeFile = codeFile; 13151 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13152 13153 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13154 try { 13155 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13156 } catch (ErrnoException e) { 13157 Slog.w(TAG, "Failed to rename", e); 13158 return false; 13159 } 13160 13161 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13162 Slog.w(TAG, "Failed to restorecon"); 13163 return false; 13164 } 13165 13166 // Reflect the rename internally 13167 codeFile = afterCodeFile; 13168 resourceFile = afterCodeFile; 13169 13170 // Reflect the rename in scanned details 13171 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13172 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13173 afterCodeFile, pkg.baseCodePath)); 13174 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13175 afterCodeFile, pkg.splitCodePaths)); 13176 13177 // Reflect the rename in app info 13178 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13179 pkg.setApplicationInfoCodePath(pkg.codePath); 13180 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13181 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13182 pkg.setApplicationInfoResourcePath(pkg.codePath); 13183 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13184 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13185 13186 return true; 13187 } 13188 13189 int doPostInstall(int status, int uid) { 13190 if (status != PackageManager.INSTALL_SUCCEEDED) { 13191 cleanUp(); 13192 } 13193 return status; 13194 } 13195 13196 @Override 13197 String getCodePath() { 13198 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13199 } 13200 13201 @Override 13202 String getResourcePath() { 13203 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13204 } 13205 13206 private boolean cleanUp() { 13207 if (codeFile == null || !codeFile.exists()) { 13208 return false; 13209 } 13210 13211 removeCodePathLI(codeFile); 13212 13213 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13214 resourceFile.delete(); 13215 } 13216 13217 return true; 13218 } 13219 13220 void cleanUpResourcesLI() { 13221 // Try enumerating all code paths before deleting 13222 List<String> allCodePaths = Collections.EMPTY_LIST; 13223 if (codeFile != null && codeFile.exists()) { 13224 try { 13225 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13226 allCodePaths = pkg.getAllCodePaths(); 13227 } catch (PackageParserException e) { 13228 // Ignored; we tried our best 13229 } 13230 } 13231 13232 cleanUp(); 13233 removeDexFiles(allCodePaths, instructionSets); 13234 } 13235 13236 boolean doPostDeleteLI(boolean delete) { 13237 // XXX err, shouldn't we respect the delete flag? 13238 cleanUpResourcesLI(); 13239 return true; 13240 } 13241 } 13242 13243 private boolean isAsecExternal(String cid) { 13244 final String asecPath = PackageHelper.getSdFilesystem(cid); 13245 return !asecPath.startsWith(mAsecInternalPath); 13246 } 13247 13248 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13249 PackageManagerException { 13250 if (copyRet < 0) { 13251 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13252 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13253 throw new PackageManagerException(copyRet, message); 13254 } 13255 } 13256 } 13257 13258 /** 13259 * Extract the MountService "container ID" from the full code path of an 13260 * .apk. 13261 */ 13262 static String cidFromCodePath(String fullCodePath) { 13263 int eidx = fullCodePath.lastIndexOf("/"); 13264 String subStr1 = fullCodePath.substring(0, eidx); 13265 int sidx = subStr1.lastIndexOf("/"); 13266 return subStr1.substring(sidx+1, eidx); 13267 } 13268 13269 /** 13270 * Logic to handle installation of ASEC applications, including copying and 13271 * renaming logic. 13272 */ 13273 class AsecInstallArgs extends InstallArgs { 13274 static final String RES_FILE_NAME = "pkg.apk"; 13275 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13276 13277 String cid; 13278 String packagePath; 13279 String resourcePath; 13280 13281 /** New install */ 13282 AsecInstallArgs(InstallParams params) { 13283 super(params.origin, params.move, params.observer, params.installFlags, 13284 params.installerPackageName, params.volumeUuid, 13285 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13286 params.grantedRuntimePermissions, 13287 params.traceMethod, params.traceCookie, params.certificates); 13288 } 13289 13290 /** Existing install */ 13291 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13292 boolean isExternal, boolean isForwardLocked) { 13293 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13294 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13295 instructionSets, null, null, null, 0, null /*certificates*/); 13296 // Hackily pretend we're still looking at a full code path 13297 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13298 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13299 } 13300 13301 // Extract cid from fullCodePath 13302 int eidx = fullCodePath.lastIndexOf("/"); 13303 String subStr1 = fullCodePath.substring(0, eidx); 13304 int sidx = subStr1.lastIndexOf("/"); 13305 cid = subStr1.substring(sidx+1, eidx); 13306 setMountPath(subStr1); 13307 } 13308 13309 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13310 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13311 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13312 instructionSets, null, null, null, 0, null /*certificates*/); 13313 this.cid = cid; 13314 setMountPath(PackageHelper.getSdDir(cid)); 13315 } 13316 13317 void createCopyFile() { 13318 cid = mInstallerService.allocateExternalStageCidLegacy(); 13319 } 13320 13321 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13322 if (origin.staged && origin.cid != null) { 13323 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13324 cid = origin.cid; 13325 setMountPath(PackageHelper.getSdDir(cid)); 13326 return PackageManager.INSTALL_SUCCEEDED; 13327 } 13328 13329 if (temp) { 13330 createCopyFile(); 13331 } else { 13332 /* 13333 * Pre-emptively destroy the container since it's destroyed if 13334 * copying fails due to it existing anyway. 13335 */ 13336 PackageHelper.destroySdDir(cid); 13337 } 13338 13339 final String newMountPath = imcs.copyPackageToContainer( 13340 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13341 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13342 13343 if (newMountPath != null) { 13344 setMountPath(newMountPath); 13345 return PackageManager.INSTALL_SUCCEEDED; 13346 } else { 13347 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13348 } 13349 } 13350 13351 @Override 13352 String getCodePath() { 13353 return packagePath; 13354 } 13355 13356 @Override 13357 String getResourcePath() { 13358 return resourcePath; 13359 } 13360 13361 int doPreInstall(int status) { 13362 if (status != PackageManager.INSTALL_SUCCEEDED) { 13363 // Destroy container 13364 PackageHelper.destroySdDir(cid); 13365 } else { 13366 boolean mounted = PackageHelper.isContainerMounted(cid); 13367 if (!mounted) { 13368 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13369 Process.SYSTEM_UID); 13370 if (newMountPath != null) { 13371 setMountPath(newMountPath); 13372 } else { 13373 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13374 } 13375 } 13376 } 13377 return status; 13378 } 13379 13380 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13381 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13382 String newMountPath = null; 13383 if (PackageHelper.isContainerMounted(cid)) { 13384 // Unmount the container 13385 if (!PackageHelper.unMountSdDir(cid)) { 13386 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13387 return false; 13388 } 13389 } 13390 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13391 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13392 " which might be stale. Will try to clean up."); 13393 // Clean up the stale container and proceed to recreate. 13394 if (!PackageHelper.destroySdDir(newCacheId)) { 13395 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13396 return false; 13397 } 13398 // Successfully cleaned up stale container. Try to rename again. 13399 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13400 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13401 + " inspite of cleaning it up."); 13402 return false; 13403 } 13404 } 13405 if (!PackageHelper.isContainerMounted(newCacheId)) { 13406 Slog.w(TAG, "Mounting container " + newCacheId); 13407 newMountPath = PackageHelper.mountSdDir(newCacheId, 13408 getEncryptKey(), Process.SYSTEM_UID); 13409 } else { 13410 newMountPath = PackageHelper.getSdDir(newCacheId); 13411 } 13412 if (newMountPath == null) { 13413 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13414 return false; 13415 } 13416 Log.i(TAG, "Succesfully renamed " + cid + 13417 " to " + newCacheId + 13418 " at new path: " + newMountPath); 13419 cid = newCacheId; 13420 13421 final File beforeCodeFile = new File(packagePath); 13422 setMountPath(newMountPath); 13423 final File afterCodeFile = new File(packagePath); 13424 13425 // Reflect the rename in scanned details 13426 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13427 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13428 afterCodeFile, pkg.baseCodePath)); 13429 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13430 afterCodeFile, pkg.splitCodePaths)); 13431 13432 // Reflect the rename in app info 13433 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13434 pkg.setApplicationInfoCodePath(pkg.codePath); 13435 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13436 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13437 pkg.setApplicationInfoResourcePath(pkg.codePath); 13438 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13439 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13440 13441 return true; 13442 } 13443 13444 private void setMountPath(String mountPath) { 13445 final File mountFile = new File(mountPath); 13446 13447 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13448 if (monolithicFile.exists()) { 13449 packagePath = monolithicFile.getAbsolutePath(); 13450 if (isFwdLocked()) { 13451 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13452 } else { 13453 resourcePath = packagePath; 13454 } 13455 } else { 13456 packagePath = mountFile.getAbsolutePath(); 13457 resourcePath = packagePath; 13458 } 13459 } 13460 13461 int doPostInstall(int status, int uid) { 13462 if (status != PackageManager.INSTALL_SUCCEEDED) { 13463 cleanUp(); 13464 } else { 13465 final int groupOwner; 13466 final String protectedFile; 13467 if (isFwdLocked()) { 13468 groupOwner = UserHandle.getSharedAppGid(uid); 13469 protectedFile = RES_FILE_NAME; 13470 } else { 13471 groupOwner = -1; 13472 protectedFile = null; 13473 } 13474 13475 if (uid < Process.FIRST_APPLICATION_UID 13476 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13477 Slog.e(TAG, "Failed to finalize " + cid); 13478 PackageHelper.destroySdDir(cid); 13479 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13480 } 13481 13482 boolean mounted = PackageHelper.isContainerMounted(cid); 13483 if (!mounted) { 13484 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13485 } 13486 } 13487 return status; 13488 } 13489 13490 private void cleanUp() { 13491 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13492 13493 // Destroy secure container 13494 PackageHelper.destroySdDir(cid); 13495 } 13496 13497 private List<String> getAllCodePaths() { 13498 final File codeFile = new File(getCodePath()); 13499 if (codeFile != null && codeFile.exists()) { 13500 try { 13501 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13502 return pkg.getAllCodePaths(); 13503 } catch (PackageParserException e) { 13504 // Ignored; we tried our best 13505 } 13506 } 13507 return Collections.EMPTY_LIST; 13508 } 13509 13510 void cleanUpResourcesLI() { 13511 // Enumerate all code paths before deleting 13512 cleanUpResourcesLI(getAllCodePaths()); 13513 } 13514 13515 private void cleanUpResourcesLI(List<String> allCodePaths) { 13516 cleanUp(); 13517 removeDexFiles(allCodePaths, instructionSets); 13518 } 13519 13520 String getPackageName() { 13521 return getAsecPackageName(cid); 13522 } 13523 13524 boolean doPostDeleteLI(boolean delete) { 13525 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13526 final List<String> allCodePaths = getAllCodePaths(); 13527 boolean mounted = PackageHelper.isContainerMounted(cid); 13528 if (mounted) { 13529 // Unmount first 13530 if (PackageHelper.unMountSdDir(cid)) { 13531 mounted = false; 13532 } 13533 } 13534 if (!mounted && delete) { 13535 cleanUpResourcesLI(allCodePaths); 13536 } 13537 return !mounted; 13538 } 13539 13540 @Override 13541 int doPreCopy() { 13542 if (isFwdLocked()) { 13543 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13544 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13545 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13546 } 13547 } 13548 13549 return PackageManager.INSTALL_SUCCEEDED; 13550 } 13551 13552 @Override 13553 int doPostCopy(int uid) { 13554 if (isFwdLocked()) { 13555 if (uid < Process.FIRST_APPLICATION_UID 13556 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13557 RES_FILE_NAME)) { 13558 Slog.e(TAG, "Failed to finalize " + cid); 13559 PackageHelper.destroySdDir(cid); 13560 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13561 } 13562 } 13563 13564 return PackageManager.INSTALL_SUCCEEDED; 13565 } 13566 } 13567 13568 /** 13569 * Logic to handle movement of existing installed applications. 13570 */ 13571 class MoveInstallArgs extends InstallArgs { 13572 private File codeFile; 13573 private File resourceFile; 13574 13575 /** New install */ 13576 MoveInstallArgs(InstallParams params) { 13577 super(params.origin, params.move, params.observer, params.installFlags, 13578 params.installerPackageName, params.volumeUuid, 13579 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13580 params.grantedRuntimePermissions, 13581 params.traceMethod, params.traceCookie, params.certificates); 13582 } 13583 13584 int copyApk(IMediaContainerService imcs, boolean temp) { 13585 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13586 + move.fromUuid + " to " + move.toUuid); 13587 synchronized (mInstaller) { 13588 try { 13589 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13590 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13591 } catch (InstallerException e) { 13592 Slog.w(TAG, "Failed to move app", e); 13593 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13594 } 13595 } 13596 13597 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13598 resourceFile = codeFile; 13599 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13600 13601 return PackageManager.INSTALL_SUCCEEDED; 13602 } 13603 13604 int doPreInstall(int status) { 13605 if (status != PackageManager.INSTALL_SUCCEEDED) { 13606 cleanUp(move.toUuid); 13607 } 13608 return status; 13609 } 13610 13611 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13612 if (status != PackageManager.INSTALL_SUCCEEDED) { 13613 cleanUp(move.toUuid); 13614 return false; 13615 } 13616 13617 // Reflect the move in app info 13618 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13619 pkg.setApplicationInfoCodePath(pkg.codePath); 13620 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13621 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13622 pkg.setApplicationInfoResourcePath(pkg.codePath); 13623 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13624 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13625 13626 return true; 13627 } 13628 13629 int doPostInstall(int status, int uid) { 13630 if (status == PackageManager.INSTALL_SUCCEEDED) { 13631 cleanUp(move.fromUuid); 13632 } else { 13633 cleanUp(move.toUuid); 13634 } 13635 return status; 13636 } 13637 13638 @Override 13639 String getCodePath() { 13640 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13641 } 13642 13643 @Override 13644 String getResourcePath() { 13645 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13646 } 13647 13648 private boolean cleanUp(String volumeUuid) { 13649 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13650 move.dataAppName); 13651 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13652 final int[] userIds = sUserManager.getUserIds(); 13653 synchronized (mInstallLock) { 13654 // Clean up both app data and code 13655 // All package moves are frozen until finished 13656 for (int userId : userIds) { 13657 try { 13658 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13659 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13660 } catch (InstallerException e) { 13661 Slog.w(TAG, String.valueOf(e)); 13662 } 13663 } 13664 removeCodePathLI(codeFile); 13665 } 13666 return true; 13667 } 13668 13669 void cleanUpResourcesLI() { 13670 throw new UnsupportedOperationException(); 13671 } 13672 13673 boolean doPostDeleteLI(boolean delete) { 13674 throw new UnsupportedOperationException(); 13675 } 13676 } 13677 13678 static String getAsecPackageName(String packageCid) { 13679 int idx = packageCid.lastIndexOf("-"); 13680 if (idx == -1) { 13681 return packageCid; 13682 } 13683 return packageCid.substring(0, idx); 13684 } 13685 13686 // Utility method used to create code paths based on package name and available index. 13687 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13688 String idxStr = ""; 13689 int idx = 1; 13690 // Fall back to default value of idx=1 if prefix is not 13691 // part of oldCodePath 13692 if (oldCodePath != null) { 13693 String subStr = oldCodePath; 13694 // Drop the suffix right away 13695 if (suffix != null && subStr.endsWith(suffix)) { 13696 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13697 } 13698 // If oldCodePath already contains prefix find out the 13699 // ending index to either increment or decrement. 13700 int sidx = subStr.lastIndexOf(prefix); 13701 if (sidx != -1) { 13702 subStr = subStr.substring(sidx + prefix.length()); 13703 if (subStr != null) { 13704 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13705 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13706 } 13707 try { 13708 idx = Integer.parseInt(subStr); 13709 if (idx <= 1) { 13710 idx++; 13711 } else { 13712 idx--; 13713 } 13714 } catch(NumberFormatException e) { 13715 } 13716 } 13717 } 13718 } 13719 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13720 return prefix + idxStr; 13721 } 13722 13723 private File getNextCodePath(File targetDir, String packageName) { 13724 int suffix = 1; 13725 File result; 13726 do { 13727 result = new File(targetDir, packageName + "-" + suffix); 13728 suffix++; 13729 } while (result.exists()); 13730 return result; 13731 } 13732 13733 // Utility method that returns the relative package path with respect 13734 // to the installation directory. Like say for /data/data/com.test-1.apk 13735 // string com.test-1 is returned. 13736 static String deriveCodePathName(String codePath) { 13737 if (codePath == null) { 13738 return null; 13739 } 13740 final File codeFile = new File(codePath); 13741 final String name = codeFile.getName(); 13742 if (codeFile.isDirectory()) { 13743 return name; 13744 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13745 final int lastDot = name.lastIndexOf('.'); 13746 return name.substring(0, lastDot); 13747 } else { 13748 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13749 return null; 13750 } 13751 } 13752 13753 static class PackageInstalledInfo { 13754 String name; 13755 int uid; 13756 // The set of users that originally had this package installed. 13757 int[] origUsers; 13758 // The set of users that now have this package installed. 13759 int[] newUsers; 13760 PackageParser.Package pkg; 13761 int returnCode; 13762 String returnMsg; 13763 PackageRemovedInfo removedInfo; 13764 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13765 13766 public void setError(int code, String msg) { 13767 setReturnCode(code); 13768 setReturnMessage(msg); 13769 Slog.w(TAG, msg); 13770 } 13771 13772 public void setError(String msg, PackageParserException e) { 13773 setReturnCode(e.error); 13774 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13775 Slog.w(TAG, msg, e); 13776 } 13777 13778 public void setError(String msg, PackageManagerException e) { 13779 returnCode = e.error; 13780 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13781 Slog.w(TAG, msg, e); 13782 } 13783 13784 public void setReturnCode(int returnCode) { 13785 this.returnCode = returnCode; 13786 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13787 for (int i = 0; i < childCount; i++) { 13788 addedChildPackages.valueAt(i).returnCode = returnCode; 13789 } 13790 } 13791 13792 private void setReturnMessage(String returnMsg) { 13793 this.returnMsg = returnMsg; 13794 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13795 for (int i = 0; i < childCount; i++) { 13796 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13797 } 13798 } 13799 13800 // In some error cases we want to convey more info back to the observer 13801 String origPackage; 13802 String origPermission; 13803 } 13804 13805 /* 13806 * Install a non-existing package. 13807 */ 13808 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13809 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13810 PackageInstalledInfo res) { 13811 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13812 13813 // Remember this for later, in case we need to rollback this install 13814 String pkgName = pkg.packageName; 13815 13816 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13817 13818 synchronized(mPackages) { 13819 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13820 // A package with the same name is already installed, though 13821 // it has been renamed to an older name. The package we 13822 // are trying to install should be installed as an update to 13823 // the existing one, but that has not been requested, so bail. 13824 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13825 + " without first uninstalling package running as " 13826 + mSettings.mRenamedPackages.get(pkgName)); 13827 return; 13828 } 13829 if (mPackages.containsKey(pkgName)) { 13830 // Don't allow installation over an existing package with the same name. 13831 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13832 + " without first uninstalling."); 13833 return; 13834 } 13835 } 13836 13837 try { 13838 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13839 System.currentTimeMillis(), user); 13840 13841 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13842 13843 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13844 prepareAppDataAfterInstallLIF(newPackage); 13845 13846 } else { 13847 // Remove package from internal structures, but keep around any 13848 // data that might have already existed 13849 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13850 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13851 } 13852 } catch (PackageManagerException e) { 13853 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13854 } 13855 13856 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13857 } 13858 13859 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13860 // Can't rotate keys during boot or if sharedUser. 13861 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13862 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13863 return false; 13864 } 13865 // app is using upgradeKeySets; make sure all are valid 13866 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13867 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13868 for (int i = 0; i < upgradeKeySets.length; i++) { 13869 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13870 Slog.wtf(TAG, "Package " 13871 + (oldPs.name != null ? oldPs.name : "<null>") 13872 + " contains upgrade-key-set reference to unknown key-set: " 13873 + upgradeKeySets[i] 13874 + " reverting to signatures check."); 13875 return false; 13876 } 13877 } 13878 return true; 13879 } 13880 13881 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13882 // Upgrade keysets are being used. Determine if new package has a superset of the 13883 // required keys. 13884 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13885 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13886 for (int i = 0; i < upgradeKeySets.length; i++) { 13887 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13888 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13889 return true; 13890 } 13891 } 13892 return false; 13893 } 13894 13895 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13896 try (DigestInputStream digestStream = 13897 new DigestInputStream(new FileInputStream(file), digest)) { 13898 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13899 } 13900 } 13901 13902 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13903 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13904 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13905 13906 final PackageParser.Package oldPackage; 13907 final String pkgName = pkg.packageName; 13908 final int[] allUsers; 13909 final int[] installedUsers; 13910 13911 synchronized(mPackages) { 13912 oldPackage = mPackages.get(pkgName); 13913 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13914 13915 // don't allow upgrade to target a release SDK from a pre-release SDK 13916 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13917 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13918 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13919 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13920 if (oldTargetsPreRelease 13921 && !newTargetsPreRelease 13922 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13923 Slog.w(TAG, "Can't install package targeting released sdk"); 13924 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13925 return; 13926 } 13927 13928 // don't allow an upgrade from full to ephemeral 13929 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13930 if (isEphemeral && !oldIsEphemeral) { 13931 // can't downgrade from full to ephemeral 13932 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13933 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13934 return; 13935 } 13936 13937 // verify signatures are valid 13938 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13939 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13940 if (!checkUpgradeKeySetLP(ps, pkg)) { 13941 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13942 "New package not signed by keys specified by upgrade-keysets: " 13943 + pkgName); 13944 return; 13945 } 13946 } else { 13947 // default to original signature matching 13948 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13949 != PackageManager.SIGNATURE_MATCH) { 13950 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13951 "New package has a different signature: " + pkgName); 13952 return; 13953 } 13954 } 13955 13956 // don't allow a system upgrade unless the upgrade hash matches 13957 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13958 byte[] digestBytes = null; 13959 try { 13960 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13961 updateDigest(digest, new File(pkg.baseCodePath)); 13962 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13963 for (String path : pkg.splitCodePaths) { 13964 updateDigest(digest, new File(path)); 13965 } 13966 } 13967 digestBytes = digest.digest(); 13968 } catch (NoSuchAlgorithmException | IOException e) { 13969 res.setError(INSTALL_FAILED_INVALID_APK, 13970 "Could not compute hash: " + pkgName); 13971 return; 13972 } 13973 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13974 res.setError(INSTALL_FAILED_INVALID_APK, 13975 "New package fails restrict-update check: " + pkgName); 13976 return; 13977 } 13978 // retain upgrade restriction 13979 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13980 } 13981 13982 // Check for shared user id changes 13983 String invalidPackageName = 13984 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13985 if (invalidPackageName != null) { 13986 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13987 "Package " + invalidPackageName + " tried to change user " 13988 + oldPackage.mSharedUserId); 13989 return; 13990 } 13991 13992 // In case of rollback, remember per-user/profile install state 13993 allUsers = sUserManager.getUserIds(); 13994 installedUsers = ps.queryInstalledUsers(allUsers, true); 13995 } 13996 13997 // Update what is removed 13998 res.removedInfo = new PackageRemovedInfo(); 13999 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14000 res.removedInfo.removedPackage = oldPackage.packageName; 14001 res.removedInfo.isUpdate = true; 14002 res.removedInfo.origUsers = installedUsers; 14003 final int childCount = (oldPackage.childPackages != null) 14004 ? oldPackage.childPackages.size() : 0; 14005 for (int i = 0; i < childCount; i++) { 14006 boolean childPackageUpdated = false; 14007 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14008 if (res.addedChildPackages != null) { 14009 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14010 if (childRes != null) { 14011 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14012 childRes.removedInfo.removedPackage = childPkg.packageName; 14013 childRes.removedInfo.isUpdate = true; 14014 childPackageUpdated = true; 14015 } 14016 } 14017 if (!childPackageUpdated) { 14018 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14019 childRemovedRes.removedPackage = childPkg.packageName; 14020 childRemovedRes.isUpdate = false; 14021 childRemovedRes.dataRemoved = true; 14022 synchronized (mPackages) { 14023 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14024 if (childPs != null) { 14025 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14026 } 14027 } 14028 if (res.removedInfo.removedChildPackages == null) { 14029 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14030 } 14031 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14032 } 14033 } 14034 14035 boolean sysPkg = (isSystemApp(oldPackage)); 14036 if (sysPkg) { 14037 // Set the system/privileged flags as needed 14038 final boolean privileged = 14039 (oldPackage.applicationInfo.privateFlags 14040 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14041 final int systemPolicyFlags = policyFlags 14042 | PackageParser.PARSE_IS_SYSTEM 14043 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14044 14045 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14046 user, allUsers, installerPackageName, res); 14047 } else { 14048 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14049 user, allUsers, installerPackageName, res); 14050 } 14051 } 14052 14053 public List<String> getPreviousCodePaths(String packageName) { 14054 final PackageSetting ps = mSettings.mPackages.get(packageName); 14055 final List<String> result = new ArrayList<String>(); 14056 if (ps != null && ps.oldCodePaths != null) { 14057 result.addAll(ps.oldCodePaths); 14058 } 14059 return result; 14060 } 14061 14062 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14063 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14064 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14065 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14066 + deletedPackage); 14067 14068 String pkgName = deletedPackage.packageName; 14069 boolean deletedPkg = true; 14070 boolean addedPkg = false; 14071 boolean updatedSettings = false; 14072 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14073 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14074 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14075 14076 final long origUpdateTime = (pkg.mExtras != null) 14077 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14078 14079 // First delete the existing package while retaining the data directory 14080 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14081 res.removedInfo, true, pkg)) { 14082 // If the existing package wasn't successfully deleted 14083 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14084 deletedPkg = false; 14085 } else { 14086 // Successfully deleted the old package; proceed with replace. 14087 14088 // If deleted package lived in a container, give users a chance to 14089 // relinquish resources before killing. 14090 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14091 if (DEBUG_INSTALL) { 14092 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14093 } 14094 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14095 final ArrayList<String> pkgList = new ArrayList<String>(1); 14096 pkgList.add(deletedPackage.applicationInfo.packageName); 14097 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14098 } 14099 14100 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14101 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14102 clearAppProfilesLIF(pkg); 14103 14104 try { 14105 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14106 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14107 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14108 14109 // Update the in-memory copy of the previous code paths. 14110 PackageSetting ps = mSettings.mPackages.get(pkgName); 14111 if (!killApp) { 14112 if (ps.oldCodePaths == null) { 14113 ps.oldCodePaths = new ArraySet<>(); 14114 } 14115 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14116 if (deletedPackage.splitCodePaths != null) { 14117 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14118 } 14119 } else { 14120 ps.oldCodePaths = null; 14121 } 14122 if (ps.childPackageNames != null) { 14123 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14124 final String childPkgName = ps.childPackageNames.get(i); 14125 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14126 childPs.oldCodePaths = ps.oldCodePaths; 14127 } 14128 } 14129 prepareAppDataAfterInstallLIF(newPackage); 14130 addedPkg = true; 14131 } catch (PackageManagerException e) { 14132 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14133 } 14134 } 14135 14136 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14137 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14138 14139 // Revert all internal state mutations and added folders for the failed install 14140 if (addedPkg) { 14141 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14142 res.removedInfo, true, null); 14143 } 14144 14145 // Restore the old package 14146 if (deletedPkg) { 14147 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14148 File restoreFile = new File(deletedPackage.codePath); 14149 // Parse old package 14150 boolean oldExternal = isExternal(deletedPackage); 14151 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14152 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14153 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14154 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14155 try { 14156 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14157 null); 14158 } catch (PackageManagerException e) { 14159 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14160 + e.getMessage()); 14161 return; 14162 } 14163 14164 synchronized (mPackages) { 14165 // Ensure the installer package name up to date 14166 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14167 14168 // Update permissions for restored package 14169 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14170 14171 mSettings.writeLPr(); 14172 } 14173 14174 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14175 } 14176 } else { 14177 synchronized (mPackages) { 14178 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14179 if (ps != null) { 14180 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14181 if (res.removedInfo.removedChildPackages != null) { 14182 final int childCount = res.removedInfo.removedChildPackages.size(); 14183 // Iterate in reverse as we may modify the collection 14184 for (int i = childCount - 1; i >= 0; i--) { 14185 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14186 if (res.addedChildPackages.containsKey(childPackageName)) { 14187 res.removedInfo.removedChildPackages.removeAt(i); 14188 } else { 14189 PackageRemovedInfo childInfo = res.removedInfo 14190 .removedChildPackages.valueAt(i); 14191 childInfo.removedForAllUsers = mPackages.get( 14192 childInfo.removedPackage) == null; 14193 } 14194 } 14195 } 14196 } 14197 } 14198 } 14199 } 14200 14201 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14202 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14203 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14204 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14205 + ", old=" + deletedPackage); 14206 14207 final boolean disabledSystem; 14208 14209 // Remove existing system package 14210 removePackageLI(deletedPackage, true); 14211 14212 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14213 if (!disabledSystem) { 14214 // We didn't need to disable the .apk as a current system package, 14215 // which means we are replacing another update that is already 14216 // installed. We need to make sure to delete the older one's .apk. 14217 res.removedInfo.args = createInstallArgsForExisting(0, 14218 deletedPackage.applicationInfo.getCodePath(), 14219 deletedPackage.applicationInfo.getResourcePath(), 14220 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14221 } else { 14222 res.removedInfo.args = null; 14223 } 14224 14225 // Successfully disabled the old package. Now proceed with re-installation 14226 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14227 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14228 clearAppProfilesLIF(pkg); 14229 14230 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14231 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14232 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14233 14234 PackageParser.Package newPackage = null; 14235 try { 14236 // Add the package to the internal data structures 14237 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14238 14239 // Set the update and install times 14240 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14241 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14242 System.currentTimeMillis()); 14243 14244 // Update the package dynamic state if succeeded 14245 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14246 // Now that the install succeeded make sure we remove data 14247 // directories for any child package the update removed. 14248 final int deletedChildCount = (deletedPackage.childPackages != null) 14249 ? deletedPackage.childPackages.size() : 0; 14250 final int newChildCount = (newPackage.childPackages != null) 14251 ? newPackage.childPackages.size() : 0; 14252 for (int i = 0; i < deletedChildCount; i++) { 14253 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14254 boolean childPackageDeleted = true; 14255 for (int j = 0; j < newChildCount; j++) { 14256 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14257 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14258 childPackageDeleted = false; 14259 break; 14260 } 14261 } 14262 if (childPackageDeleted) { 14263 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14264 deletedChildPkg.packageName); 14265 if (ps != null && res.removedInfo.removedChildPackages != null) { 14266 PackageRemovedInfo removedChildRes = res.removedInfo 14267 .removedChildPackages.get(deletedChildPkg.packageName); 14268 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14269 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14270 } 14271 } 14272 } 14273 14274 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14275 prepareAppDataAfterInstallLIF(newPackage); 14276 } 14277 } catch (PackageManagerException e) { 14278 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14279 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14280 } 14281 14282 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14283 // Re installation failed. Restore old information 14284 // Remove new pkg information 14285 if (newPackage != null) { 14286 removeInstalledPackageLI(newPackage, true); 14287 } 14288 // Add back the old system package 14289 try { 14290 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14291 } catch (PackageManagerException e) { 14292 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14293 } 14294 14295 synchronized (mPackages) { 14296 if (disabledSystem) { 14297 enableSystemPackageLPw(deletedPackage); 14298 } 14299 14300 // Ensure the installer package name up to date 14301 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14302 14303 // Update permissions for restored package 14304 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14305 14306 mSettings.writeLPr(); 14307 } 14308 14309 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14310 + " after failed upgrade"); 14311 } 14312 } 14313 14314 /** 14315 * Checks whether the parent or any of the child packages have a change shared 14316 * user. For a package to be a valid update the shred users of the parent and 14317 * the children should match. We may later support changing child shared users. 14318 * @param oldPkg The updated package. 14319 * @param newPkg The update package. 14320 * @return The shared user that change between the versions. 14321 */ 14322 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14323 PackageParser.Package newPkg) { 14324 // Check parent shared user 14325 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14326 return newPkg.packageName; 14327 } 14328 // Check child shared users 14329 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14330 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14331 for (int i = 0; i < newChildCount; i++) { 14332 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14333 // If this child was present, did it have the same shared user? 14334 for (int j = 0; j < oldChildCount; j++) { 14335 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14336 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14337 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14338 return newChildPkg.packageName; 14339 } 14340 } 14341 } 14342 return null; 14343 } 14344 14345 private void removeNativeBinariesLI(PackageSetting ps) { 14346 // Remove the lib path for the parent package 14347 if (ps != null) { 14348 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14349 // Remove the lib path for the child packages 14350 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14351 for (int i = 0; i < childCount; i++) { 14352 PackageSetting childPs = null; 14353 synchronized (mPackages) { 14354 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14355 } 14356 if (childPs != null) { 14357 NativeLibraryHelper.removeNativeBinariesLI(childPs 14358 .legacyNativeLibraryPathString); 14359 } 14360 } 14361 } 14362 } 14363 14364 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14365 // Enable the parent package 14366 mSettings.enableSystemPackageLPw(pkg.packageName); 14367 // Enable the child packages 14368 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14369 for (int i = 0; i < childCount; i++) { 14370 PackageParser.Package childPkg = pkg.childPackages.get(i); 14371 mSettings.enableSystemPackageLPw(childPkg.packageName); 14372 } 14373 } 14374 14375 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14376 PackageParser.Package newPkg) { 14377 // Disable the parent package (parent always replaced) 14378 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14379 // Disable the child packages 14380 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14381 for (int i = 0; i < childCount; i++) { 14382 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14383 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14384 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14385 } 14386 return disabled; 14387 } 14388 14389 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14390 String installerPackageName) { 14391 // Enable the parent package 14392 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14393 // Enable the child packages 14394 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14395 for (int i = 0; i < childCount; i++) { 14396 PackageParser.Package childPkg = pkg.childPackages.get(i); 14397 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14398 } 14399 } 14400 14401 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14402 // Collect all used permissions in the UID 14403 ArraySet<String> usedPermissions = new ArraySet<>(); 14404 final int packageCount = su.packages.size(); 14405 for (int i = 0; i < packageCount; i++) { 14406 PackageSetting ps = su.packages.valueAt(i); 14407 if (ps.pkg == null) { 14408 continue; 14409 } 14410 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14411 for (int j = 0; j < requestedPermCount; j++) { 14412 String permission = ps.pkg.requestedPermissions.get(j); 14413 BasePermission bp = mSettings.mPermissions.get(permission); 14414 if (bp != null) { 14415 usedPermissions.add(permission); 14416 } 14417 } 14418 } 14419 14420 PermissionsState permissionsState = su.getPermissionsState(); 14421 // Prune install permissions 14422 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14423 final int installPermCount = installPermStates.size(); 14424 for (int i = installPermCount - 1; i >= 0; i--) { 14425 PermissionState permissionState = installPermStates.get(i); 14426 if (!usedPermissions.contains(permissionState.getName())) { 14427 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14428 if (bp != null) { 14429 permissionsState.revokeInstallPermission(bp); 14430 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14431 PackageManager.MASK_PERMISSION_FLAGS, 0); 14432 } 14433 } 14434 } 14435 14436 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14437 14438 // Prune runtime permissions 14439 for (int userId : allUserIds) { 14440 List<PermissionState> runtimePermStates = permissionsState 14441 .getRuntimePermissionStates(userId); 14442 final int runtimePermCount = runtimePermStates.size(); 14443 for (int i = runtimePermCount - 1; i >= 0; i--) { 14444 PermissionState permissionState = runtimePermStates.get(i); 14445 if (!usedPermissions.contains(permissionState.getName())) { 14446 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14447 if (bp != null) { 14448 permissionsState.revokeRuntimePermission(bp, userId); 14449 permissionsState.updatePermissionFlags(bp, userId, 14450 PackageManager.MASK_PERMISSION_FLAGS, 0); 14451 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14452 runtimePermissionChangedUserIds, userId); 14453 } 14454 } 14455 } 14456 } 14457 14458 return runtimePermissionChangedUserIds; 14459 } 14460 14461 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14462 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14463 // Update the parent package setting 14464 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14465 res, user); 14466 // Update the child packages setting 14467 final int childCount = (newPackage.childPackages != null) 14468 ? newPackage.childPackages.size() : 0; 14469 for (int i = 0; i < childCount; i++) { 14470 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14471 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14472 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14473 childRes.origUsers, childRes, user); 14474 } 14475 } 14476 14477 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14478 String installerPackageName, int[] allUsers, int[] installedForUsers, 14479 PackageInstalledInfo res, UserHandle user) { 14480 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14481 14482 String pkgName = newPackage.packageName; 14483 synchronized (mPackages) { 14484 //write settings. the installStatus will be incomplete at this stage. 14485 //note that the new package setting would have already been 14486 //added to mPackages. It hasn't been persisted yet. 14487 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14488 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14489 mSettings.writeLPr(); 14490 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14491 } 14492 14493 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14494 synchronized (mPackages) { 14495 updatePermissionsLPw(newPackage.packageName, newPackage, 14496 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14497 ? UPDATE_PERMISSIONS_ALL : 0)); 14498 // For system-bundled packages, we assume that installing an upgraded version 14499 // of the package implies that the user actually wants to run that new code, 14500 // so we enable the package. 14501 PackageSetting ps = mSettings.mPackages.get(pkgName); 14502 final int userId = user.getIdentifier(); 14503 if (ps != null) { 14504 if (isSystemApp(newPackage)) { 14505 if (DEBUG_INSTALL) { 14506 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14507 } 14508 // Enable system package for requested users 14509 if (res.origUsers != null) { 14510 for (int origUserId : res.origUsers) { 14511 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14512 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14513 origUserId, installerPackageName); 14514 } 14515 } 14516 } 14517 // Also convey the prior install/uninstall state 14518 if (allUsers != null && installedForUsers != null) { 14519 for (int currentUserId : allUsers) { 14520 final boolean installed = ArrayUtils.contains( 14521 installedForUsers, currentUserId); 14522 if (DEBUG_INSTALL) { 14523 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14524 } 14525 ps.setInstalled(installed, currentUserId); 14526 } 14527 // these install state changes will be persisted in the 14528 // upcoming call to mSettings.writeLPr(). 14529 } 14530 } 14531 // It's implied that when a user requests installation, they want the app to be 14532 // installed and enabled. 14533 if (userId != UserHandle.USER_ALL) { 14534 ps.setInstalled(true, userId); 14535 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14536 } 14537 } 14538 res.name = pkgName; 14539 res.uid = newPackage.applicationInfo.uid; 14540 res.pkg = newPackage; 14541 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14542 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14543 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14544 //to update install status 14545 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14546 mSettings.writeLPr(); 14547 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14548 } 14549 14550 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14551 } 14552 14553 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14554 try { 14555 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14556 installPackageLI(args, res); 14557 } finally { 14558 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14559 } 14560 } 14561 14562 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14563 final int installFlags = args.installFlags; 14564 final String installerPackageName = args.installerPackageName; 14565 final String volumeUuid = args.volumeUuid; 14566 final File tmpPackageFile = new File(args.getCodePath()); 14567 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14568 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14569 || (args.volumeUuid != null)); 14570 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14571 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14572 boolean replace = false; 14573 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14574 if (args.move != null) { 14575 // moving a complete application; perform an initial scan on the new install location 14576 scanFlags |= SCAN_INITIAL; 14577 } 14578 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14579 scanFlags |= SCAN_DONT_KILL_APP; 14580 } 14581 14582 // Result object to be returned 14583 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14584 14585 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14586 14587 // Sanity check 14588 if (ephemeral && (forwardLocked || onExternal)) { 14589 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14590 + " external=" + onExternal); 14591 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14592 return; 14593 } 14594 14595 // Retrieve PackageSettings and parse package 14596 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14597 | PackageParser.PARSE_ENFORCE_CODE 14598 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14599 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14600 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14601 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14602 PackageParser pp = new PackageParser(); 14603 pp.setSeparateProcesses(mSeparateProcesses); 14604 pp.setDisplayMetrics(mMetrics); 14605 14606 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14607 final PackageParser.Package pkg; 14608 try { 14609 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14610 } catch (PackageParserException e) { 14611 res.setError("Failed parse during installPackageLI", e); 14612 return; 14613 } finally { 14614 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14615 } 14616 14617 // If we are installing a clustered package add results for the children 14618 if (pkg.childPackages != null) { 14619 synchronized (mPackages) { 14620 final int childCount = pkg.childPackages.size(); 14621 for (int i = 0; i < childCount; i++) { 14622 PackageParser.Package childPkg = pkg.childPackages.get(i); 14623 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14624 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14625 childRes.pkg = childPkg; 14626 childRes.name = childPkg.packageName; 14627 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14628 if (childPs != null) { 14629 childRes.origUsers = childPs.queryInstalledUsers( 14630 sUserManager.getUserIds(), true); 14631 } 14632 if ((mPackages.containsKey(childPkg.packageName))) { 14633 childRes.removedInfo = new PackageRemovedInfo(); 14634 childRes.removedInfo.removedPackage = childPkg.packageName; 14635 } 14636 if (res.addedChildPackages == null) { 14637 res.addedChildPackages = new ArrayMap<>(); 14638 } 14639 res.addedChildPackages.put(childPkg.packageName, childRes); 14640 } 14641 } 14642 } 14643 14644 // If package doesn't declare API override, mark that we have an install 14645 // time CPU ABI override. 14646 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14647 pkg.cpuAbiOverride = args.abiOverride; 14648 } 14649 14650 String pkgName = res.name = pkg.packageName; 14651 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14652 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14653 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14654 return; 14655 } 14656 } 14657 14658 try { 14659 // either use what we've been given or parse directly from the APK 14660 if (args.certificates != null) { 14661 try { 14662 PackageParser.populateCertificates(pkg, args.certificates); 14663 } catch (PackageParserException e) { 14664 // there was something wrong with the certificates we were given; 14665 // try to pull them from the APK 14666 PackageParser.collectCertificates(pkg, parseFlags); 14667 } 14668 } else { 14669 PackageParser.collectCertificates(pkg, parseFlags); 14670 } 14671 } catch (PackageParserException e) { 14672 res.setError("Failed collect during installPackageLI", e); 14673 return; 14674 } 14675 14676 // Get rid of all references to package scan path via parser. 14677 pp = null; 14678 String oldCodePath = null; 14679 boolean systemApp = false; 14680 synchronized (mPackages) { 14681 // Check if installing already existing package 14682 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14683 String oldName = mSettings.mRenamedPackages.get(pkgName); 14684 if (pkg.mOriginalPackages != null 14685 && pkg.mOriginalPackages.contains(oldName) 14686 && mPackages.containsKey(oldName)) { 14687 // This package is derived from an original package, 14688 // and this device has been updating from that original 14689 // name. We must continue using the original name, so 14690 // rename the new package here. 14691 pkg.setPackageName(oldName); 14692 pkgName = pkg.packageName; 14693 replace = true; 14694 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14695 + oldName + " pkgName=" + pkgName); 14696 } else if (mPackages.containsKey(pkgName)) { 14697 // This package, under its official name, already exists 14698 // on the device; we should replace it. 14699 replace = true; 14700 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14701 } 14702 14703 // Child packages are installed through the parent package 14704 if (pkg.parentPackage != null) { 14705 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14706 "Package " + pkg.packageName + " is child of package " 14707 + pkg.parentPackage.parentPackage + ". Child packages " 14708 + "can be updated only through the parent package."); 14709 return; 14710 } 14711 14712 if (replace) { 14713 // Prevent apps opting out from runtime permissions 14714 PackageParser.Package oldPackage = mPackages.get(pkgName); 14715 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14716 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14717 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14718 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14719 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14720 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14721 + " doesn't support runtime permissions but the old" 14722 + " target SDK " + oldTargetSdk + " does."); 14723 return; 14724 } 14725 14726 // Prevent installing of child packages 14727 if (oldPackage.parentPackage != null) { 14728 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14729 "Package " + pkg.packageName + " is child of package " 14730 + oldPackage.parentPackage + ". Child packages " 14731 + "can be updated only through the parent package."); 14732 return; 14733 } 14734 } 14735 } 14736 14737 PackageSetting ps = mSettings.mPackages.get(pkgName); 14738 if (ps != null) { 14739 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14740 14741 // Quick sanity check that we're signed correctly if updating; 14742 // we'll check this again later when scanning, but we want to 14743 // bail early here before tripping over redefined permissions. 14744 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14745 if (!checkUpgradeKeySetLP(ps, pkg)) { 14746 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14747 + pkg.packageName + " upgrade keys do not match the " 14748 + "previously installed version"); 14749 return; 14750 } 14751 } else { 14752 try { 14753 verifySignaturesLP(ps, pkg); 14754 } catch (PackageManagerException e) { 14755 res.setError(e.error, e.getMessage()); 14756 return; 14757 } 14758 } 14759 14760 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14761 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14762 systemApp = (ps.pkg.applicationInfo.flags & 14763 ApplicationInfo.FLAG_SYSTEM) != 0; 14764 } 14765 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14766 } 14767 14768 // Check whether the newly-scanned package wants to define an already-defined perm 14769 int N = pkg.permissions.size(); 14770 for (int i = N-1; i >= 0; i--) { 14771 PackageParser.Permission perm = pkg.permissions.get(i); 14772 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14773 if (bp != null) { 14774 // If the defining package is signed with our cert, it's okay. This 14775 // also includes the "updating the same package" case, of course. 14776 // "updating same package" could also involve key-rotation. 14777 final boolean sigsOk; 14778 if (bp.sourcePackage.equals(pkg.packageName) 14779 && (bp.packageSetting instanceof PackageSetting) 14780 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14781 scanFlags))) { 14782 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14783 } else { 14784 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14785 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14786 } 14787 if (!sigsOk) { 14788 // If the owning package is the system itself, we log but allow 14789 // install to proceed; we fail the install on all other permission 14790 // redefinitions. 14791 if (!bp.sourcePackage.equals("android")) { 14792 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14793 + pkg.packageName + " attempting to redeclare permission " 14794 + perm.info.name + " already owned by " + bp.sourcePackage); 14795 res.origPermission = perm.info.name; 14796 res.origPackage = bp.sourcePackage; 14797 return; 14798 } else { 14799 Slog.w(TAG, "Package " + pkg.packageName 14800 + " attempting to redeclare system permission " 14801 + perm.info.name + "; ignoring new declaration"); 14802 pkg.permissions.remove(i); 14803 } 14804 } 14805 } 14806 } 14807 } 14808 14809 if (systemApp) { 14810 if (onExternal) { 14811 // Abort update; system app can't be replaced with app on sdcard 14812 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14813 "Cannot install updates to system apps on sdcard"); 14814 return; 14815 } else if (ephemeral) { 14816 // Abort update; system app can't be replaced with an ephemeral app 14817 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14818 "Cannot update a system app with an ephemeral app"); 14819 return; 14820 } 14821 } 14822 14823 if (args.move != null) { 14824 // We did an in-place move, so dex is ready to roll 14825 scanFlags |= SCAN_NO_DEX; 14826 scanFlags |= SCAN_MOVE; 14827 14828 synchronized (mPackages) { 14829 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14830 if (ps == null) { 14831 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14832 "Missing settings for moved package " + pkgName); 14833 } 14834 14835 // We moved the entire application as-is, so bring over the 14836 // previously derived ABI information. 14837 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14838 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14839 } 14840 14841 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14842 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14843 scanFlags |= SCAN_NO_DEX; 14844 14845 try { 14846 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14847 args.abiOverride : pkg.cpuAbiOverride); 14848 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14849 true /* extract libs */); 14850 } catch (PackageManagerException pme) { 14851 Slog.e(TAG, "Error deriving application ABI", pme); 14852 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14853 return; 14854 } 14855 14856 // Shared libraries for the package need to be updated. 14857 synchronized (mPackages) { 14858 try { 14859 updateSharedLibrariesLPw(pkg, null); 14860 } catch (PackageManagerException e) { 14861 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14862 } 14863 } 14864 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14865 // Do not run PackageDexOptimizer through the local performDexOpt 14866 // method because `pkg` is not in `mPackages` yet. 14867 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14868 null /* instructionSets */, false /* checkProfiles */, 14869 getCompilerFilterForReason(REASON_INSTALL)); 14870 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14871 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14872 String msg = "Extracting package failed for " + pkgName; 14873 res.setError(INSTALL_FAILED_DEXOPT, msg); 14874 return; 14875 } 14876 14877 // Notify BackgroundDexOptService that the package has been changed. 14878 // If this is an update of a package which used to fail to compile, 14879 // BDOS will remove it from its blacklist. 14880 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14881 } 14882 14883 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14884 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14885 return; 14886 } 14887 14888 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14889 14890 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14891 "installPackageLI")) { 14892 if (replace) { 14893 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14894 installerPackageName, res); 14895 } else { 14896 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14897 args.user, installerPackageName, volumeUuid, res); 14898 } 14899 } 14900 synchronized (mPackages) { 14901 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14902 if (ps != null) { 14903 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14904 } 14905 14906 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14907 for (int i = 0; i < childCount; i++) { 14908 PackageParser.Package childPkg = pkg.childPackages.get(i); 14909 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14910 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14911 if (childPs != null) { 14912 childRes.newUsers = childPs.queryInstalledUsers( 14913 sUserManager.getUserIds(), true); 14914 } 14915 } 14916 } 14917 } 14918 14919 private void startIntentFilterVerifications(int userId, boolean replacing, 14920 PackageParser.Package pkg) { 14921 if (mIntentFilterVerifierComponent == null) { 14922 Slog.w(TAG, "No IntentFilter verification will not be done as " 14923 + "there is no IntentFilterVerifier available!"); 14924 return; 14925 } 14926 14927 final int verifierUid = getPackageUid( 14928 mIntentFilterVerifierComponent.getPackageName(), 14929 MATCH_DEBUG_TRIAGED_MISSING, 14930 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14931 14932 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14933 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14934 mHandler.sendMessage(msg); 14935 14936 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14937 for (int i = 0; i < childCount; i++) { 14938 PackageParser.Package childPkg = pkg.childPackages.get(i); 14939 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14940 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14941 mHandler.sendMessage(msg); 14942 } 14943 } 14944 14945 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14946 PackageParser.Package pkg) { 14947 int size = pkg.activities.size(); 14948 if (size == 0) { 14949 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14950 "No activity, so no need to verify any IntentFilter!"); 14951 return; 14952 } 14953 14954 final boolean hasDomainURLs = hasDomainURLs(pkg); 14955 if (!hasDomainURLs) { 14956 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14957 "No domain URLs, so no need to verify any IntentFilter!"); 14958 return; 14959 } 14960 14961 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14962 + " if any IntentFilter from the " + size 14963 + " Activities needs verification ..."); 14964 14965 int count = 0; 14966 final String packageName = pkg.packageName; 14967 14968 synchronized (mPackages) { 14969 // If this is a new install and we see that we've already run verification for this 14970 // package, we have nothing to do: it means the state was restored from backup. 14971 if (!replacing) { 14972 IntentFilterVerificationInfo ivi = 14973 mSettings.getIntentFilterVerificationLPr(packageName); 14974 if (ivi != null) { 14975 if (DEBUG_DOMAIN_VERIFICATION) { 14976 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14977 + ivi.getStatusString()); 14978 } 14979 return; 14980 } 14981 } 14982 14983 // If any filters need to be verified, then all need to be. 14984 boolean needToVerify = false; 14985 for (PackageParser.Activity a : pkg.activities) { 14986 for (ActivityIntentInfo filter : a.intents) { 14987 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14988 if (DEBUG_DOMAIN_VERIFICATION) { 14989 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14990 } 14991 needToVerify = true; 14992 break; 14993 } 14994 } 14995 } 14996 14997 if (needToVerify) { 14998 final int verificationId = mIntentFilterVerificationToken++; 14999 for (PackageParser.Activity a : pkg.activities) { 15000 for (ActivityIntentInfo filter : a.intents) { 15001 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15002 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15003 "Verification needed for IntentFilter:" + filter.toString()); 15004 mIntentFilterVerifier.addOneIntentFilterVerification( 15005 verifierUid, userId, verificationId, filter, packageName); 15006 count++; 15007 } 15008 } 15009 } 15010 } 15011 } 15012 15013 if (count > 0) { 15014 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15015 + " IntentFilter verification" + (count > 1 ? "s" : "") 15016 + " for userId:" + userId); 15017 mIntentFilterVerifier.startVerifications(userId); 15018 } else { 15019 if (DEBUG_DOMAIN_VERIFICATION) { 15020 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15021 } 15022 } 15023 } 15024 15025 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15026 final ComponentName cn = filter.activity.getComponentName(); 15027 final String packageName = cn.getPackageName(); 15028 15029 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15030 packageName); 15031 if (ivi == null) { 15032 return true; 15033 } 15034 int status = ivi.getStatus(); 15035 switch (status) { 15036 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15037 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15038 return true; 15039 15040 default: 15041 // Nothing to do 15042 return false; 15043 } 15044 } 15045 15046 private static boolean isMultiArch(ApplicationInfo info) { 15047 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15048 } 15049 15050 private static boolean isExternal(PackageParser.Package pkg) { 15051 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15052 } 15053 15054 private static boolean isExternal(PackageSetting ps) { 15055 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15056 } 15057 15058 private static boolean isEphemeral(PackageParser.Package pkg) { 15059 return pkg.applicationInfo.isEphemeralApp(); 15060 } 15061 15062 private static boolean isEphemeral(PackageSetting ps) { 15063 return ps.pkg != null && isEphemeral(ps.pkg); 15064 } 15065 15066 private static boolean isSystemApp(PackageParser.Package pkg) { 15067 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15068 } 15069 15070 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15071 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15072 } 15073 15074 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15075 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15076 } 15077 15078 private static boolean isSystemApp(PackageSetting ps) { 15079 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15080 } 15081 15082 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15083 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15084 } 15085 15086 private int packageFlagsToInstallFlags(PackageSetting ps) { 15087 int installFlags = 0; 15088 if (isEphemeral(ps)) { 15089 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15090 } 15091 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15092 // This existing package was an external ASEC install when we have 15093 // the external flag without a UUID 15094 installFlags |= PackageManager.INSTALL_EXTERNAL; 15095 } 15096 if (ps.isForwardLocked()) { 15097 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15098 } 15099 return installFlags; 15100 } 15101 15102 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15103 if (isExternal(pkg)) { 15104 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15105 return StorageManager.UUID_PRIMARY_PHYSICAL; 15106 } else { 15107 return pkg.volumeUuid; 15108 } 15109 } else { 15110 return StorageManager.UUID_PRIVATE_INTERNAL; 15111 } 15112 } 15113 15114 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15115 if (isExternal(pkg)) { 15116 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15117 return mSettings.getExternalVersion(); 15118 } else { 15119 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15120 } 15121 } else { 15122 return mSettings.getInternalVersion(); 15123 } 15124 } 15125 15126 private void deleteTempPackageFiles() { 15127 final FilenameFilter filter = new FilenameFilter() { 15128 public boolean accept(File dir, String name) { 15129 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15130 } 15131 }; 15132 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15133 file.delete(); 15134 } 15135 } 15136 15137 @Override 15138 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15139 int flags) { 15140 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15141 flags); 15142 } 15143 15144 @Override 15145 public void deletePackage(final String packageName, 15146 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15147 mContext.enforceCallingOrSelfPermission( 15148 android.Manifest.permission.DELETE_PACKAGES, null); 15149 Preconditions.checkNotNull(packageName); 15150 Preconditions.checkNotNull(observer); 15151 final int uid = Binder.getCallingUid(); 15152 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15153 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15154 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15155 mContext.enforceCallingOrSelfPermission( 15156 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15157 "deletePackage for user " + userId); 15158 } 15159 15160 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15161 try { 15162 observer.onPackageDeleted(packageName, 15163 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15164 } catch (RemoteException re) { 15165 } 15166 return; 15167 } 15168 15169 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15170 try { 15171 observer.onPackageDeleted(packageName, 15172 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15173 } catch (RemoteException re) { 15174 } 15175 return; 15176 } 15177 15178 if (DEBUG_REMOVE) { 15179 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15180 + " deleteAllUsers: " + deleteAllUsers ); 15181 } 15182 // Queue up an async operation since the package deletion may take a little while. 15183 mHandler.post(new Runnable() { 15184 public void run() { 15185 mHandler.removeCallbacks(this); 15186 int returnCode; 15187 if (!deleteAllUsers) { 15188 returnCode = deletePackageX(packageName, userId, deleteFlags); 15189 } else { 15190 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15191 // If nobody is blocking uninstall, proceed with delete for all users 15192 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15193 returnCode = deletePackageX(packageName, userId, deleteFlags); 15194 } else { 15195 // Otherwise uninstall individually for users with blockUninstalls=false 15196 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15197 for (int userId : users) { 15198 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15199 returnCode = deletePackageX(packageName, userId, userFlags); 15200 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15201 Slog.w(TAG, "Package delete failed for user " + userId 15202 + ", returnCode " + returnCode); 15203 } 15204 } 15205 } 15206 // The app has only been marked uninstalled for certain users. 15207 // We still need to report that delete was blocked 15208 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15209 } 15210 } 15211 try { 15212 observer.onPackageDeleted(packageName, returnCode, null); 15213 } catch (RemoteException e) { 15214 Log.i(TAG, "Observer no longer exists."); 15215 } //end catch 15216 } //end run 15217 }); 15218 } 15219 15220 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15221 int[] result = EMPTY_INT_ARRAY; 15222 for (int userId : userIds) { 15223 if (getBlockUninstallForUser(packageName, userId)) { 15224 result = ArrayUtils.appendInt(result, userId); 15225 } 15226 } 15227 return result; 15228 } 15229 15230 @Override 15231 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15232 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15233 } 15234 15235 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15236 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15237 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15238 try { 15239 if (dpm != null) { 15240 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15241 /* callingUserOnly =*/ false); 15242 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15243 : deviceOwnerComponentName.getPackageName(); 15244 // Does the package contains the device owner? 15245 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15246 // this check is probably not needed, since DO should be registered as a device 15247 // admin on some user too. (Original bug for this: b/17657954) 15248 if (packageName.equals(deviceOwnerPackageName)) { 15249 return true; 15250 } 15251 // Does it contain a device admin for any user? 15252 int[] users; 15253 if (userId == UserHandle.USER_ALL) { 15254 users = sUserManager.getUserIds(); 15255 } else { 15256 users = new int[]{userId}; 15257 } 15258 for (int i = 0; i < users.length; ++i) { 15259 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15260 return true; 15261 } 15262 } 15263 } 15264 } catch (RemoteException e) { 15265 } 15266 return false; 15267 } 15268 15269 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15270 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15271 } 15272 15273 /** 15274 * This method is an internal method that could be get invoked either 15275 * to delete an installed package or to clean up a failed installation. 15276 * After deleting an installed package, a broadcast is sent to notify any 15277 * listeners that the package has been removed. For cleaning up a failed 15278 * installation, the broadcast is not necessary since the package's 15279 * installation wouldn't have sent the initial broadcast either 15280 * The key steps in deleting a package are 15281 * deleting the package information in internal structures like mPackages, 15282 * deleting the packages base directories through installd 15283 * updating mSettings to reflect current status 15284 * persisting settings for later use 15285 * sending a broadcast if necessary 15286 */ 15287 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15288 final PackageRemovedInfo info = new PackageRemovedInfo(); 15289 final boolean res; 15290 15291 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15292 ? UserHandle.ALL : new UserHandle(userId); 15293 15294 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15295 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15296 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15297 } 15298 15299 PackageSetting uninstalledPs = null; 15300 15301 // for the uninstall-updates case and restricted profiles, remember the per- 15302 // user handle installed state 15303 int[] allUsers; 15304 synchronized (mPackages) { 15305 uninstalledPs = mSettings.mPackages.get(packageName); 15306 if (uninstalledPs == null) { 15307 Slog.w(TAG, "Not removing non-existent package " + packageName); 15308 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15309 } 15310 allUsers = sUserManager.getUserIds(); 15311 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15312 } 15313 15314 synchronized (mInstallLock) { 15315 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15316 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15317 "deletePackageX")) { 15318 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15319 deleteFlags | REMOVE_CHATTY, info, true, null); 15320 } 15321 synchronized (mPackages) { 15322 if (res) { 15323 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15324 } 15325 } 15326 } 15327 15328 if (res) { 15329 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15330 info.sendPackageRemovedBroadcasts(killApp); 15331 info.sendSystemPackageUpdatedBroadcasts(); 15332 info.sendSystemPackageAppearedBroadcasts(); 15333 } 15334 // Force a gc here. 15335 Runtime.getRuntime().gc(); 15336 // Delete the resources here after sending the broadcast to let 15337 // other processes clean up before deleting resources. 15338 if (info.args != null) { 15339 synchronized (mInstallLock) { 15340 info.args.doPostDeleteLI(true); 15341 } 15342 } 15343 15344 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15345 } 15346 15347 class PackageRemovedInfo { 15348 String removedPackage; 15349 int uid = -1; 15350 int removedAppId = -1; 15351 int[] origUsers; 15352 int[] removedUsers = null; 15353 boolean isRemovedPackageSystemUpdate = false; 15354 boolean isUpdate; 15355 boolean dataRemoved; 15356 boolean removedForAllUsers; 15357 // Clean up resources deleted packages. 15358 InstallArgs args = null; 15359 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15360 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15361 15362 void sendPackageRemovedBroadcasts(boolean killApp) { 15363 sendPackageRemovedBroadcastInternal(killApp); 15364 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15365 for (int i = 0; i < childCount; i++) { 15366 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15367 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15368 } 15369 } 15370 15371 void sendSystemPackageUpdatedBroadcasts() { 15372 if (isRemovedPackageSystemUpdate) { 15373 sendSystemPackageUpdatedBroadcastsInternal(); 15374 final int childCount = (removedChildPackages != null) 15375 ? removedChildPackages.size() : 0; 15376 for (int i = 0; i < childCount; i++) { 15377 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15378 if (childInfo.isRemovedPackageSystemUpdate) { 15379 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15380 } 15381 } 15382 } 15383 } 15384 15385 void sendSystemPackageAppearedBroadcasts() { 15386 final int packageCount = (appearedChildPackages != null) 15387 ? appearedChildPackages.size() : 0; 15388 for (int i = 0; i < packageCount; i++) { 15389 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15390 for (int userId : installedInfo.newUsers) { 15391 sendPackageAddedForUser(installedInfo.name, true, 15392 UserHandle.getAppId(installedInfo.uid), userId); 15393 } 15394 } 15395 } 15396 15397 private void sendSystemPackageUpdatedBroadcastsInternal() { 15398 Bundle extras = new Bundle(2); 15399 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15400 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15401 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15402 extras, 0, null, null, null); 15403 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15404 extras, 0, null, null, null); 15405 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15406 null, 0, removedPackage, null, null); 15407 } 15408 15409 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15410 Bundle extras = new Bundle(2); 15411 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15412 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15413 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15414 if (isUpdate || isRemovedPackageSystemUpdate) { 15415 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15416 } 15417 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15418 if (removedPackage != null) { 15419 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15420 extras, 0, null, null, removedUsers); 15421 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15422 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15423 removedPackage, extras, 0, null, null, removedUsers); 15424 } 15425 } 15426 if (removedAppId >= 0) { 15427 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15428 removedUsers); 15429 } 15430 } 15431 } 15432 15433 /* 15434 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15435 * flag is not set, the data directory is removed as well. 15436 * make sure this flag is set for partially installed apps. If not its meaningless to 15437 * delete a partially installed application. 15438 */ 15439 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15440 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15441 String packageName = ps.name; 15442 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15443 // Retrieve object to delete permissions for shared user later on 15444 final PackageParser.Package deletedPkg; 15445 final PackageSetting deletedPs; 15446 // reader 15447 synchronized (mPackages) { 15448 deletedPkg = mPackages.get(packageName); 15449 deletedPs = mSettings.mPackages.get(packageName); 15450 if (outInfo != null) { 15451 outInfo.removedPackage = packageName; 15452 outInfo.removedUsers = deletedPs != null 15453 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15454 : null; 15455 } 15456 } 15457 15458 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15459 15460 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15461 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15462 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15463 destroyAppProfilesLIF(deletedPkg); 15464 if (outInfo != null) { 15465 outInfo.dataRemoved = true; 15466 } 15467 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15468 } 15469 15470 // writer 15471 synchronized (mPackages) { 15472 if (deletedPs != null) { 15473 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15474 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15475 clearDefaultBrowserIfNeeded(packageName); 15476 if (outInfo != null) { 15477 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15478 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15479 } 15480 updatePermissionsLPw(deletedPs.name, null, 0); 15481 if (deletedPs.sharedUser != null) { 15482 // Remove permissions associated with package. Since runtime 15483 // permissions are per user we have to kill the removed package 15484 // or packages running under the shared user of the removed 15485 // package if revoking the permissions requested only by the removed 15486 // package is successful and this causes a change in gids. 15487 for (int userId : UserManagerService.getInstance().getUserIds()) { 15488 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15489 userId); 15490 if (userIdToKill == UserHandle.USER_ALL 15491 || userIdToKill >= UserHandle.USER_SYSTEM) { 15492 // If gids changed for this user, kill all affected packages. 15493 mHandler.post(new Runnable() { 15494 @Override 15495 public void run() { 15496 // This has to happen with no lock held. 15497 killApplication(deletedPs.name, deletedPs.appId, 15498 KILL_APP_REASON_GIDS_CHANGED); 15499 } 15500 }); 15501 break; 15502 } 15503 } 15504 } 15505 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15506 } 15507 // make sure to preserve per-user disabled state if this removal was just 15508 // a downgrade of a system app to the factory package 15509 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15510 if (DEBUG_REMOVE) { 15511 Slog.d(TAG, "Propagating install state across downgrade"); 15512 } 15513 for (int userId : allUserHandles) { 15514 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15515 if (DEBUG_REMOVE) { 15516 Slog.d(TAG, " user " + userId + " => " + installed); 15517 } 15518 ps.setInstalled(installed, userId); 15519 } 15520 } 15521 } 15522 // can downgrade to reader 15523 if (writeSettings) { 15524 // Save settings now 15525 mSettings.writeLPr(); 15526 } 15527 } 15528 if (outInfo != null) { 15529 // A user ID was deleted here. Go through all users and remove it 15530 // from KeyStore. 15531 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15532 } 15533 } 15534 15535 static boolean locationIsPrivileged(File path) { 15536 try { 15537 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15538 .getCanonicalPath(); 15539 return path.getCanonicalPath().startsWith(privilegedAppDir); 15540 } catch (IOException e) { 15541 Slog.e(TAG, "Unable to access code path " + path); 15542 } 15543 return false; 15544 } 15545 15546 /* 15547 * Tries to delete system package. 15548 */ 15549 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15550 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15551 boolean writeSettings) { 15552 if (deletedPs.parentPackageName != null) { 15553 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15554 return false; 15555 } 15556 15557 final boolean applyUserRestrictions 15558 = (allUserHandles != null) && (outInfo.origUsers != null); 15559 final PackageSetting disabledPs; 15560 // Confirm if the system package has been updated 15561 // An updated system app can be deleted. This will also have to restore 15562 // the system pkg from system partition 15563 // reader 15564 synchronized (mPackages) { 15565 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15566 } 15567 15568 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15569 + " disabledPs=" + disabledPs); 15570 15571 if (disabledPs == null) { 15572 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15573 return false; 15574 } else if (DEBUG_REMOVE) { 15575 Slog.d(TAG, "Deleting system pkg from data partition"); 15576 } 15577 15578 if (DEBUG_REMOVE) { 15579 if (applyUserRestrictions) { 15580 Slog.d(TAG, "Remembering install states:"); 15581 for (int userId : allUserHandles) { 15582 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15583 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15584 } 15585 } 15586 } 15587 15588 // Delete the updated package 15589 outInfo.isRemovedPackageSystemUpdate = true; 15590 if (outInfo.removedChildPackages != null) { 15591 final int childCount = (deletedPs.childPackageNames != null) 15592 ? deletedPs.childPackageNames.size() : 0; 15593 for (int i = 0; i < childCount; i++) { 15594 String childPackageName = deletedPs.childPackageNames.get(i); 15595 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15596 .contains(childPackageName)) { 15597 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15598 childPackageName); 15599 if (childInfo != null) { 15600 childInfo.isRemovedPackageSystemUpdate = true; 15601 } 15602 } 15603 } 15604 } 15605 15606 if (disabledPs.versionCode < deletedPs.versionCode) { 15607 // Delete data for downgrades 15608 flags &= ~PackageManager.DELETE_KEEP_DATA; 15609 } else { 15610 // Preserve data by setting flag 15611 flags |= PackageManager.DELETE_KEEP_DATA; 15612 } 15613 15614 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15615 outInfo, writeSettings, disabledPs.pkg); 15616 if (!ret) { 15617 return false; 15618 } 15619 15620 // writer 15621 synchronized (mPackages) { 15622 // Reinstate the old system package 15623 enableSystemPackageLPw(disabledPs.pkg); 15624 // Remove any native libraries from the upgraded package. 15625 removeNativeBinariesLI(deletedPs); 15626 } 15627 15628 // Install the system package 15629 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15630 int parseFlags = mDefParseFlags 15631 | PackageParser.PARSE_MUST_BE_APK 15632 | PackageParser.PARSE_IS_SYSTEM 15633 | PackageParser.PARSE_IS_SYSTEM_DIR; 15634 if (locationIsPrivileged(disabledPs.codePath)) { 15635 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15636 } 15637 15638 final PackageParser.Package newPkg; 15639 try { 15640 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15641 } catch (PackageManagerException e) { 15642 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15643 + e.getMessage()); 15644 return false; 15645 } 15646 15647 prepareAppDataAfterInstallLIF(newPkg); 15648 15649 // writer 15650 synchronized (mPackages) { 15651 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15652 15653 // Propagate the permissions state as we do not want to drop on the floor 15654 // runtime permissions. The update permissions method below will take 15655 // care of removing obsolete permissions and grant install permissions. 15656 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15657 updatePermissionsLPw(newPkg.packageName, newPkg, 15658 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15659 15660 if (applyUserRestrictions) { 15661 if (DEBUG_REMOVE) { 15662 Slog.d(TAG, "Propagating install state across reinstall"); 15663 } 15664 for (int userId : allUserHandles) { 15665 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15666 if (DEBUG_REMOVE) { 15667 Slog.d(TAG, " user " + userId + " => " + installed); 15668 } 15669 ps.setInstalled(installed, userId); 15670 15671 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15672 } 15673 // Regardless of writeSettings we need to ensure that this restriction 15674 // state propagation is persisted 15675 mSettings.writeAllUsersPackageRestrictionsLPr(); 15676 } 15677 // can downgrade to reader here 15678 if (writeSettings) { 15679 mSettings.writeLPr(); 15680 } 15681 } 15682 return true; 15683 } 15684 15685 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15686 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15687 PackageRemovedInfo outInfo, boolean writeSettings, 15688 PackageParser.Package replacingPackage) { 15689 synchronized (mPackages) { 15690 if (outInfo != null) { 15691 outInfo.uid = ps.appId; 15692 } 15693 15694 if (outInfo != null && outInfo.removedChildPackages != null) { 15695 final int childCount = (ps.childPackageNames != null) 15696 ? ps.childPackageNames.size() : 0; 15697 for (int i = 0; i < childCount; i++) { 15698 String childPackageName = ps.childPackageNames.get(i); 15699 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15700 if (childPs == null) { 15701 return false; 15702 } 15703 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15704 childPackageName); 15705 if (childInfo != null) { 15706 childInfo.uid = childPs.appId; 15707 } 15708 } 15709 } 15710 } 15711 15712 // Delete package data from internal structures and also remove data if flag is set 15713 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15714 15715 // Delete the child packages data 15716 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15717 for (int i = 0; i < childCount; i++) { 15718 PackageSetting childPs; 15719 synchronized (mPackages) { 15720 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15721 } 15722 if (childPs != null) { 15723 PackageRemovedInfo childOutInfo = (outInfo != null 15724 && outInfo.removedChildPackages != null) 15725 ? outInfo.removedChildPackages.get(childPs.name) : null; 15726 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15727 && (replacingPackage != null 15728 && !replacingPackage.hasChildPackage(childPs.name)) 15729 ? flags & ~DELETE_KEEP_DATA : flags; 15730 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15731 deleteFlags, writeSettings); 15732 } 15733 } 15734 15735 // Delete application code and resources only for parent packages 15736 if (ps.parentPackageName == null) { 15737 if (deleteCodeAndResources && (outInfo != null)) { 15738 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15739 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15740 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15741 } 15742 } 15743 15744 return true; 15745 } 15746 15747 @Override 15748 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15749 int userId) { 15750 mContext.enforceCallingOrSelfPermission( 15751 android.Manifest.permission.DELETE_PACKAGES, null); 15752 synchronized (mPackages) { 15753 PackageSetting ps = mSettings.mPackages.get(packageName); 15754 if (ps == null) { 15755 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15756 return false; 15757 } 15758 if (!ps.getInstalled(userId)) { 15759 // Can't block uninstall for an app that is not installed or enabled. 15760 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15761 return false; 15762 } 15763 ps.setBlockUninstall(blockUninstall, userId); 15764 mSettings.writePackageRestrictionsLPr(userId); 15765 } 15766 return true; 15767 } 15768 15769 @Override 15770 public boolean getBlockUninstallForUser(String packageName, int userId) { 15771 synchronized (mPackages) { 15772 PackageSetting ps = mSettings.mPackages.get(packageName); 15773 if (ps == null) { 15774 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15775 return false; 15776 } 15777 return ps.getBlockUninstall(userId); 15778 } 15779 } 15780 15781 @Override 15782 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15783 int callingUid = Binder.getCallingUid(); 15784 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15785 throw new SecurityException( 15786 "setRequiredForSystemUser can only be run by the system or root"); 15787 } 15788 synchronized (mPackages) { 15789 PackageSetting ps = mSettings.mPackages.get(packageName); 15790 if (ps == null) { 15791 Log.w(TAG, "Package doesn't exist: " + packageName); 15792 return false; 15793 } 15794 if (systemUserApp) { 15795 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15796 } else { 15797 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15798 } 15799 mSettings.writeLPr(); 15800 } 15801 return true; 15802 } 15803 15804 /* 15805 * This method handles package deletion in general 15806 */ 15807 private boolean deletePackageLIF(String packageName, UserHandle user, 15808 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15809 PackageRemovedInfo outInfo, boolean writeSettings, 15810 PackageParser.Package replacingPackage) { 15811 if (packageName == null) { 15812 Slog.w(TAG, "Attempt to delete null packageName."); 15813 return false; 15814 } 15815 15816 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15817 15818 PackageSetting ps; 15819 15820 synchronized (mPackages) { 15821 ps = mSettings.mPackages.get(packageName); 15822 if (ps == null) { 15823 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15824 return false; 15825 } 15826 15827 if (ps.parentPackageName != null && (!isSystemApp(ps) 15828 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15829 if (DEBUG_REMOVE) { 15830 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15831 + ((user == null) ? UserHandle.USER_ALL : user)); 15832 } 15833 final int removedUserId = (user != null) ? user.getIdentifier() 15834 : UserHandle.USER_ALL; 15835 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15836 return false; 15837 } 15838 markPackageUninstalledForUserLPw(ps, user); 15839 scheduleWritePackageRestrictionsLocked(user); 15840 return true; 15841 } 15842 } 15843 15844 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15845 && user.getIdentifier() != UserHandle.USER_ALL)) { 15846 // The caller is asking that the package only be deleted for a single 15847 // user. To do this, we just mark its uninstalled state and delete 15848 // its data. If this is a system app, we only allow this to happen if 15849 // they have set the special DELETE_SYSTEM_APP which requests different 15850 // semantics than normal for uninstalling system apps. 15851 markPackageUninstalledForUserLPw(ps, user); 15852 15853 if (!isSystemApp(ps)) { 15854 // Do not uninstall the APK if an app should be cached 15855 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15856 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15857 // Other user still have this package installed, so all 15858 // we need to do is clear this user's data and save that 15859 // it is uninstalled. 15860 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15861 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15862 return false; 15863 } 15864 scheduleWritePackageRestrictionsLocked(user); 15865 return true; 15866 } else { 15867 // We need to set it back to 'installed' so the uninstall 15868 // broadcasts will be sent correctly. 15869 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15870 ps.setInstalled(true, user.getIdentifier()); 15871 } 15872 } else { 15873 // This is a system app, so we assume that the 15874 // other users still have this package installed, so all 15875 // we need to do is clear this user's data and save that 15876 // it is uninstalled. 15877 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15878 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15879 return false; 15880 } 15881 scheduleWritePackageRestrictionsLocked(user); 15882 return true; 15883 } 15884 } 15885 15886 // If we are deleting a composite package for all users, keep track 15887 // of result for each child. 15888 if (ps.childPackageNames != null && outInfo != null) { 15889 synchronized (mPackages) { 15890 final int childCount = ps.childPackageNames.size(); 15891 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15892 for (int i = 0; i < childCount; i++) { 15893 String childPackageName = ps.childPackageNames.get(i); 15894 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15895 childInfo.removedPackage = childPackageName; 15896 outInfo.removedChildPackages.put(childPackageName, childInfo); 15897 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15898 if (childPs != null) { 15899 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15900 } 15901 } 15902 } 15903 } 15904 15905 boolean ret = false; 15906 if (isSystemApp(ps)) { 15907 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15908 // When an updated system application is deleted we delete the existing resources 15909 // as well and fall back to existing code in system partition 15910 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15911 } else { 15912 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15913 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15914 outInfo, writeSettings, replacingPackage); 15915 } 15916 15917 // Take a note whether we deleted the package for all users 15918 if (outInfo != null) { 15919 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15920 if (outInfo.removedChildPackages != null) { 15921 synchronized (mPackages) { 15922 final int childCount = outInfo.removedChildPackages.size(); 15923 for (int i = 0; i < childCount; i++) { 15924 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15925 if (childInfo != null) { 15926 childInfo.removedForAllUsers = mPackages.get( 15927 childInfo.removedPackage) == null; 15928 } 15929 } 15930 } 15931 } 15932 // If we uninstalled an update to a system app there may be some 15933 // child packages that appeared as they are declared in the system 15934 // app but were not declared in the update. 15935 if (isSystemApp(ps)) { 15936 synchronized (mPackages) { 15937 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15938 final int childCount = (updatedPs.childPackageNames != null) 15939 ? updatedPs.childPackageNames.size() : 0; 15940 for (int i = 0; i < childCount; i++) { 15941 String childPackageName = updatedPs.childPackageNames.get(i); 15942 if (outInfo.removedChildPackages == null 15943 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15944 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15945 if (childPs == null) { 15946 continue; 15947 } 15948 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15949 installRes.name = childPackageName; 15950 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15951 installRes.pkg = mPackages.get(childPackageName); 15952 installRes.uid = childPs.pkg.applicationInfo.uid; 15953 if (outInfo.appearedChildPackages == null) { 15954 outInfo.appearedChildPackages = new ArrayMap<>(); 15955 } 15956 outInfo.appearedChildPackages.put(childPackageName, installRes); 15957 } 15958 } 15959 } 15960 } 15961 } 15962 15963 return ret; 15964 } 15965 15966 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15967 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15968 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15969 for (int nextUserId : userIds) { 15970 if (DEBUG_REMOVE) { 15971 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15972 } 15973 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15974 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15975 false /*hidden*/, false /*suspended*/, null, null, null, 15976 false /*blockUninstall*/, 15977 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15978 } 15979 } 15980 15981 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15982 PackageRemovedInfo outInfo) { 15983 final PackageParser.Package pkg; 15984 synchronized (mPackages) { 15985 pkg = mPackages.get(ps.name); 15986 } 15987 15988 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15989 : new int[] {userId}; 15990 for (int nextUserId : userIds) { 15991 if (DEBUG_REMOVE) { 15992 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15993 + nextUserId); 15994 } 15995 15996 destroyAppDataLIF(pkg, userId, 15997 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15998 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15999 schedulePackageCleaning(ps.name, nextUserId, false); 16000 synchronized (mPackages) { 16001 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16002 scheduleWritePackageRestrictionsLocked(nextUserId); 16003 } 16004 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16005 } 16006 } 16007 16008 if (outInfo != null) { 16009 outInfo.removedPackage = ps.name; 16010 outInfo.removedAppId = ps.appId; 16011 outInfo.removedUsers = userIds; 16012 } 16013 16014 return true; 16015 } 16016 16017 private final class ClearStorageConnection implements ServiceConnection { 16018 IMediaContainerService mContainerService; 16019 16020 @Override 16021 public void onServiceConnected(ComponentName name, IBinder service) { 16022 synchronized (this) { 16023 mContainerService = IMediaContainerService.Stub.asInterface(service); 16024 notifyAll(); 16025 } 16026 } 16027 16028 @Override 16029 public void onServiceDisconnected(ComponentName name) { 16030 } 16031 } 16032 16033 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16034 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16035 16036 final boolean mounted; 16037 if (Environment.isExternalStorageEmulated()) { 16038 mounted = true; 16039 } else { 16040 final String status = Environment.getExternalStorageState(); 16041 16042 mounted = status.equals(Environment.MEDIA_MOUNTED) 16043 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16044 } 16045 16046 if (!mounted) { 16047 return; 16048 } 16049 16050 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16051 int[] users; 16052 if (userId == UserHandle.USER_ALL) { 16053 users = sUserManager.getUserIds(); 16054 } else { 16055 users = new int[] { userId }; 16056 } 16057 final ClearStorageConnection conn = new ClearStorageConnection(); 16058 if (mContext.bindServiceAsUser( 16059 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16060 try { 16061 for (int curUser : users) { 16062 long timeout = SystemClock.uptimeMillis() + 5000; 16063 synchronized (conn) { 16064 long now = SystemClock.uptimeMillis(); 16065 while (conn.mContainerService == null && now < timeout) { 16066 try { 16067 conn.wait(timeout - now); 16068 } catch (InterruptedException e) { 16069 } 16070 } 16071 } 16072 if (conn.mContainerService == null) { 16073 return; 16074 } 16075 16076 final UserEnvironment userEnv = new UserEnvironment(curUser); 16077 clearDirectory(conn.mContainerService, 16078 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16079 if (allData) { 16080 clearDirectory(conn.mContainerService, 16081 userEnv.buildExternalStorageAppDataDirs(packageName)); 16082 clearDirectory(conn.mContainerService, 16083 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16084 } 16085 } 16086 } finally { 16087 mContext.unbindService(conn); 16088 } 16089 } 16090 } 16091 16092 @Override 16093 public void clearApplicationProfileData(String packageName) { 16094 enforceSystemOrRoot("Only the system can clear all profile data"); 16095 16096 final PackageParser.Package pkg; 16097 synchronized (mPackages) { 16098 pkg = mPackages.get(packageName); 16099 } 16100 16101 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16102 synchronized (mInstallLock) { 16103 clearAppProfilesLIF(pkg); 16104 } 16105 } 16106 } 16107 16108 @Override 16109 public void clearApplicationUserData(final String packageName, 16110 final IPackageDataObserver observer, final int userId) { 16111 mContext.enforceCallingOrSelfPermission( 16112 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16113 16114 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16115 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16116 16117 final DevicePolicyManagerInternal dpmi = LocalServices 16118 .getService(DevicePolicyManagerInternal.class); 16119 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16120 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16121 } 16122 // Queue up an async operation since the package deletion may take a little while. 16123 mHandler.post(new Runnable() { 16124 public void run() { 16125 mHandler.removeCallbacks(this); 16126 final boolean succeeded; 16127 try (PackageFreezer freezer = freezePackage(packageName, 16128 "clearApplicationUserData")) { 16129 synchronized (mInstallLock) { 16130 succeeded = clearApplicationUserDataLIF(packageName, userId); 16131 } 16132 clearExternalStorageDataSync(packageName, userId, true); 16133 } 16134 if (succeeded) { 16135 // invoke DeviceStorageMonitor's update method to clear any notifications 16136 DeviceStorageMonitorInternal dsm = LocalServices 16137 .getService(DeviceStorageMonitorInternal.class); 16138 if (dsm != null) { 16139 dsm.checkMemory(); 16140 } 16141 } 16142 if(observer != null) { 16143 try { 16144 observer.onRemoveCompleted(packageName, succeeded); 16145 } catch (RemoteException e) { 16146 Log.i(TAG, "Observer no longer exists."); 16147 } 16148 } //end if observer 16149 } //end run 16150 }); 16151 } 16152 16153 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16154 if (packageName == null) { 16155 Slog.w(TAG, "Attempt to delete null packageName."); 16156 return false; 16157 } 16158 16159 // Try finding details about the requested package 16160 PackageParser.Package pkg; 16161 synchronized (mPackages) { 16162 pkg = mPackages.get(packageName); 16163 if (pkg == null) { 16164 final PackageSetting ps = mSettings.mPackages.get(packageName); 16165 if (ps != null) { 16166 pkg = ps.pkg; 16167 } 16168 } 16169 16170 if (pkg == null) { 16171 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16172 return false; 16173 } 16174 16175 PackageSetting ps = (PackageSetting) pkg.mExtras; 16176 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16177 } 16178 16179 clearAppDataLIF(pkg, userId, 16180 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16181 16182 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16183 removeKeystoreDataIfNeeded(userId, appId); 16184 16185 final UserManager um = mContext.getSystemService(UserManager.class); 16186 final int flags; 16187 if (um.isUserUnlockingOrUnlocked(userId)) { 16188 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16189 } else if (um.isUserRunning(userId)) { 16190 flags = StorageManager.FLAG_STORAGE_DE; 16191 } else { 16192 flags = 0; 16193 } 16194 prepareAppDataContentsLIF(pkg, userId, flags); 16195 16196 return true; 16197 } 16198 16199 /** 16200 * Reverts user permission state changes (permissions and flags) in 16201 * all packages for a given user. 16202 * 16203 * @param userId The device user for which to do a reset. 16204 */ 16205 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16206 final int packageCount = mPackages.size(); 16207 for (int i = 0; i < packageCount; i++) { 16208 PackageParser.Package pkg = mPackages.valueAt(i); 16209 PackageSetting ps = (PackageSetting) pkg.mExtras; 16210 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16211 } 16212 } 16213 16214 private void resetNetworkPolicies(int userId) { 16215 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16216 } 16217 16218 /** 16219 * Reverts user permission state changes (permissions and flags). 16220 * 16221 * @param ps The package for which to reset. 16222 * @param userId The device user for which to do a reset. 16223 */ 16224 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16225 final PackageSetting ps, final int userId) { 16226 if (ps.pkg == null) { 16227 return; 16228 } 16229 16230 // These are flags that can change base on user actions. 16231 final int userSettableMask = FLAG_PERMISSION_USER_SET 16232 | FLAG_PERMISSION_USER_FIXED 16233 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16234 | FLAG_PERMISSION_REVIEW_REQUIRED; 16235 16236 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16237 | FLAG_PERMISSION_POLICY_FIXED; 16238 16239 boolean writeInstallPermissions = false; 16240 boolean writeRuntimePermissions = false; 16241 16242 final int permissionCount = ps.pkg.requestedPermissions.size(); 16243 for (int i = 0; i < permissionCount; i++) { 16244 String permission = ps.pkg.requestedPermissions.get(i); 16245 16246 BasePermission bp = mSettings.mPermissions.get(permission); 16247 if (bp == null) { 16248 continue; 16249 } 16250 16251 // If shared user we just reset the state to which only this app contributed. 16252 if (ps.sharedUser != null) { 16253 boolean used = false; 16254 final int packageCount = ps.sharedUser.packages.size(); 16255 for (int j = 0; j < packageCount; j++) { 16256 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16257 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16258 && pkg.pkg.requestedPermissions.contains(permission)) { 16259 used = true; 16260 break; 16261 } 16262 } 16263 if (used) { 16264 continue; 16265 } 16266 } 16267 16268 PermissionsState permissionsState = ps.getPermissionsState(); 16269 16270 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16271 16272 // Always clear the user settable flags. 16273 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16274 bp.name) != null; 16275 // If permission review is enabled and this is a legacy app, mark the 16276 // permission as requiring a review as this is the initial state. 16277 int flags = 0; 16278 if (Build.PERMISSIONS_REVIEW_REQUIRED 16279 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16280 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16281 } 16282 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16283 if (hasInstallState) { 16284 writeInstallPermissions = true; 16285 } else { 16286 writeRuntimePermissions = true; 16287 } 16288 } 16289 16290 // Below is only runtime permission handling. 16291 if (!bp.isRuntime()) { 16292 continue; 16293 } 16294 16295 // Never clobber system or policy. 16296 if ((oldFlags & policyOrSystemFlags) != 0) { 16297 continue; 16298 } 16299 16300 // If this permission was granted by default, make sure it is. 16301 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16302 if (permissionsState.grantRuntimePermission(bp, userId) 16303 != PERMISSION_OPERATION_FAILURE) { 16304 writeRuntimePermissions = true; 16305 } 16306 // If permission review is enabled the permissions for a legacy apps 16307 // are represented as constantly granted runtime ones, so don't revoke. 16308 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16309 // Otherwise, reset the permission. 16310 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16311 switch (revokeResult) { 16312 case PERMISSION_OPERATION_SUCCESS: 16313 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16314 writeRuntimePermissions = true; 16315 final int appId = ps.appId; 16316 mHandler.post(new Runnable() { 16317 @Override 16318 public void run() { 16319 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16320 } 16321 }); 16322 } break; 16323 } 16324 } 16325 } 16326 16327 // Synchronously write as we are taking permissions away. 16328 if (writeRuntimePermissions) { 16329 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16330 } 16331 16332 // Synchronously write as we are taking permissions away. 16333 if (writeInstallPermissions) { 16334 mSettings.writeLPr(); 16335 } 16336 } 16337 16338 /** 16339 * Remove entries from the keystore daemon. Will only remove it if the 16340 * {@code appId} is valid. 16341 */ 16342 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16343 if (appId < 0) { 16344 return; 16345 } 16346 16347 final KeyStore keyStore = KeyStore.getInstance(); 16348 if (keyStore != null) { 16349 if (userId == UserHandle.USER_ALL) { 16350 for (final int individual : sUserManager.getUserIds()) { 16351 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16352 } 16353 } else { 16354 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16355 } 16356 } else { 16357 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16358 } 16359 } 16360 16361 @Override 16362 public void deleteApplicationCacheFiles(final String packageName, 16363 final IPackageDataObserver observer) { 16364 final int userId = UserHandle.getCallingUserId(); 16365 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16366 } 16367 16368 @Override 16369 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16370 final IPackageDataObserver observer) { 16371 mContext.enforceCallingOrSelfPermission( 16372 android.Manifest.permission.DELETE_CACHE_FILES, null); 16373 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16374 /* requireFullPermission= */ true, /* checkShell= */ false, 16375 "delete application cache files"); 16376 16377 final PackageParser.Package pkg; 16378 synchronized (mPackages) { 16379 pkg = mPackages.get(packageName); 16380 } 16381 16382 // Queue up an async operation since the package deletion may take a little while. 16383 mHandler.post(new Runnable() { 16384 public void run() { 16385 synchronized (mInstallLock) { 16386 final int flags = StorageManager.FLAG_STORAGE_DE 16387 | StorageManager.FLAG_STORAGE_CE; 16388 // We're only clearing cache files, so we don't care if the 16389 // app is unfrozen and still able to run 16390 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16391 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16392 } 16393 clearExternalStorageDataSync(packageName, userId, false); 16394 if (observer != null) { 16395 try { 16396 observer.onRemoveCompleted(packageName, true); 16397 } catch (RemoteException e) { 16398 Log.i(TAG, "Observer no longer exists."); 16399 } 16400 } 16401 } 16402 }); 16403 } 16404 16405 @Override 16406 public void getPackageSizeInfo(final String packageName, int userHandle, 16407 final IPackageStatsObserver observer) { 16408 mContext.enforceCallingOrSelfPermission( 16409 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16410 if (packageName == null) { 16411 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16412 } 16413 16414 PackageStats stats = new PackageStats(packageName, userHandle); 16415 16416 /* 16417 * Queue up an async operation since the package measurement may take a 16418 * little while. 16419 */ 16420 Message msg = mHandler.obtainMessage(INIT_COPY); 16421 msg.obj = new MeasureParams(stats, observer); 16422 mHandler.sendMessage(msg); 16423 } 16424 16425 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16426 final PackageSetting ps; 16427 synchronized (mPackages) { 16428 ps = mSettings.mPackages.get(packageName); 16429 if (ps == null) { 16430 Slog.w(TAG, "Failed to find settings for " + packageName); 16431 return false; 16432 } 16433 } 16434 try { 16435 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16436 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16437 ps.getCeDataInode(userId), ps.codePathString, stats); 16438 } catch (InstallerException e) { 16439 Slog.w(TAG, String.valueOf(e)); 16440 return false; 16441 } 16442 16443 // For now, ignore code size of packages on system partition 16444 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16445 stats.codeSize = 0; 16446 } 16447 16448 return true; 16449 } 16450 16451 private int getUidTargetSdkVersionLockedLPr(int uid) { 16452 Object obj = mSettings.getUserIdLPr(uid); 16453 if (obj instanceof SharedUserSetting) { 16454 final SharedUserSetting sus = (SharedUserSetting) obj; 16455 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16456 final Iterator<PackageSetting> it = sus.packages.iterator(); 16457 while (it.hasNext()) { 16458 final PackageSetting ps = it.next(); 16459 if (ps.pkg != null) { 16460 int v = ps.pkg.applicationInfo.targetSdkVersion; 16461 if (v < vers) vers = v; 16462 } 16463 } 16464 return vers; 16465 } else if (obj instanceof PackageSetting) { 16466 final PackageSetting ps = (PackageSetting) obj; 16467 if (ps.pkg != null) { 16468 return ps.pkg.applicationInfo.targetSdkVersion; 16469 } 16470 } 16471 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16472 } 16473 16474 @Override 16475 public void addPreferredActivity(IntentFilter filter, int match, 16476 ComponentName[] set, ComponentName activity, int userId) { 16477 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16478 "Adding preferred"); 16479 } 16480 16481 private void addPreferredActivityInternal(IntentFilter filter, int match, 16482 ComponentName[] set, ComponentName activity, boolean always, int userId, 16483 String opname) { 16484 // writer 16485 int callingUid = Binder.getCallingUid(); 16486 enforceCrossUserPermission(callingUid, userId, 16487 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16488 if (filter.countActions() == 0) { 16489 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16490 return; 16491 } 16492 synchronized (mPackages) { 16493 if (mContext.checkCallingOrSelfPermission( 16494 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16495 != PackageManager.PERMISSION_GRANTED) { 16496 if (getUidTargetSdkVersionLockedLPr(callingUid) 16497 < Build.VERSION_CODES.FROYO) { 16498 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16499 + callingUid); 16500 return; 16501 } 16502 mContext.enforceCallingOrSelfPermission( 16503 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16504 } 16505 16506 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16507 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16508 + userId + ":"); 16509 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16510 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16511 scheduleWritePackageRestrictionsLocked(userId); 16512 } 16513 } 16514 16515 @Override 16516 public void replacePreferredActivity(IntentFilter filter, int match, 16517 ComponentName[] set, ComponentName activity, int userId) { 16518 if (filter.countActions() != 1) { 16519 throw new IllegalArgumentException( 16520 "replacePreferredActivity expects filter to have only 1 action."); 16521 } 16522 if (filter.countDataAuthorities() != 0 16523 || filter.countDataPaths() != 0 16524 || filter.countDataSchemes() > 1 16525 || filter.countDataTypes() != 0) { 16526 throw new IllegalArgumentException( 16527 "replacePreferredActivity expects filter to have no data authorities, " + 16528 "paths, or types; and at most one scheme."); 16529 } 16530 16531 final int callingUid = Binder.getCallingUid(); 16532 enforceCrossUserPermission(callingUid, userId, 16533 true /* requireFullPermission */, false /* checkShell */, 16534 "replace preferred activity"); 16535 synchronized (mPackages) { 16536 if (mContext.checkCallingOrSelfPermission( 16537 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16538 != PackageManager.PERMISSION_GRANTED) { 16539 if (getUidTargetSdkVersionLockedLPr(callingUid) 16540 < Build.VERSION_CODES.FROYO) { 16541 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16542 + Binder.getCallingUid()); 16543 return; 16544 } 16545 mContext.enforceCallingOrSelfPermission( 16546 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16547 } 16548 16549 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16550 if (pir != null) { 16551 // Get all of the existing entries that exactly match this filter. 16552 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16553 if (existing != null && existing.size() == 1) { 16554 PreferredActivity cur = existing.get(0); 16555 if (DEBUG_PREFERRED) { 16556 Slog.i(TAG, "Checking replace of preferred:"); 16557 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16558 if (!cur.mPref.mAlways) { 16559 Slog.i(TAG, " -- CUR; not mAlways!"); 16560 } else { 16561 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16562 Slog.i(TAG, " -- CUR: mSet=" 16563 + Arrays.toString(cur.mPref.mSetComponents)); 16564 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16565 Slog.i(TAG, " -- NEW: mMatch=" 16566 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16567 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16568 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16569 } 16570 } 16571 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16572 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16573 && cur.mPref.sameSet(set)) { 16574 // Setting the preferred activity to what it happens to be already 16575 if (DEBUG_PREFERRED) { 16576 Slog.i(TAG, "Replacing with same preferred activity " 16577 + cur.mPref.mShortComponent + " for user " 16578 + userId + ":"); 16579 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16580 } 16581 return; 16582 } 16583 } 16584 16585 if (existing != null) { 16586 if (DEBUG_PREFERRED) { 16587 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16588 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16589 } 16590 for (int i = 0; i < existing.size(); i++) { 16591 PreferredActivity pa = existing.get(i); 16592 if (DEBUG_PREFERRED) { 16593 Slog.i(TAG, "Removing existing preferred activity " 16594 + pa.mPref.mComponent + ":"); 16595 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16596 } 16597 pir.removeFilter(pa); 16598 } 16599 } 16600 } 16601 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16602 "Replacing preferred"); 16603 } 16604 } 16605 16606 @Override 16607 public void clearPackagePreferredActivities(String packageName) { 16608 final int uid = Binder.getCallingUid(); 16609 // writer 16610 synchronized (mPackages) { 16611 PackageParser.Package pkg = mPackages.get(packageName); 16612 if (pkg == null || pkg.applicationInfo.uid != uid) { 16613 if (mContext.checkCallingOrSelfPermission( 16614 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16615 != PackageManager.PERMISSION_GRANTED) { 16616 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16617 < Build.VERSION_CODES.FROYO) { 16618 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16619 + Binder.getCallingUid()); 16620 return; 16621 } 16622 mContext.enforceCallingOrSelfPermission( 16623 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16624 } 16625 } 16626 16627 int user = UserHandle.getCallingUserId(); 16628 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16629 scheduleWritePackageRestrictionsLocked(user); 16630 } 16631 } 16632 } 16633 16634 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16635 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16636 ArrayList<PreferredActivity> removed = null; 16637 boolean changed = false; 16638 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16639 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16640 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16641 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16642 continue; 16643 } 16644 Iterator<PreferredActivity> it = pir.filterIterator(); 16645 while (it.hasNext()) { 16646 PreferredActivity pa = it.next(); 16647 // Mark entry for removal only if it matches the package name 16648 // and the entry is of type "always". 16649 if (packageName == null || 16650 (pa.mPref.mComponent.getPackageName().equals(packageName) 16651 && pa.mPref.mAlways)) { 16652 if (removed == null) { 16653 removed = new ArrayList<PreferredActivity>(); 16654 } 16655 removed.add(pa); 16656 } 16657 } 16658 if (removed != null) { 16659 for (int j=0; j<removed.size(); j++) { 16660 PreferredActivity pa = removed.get(j); 16661 pir.removeFilter(pa); 16662 } 16663 changed = true; 16664 } 16665 } 16666 return changed; 16667 } 16668 16669 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16670 private void clearIntentFilterVerificationsLPw(int userId) { 16671 final int packageCount = mPackages.size(); 16672 for (int i = 0; i < packageCount; i++) { 16673 PackageParser.Package pkg = mPackages.valueAt(i); 16674 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16675 } 16676 } 16677 16678 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16679 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16680 if (userId == UserHandle.USER_ALL) { 16681 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16682 sUserManager.getUserIds())) { 16683 for (int oneUserId : sUserManager.getUserIds()) { 16684 scheduleWritePackageRestrictionsLocked(oneUserId); 16685 } 16686 } 16687 } else { 16688 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16689 scheduleWritePackageRestrictionsLocked(userId); 16690 } 16691 } 16692 } 16693 16694 void clearDefaultBrowserIfNeeded(String packageName) { 16695 for (int oneUserId : sUserManager.getUserIds()) { 16696 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16697 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16698 if (packageName.equals(defaultBrowserPackageName)) { 16699 setDefaultBrowserPackageName(null, oneUserId); 16700 } 16701 } 16702 } 16703 16704 @Override 16705 public void resetApplicationPreferences(int userId) { 16706 mContext.enforceCallingOrSelfPermission( 16707 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16708 final long identity = Binder.clearCallingIdentity(); 16709 // writer 16710 try { 16711 synchronized (mPackages) { 16712 clearPackagePreferredActivitiesLPw(null, userId); 16713 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16714 // TODO: We have to reset the default SMS and Phone. This requires 16715 // significant refactoring to keep all default apps in the package 16716 // manager (cleaner but more work) or have the services provide 16717 // callbacks to the package manager to request a default app reset. 16718 applyFactoryDefaultBrowserLPw(userId); 16719 clearIntentFilterVerificationsLPw(userId); 16720 primeDomainVerificationsLPw(userId); 16721 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16722 scheduleWritePackageRestrictionsLocked(userId); 16723 } 16724 resetNetworkPolicies(userId); 16725 } finally { 16726 Binder.restoreCallingIdentity(identity); 16727 } 16728 } 16729 16730 @Override 16731 public int getPreferredActivities(List<IntentFilter> outFilters, 16732 List<ComponentName> outActivities, String packageName) { 16733 16734 int num = 0; 16735 final int userId = UserHandle.getCallingUserId(); 16736 // reader 16737 synchronized (mPackages) { 16738 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16739 if (pir != null) { 16740 final Iterator<PreferredActivity> it = pir.filterIterator(); 16741 while (it.hasNext()) { 16742 final PreferredActivity pa = it.next(); 16743 if (packageName == null 16744 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16745 && pa.mPref.mAlways)) { 16746 if (outFilters != null) { 16747 outFilters.add(new IntentFilter(pa)); 16748 } 16749 if (outActivities != null) { 16750 outActivities.add(pa.mPref.mComponent); 16751 } 16752 } 16753 } 16754 } 16755 } 16756 16757 return num; 16758 } 16759 16760 @Override 16761 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16762 int userId) { 16763 int callingUid = Binder.getCallingUid(); 16764 if (callingUid != Process.SYSTEM_UID) { 16765 throw new SecurityException( 16766 "addPersistentPreferredActivity can only be run by the system"); 16767 } 16768 if (filter.countActions() == 0) { 16769 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16770 return; 16771 } 16772 synchronized (mPackages) { 16773 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16774 ":"); 16775 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16776 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16777 new PersistentPreferredActivity(filter, activity)); 16778 scheduleWritePackageRestrictionsLocked(userId); 16779 } 16780 } 16781 16782 @Override 16783 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16784 int callingUid = Binder.getCallingUid(); 16785 if (callingUid != Process.SYSTEM_UID) { 16786 throw new SecurityException( 16787 "clearPackagePersistentPreferredActivities can only be run by the system"); 16788 } 16789 ArrayList<PersistentPreferredActivity> removed = null; 16790 boolean changed = false; 16791 synchronized (mPackages) { 16792 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16793 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16794 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16795 .valueAt(i); 16796 if (userId != thisUserId) { 16797 continue; 16798 } 16799 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16800 while (it.hasNext()) { 16801 PersistentPreferredActivity ppa = it.next(); 16802 // Mark entry for removal only if it matches the package name. 16803 if (ppa.mComponent.getPackageName().equals(packageName)) { 16804 if (removed == null) { 16805 removed = new ArrayList<PersistentPreferredActivity>(); 16806 } 16807 removed.add(ppa); 16808 } 16809 } 16810 if (removed != null) { 16811 for (int j=0; j<removed.size(); j++) { 16812 PersistentPreferredActivity ppa = removed.get(j); 16813 ppir.removeFilter(ppa); 16814 } 16815 changed = true; 16816 } 16817 } 16818 16819 if (changed) { 16820 scheduleWritePackageRestrictionsLocked(userId); 16821 } 16822 } 16823 } 16824 16825 /** 16826 * Common machinery for picking apart a restored XML blob and passing 16827 * it to a caller-supplied functor to be applied to the running system. 16828 */ 16829 private void restoreFromXml(XmlPullParser parser, int userId, 16830 String expectedStartTag, BlobXmlRestorer functor) 16831 throws IOException, XmlPullParserException { 16832 int type; 16833 while ((type = parser.next()) != XmlPullParser.START_TAG 16834 && type != XmlPullParser.END_DOCUMENT) { 16835 } 16836 if (type != XmlPullParser.START_TAG) { 16837 // oops didn't find a start tag?! 16838 if (DEBUG_BACKUP) { 16839 Slog.e(TAG, "Didn't find start tag during restore"); 16840 } 16841 return; 16842 } 16843Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16844 // this is supposed to be TAG_PREFERRED_BACKUP 16845 if (!expectedStartTag.equals(parser.getName())) { 16846 if (DEBUG_BACKUP) { 16847 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16848 } 16849 return; 16850 } 16851 16852 // skip interfering stuff, then we're aligned with the backing implementation 16853 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16854Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16855 functor.apply(parser, userId); 16856 } 16857 16858 private interface BlobXmlRestorer { 16859 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16860 } 16861 16862 /** 16863 * Non-Binder method, support for the backup/restore mechanism: write the 16864 * full set of preferred activities in its canonical XML format. Returns the 16865 * XML output as a byte array, or null if there is none. 16866 */ 16867 @Override 16868 public byte[] getPreferredActivityBackup(int userId) { 16869 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16870 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16871 } 16872 16873 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16874 try { 16875 final XmlSerializer serializer = new FastXmlSerializer(); 16876 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16877 serializer.startDocument(null, true); 16878 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16879 16880 synchronized (mPackages) { 16881 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16882 } 16883 16884 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16885 serializer.endDocument(); 16886 serializer.flush(); 16887 } catch (Exception e) { 16888 if (DEBUG_BACKUP) { 16889 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16890 } 16891 return null; 16892 } 16893 16894 return dataStream.toByteArray(); 16895 } 16896 16897 @Override 16898 public void restorePreferredActivities(byte[] backup, int userId) { 16899 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16900 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16901 } 16902 16903 try { 16904 final XmlPullParser parser = Xml.newPullParser(); 16905 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16906 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16907 new BlobXmlRestorer() { 16908 @Override 16909 public void apply(XmlPullParser parser, int userId) 16910 throws XmlPullParserException, IOException { 16911 synchronized (mPackages) { 16912 mSettings.readPreferredActivitiesLPw(parser, userId); 16913 } 16914 } 16915 } ); 16916 } catch (Exception e) { 16917 if (DEBUG_BACKUP) { 16918 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16919 } 16920 } 16921 } 16922 16923 /** 16924 * Non-Binder method, support for the backup/restore mechanism: write the 16925 * default browser (etc) settings in its canonical XML format. Returns the default 16926 * browser XML representation as a byte array, or null if there is none. 16927 */ 16928 @Override 16929 public byte[] getDefaultAppsBackup(int userId) { 16930 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16931 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16932 } 16933 16934 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16935 try { 16936 final XmlSerializer serializer = new FastXmlSerializer(); 16937 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16938 serializer.startDocument(null, true); 16939 serializer.startTag(null, TAG_DEFAULT_APPS); 16940 16941 synchronized (mPackages) { 16942 mSettings.writeDefaultAppsLPr(serializer, userId); 16943 } 16944 16945 serializer.endTag(null, TAG_DEFAULT_APPS); 16946 serializer.endDocument(); 16947 serializer.flush(); 16948 } catch (Exception e) { 16949 if (DEBUG_BACKUP) { 16950 Slog.e(TAG, "Unable to write default apps for backup", e); 16951 } 16952 return null; 16953 } 16954 16955 return dataStream.toByteArray(); 16956 } 16957 16958 @Override 16959 public void restoreDefaultApps(byte[] backup, int userId) { 16960 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16961 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16962 } 16963 16964 try { 16965 final XmlPullParser parser = Xml.newPullParser(); 16966 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16967 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16968 new BlobXmlRestorer() { 16969 @Override 16970 public void apply(XmlPullParser parser, int userId) 16971 throws XmlPullParserException, IOException { 16972 synchronized (mPackages) { 16973 mSettings.readDefaultAppsLPw(parser, userId); 16974 } 16975 } 16976 } ); 16977 } catch (Exception e) { 16978 if (DEBUG_BACKUP) { 16979 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16980 } 16981 } 16982 } 16983 16984 @Override 16985 public byte[] getIntentFilterVerificationBackup(int userId) { 16986 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16987 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16988 } 16989 16990 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16991 try { 16992 final XmlSerializer serializer = new FastXmlSerializer(); 16993 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16994 serializer.startDocument(null, true); 16995 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16996 16997 synchronized (mPackages) { 16998 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16999 } 17000 17001 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17002 serializer.endDocument(); 17003 serializer.flush(); 17004 } catch (Exception e) { 17005 if (DEBUG_BACKUP) { 17006 Slog.e(TAG, "Unable to write default apps for backup", e); 17007 } 17008 return null; 17009 } 17010 17011 return dataStream.toByteArray(); 17012 } 17013 17014 @Override 17015 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17016 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17017 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17018 } 17019 17020 try { 17021 final XmlPullParser parser = Xml.newPullParser(); 17022 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17023 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17024 new BlobXmlRestorer() { 17025 @Override 17026 public void apply(XmlPullParser parser, int userId) 17027 throws XmlPullParserException, IOException { 17028 synchronized (mPackages) { 17029 mSettings.readAllDomainVerificationsLPr(parser, userId); 17030 mSettings.writeLPr(); 17031 } 17032 } 17033 } ); 17034 } catch (Exception e) { 17035 if (DEBUG_BACKUP) { 17036 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17037 } 17038 } 17039 } 17040 17041 @Override 17042 public byte[] getPermissionGrantBackup(int userId) { 17043 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17044 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17045 } 17046 17047 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17048 try { 17049 final XmlSerializer serializer = new FastXmlSerializer(); 17050 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17051 serializer.startDocument(null, true); 17052 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17053 17054 synchronized (mPackages) { 17055 serializeRuntimePermissionGrantsLPr(serializer, userId); 17056 } 17057 17058 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17059 serializer.endDocument(); 17060 serializer.flush(); 17061 } catch (Exception e) { 17062 if (DEBUG_BACKUP) { 17063 Slog.e(TAG, "Unable to write default apps for backup", e); 17064 } 17065 return null; 17066 } 17067 17068 return dataStream.toByteArray(); 17069 } 17070 17071 @Override 17072 public void restorePermissionGrants(byte[] backup, int userId) { 17073 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17074 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17075 } 17076 17077 try { 17078 final XmlPullParser parser = Xml.newPullParser(); 17079 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17080 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17081 new BlobXmlRestorer() { 17082 @Override 17083 public void apply(XmlPullParser parser, int userId) 17084 throws XmlPullParserException, IOException { 17085 synchronized (mPackages) { 17086 processRestoredPermissionGrantsLPr(parser, userId); 17087 } 17088 } 17089 } ); 17090 } catch (Exception e) { 17091 if (DEBUG_BACKUP) { 17092 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17093 } 17094 } 17095 } 17096 17097 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17098 throws IOException { 17099 serializer.startTag(null, TAG_ALL_GRANTS); 17100 17101 final int N = mSettings.mPackages.size(); 17102 for (int i = 0; i < N; i++) { 17103 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17104 boolean pkgGrantsKnown = false; 17105 17106 PermissionsState packagePerms = ps.getPermissionsState(); 17107 17108 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17109 final int grantFlags = state.getFlags(); 17110 // only look at grants that are not system/policy fixed 17111 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17112 final boolean isGranted = state.isGranted(); 17113 // And only back up the user-twiddled state bits 17114 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17115 final String packageName = mSettings.mPackages.keyAt(i); 17116 if (!pkgGrantsKnown) { 17117 serializer.startTag(null, TAG_GRANT); 17118 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17119 pkgGrantsKnown = true; 17120 } 17121 17122 final boolean userSet = 17123 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17124 final boolean userFixed = 17125 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17126 final boolean revoke = 17127 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17128 17129 serializer.startTag(null, TAG_PERMISSION); 17130 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17131 if (isGranted) { 17132 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17133 } 17134 if (userSet) { 17135 serializer.attribute(null, ATTR_USER_SET, "true"); 17136 } 17137 if (userFixed) { 17138 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17139 } 17140 if (revoke) { 17141 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17142 } 17143 serializer.endTag(null, TAG_PERMISSION); 17144 } 17145 } 17146 } 17147 17148 if (pkgGrantsKnown) { 17149 serializer.endTag(null, TAG_GRANT); 17150 } 17151 } 17152 17153 serializer.endTag(null, TAG_ALL_GRANTS); 17154 } 17155 17156 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17157 throws XmlPullParserException, IOException { 17158 String pkgName = null; 17159 int outerDepth = parser.getDepth(); 17160 int type; 17161 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17162 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17163 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17164 continue; 17165 } 17166 17167 final String tagName = parser.getName(); 17168 if (tagName.equals(TAG_GRANT)) { 17169 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17170 if (DEBUG_BACKUP) { 17171 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17172 } 17173 } else if (tagName.equals(TAG_PERMISSION)) { 17174 17175 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17176 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17177 17178 int newFlagSet = 0; 17179 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17180 newFlagSet |= FLAG_PERMISSION_USER_SET; 17181 } 17182 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17183 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17184 } 17185 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17186 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17187 } 17188 if (DEBUG_BACKUP) { 17189 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17190 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17191 } 17192 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17193 if (ps != null) { 17194 // Already installed so we apply the grant immediately 17195 if (DEBUG_BACKUP) { 17196 Slog.v(TAG, " + already installed; applying"); 17197 } 17198 PermissionsState perms = ps.getPermissionsState(); 17199 BasePermission bp = mSettings.mPermissions.get(permName); 17200 if (bp != null) { 17201 if (isGranted) { 17202 perms.grantRuntimePermission(bp, userId); 17203 } 17204 if (newFlagSet != 0) { 17205 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17206 } 17207 } 17208 } else { 17209 // Need to wait for post-restore install to apply the grant 17210 if (DEBUG_BACKUP) { 17211 Slog.v(TAG, " - not yet installed; saving for later"); 17212 } 17213 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17214 isGranted, newFlagSet, userId); 17215 } 17216 } else { 17217 PackageManagerService.reportSettingsProblem(Log.WARN, 17218 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17219 XmlUtils.skipCurrentTag(parser); 17220 } 17221 } 17222 17223 scheduleWriteSettingsLocked(); 17224 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17225 } 17226 17227 @Override 17228 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17229 int sourceUserId, int targetUserId, int flags) { 17230 mContext.enforceCallingOrSelfPermission( 17231 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17232 int callingUid = Binder.getCallingUid(); 17233 enforceOwnerRights(ownerPackage, callingUid); 17234 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17235 if (intentFilter.countActions() == 0) { 17236 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17237 return; 17238 } 17239 synchronized (mPackages) { 17240 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17241 ownerPackage, targetUserId, flags); 17242 CrossProfileIntentResolver resolver = 17243 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17244 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17245 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17246 if (existing != null) { 17247 int size = existing.size(); 17248 for (int i = 0; i < size; i++) { 17249 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17250 return; 17251 } 17252 } 17253 } 17254 resolver.addFilter(newFilter); 17255 scheduleWritePackageRestrictionsLocked(sourceUserId); 17256 } 17257 } 17258 17259 @Override 17260 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17261 mContext.enforceCallingOrSelfPermission( 17262 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17263 int callingUid = Binder.getCallingUid(); 17264 enforceOwnerRights(ownerPackage, callingUid); 17265 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17266 synchronized (mPackages) { 17267 CrossProfileIntentResolver resolver = 17268 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17269 ArraySet<CrossProfileIntentFilter> set = 17270 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17271 for (CrossProfileIntentFilter filter : set) { 17272 if (filter.getOwnerPackage().equals(ownerPackage)) { 17273 resolver.removeFilter(filter); 17274 } 17275 } 17276 scheduleWritePackageRestrictionsLocked(sourceUserId); 17277 } 17278 } 17279 17280 // Enforcing that callingUid is owning pkg on userId 17281 private void enforceOwnerRights(String pkg, int callingUid) { 17282 // The system owns everything. 17283 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17284 return; 17285 } 17286 int callingUserId = UserHandle.getUserId(callingUid); 17287 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17288 if (pi == null) { 17289 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17290 + callingUserId); 17291 } 17292 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17293 throw new SecurityException("Calling uid " + callingUid 17294 + " does not own package " + pkg); 17295 } 17296 } 17297 17298 @Override 17299 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17300 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17301 } 17302 17303 private Intent getHomeIntent() { 17304 Intent intent = new Intent(Intent.ACTION_MAIN); 17305 intent.addCategory(Intent.CATEGORY_HOME); 17306 return intent; 17307 } 17308 17309 private IntentFilter getHomeFilter() { 17310 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17311 filter.addCategory(Intent.CATEGORY_HOME); 17312 filter.addCategory(Intent.CATEGORY_DEFAULT); 17313 return filter; 17314 } 17315 17316 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17317 int userId) { 17318 Intent intent = getHomeIntent(); 17319 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17320 PackageManager.GET_META_DATA, userId); 17321 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17322 true, false, false, userId); 17323 17324 allHomeCandidates.clear(); 17325 if (list != null) { 17326 for (ResolveInfo ri : list) { 17327 allHomeCandidates.add(ri); 17328 } 17329 } 17330 return (preferred == null || preferred.activityInfo == null) 17331 ? null 17332 : new ComponentName(preferred.activityInfo.packageName, 17333 preferred.activityInfo.name); 17334 } 17335 17336 @Override 17337 public void setHomeActivity(ComponentName comp, int userId) { 17338 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17339 getHomeActivitiesAsUser(homeActivities, userId); 17340 17341 boolean found = false; 17342 17343 final int size = homeActivities.size(); 17344 final ComponentName[] set = new ComponentName[size]; 17345 for (int i = 0; i < size; i++) { 17346 final ResolveInfo candidate = homeActivities.get(i); 17347 final ActivityInfo info = candidate.activityInfo; 17348 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17349 set[i] = activityName; 17350 if (!found && activityName.equals(comp)) { 17351 found = true; 17352 } 17353 } 17354 if (!found) { 17355 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17356 + userId); 17357 } 17358 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17359 set, comp, userId); 17360 } 17361 17362 private @Nullable String getSetupWizardPackageName() { 17363 final Intent intent = new Intent(Intent.ACTION_MAIN); 17364 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17365 17366 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17367 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17368 | MATCH_DISABLED_COMPONENTS, 17369 UserHandle.myUserId()); 17370 if (matches.size() == 1) { 17371 return matches.get(0).getComponentInfo().packageName; 17372 } else { 17373 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17374 + ": matches=" + matches); 17375 return null; 17376 } 17377 } 17378 17379 @Override 17380 public void setApplicationEnabledSetting(String appPackageName, 17381 int newState, int flags, int userId, String callingPackage) { 17382 if (!sUserManager.exists(userId)) return; 17383 if (callingPackage == null) { 17384 callingPackage = Integer.toString(Binder.getCallingUid()); 17385 } 17386 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17387 } 17388 17389 @Override 17390 public void setComponentEnabledSetting(ComponentName componentName, 17391 int newState, int flags, int userId) { 17392 if (!sUserManager.exists(userId)) return; 17393 setEnabledSetting(componentName.getPackageName(), 17394 componentName.getClassName(), newState, flags, userId, null); 17395 } 17396 17397 private void setEnabledSetting(final String packageName, String className, int newState, 17398 final int flags, int userId, String callingPackage) { 17399 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17400 || newState == COMPONENT_ENABLED_STATE_ENABLED 17401 || newState == COMPONENT_ENABLED_STATE_DISABLED 17402 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17403 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17404 throw new IllegalArgumentException("Invalid new component state: " 17405 + newState); 17406 } 17407 PackageSetting pkgSetting; 17408 final int uid = Binder.getCallingUid(); 17409 final int permission; 17410 if (uid == Process.SYSTEM_UID) { 17411 permission = PackageManager.PERMISSION_GRANTED; 17412 } else { 17413 permission = mContext.checkCallingOrSelfPermission( 17414 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17415 } 17416 enforceCrossUserPermission(uid, userId, 17417 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17418 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17419 boolean sendNow = false; 17420 boolean isApp = (className == null); 17421 String componentName = isApp ? packageName : className; 17422 int packageUid = -1; 17423 ArrayList<String> components; 17424 17425 // writer 17426 synchronized (mPackages) { 17427 pkgSetting = mSettings.mPackages.get(packageName); 17428 if (pkgSetting == null) { 17429 if (className == null) { 17430 throw new IllegalArgumentException("Unknown package: " + packageName); 17431 } 17432 throw new IllegalArgumentException( 17433 "Unknown component: " + packageName + "/" + className); 17434 } 17435 // Allow root and verify that userId is not being specified by a different user 17436 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17437 throw new SecurityException( 17438 "Permission Denial: attempt to change component state from pid=" 17439 + Binder.getCallingPid() 17440 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17441 } 17442 if (className == null) { 17443 // We're dealing with an application/package level state change 17444 if (pkgSetting.getEnabled(userId) == newState) { 17445 // Nothing to do 17446 return; 17447 } 17448 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17449 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17450 // Don't care about who enables an app. 17451 callingPackage = null; 17452 } 17453 pkgSetting.setEnabled(newState, userId, callingPackage); 17454 // pkgSetting.pkg.mSetEnabled = newState; 17455 } else { 17456 // We're dealing with a component level state change 17457 // First, verify that this is a valid class name. 17458 PackageParser.Package pkg = pkgSetting.pkg; 17459 if (pkg == null || !pkg.hasComponentClassName(className)) { 17460 if (pkg != null && 17461 pkg.applicationInfo.targetSdkVersion >= 17462 Build.VERSION_CODES.JELLY_BEAN) { 17463 throw new IllegalArgumentException("Component class " + className 17464 + " does not exist in " + packageName); 17465 } else { 17466 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17467 + className + " does not exist in " + packageName); 17468 } 17469 } 17470 switch (newState) { 17471 case COMPONENT_ENABLED_STATE_ENABLED: 17472 if (!pkgSetting.enableComponentLPw(className, userId)) { 17473 return; 17474 } 17475 break; 17476 case COMPONENT_ENABLED_STATE_DISABLED: 17477 if (!pkgSetting.disableComponentLPw(className, userId)) { 17478 return; 17479 } 17480 break; 17481 case COMPONENT_ENABLED_STATE_DEFAULT: 17482 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17483 return; 17484 } 17485 break; 17486 default: 17487 Slog.e(TAG, "Invalid new component state: " + newState); 17488 return; 17489 } 17490 } 17491 scheduleWritePackageRestrictionsLocked(userId); 17492 components = mPendingBroadcasts.get(userId, packageName); 17493 final boolean newPackage = components == null; 17494 if (newPackage) { 17495 components = new ArrayList<String>(); 17496 } 17497 if (!components.contains(componentName)) { 17498 components.add(componentName); 17499 } 17500 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17501 sendNow = true; 17502 // Purge entry from pending broadcast list if another one exists already 17503 // since we are sending one right away. 17504 mPendingBroadcasts.remove(userId, packageName); 17505 } else { 17506 if (newPackage) { 17507 mPendingBroadcasts.put(userId, packageName, components); 17508 } 17509 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17510 // Schedule a message 17511 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17512 } 17513 } 17514 } 17515 17516 long callingId = Binder.clearCallingIdentity(); 17517 try { 17518 if (sendNow) { 17519 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17520 sendPackageChangedBroadcast(packageName, 17521 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17522 } 17523 } finally { 17524 Binder.restoreCallingIdentity(callingId); 17525 } 17526 } 17527 17528 @Override 17529 public void flushPackageRestrictionsAsUser(int userId) { 17530 if (!sUserManager.exists(userId)) { 17531 return; 17532 } 17533 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17534 false /* checkShell */, "flushPackageRestrictions"); 17535 synchronized (mPackages) { 17536 mSettings.writePackageRestrictionsLPr(userId); 17537 mDirtyUsers.remove(userId); 17538 if (mDirtyUsers.isEmpty()) { 17539 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17540 } 17541 } 17542 } 17543 17544 private void sendPackageChangedBroadcast(String packageName, 17545 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17546 if (DEBUG_INSTALL) 17547 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17548 + componentNames); 17549 Bundle extras = new Bundle(4); 17550 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17551 String nameList[] = new String[componentNames.size()]; 17552 componentNames.toArray(nameList); 17553 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17554 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17555 extras.putInt(Intent.EXTRA_UID, packageUid); 17556 // If this is not reporting a change of the overall package, then only send it 17557 // to registered receivers. We don't want to launch a swath of apps for every 17558 // little component state change. 17559 final int flags = !componentNames.contains(packageName) 17560 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17561 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17562 new int[] {UserHandle.getUserId(packageUid)}); 17563 } 17564 17565 @Override 17566 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17567 if (!sUserManager.exists(userId)) return; 17568 final int uid = Binder.getCallingUid(); 17569 final int permission = mContext.checkCallingOrSelfPermission( 17570 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17571 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17572 enforceCrossUserPermission(uid, userId, 17573 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17574 // writer 17575 synchronized (mPackages) { 17576 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17577 allowedByPermission, uid, userId)) { 17578 scheduleWritePackageRestrictionsLocked(userId); 17579 } 17580 } 17581 } 17582 17583 @Override 17584 public String getInstallerPackageName(String packageName) { 17585 // reader 17586 synchronized (mPackages) { 17587 return mSettings.getInstallerPackageNameLPr(packageName); 17588 } 17589 } 17590 17591 public boolean isOrphaned(String packageName) { 17592 // reader 17593 synchronized (mPackages) { 17594 return mSettings.isOrphaned(packageName); 17595 } 17596 } 17597 17598 @Override 17599 public int getApplicationEnabledSetting(String packageName, int userId) { 17600 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17601 int uid = Binder.getCallingUid(); 17602 enforceCrossUserPermission(uid, userId, 17603 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17604 // reader 17605 synchronized (mPackages) { 17606 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17607 } 17608 } 17609 17610 @Override 17611 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17612 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17613 int uid = Binder.getCallingUid(); 17614 enforceCrossUserPermission(uid, userId, 17615 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17616 // reader 17617 synchronized (mPackages) { 17618 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17619 } 17620 } 17621 17622 @Override 17623 public void enterSafeMode() { 17624 enforceSystemOrRoot("Only the system can request entering safe mode"); 17625 17626 if (!mSystemReady) { 17627 mSafeMode = true; 17628 } 17629 } 17630 17631 @Override 17632 public void systemReady() { 17633 mSystemReady = true; 17634 17635 // Read the compatibilty setting when the system is ready. 17636 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17637 mContext.getContentResolver(), 17638 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17639 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17640 if (DEBUG_SETTINGS) { 17641 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17642 } 17643 17644 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17645 17646 synchronized (mPackages) { 17647 // Verify that all of the preferred activity components actually 17648 // exist. It is possible for applications to be updated and at 17649 // that point remove a previously declared activity component that 17650 // had been set as a preferred activity. We try to clean this up 17651 // the next time we encounter that preferred activity, but it is 17652 // possible for the user flow to never be able to return to that 17653 // situation so here we do a sanity check to make sure we haven't 17654 // left any junk around. 17655 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17656 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17657 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17658 removed.clear(); 17659 for (PreferredActivity pa : pir.filterSet()) { 17660 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17661 removed.add(pa); 17662 } 17663 } 17664 if (removed.size() > 0) { 17665 for (int r=0; r<removed.size(); r++) { 17666 PreferredActivity pa = removed.get(r); 17667 Slog.w(TAG, "Removing dangling preferred activity: " 17668 + pa.mPref.mComponent); 17669 pir.removeFilter(pa); 17670 } 17671 mSettings.writePackageRestrictionsLPr( 17672 mSettings.mPreferredActivities.keyAt(i)); 17673 } 17674 } 17675 17676 for (int userId : UserManagerService.getInstance().getUserIds()) { 17677 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17678 grantPermissionsUserIds = ArrayUtils.appendInt( 17679 grantPermissionsUserIds, userId); 17680 } 17681 } 17682 } 17683 sUserManager.systemReady(); 17684 17685 // If we upgraded grant all default permissions before kicking off. 17686 for (int userId : grantPermissionsUserIds) { 17687 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17688 } 17689 17690 // Kick off any messages waiting for system ready 17691 if (mPostSystemReadyMessages != null) { 17692 for (Message msg : mPostSystemReadyMessages) { 17693 msg.sendToTarget(); 17694 } 17695 mPostSystemReadyMessages = null; 17696 } 17697 17698 // Watch for external volumes that come and go over time 17699 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17700 storage.registerListener(mStorageListener); 17701 17702 mInstallerService.systemReady(); 17703 mPackageDexOptimizer.systemReady(); 17704 17705 MountServiceInternal mountServiceInternal = LocalServices.getService( 17706 MountServiceInternal.class); 17707 mountServiceInternal.addExternalStoragePolicy( 17708 new MountServiceInternal.ExternalStorageMountPolicy() { 17709 @Override 17710 public int getMountMode(int uid, String packageName) { 17711 if (Process.isIsolated(uid)) { 17712 return Zygote.MOUNT_EXTERNAL_NONE; 17713 } 17714 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17715 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17716 } 17717 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17718 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17719 } 17720 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17721 return Zygote.MOUNT_EXTERNAL_READ; 17722 } 17723 return Zygote.MOUNT_EXTERNAL_WRITE; 17724 } 17725 17726 @Override 17727 public boolean hasExternalStorage(int uid, String packageName) { 17728 return true; 17729 } 17730 }); 17731 17732 // Now that we're mostly running, clean up stale users and apps 17733 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17734 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17735 } 17736 17737 @Override 17738 public boolean isSafeMode() { 17739 return mSafeMode; 17740 } 17741 17742 @Override 17743 public boolean hasSystemUidErrors() { 17744 return mHasSystemUidErrors; 17745 } 17746 17747 static String arrayToString(int[] array) { 17748 StringBuffer buf = new StringBuffer(128); 17749 buf.append('['); 17750 if (array != null) { 17751 for (int i=0; i<array.length; i++) { 17752 if (i > 0) buf.append(", "); 17753 buf.append(array[i]); 17754 } 17755 } 17756 buf.append(']'); 17757 return buf.toString(); 17758 } 17759 17760 static class DumpState { 17761 public static final int DUMP_LIBS = 1 << 0; 17762 public static final int DUMP_FEATURES = 1 << 1; 17763 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17764 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17765 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17766 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17767 public static final int DUMP_PERMISSIONS = 1 << 6; 17768 public static final int DUMP_PACKAGES = 1 << 7; 17769 public static final int DUMP_SHARED_USERS = 1 << 8; 17770 public static final int DUMP_MESSAGES = 1 << 9; 17771 public static final int DUMP_PROVIDERS = 1 << 10; 17772 public static final int DUMP_VERIFIERS = 1 << 11; 17773 public static final int DUMP_PREFERRED = 1 << 12; 17774 public static final int DUMP_PREFERRED_XML = 1 << 13; 17775 public static final int DUMP_KEYSETS = 1 << 14; 17776 public static final int DUMP_VERSION = 1 << 15; 17777 public static final int DUMP_INSTALLS = 1 << 16; 17778 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17779 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17780 public static final int DUMP_FROZEN = 1 << 19; 17781 17782 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17783 17784 private int mTypes; 17785 17786 private int mOptions; 17787 17788 private boolean mTitlePrinted; 17789 17790 private SharedUserSetting mSharedUser; 17791 17792 public boolean isDumping(int type) { 17793 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17794 return true; 17795 } 17796 17797 return (mTypes & type) != 0; 17798 } 17799 17800 public void setDump(int type) { 17801 mTypes |= type; 17802 } 17803 17804 public boolean isOptionEnabled(int option) { 17805 return (mOptions & option) != 0; 17806 } 17807 17808 public void setOptionEnabled(int option) { 17809 mOptions |= option; 17810 } 17811 17812 public boolean onTitlePrinted() { 17813 final boolean printed = mTitlePrinted; 17814 mTitlePrinted = true; 17815 return printed; 17816 } 17817 17818 public boolean getTitlePrinted() { 17819 return mTitlePrinted; 17820 } 17821 17822 public void setTitlePrinted(boolean enabled) { 17823 mTitlePrinted = enabled; 17824 } 17825 17826 public SharedUserSetting getSharedUser() { 17827 return mSharedUser; 17828 } 17829 17830 public void setSharedUser(SharedUserSetting user) { 17831 mSharedUser = user; 17832 } 17833 } 17834 17835 @Override 17836 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17837 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17838 (new PackageManagerShellCommand(this)).exec( 17839 this, in, out, err, args, resultReceiver); 17840 } 17841 17842 @Override 17843 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17844 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17845 != PackageManager.PERMISSION_GRANTED) { 17846 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17847 + Binder.getCallingPid() 17848 + ", uid=" + Binder.getCallingUid() 17849 + " without permission " 17850 + android.Manifest.permission.DUMP); 17851 return; 17852 } 17853 17854 DumpState dumpState = new DumpState(); 17855 boolean fullPreferred = false; 17856 boolean checkin = false; 17857 17858 String packageName = null; 17859 ArraySet<String> permissionNames = null; 17860 17861 int opti = 0; 17862 while (opti < args.length) { 17863 String opt = args[opti]; 17864 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17865 break; 17866 } 17867 opti++; 17868 17869 if ("-a".equals(opt)) { 17870 // Right now we only know how to print all. 17871 } else if ("-h".equals(opt)) { 17872 pw.println("Package manager dump options:"); 17873 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17874 pw.println(" --checkin: dump for a checkin"); 17875 pw.println(" -f: print details of intent filters"); 17876 pw.println(" -h: print this help"); 17877 pw.println(" cmd may be one of:"); 17878 pw.println(" l[ibraries]: list known shared libraries"); 17879 pw.println(" f[eatures]: list device features"); 17880 pw.println(" k[eysets]: print known keysets"); 17881 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17882 pw.println(" perm[issions]: dump permissions"); 17883 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17884 pw.println(" pref[erred]: print preferred package settings"); 17885 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17886 pw.println(" prov[iders]: dump content providers"); 17887 pw.println(" p[ackages]: dump installed packages"); 17888 pw.println(" s[hared-users]: dump shared user IDs"); 17889 pw.println(" m[essages]: print collected runtime messages"); 17890 pw.println(" v[erifiers]: print package verifier info"); 17891 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17892 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17893 pw.println(" version: print database version info"); 17894 pw.println(" write: write current settings now"); 17895 pw.println(" installs: details about install sessions"); 17896 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17897 pw.println(" <package.name>: info about given package"); 17898 return; 17899 } else if ("--checkin".equals(opt)) { 17900 checkin = true; 17901 } else if ("-f".equals(opt)) { 17902 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17903 } else { 17904 pw.println("Unknown argument: " + opt + "; use -h for help"); 17905 } 17906 } 17907 17908 // Is the caller requesting to dump a particular piece of data? 17909 if (opti < args.length) { 17910 String cmd = args[opti]; 17911 opti++; 17912 // Is this a package name? 17913 if ("android".equals(cmd) || cmd.contains(".")) { 17914 packageName = cmd; 17915 // When dumping a single package, we always dump all of its 17916 // filter information since the amount of data will be reasonable. 17917 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17918 } else if ("check-permission".equals(cmd)) { 17919 if (opti >= args.length) { 17920 pw.println("Error: check-permission missing permission argument"); 17921 return; 17922 } 17923 String perm = args[opti]; 17924 opti++; 17925 if (opti >= args.length) { 17926 pw.println("Error: check-permission missing package argument"); 17927 return; 17928 } 17929 String pkg = args[opti]; 17930 opti++; 17931 int user = UserHandle.getUserId(Binder.getCallingUid()); 17932 if (opti < args.length) { 17933 try { 17934 user = Integer.parseInt(args[opti]); 17935 } catch (NumberFormatException e) { 17936 pw.println("Error: check-permission user argument is not a number: " 17937 + args[opti]); 17938 return; 17939 } 17940 } 17941 pw.println(checkPermission(perm, pkg, user)); 17942 return; 17943 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17944 dumpState.setDump(DumpState.DUMP_LIBS); 17945 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17946 dumpState.setDump(DumpState.DUMP_FEATURES); 17947 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17948 if (opti >= args.length) { 17949 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17950 | DumpState.DUMP_SERVICE_RESOLVERS 17951 | DumpState.DUMP_RECEIVER_RESOLVERS 17952 | DumpState.DUMP_CONTENT_RESOLVERS); 17953 } else { 17954 while (opti < args.length) { 17955 String name = args[opti]; 17956 if ("a".equals(name) || "activity".equals(name)) { 17957 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17958 } else if ("s".equals(name) || "service".equals(name)) { 17959 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17960 } else if ("r".equals(name) || "receiver".equals(name)) { 17961 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17962 } else if ("c".equals(name) || "content".equals(name)) { 17963 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17964 } else { 17965 pw.println("Error: unknown resolver table type: " + name); 17966 return; 17967 } 17968 opti++; 17969 } 17970 } 17971 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17972 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17973 } else if ("permission".equals(cmd)) { 17974 if (opti >= args.length) { 17975 pw.println("Error: permission requires permission name"); 17976 return; 17977 } 17978 permissionNames = new ArraySet<>(); 17979 while (opti < args.length) { 17980 permissionNames.add(args[opti]); 17981 opti++; 17982 } 17983 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17984 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17985 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17986 dumpState.setDump(DumpState.DUMP_PREFERRED); 17987 } else if ("preferred-xml".equals(cmd)) { 17988 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17989 if (opti < args.length && "--full".equals(args[opti])) { 17990 fullPreferred = true; 17991 opti++; 17992 } 17993 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17994 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17995 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17996 dumpState.setDump(DumpState.DUMP_PACKAGES); 17997 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17998 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17999 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18000 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18001 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18002 dumpState.setDump(DumpState.DUMP_MESSAGES); 18003 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18004 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18005 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18006 || "intent-filter-verifiers".equals(cmd)) { 18007 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18008 } else if ("version".equals(cmd)) { 18009 dumpState.setDump(DumpState.DUMP_VERSION); 18010 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18011 dumpState.setDump(DumpState.DUMP_KEYSETS); 18012 } else if ("installs".equals(cmd)) { 18013 dumpState.setDump(DumpState.DUMP_INSTALLS); 18014 } else if ("frozen".equals(cmd)) { 18015 dumpState.setDump(DumpState.DUMP_FROZEN); 18016 } else if ("write".equals(cmd)) { 18017 synchronized (mPackages) { 18018 mSettings.writeLPr(); 18019 pw.println("Settings written."); 18020 return; 18021 } 18022 } 18023 } 18024 18025 if (checkin) { 18026 pw.println("vers,1"); 18027 } 18028 18029 // reader 18030 synchronized (mPackages) { 18031 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18032 if (!checkin) { 18033 if (dumpState.onTitlePrinted()) 18034 pw.println(); 18035 pw.println("Database versions:"); 18036 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18037 } 18038 } 18039 18040 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18041 if (!checkin) { 18042 if (dumpState.onTitlePrinted()) 18043 pw.println(); 18044 pw.println("Verifiers:"); 18045 pw.print(" Required: "); 18046 pw.print(mRequiredVerifierPackage); 18047 pw.print(" (uid="); 18048 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18049 UserHandle.USER_SYSTEM)); 18050 pw.println(")"); 18051 } else if (mRequiredVerifierPackage != null) { 18052 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18053 pw.print(","); 18054 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18055 UserHandle.USER_SYSTEM)); 18056 } 18057 } 18058 18059 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18060 packageName == null) { 18061 if (mIntentFilterVerifierComponent != null) { 18062 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18063 if (!checkin) { 18064 if (dumpState.onTitlePrinted()) 18065 pw.println(); 18066 pw.println("Intent Filter Verifier:"); 18067 pw.print(" Using: "); 18068 pw.print(verifierPackageName); 18069 pw.print(" (uid="); 18070 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18071 UserHandle.USER_SYSTEM)); 18072 pw.println(")"); 18073 } else if (verifierPackageName != null) { 18074 pw.print("ifv,"); pw.print(verifierPackageName); 18075 pw.print(","); 18076 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18077 UserHandle.USER_SYSTEM)); 18078 } 18079 } else { 18080 pw.println(); 18081 pw.println("No Intent Filter Verifier available!"); 18082 } 18083 } 18084 18085 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18086 boolean printedHeader = false; 18087 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18088 while (it.hasNext()) { 18089 String name = it.next(); 18090 SharedLibraryEntry ent = mSharedLibraries.get(name); 18091 if (!checkin) { 18092 if (!printedHeader) { 18093 if (dumpState.onTitlePrinted()) 18094 pw.println(); 18095 pw.println("Libraries:"); 18096 printedHeader = true; 18097 } 18098 pw.print(" "); 18099 } else { 18100 pw.print("lib,"); 18101 } 18102 pw.print(name); 18103 if (!checkin) { 18104 pw.print(" -> "); 18105 } 18106 if (ent.path != null) { 18107 if (!checkin) { 18108 pw.print("(jar) "); 18109 pw.print(ent.path); 18110 } else { 18111 pw.print(",jar,"); 18112 pw.print(ent.path); 18113 } 18114 } else { 18115 if (!checkin) { 18116 pw.print("(apk) "); 18117 pw.print(ent.apk); 18118 } else { 18119 pw.print(",apk,"); 18120 pw.print(ent.apk); 18121 } 18122 } 18123 pw.println(); 18124 } 18125 } 18126 18127 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18128 if (dumpState.onTitlePrinted()) 18129 pw.println(); 18130 if (!checkin) { 18131 pw.println("Features:"); 18132 } 18133 18134 for (FeatureInfo feat : mAvailableFeatures.values()) { 18135 if (checkin) { 18136 pw.print("feat,"); 18137 pw.print(feat.name); 18138 pw.print(","); 18139 pw.println(feat.version); 18140 } else { 18141 pw.print(" "); 18142 pw.print(feat.name); 18143 if (feat.version > 0) { 18144 pw.print(" version="); 18145 pw.print(feat.version); 18146 } 18147 pw.println(); 18148 } 18149 } 18150 } 18151 18152 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18153 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18154 : "Activity Resolver Table:", " ", packageName, 18155 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18156 dumpState.setTitlePrinted(true); 18157 } 18158 } 18159 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18160 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18161 : "Receiver Resolver Table:", " ", packageName, 18162 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18163 dumpState.setTitlePrinted(true); 18164 } 18165 } 18166 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18167 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18168 : "Service Resolver Table:", " ", packageName, 18169 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18170 dumpState.setTitlePrinted(true); 18171 } 18172 } 18173 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18174 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18175 : "Provider Resolver Table:", " ", packageName, 18176 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18177 dumpState.setTitlePrinted(true); 18178 } 18179 } 18180 18181 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18182 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18183 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18184 int user = mSettings.mPreferredActivities.keyAt(i); 18185 if (pir.dump(pw, 18186 dumpState.getTitlePrinted() 18187 ? "\nPreferred Activities User " + user + ":" 18188 : "Preferred Activities User " + user + ":", " ", 18189 packageName, true, false)) { 18190 dumpState.setTitlePrinted(true); 18191 } 18192 } 18193 } 18194 18195 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18196 pw.flush(); 18197 FileOutputStream fout = new FileOutputStream(fd); 18198 BufferedOutputStream str = new BufferedOutputStream(fout); 18199 XmlSerializer serializer = new FastXmlSerializer(); 18200 try { 18201 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18202 serializer.startDocument(null, true); 18203 serializer.setFeature( 18204 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18205 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18206 serializer.endDocument(); 18207 serializer.flush(); 18208 } catch (IllegalArgumentException e) { 18209 pw.println("Failed writing: " + e); 18210 } catch (IllegalStateException e) { 18211 pw.println("Failed writing: " + e); 18212 } catch (IOException e) { 18213 pw.println("Failed writing: " + e); 18214 } 18215 } 18216 18217 if (!checkin 18218 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18219 && packageName == null) { 18220 pw.println(); 18221 int count = mSettings.mPackages.size(); 18222 if (count == 0) { 18223 pw.println("No applications!"); 18224 pw.println(); 18225 } else { 18226 final String prefix = " "; 18227 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18228 if (allPackageSettings.size() == 0) { 18229 pw.println("No domain preferred apps!"); 18230 pw.println(); 18231 } else { 18232 pw.println("App verification status:"); 18233 pw.println(); 18234 count = 0; 18235 for (PackageSetting ps : allPackageSettings) { 18236 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18237 if (ivi == null || ivi.getPackageName() == null) continue; 18238 pw.println(prefix + "Package: " + ivi.getPackageName()); 18239 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18240 pw.println(prefix + "Status: " + ivi.getStatusString()); 18241 pw.println(); 18242 count++; 18243 } 18244 if (count == 0) { 18245 pw.println(prefix + "No app verification established."); 18246 pw.println(); 18247 } 18248 for (int userId : sUserManager.getUserIds()) { 18249 pw.println("App linkages for user " + userId + ":"); 18250 pw.println(); 18251 count = 0; 18252 for (PackageSetting ps : allPackageSettings) { 18253 final long status = ps.getDomainVerificationStatusForUser(userId); 18254 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18255 continue; 18256 } 18257 pw.println(prefix + "Package: " + ps.name); 18258 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18259 String statusStr = IntentFilterVerificationInfo. 18260 getStatusStringFromValue(status); 18261 pw.println(prefix + "Status: " + statusStr); 18262 pw.println(); 18263 count++; 18264 } 18265 if (count == 0) { 18266 pw.println(prefix + "No configured app linkages."); 18267 pw.println(); 18268 } 18269 } 18270 } 18271 } 18272 } 18273 18274 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18275 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18276 if (packageName == null && permissionNames == null) { 18277 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18278 if (iperm == 0) { 18279 if (dumpState.onTitlePrinted()) 18280 pw.println(); 18281 pw.println("AppOp Permissions:"); 18282 } 18283 pw.print(" AppOp Permission "); 18284 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18285 pw.println(":"); 18286 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18287 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18288 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18289 } 18290 } 18291 } 18292 } 18293 18294 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18295 boolean printedSomething = false; 18296 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18297 if (packageName != null && !packageName.equals(p.info.packageName)) { 18298 continue; 18299 } 18300 if (!printedSomething) { 18301 if (dumpState.onTitlePrinted()) 18302 pw.println(); 18303 pw.println("Registered ContentProviders:"); 18304 printedSomething = true; 18305 } 18306 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18307 pw.print(" "); pw.println(p.toString()); 18308 } 18309 printedSomething = false; 18310 for (Map.Entry<String, PackageParser.Provider> entry : 18311 mProvidersByAuthority.entrySet()) { 18312 PackageParser.Provider p = entry.getValue(); 18313 if (packageName != null && !packageName.equals(p.info.packageName)) { 18314 continue; 18315 } 18316 if (!printedSomething) { 18317 if (dumpState.onTitlePrinted()) 18318 pw.println(); 18319 pw.println("ContentProvider Authorities:"); 18320 printedSomething = true; 18321 } 18322 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18323 pw.print(" "); pw.println(p.toString()); 18324 if (p.info != null && p.info.applicationInfo != null) { 18325 final String appInfo = p.info.applicationInfo.toString(); 18326 pw.print(" applicationInfo="); pw.println(appInfo); 18327 } 18328 } 18329 } 18330 18331 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18332 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18333 } 18334 18335 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18336 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18337 } 18338 18339 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18340 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18341 } 18342 18343 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18344 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18345 } 18346 18347 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18348 // XXX should handle packageName != null by dumping only install data that 18349 // the given package is involved with. 18350 if (dumpState.onTitlePrinted()) pw.println(); 18351 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18352 } 18353 18354 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18355 // XXX should handle packageName != null by dumping only install data that 18356 // the given package is involved with. 18357 if (dumpState.onTitlePrinted()) pw.println(); 18358 18359 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18360 ipw.println(); 18361 ipw.println("Frozen packages:"); 18362 ipw.increaseIndent(); 18363 if (mFrozenPackages.size() == 0) { 18364 ipw.println("(none)"); 18365 } else { 18366 for (int i = 0; i < mFrozenPackages.size(); i++) { 18367 ipw.println(mFrozenPackages.valueAt(i)); 18368 } 18369 } 18370 ipw.decreaseIndent(); 18371 } 18372 18373 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18374 if (dumpState.onTitlePrinted()) pw.println(); 18375 mSettings.dumpReadMessagesLPr(pw, dumpState); 18376 18377 pw.println(); 18378 pw.println("Package warning messages:"); 18379 BufferedReader in = null; 18380 String line = null; 18381 try { 18382 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18383 while ((line = in.readLine()) != null) { 18384 if (line.contains("ignored: updated version")) continue; 18385 pw.println(line); 18386 } 18387 } catch (IOException ignored) { 18388 } finally { 18389 IoUtils.closeQuietly(in); 18390 } 18391 } 18392 18393 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18394 BufferedReader in = null; 18395 String line = null; 18396 try { 18397 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18398 while ((line = in.readLine()) != null) { 18399 if (line.contains("ignored: updated version")) continue; 18400 pw.print("msg,"); 18401 pw.println(line); 18402 } 18403 } catch (IOException ignored) { 18404 } finally { 18405 IoUtils.closeQuietly(in); 18406 } 18407 } 18408 } 18409 } 18410 18411 private String dumpDomainString(String packageName) { 18412 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18413 .getList(); 18414 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18415 18416 ArraySet<String> result = new ArraySet<>(); 18417 if (iviList.size() > 0) { 18418 for (IntentFilterVerificationInfo ivi : iviList) { 18419 for (String host : ivi.getDomains()) { 18420 result.add(host); 18421 } 18422 } 18423 } 18424 if (filters != null && filters.size() > 0) { 18425 for (IntentFilter filter : filters) { 18426 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18427 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18428 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18429 result.addAll(filter.getHostsList()); 18430 } 18431 } 18432 } 18433 18434 StringBuilder sb = new StringBuilder(result.size() * 16); 18435 for (String domain : result) { 18436 if (sb.length() > 0) sb.append(" "); 18437 sb.append(domain); 18438 } 18439 return sb.toString(); 18440 } 18441 18442 // ------- apps on sdcard specific code ------- 18443 static final boolean DEBUG_SD_INSTALL = false; 18444 18445 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18446 18447 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18448 18449 private boolean mMediaMounted = false; 18450 18451 static String getEncryptKey() { 18452 try { 18453 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18454 SD_ENCRYPTION_KEYSTORE_NAME); 18455 if (sdEncKey == null) { 18456 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18457 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18458 if (sdEncKey == null) { 18459 Slog.e(TAG, "Failed to create encryption keys"); 18460 return null; 18461 } 18462 } 18463 return sdEncKey; 18464 } catch (NoSuchAlgorithmException nsae) { 18465 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18466 return null; 18467 } catch (IOException ioe) { 18468 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18469 return null; 18470 } 18471 } 18472 18473 /* 18474 * Update media status on PackageManager. 18475 */ 18476 @Override 18477 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18478 int callingUid = Binder.getCallingUid(); 18479 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18480 throw new SecurityException("Media status can only be updated by the system"); 18481 } 18482 // reader; this apparently protects mMediaMounted, but should probably 18483 // be a different lock in that case. 18484 synchronized (mPackages) { 18485 Log.i(TAG, "Updating external media status from " 18486 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18487 + (mediaStatus ? "mounted" : "unmounted")); 18488 if (DEBUG_SD_INSTALL) 18489 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18490 + ", mMediaMounted=" + mMediaMounted); 18491 if (mediaStatus == mMediaMounted) { 18492 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18493 : 0, -1); 18494 mHandler.sendMessage(msg); 18495 return; 18496 } 18497 mMediaMounted = mediaStatus; 18498 } 18499 // Queue up an async operation since the package installation may take a 18500 // little while. 18501 mHandler.post(new Runnable() { 18502 public void run() { 18503 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18504 } 18505 }); 18506 } 18507 18508 /** 18509 * Called by MountService when the initial ASECs to scan are available. 18510 * Should block until all the ASEC containers are finished being scanned. 18511 */ 18512 public void scanAvailableAsecs() { 18513 updateExternalMediaStatusInner(true, false, false); 18514 } 18515 18516 /* 18517 * Collect information of applications on external media, map them against 18518 * existing containers and update information based on current mount status. 18519 * Please note that we always have to report status if reportStatus has been 18520 * set to true especially when unloading packages. 18521 */ 18522 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18523 boolean externalStorage) { 18524 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18525 int[] uidArr = EmptyArray.INT; 18526 18527 final String[] list = PackageHelper.getSecureContainerList(); 18528 if (ArrayUtils.isEmpty(list)) { 18529 Log.i(TAG, "No secure containers found"); 18530 } else { 18531 // Process list of secure containers and categorize them 18532 // as active or stale based on their package internal state. 18533 18534 // reader 18535 synchronized (mPackages) { 18536 for (String cid : list) { 18537 // Leave stages untouched for now; installer service owns them 18538 if (PackageInstallerService.isStageName(cid)) continue; 18539 18540 if (DEBUG_SD_INSTALL) 18541 Log.i(TAG, "Processing container " + cid); 18542 String pkgName = getAsecPackageName(cid); 18543 if (pkgName == null) { 18544 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18545 continue; 18546 } 18547 if (DEBUG_SD_INSTALL) 18548 Log.i(TAG, "Looking for pkg : " + pkgName); 18549 18550 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18551 if (ps == null) { 18552 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18553 continue; 18554 } 18555 18556 /* 18557 * Skip packages that are not external if we're unmounting 18558 * external storage. 18559 */ 18560 if (externalStorage && !isMounted && !isExternal(ps)) { 18561 continue; 18562 } 18563 18564 final AsecInstallArgs args = new AsecInstallArgs(cid, 18565 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18566 // The package status is changed only if the code path 18567 // matches between settings and the container id. 18568 if (ps.codePathString != null 18569 && ps.codePathString.startsWith(args.getCodePath())) { 18570 if (DEBUG_SD_INSTALL) { 18571 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18572 + " at code path: " + ps.codePathString); 18573 } 18574 18575 // We do have a valid package installed on sdcard 18576 processCids.put(args, ps.codePathString); 18577 final int uid = ps.appId; 18578 if (uid != -1) { 18579 uidArr = ArrayUtils.appendInt(uidArr, uid); 18580 } 18581 } else { 18582 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18583 + ps.codePathString); 18584 } 18585 } 18586 } 18587 18588 Arrays.sort(uidArr); 18589 } 18590 18591 // Process packages with valid entries. 18592 if (isMounted) { 18593 if (DEBUG_SD_INSTALL) 18594 Log.i(TAG, "Loading packages"); 18595 loadMediaPackages(processCids, uidArr, externalStorage); 18596 startCleaningPackages(); 18597 mInstallerService.onSecureContainersAvailable(); 18598 } else { 18599 if (DEBUG_SD_INSTALL) 18600 Log.i(TAG, "Unloading packages"); 18601 unloadMediaPackages(processCids, uidArr, reportStatus); 18602 } 18603 } 18604 18605 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18606 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18607 final int size = infos.size(); 18608 final String[] packageNames = new String[size]; 18609 final int[] packageUids = new int[size]; 18610 for (int i = 0; i < size; i++) { 18611 final ApplicationInfo info = infos.get(i); 18612 packageNames[i] = info.packageName; 18613 packageUids[i] = info.uid; 18614 } 18615 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18616 finishedReceiver); 18617 } 18618 18619 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18620 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18621 sendResourcesChangedBroadcast(mediaStatus, replacing, 18622 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18623 } 18624 18625 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18626 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18627 int size = pkgList.length; 18628 if (size > 0) { 18629 // Send broadcasts here 18630 Bundle extras = new Bundle(); 18631 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18632 if (uidArr != null) { 18633 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18634 } 18635 if (replacing) { 18636 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18637 } 18638 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18639 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18640 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18641 } 18642 } 18643 18644 /* 18645 * Look at potentially valid container ids from processCids If package 18646 * information doesn't match the one on record or package scanning fails, 18647 * the cid is added to list of removeCids. We currently don't delete stale 18648 * containers. 18649 */ 18650 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18651 boolean externalStorage) { 18652 ArrayList<String> pkgList = new ArrayList<String>(); 18653 Set<AsecInstallArgs> keys = processCids.keySet(); 18654 18655 for (AsecInstallArgs args : keys) { 18656 String codePath = processCids.get(args); 18657 if (DEBUG_SD_INSTALL) 18658 Log.i(TAG, "Loading container : " + args.cid); 18659 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18660 try { 18661 // Make sure there are no container errors first. 18662 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18663 Slog.e(TAG, "Failed to mount cid : " + args.cid 18664 + " when installing from sdcard"); 18665 continue; 18666 } 18667 // Check code path here. 18668 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18669 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18670 + " does not match one in settings " + codePath); 18671 continue; 18672 } 18673 // Parse package 18674 int parseFlags = mDefParseFlags; 18675 if (args.isExternalAsec()) { 18676 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18677 } 18678 if (args.isFwdLocked()) { 18679 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18680 } 18681 18682 synchronized (mInstallLock) { 18683 PackageParser.Package pkg = null; 18684 try { 18685 // Sadly we don't know the package name yet to freeze it 18686 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18687 SCAN_IGNORE_FROZEN, 0, null); 18688 } catch (PackageManagerException e) { 18689 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18690 } 18691 // Scan the package 18692 if (pkg != null) { 18693 /* 18694 * TODO why is the lock being held? doPostInstall is 18695 * called in other places without the lock. This needs 18696 * to be straightened out. 18697 */ 18698 // writer 18699 synchronized (mPackages) { 18700 retCode = PackageManager.INSTALL_SUCCEEDED; 18701 pkgList.add(pkg.packageName); 18702 // Post process args 18703 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18704 pkg.applicationInfo.uid); 18705 } 18706 } else { 18707 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18708 } 18709 } 18710 18711 } finally { 18712 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18713 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18714 } 18715 } 18716 } 18717 // writer 18718 synchronized (mPackages) { 18719 // If the platform SDK has changed since the last time we booted, 18720 // we need to re-grant app permission to catch any new ones that 18721 // appear. This is really a hack, and means that apps can in some 18722 // cases get permissions that the user didn't initially explicitly 18723 // allow... it would be nice to have some better way to handle 18724 // this situation. 18725 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18726 : mSettings.getInternalVersion(); 18727 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18728 : StorageManager.UUID_PRIVATE_INTERNAL; 18729 18730 int updateFlags = UPDATE_PERMISSIONS_ALL; 18731 if (ver.sdkVersion != mSdkVersion) { 18732 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18733 + mSdkVersion + "; regranting permissions for external"); 18734 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18735 } 18736 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18737 18738 // Yay, everything is now upgraded 18739 ver.forceCurrent(); 18740 18741 // can downgrade to reader 18742 // Persist settings 18743 mSettings.writeLPr(); 18744 } 18745 // Send a broadcast to let everyone know we are done processing 18746 if (pkgList.size() > 0) { 18747 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18748 } 18749 } 18750 18751 /* 18752 * Utility method to unload a list of specified containers 18753 */ 18754 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18755 // Just unmount all valid containers. 18756 for (AsecInstallArgs arg : cidArgs) { 18757 synchronized (mInstallLock) { 18758 arg.doPostDeleteLI(false); 18759 } 18760 } 18761 } 18762 18763 /* 18764 * Unload packages mounted on external media. This involves deleting package 18765 * data from internal structures, sending broadcasts about disabled packages, 18766 * gc'ing to free up references, unmounting all secure containers 18767 * corresponding to packages on external media, and posting a 18768 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18769 * that we always have to post this message if status has been requested no 18770 * matter what. 18771 */ 18772 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18773 final boolean reportStatus) { 18774 if (DEBUG_SD_INSTALL) 18775 Log.i(TAG, "unloading media packages"); 18776 ArrayList<String> pkgList = new ArrayList<String>(); 18777 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18778 final Set<AsecInstallArgs> keys = processCids.keySet(); 18779 for (AsecInstallArgs args : keys) { 18780 String pkgName = args.getPackageName(); 18781 if (DEBUG_SD_INSTALL) 18782 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18783 // Delete package internally 18784 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18785 synchronized (mInstallLock) { 18786 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18787 final boolean res; 18788 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18789 "unloadMediaPackages")) { 18790 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18791 null); 18792 } 18793 if (res) { 18794 pkgList.add(pkgName); 18795 } else { 18796 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18797 failedList.add(args); 18798 } 18799 } 18800 } 18801 18802 // reader 18803 synchronized (mPackages) { 18804 // We didn't update the settings after removing each package; 18805 // write them now for all packages. 18806 mSettings.writeLPr(); 18807 } 18808 18809 // We have to absolutely send UPDATED_MEDIA_STATUS only 18810 // after confirming that all the receivers processed the ordered 18811 // broadcast when packages get disabled, force a gc to clean things up. 18812 // and unload all the containers. 18813 if (pkgList.size() > 0) { 18814 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18815 new IIntentReceiver.Stub() { 18816 public void performReceive(Intent intent, int resultCode, String data, 18817 Bundle extras, boolean ordered, boolean sticky, 18818 int sendingUser) throws RemoteException { 18819 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18820 reportStatus ? 1 : 0, 1, keys); 18821 mHandler.sendMessage(msg); 18822 } 18823 }); 18824 } else { 18825 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18826 keys); 18827 mHandler.sendMessage(msg); 18828 } 18829 } 18830 18831 private void loadPrivatePackages(final VolumeInfo vol) { 18832 mHandler.post(new Runnable() { 18833 @Override 18834 public void run() { 18835 loadPrivatePackagesInner(vol); 18836 } 18837 }); 18838 } 18839 18840 private void loadPrivatePackagesInner(VolumeInfo vol) { 18841 final String volumeUuid = vol.fsUuid; 18842 if (TextUtils.isEmpty(volumeUuid)) { 18843 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18844 return; 18845 } 18846 18847 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18848 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18849 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18850 18851 final VersionInfo ver; 18852 final List<PackageSetting> packages; 18853 synchronized (mPackages) { 18854 ver = mSettings.findOrCreateVersion(volumeUuid); 18855 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18856 } 18857 18858 for (PackageSetting ps : packages) { 18859 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18860 synchronized (mInstallLock) { 18861 final PackageParser.Package pkg; 18862 try { 18863 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18864 loaded.add(pkg.applicationInfo); 18865 18866 } catch (PackageManagerException e) { 18867 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18868 } 18869 18870 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18871 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18872 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18873 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18874 } 18875 } 18876 } 18877 18878 // Reconcile app data for all started/unlocked users 18879 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18880 final UserManager um = mContext.getSystemService(UserManager.class); 18881 for (UserInfo user : um.getUsers()) { 18882 final int flags; 18883 if (um.isUserUnlockingOrUnlocked(user.id)) { 18884 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18885 } else if (um.isUserRunning(user.id)) { 18886 flags = StorageManager.FLAG_STORAGE_DE; 18887 } else { 18888 continue; 18889 } 18890 18891 try { 18892 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18893 synchronized (mInstallLock) { 18894 reconcileAppsDataLI(volumeUuid, user.id, flags); 18895 } 18896 } catch (IllegalStateException e) { 18897 // Device was probably ejected, and we'll process that event momentarily 18898 Slog.w(TAG, "Failed to prepare storage: " + e); 18899 } 18900 } 18901 18902 synchronized (mPackages) { 18903 int updateFlags = UPDATE_PERMISSIONS_ALL; 18904 if (ver.sdkVersion != mSdkVersion) { 18905 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18906 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18907 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18908 } 18909 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18910 18911 // Yay, everything is now upgraded 18912 ver.forceCurrent(); 18913 18914 mSettings.writeLPr(); 18915 } 18916 18917 for (PackageFreezer freezer : freezers) { 18918 freezer.close(); 18919 } 18920 18921 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18922 sendResourcesChangedBroadcast(true, false, loaded, null); 18923 } 18924 18925 private void unloadPrivatePackages(final VolumeInfo vol) { 18926 mHandler.post(new Runnable() { 18927 @Override 18928 public void run() { 18929 unloadPrivatePackagesInner(vol); 18930 } 18931 }); 18932 } 18933 18934 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18935 final String volumeUuid = vol.fsUuid; 18936 if (TextUtils.isEmpty(volumeUuid)) { 18937 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18938 return; 18939 } 18940 18941 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18942 synchronized (mInstallLock) { 18943 synchronized (mPackages) { 18944 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18945 for (PackageSetting ps : packages) { 18946 if (ps.pkg == null) continue; 18947 18948 final ApplicationInfo info = ps.pkg.applicationInfo; 18949 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18950 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18951 18952 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18953 "unloadPrivatePackagesInner")) { 18954 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18955 false, null)) { 18956 unloaded.add(info); 18957 } else { 18958 Slog.w(TAG, "Failed to unload " + ps.codePath); 18959 } 18960 } 18961 } 18962 18963 mSettings.writeLPr(); 18964 } 18965 } 18966 18967 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18968 sendResourcesChangedBroadcast(false, false, unloaded, null); 18969 } 18970 18971 /** 18972 * Prepare storage areas for given user on all mounted devices. 18973 */ 18974 void prepareUserData(int userId, int userSerial, int flags) { 18975 synchronized (mInstallLock) { 18976 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18977 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18978 final String volumeUuid = vol.getFsUuid(); 18979 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18980 } 18981 } 18982 } 18983 18984 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18985 boolean allowRecover) { 18986 // Prepare storage and verify that serial numbers are consistent; if 18987 // there's a mismatch we need to destroy to avoid leaking data 18988 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18989 try { 18990 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18991 18992 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18993 UserManagerService.enforceSerialNumber( 18994 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18995 } 18996 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18997 UserManagerService.enforceSerialNumber( 18998 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18999 } 19000 19001 synchronized (mInstallLock) { 19002 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19003 } 19004 } catch (Exception e) { 19005 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19006 + " because we failed to prepare: " + e); 19007 destroyUserDataLI(volumeUuid, userId, 19008 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19009 19010 if (allowRecover) { 19011 // Try one last time; if we fail again we're really in trouble 19012 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19013 } 19014 } 19015 } 19016 19017 /** 19018 * Destroy storage areas for given user on all mounted devices. 19019 */ 19020 void destroyUserData(int userId, int flags) { 19021 synchronized (mInstallLock) { 19022 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19023 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19024 final String volumeUuid = vol.getFsUuid(); 19025 destroyUserDataLI(volumeUuid, userId, flags); 19026 } 19027 } 19028 } 19029 19030 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19031 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19032 try { 19033 // Clean up app data, profile data, and media data 19034 mInstaller.destroyUserData(volumeUuid, userId, flags); 19035 19036 // Clean up system data 19037 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19038 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19039 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19040 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19041 } 19042 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19043 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19044 } 19045 } 19046 19047 // Data with special labels is now gone, so finish the job 19048 storage.destroyUserStorage(volumeUuid, userId, flags); 19049 19050 } catch (Exception e) { 19051 logCriticalInfo(Log.WARN, 19052 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19053 } 19054 } 19055 19056 /** 19057 * Examine all users present on given mounted volume, and destroy data 19058 * belonging to users that are no longer valid, or whose user ID has been 19059 * recycled. 19060 */ 19061 private void reconcileUsers(String volumeUuid) { 19062 final List<File> files = new ArrayList<>(); 19063 Collections.addAll(files, FileUtils 19064 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19065 Collections.addAll(files, FileUtils 19066 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19067 for (File file : files) { 19068 if (!file.isDirectory()) continue; 19069 19070 final int userId; 19071 final UserInfo info; 19072 try { 19073 userId = Integer.parseInt(file.getName()); 19074 info = sUserManager.getUserInfo(userId); 19075 } catch (NumberFormatException e) { 19076 Slog.w(TAG, "Invalid user directory " + file); 19077 continue; 19078 } 19079 19080 boolean destroyUser = false; 19081 if (info == null) { 19082 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19083 + " because no matching user was found"); 19084 destroyUser = true; 19085 } else if (!mOnlyCore) { 19086 try { 19087 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19088 } catch (IOException e) { 19089 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19090 + " because we failed to enforce serial number: " + e); 19091 destroyUser = true; 19092 } 19093 } 19094 19095 if (destroyUser) { 19096 synchronized (mInstallLock) { 19097 destroyUserDataLI(volumeUuid, userId, 19098 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19099 } 19100 } 19101 } 19102 } 19103 19104 private void assertPackageKnown(String volumeUuid, String packageName) 19105 throws PackageManagerException { 19106 synchronized (mPackages) { 19107 final PackageSetting ps = mSettings.mPackages.get(packageName); 19108 if (ps == null) { 19109 throw new PackageManagerException("Package " + packageName + " is unknown"); 19110 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19111 throw new PackageManagerException( 19112 "Package " + packageName + " found on unknown volume " + volumeUuid 19113 + "; expected volume " + ps.volumeUuid); 19114 } 19115 } 19116 } 19117 19118 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19119 throws PackageManagerException { 19120 synchronized (mPackages) { 19121 final PackageSetting ps = mSettings.mPackages.get(packageName); 19122 if (ps == null) { 19123 throw new PackageManagerException("Package " + packageName + " is unknown"); 19124 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19125 throw new PackageManagerException( 19126 "Package " + packageName + " found on unknown volume " + volumeUuid 19127 + "; expected volume " + ps.volumeUuid); 19128 } else if (!ps.getInstalled(userId)) { 19129 throw new PackageManagerException( 19130 "Package " + packageName + " not installed for user " + userId); 19131 } 19132 } 19133 } 19134 19135 /** 19136 * Examine all apps present on given mounted volume, and destroy apps that 19137 * aren't expected, either due to uninstallation or reinstallation on 19138 * another volume. 19139 */ 19140 private void reconcileApps(String volumeUuid) { 19141 final File[] files = FileUtils 19142 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19143 for (File file : files) { 19144 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19145 && !PackageInstallerService.isStageName(file.getName()); 19146 if (!isPackage) { 19147 // Ignore entries which are not packages 19148 continue; 19149 } 19150 19151 try { 19152 final PackageLite pkg = PackageParser.parsePackageLite(file, 19153 PackageParser.PARSE_MUST_BE_APK); 19154 assertPackageKnown(volumeUuid, pkg.packageName); 19155 19156 } catch (PackageParserException | PackageManagerException e) { 19157 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19158 synchronized (mInstallLock) { 19159 removeCodePathLI(file); 19160 } 19161 } 19162 } 19163 } 19164 19165 /** 19166 * Reconcile all app data for the given user. 19167 * <p> 19168 * Verifies that directories exist and that ownership and labeling is 19169 * correct for all installed apps on all mounted volumes. 19170 */ 19171 void reconcileAppsData(int userId, int flags) { 19172 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19173 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19174 final String volumeUuid = vol.getFsUuid(); 19175 synchronized (mInstallLock) { 19176 reconcileAppsDataLI(volumeUuid, userId, flags); 19177 } 19178 } 19179 } 19180 19181 /** 19182 * Reconcile all app data on given mounted volume. 19183 * <p> 19184 * Destroys app data that isn't expected, either due to uninstallation or 19185 * reinstallation on another volume. 19186 * <p> 19187 * Verifies that directories exist and that ownership and labeling is 19188 * correct for all installed apps. 19189 */ 19190 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19191 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19192 + Integer.toHexString(flags)); 19193 19194 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19195 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19196 19197 boolean restoreconNeeded = false; 19198 19199 // First look for stale data that doesn't belong, and check if things 19200 // have changed since we did our last restorecon 19201 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19202 if (StorageManager.isFileEncryptedNativeOrEmulated() 19203 && !StorageManager.isUserKeyUnlocked(userId)) { 19204 throw new RuntimeException( 19205 "Yikes, someone asked us to reconcile CE storage while " + userId 19206 + " was still locked; this would have caused massive data loss!"); 19207 } 19208 19209 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19210 19211 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19212 for (File file : files) { 19213 final String packageName = file.getName(); 19214 try { 19215 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19216 } catch (PackageManagerException e) { 19217 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19218 try { 19219 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19220 StorageManager.FLAG_STORAGE_CE, 0); 19221 } catch (InstallerException e2) { 19222 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19223 } 19224 } 19225 } 19226 } 19227 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19228 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19229 19230 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19231 for (File file : files) { 19232 final String packageName = file.getName(); 19233 try { 19234 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19235 } catch (PackageManagerException e) { 19236 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19237 try { 19238 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19239 StorageManager.FLAG_STORAGE_DE, 0); 19240 } catch (InstallerException e2) { 19241 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19242 } 19243 } 19244 } 19245 } 19246 19247 // Ensure that data directories are ready to roll for all packages 19248 // installed for this volume and user 19249 final List<PackageSetting> packages; 19250 synchronized (mPackages) { 19251 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19252 } 19253 int preparedCount = 0; 19254 for (PackageSetting ps : packages) { 19255 final String packageName = ps.name; 19256 if (ps.pkg == null) { 19257 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19258 // TODO: might be due to legacy ASEC apps; we should circle back 19259 // and reconcile again once they're scanned 19260 continue; 19261 } 19262 19263 if (ps.getInstalled(userId)) { 19264 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19265 19266 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19267 // We may have just shuffled around app data directories, so 19268 // prepare them one more time 19269 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19270 } 19271 19272 preparedCount++; 19273 } 19274 } 19275 19276 if (restoreconNeeded) { 19277 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19278 SELinuxMMAC.setRestoreconDone(ceDir); 19279 } 19280 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19281 SELinuxMMAC.setRestoreconDone(deDir); 19282 } 19283 } 19284 19285 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19286 + " packages; restoreconNeeded was " + restoreconNeeded); 19287 } 19288 19289 /** 19290 * Prepare app data for the given app just after it was installed or 19291 * upgraded. This method carefully only touches users that it's installed 19292 * for, and it forces a restorecon to handle any seinfo changes. 19293 * <p> 19294 * Verifies that directories exist and that ownership and labeling is 19295 * correct for all installed apps. If there is an ownership mismatch, it 19296 * will try recovering system apps by wiping data; third-party app data is 19297 * left intact. 19298 * <p> 19299 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19300 */ 19301 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19302 final PackageSetting ps; 19303 synchronized (mPackages) { 19304 ps = mSettings.mPackages.get(pkg.packageName); 19305 mSettings.writeKernelMappingLPr(ps); 19306 } 19307 19308 final UserManager um = mContext.getSystemService(UserManager.class); 19309 for (UserInfo user : um.getUsers()) { 19310 final int flags; 19311 if (um.isUserUnlockingOrUnlocked(user.id)) { 19312 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19313 } else if (um.isUserRunning(user.id)) { 19314 flags = StorageManager.FLAG_STORAGE_DE; 19315 } else { 19316 continue; 19317 } 19318 19319 if (ps.getInstalled(user.id)) { 19320 // Whenever an app changes, force a restorecon of its data 19321 // TODO: when user data is locked, mark that we're still dirty 19322 prepareAppDataLIF(pkg, user.id, flags, true); 19323 } 19324 } 19325 } 19326 19327 /** 19328 * Prepare app data for the given app. 19329 * <p> 19330 * Verifies that directories exist and that ownership and labeling is 19331 * correct for all installed apps. If there is an ownership mismatch, this 19332 * will try recovering system apps by wiping data; third-party app data is 19333 * left intact. 19334 */ 19335 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19336 boolean restoreconNeeded) { 19337 if (pkg == null) { 19338 Slog.wtf(TAG, "Package was null!", new Throwable()); 19339 return; 19340 } 19341 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19342 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19343 for (int i = 0; i < childCount; i++) { 19344 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19345 } 19346 } 19347 19348 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19349 boolean restoreconNeeded) { 19350 if (DEBUG_APP_DATA) { 19351 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19352 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19353 } 19354 19355 final String volumeUuid = pkg.volumeUuid; 19356 final String packageName = pkg.packageName; 19357 final ApplicationInfo app = pkg.applicationInfo; 19358 final int appId = UserHandle.getAppId(app.uid); 19359 19360 Preconditions.checkNotNull(app.seinfo); 19361 19362 try { 19363 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19364 appId, app.seinfo, app.targetSdkVersion); 19365 } catch (InstallerException e) { 19366 if (app.isSystemApp()) { 19367 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19368 + ", but trying to recover: " + e); 19369 destroyAppDataLeafLIF(pkg, userId, flags); 19370 try { 19371 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19372 appId, app.seinfo, app.targetSdkVersion); 19373 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19374 } catch (InstallerException e2) { 19375 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19376 } 19377 } else { 19378 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19379 } 19380 } 19381 19382 if (restoreconNeeded) { 19383 try { 19384 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19385 app.seinfo); 19386 } catch (InstallerException e) { 19387 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19388 } 19389 } 19390 19391 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19392 try { 19393 // CE storage is unlocked right now, so read out the inode and 19394 // remember for use later when it's locked 19395 // TODO: mark this structure as dirty so we persist it! 19396 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19397 StorageManager.FLAG_STORAGE_CE); 19398 synchronized (mPackages) { 19399 final PackageSetting ps = mSettings.mPackages.get(packageName); 19400 if (ps != null) { 19401 ps.setCeDataInode(ceDataInode, userId); 19402 } 19403 } 19404 } catch (InstallerException e) { 19405 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19406 } 19407 } 19408 19409 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19410 } 19411 19412 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19413 if (pkg == null) { 19414 Slog.wtf(TAG, "Package was null!", new Throwable()); 19415 return; 19416 } 19417 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19418 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19419 for (int i = 0; i < childCount; i++) { 19420 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19421 } 19422 } 19423 19424 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19425 final String volumeUuid = pkg.volumeUuid; 19426 final String packageName = pkg.packageName; 19427 final ApplicationInfo app = pkg.applicationInfo; 19428 19429 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19430 // Create a native library symlink only if we have native libraries 19431 // and if the native libraries are 32 bit libraries. We do not provide 19432 // this symlink for 64 bit libraries. 19433 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19434 final String nativeLibPath = app.nativeLibraryDir; 19435 try { 19436 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19437 nativeLibPath, userId); 19438 } catch (InstallerException e) { 19439 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19440 } 19441 } 19442 } 19443 } 19444 19445 /** 19446 * For system apps on non-FBE devices, this method migrates any existing 19447 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19448 * requested by the app. 19449 */ 19450 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19451 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19452 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19453 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19454 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19455 try { 19456 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19457 storageTarget); 19458 } catch (InstallerException e) { 19459 logCriticalInfo(Log.WARN, 19460 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19461 } 19462 return true; 19463 } else { 19464 return false; 19465 } 19466 } 19467 19468 public PackageFreezer freezePackage(String packageName, String killReason) { 19469 return new PackageFreezer(packageName, killReason); 19470 } 19471 19472 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19473 String killReason) { 19474 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19475 return new PackageFreezer(); 19476 } else { 19477 return freezePackage(packageName, killReason); 19478 } 19479 } 19480 19481 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19482 String killReason) { 19483 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19484 return new PackageFreezer(); 19485 } else { 19486 return freezePackage(packageName, killReason); 19487 } 19488 } 19489 19490 /** 19491 * Class that freezes and kills the given package upon creation, and 19492 * unfreezes it upon closing. This is typically used when doing surgery on 19493 * app code/data to prevent the app from running while you're working. 19494 */ 19495 private class PackageFreezer implements AutoCloseable { 19496 private final String mPackageName; 19497 private final PackageFreezer[] mChildren; 19498 19499 private final boolean mWeFroze; 19500 19501 private final AtomicBoolean mClosed = new AtomicBoolean(); 19502 private final CloseGuard mCloseGuard = CloseGuard.get(); 19503 19504 /** 19505 * Create and return a stub freezer that doesn't actually do anything, 19506 * typically used when someone requested 19507 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19508 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19509 */ 19510 public PackageFreezer() { 19511 mPackageName = null; 19512 mChildren = null; 19513 mWeFroze = false; 19514 mCloseGuard.open("close"); 19515 } 19516 19517 public PackageFreezer(String packageName, String killReason) { 19518 synchronized (mPackages) { 19519 mPackageName = packageName; 19520 mWeFroze = mFrozenPackages.add(mPackageName); 19521 19522 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19523 if (ps != null) { 19524 killApplication(ps.name, ps.appId, killReason); 19525 } 19526 19527 final PackageParser.Package p = mPackages.get(packageName); 19528 if (p != null && p.childPackages != null) { 19529 final int N = p.childPackages.size(); 19530 mChildren = new PackageFreezer[N]; 19531 for (int i = 0; i < N; i++) { 19532 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19533 killReason); 19534 } 19535 } else { 19536 mChildren = null; 19537 } 19538 } 19539 mCloseGuard.open("close"); 19540 } 19541 19542 @Override 19543 protected void finalize() throws Throwable { 19544 try { 19545 mCloseGuard.warnIfOpen(); 19546 close(); 19547 } finally { 19548 super.finalize(); 19549 } 19550 } 19551 19552 @Override 19553 public void close() { 19554 mCloseGuard.close(); 19555 if (mClosed.compareAndSet(false, true)) { 19556 synchronized (mPackages) { 19557 if (mWeFroze) { 19558 mFrozenPackages.remove(mPackageName); 19559 } 19560 19561 if (mChildren != null) { 19562 for (PackageFreezer freezer : mChildren) { 19563 freezer.close(); 19564 } 19565 } 19566 } 19567 } 19568 } 19569 } 19570 19571 /** 19572 * Verify that given package is currently frozen. 19573 */ 19574 private void checkPackageFrozen(String packageName) { 19575 synchronized (mPackages) { 19576 if (!mFrozenPackages.contains(packageName)) { 19577 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19578 } 19579 } 19580 } 19581 19582 @Override 19583 public int movePackage(final String packageName, final String volumeUuid) { 19584 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19585 19586 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19587 final int moveId = mNextMoveId.getAndIncrement(); 19588 mHandler.post(new Runnable() { 19589 @Override 19590 public void run() { 19591 try { 19592 movePackageInternal(packageName, volumeUuid, moveId, user); 19593 } catch (PackageManagerException e) { 19594 Slog.w(TAG, "Failed to move " + packageName, e); 19595 mMoveCallbacks.notifyStatusChanged(moveId, 19596 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19597 } 19598 } 19599 }); 19600 return moveId; 19601 } 19602 19603 private void movePackageInternal(final String packageName, final String volumeUuid, 19604 final int moveId, UserHandle user) throws PackageManagerException { 19605 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19606 final PackageManager pm = mContext.getPackageManager(); 19607 19608 final boolean currentAsec; 19609 final String currentVolumeUuid; 19610 final File codeFile; 19611 final String installerPackageName; 19612 final String packageAbiOverride; 19613 final int appId; 19614 final String seinfo; 19615 final String label; 19616 final int targetSdkVersion; 19617 final PackageFreezer freezer; 19618 19619 // reader 19620 synchronized (mPackages) { 19621 final PackageParser.Package pkg = mPackages.get(packageName); 19622 final PackageSetting ps = mSettings.mPackages.get(packageName); 19623 if (pkg == null || ps == null) { 19624 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19625 } 19626 19627 if (pkg.applicationInfo.isSystemApp()) { 19628 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19629 "Cannot move system application"); 19630 } 19631 19632 if (pkg.applicationInfo.isExternalAsec()) { 19633 currentAsec = true; 19634 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19635 } else if (pkg.applicationInfo.isForwardLocked()) { 19636 currentAsec = true; 19637 currentVolumeUuid = "forward_locked"; 19638 } else { 19639 currentAsec = false; 19640 currentVolumeUuid = ps.volumeUuid; 19641 19642 final File probe = new File(pkg.codePath); 19643 final File probeOat = new File(probe, "oat"); 19644 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19645 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19646 "Move only supported for modern cluster style installs"); 19647 } 19648 } 19649 19650 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19651 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19652 "Package already moved to " + volumeUuid); 19653 } 19654 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19655 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19656 "Device admin cannot be moved"); 19657 } 19658 19659 if (mFrozenPackages.contains(packageName)) { 19660 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19661 "Failed to move already frozen package"); 19662 } 19663 19664 codeFile = new File(pkg.codePath); 19665 installerPackageName = ps.installerPackageName; 19666 packageAbiOverride = ps.cpuAbiOverrideString; 19667 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19668 seinfo = pkg.applicationInfo.seinfo; 19669 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19670 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19671 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19672 } 19673 19674 final Bundle extras = new Bundle(); 19675 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19676 extras.putString(Intent.EXTRA_TITLE, label); 19677 mMoveCallbacks.notifyCreated(moveId, extras); 19678 19679 int installFlags; 19680 final boolean moveCompleteApp; 19681 final File measurePath; 19682 19683 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19684 installFlags = INSTALL_INTERNAL; 19685 moveCompleteApp = !currentAsec; 19686 measurePath = Environment.getDataAppDirectory(volumeUuid); 19687 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19688 installFlags = INSTALL_EXTERNAL; 19689 moveCompleteApp = false; 19690 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19691 } else { 19692 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19693 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19694 || !volume.isMountedWritable()) { 19695 freezer.close(); 19696 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19697 "Move location not mounted private volume"); 19698 } 19699 19700 Preconditions.checkState(!currentAsec); 19701 19702 installFlags = INSTALL_INTERNAL; 19703 moveCompleteApp = true; 19704 measurePath = Environment.getDataAppDirectory(volumeUuid); 19705 } 19706 19707 final PackageStats stats = new PackageStats(null, -1); 19708 synchronized (mInstaller) { 19709 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19710 freezer.close(); 19711 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19712 "Failed to measure package size"); 19713 } 19714 } 19715 19716 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19717 + stats.dataSize); 19718 19719 final long startFreeBytes = measurePath.getFreeSpace(); 19720 final long sizeBytes; 19721 if (moveCompleteApp) { 19722 sizeBytes = stats.codeSize + stats.dataSize; 19723 } else { 19724 sizeBytes = stats.codeSize; 19725 } 19726 19727 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19728 freezer.close(); 19729 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19730 "Not enough free space to move"); 19731 } 19732 19733 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19734 19735 final CountDownLatch installedLatch = new CountDownLatch(1); 19736 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19737 @Override 19738 public void onUserActionRequired(Intent intent) throws RemoteException { 19739 throw new IllegalStateException(); 19740 } 19741 19742 @Override 19743 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19744 Bundle extras) throws RemoteException { 19745 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19746 + PackageManager.installStatusToString(returnCode, msg)); 19747 19748 installedLatch.countDown(); 19749 freezer.close(); 19750 19751 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19752 switch (status) { 19753 case PackageInstaller.STATUS_SUCCESS: 19754 mMoveCallbacks.notifyStatusChanged(moveId, 19755 PackageManager.MOVE_SUCCEEDED); 19756 break; 19757 case PackageInstaller.STATUS_FAILURE_STORAGE: 19758 mMoveCallbacks.notifyStatusChanged(moveId, 19759 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19760 break; 19761 default: 19762 mMoveCallbacks.notifyStatusChanged(moveId, 19763 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19764 break; 19765 } 19766 } 19767 }; 19768 19769 final MoveInfo move; 19770 if (moveCompleteApp) { 19771 // Kick off a thread to report progress estimates 19772 new Thread() { 19773 @Override 19774 public void run() { 19775 while (true) { 19776 try { 19777 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19778 break; 19779 } 19780 } catch (InterruptedException ignored) { 19781 } 19782 19783 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19784 final int progress = 10 + (int) MathUtils.constrain( 19785 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19786 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19787 } 19788 } 19789 }.start(); 19790 19791 final String dataAppName = codeFile.getName(); 19792 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19793 dataAppName, appId, seinfo, targetSdkVersion); 19794 } else { 19795 move = null; 19796 } 19797 19798 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19799 19800 final Message msg = mHandler.obtainMessage(INIT_COPY); 19801 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19802 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19803 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19804 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19805 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19806 msg.obj = params; 19807 19808 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19809 System.identityHashCode(msg.obj)); 19810 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19811 System.identityHashCode(msg.obj)); 19812 19813 mHandler.sendMessage(msg); 19814 } 19815 19816 @Override 19817 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19818 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19819 19820 final int realMoveId = mNextMoveId.getAndIncrement(); 19821 final Bundle extras = new Bundle(); 19822 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19823 mMoveCallbacks.notifyCreated(realMoveId, extras); 19824 19825 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19826 @Override 19827 public void onCreated(int moveId, Bundle extras) { 19828 // Ignored 19829 } 19830 19831 @Override 19832 public void onStatusChanged(int moveId, int status, long estMillis) { 19833 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19834 } 19835 }; 19836 19837 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19838 storage.setPrimaryStorageUuid(volumeUuid, callback); 19839 return realMoveId; 19840 } 19841 19842 @Override 19843 public int getMoveStatus(int moveId) { 19844 mContext.enforceCallingOrSelfPermission( 19845 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19846 return mMoveCallbacks.mLastStatus.get(moveId); 19847 } 19848 19849 @Override 19850 public void registerMoveCallback(IPackageMoveObserver callback) { 19851 mContext.enforceCallingOrSelfPermission( 19852 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19853 mMoveCallbacks.register(callback); 19854 } 19855 19856 @Override 19857 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19858 mContext.enforceCallingOrSelfPermission( 19859 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19860 mMoveCallbacks.unregister(callback); 19861 } 19862 19863 @Override 19864 public boolean setInstallLocation(int loc) { 19865 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19866 null); 19867 if (getInstallLocation() == loc) { 19868 return true; 19869 } 19870 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19871 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19872 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19873 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19874 return true; 19875 } 19876 return false; 19877 } 19878 19879 @Override 19880 public int getInstallLocation() { 19881 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19882 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19883 PackageHelper.APP_INSTALL_AUTO); 19884 } 19885 19886 /** Called by UserManagerService */ 19887 void cleanUpUser(UserManagerService userManager, int userHandle) { 19888 synchronized (mPackages) { 19889 mDirtyUsers.remove(userHandle); 19890 mUserNeedsBadging.delete(userHandle); 19891 mSettings.removeUserLPw(userHandle); 19892 mPendingBroadcasts.remove(userHandle); 19893 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19894 removeUnusedPackagesLPw(userManager, userHandle); 19895 } 19896 } 19897 19898 /** 19899 * We're removing userHandle and would like to remove any downloaded packages 19900 * that are no longer in use by any other user. 19901 * @param userHandle the user being removed 19902 */ 19903 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19904 final boolean DEBUG_CLEAN_APKS = false; 19905 int [] users = userManager.getUserIds(); 19906 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19907 while (psit.hasNext()) { 19908 PackageSetting ps = psit.next(); 19909 if (ps.pkg == null) { 19910 continue; 19911 } 19912 final String packageName = ps.pkg.packageName; 19913 // Skip over if system app 19914 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19915 continue; 19916 } 19917 if (DEBUG_CLEAN_APKS) { 19918 Slog.i(TAG, "Checking package " + packageName); 19919 } 19920 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19921 if (keep) { 19922 if (DEBUG_CLEAN_APKS) { 19923 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19924 } 19925 } else { 19926 for (int i = 0; i < users.length; i++) { 19927 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19928 keep = true; 19929 if (DEBUG_CLEAN_APKS) { 19930 Slog.i(TAG, " Keeping package " + packageName + " for user " 19931 + users[i]); 19932 } 19933 break; 19934 } 19935 } 19936 } 19937 if (!keep) { 19938 if (DEBUG_CLEAN_APKS) { 19939 Slog.i(TAG, " Removing package " + packageName); 19940 } 19941 mHandler.post(new Runnable() { 19942 public void run() { 19943 deletePackageX(packageName, userHandle, 0); 19944 } //end run 19945 }); 19946 } 19947 } 19948 } 19949 19950 /** Called by UserManagerService */ 19951 void createNewUser(int userHandle) { 19952 synchronized (mInstallLock) { 19953 mSettings.createNewUserLI(this, mInstaller, userHandle); 19954 } 19955 synchronized (mPackages) { 19956 applyFactoryDefaultBrowserLPw(userHandle); 19957 primeDomainVerificationsLPw(userHandle); 19958 } 19959 } 19960 19961 void newUserCreated(final int userHandle) { 19962 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19963 // If permission review for legacy apps is required, we represent 19964 // dagerous permissions for such apps as always granted runtime 19965 // permissions to keep per user flag state whether review is needed. 19966 // Hence, if a new user is added we have to propagate dangerous 19967 // permission grants for these legacy apps. 19968 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19969 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19970 | UPDATE_PERMISSIONS_REPLACE_ALL); 19971 } 19972 } 19973 19974 @Override 19975 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19976 mContext.enforceCallingOrSelfPermission( 19977 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19978 "Only package verification agents can read the verifier device identity"); 19979 19980 synchronized (mPackages) { 19981 return mSettings.getVerifierDeviceIdentityLPw(); 19982 } 19983 } 19984 19985 @Override 19986 public void setPermissionEnforced(String permission, boolean enforced) { 19987 // TODO: Now that we no longer change GID for storage, this should to away. 19988 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19989 "setPermissionEnforced"); 19990 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19991 synchronized (mPackages) { 19992 if (mSettings.mReadExternalStorageEnforced == null 19993 || mSettings.mReadExternalStorageEnforced != enforced) { 19994 mSettings.mReadExternalStorageEnforced = enforced; 19995 mSettings.writeLPr(); 19996 } 19997 } 19998 // kill any non-foreground processes so we restart them and 19999 // grant/revoke the GID. 20000 final IActivityManager am = ActivityManagerNative.getDefault(); 20001 if (am != null) { 20002 final long token = Binder.clearCallingIdentity(); 20003 try { 20004 am.killProcessesBelowForeground("setPermissionEnforcement"); 20005 } catch (RemoteException e) { 20006 } finally { 20007 Binder.restoreCallingIdentity(token); 20008 } 20009 } 20010 } else { 20011 throw new IllegalArgumentException("No selective enforcement for " + permission); 20012 } 20013 } 20014 20015 @Override 20016 @Deprecated 20017 public boolean isPermissionEnforced(String permission) { 20018 return true; 20019 } 20020 20021 @Override 20022 public boolean isStorageLow() { 20023 final long token = Binder.clearCallingIdentity(); 20024 try { 20025 final DeviceStorageMonitorInternal 20026 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20027 if (dsm != null) { 20028 return dsm.isMemoryLow(); 20029 } else { 20030 return false; 20031 } 20032 } finally { 20033 Binder.restoreCallingIdentity(token); 20034 } 20035 } 20036 20037 @Override 20038 public IPackageInstaller getPackageInstaller() { 20039 return mInstallerService; 20040 } 20041 20042 private boolean userNeedsBadging(int userId) { 20043 int index = mUserNeedsBadging.indexOfKey(userId); 20044 if (index < 0) { 20045 final UserInfo userInfo; 20046 final long token = Binder.clearCallingIdentity(); 20047 try { 20048 userInfo = sUserManager.getUserInfo(userId); 20049 } finally { 20050 Binder.restoreCallingIdentity(token); 20051 } 20052 final boolean b; 20053 if (userInfo != null && userInfo.isManagedProfile()) { 20054 b = true; 20055 } else { 20056 b = false; 20057 } 20058 mUserNeedsBadging.put(userId, b); 20059 return b; 20060 } 20061 return mUserNeedsBadging.valueAt(index); 20062 } 20063 20064 @Override 20065 public KeySet getKeySetByAlias(String packageName, String alias) { 20066 if (packageName == null || alias == null) { 20067 return null; 20068 } 20069 synchronized(mPackages) { 20070 final PackageParser.Package pkg = mPackages.get(packageName); 20071 if (pkg == null) { 20072 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20073 throw new IllegalArgumentException("Unknown package: " + packageName); 20074 } 20075 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20076 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20077 } 20078 } 20079 20080 @Override 20081 public KeySet getSigningKeySet(String packageName) { 20082 if (packageName == null) { 20083 return null; 20084 } 20085 synchronized(mPackages) { 20086 final PackageParser.Package pkg = mPackages.get(packageName); 20087 if (pkg == null) { 20088 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20089 throw new IllegalArgumentException("Unknown package: " + packageName); 20090 } 20091 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20092 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20093 throw new SecurityException("May not access signing KeySet of other apps."); 20094 } 20095 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20096 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20097 } 20098 } 20099 20100 @Override 20101 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20102 if (packageName == null || ks == null) { 20103 return false; 20104 } 20105 synchronized(mPackages) { 20106 final PackageParser.Package pkg = mPackages.get(packageName); 20107 if (pkg == null) { 20108 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20109 throw new IllegalArgumentException("Unknown package: " + packageName); 20110 } 20111 IBinder ksh = ks.getToken(); 20112 if (ksh instanceof KeySetHandle) { 20113 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20114 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20115 } 20116 return false; 20117 } 20118 } 20119 20120 @Override 20121 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20122 if (packageName == null || ks == null) { 20123 return false; 20124 } 20125 synchronized(mPackages) { 20126 final PackageParser.Package pkg = mPackages.get(packageName); 20127 if (pkg == null) { 20128 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20129 throw new IllegalArgumentException("Unknown package: " + packageName); 20130 } 20131 IBinder ksh = ks.getToken(); 20132 if (ksh instanceof KeySetHandle) { 20133 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20134 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20135 } 20136 return false; 20137 } 20138 } 20139 20140 private void deletePackageIfUnusedLPr(final String packageName) { 20141 PackageSetting ps = mSettings.mPackages.get(packageName); 20142 if (ps == null) { 20143 return; 20144 } 20145 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20146 // TODO Implement atomic delete if package is unused 20147 // It is currently possible that the package will be deleted even if it is installed 20148 // after this method returns. 20149 mHandler.post(new Runnable() { 20150 public void run() { 20151 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20152 } 20153 }); 20154 } 20155 } 20156 20157 /** 20158 * Check and throw if the given before/after packages would be considered a 20159 * downgrade. 20160 */ 20161 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20162 throws PackageManagerException { 20163 if (after.versionCode < before.mVersionCode) { 20164 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20165 "Update version code " + after.versionCode + " is older than current " 20166 + before.mVersionCode); 20167 } else if (after.versionCode == before.mVersionCode) { 20168 if (after.baseRevisionCode < before.baseRevisionCode) { 20169 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20170 "Update base revision code " + after.baseRevisionCode 20171 + " is older than current " + before.baseRevisionCode); 20172 } 20173 20174 if (!ArrayUtils.isEmpty(after.splitNames)) { 20175 for (int i = 0; i < after.splitNames.length; i++) { 20176 final String splitName = after.splitNames[i]; 20177 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20178 if (j != -1) { 20179 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20180 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20181 "Update split " + splitName + " revision code " 20182 + after.splitRevisionCodes[i] + " is older than current " 20183 + before.splitRevisionCodes[j]); 20184 } 20185 } 20186 } 20187 } 20188 } 20189 } 20190 20191 private static class MoveCallbacks extends Handler { 20192 private static final int MSG_CREATED = 1; 20193 private static final int MSG_STATUS_CHANGED = 2; 20194 20195 private final RemoteCallbackList<IPackageMoveObserver> 20196 mCallbacks = new RemoteCallbackList<>(); 20197 20198 private final SparseIntArray mLastStatus = new SparseIntArray(); 20199 20200 public MoveCallbacks(Looper looper) { 20201 super(looper); 20202 } 20203 20204 public void register(IPackageMoveObserver callback) { 20205 mCallbacks.register(callback); 20206 } 20207 20208 public void unregister(IPackageMoveObserver callback) { 20209 mCallbacks.unregister(callback); 20210 } 20211 20212 @Override 20213 public void handleMessage(Message msg) { 20214 final SomeArgs args = (SomeArgs) msg.obj; 20215 final int n = mCallbacks.beginBroadcast(); 20216 for (int i = 0; i < n; i++) { 20217 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20218 try { 20219 invokeCallback(callback, msg.what, args); 20220 } catch (RemoteException ignored) { 20221 } 20222 } 20223 mCallbacks.finishBroadcast(); 20224 args.recycle(); 20225 } 20226 20227 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20228 throws RemoteException { 20229 switch (what) { 20230 case MSG_CREATED: { 20231 callback.onCreated(args.argi1, (Bundle) args.arg2); 20232 break; 20233 } 20234 case MSG_STATUS_CHANGED: { 20235 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20236 break; 20237 } 20238 } 20239 } 20240 20241 private void notifyCreated(int moveId, Bundle extras) { 20242 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20243 20244 final SomeArgs args = SomeArgs.obtain(); 20245 args.argi1 = moveId; 20246 args.arg2 = extras; 20247 obtainMessage(MSG_CREATED, args).sendToTarget(); 20248 } 20249 20250 private void notifyStatusChanged(int moveId, int status) { 20251 notifyStatusChanged(moveId, status, -1); 20252 } 20253 20254 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20255 Slog.v(TAG, "Move " + moveId + " status " + status); 20256 20257 final SomeArgs args = SomeArgs.obtain(); 20258 args.argi1 = moveId; 20259 args.argi2 = status; 20260 args.arg3 = estMillis; 20261 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20262 20263 synchronized (mLastStatus) { 20264 mLastStatus.put(moveId, status); 20265 } 20266 } 20267 } 20268 20269 private final static class OnPermissionChangeListeners extends Handler { 20270 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20271 20272 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20273 new RemoteCallbackList<>(); 20274 20275 public OnPermissionChangeListeners(Looper looper) { 20276 super(looper); 20277 } 20278 20279 @Override 20280 public void handleMessage(Message msg) { 20281 switch (msg.what) { 20282 case MSG_ON_PERMISSIONS_CHANGED: { 20283 final int uid = msg.arg1; 20284 handleOnPermissionsChanged(uid); 20285 } break; 20286 } 20287 } 20288 20289 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20290 mPermissionListeners.register(listener); 20291 20292 } 20293 20294 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20295 mPermissionListeners.unregister(listener); 20296 } 20297 20298 public void onPermissionsChanged(int uid) { 20299 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20300 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20301 } 20302 } 20303 20304 private void handleOnPermissionsChanged(int uid) { 20305 final int count = mPermissionListeners.beginBroadcast(); 20306 try { 20307 for (int i = 0; i < count; i++) { 20308 IOnPermissionsChangeListener callback = mPermissionListeners 20309 .getBroadcastItem(i); 20310 try { 20311 callback.onPermissionsChanged(uid); 20312 } catch (RemoteException e) { 20313 Log.e(TAG, "Permission listener is dead", e); 20314 } 20315 } 20316 } finally { 20317 mPermissionListeners.finishBroadcast(); 20318 } 20319 } 20320 } 20321 20322 private class PackageManagerInternalImpl extends PackageManagerInternal { 20323 @Override 20324 public void setLocationPackagesProvider(PackagesProvider provider) { 20325 synchronized (mPackages) { 20326 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20327 } 20328 } 20329 20330 @Override 20331 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20332 synchronized (mPackages) { 20333 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20334 } 20335 } 20336 20337 @Override 20338 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20339 synchronized (mPackages) { 20340 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20341 } 20342 } 20343 20344 @Override 20345 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20346 synchronized (mPackages) { 20347 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20348 } 20349 } 20350 20351 @Override 20352 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20353 synchronized (mPackages) { 20354 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20355 } 20356 } 20357 20358 @Override 20359 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20360 synchronized (mPackages) { 20361 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20362 } 20363 } 20364 20365 @Override 20366 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20367 synchronized (mPackages) { 20368 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20369 packageName, userId); 20370 } 20371 } 20372 20373 @Override 20374 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20375 synchronized (mPackages) { 20376 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20377 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20378 packageName, userId); 20379 } 20380 } 20381 20382 @Override 20383 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20384 synchronized (mPackages) { 20385 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20386 packageName, userId); 20387 } 20388 } 20389 20390 @Override 20391 public void setKeepUninstalledPackages(final List<String> packageList) { 20392 Preconditions.checkNotNull(packageList); 20393 List<String> removedFromList = null; 20394 synchronized (mPackages) { 20395 if (mKeepUninstalledPackages != null) { 20396 final int packagesCount = mKeepUninstalledPackages.size(); 20397 for (int i = 0; i < packagesCount; i++) { 20398 String oldPackage = mKeepUninstalledPackages.get(i); 20399 if (packageList != null && packageList.contains(oldPackage)) { 20400 continue; 20401 } 20402 if (removedFromList == null) { 20403 removedFromList = new ArrayList<>(); 20404 } 20405 removedFromList.add(oldPackage); 20406 } 20407 } 20408 mKeepUninstalledPackages = new ArrayList<>(packageList); 20409 if (removedFromList != null) { 20410 final int removedCount = removedFromList.size(); 20411 for (int i = 0; i < removedCount; i++) { 20412 deletePackageIfUnusedLPr(removedFromList.get(i)); 20413 } 20414 } 20415 } 20416 } 20417 20418 @Override 20419 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20420 synchronized (mPackages) { 20421 // If we do not support permission review, done. 20422 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20423 return false; 20424 } 20425 20426 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20427 if (packageSetting == null) { 20428 return false; 20429 } 20430 20431 // Permission review applies only to apps not supporting the new permission model. 20432 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20433 return false; 20434 } 20435 20436 // Legacy apps have the permission and get user consent on launch. 20437 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20438 return permissionsState.isPermissionReviewRequired(userId); 20439 } 20440 } 20441 20442 @Override 20443 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20444 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20445 } 20446 20447 @Override 20448 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20449 int userId) { 20450 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20451 } 20452 } 20453 20454 @Override 20455 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20456 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20457 synchronized (mPackages) { 20458 final long identity = Binder.clearCallingIdentity(); 20459 try { 20460 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20461 packageNames, userId); 20462 } finally { 20463 Binder.restoreCallingIdentity(identity); 20464 } 20465 } 20466 } 20467 20468 private static void enforceSystemOrPhoneCaller(String tag) { 20469 int callingUid = Binder.getCallingUid(); 20470 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20471 throw new SecurityException( 20472 "Cannot call " + tag + " from UID " + callingUid); 20473 } 20474 } 20475 20476 boolean isHistoricalPackageUsageAvailable() { 20477 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20478 } 20479 20480 /** 20481 * Return a <b>copy</b> of the collection of packages known to the package manager. 20482 * @return A copy of the values of mPackages. 20483 */ 20484 Collection<PackageParser.Package> getPackages() { 20485 synchronized (mPackages) { 20486 return new ArrayList<>(mPackages.values()); 20487 } 20488 } 20489 20490 /** 20491 * Logs process start information (including base APK hash) to the security log. 20492 * @hide 20493 */ 20494 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20495 String apkFile, int pid) { 20496 if (!SecurityLog.isLoggingEnabled()) { 20497 return; 20498 } 20499 Bundle data = new Bundle(); 20500 data.putLong("startTimestamp", System.currentTimeMillis()); 20501 data.putString("processName", processName); 20502 data.putInt("uid", uid); 20503 data.putString("seinfo", seinfo); 20504 data.putString("apkFile", apkFile); 20505 data.putInt("pid", pid); 20506 Message msg = mProcessLoggingHandler.obtainMessage( 20507 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20508 msg.setData(data); 20509 mProcessLoggingHandler.sendMessage(msg); 20510 } 20511} 20512