PackageManagerService.java revision 86100d18ad0bd5ae3267a0e0944d15f4fe94078a
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.INetworkPolicyManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.UserManagerInternal; 194import android.os.storage.IMountService; 195import android.os.storage.MountServiceInternal; 196import android.os.storage.StorageEventListener; 197import android.os.storage.StorageManager; 198import android.os.storage.VolumeInfo; 199import android.os.storage.VolumeRecord; 200import android.security.KeyStore; 201import android.security.SystemKeyStore; 202import android.system.ErrnoException; 203import android.system.Os; 204import android.text.TextUtils; 205import android.text.format.DateUtils; 206import android.util.ArrayMap; 207import android.util.ArraySet; 208import android.util.AtomicFile; 209import android.util.DisplayMetrics; 210import android.util.EventLog; 211import android.util.ExceptionUtils; 212import android.util.Log; 213import android.util.LogPrinter; 214import android.util.MathUtils; 215import android.util.PrintStreamPrinter; 216import android.util.Slog; 217import android.util.SparseArray; 218import android.util.SparseBooleanArray; 219import android.util.SparseIntArray; 220import android.util.Xml; 221import android.util.jar.StrictJarFile; 222import android.view.Display; 223 224import com.android.internal.R; 225import com.android.internal.annotations.GuardedBy; 226import com.android.internal.app.IMediaContainerService; 227import com.android.internal.app.ResolverActivity; 228import com.android.internal.content.NativeLibraryHelper; 229import com.android.internal.content.PackageHelper; 230import com.android.internal.logging.MetricsLogger; 231import com.android.internal.os.IParcelFileDescriptorFactory; 232import com.android.internal.os.InstallerConnection.InstallerException; 233import com.android.internal.os.SomeArgs; 234import com.android.internal.os.Zygote; 235import com.android.internal.telephony.CarrierAppUtils; 236import com.android.internal.util.ArrayUtils; 237import com.android.internal.util.FastPrintWriter; 238import com.android.internal.util.FastXmlSerializer; 239import com.android.internal.util.IndentingPrintWriter; 240import com.android.internal.util.Preconditions; 241import com.android.internal.util.XmlUtils; 242import com.android.server.EventLogTags; 243import com.android.server.FgThread; 244import com.android.server.IntentResolver; 245import com.android.server.LocalServices; 246import com.android.server.ServiceThread; 247import com.android.server.SystemConfig; 248import com.android.server.Watchdog; 249import com.android.server.net.NetworkPolicyManagerInternal; 250import com.android.server.pm.PermissionsState.PermissionState; 251import com.android.server.pm.Settings.DatabaseVersion; 252import com.android.server.pm.Settings.VersionInfo; 253import com.android.server.storage.DeviceStorageMonitorInternal; 254 255import dalvik.system.CloseGuard; 256import dalvik.system.DexFile; 257import dalvik.system.VMRuntime; 258 259import libcore.io.IoUtils; 260import libcore.util.EmptyArray; 261 262import org.xmlpull.v1.XmlPullParser; 263import org.xmlpull.v1.XmlPullParserException; 264import org.xmlpull.v1.XmlSerializer; 265 266import java.io.BufferedInputStream; 267import java.io.BufferedOutputStream; 268import java.io.BufferedReader; 269import java.io.ByteArrayInputStream; 270import java.io.ByteArrayOutputStream; 271import java.io.File; 272import java.io.FileDescriptor; 273import java.io.FileInputStream; 274import java.io.FileNotFoundException; 275import java.io.FileOutputStream; 276import java.io.FileReader; 277import java.io.FilenameFilter; 278import java.io.IOException; 279import java.io.InputStream; 280import java.io.PrintWriter; 281import java.nio.charset.StandardCharsets; 282import java.security.DigestInputStream; 283import java.security.MessageDigest; 284import java.security.NoSuchAlgorithmException; 285import java.security.PublicKey; 286import java.security.cert.Certificate; 287import java.security.cert.CertificateEncodingException; 288import java.security.cert.CertificateException; 289import java.text.SimpleDateFormat; 290import java.util.ArrayList; 291import java.util.Arrays; 292import java.util.Collection; 293import java.util.Collections; 294import java.util.Comparator; 295import java.util.Date; 296import java.util.HashSet; 297import java.util.Iterator; 298import java.util.List; 299import java.util.Map; 300import java.util.Objects; 301import java.util.Set; 302import java.util.concurrent.CountDownLatch; 303import java.util.concurrent.TimeUnit; 304import java.util.concurrent.atomic.AtomicBoolean; 305import java.util.concurrent.atomic.AtomicInteger; 306import java.util.concurrent.atomic.AtomicLong; 307 308/** 309 * Keep track of all those APKs everywhere. 310 * <p> 311 * Internally there are two important locks: 312 * <ul> 313 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 314 * and other related state. It is a fine-grained lock that should only be held 315 * momentarily, as it's one of the most contended locks in the system. 316 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 317 * operations typically involve heavy lifting of application data on disk. Since 318 * {@code installd} is single-threaded, and it's operations can often be slow, 319 * this lock should never be acquired while already holding {@link #mPackages}. 320 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 321 * holding {@link #mInstallLock}. 322 * </ul> 323 * Many internal methods rely on the caller to hold the appropriate locks, and 324 * this contract is expressed through method name suffixes: 325 * <ul> 326 * <li>fooLI(): the caller must hold {@link #mInstallLock} 327 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 328 * being modified must be frozen 329 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 330 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 331 * </ul> 332 * <p> 333 * Because this class is very central to the platform's security; please run all 334 * CTS and unit tests whenever making modifications: 335 * 336 * <pre> 337 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 338 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 339 * </pre> 340 */ 341public class PackageManagerService extends IPackageManager.Stub { 342 static final String TAG = "PackageManager"; 343 static final boolean DEBUG_SETTINGS = false; 344 static final boolean DEBUG_PREFERRED = false; 345 static final boolean DEBUG_UPGRADE = false; 346 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 347 private static final boolean DEBUG_BACKUP = false; 348 private static final boolean DEBUG_INSTALL = false; 349 private static final boolean DEBUG_REMOVE = false; 350 private static final boolean DEBUG_BROADCASTS = false; 351 private static final boolean DEBUG_SHOW_INFO = false; 352 private static final boolean DEBUG_PACKAGE_INFO = false; 353 private static final boolean DEBUG_INTENT_MATCHING = false; 354 private static final boolean DEBUG_PACKAGE_SCANNING = false; 355 private static final boolean DEBUG_VERIFY = false; 356 private static final boolean DEBUG_FILTERS = false; 357 358 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 359 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 360 // user, but by default initialize to this. 361 static final boolean DEBUG_DEXOPT = false; 362 363 private static final boolean DEBUG_ABI_SELECTION = false; 364 private static final boolean DEBUG_EPHEMERAL = false; 365 private static final boolean DEBUG_TRIAGED_MISSING = false; 366 private static final boolean DEBUG_APP_DATA = false; 367 368 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 369 370 private static final boolean DISABLE_EPHEMERAL_APPS = true; 371 372 private static final int RADIO_UID = Process.PHONE_UID; 373 private static final int LOG_UID = Process.LOG_UID; 374 private static final int NFC_UID = Process.NFC_UID; 375 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 376 private static final int SHELL_UID = Process.SHELL_UID; 377 378 // Cap the size of permission trees that 3rd party apps can define 379 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 380 381 // Suffix used during package installation when copying/moving 382 // package apks to install directory. 383 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 384 385 static final int SCAN_NO_DEX = 1<<1; 386 static final int SCAN_FORCE_DEX = 1<<2; 387 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 388 static final int SCAN_NEW_INSTALL = 1<<4; 389 static final int SCAN_NO_PATHS = 1<<5; 390 static final int SCAN_UPDATE_TIME = 1<<6; 391 static final int SCAN_DEFER_DEX = 1<<7; 392 static final int SCAN_BOOTING = 1<<8; 393 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 394 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 395 static final int SCAN_REPLACING = 1<<11; 396 static final int SCAN_REQUIRE_KNOWN = 1<<12; 397 static final int SCAN_MOVE = 1<<13; 398 static final int SCAN_INITIAL = 1<<14; 399 static final int SCAN_CHECK_ONLY = 1<<15; 400 static final int SCAN_DONT_KILL_APP = 1<<17; 401 static final int SCAN_IGNORE_FROZEN = 1<<18; 402 403 static final int REMOVE_CHATTY = 1<<16; 404 405 private static final int[] EMPTY_INT_ARRAY = new int[0]; 406 407 /** 408 * Timeout (in milliseconds) after which the watchdog should declare that 409 * our handler thread is wedged. The usual default for such things is one 410 * minute but we sometimes do very lengthy I/O operations on this thread, 411 * such as installing multi-gigabyte applications, so ours needs to be longer. 412 */ 413 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 414 415 /** 416 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 417 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 418 * settings entry if available, otherwise we use the hardcoded default. If it's been 419 * more than this long since the last fstrim, we force one during the boot sequence. 420 * 421 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 422 * one gets run at the next available charging+idle time. This final mandatory 423 * no-fstrim check kicks in only of the other scheduling criteria is never met. 424 */ 425 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 426 427 /** 428 * Whether verification is enabled by default. 429 */ 430 private static final boolean DEFAULT_VERIFY_ENABLE = true; 431 432 /** 433 * The default maximum time to wait for the verification agent to return in 434 * milliseconds. 435 */ 436 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 437 438 /** 439 * The default response for package verification timeout. 440 * 441 * This can be either PackageManager.VERIFICATION_ALLOW or 442 * PackageManager.VERIFICATION_REJECT. 443 */ 444 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 445 446 static final String PLATFORM_PACKAGE_NAME = "android"; 447 448 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 449 450 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 451 DEFAULT_CONTAINER_PACKAGE, 452 "com.android.defcontainer.DefaultContainerService"); 453 454 private static final String KILL_APP_REASON_GIDS_CHANGED = 455 "permission grant or revoke changed gids"; 456 457 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 458 "permissions revoked"; 459 460 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 461 462 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 463 464 /** Permission grant: not grant the permission. */ 465 private static final int GRANT_DENIED = 1; 466 467 /** Permission grant: grant the permission as an install permission. */ 468 private static final int GRANT_INSTALL = 2; 469 470 /** Permission grant: grant the permission as a runtime one. */ 471 private static final int GRANT_RUNTIME = 3; 472 473 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 474 private static final int GRANT_UPGRADE = 4; 475 476 /** Canonical intent used to identify what counts as a "web browser" app */ 477 private static final Intent sBrowserIntent; 478 static { 479 sBrowserIntent = new Intent(); 480 sBrowserIntent.setAction(Intent.ACTION_VIEW); 481 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 482 sBrowserIntent.setData(Uri.parse("http:")); 483 } 484 485 /** 486 * The set of all protected actions [i.e. those actions for which a high priority 487 * intent filter is disallowed]. 488 */ 489 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 490 static { 491 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 493 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 494 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 495 } 496 497 // Compilation reasons. 498 public static final int REASON_FIRST_BOOT = 0; 499 public static final int REASON_BOOT = 1; 500 public static final int REASON_INSTALL = 2; 501 public static final int REASON_BACKGROUND_DEXOPT = 3; 502 public static final int REASON_AB_OTA = 4; 503 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 504 public static final int REASON_SHARED_APK = 6; 505 public static final int REASON_FORCED_DEXOPT = 7; 506 507 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 508 509 /** Special library name that skips shared libraries check during compilation. */ 510 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 511 512 final ServiceThread mHandlerThread; 513 514 final PackageHandler mHandler; 515 516 private final ProcessLoggingHandler mProcessLoggingHandler; 517 518 /** 519 * Messages for {@link #mHandler} that need to wait for system ready before 520 * being dispatched. 521 */ 522 private ArrayList<Message> mPostSystemReadyMessages; 523 524 final int mSdkVersion = Build.VERSION.SDK_INT; 525 526 final Context mContext; 527 final boolean mFactoryTest; 528 final boolean mOnlyCore; 529 final DisplayMetrics mMetrics; 530 final int mDefParseFlags; 531 final String[] mSeparateProcesses; 532 final boolean mIsUpgrade; 533 final boolean mIsPreNUpgrade; 534 535 /** The location for ASEC container files on internal storage. */ 536 final String mAsecInternalPath; 537 538 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 539 // LOCK HELD. Can be called with mInstallLock held. 540 @GuardedBy("mInstallLock") 541 final Installer mInstaller; 542 543 /** Directory where installed third-party apps stored */ 544 final File mAppInstallDir; 545 final File mEphemeralInstallDir; 546 547 /** 548 * Directory to which applications installed internally have their 549 * 32 bit native libraries copied. 550 */ 551 private File mAppLib32InstallDir; 552 553 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 554 // apps. 555 final File mDrmAppPrivateInstallDir; 556 557 // ---------------------------------------------------------------- 558 559 // Lock for state used when installing and doing other long running 560 // operations. Methods that must be called with this lock held have 561 // the suffix "LI". 562 final Object mInstallLock = new Object(); 563 564 // ---------------------------------------------------------------- 565 566 // Keys are String (package name), values are Package. This also serves 567 // as the lock for the global state. Methods that must be called with 568 // this lock held have the prefix "LP". 569 @GuardedBy("mPackages") 570 final ArrayMap<String, PackageParser.Package> mPackages = 571 new ArrayMap<String, PackageParser.Package>(); 572 573 final ArrayMap<String, Set<String>> mKnownCodebase = 574 new ArrayMap<String, Set<String>>(); 575 576 // Tracks available target package names -> overlay package paths. 577 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 578 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 579 580 /** 581 * Tracks new system packages [received in an OTA] that we expect to 582 * find updated user-installed versions. Keys are package name, values 583 * are package location. 584 */ 585 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 586 /** 587 * Tracks high priority intent filters for protected actions. During boot, certain 588 * filter actions are protected and should never be allowed to have a high priority 589 * intent filter for them. However, there is one, and only one exception -- the 590 * setup wizard. It must be able to define a high priority intent filter for these 591 * actions to ensure there are no escapes from the wizard. We need to delay processing 592 * of these during boot as we need to look at all of the system packages in order 593 * to know which component is the setup wizard. 594 */ 595 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 596 /** 597 * Whether or not processing protected filters should be deferred. 598 */ 599 private boolean mDeferProtectedFilters = true; 600 601 /** 602 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 603 */ 604 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 605 /** 606 * Whether or not system app permissions should be promoted from install to runtime. 607 */ 608 boolean mPromoteSystemApps; 609 610 @GuardedBy("mPackages") 611 final Settings mSettings; 612 613 /** 614 * Set of package names that are currently "frozen", which means active 615 * surgery is being done on the code/data for that package. The platform 616 * will refuse to launch frozen packages to avoid race conditions. 617 * 618 * @see PackageFreezer 619 */ 620 @GuardedBy("mPackages") 621 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 622 623 boolean mRestoredSettings; 624 625 // System configuration read by SystemConfig. 626 final int[] mGlobalGids; 627 final SparseArray<ArraySet<String>> mSystemPermissions; 628 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 629 630 // If mac_permissions.xml was found for seinfo labeling. 631 boolean mFoundPolicyFile; 632 633 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 634 635 public static final class SharedLibraryEntry { 636 public final String path; 637 public final String apk; 638 639 SharedLibraryEntry(String _path, String _apk) { 640 path = _path; 641 apk = _apk; 642 } 643 } 644 645 // Currently known shared libraries. 646 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 647 new ArrayMap<String, SharedLibraryEntry>(); 648 649 // All available activities, for your resolving pleasure. 650 final ActivityIntentResolver mActivities = 651 new ActivityIntentResolver(); 652 653 // All available receivers, for your resolving pleasure. 654 final ActivityIntentResolver mReceivers = 655 new ActivityIntentResolver(); 656 657 // All available services, for your resolving pleasure. 658 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 659 660 // All available providers, for your resolving pleasure. 661 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 662 663 // Mapping from provider base names (first directory in content URI codePath) 664 // to the provider information. 665 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 666 new ArrayMap<String, PackageParser.Provider>(); 667 668 // Mapping from instrumentation class names to info about them. 669 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 670 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 671 672 // Mapping from permission names to info about them. 673 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 674 new ArrayMap<String, PackageParser.PermissionGroup>(); 675 676 // Packages whose data we have transfered into another package, thus 677 // should no longer exist. 678 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 679 680 // Broadcast actions that are only available to the system. 681 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 682 683 /** List of packages waiting for verification. */ 684 final SparseArray<PackageVerificationState> mPendingVerification 685 = new SparseArray<PackageVerificationState>(); 686 687 /** Set of packages associated with each app op permission. */ 688 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 689 690 final PackageInstallerService mInstallerService; 691 692 private final PackageDexOptimizer mPackageDexOptimizer; 693 694 private AtomicInteger mNextMoveId = new AtomicInteger(); 695 private final MoveCallbacks mMoveCallbacks; 696 697 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 698 699 // Cache of users who need badging. 700 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 701 702 /** Token for keys in mPendingVerification. */ 703 private int mPendingVerificationToken = 0; 704 705 volatile boolean mSystemReady; 706 volatile boolean mSafeMode; 707 volatile boolean mHasSystemUidErrors; 708 709 ApplicationInfo mAndroidApplication; 710 final ActivityInfo mResolveActivity = new ActivityInfo(); 711 final ResolveInfo mResolveInfo = new ResolveInfo(); 712 ComponentName mResolveComponentName; 713 PackageParser.Package mPlatformPackage; 714 ComponentName mCustomResolverComponentName; 715 716 boolean mResolverReplaced = false; 717 718 private final @Nullable ComponentName mIntentFilterVerifierComponent; 719 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 720 721 private int mIntentFilterVerificationToken = 0; 722 723 /** Component that knows whether or not an ephemeral application exists */ 724 final ComponentName mEphemeralResolverComponent; 725 /** The service connection to the ephemeral resolver */ 726 final EphemeralResolverConnection mEphemeralResolverConnection; 727 728 /** Component used to install ephemeral applications */ 729 final ComponentName mEphemeralInstallerComponent; 730 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 731 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 732 733 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 734 = new SparseArray<IntentFilterVerificationState>(); 735 736 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 737 new DefaultPermissionGrantPolicy(this); 738 739 // List of packages names to keep cached, even if they are uninstalled for all users 740 private List<String> mKeepUninstalledPackages; 741 742 private UserManagerInternal mUserManagerInternal; 743 744 private static class IFVerificationParams { 745 PackageParser.Package pkg; 746 boolean replacing; 747 int userId; 748 int verifierUid; 749 750 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 751 int _userId, int _verifierUid) { 752 pkg = _pkg; 753 replacing = _replacing; 754 userId = _userId; 755 replacing = _replacing; 756 verifierUid = _verifierUid; 757 } 758 } 759 760 private interface IntentFilterVerifier<T extends IntentFilter> { 761 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 762 T filter, String packageName); 763 void startVerifications(int userId); 764 void receiveVerificationResponse(int verificationId); 765 } 766 767 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 768 private Context mContext; 769 private ComponentName mIntentFilterVerifierComponent; 770 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 771 772 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 773 mContext = context; 774 mIntentFilterVerifierComponent = verifierComponent; 775 } 776 777 private String getDefaultScheme() { 778 return IntentFilter.SCHEME_HTTPS; 779 } 780 781 @Override 782 public void startVerifications(int userId) { 783 // Launch verifications requests 784 int count = mCurrentIntentFilterVerifications.size(); 785 for (int n=0; n<count; n++) { 786 int verificationId = mCurrentIntentFilterVerifications.get(n); 787 final IntentFilterVerificationState ivs = 788 mIntentFilterVerificationStates.get(verificationId); 789 790 String packageName = ivs.getPackageName(); 791 792 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 793 final int filterCount = filters.size(); 794 ArraySet<String> domainsSet = new ArraySet<>(); 795 for (int m=0; m<filterCount; m++) { 796 PackageParser.ActivityIntentInfo filter = filters.get(m); 797 domainsSet.addAll(filter.getHostsList()); 798 } 799 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 800 synchronized (mPackages) { 801 if (mSettings.createIntentFilterVerificationIfNeededLPw( 802 packageName, domainsList) != null) { 803 scheduleWriteSettingsLocked(); 804 } 805 } 806 sendVerificationRequest(userId, verificationId, ivs); 807 } 808 mCurrentIntentFilterVerifications.clear(); 809 } 810 811 private void sendVerificationRequest(int userId, int verificationId, 812 IntentFilterVerificationState ivs) { 813 814 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 815 verificationIntent.putExtra( 816 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 817 verificationId); 818 verificationIntent.putExtra( 819 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 820 getDefaultScheme()); 821 verificationIntent.putExtra( 822 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 823 ivs.getHostsString()); 824 verificationIntent.putExtra( 825 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 826 ivs.getPackageName()); 827 verificationIntent.setComponent(mIntentFilterVerifierComponent); 828 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 829 830 UserHandle user = new UserHandle(userId); 831 mContext.sendBroadcastAsUser(verificationIntent, user); 832 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 833 "Sending IntentFilter verification broadcast"); 834 } 835 836 public void receiveVerificationResponse(int verificationId) { 837 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 838 839 final boolean verified = ivs.isVerified(); 840 841 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 842 final int count = filters.size(); 843 if (DEBUG_DOMAIN_VERIFICATION) { 844 Slog.i(TAG, "Received verification response " + verificationId 845 + " for " + count + " filters, verified=" + verified); 846 } 847 for (int n=0; n<count; n++) { 848 PackageParser.ActivityIntentInfo filter = filters.get(n); 849 filter.setVerified(verified); 850 851 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 852 + " verified with result:" + verified + " and hosts:" 853 + ivs.getHostsString()); 854 } 855 856 mIntentFilterVerificationStates.remove(verificationId); 857 858 final String packageName = ivs.getPackageName(); 859 IntentFilterVerificationInfo ivi = null; 860 861 synchronized (mPackages) { 862 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 863 } 864 if (ivi == null) { 865 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 866 + verificationId + " packageName:" + packageName); 867 return; 868 } 869 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 870 "Updating IntentFilterVerificationInfo for package " + packageName 871 +" verificationId:" + verificationId); 872 873 synchronized (mPackages) { 874 if (verified) { 875 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 876 } else { 877 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 878 } 879 scheduleWriteSettingsLocked(); 880 881 final int userId = ivs.getUserId(); 882 if (userId != UserHandle.USER_ALL) { 883 final int userStatus = 884 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 885 886 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 887 boolean needUpdate = false; 888 889 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 890 // already been set by the User thru the Disambiguation dialog 891 switch (userStatus) { 892 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 893 if (verified) { 894 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 895 } else { 896 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 897 } 898 needUpdate = true; 899 break; 900 901 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 902 if (verified) { 903 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 904 needUpdate = true; 905 } 906 break; 907 908 default: 909 // Nothing to do 910 } 911 912 if (needUpdate) { 913 mSettings.updateIntentFilterVerificationStatusLPw( 914 packageName, updatedStatus, userId); 915 scheduleWritePackageRestrictionsLocked(userId); 916 } 917 } 918 } 919 } 920 921 @Override 922 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 923 ActivityIntentInfo filter, String packageName) { 924 if (!hasValidDomains(filter)) { 925 return false; 926 } 927 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 928 if (ivs == null) { 929 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 930 packageName); 931 } 932 if (DEBUG_DOMAIN_VERIFICATION) { 933 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 934 } 935 ivs.addFilter(filter); 936 return true; 937 } 938 939 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 940 int userId, int verificationId, String packageName) { 941 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 942 verifierUid, userId, packageName); 943 ivs.setPendingState(); 944 synchronized (mPackages) { 945 mIntentFilterVerificationStates.append(verificationId, ivs); 946 mCurrentIntentFilterVerifications.add(verificationId); 947 } 948 return ivs; 949 } 950 } 951 952 private static boolean hasValidDomains(ActivityIntentInfo filter) { 953 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 954 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 955 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 956 } 957 958 // Set of pending broadcasts for aggregating enable/disable of components. 959 static class PendingPackageBroadcasts { 960 // for each user id, a map of <package name -> components within that package> 961 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 962 963 public PendingPackageBroadcasts() { 964 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 965 } 966 967 public ArrayList<String> get(int userId, String packageName) { 968 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 969 return packages.get(packageName); 970 } 971 972 public void put(int userId, String packageName, ArrayList<String> components) { 973 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 974 packages.put(packageName, components); 975 } 976 977 public void remove(int userId, String packageName) { 978 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 979 if (packages != null) { 980 packages.remove(packageName); 981 } 982 } 983 984 public void remove(int userId) { 985 mUidMap.remove(userId); 986 } 987 988 public int userIdCount() { 989 return mUidMap.size(); 990 } 991 992 public int userIdAt(int n) { 993 return mUidMap.keyAt(n); 994 } 995 996 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 997 return mUidMap.get(userId); 998 } 999 1000 public int size() { 1001 // total number of pending broadcast entries across all userIds 1002 int num = 0; 1003 for (int i = 0; i< mUidMap.size(); i++) { 1004 num += mUidMap.valueAt(i).size(); 1005 } 1006 return num; 1007 } 1008 1009 public void clear() { 1010 mUidMap.clear(); 1011 } 1012 1013 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1014 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1015 if (map == null) { 1016 map = new ArrayMap<String, ArrayList<String>>(); 1017 mUidMap.put(userId, map); 1018 } 1019 return map; 1020 } 1021 } 1022 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1023 1024 // Service Connection to remote media container service to copy 1025 // package uri's from external media onto secure containers 1026 // or internal storage. 1027 private IMediaContainerService mContainerService = null; 1028 1029 static final int SEND_PENDING_BROADCAST = 1; 1030 static final int MCS_BOUND = 3; 1031 static final int END_COPY = 4; 1032 static final int INIT_COPY = 5; 1033 static final int MCS_UNBIND = 6; 1034 static final int START_CLEANING_PACKAGE = 7; 1035 static final int FIND_INSTALL_LOC = 8; 1036 static final int POST_INSTALL = 9; 1037 static final int MCS_RECONNECT = 10; 1038 static final int MCS_GIVE_UP = 11; 1039 static final int UPDATED_MEDIA_STATUS = 12; 1040 static final int WRITE_SETTINGS = 13; 1041 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1042 static final int PACKAGE_VERIFIED = 15; 1043 static final int CHECK_PENDING_VERIFICATION = 16; 1044 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1045 static final int INTENT_FILTER_VERIFIED = 18; 1046 1047 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1048 1049 // Delay time in millisecs 1050 static final int BROADCAST_DELAY = 10 * 1000; 1051 1052 static UserManagerService sUserManager; 1053 1054 // Stores a list of users whose package restrictions file needs to be updated 1055 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1056 1057 final private DefaultContainerConnection mDefContainerConn = 1058 new DefaultContainerConnection(); 1059 class DefaultContainerConnection implements ServiceConnection { 1060 public void onServiceConnected(ComponentName name, IBinder service) { 1061 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1062 IMediaContainerService imcs = 1063 IMediaContainerService.Stub.asInterface(service); 1064 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1065 } 1066 1067 public void onServiceDisconnected(ComponentName name) { 1068 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1069 } 1070 } 1071 1072 // Recordkeeping of restore-after-install operations that are currently in flight 1073 // between the Package Manager and the Backup Manager 1074 static class PostInstallData { 1075 public InstallArgs args; 1076 public PackageInstalledInfo res; 1077 1078 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1079 args = _a; 1080 res = _r; 1081 } 1082 } 1083 1084 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1085 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1086 1087 // XML tags for backup/restore of various bits of state 1088 private static final String TAG_PREFERRED_BACKUP = "pa"; 1089 private static final String TAG_DEFAULT_APPS = "da"; 1090 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1091 1092 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1093 private static final String TAG_ALL_GRANTS = "rt-grants"; 1094 private static final String TAG_GRANT = "grant"; 1095 private static final String ATTR_PACKAGE_NAME = "pkg"; 1096 1097 private static final String TAG_PERMISSION = "perm"; 1098 private static final String ATTR_PERMISSION_NAME = "name"; 1099 private static final String ATTR_IS_GRANTED = "g"; 1100 private static final String ATTR_USER_SET = "set"; 1101 private static final String ATTR_USER_FIXED = "fixed"; 1102 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1103 1104 // System/policy permission grants are not backed up 1105 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1106 FLAG_PERMISSION_POLICY_FIXED 1107 | FLAG_PERMISSION_SYSTEM_FIXED 1108 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1109 1110 // And we back up these user-adjusted states 1111 private static final int USER_RUNTIME_GRANT_MASK = 1112 FLAG_PERMISSION_USER_SET 1113 | FLAG_PERMISSION_USER_FIXED 1114 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1115 1116 final @Nullable String mRequiredVerifierPackage; 1117 final @NonNull String mRequiredInstallerPackage; 1118 final @Nullable String mSetupWizardPackage; 1119 final @NonNull String mServicesSystemSharedLibraryPackageName; 1120 final @NonNull String mSharedSystemSharedLibraryPackageName; 1121 1122 private final PackageUsage mPackageUsage = new PackageUsage(); 1123 1124 private class PackageUsage { 1125 private static final int WRITE_INTERVAL 1126 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1127 1128 private final Object mFileLock = new Object(); 1129 private final AtomicLong mLastWritten = new AtomicLong(0); 1130 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1131 1132 private boolean mIsHistoricalPackageUsageAvailable = true; 1133 1134 boolean isHistoricalPackageUsageAvailable() { 1135 return mIsHistoricalPackageUsageAvailable; 1136 } 1137 1138 void write(boolean force) { 1139 if (force) { 1140 writeInternal(); 1141 return; 1142 } 1143 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1144 && !DEBUG_DEXOPT) { 1145 return; 1146 } 1147 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1148 new Thread("PackageUsage_DiskWriter") { 1149 @Override 1150 public void run() { 1151 try { 1152 writeInternal(); 1153 } finally { 1154 mBackgroundWriteRunning.set(false); 1155 } 1156 } 1157 }.start(); 1158 } 1159 } 1160 1161 private void writeInternal() { 1162 synchronized (mPackages) { 1163 synchronized (mFileLock) { 1164 AtomicFile file = getFile(); 1165 FileOutputStream f = null; 1166 try { 1167 f = file.startWrite(); 1168 BufferedOutputStream out = new BufferedOutputStream(f); 1169 FileUtils.setPermissions(file.getBaseFile().getPath(), 1170 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1171 StringBuilder sb = new StringBuilder(); 1172 1173 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 1177 for (PackageParser.Package pkg : mPackages.values()) { 1178 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1179 continue; 1180 } 1181 sb.setLength(0); 1182 sb.append(pkg.packageName); 1183 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1184 sb.append(' '); 1185 sb.append(usageTimeInMillis); 1186 } 1187 sb.append('\n'); 1188 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1189 } 1190 out.flush(); 1191 file.finishWrite(f); 1192 } catch (IOException e) { 1193 if (f != null) { 1194 file.failWrite(f); 1195 } 1196 Log.e(TAG, "Failed to write package usage times", e); 1197 } 1198 } 1199 } 1200 mLastWritten.set(SystemClock.elapsedRealtime()); 1201 } 1202 1203 void readLP() { 1204 synchronized (mFileLock) { 1205 AtomicFile file = getFile(); 1206 BufferedInputStream in = null; 1207 try { 1208 in = new BufferedInputStream(file.openRead()); 1209 StringBuffer sb = new StringBuffer(); 1210 1211 String firstLine = readLine(in, sb); 1212 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1213 readVersion1LP(in, sb); 1214 } else { 1215 readVersion0LP(in, sb, firstLine); 1216 } 1217 } catch (FileNotFoundException expected) { 1218 mIsHistoricalPackageUsageAvailable = false; 1219 } catch (IOException e) { 1220 Log.w(TAG, "Failed to read package usage times", e); 1221 } finally { 1222 IoUtils.closeQuietly(in); 1223 } 1224 } 1225 mLastWritten.set(SystemClock.elapsedRealtime()); 1226 } 1227 1228 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1229 throws IOException { 1230 // Initial version of the file had no version number and stored one 1231 // package-timestamp pair per line. 1232 // Note that the first line has already been read from the InputStream. 1233 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1234 String[] tokens = line.split(" "); 1235 if (tokens.length != 2) { 1236 throw new IOException("Failed to parse " + line + 1237 " as package-timestamp pair."); 1238 } 1239 1240 String packageName = tokens[0]; 1241 PackageParser.Package pkg = mPackages.get(packageName); 1242 if (pkg == null) { 1243 continue; 1244 } 1245 1246 long timestamp = parseAsLong(tokens[1]); 1247 for (int reason = 0; 1248 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1249 reason++) { 1250 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1251 } 1252 } 1253 } 1254 1255 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1256 // Version 1 of the file started with the corresponding version 1257 // number and then stored a package name and eight timestamps per line. 1258 String line; 1259 while ((line = readLine(in, sb)) != null) { 1260 String[] tokens = line.split(" "); 1261 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1262 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1263 } 1264 1265 String packageName = tokens[0]; 1266 PackageParser.Package pkg = mPackages.get(packageName); 1267 if (pkg == null) { 1268 continue; 1269 } 1270 1271 for (int reason = 0; 1272 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1273 reason++) { 1274 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1275 } 1276 } 1277 } 1278 1279 private long parseAsLong(String token) throws IOException { 1280 try { 1281 return Long.parseLong(token); 1282 } catch (NumberFormatException e) { 1283 throw new IOException("Failed to parse " + token + " as a long.", e); 1284 } 1285 } 1286 1287 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1288 return readToken(in, sb, '\n'); 1289 } 1290 1291 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1292 throws IOException { 1293 sb.setLength(0); 1294 while (true) { 1295 int ch = in.read(); 1296 if (ch == -1) { 1297 if (sb.length() == 0) { 1298 return null; 1299 } 1300 throw new IOException("Unexpected EOF"); 1301 } 1302 if (ch == endOfToken) { 1303 return sb.toString(); 1304 } 1305 sb.append((char)ch); 1306 } 1307 } 1308 1309 private AtomicFile getFile() { 1310 File dataDir = Environment.getDataDirectory(); 1311 File systemDir = new File(dataDir, "system"); 1312 File fname = new File(systemDir, "package-usage.list"); 1313 return new AtomicFile(fname); 1314 } 1315 1316 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1317 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1318 } 1319 1320 class PackageHandler extends Handler { 1321 private boolean mBound = false; 1322 final ArrayList<HandlerParams> mPendingInstalls = 1323 new ArrayList<HandlerParams>(); 1324 1325 private boolean connectToService() { 1326 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1327 " DefaultContainerService"); 1328 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1330 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1331 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1332 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1333 mBound = true; 1334 return true; 1335 } 1336 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1337 return false; 1338 } 1339 1340 private void disconnectService() { 1341 mContainerService = null; 1342 mBound = false; 1343 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1344 mContext.unbindService(mDefContainerConn); 1345 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1346 } 1347 1348 PackageHandler(Looper looper) { 1349 super(looper); 1350 } 1351 1352 public void handleMessage(Message msg) { 1353 try { 1354 doHandleMessage(msg); 1355 } finally { 1356 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1357 } 1358 } 1359 1360 void doHandleMessage(Message msg) { 1361 switch (msg.what) { 1362 case INIT_COPY: { 1363 HandlerParams params = (HandlerParams) msg.obj; 1364 int idx = mPendingInstalls.size(); 1365 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1366 // If a bind was already initiated we dont really 1367 // need to do anything. The pending install 1368 // will be processed later on. 1369 if (!mBound) { 1370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1371 System.identityHashCode(mHandler)); 1372 // If this is the only one pending we might 1373 // have to bind to the service again. 1374 if (!connectToService()) { 1375 Slog.e(TAG, "Failed to bind to media container service"); 1376 params.serviceError(); 1377 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1378 System.identityHashCode(mHandler)); 1379 if (params.traceMethod != null) { 1380 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1381 params.traceCookie); 1382 } 1383 return; 1384 } else { 1385 // Once we bind to the service, the first 1386 // pending request will be processed. 1387 mPendingInstalls.add(idx, params); 1388 } 1389 } else { 1390 mPendingInstalls.add(idx, params); 1391 // Already bound to the service. Just make 1392 // sure we trigger off processing the first request. 1393 if (idx == 0) { 1394 mHandler.sendEmptyMessage(MCS_BOUND); 1395 } 1396 } 1397 break; 1398 } 1399 case MCS_BOUND: { 1400 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1401 if (msg.obj != null) { 1402 mContainerService = (IMediaContainerService) msg.obj; 1403 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1404 System.identityHashCode(mHandler)); 1405 } 1406 if (mContainerService == null) { 1407 if (!mBound) { 1408 // Something seriously wrong since we are not bound and we are not 1409 // waiting for connection. Bail out. 1410 Slog.e(TAG, "Cannot bind to media container service"); 1411 for (HandlerParams params : mPendingInstalls) { 1412 // Indicate service bind error 1413 params.serviceError(); 1414 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1415 System.identityHashCode(params)); 1416 if (params.traceMethod != null) { 1417 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1418 params.traceMethod, params.traceCookie); 1419 } 1420 return; 1421 } 1422 mPendingInstalls.clear(); 1423 } else { 1424 Slog.w(TAG, "Waiting to connect to media container service"); 1425 } 1426 } else if (mPendingInstalls.size() > 0) { 1427 HandlerParams params = mPendingInstalls.get(0); 1428 if (params != null) { 1429 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1430 System.identityHashCode(params)); 1431 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1432 if (params.startCopy()) { 1433 // We are done... look for more work or to 1434 // go idle. 1435 if (DEBUG_SD_INSTALL) Log.i(TAG, 1436 "Checking for more work or unbind..."); 1437 // Delete pending install 1438 if (mPendingInstalls.size() > 0) { 1439 mPendingInstalls.remove(0); 1440 } 1441 if (mPendingInstalls.size() == 0) { 1442 if (mBound) { 1443 if (DEBUG_SD_INSTALL) Log.i(TAG, 1444 "Posting delayed MCS_UNBIND"); 1445 removeMessages(MCS_UNBIND); 1446 Message ubmsg = obtainMessage(MCS_UNBIND); 1447 // Unbind after a little delay, to avoid 1448 // continual thrashing. 1449 sendMessageDelayed(ubmsg, 10000); 1450 } 1451 } else { 1452 // There are more pending requests in queue. 1453 // Just post MCS_BOUND message to trigger processing 1454 // of next pending install. 1455 if (DEBUG_SD_INSTALL) Log.i(TAG, 1456 "Posting MCS_BOUND for next work"); 1457 mHandler.sendEmptyMessage(MCS_BOUND); 1458 } 1459 } 1460 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1461 } 1462 } else { 1463 // Should never happen ideally. 1464 Slog.w(TAG, "Empty queue"); 1465 } 1466 break; 1467 } 1468 case MCS_RECONNECT: { 1469 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1470 if (mPendingInstalls.size() > 0) { 1471 if (mBound) { 1472 disconnectService(); 1473 } 1474 if (!connectToService()) { 1475 Slog.e(TAG, "Failed to bind to media container service"); 1476 for (HandlerParams params : mPendingInstalls) { 1477 // Indicate service bind error 1478 params.serviceError(); 1479 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1480 System.identityHashCode(params)); 1481 } 1482 mPendingInstalls.clear(); 1483 } 1484 } 1485 break; 1486 } 1487 case MCS_UNBIND: { 1488 // If there is no actual work left, then time to unbind. 1489 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1490 1491 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1492 if (mBound) { 1493 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1494 1495 disconnectService(); 1496 } 1497 } else if (mPendingInstalls.size() > 0) { 1498 // There are more pending requests in queue. 1499 // Just post MCS_BOUND message to trigger processing 1500 // of next pending install. 1501 mHandler.sendEmptyMessage(MCS_BOUND); 1502 } 1503 1504 break; 1505 } 1506 case MCS_GIVE_UP: { 1507 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1508 HandlerParams params = mPendingInstalls.remove(0); 1509 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1510 System.identityHashCode(params)); 1511 break; 1512 } 1513 case SEND_PENDING_BROADCAST: { 1514 String packages[]; 1515 ArrayList<String> components[]; 1516 int size = 0; 1517 int uids[]; 1518 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1519 synchronized (mPackages) { 1520 if (mPendingBroadcasts == null) { 1521 return; 1522 } 1523 size = mPendingBroadcasts.size(); 1524 if (size <= 0) { 1525 // Nothing to be done. Just return 1526 return; 1527 } 1528 packages = new String[size]; 1529 components = new ArrayList[size]; 1530 uids = new int[size]; 1531 int i = 0; // filling out the above arrays 1532 1533 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1534 int packageUserId = mPendingBroadcasts.userIdAt(n); 1535 Iterator<Map.Entry<String, ArrayList<String>>> it 1536 = mPendingBroadcasts.packagesForUserId(packageUserId) 1537 .entrySet().iterator(); 1538 while (it.hasNext() && i < size) { 1539 Map.Entry<String, ArrayList<String>> ent = it.next(); 1540 packages[i] = ent.getKey(); 1541 components[i] = ent.getValue(); 1542 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1543 uids[i] = (ps != null) 1544 ? UserHandle.getUid(packageUserId, ps.appId) 1545 : -1; 1546 i++; 1547 } 1548 } 1549 size = i; 1550 mPendingBroadcasts.clear(); 1551 } 1552 // Send broadcasts 1553 for (int i = 0; i < size; i++) { 1554 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1555 } 1556 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1557 break; 1558 } 1559 case START_CLEANING_PACKAGE: { 1560 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1561 final String packageName = (String)msg.obj; 1562 final int userId = msg.arg1; 1563 final boolean andCode = msg.arg2 != 0; 1564 synchronized (mPackages) { 1565 if (userId == UserHandle.USER_ALL) { 1566 int[] users = sUserManager.getUserIds(); 1567 for (int user : users) { 1568 mSettings.addPackageToCleanLPw( 1569 new PackageCleanItem(user, packageName, andCode)); 1570 } 1571 } else { 1572 mSettings.addPackageToCleanLPw( 1573 new PackageCleanItem(userId, packageName, andCode)); 1574 } 1575 } 1576 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1577 startCleaningPackages(); 1578 } break; 1579 case POST_INSTALL: { 1580 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1581 1582 PostInstallData data = mRunningInstalls.get(msg.arg1); 1583 final boolean didRestore = (msg.arg2 != 0); 1584 mRunningInstalls.delete(msg.arg1); 1585 1586 if (data != null) { 1587 InstallArgs args = data.args; 1588 PackageInstalledInfo parentRes = data.res; 1589 1590 final boolean grantPermissions = (args.installFlags 1591 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1592 final boolean killApp = (args.installFlags 1593 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1594 final String[] grantedPermissions = args.installGrantPermissions; 1595 1596 // Handle the parent package 1597 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1598 grantedPermissions, didRestore, args.installerPackageName, 1599 args.observer); 1600 1601 // Handle the child packages 1602 final int childCount = (parentRes.addedChildPackages != null) 1603 ? parentRes.addedChildPackages.size() : 0; 1604 for (int i = 0; i < childCount; i++) { 1605 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1606 handlePackagePostInstall(childRes, grantPermissions, killApp, 1607 grantedPermissions, false, args.installerPackageName, 1608 args.observer); 1609 } 1610 1611 // Log tracing if needed 1612 if (args.traceMethod != null) { 1613 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1614 args.traceCookie); 1615 } 1616 } else { 1617 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1618 } 1619 1620 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1621 } break; 1622 case UPDATED_MEDIA_STATUS: { 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1624 boolean reportStatus = msg.arg1 == 1; 1625 boolean doGc = msg.arg2 == 1; 1626 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1627 if (doGc) { 1628 // Force a gc to clear up stale containers. 1629 Runtime.getRuntime().gc(); 1630 } 1631 if (msg.obj != null) { 1632 @SuppressWarnings("unchecked") 1633 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1634 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1635 // Unload containers 1636 unloadAllContainers(args); 1637 } 1638 if (reportStatus) { 1639 try { 1640 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1641 PackageHelper.getMountService().finishMediaUpdate(); 1642 } catch (RemoteException e) { 1643 Log.e(TAG, "MountService not running?"); 1644 } 1645 } 1646 } break; 1647 case WRITE_SETTINGS: { 1648 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1649 synchronized (mPackages) { 1650 removeMessages(WRITE_SETTINGS); 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 mSettings.writeLPr(); 1653 mDirtyUsers.clear(); 1654 } 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1656 } break; 1657 case WRITE_PACKAGE_RESTRICTIONS: { 1658 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1659 synchronized (mPackages) { 1660 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1661 for (int userId : mDirtyUsers) { 1662 mSettings.writePackageRestrictionsLPr(userId); 1663 } 1664 mDirtyUsers.clear(); 1665 } 1666 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1667 } break; 1668 case CHECK_PENDING_VERIFICATION: { 1669 final int verificationId = msg.arg1; 1670 final PackageVerificationState state = mPendingVerification.get(verificationId); 1671 1672 if ((state != null) && !state.timeoutExtended()) { 1673 final InstallArgs args = state.getInstallArgs(); 1674 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1675 1676 Slog.i(TAG, "Verification timed out for " + originUri); 1677 mPendingVerification.remove(verificationId); 1678 1679 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1680 1681 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1682 Slog.i(TAG, "Continuing with installation of " + originUri); 1683 state.setVerifierResponse(Binder.getCallingUid(), 1684 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1685 broadcastPackageVerified(verificationId, originUri, 1686 PackageManager.VERIFICATION_ALLOW, 1687 state.getInstallArgs().getUser()); 1688 try { 1689 ret = args.copyApk(mContainerService, true); 1690 } catch (RemoteException e) { 1691 Slog.e(TAG, "Could not contact the ContainerService"); 1692 } 1693 } else { 1694 broadcastPackageVerified(verificationId, originUri, 1695 PackageManager.VERIFICATION_REJECT, 1696 state.getInstallArgs().getUser()); 1697 } 1698 1699 Trace.asyncTraceEnd( 1700 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1701 1702 processPendingInstall(args, ret); 1703 mHandler.sendEmptyMessage(MCS_UNBIND); 1704 } 1705 break; 1706 } 1707 case PACKAGE_VERIFIED: { 1708 final int verificationId = msg.arg1; 1709 1710 final PackageVerificationState state = mPendingVerification.get(verificationId); 1711 if (state == null) { 1712 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1713 break; 1714 } 1715 1716 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1717 1718 state.setVerifierResponse(response.callerUid, response.code); 1719 1720 if (state.isVerificationComplete()) { 1721 mPendingVerification.remove(verificationId); 1722 1723 final InstallArgs args = state.getInstallArgs(); 1724 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1725 1726 int ret; 1727 if (state.isInstallAllowed()) { 1728 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1729 broadcastPackageVerified(verificationId, originUri, 1730 response.code, state.getInstallArgs().getUser()); 1731 try { 1732 ret = args.copyApk(mContainerService, true); 1733 } catch (RemoteException e) { 1734 Slog.e(TAG, "Could not contact the ContainerService"); 1735 } 1736 } else { 1737 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1738 } 1739 1740 Trace.asyncTraceEnd( 1741 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1742 1743 processPendingInstall(args, ret); 1744 mHandler.sendEmptyMessage(MCS_UNBIND); 1745 } 1746 1747 break; 1748 } 1749 case START_INTENT_FILTER_VERIFICATIONS: { 1750 IFVerificationParams params = (IFVerificationParams) msg.obj; 1751 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1752 params.replacing, params.pkg); 1753 break; 1754 } 1755 case INTENT_FILTER_VERIFIED: { 1756 final int verificationId = msg.arg1; 1757 1758 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1759 verificationId); 1760 if (state == null) { 1761 Slog.w(TAG, "Invalid IntentFilter verification token " 1762 + verificationId + " received"); 1763 break; 1764 } 1765 1766 final int userId = state.getUserId(); 1767 1768 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1769 "Processing IntentFilter verification with token:" 1770 + verificationId + " and userId:" + userId); 1771 1772 final IntentFilterVerificationResponse response = 1773 (IntentFilterVerificationResponse) msg.obj; 1774 1775 state.setVerifierResponse(response.callerUid, response.code); 1776 1777 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1778 "IntentFilter verification with token:" + verificationId 1779 + " and userId:" + userId 1780 + " is settings verifier response with response code:" 1781 + response.code); 1782 1783 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1784 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1785 + response.getFailedDomainsString()); 1786 } 1787 1788 if (state.isVerificationComplete()) { 1789 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1790 } else { 1791 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1792 "IntentFilter verification with token:" + verificationId 1793 + " was not said to be complete"); 1794 } 1795 1796 break; 1797 } 1798 } 1799 } 1800 } 1801 1802 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1803 boolean killApp, String[] grantedPermissions, 1804 boolean launchedForRestore, String installerPackage, 1805 IPackageInstallObserver2 installObserver) { 1806 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1807 // Send the removed broadcasts 1808 if (res.removedInfo != null) { 1809 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1810 } 1811 1812 // Now that we successfully installed the package, grant runtime 1813 // permissions if requested before broadcasting the install. 1814 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1815 >= Build.VERSION_CODES.M) { 1816 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1817 } 1818 1819 final boolean update = res.removedInfo != null 1820 && res.removedInfo.removedPackage != null; 1821 1822 // If this is the first time we have child packages for a disabled privileged 1823 // app that had no children, we grant requested runtime permissions to the new 1824 // children if the parent on the system image had them already granted. 1825 if (res.pkg.parentPackage != null) { 1826 synchronized (mPackages) { 1827 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1828 } 1829 } 1830 1831 synchronized (mPackages) { 1832 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1833 } 1834 1835 final String packageName = res.pkg.applicationInfo.packageName; 1836 Bundle extras = new Bundle(1); 1837 extras.putInt(Intent.EXTRA_UID, res.uid); 1838 1839 // Determine the set of users who are adding this package for 1840 // the first time vs. those who are seeing an update. 1841 int[] firstUsers = EMPTY_INT_ARRAY; 1842 int[] updateUsers = EMPTY_INT_ARRAY; 1843 if (res.origUsers == null || res.origUsers.length == 0) { 1844 firstUsers = res.newUsers; 1845 } else { 1846 for (int newUser : res.newUsers) { 1847 boolean isNew = true; 1848 for (int origUser : res.origUsers) { 1849 if (origUser == newUser) { 1850 isNew = false; 1851 break; 1852 } 1853 } 1854 if (isNew) { 1855 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1856 } else { 1857 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1858 } 1859 } 1860 } 1861 1862 // Send installed broadcasts if the install/update is not ephemeral 1863 if (!isEphemeral(res.pkg)) { 1864 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1865 1866 // Send added for users that see the package for the first time 1867 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1868 extras, 0 /*flags*/, null /*targetPackage*/, 1869 null /*finishedReceiver*/, firstUsers); 1870 1871 // Send added for users that don't see the package for the first time 1872 if (update) { 1873 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1874 } 1875 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1876 extras, 0 /*flags*/, null /*targetPackage*/, 1877 null /*finishedReceiver*/, updateUsers); 1878 1879 // Send replaced for users that don't see the package for the first time 1880 if (update) { 1881 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1882 packageName, extras, 0 /*flags*/, 1883 null /*targetPackage*/, null /*finishedReceiver*/, 1884 updateUsers); 1885 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1886 null /*package*/, null /*extras*/, 0 /*flags*/, 1887 packageName /*targetPackage*/, 1888 null /*finishedReceiver*/, updateUsers); 1889 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1890 // First-install and we did a restore, so we're responsible for the 1891 // first-launch broadcast. 1892 if (DEBUG_BACKUP) { 1893 Slog.i(TAG, "Post-restore of " + packageName 1894 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1895 } 1896 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1897 } 1898 1899 // Send broadcast package appeared if forward locked/external for all users 1900 // treat asec-hosted packages like removable media on upgrade 1901 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1902 if (DEBUG_INSTALL) { 1903 Slog.i(TAG, "upgrading pkg " + res.pkg 1904 + " is ASEC-hosted -> AVAILABLE"); 1905 } 1906 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1907 ArrayList<String> pkgList = new ArrayList<>(1); 1908 pkgList.add(packageName); 1909 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1910 } 1911 } 1912 1913 // Work that needs to happen on first install within each user 1914 if (firstUsers != null && firstUsers.length > 0) { 1915 synchronized (mPackages) { 1916 for (int userId : firstUsers) { 1917 // If this app is a browser and it's newly-installed for some 1918 // users, clear any default-browser state in those users. The 1919 // app's nature doesn't depend on the user, so we can just check 1920 // its browser nature in any user and generalize. 1921 if (packageIsBrowser(packageName, userId)) { 1922 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1923 } 1924 1925 // We may also need to apply pending (restored) runtime 1926 // permission grants within these users. 1927 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1928 } 1929 } 1930 } 1931 1932 // Log current value of "unknown sources" setting 1933 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1934 getUnknownSourcesSettings()); 1935 1936 // Force a gc to clear up things 1937 Runtime.getRuntime().gc(); 1938 1939 // Remove the replaced package's older resources safely now 1940 // We delete after a gc for applications on sdcard. 1941 if (res.removedInfo != null && res.removedInfo.args != null) { 1942 synchronized (mInstallLock) { 1943 res.removedInfo.args.doPostDeleteLI(true); 1944 } 1945 } 1946 } 1947 1948 // If someone is watching installs - notify them 1949 if (installObserver != null) { 1950 try { 1951 Bundle extras = extrasForInstallResult(res); 1952 installObserver.onPackageInstalled(res.name, res.returnCode, 1953 res.returnMsg, extras); 1954 } catch (RemoteException e) { 1955 Slog.i(TAG, "Observer no longer exists."); 1956 } 1957 } 1958 } 1959 1960 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1961 PackageParser.Package pkg) { 1962 if (pkg.parentPackage == null) { 1963 return; 1964 } 1965 if (pkg.requestedPermissions == null) { 1966 return; 1967 } 1968 final PackageSetting disabledSysParentPs = mSettings 1969 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1970 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1971 || !disabledSysParentPs.isPrivileged() 1972 || (disabledSysParentPs.childPackageNames != null 1973 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1974 return; 1975 } 1976 final int[] allUserIds = sUserManager.getUserIds(); 1977 final int permCount = pkg.requestedPermissions.size(); 1978 for (int i = 0; i < permCount; i++) { 1979 String permission = pkg.requestedPermissions.get(i); 1980 BasePermission bp = mSettings.mPermissions.get(permission); 1981 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1982 continue; 1983 } 1984 for (int userId : allUserIds) { 1985 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1986 permission, userId)) { 1987 grantRuntimePermission(pkg.packageName, permission, userId); 1988 } 1989 } 1990 } 1991 } 1992 1993 private StorageEventListener mStorageListener = new StorageEventListener() { 1994 @Override 1995 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1996 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1997 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1998 final String volumeUuid = vol.getFsUuid(); 1999 2000 // Clean up any users or apps that were removed or recreated 2001 // while this volume was missing 2002 reconcileUsers(volumeUuid); 2003 reconcileApps(volumeUuid); 2004 2005 // Clean up any install sessions that expired or were 2006 // cancelled while this volume was missing 2007 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2008 2009 loadPrivatePackages(vol); 2010 2011 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2012 unloadPrivatePackages(vol); 2013 } 2014 } 2015 2016 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2017 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2018 updateExternalMediaStatus(true, false); 2019 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2020 updateExternalMediaStatus(false, false); 2021 } 2022 } 2023 } 2024 2025 @Override 2026 public void onVolumeForgotten(String fsUuid) { 2027 if (TextUtils.isEmpty(fsUuid)) { 2028 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2029 return; 2030 } 2031 2032 // Remove any apps installed on the forgotten volume 2033 synchronized (mPackages) { 2034 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2035 for (PackageSetting ps : packages) { 2036 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2037 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2038 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2039 } 2040 2041 mSettings.onVolumeForgotten(fsUuid); 2042 mSettings.writeLPr(); 2043 } 2044 } 2045 }; 2046 2047 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2048 String[] grantedPermissions) { 2049 for (int userId : userIds) { 2050 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2051 } 2052 2053 // We could have touched GID membership, so flush out packages.list 2054 synchronized (mPackages) { 2055 mSettings.writePackageListLPr(); 2056 } 2057 } 2058 2059 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2060 String[] grantedPermissions) { 2061 SettingBase sb = (SettingBase) pkg.mExtras; 2062 if (sb == null) { 2063 return; 2064 } 2065 2066 PermissionsState permissionsState = sb.getPermissionsState(); 2067 2068 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2069 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2070 2071 for (String permission : pkg.requestedPermissions) { 2072 final BasePermission bp; 2073 synchronized (mPackages) { 2074 bp = mSettings.mPermissions.get(permission); 2075 } 2076 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2077 && (grantedPermissions == null 2078 || ArrayUtils.contains(grantedPermissions, permission))) { 2079 final int flags = permissionsState.getPermissionFlags(permission, userId); 2080 // Installer cannot change immutable permissions. 2081 if ((flags & immutableFlags) == 0) { 2082 grantRuntimePermission(pkg.packageName, permission, userId); 2083 } 2084 } 2085 } 2086 } 2087 2088 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2089 Bundle extras = null; 2090 switch (res.returnCode) { 2091 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2092 extras = new Bundle(); 2093 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2094 res.origPermission); 2095 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2096 res.origPackage); 2097 break; 2098 } 2099 case PackageManager.INSTALL_SUCCEEDED: { 2100 extras = new Bundle(); 2101 extras.putBoolean(Intent.EXTRA_REPLACING, 2102 res.removedInfo != null && res.removedInfo.removedPackage != null); 2103 break; 2104 } 2105 } 2106 return extras; 2107 } 2108 2109 void scheduleWriteSettingsLocked() { 2110 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2111 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2112 } 2113 } 2114 2115 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2116 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2117 scheduleWritePackageRestrictionsLocked(userId); 2118 } 2119 2120 void scheduleWritePackageRestrictionsLocked(int userId) { 2121 final int[] userIds = (userId == UserHandle.USER_ALL) 2122 ? sUserManager.getUserIds() : new int[]{userId}; 2123 for (int nextUserId : userIds) { 2124 if (!sUserManager.exists(nextUserId)) return; 2125 mDirtyUsers.add(nextUserId); 2126 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2127 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2128 } 2129 } 2130 } 2131 2132 public static PackageManagerService main(Context context, Installer installer, 2133 boolean factoryTest, boolean onlyCore) { 2134 // Self-check for initial settings. 2135 PackageManagerServiceCompilerMapping.checkProperties(); 2136 2137 PackageManagerService m = new PackageManagerService(context, installer, 2138 factoryTest, onlyCore); 2139 m.enableSystemUserPackages(); 2140 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2141 // disabled after already being started. 2142 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2143 UserHandle.USER_SYSTEM); 2144 ServiceManager.addService("package", m); 2145 return m; 2146 } 2147 2148 private void enableSystemUserPackages() { 2149 if (!UserManager.isSplitSystemUser()) { 2150 return; 2151 } 2152 // For system user, enable apps based on the following conditions: 2153 // - app is whitelisted or belong to one of these groups: 2154 // -- system app which has no launcher icons 2155 // -- system app which has INTERACT_ACROSS_USERS permission 2156 // -- system IME app 2157 // - app is not in the blacklist 2158 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2159 Set<String> enableApps = new ArraySet<>(); 2160 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2161 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2162 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2163 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2164 enableApps.addAll(wlApps); 2165 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2166 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2167 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2168 enableApps.removeAll(blApps); 2169 Log.i(TAG, "Applications installed for system user: " + enableApps); 2170 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2171 UserHandle.SYSTEM); 2172 final int allAppsSize = allAps.size(); 2173 synchronized (mPackages) { 2174 for (int i = 0; i < allAppsSize; i++) { 2175 String pName = allAps.get(i); 2176 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2177 // Should not happen, but we shouldn't be failing if it does 2178 if (pkgSetting == null) { 2179 continue; 2180 } 2181 boolean install = enableApps.contains(pName); 2182 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2183 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2184 + " for system user"); 2185 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2186 } 2187 } 2188 } 2189 } 2190 2191 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2192 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2193 Context.DISPLAY_SERVICE); 2194 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2195 } 2196 2197 public PackageManagerService(Context context, Installer installer, 2198 boolean factoryTest, boolean onlyCore) { 2199 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2200 SystemClock.uptimeMillis()); 2201 2202 if (mSdkVersion <= 0) { 2203 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2204 } 2205 2206 mContext = context; 2207 mFactoryTest = factoryTest; 2208 mOnlyCore = onlyCore; 2209 mMetrics = new DisplayMetrics(); 2210 mSettings = new Settings(mPackages); 2211 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2212 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2213 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2214 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2215 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2216 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2217 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2218 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2219 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2220 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2221 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2222 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2223 2224 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2225 if (separateProcesses != null && separateProcesses.length() > 0) { 2226 if ("*".equals(separateProcesses)) { 2227 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2228 mSeparateProcesses = null; 2229 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2230 } else { 2231 mDefParseFlags = 0; 2232 mSeparateProcesses = separateProcesses.split(","); 2233 Slog.w(TAG, "Running with debug.separate_processes: " 2234 + separateProcesses); 2235 } 2236 } else { 2237 mDefParseFlags = 0; 2238 mSeparateProcesses = null; 2239 } 2240 2241 mInstaller = installer; 2242 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2243 "*dexopt*"); 2244 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2245 2246 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2247 FgThread.get().getLooper()); 2248 2249 getDefaultDisplayMetrics(context, mMetrics); 2250 2251 SystemConfig systemConfig = SystemConfig.getInstance(); 2252 mGlobalGids = systemConfig.getGlobalGids(); 2253 mSystemPermissions = systemConfig.getSystemPermissions(); 2254 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2255 2256 synchronized (mInstallLock) { 2257 // writer 2258 synchronized (mPackages) { 2259 mHandlerThread = new ServiceThread(TAG, 2260 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2261 mHandlerThread.start(); 2262 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2263 mProcessLoggingHandler = new ProcessLoggingHandler(); 2264 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2265 2266 File dataDir = Environment.getDataDirectory(); 2267 mAppInstallDir = new File(dataDir, "app"); 2268 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2269 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2270 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2271 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2272 2273 sUserManager = new UserManagerService(context, this, mPackages); 2274 2275 // Propagate permission configuration in to package manager. 2276 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2277 = systemConfig.getPermissions(); 2278 for (int i=0; i<permConfig.size(); i++) { 2279 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2280 BasePermission bp = mSettings.mPermissions.get(perm.name); 2281 if (bp == null) { 2282 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2283 mSettings.mPermissions.put(perm.name, bp); 2284 } 2285 if (perm.gids != null) { 2286 bp.setGids(perm.gids, perm.perUser); 2287 } 2288 } 2289 2290 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2291 for (int i=0; i<libConfig.size(); i++) { 2292 mSharedLibraries.put(libConfig.keyAt(i), 2293 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2294 } 2295 2296 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2297 2298 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2299 2300 String customResolverActivity = Resources.getSystem().getString( 2301 R.string.config_customResolverActivity); 2302 if (TextUtils.isEmpty(customResolverActivity)) { 2303 customResolverActivity = null; 2304 } else { 2305 mCustomResolverComponentName = ComponentName.unflattenFromString( 2306 customResolverActivity); 2307 } 2308 2309 long startTime = SystemClock.uptimeMillis(); 2310 2311 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2312 startTime); 2313 2314 // Set flag to monitor and not change apk file paths when 2315 // scanning install directories. 2316 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2317 2318 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2319 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2320 2321 if (bootClassPath == null) { 2322 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2323 } 2324 2325 if (systemServerClassPath == null) { 2326 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2327 } 2328 2329 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2330 final String[] dexCodeInstructionSets = 2331 getDexCodeInstructionSets( 2332 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2333 2334 /** 2335 * Ensure all external libraries have had dexopt run on them. 2336 */ 2337 if (mSharedLibraries.size() > 0) { 2338 // NOTE: For now, we're compiling these system "shared libraries" 2339 // (and framework jars) into all available architectures. It's possible 2340 // to compile them only when we come across an app that uses them (there's 2341 // already logic for that in scanPackageLI) but that adds some complexity. 2342 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2343 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2344 final String lib = libEntry.path; 2345 if (lib == null) { 2346 continue; 2347 } 2348 2349 try { 2350 // Shared libraries do not have profiles so we perform a full 2351 // AOT compilation (if needed). 2352 int dexoptNeeded = DexFile.getDexOptNeeded( 2353 lib, dexCodeInstructionSet, 2354 getCompilerFilterForReason(REASON_SHARED_APK), 2355 false /* newProfile */); 2356 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2357 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2358 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2359 getCompilerFilterForReason(REASON_SHARED_APK), 2360 StorageManager.UUID_PRIVATE_INTERNAL, 2361 SKIP_SHARED_LIBRARY_CHECK); 2362 } 2363 } catch (FileNotFoundException e) { 2364 Slog.w(TAG, "Library not found: " + lib); 2365 } catch (IOException | InstallerException e) { 2366 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2367 + e.getMessage()); 2368 } 2369 } 2370 } 2371 } 2372 2373 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2374 2375 final VersionInfo ver = mSettings.getInternalVersion(); 2376 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2377 2378 // when upgrading from pre-M, promote system app permissions from install to runtime 2379 mPromoteSystemApps = 2380 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2381 2382 // save off the names of pre-existing system packages prior to scanning; we don't 2383 // want to automatically grant runtime permissions for new system apps 2384 if (mPromoteSystemApps) { 2385 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2386 while (pkgSettingIter.hasNext()) { 2387 PackageSetting ps = pkgSettingIter.next(); 2388 if (isSystemApp(ps)) { 2389 mExistingSystemPackages.add(ps.name); 2390 } 2391 } 2392 } 2393 2394 // When upgrading from pre-N, we need to handle package extraction like first boot, 2395 // as there is no profiling data available. 2396 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2397 mSettings.setNWorkDone(); 2398 2399 // Collect vendor overlay packages. 2400 // (Do this before scanning any apps.) 2401 // For security and version matching reason, only consider 2402 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2403 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2404 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2405 | PackageParser.PARSE_IS_SYSTEM 2406 | PackageParser.PARSE_IS_SYSTEM_DIR 2407 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2408 2409 // Find base frameworks (resource packages without code). 2410 scanDirTracedLI(frameworkDir, mDefParseFlags 2411 | PackageParser.PARSE_IS_SYSTEM 2412 | PackageParser.PARSE_IS_SYSTEM_DIR 2413 | PackageParser.PARSE_IS_PRIVILEGED, 2414 scanFlags | SCAN_NO_DEX, 0); 2415 2416 // Collected privileged system packages. 2417 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2418 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2419 | PackageParser.PARSE_IS_SYSTEM 2420 | PackageParser.PARSE_IS_SYSTEM_DIR 2421 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2422 2423 // Collect ordinary system packages. 2424 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2425 scanDirTracedLI(systemAppDir, mDefParseFlags 2426 | PackageParser.PARSE_IS_SYSTEM 2427 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2428 2429 // Collect all vendor packages. 2430 File vendorAppDir = new File("/vendor/app"); 2431 try { 2432 vendorAppDir = vendorAppDir.getCanonicalFile(); 2433 } catch (IOException e) { 2434 // failed to look up canonical path, continue with original one 2435 } 2436 scanDirTracedLI(vendorAppDir, mDefParseFlags 2437 | PackageParser.PARSE_IS_SYSTEM 2438 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2439 2440 // Collect all OEM packages. 2441 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2442 scanDirTracedLI(oemAppDir, mDefParseFlags 2443 | PackageParser.PARSE_IS_SYSTEM 2444 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2445 2446 // Prune any system packages that no longer exist. 2447 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2448 if (!mOnlyCore) { 2449 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2450 while (psit.hasNext()) { 2451 PackageSetting ps = psit.next(); 2452 2453 /* 2454 * If this is not a system app, it can't be a 2455 * disable system app. 2456 */ 2457 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2458 continue; 2459 } 2460 2461 /* 2462 * If the package is scanned, it's not erased. 2463 */ 2464 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2465 if (scannedPkg != null) { 2466 /* 2467 * If the system app is both scanned and in the 2468 * disabled packages list, then it must have been 2469 * added via OTA. Remove it from the currently 2470 * scanned package so the previously user-installed 2471 * application can be scanned. 2472 */ 2473 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2474 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2475 + ps.name + "; removing system app. Last known codePath=" 2476 + ps.codePathString + ", installStatus=" + ps.installStatus 2477 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2478 + scannedPkg.mVersionCode); 2479 removePackageLI(scannedPkg, true); 2480 mExpectingBetter.put(ps.name, ps.codePath); 2481 } 2482 2483 continue; 2484 } 2485 2486 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2487 psit.remove(); 2488 logCriticalInfo(Log.WARN, "System package " + ps.name 2489 + " no longer exists; it's data will be wiped"); 2490 // Actual deletion of code and data will be handled by later 2491 // reconciliation step 2492 } else { 2493 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2494 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2495 possiblyDeletedUpdatedSystemApps.add(ps.name); 2496 } 2497 } 2498 } 2499 } 2500 2501 //look for any incomplete package installations 2502 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2503 for (int i = 0; i < deletePkgsList.size(); i++) { 2504 // Actual deletion of code and data will be handled by later 2505 // reconciliation step 2506 final String packageName = deletePkgsList.get(i).name; 2507 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2508 synchronized (mPackages) { 2509 mSettings.removePackageLPw(packageName); 2510 } 2511 } 2512 2513 //delete tmp files 2514 deleteTempPackageFiles(); 2515 2516 // Remove any shared userIDs that have no associated packages 2517 mSettings.pruneSharedUsersLPw(); 2518 2519 if (!mOnlyCore) { 2520 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2521 SystemClock.uptimeMillis()); 2522 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2523 2524 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2525 | PackageParser.PARSE_FORWARD_LOCK, 2526 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2527 2528 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2529 | PackageParser.PARSE_IS_EPHEMERAL, 2530 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2531 2532 /** 2533 * Remove disable package settings for any updated system 2534 * apps that were removed via an OTA. If they're not a 2535 * previously-updated app, remove them completely. 2536 * Otherwise, just revoke their system-level permissions. 2537 */ 2538 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2539 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2540 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2541 2542 String msg; 2543 if (deletedPkg == null) { 2544 msg = "Updated system package " + deletedAppName 2545 + " no longer exists; it's data will be wiped"; 2546 // Actual deletion of code and data will be handled by later 2547 // reconciliation step 2548 } else { 2549 msg = "Updated system app + " + deletedAppName 2550 + " no longer present; removing system privileges for " 2551 + deletedAppName; 2552 2553 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2554 2555 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2556 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2557 } 2558 logCriticalInfo(Log.WARN, msg); 2559 } 2560 2561 /** 2562 * Make sure all system apps that we expected to appear on 2563 * the userdata partition actually showed up. If they never 2564 * appeared, crawl back and revive the system version. 2565 */ 2566 for (int i = 0; i < mExpectingBetter.size(); i++) { 2567 final String packageName = mExpectingBetter.keyAt(i); 2568 if (!mPackages.containsKey(packageName)) { 2569 final File scanFile = mExpectingBetter.valueAt(i); 2570 2571 logCriticalInfo(Log.WARN, "Expected better " + packageName 2572 + " but never showed up; reverting to system"); 2573 2574 int reparseFlags = mDefParseFlags; 2575 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2576 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2577 | PackageParser.PARSE_IS_SYSTEM_DIR 2578 | PackageParser.PARSE_IS_PRIVILEGED; 2579 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2580 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR; 2582 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2583 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2584 | PackageParser.PARSE_IS_SYSTEM_DIR; 2585 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2586 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2587 | PackageParser.PARSE_IS_SYSTEM_DIR; 2588 } else { 2589 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2590 continue; 2591 } 2592 2593 mSettings.enableSystemPackageLPw(packageName); 2594 2595 try { 2596 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2597 } catch (PackageManagerException e) { 2598 Slog.e(TAG, "Failed to parse original system package: " 2599 + e.getMessage()); 2600 } 2601 } 2602 } 2603 } 2604 mExpectingBetter.clear(); 2605 2606 // Resolve protected action filters. Only the setup wizard is allowed to 2607 // have a high priority filter for these actions. 2608 mSetupWizardPackage = getSetupWizardPackageName(); 2609 if (mProtectedFilters.size() > 0) { 2610 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2611 Slog.i(TAG, "No setup wizard;" 2612 + " All protected intents capped to priority 0"); 2613 } 2614 for (ActivityIntentInfo filter : mProtectedFilters) { 2615 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2616 if (DEBUG_FILTERS) { 2617 Slog.i(TAG, "Found setup wizard;" 2618 + " allow priority " + filter.getPriority() + ";" 2619 + " package: " + filter.activity.info.packageName 2620 + " activity: " + filter.activity.className 2621 + " priority: " + filter.getPriority()); 2622 } 2623 // skip setup wizard; allow it to keep the high priority filter 2624 continue; 2625 } 2626 Slog.w(TAG, "Protected action; cap priority to 0;" 2627 + " package: " + filter.activity.info.packageName 2628 + " activity: " + filter.activity.className 2629 + " origPrio: " + filter.getPriority()); 2630 filter.setPriority(0); 2631 } 2632 } 2633 mDeferProtectedFilters = false; 2634 mProtectedFilters.clear(); 2635 2636 // Now that we know all of the shared libraries, update all clients to have 2637 // the correct library paths. 2638 updateAllSharedLibrariesLPw(); 2639 2640 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2641 // NOTE: We ignore potential failures here during a system scan (like 2642 // the rest of the commands above) because there's precious little we 2643 // can do about it. A settings error is reported, though. 2644 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2645 false /* boot complete */); 2646 } 2647 2648 // Now that we know all the packages we are keeping, 2649 // read and update their last usage times. 2650 mPackageUsage.readLP(); 2651 2652 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2653 SystemClock.uptimeMillis()); 2654 Slog.i(TAG, "Time to scan packages: " 2655 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2656 + " seconds"); 2657 2658 // If the platform SDK has changed since the last time we booted, 2659 // we need to re-grant app permission to catch any new ones that 2660 // appear. This is really a hack, and means that apps can in some 2661 // cases get permissions that the user didn't initially explicitly 2662 // allow... it would be nice to have some better way to handle 2663 // this situation. 2664 int updateFlags = UPDATE_PERMISSIONS_ALL; 2665 if (ver.sdkVersion != mSdkVersion) { 2666 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2667 + mSdkVersion + "; regranting permissions for internal storage"); 2668 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2669 } 2670 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2671 ver.sdkVersion = mSdkVersion; 2672 2673 // If this is the first boot or an update from pre-M, and it is a normal 2674 // boot, then we need to initialize the default preferred apps across 2675 // all defined users. 2676 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2677 for (UserInfo user : sUserManager.getUsers(true)) { 2678 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2679 applyFactoryDefaultBrowserLPw(user.id); 2680 primeDomainVerificationsLPw(user.id); 2681 } 2682 } 2683 2684 // Prepare storage for system user really early during boot, 2685 // since core system apps like SettingsProvider and SystemUI 2686 // can't wait for user to start 2687 final int storageFlags; 2688 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2689 storageFlags = StorageManager.FLAG_STORAGE_DE; 2690 } else { 2691 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2692 } 2693 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2694 storageFlags); 2695 2696 // If this is first boot after an OTA, and a normal boot, then 2697 // we need to clear code cache directories. 2698 if (mIsUpgrade && !onlyCore) { 2699 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2700 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2701 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2702 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2703 // No apps are running this early, so no need to freeze 2704 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2705 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2706 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2707 } 2708 clearAppProfilesLIF(ps.pkg); 2709 } 2710 ver.fingerprint = Build.FINGERPRINT; 2711 } 2712 2713 checkDefaultBrowser(); 2714 2715 // clear only after permissions and other defaults have been updated 2716 mExistingSystemPackages.clear(); 2717 mPromoteSystemApps = false; 2718 2719 // All the changes are done during package scanning. 2720 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2721 2722 // can downgrade to reader 2723 mSettings.writeLPr(); 2724 2725 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2726 SystemClock.uptimeMillis()); 2727 2728 if (!mOnlyCore) { 2729 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2730 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2731 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2732 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2733 mIntentFilterVerifierComponent); 2734 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2735 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2736 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2737 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2738 } else { 2739 mRequiredVerifierPackage = null; 2740 mRequiredInstallerPackage = null; 2741 mIntentFilterVerifierComponent = null; 2742 mIntentFilterVerifier = null; 2743 mServicesSystemSharedLibraryPackageName = null; 2744 mSharedSystemSharedLibraryPackageName = null; 2745 } 2746 2747 mInstallerService = new PackageInstallerService(context, this); 2748 2749 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2750 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2751 // both the installer and resolver must be present to enable ephemeral 2752 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2753 if (DEBUG_EPHEMERAL) { 2754 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2755 + " installer:" + ephemeralInstallerComponent); 2756 } 2757 mEphemeralResolverComponent = ephemeralResolverComponent; 2758 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2759 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2760 mEphemeralResolverConnection = 2761 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2762 } else { 2763 if (DEBUG_EPHEMERAL) { 2764 final String missingComponent = 2765 (ephemeralResolverComponent == null) 2766 ? (ephemeralInstallerComponent == null) 2767 ? "resolver and installer" 2768 : "resolver" 2769 : "installer"; 2770 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2771 } 2772 mEphemeralResolverComponent = null; 2773 mEphemeralInstallerComponent = null; 2774 mEphemeralResolverConnection = null; 2775 } 2776 2777 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2778 } // synchronized (mPackages) 2779 } // synchronized (mInstallLock) 2780 2781 // Now after opening every single application zip, make sure they 2782 // are all flushed. Not really needed, but keeps things nice and 2783 // tidy. 2784 Runtime.getRuntime().gc(); 2785 2786 // The initial scanning above does many calls into installd while 2787 // holding the mPackages lock, but we're mostly interested in yelling 2788 // once we have a booted system. 2789 mInstaller.setWarnIfHeld(mPackages); 2790 2791 // Expose private service for system components to use. 2792 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2793 } 2794 2795 @Override 2796 public boolean isFirstBoot() { 2797 return !mRestoredSettings; 2798 } 2799 2800 @Override 2801 public boolean isOnlyCoreApps() { 2802 return mOnlyCore; 2803 } 2804 2805 @Override 2806 public boolean isUpgrade() { 2807 return mIsUpgrade; 2808 } 2809 2810 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2811 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2812 2813 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2814 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2815 UserHandle.USER_SYSTEM); 2816 if (matches.size() == 1) { 2817 return matches.get(0).getComponentInfo().packageName; 2818 } else { 2819 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2820 return null; 2821 } 2822 } 2823 2824 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2825 synchronized (mPackages) { 2826 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2827 if (libraryEntry == null) { 2828 throw new IllegalStateException("Missing required shared library:" + libraryName); 2829 } 2830 return libraryEntry.apk; 2831 } 2832 } 2833 2834 private @NonNull String getRequiredInstallerLPr() { 2835 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2836 intent.addCategory(Intent.CATEGORY_DEFAULT); 2837 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2838 2839 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2840 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2841 UserHandle.USER_SYSTEM); 2842 if (matches.size() == 1) { 2843 ResolveInfo resolveInfo = matches.get(0); 2844 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2845 throw new RuntimeException("The installer must be a privileged app"); 2846 } 2847 return matches.get(0).getComponentInfo().packageName; 2848 } else { 2849 throw new RuntimeException("There must be exactly one installer; found " + matches); 2850 } 2851 } 2852 2853 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2854 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2855 2856 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2857 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2858 UserHandle.USER_SYSTEM); 2859 ResolveInfo best = null; 2860 final int N = matches.size(); 2861 for (int i = 0; i < N; i++) { 2862 final ResolveInfo cur = matches.get(i); 2863 final String packageName = cur.getComponentInfo().packageName; 2864 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2865 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2866 continue; 2867 } 2868 2869 if (best == null || cur.priority > best.priority) { 2870 best = cur; 2871 } 2872 } 2873 2874 if (best != null) { 2875 return best.getComponentInfo().getComponentName(); 2876 } else { 2877 throw new RuntimeException("There must be at least one intent filter verifier"); 2878 } 2879 } 2880 2881 private @Nullable ComponentName getEphemeralResolverLPr() { 2882 final String[] packageArray = 2883 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2884 if (packageArray.length == 0) { 2885 if (DEBUG_EPHEMERAL) { 2886 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2887 } 2888 return null; 2889 } 2890 2891 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2892 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2893 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2894 UserHandle.USER_SYSTEM); 2895 2896 final int N = resolvers.size(); 2897 if (N == 0) { 2898 if (DEBUG_EPHEMERAL) { 2899 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2900 } 2901 return null; 2902 } 2903 2904 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2905 for (int i = 0; i < N; i++) { 2906 final ResolveInfo info = resolvers.get(i); 2907 2908 if (info.serviceInfo == null) { 2909 continue; 2910 } 2911 2912 final String packageName = info.serviceInfo.packageName; 2913 if (!possiblePackages.contains(packageName)) { 2914 if (DEBUG_EPHEMERAL) { 2915 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2916 + " pkg: " + packageName + ", info:" + info); 2917 } 2918 continue; 2919 } 2920 2921 if (DEBUG_EPHEMERAL) { 2922 Slog.v(TAG, "Ephemeral resolver found;" 2923 + " pkg: " + packageName + ", info:" + info); 2924 } 2925 return new ComponentName(packageName, info.serviceInfo.name); 2926 } 2927 if (DEBUG_EPHEMERAL) { 2928 Slog.v(TAG, "Ephemeral resolver NOT found"); 2929 } 2930 return null; 2931 } 2932 2933 private @Nullable ComponentName getEphemeralInstallerLPr() { 2934 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2935 intent.addCategory(Intent.CATEGORY_DEFAULT); 2936 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2937 2938 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2939 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2940 UserHandle.USER_SYSTEM); 2941 if (matches.size() == 0) { 2942 return null; 2943 } else if (matches.size() == 1) { 2944 return matches.get(0).getComponentInfo().getComponentName(); 2945 } else { 2946 throw new RuntimeException( 2947 "There must be at most one ephemeral installer; found " + matches); 2948 } 2949 } 2950 2951 private void primeDomainVerificationsLPw(int userId) { 2952 if (DEBUG_DOMAIN_VERIFICATION) { 2953 Slog.d(TAG, "Priming domain verifications in user " + userId); 2954 } 2955 2956 SystemConfig systemConfig = SystemConfig.getInstance(); 2957 ArraySet<String> packages = systemConfig.getLinkedApps(); 2958 ArraySet<String> domains = new ArraySet<String>(); 2959 2960 for (String packageName : packages) { 2961 PackageParser.Package pkg = mPackages.get(packageName); 2962 if (pkg != null) { 2963 if (!pkg.isSystemApp()) { 2964 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2965 continue; 2966 } 2967 2968 domains.clear(); 2969 for (PackageParser.Activity a : pkg.activities) { 2970 for (ActivityIntentInfo filter : a.intents) { 2971 if (hasValidDomains(filter)) { 2972 domains.addAll(filter.getHostsList()); 2973 } 2974 } 2975 } 2976 2977 if (domains.size() > 0) { 2978 if (DEBUG_DOMAIN_VERIFICATION) { 2979 Slog.v(TAG, " + " + packageName); 2980 } 2981 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2982 // state w.r.t. the formal app-linkage "no verification attempted" state; 2983 // and then 'always' in the per-user state actually used for intent resolution. 2984 final IntentFilterVerificationInfo ivi; 2985 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2986 new ArrayList<String>(domains)); 2987 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2988 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2989 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2990 } else { 2991 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2992 + "' does not handle web links"); 2993 } 2994 } else { 2995 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2996 } 2997 } 2998 2999 scheduleWritePackageRestrictionsLocked(userId); 3000 scheduleWriteSettingsLocked(); 3001 } 3002 3003 private void applyFactoryDefaultBrowserLPw(int userId) { 3004 // The default browser app's package name is stored in a string resource, 3005 // with a product-specific overlay used for vendor customization. 3006 String browserPkg = mContext.getResources().getString( 3007 com.android.internal.R.string.default_browser); 3008 if (!TextUtils.isEmpty(browserPkg)) { 3009 // non-empty string => required to be a known package 3010 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3011 if (ps == null) { 3012 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3013 browserPkg = null; 3014 } else { 3015 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3016 } 3017 } 3018 3019 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3020 // default. If there's more than one, just leave everything alone. 3021 if (browserPkg == null) { 3022 calculateDefaultBrowserLPw(userId); 3023 } 3024 } 3025 3026 private void calculateDefaultBrowserLPw(int userId) { 3027 List<String> allBrowsers = resolveAllBrowserApps(userId); 3028 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3029 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3030 } 3031 3032 private List<String> resolveAllBrowserApps(int userId) { 3033 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3034 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3035 PackageManager.MATCH_ALL, userId); 3036 3037 final int count = list.size(); 3038 List<String> result = new ArrayList<String>(count); 3039 for (int i=0; i<count; i++) { 3040 ResolveInfo info = list.get(i); 3041 if (info.activityInfo == null 3042 || !info.handleAllWebDataURI 3043 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3044 || result.contains(info.activityInfo.packageName)) { 3045 continue; 3046 } 3047 result.add(info.activityInfo.packageName); 3048 } 3049 3050 return result; 3051 } 3052 3053 private boolean packageIsBrowser(String packageName, int userId) { 3054 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3055 PackageManager.MATCH_ALL, userId); 3056 final int N = list.size(); 3057 for (int i = 0; i < N; i++) { 3058 ResolveInfo info = list.get(i); 3059 if (packageName.equals(info.activityInfo.packageName)) { 3060 return true; 3061 } 3062 } 3063 return false; 3064 } 3065 3066 private void checkDefaultBrowser() { 3067 final int myUserId = UserHandle.myUserId(); 3068 final String packageName = getDefaultBrowserPackageName(myUserId); 3069 if (packageName != null) { 3070 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3071 if (info == null) { 3072 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3073 synchronized (mPackages) { 3074 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3075 } 3076 } 3077 } 3078 } 3079 3080 @Override 3081 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3082 throws RemoteException { 3083 try { 3084 return super.onTransact(code, data, reply, flags); 3085 } catch (RuntimeException e) { 3086 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3087 Slog.wtf(TAG, "Package Manager Crash", e); 3088 } 3089 throw e; 3090 } 3091 } 3092 3093 static int[] appendInts(int[] cur, int[] add) { 3094 if (add == null) return cur; 3095 if (cur == null) return add; 3096 final int N = add.length; 3097 for (int i=0; i<N; i++) { 3098 cur = appendInt(cur, add[i]); 3099 } 3100 return cur; 3101 } 3102 3103 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3104 if (!sUserManager.exists(userId)) return null; 3105 if (ps == null) { 3106 return null; 3107 } 3108 final PackageParser.Package p = ps.pkg; 3109 if (p == null) { 3110 return null; 3111 } 3112 3113 final PermissionsState permissionsState = ps.getPermissionsState(); 3114 3115 final int[] gids = permissionsState.computeGids(userId); 3116 final Set<String> permissions = permissionsState.getPermissions(userId); 3117 final PackageUserState state = ps.readUserState(userId); 3118 3119 return PackageParser.generatePackageInfo(p, gids, flags, 3120 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3121 } 3122 3123 @Override 3124 public void checkPackageStartable(String packageName, int userId) { 3125 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3126 3127 synchronized (mPackages) { 3128 final PackageSetting ps = mSettings.mPackages.get(packageName); 3129 if (ps == null) { 3130 throw new SecurityException("Package " + packageName + " was not found!"); 3131 } 3132 3133 if (!ps.getInstalled(userId)) { 3134 throw new SecurityException( 3135 "Package " + packageName + " was not installed for user " + userId + "!"); 3136 } 3137 3138 if (mSafeMode && !ps.isSystem()) { 3139 throw new SecurityException("Package " + packageName + " not a system app!"); 3140 } 3141 3142 if (mFrozenPackages.contains(packageName)) { 3143 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3144 } 3145 3146 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3147 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3148 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3149 } 3150 } 3151 } 3152 3153 @Override 3154 public boolean isPackageAvailable(String packageName, int userId) { 3155 if (!sUserManager.exists(userId)) return false; 3156 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3157 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3158 synchronized (mPackages) { 3159 PackageParser.Package p = mPackages.get(packageName); 3160 if (p != null) { 3161 final PackageSetting ps = (PackageSetting) p.mExtras; 3162 if (ps != null) { 3163 final PackageUserState state = ps.readUserState(userId); 3164 if (state != null) { 3165 return PackageParser.isAvailable(state); 3166 } 3167 } 3168 } 3169 } 3170 return false; 3171 } 3172 3173 @Override 3174 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3175 if (!sUserManager.exists(userId)) return null; 3176 flags = updateFlagsForPackage(flags, userId, packageName); 3177 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3178 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3179 // reader 3180 synchronized (mPackages) { 3181 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3182 PackageParser.Package p = null; 3183 if (matchFactoryOnly) { 3184 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3185 if (ps != null) { 3186 return generatePackageInfo(ps, flags, userId); 3187 } 3188 } 3189 if (p == null) { 3190 p = mPackages.get(packageName); 3191 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3192 return null; 3193 } 3194 } 3195 if (DEBUG_PACKAGE_INFO) 3196 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3197 if (p != null) { 3198 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3199 } 3200 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3201 final PackageSetting ps = mSettings.mPackages.get(packageName); 3202 return generatePackageInfo(ps, flags, userId); 3203 } 3204 } 3205 return null; 3206 } 3207 3208 @Override 3209 public String[] currentToCanonicalPackageNames(String[] names) { 3210 String[] out = new String[names.length]; 3211 // reader 3212 synchronized (mPackages) { 3213 for (int i=names.length-1; i>=0; i--) { 3214 PackageSetting ps = mSettings.mPackages.get(names[i]); 3215 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3216 } 3217 } 3218 return out; 3219 } 3220 3221 @Override 3222 public String[] canonicalToCurrentPackageNames(String[] names) { 3223 String[] out = new String[names.length]; 3224 // reader 3225 synchronized (mPackages) { 3226 for (int i=names.length-1; i>=0; i--) { 3227 String cur = mSettings.mRenamedPackages.get(names[i]); 3228 out[i] = cur != null ? cur : names[i]; 3229 } 3230 } 3231 return out; 3232 } 3233 3234 @Override 3235 public int getPackageUid(String packageName, int flags, int userId) { 3236 if (!sUserManager.exists(userId)) return -1; 3237 flags = updateFlagsForPackage(flags, userId, packageName); 3238 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3239 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3240 3241 // reader 3242 synchronized (mPackages) { 3243 final PackageParser.Package p = mPackages.get(packageName); 3244 if (p != null && p.isMatch(flags)) { 3245 return UserHandle.getUid(userId, p.applicationInfo.uid); 3246 } 3247 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3248 final PackageSetting ps = mSettings.mPackages.get(packageName); 3249 if (ps != null && ps.isMatch(flags)) { 3250 return UserHandle.getUid(userId, ps.appId); 3251 } 3252 } 3253 } 3254 3255 return -1; 3256 } 3257 3258 @Override 3259 public int[] getPackageGids(String packageName, int flags, int userId) { 3260 if (!sUserManager.exists(userId)) return null; 3261 flags = updateFlagsForPackage(flags, userId, packageName); 3262 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3263 false /* requireFullPermission */, false /* checkShell */, 3264 "getPackageGids"); 3265 3266 // reader 3267 synchronized (mPackages) { 3268 final PackageParser.Package p = mPackages.get(packageName); 3269 if (p != null && p.isMatch(flags)) { 3270 PackageSetting ps = (PackageSetting) p.mExtras; 3271 return ps.getPermissionsState().computeGids(userId); 3272 } 3273 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3274 final PackageSetting ps = mSettings.mPackages.get(packageName); 3275 if (ps != null && ps.isMatch(flags)) { 3276 return ps.getPermissionsState().computeGids(userId); 3277 } 3278 } 3279 } 3280 3281 return null; 3282 } 3283 3284 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3285 if (bp.perm != null) { 3286 return PackageParser.generatePermissionInfo(bp.perm, flags); 3287 } 3288 PermissionInfo pi = new PermissionInfo(); 3289 pi.name = bp.name; 3290 pi.packageName = bp.sourcePackage; 3291 pi.nonLocalizedLabel = bp.name; 3292 pi.protectionLevel = bp.protectionLevel; 3293 return pi; 3294 } 3295 3296 @Override 3297 public PermissionInfo getPermissionInfo(String name, int flags) { 3298 // reader 3299 synchronized (mPackages) { 3300 final BasePermission p = mSettings.mPermissions.get(name); 3301 if (p != null) { 3302 return generatePermissionInfo(p, flags); 3303 } 3304 return null; 3305 } 3306 } 3307 3308 @Override 3309 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3310 int flags) { 3311 // reader 3312 synchronized (mPackages) { 3313 if (group != null && !mPermissionGroups.containsKey(group)) { 3314 // This is thrown as NameNotFoundException 3315 return null; 3316 } 3317 3318 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3319 for (BasePermission p : mSettings.mPermissions.values()) { 3320 if (group == null) { 3321 if (p.perm == null || p.perm.info.group == null) { 3322 out.add(generatePermissionInfo(p, flags)); 3323 } 3324 } else { 3325 if (p.perm != null && group.equals(p.perm.info.group)) { 3326 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3327 } 3328 } 3329 } 3330 return new ParceledListSlice<>(out); 3331 } 3332 } 3333 3334 @Override 3335 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3336 // reader 3337 synchronized (mPackages) { 3338 return PackageParser.generatePermissionGroupInfo( 3339 mPermissionGroups.get(name), flags); 3340 } 3341 } 3342 3343 @Override 3344 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3345 // reader 3346 synchronized (mPackages) { 3347 final int N = mPermissionGroups.size(); 3348 ArrayList<PermissionGroupInfo> out 3349 = new ArrayList<PermissionGroupInfo>(N); 3350 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3351 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3352 } 3353 return new ParceledListSlice<>(out); 3354 } 3355 } 3356 3357 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3358 int userId) { 3359 if (!sUserManager.exists(userId)) return null; 3360 PackageSetting ps = mSettings.mPackages.get(packageName); 3361 if (ps != null) { 3362 if (ps.pkg == null) { 3363 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3364 if (pInfo != null) { 3365 return pInfo.applicationInfo; 3366 } 3367 return null; 3368 } 3369 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3370 ps.readUserState(userId), userId); 3371 } 3372 return null; 3373 } 3374 3375 @Override 3376 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3377 if (!sUserManager.exists(userId)) return null; 3378 flags = updateFlagsForApplication(flags, userId, packageName); 3379 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3380 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3381 // writer 3382 synchronized (mPackages) { 3383 PackageParser.Package p = mPackages.get(packageName); 3384 if (DEBUG_PACKAGE_INFO) Log.v( 3385 TAG, "getApplicationInfo " + packageName 3386 + ": " + p); 3387 if (p != null) { 3388 PackageSetting ps = mSettings.mPackages.get(packageName); 3389 if (ps == null) return null; 3390 // Note: isEnabledLP() does not apply here - always return info 3391 return PackageParser.generateApplicationInfo( 3392 p, flags, ps.readUserState(userId), userId); 3393 } 3394 if ("android".equals(packageName)||"system".equals(packageName)) { 3395 return mAndroidApplication; 3396 } 3397 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3398 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3399 } 3400 } 3401 return null; 3402 } 3403 3404 @Override 3405 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3406 final IPackageDataObserver observer) { 3407 mContext.enforceCallingOrSelfPermission( 3408 android.Manifest.permission.CLEAR_APP_CACHE, null); 3409 // Queue up an async operation since clearing cache may take a little while. 3410 mHandler.post(new Runnable() { 3411 public void run() { 3412 mHandler.removeCallbacks(this); 3413 boolean success = true; 3414 synchronized (mInstallLock) { 3415 try { 3416 mInstaller.freeCache(volumeUuid, freeStorageSize); 3417 } catch (InstallerException e) { 3418 Slog.w(TAG, "Couldn't clear application caches: " + e); 3419 success = false; 3420 } 3421 } 3422 if (observer != null) { 3423 try { 3424 observer.onRemoveCompleted(null, success); 3425 } catch (RemoteException e) { 3426 Slog.w(TAG, "RemoveException when invoking call back"); 3427 } 3428 } 3429 } 3430 }); 3431 } 3432 3433 @Override 3434 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3435 final IntentSender pi) { 3436 mContext.enforceCallingOrSelfPermission( 3437 android.Manifest.permission.CLEAR_APP_CACHE, null); 3438 // Queue up an async operation since clearing cache may take a little while. 3439 mHandler.post(new Runnable() { 3440 public void run() { 3441 mHandler.removeCallbacks(this); 3442 boolean success = true; 3443 synchronized (mInstallLock) { 3444 try { 3445 mInstaller.freeCache(volumeUuid, freeStorageSize); 3446 } catch (InstallerException e) { 3447 Slog.w(TAG, "Couldn't clear application caches: " + e); 3448 success = false; 3449 } 3450 } 3451 if(pi != null) { 3452 try { 3453 // Callback via pending intent 3454 int code = success ? 1 : 0; 3455 pi.sendIntent(null, code, null, 3456 null, null); 3457 } catch (SendIntentException e1) { 3458 Slog.i(TAG, "Failed to send pending intent"); 3459 } 3460 } 3461 } 3462 }); 3463 } 3464 3465 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3466 synchronized (mInstallLock) { 3467 try { 3468 mInstaller.freeCache(volumeUuid, freeStorageSize); 3469 } catch (InstallerException e) { 3470 throw new IOException("Failed to free enough space", e); 3471 } 3472 } 3473 } 3474 3475 /** 3476 * Update given flags based on encryption status of current user. 3477 */ 3478 private int updateFlags(int flags, int userId) { 3479 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3480 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3481 // Caller expressed an explicit opinion about what encryption 3482 // aware/unaware components they want to see, so fall through and 3483 // give them what they want 3484 } else { 3485 // Caller expressed no opinion, so match based on user state 3486 if (getUserManagerInternal().isUserUnlockingOrUnlocked(userId)) { 3487 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3488 } else { 3489 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3490 } 3491 } 3492 return flags; 3493 } 3494 3495 private UserManagerInternal getUserManagerInternal() { 3496 if (mUserManagerInternal == null) { 3497 mUserManagerInternal = LocalServices.getService(UserManagerInternal.class); 3498 } 3499 return mUserManagerInternal; 3500 } 3501 3502 /** 3503 * Update given flags when being used to request {@link PackageInfo}. 3504 */ 3505 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3506 boolean triaged = true; 3507 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3508 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3509 // Caller is asking for component details, so they'd better be 3510 // asking for specific encryption matching behavior, or be triaged 3511 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3512 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3513 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3514 triaged = false; 3515 } 3516 } 3517 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3518 | PackageManager.MATCH_SYSTEM_ONLY 3519 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3520 triaged = false; 3521 } 3522 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3523 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3524 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3525 } 3526 return updateFlags(flags, userId); 3527 } 3528 3529 /** 3530 * Update given flags when being used to request {@link ApplicationInfo}. 3531 */ 3532 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3533 return updateFlagsForPackage(flags, userId, cookie); 3534 } 3535 3536 /** 3537 * Update given flags when being used to request {@link ComponentInfo}. 3538 */ 3539 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3540 if (cookie instanceof Intent) { 3541 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3542 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3543 } 3544 } 3545 3546 boolean triaged = true; 3547 // Caller is asking for component details, so they'd better be 3548 // asking for specific encryption matching behavior, or be triaged 3549 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3550 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3551 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3552 triaged = false; 3553 } 3554 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3555 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3556 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3557 } 3558 3559 return updateFlags(flags, userId); 3560 } 3561 3562 /** 3563 * Update given flags when being used to request {@link ResolveInfo}. 3564 */ 3565 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3566 // Safe mode means we shouldn't match any third-party components 3567 if (mSafeMode) { 3568 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3569 } 3570 3571 return updateFlagsForComponent(flags, userId, cookie); 3572 } 3573 3574 @Override 3575 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3576 if (!sUserManager.exists(userId)) return null; 3577 flags = updateFlagsForComponent(flags, userId, component); 3578 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3579 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3580 synchronized (mPackages) { 3581 PackageParser.Activity a = mActivities.mActivities.get(component); 3582 3583 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3584 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3585 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3586 if (ps == null) return null; 3587 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3588 userId); 3589 } 3590 if (mResolveComponentName.equals(component)) { 3591 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3592 new PackageUserState(), userId); 3593 } 3594 } 3595 return null; 3596 } 3597 3598 @Override 3599 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3600 String resolvedType) { 3601 synchronized (mPackages) { 3602 if (component.equals(mResolveComponentName)) { 3603 // The resolver supports EVERYTHING! 3604 return true; 3605 } 3606 PackageParser.Activity a = mActivities.mActivities.get(component); 3607 if (a == null) { 3608 return false; 3609 } 3610 for (int i=0; i<a.intents.size(); i++) { 3611 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3612 intent.getData(), intent.getCategories(), TAG) >= 0) { 3613 return true; 3614 } 3615 } 3616 return false; 3617 } 3618 } 3619 3620 @Override 3621 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3622 if (!sUserManager.exists(userId)) return null; 3623 flags = updateFlagsForComponent(flags, userId, component); 3624 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3625 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3626 synchronized (mPackages) { 3627 PackageParser.Activity a = mReceivers.mActivities.get(component); 3628 if (DEBUG_PACKAGE_INFO) Log.v( 3629 TAG, "getReceiverInfo " + component + ": " + a); 3630 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3631 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3632 if (ps == null) return null; 3633 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3634 userId); 3635 } 3636 } 3637 return null; 3638 } 3639 3640 @Override 3641 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3642 if (!sUserManager.exists(userId)) return null; 3643 flags = updateFlagsForComponent(flags, userId, component); 3644 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3645 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3646 synchronized (mPackages) { 3647 PackageParser.Service s = mServices.mServices.get(component); 3648 if (DEBUG_PACKAGE_INFO) Log.v( 3649 TAG, "getServiceInfo " + component + ": " + s); 3650 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3651 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3652 if (ps == null) return null; 3653 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3654 userId); 3655 } 3656 } 3657 return null; 3658 } 3659 3660 @Override 3661 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3662 if (!sUserManager.exists(userId)) return null; 3663 flags = updateFlagsForComponent(flags, userId, component); 3664 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3665 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3666 synchronized (mPackages) { 3667 PackageParser.Provider p = mProviders.mProviders.get(component); 3668 if (DEBUG_PACKAGE_INFO) Log.v( 3669 TAG, "getProviderInfo " + component + ": " + p); 3670 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3671 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3672 if (ps == null) return null; 3673 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3674 userId); 3675 } 3676 } 3677 return null; 3678 } 3679 3680 @Override 3681 public String[] getSystemSharedLibraryNames() { 3682 Set<String> libSet; 3683 synchronized (mPackages) { 3684 libSet = mSharedLibraries.keySet(); 3685 int size = libSet.size(); 3686 if (size > 0) { 3687 String[] libs = new String[size]; 3688 libSet.toArray(libs); 3689 return libs; 3690 } 3691 } 3692 return null; 3693 } 3694 3695 @Override 3696 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3697 synchronized (mPackages) { 3698 return mServicesSystemSharedLibraryPackageName; 3699 } 3700 } 3701 3702 @Override 3703 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3704 synchronized (mPackages) { 3705 return mSharedSystemSharedLibraryPackageName; 3706 } 3707 } 3708 3709 @Override 3710 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3711 synchronized (mPackages) { 3712 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3713 3714 final FeatureInfo fi = new FeatureInfo(); 3715 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3716 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3717 res.add(fi); 3718 3719 return new ParceledListSlice<>(res); 3720 } 3721 } 3722 3723 @Override 3724 public boolean hasSystemFeature(String name, int version) { 3725 synchronized (mPackages) { 3726 final FeatureInfo feat = mAvailableFeatures.get(name); 3727 if (feat == null) { 3728 return false; 3729 } else { 3730 return feat.version >= version; 3731 } 3732 } 3733 } 3734 3735 @Override 3736 public int checkPermission(String permName, String pkgName, int userId) { 3737 if (!sUserManager.exists(userId)) { 3738 return PackageManager.PERMISSION_DENIED; 3739 } 3740 3741 synchronized (mPackages) { 3742 final PackageParser.Package p = mPackages.get(pkgName); 3743 if (p != null && p.mExtras != null) { 3744 final PackageSetting ps = (PackageSetting) p.mExtras; 3745 final PermissionsState permissionsState = ps.getPermissionsState(); 3746 if (permissionsState.hasPermission(permName, userId)) { 3747 return PackageManager.PERMISSION_GRANTED; 3748 } 3749 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3750 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3751 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3752 return PackageManager.PERMISSION_GRANTED; 3753 } 3754 } 3755 } 3756 3757 return PackageManager.PERMISSION_DENIED; 3758 } 3759 3760 @Override 3761 public int checkUidPermission(String permName, int uid) { 3762 final int userId = UserHandle.getUserId(uid); 3763 3764 if (!sUserManager.exists(userId)) { 3765 return PackageManager.PERMISSION_DENIED; 3766 } 3767 3768 synchronized (mPackages) { 3769 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3770 if (obj != null) { 3771 final SettingBase ps = (SettingBase) obj; 3772 final PermissionsState permissionsState = ps.getPermissionsState(); 3773 if (permissionsState.hasPermission(permName, userId)) { 3774 return PackageManager.PERMISSION_GRANTED; 3775 } 3776 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3777 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3778 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 } else { 3782 ArraySet<String> perms = mSystemPermissions.get(uid); 3783 if (perms != null) { 3784 if (perms.contains(permName)) { 3785 return PackageManager.PERMISSION_GRANTED; 3786 } 3787 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3788 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3789 return PackageManager.PERMISSION_GRANTED; 3790 } 3791 } 3792 } 3793 } 3794 3795 return PackageManager.PERMISSION_DENIED; 3796 } 3797 3798 @Override 3799 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3800 if (UserHandle.getCallingUserId() != userId) { 3801 mContext.enforceCallingPermission( 3802 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3803 "isPermissionRevokedByPolicy for user " + userId); 3804 } 3805 3806 if (checkPermission(permission, packageName, userId) 3807 == PackageManager.PERMISSION_GRANTED) { 3808 return false; 3809 } 3810 3811 final long identity = Binder.clearCallingIdentity(); 3812 try { 3813 final int flags = getPermissionFlags(permission, packageName, userId); 3814 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3815 } finally { 3816 Binder.restoreCallingIdentity(identity); 3817 } 3818 } 3819 3820 @Override 3821 public String getPermissionControllerPackageName() { 3822 synchronized (mPackages) { 3823 return mRequiredInstallerPackage; 3824 } 3825 } 3826 3827 /** 3828 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3829 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3830 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3831 * @param message the message to log on security exception 3832 */ 3833 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3834 boolean checkShell, String message) { 3835 if (userId < 0) { 3836 throw new IllegalArgumentException("Invalid userId " + userId); 3837 } 3838 if (checkShell) { 3839 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3840 } 3841 if (userId == UserHandle.getUserId(callingUid)) return; 3842 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3843 if (requireFullPermission) { 3844 mContext.enforceCallingOrSelfPermission( 3845 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3846 } else { 3847 try { 3848 mContext.enforceCallingOrSelfPermission( 3849 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3850 } catch (SecurityException se) { 3851 mContext.enforceCallingOrSelfPermission( 3852 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3853 } 3854 } 3855 } 3856 } 3857 3858 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3859 if (callingUid == Process.SHELL_UID) { 3860 if (userHandle >= 0 3861 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3862 throw new SecurityException("Shell does not have permission to access user " 3863 + userHandle); 3864 } else if (userHandle < 0) { 3865 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3866 + Debug.getCallers(3)); 3867 } 3868 } 3869 } 3870 3871 private BasePermission findPermissionTreeLP(String permName) { 3872 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3873 if (permName.startsWith(bp.name) && 3874 permName.length() > bp.name.length() && 3875 permName.charAt(bp.name.length()) == '.') { 3876 return bp; 3877 } 3878 } 3879 return null; 3880 } 3881 3882 private BasePermission checkPermissionTreeLP(String permName) { 3883 if (permName != null) { 3884 BasePermission bp = findPermissionTreeLP(permName); 3885 if (bp != null) { 3886 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3887 return bp; 3888 } 3889 throw new SecurityException("Calling uid " 3890 + Binder.getCallingUid() 3891 + " is not allowed to add to permission tree " 3892 + bp.name + " owned by uid " + bp.uid); 3893 } 3894 } 3895 throw new SecurityException("No permission tree found for " + permName); 3896 } 3897 3898 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3899 if (s1 == null) { 3900 return s2 == null; 3901 } 3902 if (s2 == null) { 3903 return false; 3904 } 3905 if (s1.getClass() != s2.getClass()) { 3906 return false; 3907 } 3908 return s1.equals(s2); 3909 } 3910 3911 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3912 if (pi1.icon != pi2.icon) return false; 3913 if (pi1.logo != pi2.logo) return false; 3914 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3915 if (!compareStrings(pi1.name, pi2.name)) return false; 3916 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3917 // We'll take care of setting this one. 3918 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3919 // These are not currently stored in settings. 3920 //if (!compareStrings(pi1.group, pi2.group)) return false; 3921 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3922 //if (pi1.labelRes != pi2.labelRes) return false; 3923 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3924 return true; 3925 } 3926 3927 int permissionInfoFootprint(PermissionInfo info) { 3928 int size = info.name.length(); 3929 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3930 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3931 return size; 3932 } 3933 3934 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3935 int size = 0; 3936 for (BasePermission perm : mSettings.mPermissions.values()) { 3937 if (perm.uid == tree.uid) { 3938 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3939 } 3940 } 3941 return size; 3942 } 3943 3944 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3945 // We calculate the max size of permissions defined by this uid and throw 3946 // if that plus the size of 'info' would exceed our stated maximum. 3947 if (tree.uid != Process.SYSTEM_UID) { 3948 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3949 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3950 throw new SecurityException("Permission tree size cap exceeded"); 3951 } 3952 } 3953 } 3954 3955 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3956 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3957 throw new SecurityException("Label must be specified in permission"); 3958 } 3959 BasePermission tree = checkPermissionTreeLP(info.name); 3960 BasePermission bp = mSettings.mPermissions.get(info.name); 3961 boolean added = bp == null; 3962 boolean changed = true; 3963 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3964 if (added) { 3965 enforcePermissionCapLocked(info, tree); 3966 bp = new BasePermission(info.name, tree.sourcePackage, 3967 BasePermission.TYPE_DYNAMIC); 3968 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3969 throw new SecurityException( 3970 "Not allowed to modify non-dynamic permission " 3971 + info.name); 3972 } else { 3973 if (bp.protectionLevel == fixedLevel 3974 && bp.perm.owner.equals(tree.perm.owner) 3975 && bp.uid == tree.uid 3976 && comparePermissionInfos(bp.perm.info, info)) { 3977 changed = false; 3978 } 3979 } 3980 bp.protectionLevel = fixedLevel; 3981 info = new PermissionInfo(info); 3982 info.protectionLevel = fixedLevel; 3983 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3984 bp.perm.info.packageName = tree.perm.info.packageName; 3985 bp.uid = tree.uid; 3986 if (added) { 3987 mSettings.mPermissions.put(info.name, bp); 3988 } 3989 if (changed) { 3990 if (!async) { 3991 mSettings.writeLPr(); 3992 } else { 3993 scheduleWriteSettingsLocked(); 3994 } 3995 } 3996 return added; 3997 } 3998 3999 @Override 4000 public boolean addPermission(PermissionInfo info) { 4001 synchronized (mPackages) { 4002 return addPermissionLocked(info, false); 4003 } 4004 } 4005 4006 @Override 4007 public boolean addPermissionAsync(PermissionInfo info) { 4008 synchronized (mPackages) { 4009 return addPermissionLocked(info, true); 4010 } 4011 } 4012 4013 @Override 4014 public void removePermission(String name) { 4015 synchronized (mPackages) { 4016 checkPermissionTreeLP(name); 4017 BasePermission bp = mSettings.mPermissions.get(name); 4018 if (bp != null) { 4019 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4020 throw new SecurityException( 4021 "Not allowed to modify non-dynamic permission " 4022 + name); 4023 } 4024 mSettings.mPermissions.remove(name); 4025 mSettings.writeLPr(); 4026 } 4027 } 4028 } 4029 4030 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4031 BasePermission bp) { 4032 int index = pkg.requestedPermissions.indexOf(bp.name); 4033 if (index == -1) { 4034 throw new SecurityException("Package " + pkg.packageName 4035 + " has not requested permission " + bp.name); 4036 } 4037 if (!bp.isRuntime() && !bp.isDevelopment()) { 4038 throw new SecurityException("Permission " + bp.name 4039 + " is not a changeable permission type"); 4040 } 4041 } 4042 4043 @Override 4044 public void grantRuntimePermission(String packageName, String name, final int userId) { 4045 if (!sUserManager.exists(userId)) { 4046 Log.e(TAG, "No such user:" + userId); 4047 return; 4048 } 4049 4050 mContext.enforceCallingOrSelfPermission( 4051 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4052 "grantRuntimePermission"); 4053 4054 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4055 true /* requireFullPermission */, true /* checkShell */, 4056 "grantRuntimePermission"); 4057 4058 final int uid; 4059 final SettingBase sb; 4060 4061 synchronized (mPackages) { 4062 final PackageParser.Package pkg = mPackages.get(packageName); 4063 if (pkg == null) { 4064 throw new IllegalArgumentException("Unknown package: " + packageName); 4065 } 4066 4067 final BasePermission bp = mSettings.mPermissions.get(name); 4068 if (bp == null) { 4069 throw new IllegalArgumentException("Unknown permission: " + name); 4070 } 4071 4072 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4073 4074 // If a permission review is required for legacy apps we represent 4075 // their permissions as always granted runtime ones since we need 4076 // to keep the review required permission flag per user while an 4077 // install permission's state is shared across all users. 4078 if (Build.PERMISSIONS_REVIEW_REQUIRED 4079 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4080 && bp.isRuntime()) { 4081 return; 4082 } 4083 4084 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4085 sb = (SettingBase) pkg.mExtras; 4086 if (sb == null) { 4087 throw new IllegalArgumentException("Unknown package: " + packageName); 4088 } 4089 4090 final PermissionsState permissionsState = sb.getPermissionsState(); 4091 4092 final int flags = permissionsState.getPermissionFlags(name, userId); 4093 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4094 throw new SecurityException("Cannot grant system fixed permission " 4095 + name + " for package " + packageName); 4096 } 4097 4098 if (bp.isDevelopment()) { 4099 // Development permissions must be handled specially, since they are not 4100 // normal runtime permissions. For now they apply to all users. 4101 if (permissionsState.grantInstallPermission(bp) != 4102 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4103 scheduleWriteSettingsLocked(); 4104 } 4105 return; 4106 } 4107 4108 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4109 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4110 return; 4111 } 4112 4113 final int result = permissionsState.grantRuntimePermission(bp, userId); 4114 switch (result) { 4115 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4116 return; 4117 } 4118 4119 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4120 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4121 mHandler.post(new Runnable() { 4122 @Override 4123 public void run() { 4124 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4125 } 4126 }); 4127 } 4128 break; 4129 } 4130 4131 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4132 4133 // Not critical if that is lost - app has to request again. 4134 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4135 } 4136 4137 // Only need to do this if user is initialized. Otherwise it's a new user 4138 // and there are no processes running as the user yet and there's no need 4139 // to make an expensive call to remount processes for the changed permissions. 4140 if (READ_EXTERNAL_STORAGE.equals(name) 4141 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4142 final long token = Binder.clearCallingIdentity(); 4143 try { 4144 if (sUserManager.isInitialized(userId)) { 4145 MountServiceInternal mountServiceInternal = LocalServices.getService( 4146 MountServiceInternal.class); 4147 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4148 } 4149 } finally { 4150 Binder.restoreCallingIdentity(token); 4151 } 4152 } 4153 } 4154 4155 @Override 4156 public void revokeRuntimePermission(String packageName, String name, int userId) { 4157 if (!sUserManager.exists(userId)) { 4158 Log.e(TAG, "No such user:" + userId); 4159 return; 4160 } 4161 4162 mContext.enforceCallingOrSelfPermission( 4163 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4164 "revokeRuntimePermission"); 4165 4166 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4167 true /* requireFullPermission */, true /* checkShell */, 4168 "revokeRuntimePermission"); 4169 4170 final int appId; 4171 4172 synchronized (mPackages) { 4173 final PackageParser.Package pkg = mPackages.get(packageName); 4174 if (pkg == null) { 4175 throw new IllegalArgumentException("Unknown package: " + packageName); 4176 } 4177 4178 final BasePermission bp = mSettings.mPermissions.get(name); 4179 if (bp == null) { 4180 throw new IllegalArgumentException("Unknown permission: " + name); 4181 } 4182 4183 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4184 4185 // If a permission review is required for legacy apps we represent 4186 // their permissions as always granted runtime ones since we need 4187 // to keep the review required permission flag per user while an 4188 // install permission's state is shared across all users. 4189 if (Build.PERMISSIONS_REVIEW_REQUIRED 4190 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4191 && bp.isRuntime()) { 4192 return; 4193 } 4194 4195 SettingBase sb = (SettingBase) pkg.mExtras; 4196 if (sb == null) { 4197 throw new IllegalArgumentException("Unknown package: " + packageName); 4198 } 4199 4200 final PermissionsState permissionsState = sb.getPermissionsState(); 4201 4202 final int flags = permissionsState.getPermissionFlags(name, userId); 4203 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4204 throw new SecurityException("Cannot revoke system fixed permission " 4205 + name + " for package " + packageName); 4206 } 4207 4208 if (bp.isDevelopment()) { 4209 // Development permissions must be handled specially, since they are not 4210 // normal runtime permissions. For now they apply to all users. 4211 if (permissionsState.revokeInstallPermission(bp) != 4212 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4213 scheduleWriteSettingsLocked(); 4214 } 4215 return; 4216 } 4217 4218 if (permissionsState.revokeRuntimePermission(bp, userId) == 4219 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4220 return; 4221 } 4222 4223 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4224 4225 // Critical, after this call app should never have the permission. 4226 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4227 4228 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4229 } 4230 4231 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4232 } 4233 4234 @Override 4235 public void resetRuntimePermissions() { 4236 mContext.enforceCallingOrSelfPermission( 4237 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4238 "revokeRuntimePermission"); 4239 4240 int callingUid = Binder.getCallingUid(); 4241 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4242 mContext.enforceCallingOrSelfPermission( 4243 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4244 "resetRuntimePermissions"); 4245 } 4246 4247 synchronized (mPackages) { 4248 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4249 for (int userId : UserManagerService.getInstance().getUserIds()) { 4250 final int packageCount = mPackages.size(); 4251 for (int i = 0; i < packageCount; i++) { 4252 PackageParser.Package pkg = mPackages.valueAt(i); 4253 if (!(pkg.mExtras instanceof PackageSetting)) { 4254 continue; 4255 } 4256 PackageSetting ps = (PackageSetting) pkg.mExtras; 4257 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4258 } 4259 } 4260 } 4261 } 4262 4263 @Override 4264 public int getPermissionFlags(String name, String packageName, int userId) { 4265 if (!sUserManager.exists(userId)) { 4266 return 0; 4267 } 4268 4269 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4270 4271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4272 true /* requireFullPermission */, false /* checkShell */, 4273 "getPermissionFlags"); 4274 4275 synchronized (mPackages) { 4276 final PackageParser.Package pkg = mPackages.get(packageName); 4277 if (pkg == null) { 4278 return 0; 4279 } 4280 4281 final BasePermission bp = mSettings.mPermissions.get(name); 4282 if (bp == null) { 4283 return 0; 4284 } 4285 4286 SettingBase sb = (SettingBase) pkg.mExtras; 4287 if (sb == null) { 4288 return 0; 4289 } 4290 4291 PermissionsState permissionsState = sb.getPermissionsState(); 4292 return permissionsState.getPermissionFlags(name, userId); 4293 } 4294 } 4295 4296 @Override 4297 public void updatePermissionFlags(String name, String packageName, int flagMask, 4298 int flagValues, int userId) { 4299 if (!sUserManager.exists(userId)) { 4300 return; 4301 } 4302 4303 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4304 4305 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4306 true /* requireFullPermission */, true /* checkShell */, 4307 "updatePermissionFlags"); 4308 4309 // Only the system can change these flags and nothing else. 4310 if (getCallingUid() != Process.SYSTEM_UID) { 4311 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4312 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4313 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4314 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4315 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4316 } 4317 4318 synchronized (mPackages) { 4319 final PackageParser.Package pkg = mPackages.get(packageName); 4320 if (pkg == null) { 4321 throw new IllegalArgumentException("Unknown package: " + packageName); 4322 } 4323 4324 final BasePermission bp = mSettings.mPermissions.get(name); 4325 if (bp == null) { 4326 throw new IllegalArgumentException("Unknown permission: " + name); 4327 } 4328 4329 SettingBase sb = (SettingBase) pkg.mExtras; 4330 if (sb == null) { 4331 throw new IllegalArgumentException("Unknown package: " + packageName); 4332 } 4333 4334 PermissionsState permissionsState = sb.getPermissionsState(); 4335 4336 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4337 4338 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4339 // Install and runtime permissions are stored in different places, 4340 // so figure out what permission changed and persist the change. 4341 if (permissionsState.getInstallPermissionState(name) != null) { 4342 scheduleWriteSettingsLocked(); 4343 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4344 || hadState) { 4345 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4346 } 4347 } 4348 } 4349 } 4350 4351 /** 4352 * Update the permission flags for all packages and runtime permissions of a user in order 4353 * to allow device or profile owner to remove POLICY_FIXED. 4354 */ 4355 @Override 4356 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4357 if (!sUserManager.exists(userId)) { 4358 return; 4359 } 4360 4361 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4362 4363 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4364 true /* requireFullPermission */, true /* checkShell */, 4365 "updatePermissionFlagsForAllApps"); 4366 4367 // Only the system can change system fixed flags. 4368 if (getCallingUid() != Process.SYSTEM_UID) { 4369 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4370 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4371 } 4372 4373 synchronized (mPackages) { 4374 boolean changed = false; 4375 final int packageCount = mPackages.size(); 4376 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4377 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4378 SettingBase sb = (SettingBase) pkg.mExtras; 4379 if (sb == null) { 4380 continue; 4381 } 4382 PermissionsState permissionsState = sb.getPermissionsState(); 4383 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4384 userId, flagMask, flagValues); 4385 } 4386 if (changed) { 4387 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4388 } 4389 } 4390 } 4391 4392 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4393 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4394 != PackageManager.PERMISSION_GRANTED 4395 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4396 != PackageManager.PERMISSION_GRANTED) { 4397 throw new SecurityException(message + " requires " 4398 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4399 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4400 } 4401 } 4402 4403 @Override 4404 public boolean shouldShowRequestPermissionRationale(String permissionName, 4405 String packageName, int userId) { 4406 if (UserHandle.getCallingUserId() != userId) { 4407 mContext.enforceCallingPermission( 4408 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4409 "canShowRequestPermissionRationale for user " + userId); 4410 } 4411 4412 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4413 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4414 return false; 4415 } 4416 4417 if (checkPermission(permissionName, packageName, userId) 4418 == PackageManager.PERMISSION_GRANTED) { 4419 return false; 4420 } 4421 4422 final int flags; 4423 4424 final long identity = Binder.clearCallingIdentity(); 4425 try { 4426 flags = getPermissionFlags(permissionName, 4427 packageName, userId); 4428 } finally { 4429 Binder.restoreCallingIdentity(identity); 4430 } 4431 4432 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4433 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4434 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4435 4436 if ((flags & fixedFlags) != 0) { 4437 return false; 4438 } 4439 4440 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4441 } 4442 4443 @Override 4444 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4445 mContext.enforceCallingOrSelfPermission( 4446 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4447 "addOnPermissionsChangeListener"); 4448 4449 synchronized (mPackages) { 4450 mOnPermissionChangeListeners.addListenerLocked(listener); 4451 } 4452 } 4453 4454 @Override 4455 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4456 synchronized (mPackages) { 4457 mOnPermissionChangeListeners.removeListenerLocked(listener); 4458 } 4459 } 4460 4461 @Override 4462 public boolean isProtectedBroadcast(String actionName) { 4463 synchronized (mPackages) { 4464 if (mProtectedBroadcasts.contains(actionName)) { 4465 return true; 4466 } else if (actionName != null) { 4467 // TODO: remove these terrible hacks 4468 if (actionName.startsWith("android.net.netmon.lingerExpired") 4469 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4470 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4471 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4472 return true; 4473 } 4474 } 4475 } 4476 return false; 4477 } 4478 4479 @Override 4480 public int checkSignatures(String pkg1, String pkg2) { 4481 synchronized (mPackages) { 4482 final PackageParser.Package p1 = mPackages.get(pkg1); 4483 final PackageParser.Package p2 = mPackages.get(pkg2); 4484 if (p1 == null || p1.mExtras == null 4485 || p2 == null || p2.mExtras == null) { 4486 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4487 } 4488 return compareSignatures(p1.mSignatures, p2.mSignatures); 4489 } 4490 } 4491 4492 @Override 4493 public int checkUidSignatures(int uid1, int uid2) { 4494 // Map to base uids. 4495 uid1 = UserHandle.getAppId(uid1); 4496 uid2 = UserHandle.getAppId(uid2); 4497 // reader 4498 synchronized (mPackages) { 4499 Signature[] s1; 4500 Signature[] s2; 4501 Object obj = mSettings.getUserIdLPr(uid1); 4502 if (obj != null) { 4503 if (obj instanceof SharedUserSetting) { 4504 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4505 } else if (obj instanceof PackageSetting) { 4506 s1 = ((PackageSetting)obj).signatures.mSignatures; 4507 } else { 4508 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4509 } 4510 } else { 4511 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4512 } 4513 obj = mSettings.getUserIdLPr(uid2); 4514 if (obj != null) { 4515 if (obj instanceof SharedUserSetting) { 4516 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4517 } else if (obj instanceof PackageSetting) { 4518 s2 = ((PackageSetting)obj).signatures.mSignatures; 4519 } else { 4520 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4521 } 4522 } else { 4523 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4524 } 4525 return compareSignatures(s1, s2); 4526 } 4527 } 4528 4529 /** 4530 * This method should typically only be used when granting or revoking 4531 * permissions, since the app may immediately restart after this call. 4532 * <p> 4533 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4534 * guard your work against the app being relaunched. 4535 */ 4536 private void killUid(int appId, int userId, String reason) { 4537 final long identity = Binder.clearCallingIdentity(); 4538 try { 4539 IActivityManager am = ActivityManagerNative.getDefault(); 4540 if (am != null) { 4541 try { 4542 am.killUid(appId, userId, reason); 4543 } catch (RemoteException e) { 4544 /* ignore - same process */ 4545 } 4546 } 4547 } finally { 4548 Binder.restoreCallingIdentity(identity); 4549 } 4550 } 4551 4552 /** 4553 * Compares two sets of signatures. Returns: 4554 * <br /> 4555 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4556 * <br /> 4557 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4558 * <br /> 4559 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4560 * <br /> 4561 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4562 * <br /> 4563 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4564 */ 4565 static int compareSignatures(Signature[] s1, Signature[] s2) { 4566 if (s1 == null) { 4567 return s2 == null 4568 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4569 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4570 } 4571 4572 if (s2 == null) { 4573 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4574 } 4575 4576 if (s1.length != s2.length) { 4577 return PackageManager.SIGNATURE_NO_MATCH; 4578 } 4579 4580 // Since both signature sets are of size 1, we can compare without HashSets. 4581 if (s1.length == 1) { 4582 return s1[0].equals(s2[0]) ? 4583 PackageManager.SIGNATURE_MATCH : 4584 PackageManager.SIGNATURE_NO_MATCH; 4585 } 4586 4587 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4588 for (Signature sig : s1) { 4589 set1.add(sig); 4590 } 4591 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4592 for (Signature sig : s2) { 4593 set2.add(sig); 4594 } 4595 // Make sure s2 contains all signatures in s1. 4596 if (set1.equals(set2)) { 4597 return PackageManager.SIGNATURE_MATCH; 4598 } 4599 return PackageManager.SIGNATURE_NO_MATCH; 4600 } 4601 4602 /** 4603 * If the database version for this type of package (internal storage or 4604 * external storage) is less than the version where package signatures 4605 * were updated, return true. 4606 */ 4607 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4608 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4609 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4610 } 4611 4612 /** 4613 * Used for backward compatibility to make sure any packages with 4614 * certificate chains get upgraded to the new style. {@code existingSigs} 4615 * will be in the old format (since they were stored on disk from before the 4616 * system upgrade) and {@code scannedSigs} will be in the newer format. 4617 */ 4618 private int compareSignaturesCompat(PackageSignatures existingSigs, 4619 PackageParser.Package scannedPkg) { 4620 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4621 return PackageManager.SIGNATURE_NO_MATCH; 4622 } 4623 4624 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4625 for (Signature sig : existingSigs.mSignatures) { 4626 existingSet.add(sig); 4627 } 4628 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4629 for (Signature sig : scannedPkg.mSignatures) { 4630 try { 4631 Signature[] chainSignatures = sig.getChainSignatures(); 4632 for (Signature chainSig : chainSignatures) { 4633 scannedCompatSet.add(chainSig); 4634 } 4635 } catch (CertificateEncodingException e) { 4636 scannedCompatSet.add(sig); 4637 } 4638 } 4639 /* 4640 * Make sure the expanded scanned set contains all signatures in the 4641 * existing one. 4642 */ 4643 if (scannedCompatSet.equals(existingSet)) { 4644 // Migrate the old signatures to the new scheme. 4645 existingSigs.assignSignatures(scannedPkg.mSignatures); 4646 // The new KeySets will be re-added later in the scanning process. 4647 synchronized (mPackages) { 4648 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4649 } 4650 return PackageManager.SIGNATURE_MATCH; 4651 } 4652 return PackageManager.SIGNATURE_NO_MATCH; 4653 } 4654 4655 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4656 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4657 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4658 } 4659 4660 private int compareSignaturesRecover(PackageSignatures existingSigs, 4661 PackageParser.Package scannedPkg) { 4662 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4663 return PackageManager.SIGNATURE_NO_MATCH; 4664 } 4665 4666 String msg = null; 4667 try { 4668 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4669 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4670 + scannedPkg.packageName); 4671 return PackageManager.SIGNATURE_MATCH; 4672 } 4673 } catch (CertificateException e) { 4674 msg = e.getMessage(); 4675 } 4676 4677 logCriticalInfo(Log.INFO, 4678 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4679 return PackageManager.SIGNATURE_NO_MATCH; 4680 } 4681 4682 @Override 4683 public List<String> getAllPackages() { 4684 synchronized (mPackages) { 4685 return new ArrayList<String>(mPackages.keySet()); 4686 } 4687 } 4688 4689 @Override 4690 public String[] getPackagesForUid(int uid) { 4691 uid = UserHandle.getAppId(uid); 4692 // reader 4693 synchronized (mPackages) { 4694 Object obj = mSettings.getUserIdLPr(uid); 4695 if (obj instanceof SharedUserSetting) { 4696 final SharedUserSetting sus = (SharedUserSetting) obj; 4697 final int N = sus.packages.size(); 4698 final String[] res = new String[N]; 4699 final Iterator<PackageSetting> it = sus.packages.iterator(); 4700 int i = 0; 4701 while (it.hasNext()) { 4702 res[i++] = it.next().name; 4703 } 4704 return res; 4705 } else if (obj instanceof PackageSetting) { 4706 final PackageSetting ps = (PackageSetting) obj; 4707 return new String[] { ps.name }; 4708 } 4709 } 4710 return null; 4711 } 4712 4713 @Override 4714 public String getNameForUid(int uid) { 4715 // reader 4716 synchronized (mPackages) { 4717 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4718 if (obj instanceof SharedUserSetting) { 4719 final SharedUserSetting sus = (SharedUserSetting) obj; 4720 return sus.name + ":" + sus.userId; 4721 } else if (obj instanceof PackageSetting) { 4722 final PackageSetting ps = (PackageSetting) obj; 4723 return ps.name; 4724 } 4725 } 4726 return null; 4727 } 4728 4729 @Override 4730 public int getUidForSharedUser(String sharedUserName) { 4731 if(sharedUserName == null) { 4732 return -1; 4733 } 4734 // reader 4735 synchronized (mPackages) { 4736 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4737 if (suid == null) { 4738 return -1; 4739 } 4740 return suid.userId; 4741 } 4742 } 4743 4744 @Override 4745 public int getFlagsForUid(int uid) { 4746 synchronized (mPackages) { 4747 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4748 if (obj instanceof SharedUserSetting) { 4749 final SharedUserSetting sus = (SharedUserSetting) obj; 4750 return sus.pkgFlags; 4751 } else if (obj instanceof PackageSetting) { 4752 final PackageSetting ps = (PackageSetting) obj; 4753 return ps.pkgFlags; 4754 } 4755 } 4756 return 0; 4757 } 4758 4759 @Override 4760 public int getPrivateFlagsForUid(int uid) { 4761 synchronized (mPackages) { 4762 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4763 if (obj instanceof SharedUserSetting) { 4764 final SharedUserSetting sus = (SharedUserSetting) obj; 4765 return sus.pkgPrivateFlags; 4766 } else if (obj instanceof PackageSetting) { 4767 final PackageSetting ps = (PackageSetting) obj; 4768 return ps.pkgPrivateFlags; 4769 } 4770 } 4771 return 0; 4772 } 4773 4774 @Override 4775 public boolean isUidPrivileged(int uid) { 4776 uid = UserHandle.getAppId(uid); 4777 // reader 4778 synchronized (mPackages) { 4779 Object obj = mSettings.getUserIdLPr(uid); 4780 if (obj instanceof SharedUserSetting) { 4781 final SharedUserSetting sus = (SharedUserSetting) obj; 4782 final Iterator<PackageSetting> it = sus.packages.iterator(); 4783 while (it.hasNext()) { 4784 if (it.next().isPrivileged()) { 4785 return true; 4786 } 4787 } 4788 } else if (obj instanceof PackageSetting) { 4789 final PackageSetting ps = (PackageSetting) obj; 4790 return ps.isPrivileged(); 4791 } 4792 } 4793 return false; 4794 } 4795 4796 @Override 4797 public String[] getAppOpPermissionPackages(String permissionName) { 4798 synchronized (mPackages) { 4799 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4800 if (pkgs == null) { 4801 return null; 4802 } 4803 return pkgs.toArray(new String[pkgs.size()]); 4804 } 4805 } 4806 4807 @Override 4808 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4809 int flags, int userId) { 4810 try { 4811 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4812 4813 if (!sUserManager.exists(userId)) return null; 4814 flags = updateFlagsForResolve(flags, userId, intent); 4815 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4816 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4817 4818 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4819 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4820 flags, userId); 4821 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4822 4823 final ResolveInfo bestChoice = 4824 chooseBestActivity(intent, resolvedType, flags, query, userId); 4825 4826 if (isEphemeralAllowed(intent, query, userId)) { 4827 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4828 final EphemeralResolveInfo ai = 4829 getEphemeralResolveInfo(intent, resolvedType, userId); 4830 if (ai != null) { 4831 if (DEBUG_EPHEMERAL) { 4832 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4833 } 4834 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4835 bestChoice.ephemeralResolveInfo = ai; 4836 } 4837 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4838 } 4839 return bestChoice; 4840 } finally { 4841 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4842 } 4843 } 4844 4845 @Override 4846 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4847 IntentFilter filter, int match, ComponentName activity) { 4848 final int userId = UserHandle.getCallingUserId(); 4849 if (DEBUG_PREFERRED) { 4850 Log.v(TAG, "setLastChosenActivity intent=" + intent 4851 + " resolvedType=" + resolvedType 4852 + " flags=" + flags 4853 + " filter=" + filter 4854 + " match=" + match 4855 + " activity=" + activity); 4856 filter.dump(new PrintStreamPrinter(System.out), " "); 4857 } 4858 intent.setComponent(null); 4859 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4860 userId); 4861 // Find any earlier preferred or last chosen entries and nuke them 4862 findPreferredActivity(intent, resolvedType, 4863 flags, query, 0, false, true, false, userId); 4864 // Add the new activity as the last chosen for this filter 4865 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4866 "Setting last chosen"); 4867 } 4868 4869 @Override 4870 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4871 final int userId = UserHandle.getCallingUserId(); 4872 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4873 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4874 userId); 4875 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4876 false, false, false, userId); 4877 } 4878 4879 4880 private boolean isEphemeralAllowed( 4881 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4882 // Short circuit and return early if possible. 4883 if (DISABLE_EPHEMERAL_APPS) { 4884 return false; 4885 } 4886 final int callingUser = UserHandle.getCallingUserId(); 4887 if (callingUser != UserHandle.USER_SYSTEM) { 4888 return false; 4889 } 4890 if (mEphemeralResolverConnection == null) { 4891 return false; 4892 } 4893 if (intent.getComponent() != null) { 4894 return false; 4895 } 4896 if (intent.getPackage() != null) { 4897 return false; 4898 } 4899 final boolean isWebUri = hasWebURI(intent); 4900 if (!isWebUri) { 4901 return false; 4902 } 4903 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4904 synchronized (mPackages) { 4905 final int count = resolvedActivites.size(); 4906 for (int n = 0; n < count; n++) { 4907 ResolveInfo info = resolvedActivites.get(n); 4908 String packageName = info.activityInfo.packageName; 4909 PackageSetting ps = mSettings.mPackages.get(packageName); 4910 if (ps != null) { 4911 // Try to get the status from User settings first 4912 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4913 int status = (int) (packedStatus >> 32); 4914 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4915 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4916 if (DEBUG_EPHEMERAL) { 4917 Slog.v(TAG, "DENY ephemeral apps;" 4918 + " pkg: " + packageName + ", status: " + status); 4919 } 4920 return false; 4921 } 4922 } 4923 } 4924 } 4925 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4926 return true; 4927 } 4928 4929 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4930 int userId) { 4931 MessageDigest digest = null; 4932 try { 4933 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4934 } catch (NoSuchAlgorithmException e) { 4935 // If we can't create a digest, ignore ephemeral apps. 4936 return null; 4937 } 4938 4939 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4940 final byte[] digestBytes = digest.digest(hostBytes); 4941 int shaPrefix = 4942 digestBytes[0] << 24 4943 | digestBytes[1] << 16 4944 | digestBytes[2] << 8 4945 | digestBytes[3] << 0; 4946 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4947 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4948 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4949 // No hash prefix match; there are no ephemeral apps for this domain. 4950 return null; 4951 } 4952 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4953 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4954 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4955 continue; 4956 } 4957 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4958 // No filters; this should never happen. 4959 if (filters.isEmpty()) { 4960 continue; 4961 } 4962 // We have a domain match; resolve the filters to see if anything matches. 4963 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4964 for (int j = filters.size() - 1; j >= 0; --j) { 4965 final EphemeralResolveIntentInfo intentInfo = 4966 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4967 ephemeralResolver.addFilter(intentInfo); 4968 } 4969 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4970 intent, resolvedType, false /*defaultOnly*/, userId); 4971 if (!matchedResolveInfoList.isEmpty()) { 4972 return matchedResolveInfoList.get(0); 4973 } 4974 } 4975 // Hash or filter mis-match; no ephemeral apps for this domain. 4976 return null; 4977 } 4978 4979 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4980 int flags, List<ResolveInfo> query, int userId) { 4981 if (query != null) { 4982 final int N = query.size(); 4983 if (N == 1) { 4984 return query.get(0); 4985 } else if (N > 1) { 4986 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4987 // If there is more than one activity with the same priority, 4988 // then let the user decide between them. 4989 ResolveInfo r0 = query.get(0); 4990 ResolveInfo r1 = query.get(1); 4991 if (DEBUG_INTENT_MATCHING || debug) { 4992 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4993 + r1.activityInfo.name + "=" + r1.priority); 4994 } 4995 // If the first activity has a higher priority, or a different 4996 // default, then it is always desirable to pick it. 4997 if (r0.priority != r1.priority 4998 || r0.preferredOrder != r1.preferredOrder 4999 || r0.isDefault != r1.isDefault) { 5000 return query.get(0); 5001 } 5002 // If we have saved a preference for a preferred activity for 5003 // this Intent, use that. 5004 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5005 flags, query, r0.priority, true, false, debug, userId); 5006 if (ri != null) { 5007 return ri; 5008 } 5009 ri = new ResolveInfo(mResolveInfo); 5010 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5011 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5012 // If all of the options come from the same package, show the application's 5013 // label and icon instead of the generic resolver's. 5014 // Some calls like Intent.resolveActivityInfo query the ResolveInfo from here 5015 // and then throw away the ResolveInfo itself, meaning that the caller loses 5016 // the resolvePackageName. Therefore the activityInfo.labelRes above provides 5017 // a fallback for this case; we only set the target package's resources on 5018 // the ResolveInfo, not the ActivityInfo. 5019 final String intentPackage = intent.getPackage(); 5020 if (!TextUtils.isEmpty(intentPackage) && allHavePackage(query, intentPackage)) { 5021 final ApplicationInfo appi = query.get(0).activityInfo.applicationInfo; 5022 ri.resolvePackageName = intentPackage; 5023 if (userNeedsBadging(userId)) { 5024 ri.noResourceId = true; 5025 } else { 5026 ri.icon = appi.icon; 5027 } 5028 ri.iconResourceId = appi.icon; 5029 ri.labelRes = appi.labelRes; 5030 } 5031 ri.activityInfo.applicationInfo = new ApplicationInfo( 5032 ri.activityInfo.applicationInfo); 5033 if (userId != 0) { 5034 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5035 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5036 } 5037 // Make sure that the resolver is displayable in car mode 5038 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5039 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5040 return ri; 5041 } 5042 } 5043 return null; 5044 } 5045 5046 /** 5047 * Return true if the given list is not empty and all of its contents have 5048 * an activityInfo with the given package name. 5049 */ 5050 private boolean allHavePackage(List<ResolveInfo> list, String packageName) { 5051 if (ArrayUtils.isEmpty(list)) { 5052 return false; 5053 } 5054 for (int i = 0, N = list.size(); i < N; i++) { 5055 final ResolveInfo ri = list.get(i); 5056 final ActivityInfo ai = ri != null ? ri.activityInfo : null; 5057 if (ai == null || !packageName.equals(ai.packageName)) { 5058 return false; 5059 } 5060 } 5061 return true; 5062 } 5063 5064 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5065 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5066 final int N = query.size(); 5067 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5068 .get(userId); 5069 // Get the list of persistent preferred activities that handle the intent 5070 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5071 List<PersistentPreferredActivity> pprefs = ppir != null 5072 ? ppir.queryIntent(intent, resolvedType, 5073 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5074 : null; 5075 if (pprefs != null && pprefs.size() > 0) { 5076 final int M = pprefs.size(); 5077 for (int i=0; i<M; i++) { 5078 final PersistentPreferredActivity ppa = pprefs.get(i); 5079 if (DEBUG_PREFERRED || debug) { 5080 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5081 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5082 + "\n component=" + ppa.mComponent); 5083 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5084 } 5085 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5086 flags | MATCH_DISABLED_COMPONENTS, userId); 5087 if (DEBUG_PREFERRED || debug) { 5088 Slog.v(TAG, "Found persistent preferred activity:"); 5089 if (ai != null) { 5090 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5091 } else { 5092 Slog.v(TAG, " null"); 5093 } 5094 } 5095 if (ai == null) { 5096 // This previously registered persistent preferred activity 5097 // component is no longer known. Ignore it and do NOT remove it. 5098 continue; 5099 } 5100 for (int j=0; j<N; j++) { 5101 final ResolveInfo ri = query.get(j); 5102 if (!ri.activityInfo.applicationInfo.packageName 5103 .equals(ai.applicationInfo.packageName)) { 5104 continue; 5105 } 5106 if (!ri.activityInfo.name.equals(ai.name)) { 5107 continue; 5108 } 5109 // Found a persistent preference that can handle the intent. 5110 if (DEBUG_PREFERRED || debug) { 5111 Slog.v(TAG, "Returning persistent preferred activity: " + 5112 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5113 } 5114 return ri; 5115 } 5116 } 5117 } 5118 return null; 5119 } 5120 5121 // TODO: handle preferred activities missing while user has amnesia 5122 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5123 List<ResolveInfo> query, int priority, boolean always, 5124 boolean removeMatches, boolean debug, int userId) { 5125 if (!sUserManager.exists(userId)) return null; 5126 flags = updateFlagsForResolve(flags, userId, intent); 5127 // writer 5128 synchronized (mPackages) { 5129 if (intent.getSelector() != null) { 5130 intent = intent.getSelector(); 5131 } 5132 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5133 5134 // Try to find a matching persistent preferred activity. 5135 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5136 debug, userId); 5137 5138 // If a persistent preferred activity matched, use it. 5139 if (pri != null) { 5140 return pri; 5141 } 5142 5143 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5144 // Get the list of preferred activities that handle the intent 5145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5146 List<PreferredActivity> prefs = pir != null 5147 ? pir.queryIntent(intent, resolvedType, 5148 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5149 : null; 5150 if (prefs != null && prefs.size() > 0) { 5151 boolean changed = false; 5152 try { 5153 // First figure out how good the original match set is. 5154 // We will only allow preferred activities that came 5155 // from the same match quality. 5156 int match = 0; 5157 5158 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5159 5160 final int N = query.size(); 5161 for (int j=0; j<N; j++) { 5162 final ResolveInfo ri = query.get(j); 5163 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5164 + ": 0x" + Integer.toHexString(match)); 5165 if (ri.match > match) { 5166 match = ri.match; 5167 } 5168 } 5169 5170 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5171 + Integer.toHexString(match)); 5172 5173 match &= IntentFilter.MATCH_CATEGORY_MASK; 5174 final int M = prefs.size(); 5175 for (int i=0; i<M; i++) { 5176 final PreferredActivity pa = prefs.get(i); 5177 if (DEBUG_PREFERRED || debug) { 5178 Slog.v(TAG, "Checking PreferredActivity ds=" 5179 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5180 + "\n component=" + pa.mPref.mComponent); 5181 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5182 } 5183 if (pa.mPref.mMatch != match) { 5184 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5185 + Integer.toHexString(pa.mPref.mMatch)); 5186 continue; 5187 } 5188 // If it's not an "always" type preferred activity and that's what we're 5189 // looking for, skip it. 5190 if (always && !pa.mPref.mAlways) { 5191 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5192 continue; 5193 } 5194 final ActivityInfo ai = getActivityInfo( 5195 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5196 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5197 userId); 5198 if (DEBUG_PREFERRED || debug) { 5199 Slog.v(TAG, "Found preferred activity:"); 5200 if (ai != null) { 5201 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5202 } else { 5203 Slog.v(TAG, " null"); 5204 } 5205 } 5206 if (ai == null) { 5207 // This previously registered preferred activity 5208 // component is no longer known. Most likely an update 5209 // to the app was installed and in the new version this 5210 // component no longer exists. Clean it up by removing 5211 // it from the preferred activities list, and skip it. 5212 Slog.w(TAG, "Removing dangling preferred activity: " 5213 + pa.mPref.mComponent); 5214 pir.removeFilter(pa); 5215 changed = true; 5216 continue; 5217 } 5218 for (int j=0; j<N; j++) { 5219 final ResolveInfo ri = query.get(j); 5220 if (!ri.activityInfo.applicationInfo.packageName 5221 .equals(ai.applicationInfo.packageName)) { 5222 continue; 5223 } 5224 if (!ri.activityInfo.name.equals(ai.name)) { 5225 continue; 5226 } 5227 5228 if (removeMatches) { 5229 pir.removeFilter(pa); 5230 changed = true; 5231 if (DEBUG_PREFERRED) { 5232 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5233 } 5234 break; 5235 } 5236 5237 // Okay we found a previously set preferred or last chosen app. 5238 // If the result set is different from when this 5239 // was created, we need to clear it and re-ask the 5240 // user their preference, if we're looking for an "always" type entry. 5241 if (always && !pa.mPref.sameSet(query)) { 5242 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5243 + intent + " type " + resolvedType); 5244 if (DEBUG_PREFERRED) { 5245 Slog.v(TAG, "Removing preferred activity since set changed " 5246 + pa.mPref.mComponent); 5247 } 5248 pir.removeFilter(pa); 5249 // Re-add the filter as a "last chosen" entry (!always) 5250 PreferredActivity lastChosen = new PreferredActivity( 5251 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5252 pir.addFilter(lastChosen); 5253 changed = true; 5254 return null; 5255 } 5256 5257 // Yay! Either the set matched or we're looking for the last chosen 5258 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5259 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5260 return ri; 5261 } 5262 } 5263 } finally { 5264 if (changed) { 5265 if (DEBUG_PREFERRED) { 5266 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5267 } 5268 scheduleWritePackageRestrictionsLocked(userId); 5269 } 5270 } 5271 } 5272 } 5273 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5274 return null; 5275 } 5276 5277 /* 5278 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5279 */ 5280 @Override 5281 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5282 int targetUserId) { 5283 mContext.enforceCallingOrSelfPermission( 5284 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5285 List<CrossProfileIntentFilter> matches = 5286 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5287 if (matches != null) { 5288 int size = matches.size(); 5289 for (int i = 0; i < size; i++) { 5290 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5291 } 5292 } 5293 if (hasWebURI(intent)) { 5294 // cross-profile app linking works only towards the parent. 5295 final UserInfo parent = getProfileParent(sourceUserId); 5296 synchronized(mPackages) { 5297 int flags = updateFlagsForResolve(0, parent.id, intent); 5298 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5299 intent, resolvedType, flags, sourceUserId, parent.id); 5300 return xpDomainInfo != null; 5301 } 5302 } 5303 return false; 5304 } 5305 5306 private UserInfo getProfileParent(int userId) { 5307 final long identity = Binder.clearCallingIdentity(); 5308 try { 5309 return sUserManager.getProfileParent(userId); 5310 } finally { 5311 Binder.restoreCallingIdentity(identity); 5312 } 5313 } 5314 5315 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5316 String resolvedType, int userId) { 5317 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5318 if (resolver != null) { 5319 return resolver.queryIntent(intent, resolvedType, false, userId); 5320 } 5321 return null; 5322 } 5323 5324 @Override 5325 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5326 String resolvedType, int flags, int userId) { 5327 try { 5328 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5329 5330 return new ParceledListSlice<>( 5331 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5332 } finally { 5333 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5334 } 5335 } 5336 5337 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5338 String resolvedType, int flags, int userId) { 5339 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5340 flags = updateFlagsForResolve(flags, userId, intent); 5341 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5342 false /* requireFullPermission */, false /* checkShell */, 5343 "query intent activities"); 5344 ComponentName comp = intent.getComponent(); 5345 if (comp == null) { 5346 if (intent.getSelector() != null) { 5347 intent = intent.getSelector(); 5348 comp = intent.getComponent(); 5349 } 5350 } 5351 5352 if (comp != null) { 5353 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5354 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5355 if (ai != null) { 5356 final ResolveInfo ri = new ResolveInfo(); 5357 ri.activityInfo = ai; 5358 list.add(ri); 5359 } 5360 return list; 5361 } 5362 5363 // reader 5364 synchronized (mPackages) { 5365 final String pkgName = intent.getPackage(); 5366 if (pkgName == null) { 5367 List<CrossProfileIntentFilter> matchingFilters = 5368 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5369 // Check for results that need to skip the current profile. 5370 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5371 resolvedType, flags, userId); 5372 if (xpResolveInfo != null) { 5373 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5374 result.add(xpResolveInfo); 5375 return filterIfNotSystemUser(result, userId); 5376 } 5377 5378 // Check for results in the current profile. 5379 List<ResolveInfo> result = mActivities.queryIntent( 5380 intent, resolvedType, flags, userId); 5381 result = filterIfNotSystemUser(result, userId); 5382 5383 // Check for cross profile results. 5384 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5385 xpResolveInfo = queryCrossProfileIntents( 5386 matchingFilters, intent, resolvedType, flags, userId, 5387 hasNonNegativePriorityResult); 5388 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5389 boolean isVisibleToUser = filterIfNotSystemUser( 5390 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5391 if (isVisibleToUser) { 5392 result.add(xpResolveInfo); 5393 Collections.sort(result, mResolvePrioritySorter); 5394 } 5395 } 5396 if (hasWebURI(intent)) { 5397 CrossProfileDomainInfo xpDomainInfo = null; 5398 final UserInfo parent = getProfileParent(userId); 5399 if (parent != null) { 5400 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5401 flags, userId, parent.id); 5402 } 5403 if (xpDomainInfo != null) { 5404 if (xpResolveInfo != null) { 5405 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5406 // in the result. 5407 result.remove(xpResolveInfo); 5408 } 5409 if (result.size() == 0) { 5410 result.add(xpDomainInfo.resolveInfo); 5411 return result; 5412 } 5413 } else if (result.size() <= 1) { 5414 return result; 5415 } 5416 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5417 xpDomainInfo, userId); 5418 Collections.sort(result, mResolvePrioritySorter); 5419 } 5420 return result; 5421 } 5422 final PackageParser.Package pkg = mPackages.get(pkgName); 5423 if (pkg != null) { 5424 return filterIfNotSystemUser( 5425 mActivities.queryIntentForPackage( 5426 intent, resolvedType, flags, pkg.activities, userId), 5427 userId); 5428 } 5429 return new ArrayList<ResolveInfo>(); 5430 } 5431 } 5432 5433 private static class CrossProfileDomainInfo { 5434 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5435 ResolveInfo resolveInfo; 5436 /* Best domain verification status of the activities found in the other profile */ 5437 int bestDomainVerificationStatus; 5438 } 5439 5440 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5441 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5442 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5443 sourceUserId)) { 5444 return null; 5445 } 5446 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5447 resolvedType, flags, parentUserId); 5448 5449 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5450 return null; 5451 } 5452 CrossProfileDomainInfo result = null; 5453 int size = resultTargetUser.size(); 5454 for (int i = 0; i < size; i++) { 5455 ResolveInfo riTargetUser = resultTargetUser.get(i); 5456 // Intent filter verification is only for filters that specify a host. So don't return 5457 // those that handle all web uris. 5458 if (riTargetUser.handleAllWebDataURI) { 5459 continue; 5460 } 5461 String packageName = riTargetUser.activityInfo.packageName; 5462 PackageSetting ps = mSettings.mPackages.get(packageName); 5463 if (ps == null) { 5464 continue; 5465 } 5466 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5467 int status = (int)(verificationState >> 32); 5468 if (result == null) { 5469 result = new CrossProfileDomainInfo(); 5470 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5471 sourceUserId, parentUserId); 5472 result.bestDomainVerificationStatus = status; 5473 } else { 5474 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5475 result.bestDomainVerificationStatus); 5476 } 5477 } 5478 // Don't consider matches with status NEVER across profiles. 5479 if (result != null && result.bestDomainVerificationStatus 5480 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5481 return null; 5482 } 5483 return result; 5484 } 5485 5486 /** 5487 * Verification statuses are ordered from the worse to the best, except for 5488 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5489 */ 5490 private int bestDomainVerificationStatus(int status1, int status2) { 5491 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5492 return status2; 5493 } 5494 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5495 return status1; 5496 } 5497 return (int) MathUtils.max(status1, status2); 5498 } 5499 5500 private boolean isUserEnabled(int userId) { 5501 long callingId = Binder.clearCallingIdentity(); 5502 try { 5503 UserInfo userInfo = sUserManager.getUserInfo(userId); 5504 return userInfo != null && userInfo.isEnabled(); 5505 } finally { 5506 Binder.restoreCallingIdentity(callingId); 5507 } 5508 } 5509 5510 /** 5511 * Filter out activities with systemUserOnly flag set, when current user is not System. 5512 * 5513 * @return filtered list 5514 */ 5515 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5516 if (userId == UserHandle.USER_SYSTEM) { 5517 return resolveInfos; 5518 } 5519 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5520 ResolveInfo info = resolveInfos.get(i); 5521 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5522 resolveInfos.remove(i); 5523 } 5524 } 5525 return resolveInfos; 5526 } 5527 5528 /** 5529 * @param resolveInfos list of resolve infos in descending priority order 5530 * @return if the list contains a resolve info with non-negative priority 5531 */ 5532 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5533 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5534 } 5535 5536 private static boolean hasWebURI(Intent intent) { 5537 if (intent.getData() == null) { 5538 return false; 5539 } 5540 final String scheme = intent.getScheme(); 5541 if (TextUtils.isEmpty(scheme)) { 5542 return false; 5543 } 5544 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5545 } 5546 5547 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5548 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5549 int userId) { 5550 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5551 5552 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5553 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5554 candidates.size()); 5555 } 5556 5557 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5558 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5559 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5560 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5561 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5562 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5563 5564 synchronized (mPackages) { 5565 final int count = candidates.size(); 5566 // First, try to use linked apps. Partition the candidates into four lists: 5567 // one for the final results, one for the "do not use ever", one for "undefined status" 5568 // and finally one for "browser app type". 5569 for (int n=0; n<count; n++) { 5570 ResolveInfo info = candidates.get(n); 5571 String packageName = info.activityInfo.packageName; 5572 PackageSetting ps = mSettings.mPackages.get(packageName); 5573 if (ps != null) { 5574 // Add to the special match all list (Browser use case) 5575 if (info.handleAllWebDataURI) { 5576 matchAllList.add(info); 5577 continue; 5578 } 5579 // Try to get the status from User settings first 5580 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5581 int status = (int)(packedStatus >> 32); 5582 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5583 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5584 if (DEBUG_DOMAIN_VERIFICATION) { 5585 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5586 + " : linkgen=" + linkGeneration); 5587 } 5588 // Use link-enabled generation as preferredOrder, i.e. 5589 // prefer newly-enabled over earlier-enabled. 5590 info.preferredOrder = linkGeneration; 5591 alwaysList.add(info); 5592 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5593 if (DEBUG_DOMAIN_VERIFICATION) { 5594 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5595 } 5596 neverList.add(info); 5597 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5598 if (DEBUG_DOMAIN_VERIFICATION) { 5599 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5600 } 5601 alwaysAskList.add(info); 5602 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5603 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5604 if (DEBUG_DOMAIN_VERIFICATION) { 5605 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5606 } 5607 undefinedList.add(info); 5608 } 5609 } 5610 } 5611 5612 // We'll want to include browser possibilities in a few cases 5613 boolean includeBrowser = false; 5614 5615 // First try to add the "always" resolution(s) for the current user, if any 5616 if (alwaysList.size() > 0) { 5617 result.addAll(alwaysList); 5618 } else { 5619 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5620 result.addAll(undefinedList); 5621 // Maybe add one for the other profile. 5622 if (xpDomainInfo != null && ( 5623 xpDomainInfo.bestDomainVerificationStatus 5624 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5625 result.add(xpDomainInfo.resolveInfo); 5626 } 5627 includeBrowser = true; 5628 } 5629 5630 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5631 // If there were 'always' entries their preferred order has been set, so we also 5632 // back that off to make the alternatives equivalent 5633 if (alwaysAskList.size() > 0) { 5634 for (ResolveInfo i : result) { 5635 i.preferredOrder = 0; 5636 } 5637 result.addAll(alwaysAskList); 5638 includeBrowser = true; 5639 } 5640 5641 if (includeBrowser) { 5642 // Also add browsers (all of them or only the default one) 5643 if (DEBUG_DOMAIN_VERIFICATION) { 5644 Slog.v(TAG, " ...including browsers in candidate set"); 5645 } 5646 if ((matchFlags & MATCH_ALL) != 0) { 5647 result.addAll(matchAllList); 5648 } else { 5649 // Browser/generic handling case. If there's a default browser, go straight 5650 // to that (but only if there is no other higher-priority match). 5651 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5652 int maxMatchPrio = 0; 5653 ResolveInfo defaultBrowserMatch = null; 5654 final int numCandidates = matchAllList.size(); 5655 for (int n = 0; n < numCandidates; n++) { 5656 ResolveInfo info = matchAllList.get(n); 5657 // track the highest overall match priority... 5658 if (info.priority > maxMatchPrio) { 5659 maxMatchPrio = info.priority; 5660 } 5661 // ...and the highest-priority default browser match 5662 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5663 if (defaultBrowserMatch == null 5664 || (defaultBrowserMatch.priority < info.priority)) { 5665 if (debug) { 5666 Slog.v(TAG, "Considering default browser match " + info); 5667 } 5668 defaultBrowserMatch = info; 5669 } 5670 } 5671 } 5672 if (defaultBrowserMatch != null 5673 && defaultBrowserMatch.priority >= maxMatchPrio 5674 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5675 { 5676 if (debug) { 5677 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5678 } 5679 result.add(defaultBrowserMatch); 5680 } else { 5681 result.addAll(matchAllList); 5682 } 5683 } 5684 5685 // If there is nothing selected, add all candidates and remove the ones that the user 5686 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5687 if (result.size() == 0) { 5688 result.addAll(candidates); 5689 result.removeAll(neverList); 5690 } 5691 } 5692 } 5693 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5694 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5695 result.size()); 5696 for (ResolveInfo info : result) { 5697 Slog.v(TAG, " + " + info.activityInfo); 5698 } 5699 } 5700 return result; 5701 } 5702 5703 // Returns a packed value as a long: 5704 // 5705 // high 'int'-sized word: link status: undefined/ask/never/always. 5706 // low 'int'-sized word: relative priority among 'always' results. 5707 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5708 long result = ps.getDomainVerificationStatusForUser(userId); 5709 // if none available, get the master status 5710 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5711 if (ps.getIntentFilterVerificationInfo() != null) { 5712 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5713 } 5714 } 5715 return result; 5716 } 5717 5718 private ResolveInfo querySkipCurrentProfileIntents( 5719 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5720 int flags, int sourceUserId) { 5721 if (matchingFilters != null) { 5722 int size = matchingFilters.size(); 5723 for (int i = 0; i < size; i ++) { 5724 CrossProfileIntentFilter filter = matchingFilters.get(i); 5725 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5726 // Checking if there are activities in the target user that can handle the 5727 // intent. 5728 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5729 resolvedType, flags, sourceUserId); 5730 if (resolveInfo != null) { 5731 return resolveInfo; 5732 } 5733 } 5734 } 5735 } 5736 return null; 5737 } 5738 5739 // Return matching ResolveInfo in target user if any. 5740 private ResolveInfo queryCrossProfileIntents( 5741 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5742 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5743 if (matchingFilters != null) { 5744 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5745 // match the same intent. For performance reasons, it is better not to 5746 // run queryIntent twice for the same userId 5747 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5748 int size = matchingFilters.size(); 5749 for (int i = 0; i < size; i++) { 5750 CrossProfileIntentFilter filter = matchingFilters.get(i); 5751 int targetUserId = filter.getTargetUserId(); 5752 boolean skipCurrentProfile = 5753 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5754 boolean skipCurrentProfileIfNoMatchFound = 5755 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5756 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5757 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5758 // Checking if there are activities in the target user that can handle the 5759 // intent. 5760 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5761 resolvedType, flags, sourceUserId); 5762 if (resolveInfo != null) return resolveInfo; 5763 alreadyTriedUserIds.put(targetUserId, true); 5764 } 5765 } 5766 } 5767 return null; 5768 } 5769 5770 /** 5771 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5772 * will forward the intent to the filter's target user. 5773 * Otherwise, returns null. 5774 */ 5775 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5776 String resolvedType, int flags, int sourceUserId) { 5777 int targetUserId = filter.getTargetUserId(); 5778 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5779 resolvedType, flags, targetUserId); 5780 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5781 // If all the matches in the target profile are suspended, return null. 5782 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5783 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5784 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5785 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5786 targetUserId); 5787 } 5788 } 5789 } 5790 return null; 5791 } 5792 5793 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5794 int sourceUserId, int targetUserId) { 5795 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5796 long ident = Binder.clearCallingIdentity(); 5797 boolean targetIsProfile; 5798 try { 5799 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5800 } finally { 5801 Binder.restoreCallingIdentity(ident); 5802 } 5803 String className; 5804 if (targetIsProfile) { 5805 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5806 } else { 5807 className = FORWARD_INTENT_TO_PARENT; 5808 } 5809 ComponentName forwardingActivityComponentName = new ComponentName( 5810 mAndroidApplication.packageName, className); 5811 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5812 sourceUserId); 5813 if (!targetIsProfile) { 5814 forwardingActivityInfo.showUserIcon = targetUserId; 5815 forwardingResolveInfo.noResourceId = true; 5816 } 5817 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5818 forwardingResolveInfo.priority = 0; 5819 forwardingResolveInfo.preferredOrder = 0; 5820 forwardingResolveInfo.match = 0; 5821 forwardingResolveInfo.isDefault = true; 5822 forwardingResolveInfo.filter = filter; 5823 forwardingResolveInfo.targetUserId = targetUserId; 5824 return forwardingResolveInfo; 5825 } 5826 5827 @Override 5828 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5829 Intent[] specifics, String[] specificTypes, Intent intent, 5830 String resolvedType, int flags, int userId) { 5831 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5832 specificTypes, intent, resolvedType, flags, userId)); 5833 } 5834 5835 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5836 Intent[] specifics, String[] specificTypes, Intent intent, 5837 String resolvedType, int flags, int userId) { 5838 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5839 flags = updateFlagsForResolve(flags, userId, intent); 5840 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5841 false /* requireFullPermission */, false /* checkShell */, 5842 "query intent activity options"); 5843 final String resultsAction = intent.getAction(); 5844 5845 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5846 | PackageManager.GET_RESOLVED_FILTER, userId); 5847 5848 if (DEBUG_INTENT_MATCHING) { 5849 Log.v(TAG, "Query " + intent + ": " + results); 5850 } 5851 5852 int specificsPos = 0; 5853 int N; 5854 5855 // todo: note that the algorithm used here is O(N^2). This 5856 // isn't a problem in our current environment, but if we start running 5857 // into situations where we have more than 5 or 10 matches then this 5858 // should probably be changed to something smarter... 5859 5860 // First we go through and resolve each of the specific items 5861 // that were supplied, taking care of removing any corresponding 5862 // duplicate items in the generic resolve list. 5863 if (specifics != null) { 5864 for (int i=0; i<specifics.length; i++) { 5865 final Intent sintent = specifics[i]; 5866 if (sintent == null) { 5867 continue; 5868 } 5869 5870 if (DEBUG_INTENT_MATCHING) { 5871 Log.v(TAG, "Specific #" + i + ": " + sintent); 5872 } 5873 5874 String action = sintent.getAction(); 5875 if (resultsAction != null && resultsAction.equals(action)) { 5876 // If this action was explicitly requested, then don't 5877 // remove things that have it. 5878 action = null; 5879 } 5880 5881 ResolveInfo ri = null; 5882 ActivityInfo ai = null; 5883 5884 ComponentName comp = sintent.getComponent(); 5885 if (comp == null) { 5886 ri = resolveIntent( 5887 sintent, 5888 specificTypes != null ? specificTypes[i] : null, 5889 flags, userId); 5890 if (ri == null) { 5891 continue; 5892 } 5893 if (ri == mResolveInfo) { 5894 // ACK! Must do something better with this. 5895 } 5896 ai = ri.activityInfo; 5897 comp = new ComponentName(ai.applicationInfo.packageName, 5898 ai.name); 5899 } else { 5900 ai = getActivityInfo(comp, flags, userId); 5901 if (ai == null) { 5902 continue; 5903 } 5904 } 5905 5906 // Look for any generic query activities that are duplicates 5907 // of this specific one, and remove them from the results. 5908 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5909 N = results.size(); 5910 int j; 5911 for (j=specificsPos; j<N; j++) { 5912 ResolveInfo sri = results.get(j); 5913 if ((sri.activityInfo.name.equals(comp.getClassName()) 5914 && sri.activityInfo.applicationInfo.packageName.equals( 5915 comp.getPackageName())) 5916 || (action != null && sri.filter.matchAction(action))) { 5917 results.remove(j); 5918 if (DEBUG_INTENT_MATCHING) Log.v( 5919 TAG, "Removing duplicate item from " + j 5920 + " due to specific " + specificsPos); 5921 if (ri == null) { 5922 ri = sri; 5923 } 5924 j--; 5925 N--; 5926 } 5927 } 5928 5929 // Add this specific item to its proper place. 5930 if (ri == null) { 5931 ri = new ResolveInfo(); 5932 ri.activityInfo = ai; 5933 } 5934 results.add(specificsPos, ri); 5935 ri.specificIndex = i; 5936 specificsPos++; 5937 } 5938 } 5939 5940 // Now we go through the remaining generic results and remove any 5941 // duplicate actions that are found here. 5942 N = results.size(); 5943 for (int i=specificsPos; i<N-1; i++) { 5944 final ResolveInfo rii = results.get(i); 5945 if (rii.filter == null) { 5946 continue; 5947 } 5948 5949 // Iterate over all of the actions of this result's intent 5950 // filter... typically this should be just one. 5951 final Iterator<String> it = rii.filter.actionsIterator(); 5952 if (it == null) { 5953 continue; 5954 } 5955 while (it.hasNext()) { 5956 final String action = it.next(); 5957 if (resultsAction != null && resultsAction.equals(action)) { 5958 // If this action was explicitly requested, then don't 5959 // remove things that have it. 5960 continue; 5961 } 5962 for (int j=i+1; j<N; j++) { 5963 final ResolveInfo rij = results.get(j); 5964 if (rij.filter != null && rij.filter.hasAction(action)) { 5965 results.remove(j); 5966 if (DEBUG_INTENT_MATCHING) Log.v( 5967 TAG, "Removing duplicate item from " + j 5968 + " due to action " + action + " at " + i); 5969 j--; 5970 N--; 5971 } 5972 } 5973 } 5974 5975 // If the caller didn't request filter information, drop it now 5976 // so we don't have to marshall/unmarshall it. 5977 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5978 rii.filter = null; 5979 } 5980 } 5981 5982 // Filter out the caller activity if so requested. 5983 if (caller != null) { 5984 N = results.size(); 5985 for (int i=0; i<N; i++) { 5986 ActivityInfo ainfo = results.get(i).activityInfo; 5987 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5988 && caller.getClassName().equals(ainfo.name)) { 5989 results.remove(i); 5990 break; 5991 } 5992 } 5993 } 5994 5995 // If the caller didn't request filter information, 5996 // drop them now so we don't have to 5997 // marshall/unmarshall it. 5998 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5999 N = results.size(); 6000 for (int i=0; i<N; i++) { 6001 results.get(i).filter = null; 6002 } 6003 } 6004 6005 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 6006 return results; 6007 } 6008 6009 @Override 6010 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 6011 String resolvedType, int flags, int userId) { 6012 return new ParceledListSlice<>( 6013 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 6014 } 6015 6016 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 6017 String resolvedType, int flags, int userId) { 6018 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6019 flags = updateFlagsForResolve(flags, userId, intent); 6020 ComponentName comp = intent.getComponent(); 6021 if (comp == null) { 6022 if (intent.getSelector() != null) { 6023 intent = intent.getSelector(); 6024 comp = intent.getComponent(); 6025 } 6026 } 6027 if (comp != null) { 6028 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6029 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 6030 if (ai != null) { 6031 ResolveInfo ri = new ResolveInfo(); 6032 ri.activityInfo = ai; 6033 list.add(ri); 6034 } 6035 return list; 6036 } 6037 6038 // reader 6039 synchronized (mPackages) { 6040 String pkgName = intent.getPackage(); 6041 if (pkgName == null) { 6042 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6043 } 6044 final PackageParser.Package pkg = mPackages.get(pkgName); 6045 if (pkg != null) { 6046 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6047 userId); 6048 } 6049 return Collections.emptyList(); 6050 } 6051 } 6052 6053 @Override 6054 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6055 if (!sUserManager.exists(userId)) return null; 6056 flags = updateFlagsForResolve(flags, userId, intent); 6057 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6058 if (query != null) { 6059 if (query.size() >= 1) { 6060 // If there is more than one service with the same priority, 6061 // just arbitrarily pick the first one. 6062 return query.get(0); 6063 } 6064 } 6065 return null; 6066 } 6067 6068 @Override 6069 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6070 String resolvedType, int flags, int userId) { 6071 return new ParceledListSlice<>( 6072 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6073 } 6074 6075 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6076 String resolvedType, int flags, int userId) { 6077 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6078 flags = updateFlagsForResolve(flags, userId, intent); 6079 ComponentName comp = intent.getComponent(); 6080 if (comp == null) { 6081 if (intent.getSelector() != null) { 6082 intent = intent.getSelector(); 6083 comp = intent.getComponent(); 6084 } 6085 } 6086 if (comp != null) { 6087 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6088 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6089 if (si != null) { 6090 final ResolveInfo ri = new ResolveInfo(); 6091 ri.serviceInfo = si; 6092 list.add(ri); 6093 } 6094 return list; 6095 } 6096 6097 // reader 6098 synchronized (mPackages) { 6099 String pkgName = intent.getPackage(); 6100 if (pkgName == null) { 6101 return mServices.queryIntent(intent, resolvedType, flags, userId); 6102 } 6103 final PackageParser.Package pkg = mPackages.get(pkgName); 6104 if (pkg != null) { 6105 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6106 userId); 6107 } 6108 return Collections.emptyList(); 6109 } 6110 } 6111 6112 @Override 6113 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6114 String resolvedType, int flags, int userId) { 6115 return new ParceledListSlice<>( 6116 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6117 } 6118 6119 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6120 Intent intent, String resolvedType, int flags, int userId) { 6121 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6122 flags = updateFlagsForResolve(flags, userId, intent); 6123 ComponentName comp = intent.getComponent(); 6124 if (comp == null) { 6125 if (intent.getSelector() != null) { 6126 intent = intent.getSelector(); 6127 comp = intent.getComponent(); 6128 } 6129 } 6130 if (comp != null) { 6131 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6132 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6133 if (pi != null) { 6134 final ResolveInfo ri = new ResolveInfo(); 6135 ri.providerInfo = pi; 6136 list.add(ri); 6137 } 6138 return list; 6139 } 6140 6141 // reader 6142 synchronized (mPackages) { 6143 String pkgName = intent.getPackage(); 6144 if (pkgName == null) { 6145 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6146 } 6147 final PackageParser.Package pkg = mPackages.get(pkgName); 6148 if (pkg != null) { 6149 return mProviders.queryIntentForPackage( 6150 intent, resolvedType, flags, pkg.providers, userId); 6151 } 6152 return Collections.emptyList(); 6153 } 6154 } 6155 6156 @Override 6157 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6158 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6159 flags = updateFlagsForPackage(flags, userId, null); 6160 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6161 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6162 true /* requireFullPermission */, false /* checkShell */, 6163 "get installed packages"); 6164 6165 // writer 6166 synchronized (mPackages) { 6167 ArrayList<PackageInfo> list; 6168 if (listUninstalled) { 6169 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6170 for (PackageSetting ps : mSettings.mPackages.values()) { 6171 final PackageInfo pi; 6172 if (ps.pkg != null) { 6173 pi = generatePackageInfo(ps, flags, userId); 6174 } else { 6175 pi = generatePackageInfo(ps, flags, userId); 6176 } 6177 if (pi != null) { 6178 list.add(pi); 6179 } 6180 } 6181 } else { 6182 list = new ArrayList<PackageInfo>(mPackages.size()); 6183 for (PackageParser.Package p : mPackages.values()) { 6184 final PackageInfo pi = 6185 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6186 if (pi != null) { 6187 list.add(pi); 6188 } 6189 } 6190 } 6191 6192 return new ParceledListSlice<PackageInfo>(list); 6193 } 6194 } 6195 6196 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6197 String[] permissions, boolean[] tmp, int flags, int userId) { 6198 int numMatch = 0; 6199 final PermissionsState permissionsState = ps.getPermissionsState(); 6200 for (int i=0; i<permissions.length; i++) { 6201 final String permission = permissions[i]; 6202 if (permissionsState.hasPermission(permission, userId)) { 6203 tmp[i] = true; 6204 numMatch++; 6205 } else { 6206 tmp[i] = false; 6207 } 6208 } 6209 if (numMatch == 0) { 6210 return; 6211 } 6212 final PackageInfo pi; 6213 if (ps.pkg != null) { 6214 pi = generatePackageInfo(ps, flags, userId); 6215 } else { 6216 pi = generatePackageInfo(ps, flags, userId); 6217 } 6218 // The above might return null in cases of uninstalled apps or install-state 6219 // skew across users/profiles. 6220 if (pi != null) { 6221 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6222 if (numMatch == permissions.length) { 6223 pi.requestedPermissions = permissions; 6224 } else { 6225 pi.requestedPermissions = new String[numMatch]; 6226 numMatch = 0; 6227 for (int i=0; i<permissions.length; i++) { 6228 if (tmp[i]) { 6229 pi.requestedPermissions[numMatch] = permissions[i]; 6230 numMatch++; 6231 } 6232 } 6233 } 6234 } 6235 list.add(pi); 6236 } 6237 } 6238 6239 @Override 6240 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6241 String[] permissions, int flags, int userId) { 6242 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6243 flags = updateFlagsForPackage(flags, userId, permissions); 6244 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6245 6246 // writer 6247 synchronized (mPackages) { 6248 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6249 boolean[] tmpBools = new boolean[permissions.length]; 6250 if (listUninstalled) { 6251 for (PackageSetting ps : mSettings.mPackages.values()) { 6252 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6253 } 6254 } else { 6255 for (PackageParser.Package pkg : mPackages.values()) { 6256 PackageSetting ps = (PackageSetting)pkg.mExtras; 6257 if (ps != null) { 6258 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6259 userId); 6260 } 6261 } 6262 } 6263 6264 return new ParceledListSlice<PackageInfo>(list); 6265 } 6266 } 6267 6268 @Override 6269 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6270 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6271 flags = updateFlagsForApplication(flags, userId, null); 6272 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6273 6274 // writer 6275 synchronized (mPackages) { 6276 ArrayList<ApplicationInfo> list; 6277 if (listUninstalled) { 6278 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6279 for (PackageSetting ps : mSettings.mPackages.values()) { 6280 ApplicationInfo ai; 6281 if (ps.pkg != null) { 6282 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6283 ps.readUserState(userId), userId); 6284 } else { 6285 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6286 } 6287 if (ai != null) { 6288 list.add(ai); 6289 } 6290 } 6291 } else { 6292 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6293 for (PackageParser.Package p : mPackages.values()) { 6294 if (p.mExtras != null) { 6295 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6296 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6297 if (ai != null) { 6298 list.add(ai); 6299 } 6300 } 6301 } 6302 } 6303 6304 return new ParceledListSlice<ApplicationInfo>(list); 6305 } 6306 } 6307 6308 @Override 6309 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6310 if (DISABLE_EPHEMERAL_APPS) { 6311 return null; 6312 } 6313 6314 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6315 "getEphemeralApplications"); 6316 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6317 true /* requireFullPermission */, false /* checkShell */, 6318 "getEphemeralApplications"); 6319 synchronized (mPackages) { 6320 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6321 .getEphemeralApplicationsLPw(userId); 6322 if (ephemeralApps != null) { 6323 return new ParceledListSlice<>(ephemeralApps); 6324 } 6325 } 6326 return null; 6327 } 6328 6329 @Override 6330 public boolean isEphemeralApplication(String packageName, int userId) { 6331 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6332 true /* requireFullPermission */, false /* checkShell */, 6333 "isEphemeral"); 6334 if (DISABLE_EPHEMERAL_APPS) { 6335 return false; 6336 } 6337 6338 if (!isCallerSameApp(packageName)) { 6339 return false; 6340 } 6341 synchronized (mPackages) { 6342 PackageParser.Package pkg = mPackages.get(packageName); 6343 if (pkg != null) { 6344 return pkg.applicationInfo.isEphemeralApp(); 6345 } 6346 } 6347 return false; 6348 } 6349 6350 @Override 6351 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6352 if (DISABLE_EPHEMERAL_APPS) { 6353 return null; 6354 } 6355 6356 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6357 true /* requireFullPermission */, false /* checkShell */, 6358 "getCookie"); 6359 if (!isCallerSameApp(packageName)) { 6360 return null; 6361 } 6362 synchronized (mPackages) { 6363 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6364 packageName, userId); 6365 } 6366 } 6367 6368 @Override 6369 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6370 if (DISABLE_EPHEMERAL_APPS) { 6371 return true; 6372 } 6373 6374 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6375 true /* requireFullPermission */, true /* checkShell */, 6376 "setCookie"); 6377 if (!isCallerSameApp(packageName)) { 6378 return false; 6379 } 6380 synchronized (mPackages) { 6381 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6382 packageName, cookie, userId); 6383 } 6384 } 6385 6386 @Override 6387 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6388 if (DISABLE_EPHEMERAL_APPS) { 6389 return null; 6390 } 6391 6392 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6393 "getEphemeralApplicationIcon"); 6394 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6395 true /* requireFullPermission */, false /* checkShell */, 6396 "getEphemeralApplicationIcon"); 6397 synchronized (mPackages) { 6398 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6399 packageName, userId); 6400 } 6401 } 6402 6403 private boolean isCallerSameApp(String packageName) { 6404 PackageParser.Package pkg = mPackages.get(packageName); 6405 return pkg != null 6406 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6407 } 6408 6409 @Override 6410 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6411 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6412 } 6413 6414 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6415 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6416 6417 // reader 6418 synchronized (mPackages) { 6419 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6420 final int userId = UserHandle.getCallingUserId(); 6421 while (i.hasNext()) { 6422 final PackageParser.Package p = i.next(); 6423 if (p.applicationInfo == null) continue; 6424 6425 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6426 && !p.applicationInfo.isDirectBootAware(); 6427 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6428 && p.applicationInfo.isDirectBootAware(); 6429 6430 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6431 && (!mSafeMode || isSystemApp(p)) 6432 && (matchesUnaware || matchesAware)) { 6433 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6434 if (ps != null) { 6435 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6436 ps.readUserState(userId), userId); 6437 if (ai != null) { 6438 finalList.add(ai); 6439 } 6440 } 6441 } 6442 } 6443 } 6444 6445 return finalList; 6446 } 6447 6448 @Override 6449 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6450 if (!sUserManager.exists(userId)) return null; 6451 flags = updateFlagsForComponent(flags, userId, name); 6452 // reader 6453 synchronized (mPackages) { 6454 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6455 PackageSetting ps = provider != null 6456 ? mSettings.mPackages.get(provider.owner.packageName) 6457 : null; 6458 return ps != null 6459 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6460 ? PackageParser.generateProviderInfo(provider, flags, 6461 ps.readUserState(userId), userId) 6462 : null; 6463 } 6464 } 6465 6466 /** 6467 * @deprecated 6468 */ 6469 @Deprecated 6470 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6471 // reader 6472 synchronized (mPackages) { 6473 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6474 .entrySet().iterator(); 6475 final int userId = UserHandle.getCallingUserId(); 6476 while (i.hasNext()) { 6477 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6478 PackageParser.Provider p = entry.getValue(); 6479 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6480 6481 if (ps != null && p.syncable 6482 && (!mSafeMode || (p.info.applicationInfo.flags 6483 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6484 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6485 ps.readUserState(userId), userId); 6486 if (info != null) { 6487 outNames.add(entry.getKey()); 6488 outInfo.add(info); 6489 } 6490 } 6491 } 6492 } 6493 } 6494 6495 @Override 6496 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6497 int uid, int flags) { 6498 final int userId = processName != null ? UserHandle.getUserId(uid) 6499 : UserHandle.getCallingUserId(); 6500 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6501 flags = updateFlagsForComponent(flags, userId, processName); 6502 6503 ArrayList<ProviderInfo> finalList = null; 6504 // reader 6505 synchronized (mPackages) { 6506 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6507 while (i.hasNext()) { 6508 final PackageParser.Provider p = i.next(); 6509 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6510 if (ps != null && p.info.authority != null 6511 && (processName == null 6512 || (p.info.processName.equals(processName) 6513 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6514 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6515 if (finalList == null) { 6516 finalList = new ArrayList<ProviderInfo>(3); 6517 } 6518 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6519 ps.readUserState(userId), userId); 6520 if (info != null) { 6521 finalList.add(info); 6522 } 6523 } 6524 } 6525 } 6526 6527 if (finalList != null) { 6528 Collections.sort(finalList, mProviderInitOrderSorter); 6529 return new ParceledListSlice<ProviderInfo>(finalList); 6530 } 6531 6532 return ParceledListSlice.emptyList(); 6533 } 6534 6535 @Override 6536 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6537 // reader 6538 synchronized (mPackages) { 6539 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6540 return PackageParser.generateInstrumentationInfo(i, flags); 6541 } 6542 } 6543 6544 @Override 6545 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6546 String targetPackage, int flags) { 6547 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6548 } 6549 6550 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6551 int flags) { 6552 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6553 6554 // reader 6555 synchronized (mPackages) { 6556 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6557 while (i.hasNext()) { 6558 final PackageParser.Instrumentation p = i.next(); 6559 if (targetPackage == null 6560 || targetPackage.equals(p.info.targetPackage)) { 6561 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6562 flags); 6563 if (ii != null) { 6564 finalList.add(ii); 6565 } 6566 } 6567 } 6568 } 6569 6570 return finalList; 6571 } 6572 6573 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6574 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6575 if (overlays == null) { 6576 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6577 return; 6578 } 6579 for (PackageParser.Package opkg : overlays.values()) { 6580 // Not much to do if idmap fails: we already logged the error 6581 // and we certainly don't want to abort installation of pkg simply 6582 // because an overlay didn't fit properly. For these reasons, 6583 // ignore the return value of createIdmapForPackagePairLI. 6584 createIdmapForPackagePairLI(pkg, opkg); 6585 } 6586 } 6587 6588 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6589 PackageParser.Package opkg) { 6590 if (!opkg.mTrustedOverlay) { 6591 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6592 opkg.baseCodePath + ": overlay not trusted"); 6593 return false; 6594 } 6595 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6596 if (overlaySet == null) { 6597 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6598 opkg.baseCodePath + " but target package has no known overlays"); 6599 return false; 6600 } 6601 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6602 // TODO: generate idmap for split APKs 6603 try { 6604 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6605 } catch (InstallerException e) { 6606 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6607 + opkg.baseCodePath); 6608 return false; 6609 } 6610 PackageParser.Package[] overlayArray = 6611 overlaySet.values().toArray(new PackageParser.Package[0]); 6612 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6613 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6614 return p1.mOverlayPriority - p2.mOverlayPriority; 6615 } 6616 }; 6617 Arrays.sort(overlayArray, cmp); 6618 6619 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6620 int i = 0; 6621 for (PackageParser.Package p : overlayArray) { 6622 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6623 } 6624 return true; 6625 } 6626 6627 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6628 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6629 try { 6630 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6631 } finally { 6632 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6633 } 6634 } 6635 6636 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6637 final File[] files = dir.listFiles(); 6638 if (ArrayUtils.isEmpty(files)) { 6639 Log.d(TAG, "No files in app dir " + dir); 6640 return; 6641 } 6642 6643 if (DEBUG_PACKAGE_SCANNING) { 6644 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6645 + " flags=0x" + Integer.toHexString(parseFlags)); 6646 } 6647 6648 for (File file : files) { 6649 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6650 && !PackageInstallerService.isStageName(file.getName()); 6651 if (!isPackage) { 6652 // Ignore entries which are not packages 6653 continue; 6654 } 6655 try { 6656 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6657 scanFlags, currentTime, null); 6658 } catch (PackageManagerException e) { 6659 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6660 6661 // Delete invalid userdata apps 6662 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6663 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6664 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6665 removeCodePathLI(file); 6666 } 6667 } 6668 } 6669 } 6670 6671 private static File getSettingsProblemFile() { 6672 File dataDir = Environment.getDataDirectory(); 6673 File systemDir = new File(dataDir, "system"); 6674 File fname = new File(systemDir, "uiderrors.txt"); 6675 return fname; 6676 } 6677 6678 static void reportSettingsProblem(int priority, String msg) { 6679 logCriticalInfo(priority, msg); 6680 } 6681 6682 static void logCriticalInfo(int priority, String msg) { 6683 Slog.println(priority, TAG, msg); 6684 EventLogTags.writePmCriticalInfo(msg); 6685 try { 6686 File fname = getSettingsProblemFile(); 6687 FileOutputStream out = new FileOutputStream(fname, true); 6688 PrintWriter pw = new FastPrintWriter(out); 6689 SimpleDateFormat formatter = new SimpleDateFormat(); 6690 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6691 pw.println(dateString + ": " + msg); 6692 pw.close(); 6693 FileUtils.setPermissions( 6694 fname.toString(), 6695 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6696 -1, -1); 6697 } catch (java.io.IOException e) { 6698 } 6699 } 6700 6701 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6702 final int policyFlags) throws PackageManagerException { 6703 if (ps != null 6704 && ps.codePath.equals(srcFile) 6705 && ps.timeStamp == srcFile.lastModified() 6706 && !isCompatSignatureUpdateNeeded(pkg) 6707 && !isRecoverSignatureUpdateNeeded(pkg)) { 6708 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6709 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6710 ArraySet<PublicKey> signingKs; 6711 synchronized (mPackages) { 6712 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6713 } 6714 if (ps.signatures.mSignatures != null 6715 && ps.signatures.mSignatures.length != 0 6716 && signingKs != null) { 6717 // Optimization: reuse the existing cached certificates 6718 // if the package appears to be unchanged. 6719 pkg.mSignatures = ps.signatures.mSignatures; 6720 pkg.mSigningKeys = signingKs; 6721 return; 6722 } 6723 6724 Slog.w(TAG, "PackageSetting for " + ps.name 6725 + " is missing signatures. Collecting certs again to recover them."); 6726 } else { 6727 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6728 } 6729 6730 try { 6731 PackageParser.collectCertificates(pkg, policyFlags); 6732 } catch (PackageParserException e) { 6733 throw PackageManagerException.from(e); 6734 } 6735 } 6736 6737 /** 6738 * Traces a package scan. 6739 * @see #scanPackageLI(File, int, int, long, UserHandle) 6740 */ 6741 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6742 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6743 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6744 try { 6745 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6746 } finally { 6747 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6748 } 6749 } 6750 6751 /** 6752 * Scans a package and returns the newly parsed package. 6753 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6754 */ 6755 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6756 long currentTime, UserHandle user) throws PackageManagerException { 6757 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6758 PackageParser pp = new PackageParser(); 6759 pp.setSeparateProcesses(mSeparateProcesses); 6760 pp.setOnlyCoreApps(mOnlyCore); 6761 pp.setDisplayMetrics(mMetrics); 6762 6763 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6764 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6765 } 6766 6767 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6768 final PackageParser.Package pkg; 6769 try { 6770 pkg = pp.parsePackage(scanFile, parseFlags); 6771 } catch (PackageParserException e) { 6772 throw PackageManagerException.from(e); 6773 } finally { 6774 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6775 } 6776 6777 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6778 } 6779 6780 /** 6781 * Scans a package and returns the newly parsed package. 6782 * @throws PackageManagerException on a parse error. 6783 */ 6784 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6785 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6786 throws PackageManagerException { 6787 // If the package has children and this is the first dive in the function 6788 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6789 // packages (parent and children) would be successfully scanned before the 6790 // actual scan since scanning mutates internal state and we want to atomically 6791 // install the package and its children. 6792 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6793 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6794 scanFlags |= SCAN_CHECK_ONLY; 6795 } 6796 } else { 6797 scanFlags &= ~SCAN_CHECK_ONLY; 6798 } 6799 6800 // Scan the parent 6801 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6802 scanFlags, currentTime, user); 6803 6804 // Scan the children 6805 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6806 for (int i = 0; i < childCount; i++) { 6807 PackageParser.Package childPackage = pkg.childPackages.get(i); 6808 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6809 currentTime, user); 6810 } 6811 6812 6813 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6814 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6815 } 6816 6817 return scannedPkg; 6818 } 6819 6820 /** 6821 * Scans a package and returns the newly parsed package. 6822 * @throws PackageManagerException on a parse error. 6823 */ 6824 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6825 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6826 throws PackageManagerException { 6827 PackageSetting ps = null; 6828 PackageSetting updatedPkg; 6829 // reader 6830 synchronized (mPackages) { 6831 // Look to see if we already know about this package. 6832 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6833 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6834 // This package has been renamed to its original name. Let's 6835 // use that. 6836 ps = mSettings.peekPackageLPr(oldName); 6837 } 6838 // If there was no original package, see one for the real package name. 6839 if (ps == null) { 6840 ps = mSettings.peekPackageLPr(pkg.packageName); 6841 } 6842 // Check to see if this package could be hiding/updating a system 6843 // package. Must look for it either under the original or real 6844 // package name depending on our state. 6845 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6846 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6847 6848 // If this is a package we don't know about on the system partition, we 6849 // may need to remove disabled child packages on the system partition 6850 // or may need to not add child packages if the parent apk is updated 6851 // on the data partition and no longer defines this child package. 6852 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6853 // If this is a parent package for an updated system app and this system 6854 // app got an OTA update which no longer defines some of the child packages 6855 // we have to prune them from the disabled system packages. 6856 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6857 if (disabledPs != null) { 6858 final int scannedChildCount = (pkg.childPackages != null) 6859 ? pkg.childPackages.size() : 0; 6860 final int disabledChildCount = disabledPs.childPackageNames != null 6861 ? disabledPs.childPackageNames.size() : 0; 6862 for (int i = 0; i < disabledChildCount; i++) { 6863 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6864 boolean disabledPackageAvailable = false; 6865 for (int j = 0; j < scannedChildCount; j++) { 6866 PackageParser.Package childPkg = pkg.childPackages.get(j); 6867 if (childPkg.packageName.equals(disabledChildPackageName)) { 6868 disabledPackageAvailable = true; 6869 break; 6870 } 6871 } 6872 if (!disabledPackageAvailable) { 6873 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6874 } 6875 } 6876 } 6877 } 6878 } 6879 6880 boolean updatedPkgBetter = false; 6881 // First check if this is a system package that may involve an update 6882 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6883 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6884 // it needs to drop FLAG_PRIVILEGED. 6885 if (locationIsPrivileged(scanFile)) { 6886 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6887 } else { 6888 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6889 } 6890 6891 if (ps != null && !ps.codePath.equals(scanFile)) { 6892 // The path has changed from what was last scanned... check the 6893 // version of the new path against what we have stored to determine 6894 // what to do. 6895 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6896 if (pkg.mVersionCode <= ps.versionCode) { 6897 // The system package has been updated and the code path does not match 6898 // Ignore entry. Skip it. 6899 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6900 + " ignored: updated version " + ps.versionCode 6901 + " better than this " + pkg.mVersionCode); 6902 if (!updatedPkg.codePath.equals(scanFile)) { 6903 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6904 + ps.name + " changing from " + updatedPkg.codePathString 6905 + " to " + scanFile); 6906 updatedPkg.codePath = scanFile; 6907 updatedPkg.codePathString = scanFile.toString(); 6908 updatedPkg.resourcePath = scanFile; 6909 updatedPkg.resourcePathString = scanFile.toString(); 6910 } 6911 updatedPkg.pkg = pkg; 6912 updatedPkg.versionCode = pkg.mVersionCode; 6913 6914 // Update the disabled system child packages to point to the package too. 6915 final int childCount = updatedPkg.childPackageNames != null 6916 ? updatedPkg.childPackageNames.size() : 0; 6917 for (int i = 0; i < childCount; i++) { 6918 String childPackageName = updatedPkg.childPackageNames.get(i); 6919 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6920 childPackageName); 6921 if (updatedChildPkg != null) { 6922 updatedChildPkg.pkg = pkg; 6923 updatedChildPkg.versionCode = pkg.mVersionCode; 6924 } 6925 } 6926 6927 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6928 + scanFile + " ignored: updated version " + ps.versionCode 6929 + " better than this " + pkg.mVersionCode); 6930 } else { 6931 // The current app on the system partition is better than 6932 // what we have updated to on the data partition; switch 6933 // back to the system partition version. 6934 // At this point, its safely assumed that package installation for 6935 // apps in system partition will go through. If not there won't be a working 6936 // version of the app 6937 // writer 6938 synchronized (mPackages) { 6939 // Just remove the loaded entries from package lists. 6940 mPackages.remove(ps.name); 6941 } 6942 6943 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6944 + " reverting from " + ps.codePathString 6945 + ": new version " + pkg.mVersionCode 6946 + " better than installed " + ps.versionCode); 6947 6948 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6949 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6950 synchronized (mInstallLock) { 6951 args.cleanUpResourcesLI(); 6952 } 6953 synchronized (mPackages) { 6954 mSettings.enableSystemPackageLPw(ps.name); 6955 } 6956 updatedPkgBetter = true; 6957 } 6958 } 6959 } 6960 6961 if (updatedPkg != null) { 6962 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6963 // initially 6964 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6965 6966 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6967 // flag set initially 6968 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6969 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6970 } 6971 } 6972 6973 // Verify certificates against what was last scanned 6974 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6975 6976 /* 6977 * A new system app appeared, but we already had a non-system one of the 6978 * same name installed earlier. 6979 */ 6980 boolean shouldHideSystemApp = false; 6981 if (updatedPkg == null && ps != null 6982 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6983 /* 6984 * Check to make sure the signatures match first. If they don't, 6985 * wipe the installed application and its data. 6986 */ 6987 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6988 != PackageManager.SIGNATURE_MATCH) { 6989 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6990 + " signatures don't match existing userdata copy; removing"); 6991 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6992 "scanPackageInternalLI")) { 6993 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6994 } 6995 ps = null; 6996 } else { 6997 /* 6998 * If the newly-added system app is an older version than the 6999 * already installed version, hide it. It will be scanned later 7000 * and re-added like an update. 7001 */ 7002 if (pkg.mVersionCode <= ps.versionCode) { 7003 shouldHideSystemApp = true; 7004 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 7005 + " but new version " + pkg.mVersionCode + " better than installed " 7006 + ps.versionCode + "; hiding system"); 7007 } else { 7008 /* 7009 * The newly found system app is a newer version that the 7010 * one previously installed. Simply remove the 7011 * already-installed application and replace it with our own 7012 * while keeping the application data. 7013 */ 7014 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 7015 + " reverting from " + ps.codePathString + ": new version " 7016 + pkg.mVersionCode + " better than installed " + ps.versionCode); 7017 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 7018 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 7019 synchronized (mInstallLock) { 7020 args.cleanUpResourcesLI(); 7021 } 7022 } 7023 } 7024 } 7025 7026 // The apk is forward locked (not public) if its code and resources 7027 // are kept in different files. (except for app in either system or 7028 // vendor path). 7029 // TODO grab this value from PackageSettings 7030 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7031 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 7032 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 7033 } 7034 } 7035 7036 // TODO: extend to support forward-locked splits 7037 String resourcePath = null; 7038 String baseResourcePath = null; 7039 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7040 if (ps != null && ps.resourcePathString != null) { 7041 resourcePath = ps.resourcePathString; 7042 baseResourcePath = ps.resourcePathString; 7043 } else { 7044 // Should not happen at all. Just log an error. 7045 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7046 } 7047 } else { 7048 resourcePath = pkg.codePath; 7049 baseResourcePath = pkg.baseCodePath; 7050 } 7051 7052 // Set application objects path explicitly. 7053 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7054 pkg.setApplicationInfoCodePath(pkg.codePath); 7055 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7056 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7057 pkg.setApplicationInfoResourcePath(resourcePath); 7058 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7059 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7060 7061 // Note that we invoke the following method only if we are about to unpack an application 7062 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7063 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7064 7065 /* 7066 * If the system app should be overridden by a previously installed 7067 * data, hide the system app now and let the /data/app scan pick it up 7068 * again. 7069 */ 7070 if (shouldHideSystemApp) { 7071 synchronized (mPackages) { 7072 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7073 } 7074 } 7075 7076 return scannedPkg; 7077 } 7078 7079 private static String fixProcessName(String defProcessName, 7080 String processName, int uid) { 7081 if (processName == null) { 7082 return defProcessName; 7083 } 7084 return processName; 7085 } 7086 7087 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7088 throws PackageManagerException { 7089 if (pkgSetting.signatures.mSignatures != null) { 7090 // Already existing package. Make sure signatures match 7091 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7092 == PackageManager.SIGNATURE_MATCH; 7093 if (!match) { 7094 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7095 == PackageManager.SIGNATURE_MATCH; 7096 } 7097 if (!match) { 7098 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7099 == PackageManager.SIGNATURE_MATCH; 7100 } 7101 if (!match) { 7102 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7103 + pkg.packageName + " signatures do not match the " 7104 + "previously installed version; ignoring!"); 7105 } 7106 } 7107 7108 // Check for shared user signatures 7109 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7110 // Already existing package. Make sure signatures match 7111 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7112 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7113 if (!match) { 7114 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7115 == PackageManager.SIGNATURE_MATCH; 7116 } 7117 if (!match) { 7118 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7119 == PackageManager.SIGNATURE_MATCH; 7120 } 7121 if (!match) { 7122 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7123 "Package " + pkg.packageName 7124 + " has no signatures that match those in shared user " 7125 + pkgSetting.sharedUser.name + "; ignoring!"); 7126 } 7127 } 7128 } 7129 7130 /** 7131 * Enforces that only the system UID or root's UID can call a method exposed 7132 * via Binder. 7133 * 7134 * @param message used as message if SecurityException is thrown 7135 * @throws SecurityException if the caller is not system or root 7136 */ 7137 private static final void enforceSystemOrRoot(String message) { 7138 final int uid = Binder.getCallingUid(); 7139 if (uid != Process.SYSTEM_UID && uid != 0) { 7140 throw new SecurityException(message); 7141 } 7142 } 7143 7144 @Override 7145 public void performFstrimIfNeeded() { 7146 enforceSystemOrRoot("Only the system can request fstrim"); 7147 7148 // Before everything else, see whether we need to fstrim. 7149 try { 7150 IMountService ms = PackageHelper.getMountService(); 7151 if (ms != null) { 7152 final boolean isUpgrade = isUpgrade(); 7153 boolean doTrim = isUpgrade; 7154 if (doTrim) { 7155 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7156 } else { 7157 final long interval = android.provider.Settings.Global.getLong( 7158 mContext.getContentResolver(), 7159 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7160 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7161 if (interval > 0) { 7162 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7163 if (timeSinceLast > interval) { 7164 doTrim = true; 7165 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7166 + "; running immediately"); 7167 } 7168 } 7169 } 7170 if (doTrim) { 7171 if (!isFirstBoot()) { 7172 try { 7173 ActivityManagerNative.getDefault().showBootMessage( 7174 mContext.getResources().getString( 7175 R.string.android_upgrading_fstrim), true); 7176 } catch (RemoteException e) { 7177 } 7178 } 7179 ms.runMaintenance(); 7180 } 7181 } else { 7182 Slog.e(TAG, "Mount service unavailable!"); 7183 } 7184 } catch (RemoteException e) { 7185 // Can't happen; MountService is local 7186 } 7187 } 7188 7189 @Override 7190 public void updatePackagesIfNeeded() { 7191 enforceSystemOrRoot("Only the system can request package update"); 7192 7193 // We need to re-extract after an OTA. 7194 boolean causeUpgrade = isUpgrade(); 7195 7196 // First boot or factory reset. 7197 // Note: we also handle devices that are upgrading to N right now as if it is their 7198 // first boot, as they do not have profile data. 7199 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7200 7201 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7202 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7203 7204 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7205 return; 7206 } 7207 7208 List<PackageParser.Package> pkgs; 7209 synchronized (mPackages) { 7210 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7211 } 7212 7213 int numberOfPackagesVisited = 0; 7214 int numberOfPackagesOptimized = 0; 7215 int numberOfPackagesSkipped = 0; 7216 int numberOfPackagesFailed = 0; 7217 final int numberOfPackagesToDexopt = pkgs.size(); 7218 final long startTime = System.nanoTime(); 7219 7220 for (PackageParser.Package pkg : pkgs) { 7221 numberOfPackagesVisited++; 7222 7223 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7224 if (DEBUG_DEXOPT) { 7225 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7226 } 7227 numberOfPackagesSkipped++; 7228 continue; 7229 } 7230 7231 if (DEBUG_DEXOPT) { 7232 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7233 numberOfPackagesToDexopt + ": " + pkg.packageName); 7234 } 7235 7236 if (mIsPreNUpgrade) { 7237 try { 7238 ActivityManagerNative.getDefault().showBootMessage( 7239 mContext.getResources().getString(R.string.android_upgrading_apk, 7240 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7241 } catch (RemoteException e) { 7242 } 7243 } 7244 7245 // checkProfiles is false to avoid merging profiles during boot which 7246 // might interfere with background compilation (b/28612421). 7247 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7248 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7249 // trade-off worth doing to save boot time work. 7250 int dexOptStatus = performDexOptTraced(pkg.packageName, 7251 null /* instructionSet */, 7252 false /* checkProfiles */, 7253 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7254 false /* force */); 7255 switch (dexOptStatus) { 7256 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7257 numberOfPackagesOptimized++; 7258 break; 7259 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7260 numberOfPackagesSkipped++; 7261 break; 7262 case PackageDexOptimizer.DEX_OPT_FAILED: 7263 numberOfPackagesFailed++; 7264 break; 7265 default: 7266 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7267 break; 7268 } 7269 } 7270 7271 final int elapsedTimeSeconds = 7272 (int) TimeUnit.NANOSECONDS.toSeconds(System.nanoTime() - startTime); 7273 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7274 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7275 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7276 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7277 MetricsLogger.histogram(mContext, "opt_dialog_time_s", elapsedTimeSeconds); 7278 } 7279 7280 @Override 7281 public void notifyPackageUse(String packageName, int reason) { 7282 synchronized (mPackages) { 7283 PackageParser.Package p = mPackages.get(packageName); 7284 if (p == null) { 7285 return; 7286 } 7287 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7288 } 7289 } 7290 7291 // TODO: this is not used nor needed. Delete it. 7292 @Override 7293 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7294 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7295 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7296 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7297 } 7298 7299 @Override 7300 public boolean performDexOpt(String packageName, String instructionSet, 7301 boolean checkProfiles, int compileReason, boolean force) { 7302 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7303 getCompilerFilterForReason(compileReason), force); 7304 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7305 } 7306 7307 @Override 7308 public boolean performDexOptMode(String packageName, String instructionSet, 7309 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7310 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7311 targetCompilerFilter, force); 7312 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7313 } 7314 7315 private int performDexOptTraced(String packageName, String instructionSet, 7316 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7317 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7318 try { 7319 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7320 targetCompilerFilter, force); 7321 } finally { 7322 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7323 } 7324 } 7325 7326 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7327 // if the package can now be considered up to date for the given filter. 7328 private int performDexOptInternal(String packageName, String instructionSet, 7329 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7330 PackageParser.Package p; 7331 final String targetInstructionSet; 7332 synchronized (mPackages) { 7333 p = mPackages.get(packageName); 7334 if (p == null) { 7335 // Package could not be found. Report failure. 7336 return PackageDexOptimizer.DEX_OPT_FAILED; 7337 } 7338 mPackageUsage.write(false); 7339 7340 targetInstructionSet = instructionSet != null ? instructionSet : 7341 getPrimaryInstructionSet(p.applicationInfo); 7342 } 7343 long callingId = Binder.clearCallingIdentity(); 7344 try { 7345 synchronized (mInstallLock) { 7346 final String[] instructionSets = new String[] { targetInstructionSet }; 7347 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7348 targetCompilerFilter, force); 7349 } 7350 } finally { 7351 Binder.restoreCallingIdentity(callingId); 7352 } 7353 } 7354 7355 public ArraySet<String> getOptimizablePackages() { 7356 ArraySet<String> pkgs = new ArraySet<String>(); 7357 synchronized (mPackages) { 7358 for (PackageParser.Package p : mPackages.values()) { 7359 if (PackageDexOptimizer.canOptimizePackage(p)) { 7360 pkgs.add(p.packageName); 7361 } 7362 } 7363 } 7364 return pkgs; 7365 } 7366 7367 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7368 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7369 boolean force) { 7370 // Select the dex optimizer based on the force parameter. 7371 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7372 // allocate an object here. 7373 PackageDexOptimizer pdo = force 7374 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7375 : mPackageDexOptimizer; 7376 7377 // Optimize all dependencies first. Note: we ignore the return value and march on 7378 // on errors. 7379 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7380 if (!deps.isEmpty()) { 7381 for (PackageParser.Package depPackage : deps) { 7382 // TODO: Analyze and investigate if we (should) profile libraries. 7383 // Currently this will do a full compilation of the library by default. 7384 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7385 false /* checkProfiles */, 7386 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7387 } 7388 } 7389 7390 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7391 targetCompilerFilter); 7392 } 7393 7394 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7395 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7396 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7397 Set<String> collectedNames = new HashSet<>(); 7398 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7399 7400 retValue.remove(p); 7401 7402 return retValue; 7403 } else { 7404 return Collections.emptyList(); 7405 } 7406 } 7407 7408 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7409 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7410 if (!collectedNames.contains(p.packageName)) { 7411 collectedNames.add(p.packageName); 7412 collected.add(p); 7413 7414 if (p.usesLibraries != null) { 7415 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7416 } 7417 if (p.usesOptionalLibraries != null) { 7418 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7419 collectedNames); 7420 } 7421 } 7422 } 7423 7424 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7425 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7426 for (String libName : libs) { 7427 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7428 if (libPkg != null) { 7429 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7430 } 7431 } 7432 } 7433 7434 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7435 synchronized (mPackages) { 7436 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7437 if (lib != null && lib.apk != null) { 7438 return mPackages.get(lib.apk); 7439 } 7440 } 7441 return null; 7442 } 7443 7444 public void shutdown() { 7445 mPackageUsage.write(true); 7446 } 7447 7448 @Override 7449 public void forceDexOpt(String packageName) { 7450 enforceSystemOrRoot("forceDexOpt"); 7451 7452 PackageParser.Package pkg; 7453 synchronized (mPackages) { 7454 pkg = mPackages.get(packageName); 7455 if (pkg == null) { 7456 throw new IllegalArgumentException("Unknown package: " + packageName); 7457 } 7458 } 7459 7460 synchronized (mInstallLock) { 7461 final String[] instructionSets = new String[] { 7462 getPrimaryInstructionSet(pkg.applicationInfo) }; 7463 7464 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7465 7466 // Whoever is calling forceDexOpt wants a fully compiled package. 7467 // Don't use profiles since that may cause compilation to be skipped. 7468 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7469 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7470 true /* force */); 7471 7472 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7473 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7474 throw new IllegalStateException("Failed to dexopt: " + res); 7475 } 7476 } 7477 } 7478 7479 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7480 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7481 Slog.w(TAG, "Unable to update from " + oldPkg.name 7482 + " to " + newPkg.packageName 7483 + ": old package not in system partition"); 7484 return false; 7485 } else if (mPackages.get(oldPkg.name) != null) { 7486 Slog.w(TAG, "Unable to update from " + oldPkg.name 7487 + " to " + newPkg.packageName 7488 + ": old package still exists"); 7489 return false; 7490 } 7491 return true; 7492 } 7493 7494 void removeCodePathLI(File codePath) { 7495 if (codePath.isDirectory()) { 7496 try { 7497 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7498 } catch (InstallerException e) { 7499 Slog.w(TAG, "Failed to remove code path", e); 7500 } 7501 } else { 7502 codePath.delete(); 7503 } 7504 } 7505 7506 private int[] resolveUserIds(int userId) { 7507 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7508 } 7509 7510 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7511 if (pkg == null) { 7512 Slog.wtf(TAG, "Package was null!", new Throwable()); 7513 return; 7514 } 7515 clearAppDataLeafLIF(pkg, userId, flags); 7516 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7517 for (int i = 0; i < childCount; i++) { 7518 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7519 } 7520 } 7521 7522 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7523 final PackageSetting ps; 7524 synchronized (mPackages) { 7525 ps = mSettings.mPackages.get(pkg.packageName); 7526 } 7527 for (int realUserId : resolveUserIds(userId)) { 7528 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7529 try { 7530 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7531 ceDataInode); 7532 } catch (InstallerException e) { 7533 Slog.w(TAG, String.valueOf(e)); 7534 } 7535 } 7536 } 7537 7538 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7539 if (pkg == null) { 7540 Slog.wtf(TAG, "Package was null!", new Throwable()); 7541 return; 7542 } 7543 destroyAppDataLeafLIF(pkg, userId, flags); 7544 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7545 for (int i = 0; i < childCount; i++) { 7546 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7547 } 7548 } 7549 7550 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7551 final PackageSetting ps; 7552 synchronized (mPackages) { 7553 ps = mSettings.mPackages.get(pkg.packageName); 7554 } 7555 for (int realUserId : resolveUserIds(userId)) { 7556 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7557 try { 7558 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7559 ceDataInode); 7560 } catch (InstallerException e) { 7561 Slog.w(TAG, String.valueOf(e)); 7562 } 7563 } 7564 } 7565 7566 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7567 if (pkg == null) { 7568 Slog.wtf(TAG, "Package was null!", new Throwable()); 7569 return; 7570 } 7571 destroyAppProfilesLeafLIF(pkg); 7572 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7573 for (int i = 0; i < childCount; i++) { 7574 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7575 } 7576 } 7577 7578 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7579 try { 7580 mInstaller.destroyAppProfiles(pkg.packageName); 7581 } catch (InstallerException e) { 7582 Slog.w(TAG, String.valueOf(e)); 7583 } 7584 } 7585 7586 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7587 if (pkg == null) { 7588 Slog.wtf(TAG, "Package was null!", new Throwable()); 7589 return; 7590 } 7591 clearAppProfilesLeafLIF(pkg); 7592 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7593 for (int i = 0; i < childCount; i++) { 7594 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7595 } 7596 } 7597 7598 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7599 try { 7600 mInstaller.clearAppProfiles(pkg.packageName); 7601 } catch (InstallerException e) { 7602 Slog.w(TAG, String.valueOf(e)); 7603 } 7604 } 7605 7606 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7607 long lastUpdateTime) { 7608 // Set parent install/update time 7609 PackageSetting ps = (PackageSetting) pkg.mExtras; 7610 if (ps != null) { 7611 ps.firstInstallTime = firstInstallTime; 7612 ps.lastUpdateTime = lastUpdateTime; 7613 } 7614 // Set children install/update time 7615 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7616 for (int i = 0; i < childCount; i++) { 7617 PackageParser.Package childPkg = pkg.childPackages.get(i); 7618 ps = (PackageSetting) childPkg.mExtras; 7619 if (ps != null) { 7620 ps.firstInstallTime = firstInstallTime; 7621 ps.lastUpdateTime = lastUpdateTime; 7622 } 7623 } 7624 } 7625 7626 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7627 PackageParser.Package changingLib) { 7628 if (file.path != null) { 7629 usesLibraryFiles.add(file.path); 7630 return; 7631 } 7632 PackageParser.Package p = mPackages.get(file.apk); 7633 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7634 // If we are doing this while in the middle of updating a library apk, 7635 // then we need to make sure to use that new apk for determining the 7636 // dependencies here. (We haven't yet finished committing the new apk 7637 // to the package manager state.) 7638 if (p == null || p.packageName.equals(changingLib.packageName)) { 7639 p = changingLib; 7640 } 7641 } 7642 if (p != null) { 7643 usesLibraryFiles.addAll(p.getAllCodePaths()); 7644 } 7645 } 7646 7647 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7648 PackageParser.Package changingLib) throws PackageManagerException { 7649 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7650 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7651 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7652 for (int i=0; i<N; i++) { 7653 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7654 if (file == null) { 7655 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7656 "Package " + pkg.packageName + " requires unavailable shared library " 7657 + pkg.usesLibraries.get(i) + "; failing!"); 7658 } 7659 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7660 } 7661 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7662 for (int i=0; i<N; i++) { 7663 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7664 if (file == null) { 7665 Slog.w(TAG, "Package " + pkg.packageName 7666 + " desires unavailable shared library " 7667 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7668 } else { 7669 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7670 } 7671 } 7672 N = usesLibraryFiles.size(); 7673 if (N > 0) { 7674 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7675 } else { 7676 pkg.usesLibraryFiles = null; 7677 } 7678 } 7679 } 7680 7681 private static boolean hasString(List<String> list, List<String> which) { 7682 if (list == null) { 7683 return false; 7684 } 7685 for (int i=list.size()-1; i>=0; i--) { 7686 for (int j=which.size()-1; j>=0; j--) { 7687 if (which.get(j).equals(list.get(i))) { 7688 return true; 7689 } 7690 } 7691 } 7692 return false; 7693 } 7694 7695 private void updateAllSharedLibrariesLPw() { 7696 for (PackageParser.Package pkg : mPackages.values()) { 7697 try { 7698 updateSharedLibrariesLPw(pkg, null); 7699 } catch (PackageManagerException e) { 7700 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7701 } 7702 } 7703 } 7704 7705 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7706 PackageParser.Package changingPkg) { 7707 ArrayList<PackageParser.Package> res = null; 7708 for (PackageParser.Package pkg : mPackages.values()) { 7709 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7710 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7711 if (res == null) { 7712 res = new ArrayList<PackageParser.Package>(); 7713 } 7714 res.add(pkg); 7715 try { 7716 updateSharedLibrariesLPw(pkg, changingPkg); 7717 } catch (PackageManagerException e) { 7718 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7719 } 7720 } 7721 } 7722 return res; 7723 } 7724 7725 /** 7726 * Derive the value of the {@code cpuAbiOverride} based on the provided 7727 * value and an optional stored value from the package settings. 7728 */ 7729 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7730 String cpuAbiOverride = null; 7731 7732 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7733 cpuAbiOverride = null; 7734 } else if (abiOverride != null) { 7735 cpuAbiOverride = abiOverride; 7736 } else if (settings != null) { 7737 cpuAbiOverride = settings.cpuAbiOverrideString; 7738 } 7739 7740 return cpuAbiOverride; 7741 } 7742 7743 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7744 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7745 throws PackageManagerException { 7746 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7747 // If the package has children and this is the first dive in the function 7748 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7749 // whether all packages (parent and children) would be successfully scanned 7750 // before the actual scan since scanning mutates internal state and we want 7751 // to atomically install the package and its children. 7752 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7753 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7754 scanFlags |= SCAN_CHECK_ONLY; 7755 } 7756 } else { 7757 scanFlags &= ~SCAN_CHECK_ONLY; 7758 } 7759 7760 final PackageParser.Package scannedPkg; 7761 try { 7762 // Scan the parent 7763 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7764 // Scan the children 7765 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7766 for (int i = 0; i < childCount; i++) { 7767 PackageParser.Package childPkg = pkg.childPackages.get(i); 7768 scanPackageLI(childPkg, policyFlags, 7769 scanFlags, currentTime, user); 7770 } 7771 } finally { 7772 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7773 } 7774 7775 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7776 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7777 } 7778 7779 return scannedPkg; 7780 } 7781 7782 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7783 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7784 boolean success = false; 7785 try { 7786 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7787 currentTime, user); 7788 success = true; 7789 return res; 7790 } finally { 7791 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7792 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7793 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7794 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7795 destroyAppProfilesLIF(pkg); 7796 } 7797 } 7798 } 7799 7800 /** 7801 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7802 */ 7803 private static boolean apkHasCode(String fileName) { 7804 StrictJarFile jarFile = null; 7805 try { 7806 jarFile = new StrictJarFile(fileName, 7807 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7808 return jarFile.findEntry("classes.dex") != null; 7809 } catch (IOException ignore) { 7810 } finally { 7811 try { 7812 jarFile.close(); 7813 } catch (IOException ignore) {} 7814 } 7815 return false; 7816 } 7817 7818 /** 7819 * Enforces code policy for the package. This ensures that if an APK has 7820 * declared hasCode="true" in its manifest that the APK actually contains 7821 * code. 7822 * 7823 * @throws PackageManagerException If bytecode could not be found when it should exist 7824 */ 7825 private static void enforceCodePolicy(PackageParser.Package pkg) 7826 throws PackageManagerException { 7827 final boolean shouldHaveCode = 7828 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7829 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7830 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7831 "Package " + pkg.baseCodePath + " code is missing"); 7832 } 7833 7834 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7835 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7836 final boolean splitShouldHaveCode = 7837 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7838 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7839 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7840 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7841 } 7842 } 7843 } 7844 } 7845 7846 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7847 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7848 throws PackageManagerException { 7849 final File scanFile = new File(pkg.codePath); 7850 if (pkg.applicationInfo.getCodePath() == null || 7851 pkg.applicationInfo.getResourcePath() == null) { 7852 // Bail out. The resource and code paths haven't been set. 7853 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7854 "Code and resource paths haven't been set correctly"); 7855 } 7856 7857 // Apply policy 7858 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7859 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7860 if (pkg.applicationInfo.isDirectBootAware()) { 7861 // we're direct boot aware; set for all components 7862 for (PackageParser.Service s : pkg.services) { 7863 s.info.encryptionAware = s.info.directBootAware = true; 7864 } 7865 for (PackageParser.Provider p : pkg.providers) { 7866 p.info.encryptionAware = p.info.directBootAware = true; 7867 } 7868 for (PackageParser.Activity a : pkg.activities) { 7869 a.info.encryptionAware = a.info.directBootAware = true; 7870 } 7871 for (PackageParser.Activity r : pkg.receivers) { 7872 r.info.encryptionAware = r.info.directBootAware = true; 7873 } 7874 } 7875 } else { 7876 // Only allow system apps to be flagged as core apps. 7877 pkg.coreApp = false; 7878 // clear flags not applicable to regular apps 7879 pkg.applicationInfo.privateFlags &= 7880 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7881 pkg.applicationInfo.privateFlags &= 7882 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7883 } 7884 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7885 7886 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7887 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7888 } 7889 7890 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7891 enforceCodePolicy(pkg); 7892 } 7893 7894 if (mCustomResolverComponentName != null && 7895 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7896 setUpCustomResolverActivity(pkg); 7897 } 7898 7899 if (pkg.packageName.equals("android")) { 7900 synchronized (mPackages) { 7901 if (mAndroidApplication != null) { 7902 Slog.w(TAG, "*************************************************"); 7903 Slog.w(TAG, "Core android package being redefined. Skipping."); 7904 Slog.w(TAG, " file=" + scanFile); 7905 Slog.w(TAG, "*************************************************"); 7906 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7907 "Core android package being redefined. Skipping."); 7908 } 7909 7910 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7911 // Set up information for our fall-back user intent resolution activity. 7912 mPlatformPackage = pkg; 7913 pkg.mVersionCode = mSdkVersion; 7914 mAndroidApplication = pkg.applicationInfo; 7915 7916 if (!mResolverReplaced) { 7917 mResolveActivity.applicationInfo = mAndroidApplication; 7918 mResolveActivity.name = ResolverActivity.class.getName(); 7919 mResolveActivity.packageName = mAndroidApplication.packageName; 7920 mResolveActivity.processName = "system:ui"; 7921 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7922 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7923 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7924 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7925 mResolveActivity.exported = true; 7926 mResolveActivity.enabled = true; 7927 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7928 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7929 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7930 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7931 | ActivityInfo.CONFIG_ORIENTATION 7932 | ActivityInfo.CONFIG_KEYBOARD 7933 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7934 mResolveInfo.activityInfo = mResolveActivity; 7935 mResolveInfo.priority = 0; 7936 mResolveInfo.preferredOrder = 0; 7937 mResolveInfo.match = 0; 7938 mResolveComponentName = new ComponentName( 7939 mAndroidApplication.packageName, mResolveActivity.name); 7940 } 7941 } 7942 } 7943 } 7944 7945 if (DEBUG_PACKAGE_SCANNING) { 7946 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7947 Log.d(TAG, "Scanning package " + pkg.packageName); 7948 } 7949 7950 synchronized (mPackages) { 7951 if (mPackages.containsKey(pkg.packageName) 7952 || mSharedLibraries.containsKey(pkg.packageName)) { 7953 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7954 "Application package " + pkg.packageName 7955 + " already installed. Skipping duplicate."); 7956 } 7957 7958 // If we're only installing presumed-existing packages, require that the 7959 // scanned APK is both already known and at the path previously established 7960 // for it. Previously unknown packages we pick up normally, but if we have an 7961 // a priori expectation about this package's install presence, enforce it. 7962 // With a singular exception for new system packages. When an OTA contains 7963 // a new system package, we allow the codepath to change from a system location 7964 // to the user-installed location. If we don't allow this change, any newer, 7965 // user-installed version of the application will be ignored. 7966 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7967 if (mExpectingBetter.containsKey(pkg.packageName)) { 7968 logCriticalInfo(Log.WARN, 7969 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7970 } else { 7971 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7972 if (known != null) { 7973 if (DEBUG_PACKAGE_SCANNING) { 7974 Log.d(TAG, "Examining " + pkg.codePath 7975 + " and requiring known paths " + known.codePathString 7976 + " & " + known.resourcePathString); 7977 } 7978 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7979 || !pkg.applicationInfo.getResourcePath().equals( 7980 known.resourcePathString)) { 7981 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7982 "Application package " + pkg.packageName 7983 + " found at " + pkg.applicationInfo.getCodePath() 7984 + " but expected at " + known.codePathString 7985 + "; ignoring."); 7986 } 7987 } 7988 } 7989 } 7990 } 7991 7992 // Initialize package source and resource directories 7993 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7994 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7995 7996 SharedUserSetting suid = null; 7997 PackageSetting pkgSetting = null; 7998 7999 if (!isSystemApp(pkg)) { 8000 // Only system apps can use these features. 8001 pkg.mOriginalPackages = null; 8002 pkg.mRealPackage = null; 8003 pkg.mAdoptPermissions = null; 8004 } 8005 8006 // Getting the package setting may have a side-effect, so if we 8007 // are only checking if scan would succeed, stash a copy of the 8008 // old setting to restore at the end. 8009 PackageSetting nonMutatedPs = null; 8010 8011 // writer 8012 synchronized (mPackages) { 8013 if (pkg.mSharedUserId != null) { 8014 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 8015 if (suid == null) { 8016 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8017 "Creating application package " + pkg.packageName 8018 + " for shared user failed"); 8019 } 8020 if (DEBUG_PACKAGE_SCANNING) { 8021 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8022 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 8023 + "): packages=" + suid.packages); 8024 } 8025 } 8026 8027 // Check if we are renaming from an original package name. 8028 PackageSetting origPackage = null; 8029 String realName = null; 8030 if (pkg.mOriginalPackages != null) { 8031 // This package may need to be renamed to a previously 8032 // installed name. Let's check on that... 8033 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 8034 if (pkg.mOriginalPackages.contains(renamed)) { 8035 // This package had originally been installed as the 8036 // original name, and we have already taken care of 8037 // transitioning to the new one. Just update the new 8038 // one to continue using the old name. 8039 realName = pkg.mRealPackage; 8040 if (!pkg.packageName.equals(renamed)) { 8041 // Callers into this function may have already taken 8042 // care of renaming the package; only do it here if 8043 // it is not already done. 8044 pkg.setPackageName(renamed); 8045 } 8046 8047 } else { 8048 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8049 if ((origPackage = mSettings.peekPackageLPr( 8050 pkg.mOriginalPackages.get(i))) != null) { 8051 // We do have the package already installed under its 8052 // original name... should we use it? 8053 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8054 // New package is not compatible with original. 8055 origPackage = null; 8056 continue; 8057 } else if (origPackage.sharedUser != null) { 8058 // Make sure uid is compatible between packages. 8059 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8060 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8061 + " to " + pkg.packageName + ": old uid " 8062 + origPackage.sharedUser.name 8063 + " differs from " + pkg.mSharedUserId); 8064 origPackage = null; 8065 continue; 8066 } 8067 // TODO: Add case when shared user id is added [b/28144775] 8068 } else { 8069 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8070 + pkg.packageName + " to old name " + origPackage.name); 8071 } 8072 break; 8073 } 8074 } 8075 } 8076 } 8077 8078 if (mTransferedPackages.contains(pkg.packageName)) { 8079 Slog.w(TAG, "Package " + pkg.packageName 8080 + " was transferred to another, but its .apk remains"); 8081 } 8082 8083 // See comments in nonMutatedPs declaration 8084 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8085 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8086 if (foundPs != null) { 8087 nonMutatedPs = new PackageSetting(foundPs); 8088 } 8089 } 8090 8091 // Just create the setting, don't add it yet. For already existing packages 8092 // the PkgSetting exists already and doesn't have to be created. 8093 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8094 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8095 pkg.applicationInfo.primaryCpuAbi, 8096 pkg.applicationInfo.secondaryCpuAbi, 8097 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8098 user, false); 8099 if (pkgSetting == null) { 8100 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8101 "Creating application package " + pkg.packageName + " failed"); 8102 } 8103 8104 if (pkgSetting.origPackage != null) { 8105 // If we are first transitioning from an original package, 8106 // fix up the new package's name now. We need to do this after 8107 // looking up the package under its new name, so getPackageLP 8108 // can take care of fiddling things correctly. 8109 pkg.setPackageName(origPackage.name); 8110 8111 // File a report about this. 8112 String msg = "New package " + pkgSetting.realName 8113 + " renamed to replace old package " + pkgSetting.name; 8114 reportSettingsProblem(Log.WARN, msg); 8115 8116 // Make a note of it. 8117 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8118 mTransferedPackages.add(origPackage.name); 8119 } 8120 8121 // No longer need to retain this. 8122 pkgSetting.origPackage = null; 8123 } 8124 8125 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8126 // Make a note of it. 8127 mTransferedPackages.add(pkg.packageName); 8128 } 8129 8130 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8131 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8132 } 8133 8134 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8135 // Check all shared libraries and map to their actual file path. 8136 // We only do this here for apps not on a system dir, because those 8137 // are the only ones that can fail an install due to this. We 8138 // will take care of the system apps by updating all of their 8139 // library paths after the scan is done. 8140 updateSharedLibrariesLPw(pkg, null); 8141 } 8142 8143 if (mFoundPolicyFile) { 8144 SELinuxMMAC.assignSeinfoValue(pkg); 8145 } 8146 8147 pkg.applicationInfo.uid = pkgSetting.appId; 8148 pkg.mExtras = pkgSetting; 8149 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8150 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8151 // We just determined the app is signed correctly, so bring 8152 // over the latest parsed certs. 8153 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8154 } else { 8155 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8156 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8157 "Package " + pkg.packageName + " upgrade keys do not match the " 8158 + "previously installed version"); 8159 } else { 8160 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8161 String msg = "System package " + pkg.packageName 8162 + " signature changed; retaining data."; 8163 reportSettingsProblem(Log.WARN, msg); 8164 } 8165 } 8166 } else { 8167 try { 8168 verifySignaturesLP(pkgSetting, pkg); 8169 // We just determined the app is signed correctly, so bring 8170 // over the latest parsed certs. 8171 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8172 } catch (PackageManagerException e) { 8173 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8174 throw e; 8175 } 8176 // The signature has changed, but this package is in the system 8177 // image... let's recover! 8178 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8179 // However... if this package is part of a shared user, but it 8180 // doesn't match the signature of the shared user, let's fail. 8181 // What this means is that you can't change the signatures 8182 // associated with an overall shared user, which doesn't seem all 8183 // that unreasonable. 8184 if (pkgSetting.sharedUser != null) { 8185 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8186 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8187 throw new PackageManagerException( 8188 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8189 "Signature mismatch for shared user: " 8190 + pkgSetting.sharedUser); 8191 } 8192 } 8193 // File a report about this. 8194 String msg = "System package " + pkg.packageName 8195 + " signature changed; retaining data."; 8196 reportSettingsProblem(Log.WARN, msg); 8197 } 8198 } 8199 // Verify that this new package doesn't have any content providers 8200 // that conflict with existing packages. Only do this if the 8201 // package isn't already installed, since we don't want to break 8202 // things that are installed. 8203 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8204 final int N = pkg.providers.size(); 8205 int i; 8206 for (i=0; i<N; i++) { 8207 PackageParser.Provider p = pkg.providers.get(i); 8208 if (p.info.authority != null) { 8209 String names[] = p.info.authority.split(";"); 8210 for (int j = 0; j < names.length; j++) { 8211 if (mProvidersByAuthority.containsKey(names[j])) { 8212 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8213 final String otherPackageName = 8214 ((other != null && other.getComponentName() != null) ? 8215 other.getComponentName().getPackageName() : "?"); 8216 throw new PackageManagerException( 8217 INSTALL_FAILED_CONFLICTING_PROVIDER, 8218 "Can't install because provider name " + names[j] 8219 + " (in package " + pkg.applicationInfo.packageName 8220 + ") is already used by " + otherPackageName); 8221 } 8222 } 8223 } 8224 } 8225 } 8226 8227 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8228 // This package wants to adopt ownership of permissions from 8229 // another package. 8230 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8231 final String origName = pkg.mAdoptPermissions.get(i); 8232 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8233 if (orig != null) { 8234 if (verifyPackageUpdateLPr(orig, pkg)) { 8235 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8236 + pkg.packageName); 8237 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8238 } 8239 } 8240 } 8241 } 8242 } 8243 8244 final String pkgName = pkg.packageName; 8245 8246 final long scanFileTime = scanFile.lastModified(); 8247 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8248 pkg.applicationInfo.processName = fixProcessName( 8249 pkg.applicationInfo.packageName, 8250 pkg.applicationInfo.processName, 8251 pkg.applicationInfo.uid); 8252 8253 if (pkg != mPlatformPackage) { 8254 // Get all of our default paths setup 8255 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8256 } 8257 8258 final String path = scanFile.getPath(); 8259 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8260 8261 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8262 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8263 8264 // Some system apps still use directory structure for native libraries 8265 // in which case we might end up not detecting abi solely based on apk 8266 // structure. Try to detect abi based on directory structure. 8267 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8268 pkg.applicationInfo.primaryCpuAbi == null) { 8269 setBundledAppAbisAndRoots(pkg, pkgSetting); 8270 setNativeLibraryPaths(pkg); 8271 } 8272 8273 } else { 8274 if ((scanFlags & SCAN_MOVE) != 0) { 8275 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8276 // but we already have this packages package info in the PackageSetting. We just 8277 // use that and derive the native library path based on the new codepath. 8278 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8279 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8280 } 8281 8282 // Set native library paths again. For moves, the path will be updated based on the 8283 // ABIs we've determined above. For non-moves, the path will be updated based on the 8284 // ABIs we determined during compilation, but the path will depend on the final 8285 // package path (after the rename away from the stage path). 8286 setNativeLibraryPaths(pkg); 8287 } 8288 8289 // This is a special case for the "system" package, where the ABI is 8290 // dictated by the zygote configuration (and init.rc). We should keep track 8291 // of this ABI so that we can deal with "normal" applications that run under 8292 // the same UID correctly. 8293 if (mPlatformPackage == pkg) { 8294 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8295 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8296 } 8297 8298 // If there's a mismatch between the abi-override in the package setting 8299 // and the abiOverride specified for the install. Warn about this because we 8300 // would've already compiled the app without taking the package setting into 8301 // account. 8302 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8303 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8304 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8305 " for package " + pkg.packageName); 8306 } 8307 } 8308 8309 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8310 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8311 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8312 8313 // Copy the derived override back to the parsed package, so that we can 8314 // update the package settings accordingly. 8315 pkg.cpuAbiOverride = cpuAbiOverride; 8316 8317 if (DEBUG_ABI_SELECTION) { 8318 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8319 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8320 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8321 } 8322 8323 // Push the derived path down into PackageSettings so we know what to 8324 // clean up at uninstall time. 8325 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8326 8327 if (DEBUG_ABI_SELECTION) { 8328 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8329 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8330 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8331 } 8332 8333 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8334 // We don't do this here during boot because we can do it all 8335 // at once after scanning all existing packages. 8336 // 8337 // We also do this *before* we perform dexopt on this package, so that 8338 // we can avoid redundant dexopts, and also to make sure we've got the 8339 // code and package path correct. 8340 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8341 pkg, true /* boot complete */); 8342 } 8343 8344 if (mFactoryTest && pkg.requestedPermissions.contains( 8345 android.Manifest.permission.FACTORY_TEST)) { 8346 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8347 } 8348 8349 ArrayList<PackageParser.Package> clientLibPkgs = null; 8350 8351 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8352 if (nonMutatedPs != null) { 8353 synchronized (mPackages) { 8354 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8355 } 8356 } 8357 return pkg; 8358 } 8359 8360 // Only privileged apps and updated privileged apps can add child packages. 8361 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8362 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8363 throw new PackageManagerException("Only privileged apps and updated " 8364 + "privileged apps can add child packages. Ignoring package " 8365 + pkg.packageName); 8366 } 8367 final int childCount = pkg.childPackages.size(); 8368 for (int i = 0; i < childCount; i++) { 8369 PackageParser.Package childPkg = pkg.childPackages.get(i); 8370 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8371 childPkg.packageName)) { 8372 throw new PackageManagerException("Cannot override a child package of " 8373 + "another disabled system app. Ignoring package " + pkg.packageName); 8374 } 8375 } 8376 } 8377 8378 // writer 8379 synchronized (mPackages) { 8380 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8381 // Only system apps can add new shared libraries. 8382 if (pkg.libraryNames != null) { 8383 for (int i=0; i<pkg.libraryNames.size(); i++) { 8384 String name = pkg.libraryNames.get(i); 8385 boolean allowed = false; 8386 if (pkg.isUpdatedSystemApp()) { 8387 // New library entries can only be added through the 8388 // system image. This is important to get rid of a lot 8389 // of nasty edge cases: for example if we allowed a non- 8390 // system update of the app to add a library, then uninstalling 8391 // the update would make the library go away, and assumptions 8392 // we made such as through app install filtering would now 8393 // have allowed apps on the device which aren't compatible 8394 // with it. Better to just have the restriction here, be 8395 // conservative, and create many fewer cases that can negatively 8396 // impact the user experience. 8397 final PackageSetting sysPs = mSettings 8398 .getDisabledSystemPkgLPr(pkg.packageName); 8399 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8400 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8401 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8402 allowed = true; 8403 break; 8404 } 8405 } 8406 } 8407 } else { 8408 allowed = true; 8409 } 8410 if (allowed) { 8411 if (!mSharedLibraries.containsKey(name)) { 8412 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8413 } else if (!name.equals(pkg.packageName)) { 8414 Slog.w(TAG, "Package " + pkg.packageName + " library " 8415 + name + " already exists; skipping"); 8416 } 8417 } else { 8418 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8419 + name + " that is not declared on system image; skipping"); 8420 } 8421 } 8422 if ((scanFlags & SCAN_BOOTING) == 0) { 8423 // If we are not booting, we need to update any applications 8424 // that are clients of our shared library. If we are booting, 8425 // this will all be done once the scan is complete. 8426 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8427 } 8428 } 8429 } 8430 } 8431 8432 if ((scanFlags & SCAN_BOOTING) != 0) { 8433 // No apps can run during boot scan, so they don't need to be frozen 8434 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8435 // Caller asked to not kill app, so it's probably not frozen 8436 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8437 // Caller asked us to ignore frozen check for some reason; they 8438 // probably didn't know the package name 8439 } else { 8440 // We're doing major surgery on this package, so it better be frozen 8441 // right now to keep it from launching 8442 checkPackageFrozen(pkgName); 8443 } 8444 8445 // Also need to kill any apps that are dependent on the library. 8446 if (clientLibPkgs != null) { 8447 for (int i=0; i<clientLibPkgs.size(); i++) { 8448 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8449 killApplication(clientPkg.applicationInfo.packageName, 8450 clientPkg.applicationInfo.uid, "update lib"); 8451 } 8452 } 8453 8454 // Make sure we're not adding any bogus keyset info 8455 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8456 ksms.assertScannedPackageValid(pkg); 8457 8458 // writer 8459 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8460 8461 boolean createIdmapFailed = false; 8462 synchronized (mPackages) { 8463 // We don't expect installation to fail beyond this point 8464 8465 // Add the new setting to mSettings 8466 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8467 // Add the new setting to mPackages 8468 mPackages.put(pkg.applicationInfo.packageName, pkg); 8469 // Make sure we don't accidentally delete its data. 8470 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8471 while (iter.hasNext()) { 8472 PackageCleanItem item = iter.next(); 8473 if (pkgName.equals(item.packageName)) { 8474 iter.remove(); 8475 } 8476 } 8477 8478 // Take care of first install / last update times. 8479 if (currentTime != 0) { 8480 if (pkgSetting.firstInstallTime == 0) { 8481 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8482 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8483 pkgSetting.lastUpdateTime = currentTime; 8484 } 8485 } else if (pkgSetting.firstInstallTime == 0) { 8486 // We need *something*. Take time time stamp of the file. 8487 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8488 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8489 if (scanFileTime != pkgSetting.timeStamp) { 8490 // A package on the system image has changed; consider this 8491 // to be an update. 8492 pkgSetting.lastUpdateTime = scanFileTime; 8493 } 8494 } 8495 8496 // Add the package's KeySets to the global KeySetManagerService 8497 ksms.addScannedPackageLPw(pkg); 8498 8499 int N = pkg.providers.size(); 8500 StringBuilder r = null; 8501 int i; 8502 for (i=0; i<N; i++) { 8503 PackageParser.Provider p = pkg.providers.get(i); 8504 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8505 p.info.processName, pkg.applicationInfo.uid); 8506 mProviders.addProvider(p); 8507 p.syncable = p.info.isSyncable; 8508 if (p.info.authority != null) { 8509 String names[] = p.info.authority.split(";"); 8510 p.info.authority = null; 8511 for (int j = 0; j < names.length; j++) { 8512 if (j == 1 && p.syncable) { 8513 // We only want the first authority for a provider to possibly be 8514 // syncable, so if we already added this provider using a different 8515 // authority clear the syncable flag. We copy the provider before 8516 // changing it because the mProviders object contains a reference 8517 // to a provider that we don't want to change. 8518 // Only do this for the second authority since the resulting provider 8519 // object can be the same for all future authorities for this provider. 8520 p = new PackageParser.Provider(p); 8521 p.syncable = false; 8522 } 8523 if (!mProvidersByAuthority.containsKey(names[j])) { 8524 mProvidersByAuthority.put(names[j], p); 8525 if (p.info.authority == null) { 8526 p.info.authority = names[j]; 8527 } else { 8528 p.info.authority = p.info.authority + ";" + names[j]; 8529 } 8530 if (DEBUG_PACKAGE_SCANNING) { 8531 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8532 Log.d(TAG, "Registered content provider: " + names[j] 8533 + ", className = " + p.info.name + ", isSyncable = " 8534 + p.info.isSyncable); 8535 } 8536 } else { 8537 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8538 Slog.w(TAG, "Skipping provider name " + names[j] + 8539 " (in package " + pkg.applicationInfo.packageName + 8540 "): name already used by " 8541 + ((other != null && other.getComponentName() != null) 8542 ? other.getComponentName().getPackageName() : "?")); 8543 } 8544 } 8545 } 8546 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8547 if (r == null) { 8548 r = new StringBuilder(256); 8549 } else { 8550 r.append(' '); 8551 } 8552 r.append(p.info.name); 8553 } 8554 } 8555 if (r != null) { 8556 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8557 } 8558 8559 N = pkg.services.size(); 8560 r = null; 8561 for (i=0; i<N; i++) { 8562 PackageParser.Service s = pkg.services.get(i); 8563 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8564 s.info.processName, pkg.applicationInfo.uid); 8565 mServices.addService(s); 8566 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8567 if (r == null) { 8568 r = new StringBuilder(256); 8569 } else { 8570 r.append(' '); 8571 } 8572 r.append(s.info.name); 8573 } 8574 } 8575 if (r != null) { 8576 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8577 } 8578 8579 N = pkg.receivers.size(); 8580 r = null; 8581 for (i=0; i<N; i++) { 8582 PackageParser.Activity a = pkg.receivers.get(i); 8583 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8584 a.info.processName, pkg.applicationInfo.uid); 8585 mReceivers.addActivity(a, "receiver"); 8586 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8587 if (r == null) { 8588 r = new StringBuilder(256); 8589 } else { 8590 r.append(' '); 8591 } 8592 r.append(a.info.name); 8593 } 8594 } 8595 if (r != null) { 8596 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8597 } 8598 8599 N = pkg.activities.size(); 8600 r = null; 8601 for (i=0; i<N; i++) { 8602 PackageParser.Activity a = pkg.activities.get(i); 8603 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8604 a.info.processName, pkg.applicationInfo.uid); 8605 mActivities.addActivity(a, "activity"); 8606 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8607 if (r == null) { 8608 r = new StringBuilder(256); 8609 } else { 8610 r.append(' '); 8611 } 8612 r.append(a.info.name); 8613 } 8614 } 8615 if (r != null) { 8616 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8617 } 8618 8619 N = pkg.permissionGroups.size(); 8620 r = null; 8621 for (i=0; i<N; i++) { 8622 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8623 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8624 if (cur == null) { 8625 mPermissionGroups.put(pg.info.name, pg); 8626 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8627 if (r == null) { 8628 r = new StringBuilder(256); 8629 } else { 8630 r.append(' '); 8631 } 8632 r.append(pg.info.name); 8633 } 8634 } else { 8635 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8636 + pg.info.packageName + " ignored: original from " 8637 + cur.info.packageName); 8638 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8639 if (r == null) { 8640 r = new StringBuilder(256); 8641 } else { 8642 r.append(' '); 8643 } 8644 r.append("DUP:"); 8645 r.append(pg.info.name); 8646 } 8647 } 8648 } 8649 if (r != null) { 8650 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8651 } 8652 8653 N = pkg.permissions.size(); 8654 r = null; 8655 for (i=0; i<N; i++) { 8656 PackageParser.Permission p = pkg.permissions.get(i); 8657 8658 // Assume by default that we did not install this permission into the system. 8659 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8660 8661 // Now that permission groups have a special meaning, we ignore permission 8662 // groups for legacy apps to prevent unexpected behavior. In particular, 8663 // permissions for one app being granted to someone just becase they happen 8664 // to be in a group defined by another app (before this had no implications). 8665 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8666 p.group = mPermissionGroups.get(p.info.group); 8667 // Warn for a permission in an unknown group. 8668 if (p.info.group != null && p.group == null) { 8669 Slog.w(TAG, "Permission " + p.info.name + " from package " 8670 + p.info.packageName + " in an unknown group " + p.info.group); 8671 } 8672 } 8673 8674 ArrayMap<String, BasePermission> permissionMap = 8675 p.tree ? mSettings.mPermissionTrees 8676 : mSettings.mPermissions; 8677 BasePermission bp = permissionMap.get(p.info.name); 8678 8679 // Allow system apps to redefine non-system permissions 8680 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8681 final boolean currentOwnerIsSystem = (bp.perm != null 8682 && isSystemApp(bp.perm.owner)); 8683 if (isSystemApp(p.owner)) { 8684 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8685 // It's a built-in permission and no owner, take ownership now 8686 bp.packageSetting = pkgSetting; 8687 bp.perm = p; 8688 bp.uid = pkg.applicationInfo.uid; 8689 bp.sourcePackage = p.info.packageName; 8690 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8691 } else if (!currentOwnerIsSystem) { 8692 String msg = "New decl " + p.owner + " of permission " 8693 + p.info.name + " is system; overriding " + bp.sourcePackage; 8694 reportSettingsProblem(Log.WARN, msg); 8695 bp = null; 8696 } 8697 } 8698 } 8699 8700 if (bp == null) { 8701 bp = new BasePermission(p.info.name, p.info.packageName, 8702 BasePermission.TYPE_NORMAL); 8703 permissionMap.put(p.info.name, bp); 8704 } 8705 8706 if (bp.perm == null) { 8707 if (bp.sourcePackage == null 8708 || bp.sourcePackage.equals(p.info.packageName)) { 8709 BasePermission tree = findPermissionTreeLP(p.info.name); 8710 if (tree == null 8711 || tree.sourcePackage.equals(p.info.packageName)) { 8712 bp.packageSetting = pkgSetting; 8713 bp.perm = p; 8714 bp.uid = pkg.applicationInfo.uid; 8715 bp.sourcePackage = p.info.packageName; 8716 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8717 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8718 if (r == null) { 8719 r = new StringBuilder(256); 8720 } else { 8721 r.append(' '); 8722 } 8723 r.append(p.info.name); 8724 } 8725 } else { 8726 Slog.w(TAG, "Permission " + p.info.name + " from package " 8727 + p.info.packageName + " ignored: base tree " 8728 + tree.name + " is from package " 8729 + tree.sourcePackage); 8730 } 8731 } else { 8732 Slog.w(TAG, "Permission " + p.info.name + " from package " 8733 + p.info.packageName + " ignored: original from " 8734 + bp.sourcePackage); 8735 } 8736 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8737 if (r == null) { 8738 r = new StringBuilder(256); 8739 } else { 8740 r.append(' '); 8741 } 8742 r.append("DUP:"); 8743 r.append(p.info.name); 8744 } 8745 if (bp.perm == p) { 8746 bp.protectionLevel = p.info.protectionLevel; 8747 } 8748 } 8749 8750 if (r != null) { 8751 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8752 } 8753 8754 N = pkg.instrumentation.size(); 8755 r = null; 8756 for (i=0; i<N; i++) { 8757 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8758 a.info.packageName = pkg.applicationInfo.packageName; 8759 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8760 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8761 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8762 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8763 a.info.dataDir = pkg.applicationInfo.dataDir; 8764 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8765 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8766 8767 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8768 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8769 mInstrumentation.put(a.getComponentName(), a); 8770 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8771 if (r == null) { 8772 r = new StringBuilder(256); 8773 } else { 8774 r.append(' '); 8775 } 8776 r.append(a.info.name); 8777 } 8778 } 8779 if (r != null) { 8780 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8781 } 8782 8783 if (pkg.protectedBroadcasts != null) { 8784 N = pkg.protectedBroadcasts.size(); 8785 for (i=0; i<N; i++) { 8786 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8787 } 8788 } 8789 8790 pkgSetting.setTimeStamp(scanFileTime); 8791 8792 // Create idmap files for pairs of (packages, overlay packages). 8793 // Note: "android", ie framework-res.apk, is handled by native layers. 8794 if (pkg.mOverlayTarget != null) { 8795 // This is an overlay package. 8796 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8797 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8798 mOverlays.put(pkg.mOverlayTarget, 8799 new ArrayMap<String, PackageParser.Package>()); 8800 } 8801 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8802 map.put(pkg.packageName, pkg); 8803 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8804 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8805 createIdmapFailed = true; 8806 } 8807 } 8808 } else if (mOverlays.containsKey(pkg.packageName) && 8809 !pkg.packageName.equals("android")) { 8810 // This is a regular package, with one or more known overlay packages. 8811 createIdmapsForPackageLI(pkg); 8812 } 8813 } 8814 8815 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8816 8817 if (createIdmapFailed) { 8818 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8819 "scanPackageLI failed to createIdmap"); 8820 } 8821 return pkg; 8822 } 8823 8824 /** 8825 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8826 * is derived purely on the basis of the contents of {@code scanFile} and 8827 * {@code cpuAbiOverride}. 8828 * 8829 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8830 */ 8831 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8832 String cpuAbiOverride, boolean extractLibs) 8833 throws PackageManagerException { 8834 // TODO: We can probably be smarter about this stuff. For installed apps, 8835 // we can calculate this information at install time once and for all. For 8836 // system apps, we can probably assume that this information doesn't change 8837 // after the first boot scan. As things stand, we do lots of unnecessary work. 8838 8839 // Give ourselves some initial paths; we'll come back for another 8840 // pass once we've determined ABI below. 8841 setNativeLibraryPaths(pkg); 8842 8843 // We would never need to extract libs for forward-locked and external packages, 8844 // since the container service will do it for us. We shouldn't attempt to 8845 // extract libs from system app when it was not updated. 8846 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8847 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8848 extractLibs = false; 8849 } 8850 8851 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8852 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8853 8854 NativeLibraryHelper.Handle handle = null; 8855 try { 8856 handle = NativeLibraryHelper.Handle.create(pkg); 8857 // TODO(multiArch): This can be null for apps that didn't go through the 8858 // usual installation process. We can calculate it again, like we 8859 // do during install time. 8860 // 8861 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8862 // unnecessary. 8863 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8864 8865 // Null out the abis so that they can be recalculated. 8866 pkg.applicationInfo.primaryCpuAbi = null; 8867 pkg.applicationInfo.secondaryCpuAbi = null; 8868 if (isMultiArch(pkg.applicationInfo)) { 8869 // Warn if we've set an abiOverride for multi-lib packages.. 8870 // By definition, we need to copy both 32 and 64 bit libraries for 8871 // such packages. 8872 if (pkg.cpuAbiOverride != null 8873 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8874 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8875 } 8876 8877 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8878 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8879 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8880 if (extractLibs) { 8881 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8882 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8883 useIsaSpecificSubdirs); 8884 } else { 8885 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8886 } 8887 } 8888 8889 maybeThrowExceptionForMultiArchCopy( 8890 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8891 8892 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8893 if (extractLibs) { 8894 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8895 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8896 useIsaSpecificSubdirs); 8897 } else { 8898 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8899 } 8900 } 8901 8902 maybeThrowExceptionForMultiArchCopy( 8903 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8904 8905 if (abi64 >= 0) { 8906 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8907 } 8908 8909 if (abi32 >= 0) { 8910 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8911 if (abi64 >= 0) { 8912 if (pkg.use32bitAbi) { 8913 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8914 pkg.applicationInfo.primaryCpuAbi = abi; 8915 } else { 8916 pkg.applicationInfo.secondaryCpuAbi = abi; 8917 } 8918 } else { 8919 pkg.applicationInfo.primaryCpuAbi = abi; 8920 } 8921 } 8922 8923 } else { 8924 String[] abiList = (cpuAbiOverride != null) ? 8925 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8926 8927 // Enable gross and lame hacks for apps that are built with old 8928 // SDK tools. We must scan their APKs for renderscript bitcode and 8929 // not launch them if it's present. Don't bother checking on devices 8930 // that don't have 64 bit support. 8931 boolean needsRenderScriptOverride = false; 8932 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8933 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8934 abiList = Build.SUPPORTED_32_BIT_ABIS; 8935 needsRenderScriptOverride = true; 8936 } 8937 8938 final int copyRet; 8939 if (extractLibs) { 8940 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8941 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8942 } else { 8943 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8944 } 8945 8946 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8947 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8948 "Error unpackaging native libs for app, errorCode=" + copyRet); 8949 } 8950 8951 if (copyRet >= 0) { 8952 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8953 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8954 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8955 } else if (needsRenderScriptOverride) { 8956 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8957 } 8958 } 8959 } catch (IOException ioe) { 8960 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8961 } finally { 8962 IoUtils.closeQuietly(handle); 8963 } 8964 8965 // Now that we've calculated the ABIs and determined if it's an internal app, 8966 // we will go ahead and populate the nativeLibraryPath. 8967 setNativeLibraryPaths(pkg); 8968 } 8969 8970 /** 8971 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8972 * i.e, so that all packages can be run inside a single process if required. 8973 * 8974 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8975 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8976 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8977 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8978 * updating a package that belongs to a shared user. 8979 * 8980 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8981 * adds unnecessary complexity. 8982 */ 8983 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8984 PackageParser.Package scannedPackage, boolean bootComplete) { 8985 String requiredInstructionSet = null; 8986 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8987 requiredInstructionSet = VMRuntime.getInstructionSet( 8988 scannedPackage.applicationInfo.primaryCpuAbi); 8989 } 8990 8991 PackageSetting requirer = null; 8992 for (PackageSetting ps : packagesForUser) { 8993 // If packagesForUser contains scannedPackage, we skip it. This will happen 8994 // when scannedPackage is an update of an existing package. Without this check, 8995 // we will never be able to change the ABI of any package belonging to a shared 8996 // user, even if it's compatible with other packages. 8997 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8998 if (ps.primaryCpuAbiString == null) { 8999 continue; 9000 } 9001 9002 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 9003 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 9004 // We have a mismatch between instruction sets (say arm vs arm64) warn about 9005 // this but there's not much we can do. 9006 String errorMessage = "Instruction set mismatch, " 9007 + ((requirer == null) ? "[caller]" : requirer) 9008 + " requires " + requiredInstructionSet + " whereas " + ps 9009 + " requires " + instructionSet; 9010 Slog.w(TAG, errorMessage); 9011 } 9012 9013 if (requiredInstructionSet == null) { 9014 requiredInstructionSet = instructionSet; 9015 requirer = ps; 9016 } 9017 } 9018 } 9019 9020 if (requiredInstructionSet != null) { 9021 String adjustedAbi; 9022 if (requirer != null) { 9023 // requirer != null implies that either scannedPackage was null or that scannedPackage 9024 // did not require an ABI, in which case we have to adjust scannedPackage to match 9025 // the ABI of the set (which is the same as requirer's ABI) 9026 adjustedAbi = requirer.primaryCpuAbiString; 9027 if (scannedPackage != null) { 9028 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 9029 } 9030 } else { 9031 // requirer == null implies that we're updating all ABIs in the set to 9032 // match scannedPackage. 9033 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 9034 } 9035 9036 for (PackageSetting ps : packagesForUser) { 9037 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 9038 if (ps.primaryCpuAbiString != null) { 9039 continue; 9040 } 9041 9042 ps.primaryCpuAbiString = adjustedAbi; 9043 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9044 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9045 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9046 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9047 + " (requirer=" 9048 + (requirer == null ? "null" : requirer.pkg.packageName) 9049 + ", scannedPackage=" 9050 + (scannedPackage != null ? scannedPackage.packageName : "null") 9051 + ")"); 9052 try { 9053 mInstaller.rmdex(ps.codePathString, 9054 getDexCodeInstructionSet(getPreferredInstructionSet())); 9055 } catch (InstallerException ignored) { 9056 } 9057 } 9058 } 9059 } 9060 } 9061 } 9062 9063 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9064 synchronized (mPackages) { 9065 mResolverReplaced = true; 9066 // Set up information for custom user intent resolution activity. 9067 mResolveActivity.applicationInfo = pkg.applicationInfo; 9068 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9069 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9070 mResolveActivity.processName = pkg.applicationInfo.packageName; 9071 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9072 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9073 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9074 mResolveActivity.theme = 0; 9075 mResolveActivity.exported = true; 9076 mResolveActivity.enabled = true; 9077 mResolveInfo.activityInfo = mResolveActivity; 9078 mResolveInfo.priority = 0; 9079 mResolveInfo.preferredOrder = 0; 9080 mResolveInfo.match = 0; 9081 mResolveComponentName = mCustomResolverComponentName; 9082 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9083 mResolveComponentName); 9084 } 9085 } 9086 9087 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9088 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9089 9090 // Set up information for ephemeral installer activity 9091 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9092 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9093 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9094 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9095 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9096 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9097 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9098 mEphemeralInstallerActivity.theme = 0; 9099 mEphemeralInstallerActivity.exported = true; 9100 mEphemeralInstallerActivity.enabled = true; 9101 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9102 mEphemeralInstallerInfo.priority = 0; 9103 mEphemeralInstallerInfo.preferredOrder = 0; 9104 mEphemeralInstallerInfo.match = 0; 9105 9106 if (DEBUG_EPHEMERAL) { 9107 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9108 } 9109 } 9110 9111 private static String calculateBundledApkRoot(final String codePathString) { 9112 final File codePath = new File(codePathString); 9113 final File codeRoot; 9114 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9115 codeRoot = Environment.getRootDirectory(); 9116 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9117 codeRoot = Environment.getOemDirectory(); 9118 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9119 codeRoot = Environment.getVendorDirectory(); 9120 } else { 9121 // Unrecognized code path; take its top real segment as the apk root: 9122 // e.g. /something/app/blah.apk => /something 9123 try { 9124 File f = codePath.getCanonicalFile(); 9125 File parent = f.getParentFile(); // non-null because codePath is a file 9126 File tmp; 9127 while ((tmp = parent.getParentFile()) != null) { 9128 f = parent; 9129 parent = tmp; 9130 } 9131 codeRoot = f; 9132 Slog.w(TAG, "Unrecognized code path " 9133 + codePath + " - using " + codeRoot); 9134 } catch (IOException e) { 9135 // Can't canonicalize the code path -- shenanigans? 9136 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9137 return Environment.getRootDirectory().getPath(); 9138 } 9139 } 9140 return codeRoot.getPath(); 9141 } 9142 9143 /** 9144 * Derive and set the location of native libraries for the given package, 9145 * which varies depending on where and how the package was installed. 9146 */ 9147 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9148 final ApplicationInfo info = pkg.applicationInfo; 9149 final String codePath = pkg.codePath; 9150 final File codeFile = new File(codePath); 9151 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9152 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9153 9154 info.nativeLibraryRootDir = null; 9155 info.nativeLibraryRootRequiresIsa = false; 9156 info.nativeLibraryDir = null; 9157 info.secondaryNativeLibraryDir = null; 9158 9159 if (isApkFile(codeFile)) { 9160 // Monolithic install 9161 if (bundledApp) { 9162 // If "/system/lib64/apkname" exists, assume that is the per-package 9163 // native library directory to use; otherwise use "/system/lib/apkname". 9164 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9165 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9166 getPrimaryInstructionSet(info)); 9167 9168 // This is a bundled system app so choose the path based on the ABI. 9169 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9170 // is just the default path. 9171 final String apkName = deriveCodePathName(codePath); 9172 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9173 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9174 apkName).getAbsolutePath(); 9175 9176 if (info.secondaryCpuAbi != null) { 9177 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9178 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9179 secondaryLibDir, apkName).getAbsolutePath(); 9180 } 9181 } else if (asecApp) { 9182 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9183 .getAbsolutePath(); 9184 } else { 9185 final String apkName = deriveCodePathName(codePath); 9186 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9187 .getAbsolutePath(); 9188 } 9189 9190 info.nativeLibraryRootRequiresIsa = false; 9191 info.nativeLibraryDir = info.nativeLibraryRootDir; 9192 } else { 9193 // Cluster install 9194 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9195 info.nativeLibraryRootRequiresIsa = true; 9196 9197 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9198 getPrimaryInstructionSet(info)).getAbsolutePath(); 9199 9200 if (info.secondaryCpuAbi != null) { 9201 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9202 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9203 } 9204 } 9205 } 9206 9207 /** 9208 * Calculate the abis and roots for a bundled app. These can uniquely 9209 * be determined from the contents of the system partition, i.e whether 9210 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9211 * of this information, and instead assume that the system was built 9212 * sensibly. 9213 */ 9214 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9215 PackageSetting pkgSetting) { 9216 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9217 9218 // If "/system/lib64/apkname" exists, assume that is the per-package 9219 // native library directory to use; otherwise use "/system/lib/apkname". 9220 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9221 setBundledAppAbi(pkg, apkRoot, apkName); 9222 // pkgSetting might be null during rescan following uninstall of updates 9223 // to a bundled app, so accommodate that possibility. The settings in 9224 // that case will be established later from the parsed package. 9225 // 9226 // If the settings aren't null, sync them up with what we've just derived. 9227 // note that apkRoot isn't stored in the package settings. 9228 if (pkgSetting != null) { 9229 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9230 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9231 } 9232 } 9233 9234 /** 9235 * Deduces the ABI of a bundled app and sets the relevant fields on the 9236 * parsed pkg object. 9237 * 9238 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9239 * under which system libraries are installed. 9240 * @param apkName the name of the installed package. 9241 */ 9242 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9243 final File codeFile = new File(pkg.codePath); 9244 9245 final boolean has64BitLibs; 9246 final boolean has32BitLibs; 9247 if (isApkFile(codeFile)) { 9248 // Monolithic install 9249 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9250 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9251 } else { 9252 // Cluster install 9253 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9254 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9255 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9256 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9257 has64BitLibs = (new File(rootDir, isa)).exists(); 9258 } else { 9259 has64BitLibs = false; 9260 } 9261 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9262 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9263 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9264 has32BitLibs = (new File(rootDir, isa)).exists(); 9265 } else { 9266 has32BitLibs = false; 9267 } 9268 } 9269 9270 if (has64BitLibs && !has32BitLibs) { 9271 // The package has 64 bit libs, but not 32 bit libs. Its primary 9272 // ABI should be 64 bit. We can safely assume here that the bundled 9273 // native libraries correspond to the most preferred ABI in the list. 9274 9275 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9276 pkg.applicationInfo.secondaryCpuAbi = null; 9277 } else if (has32BitLibs && !has64BitLibs) { 9278 // The package has 32 bit libs but not 64 bit libs. Its primary 9279 // ABI should be 32 bit. 9280 9281 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9282 pkg.applicationInfo.secondaryCpuAbi = null; 9283 } else if (has32BitLibs && has64BitLibs) { 9284 // The application has both 64 and 32 bit bundled libraries. We check 9285 // here that the app declares multiArch support, and warn if it doesn't. 9286 // 9287 // We will be lenient here and record both ABIs. The primary will be the 9288 // ABI that's higher on the list, i.e, a device that's configured to prefer 9289 // 64 bit apps will see a 64 bit primary ABI, 9290 9291 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9292 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9293 } 9294 9295 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9296 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9297 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9298 } else { 9299 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9300 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9301 } 9302 } else { 9303 pkg.applicationInfo.primaryCpuAbi = null; 9304 pkg.applicationInfo.secondaryCpuAbi = null; 9305 } 9306 } 9307 9308 private void killApplication(String pkgName, int appId, String reason) { 9309 // Request the ActivityManager to kill the process(only for existing packages) 9310 // so that we do not end up in a confused state while the user is still using the older 9311 // version of the application while the new one gets installed. 9312 final long token = Binder.clearCallingIdentity(); 9313 try { 9314 IActivityManager am = ActivityManagerNative.getDefault(); 9315 if (am != null) { 9316 try { 9317 am.killApplicationWithAppId(pkgName, appId, reason); 9318 } catch (RemoteException e) { 9319 } 9320 } 9321 } finally { 9322 Binder.restoreCallingIdentity(token); 9323 } 9324 } 9325 9326 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9327 // Remove the parent package setting 9328 PackageSetting ps = (PackageSetting) pkg.mExtras; 9329 if (ps != null) { 9330 removePackageLI(ps, chatty); 9331 } 9332 // Remove the child package setting 9333 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9334 for (int i = 0; i < childCount; i++) { 9335 PackageParser.Package childPkg = pkg.childPackages.get(i); 9336 ps = (PackageSetting) childPkg.mExtras; 9337 if (ps != null) { 9338 removePackageLI(ps, chatty); 9339 } 9340 } 9341 } 9342 9343 void removePackageLI(PackageSetting ps, boolean chatty) { 9344 if (DEBUG_INSTALL) { 9345 if (chatty) 9346 Log.d(TAG, "Removing package " + ps.name); 9347 } 9348 9349 // writer 9350 synchronized (mPackages) { 9351 mPackages.remove(ps.name); 9352 final PackageParser.Package pkg = ps.pkg; 9353 if (pkg != null) { 9354 cleanPackageDataStructuresLILPw(pkg, chatty); 9355 } 9356 } 9357 } 9358 9359 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9360 if (DEBUG_INSTALL) { 9361 if (chatty) 9362 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9363 } 9364 9365 // writer 9366 synchronized (mPackages) { 9367 // Remove the parent package 9368 mPackages.remove(pkg.applicationInfo.packageName); 9369 cleanPackageDataStructuresLILPw(pkg, chatty); 9370 9371 // Remove the child packages 9372 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9373 for (int i = 0; i < childCount; i++) { 9374 PackageParser.Package childPkg = pkg.childPackages.get(i); 9375 mPackages.remove(childPkg.applicationInfo.packageName); 9376 cleanPackageDataStructuresLILPw(childPkg, chatty); 9377 } 9378 } 9379 } 9380 9381 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9382 int N = pkg.providers.size(); 9383 StringBuilder r = null; 9384 int i; 9385 for (i=0; i<N; i++) { 9386 PackageParser.Provider p = pkg.providers.get(i); 9387 mProviders.removeProvider(p); 9388 if (p.info.authority == null) { 9389 9390 /* There was another ContentProvider with this authority when 9391 * this app was installed so this authority is null, 9392 * Ignore it as we don't have to unregister the provider. 9393 */ 9394 continue; 9395 } 9396 String names[] = p.info.authority.split(";"); 9397 for (int j = 0; j < names.length; j++) { 9398 if (mProvidersByAuthority.get(names[j]) == p) { 9399 mProvidersByAuthority.remove(names[j]); 9400 if (DEBUG_REMOVE) { 9401 if (chatty) 9402 Log.d(TAG, "Unregistered content provider: " + names[j] 9403 + ", className = " + p.info.name + ", isSyncable = " 9404 + p.info.isSyncable); 9405 } 9406 } 9407 } 9408 if (DEBUG_REMOVE && chatty) { 9409 if (r == null) { 9410 r = new StringBuilder(256); 9411 } else { 9412 r.append(' '); 9413 } 9414 r.append(p.info.name); 9415 } 9416 } 9417 if (r != null) { 9418 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9419 } 9420 9421 N = pkg.services.size(); 9422 r = null; 9423 for (i=0; i<N; i++) { 9424 PackageParser.Service s = pkg.services.get(i); 9425 mServices.removeService(s); 9426 if (chatty) { 9427 if (r == null) { 9428 r = new StringBuilder(256); 9429 } else { 9430 r.append(' '); 9431 } 9432 r.append(s.info.name); 9433 } 9434 } 9435 if (r != null) { 9436 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9437 } 9438 9439 N = pkg.receivers.size(); 9440 r = null; 9441 for (i=0; i<N; i++) { 9442 PackageParser.Activity a = pkg.receivers.get(i); 9443 mReceivers.removeActivity(a, "receiver"); 9444 if (DEBUG_REMOVE && chatty) { 9445 if (r == null) { 9446 r = new StringBuilder(256); 9447 } else { 9448 r.append(' '); 9449 } 9450 r.append(a.info.name); 9451 } 9452 } 9453 if (r != null) { 9454 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9455 } 9456 9457 N = pkg.activities.size(); 9458 r = null; 9459 for (i=0; i<N; i++) { 9460 PackageParser.Activity a = pkg.activities.get(i); 9461 mActivities.removeActivity(a, "activity"); 9462 if (DEBUG_REMOVE && chatty) { 9463 if (r == null) { 9464 r = new StringBuilder(256); 9465 } else { 9466 r.append(' '); 9467 } 9468 r.append(a.info.name); 9469 } 9470 } 9471 if (r != null) { 9472 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9473 } 9474 9475 N = pkg.permissions.size(); 9476 r = null; 9477 for (i=0; i<N; i++) { 9478 PackageParser.Permission p = pkg.permissions.get(i); 9479 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9480 if (bp == null) { 9481 bp = mSettings.mPermissionTrees.get(p.info.name); 9482 } 9483 if (bp != null && bp.perm == p) { 9484 bp.perm = null; 9485 if (DEBUG_REMOVE && chatty) { 9486 if (r == null) { 9487 r = new StringBuilder(256); 9488 } else { 9489 r.append(' '); 9490 } 9491 r.append(p.info.name); 9492 } 9493 } 9494 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9495 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9496 if (appOpPkgs != null) { 9497 appOpPkgs.remove(pkg.packageName); 9498 } 9499 } 9500 } 9501 if (r != null) { 9502 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9503 } 9504 9505 N = pkg.requestedPermissions.size(); 9506 r = null; 9507 for (i=0; i<N; i++) { 9508 String perm = pkg.requestedPermissions.get(i); 9509 BasePermission bp = mSettings.mPermissions.get(perm); 9510 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9511 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9512 if (appOpPkgs != null) { 9513 appOpPkgs.remove(pkg.packageName); 9514 if (appOpPkgs.isEmpty()) { 9515 mAppOpPermissionPackages.remove(perm); 9516 } 9517 } 9518 } 9519 } 9520 if (r != null) { 9521 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9522 } 9523 9524 N = pkg.instrumentation.size(); 9525 r = null; 9526 for (i=0; i<N; i++) { 9527 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9528 mInstrumentation.remove(a.getComponentName()); 9529 if (DEBUG_REMOVE && chatty) { 9530 if (r == null) { 9531 r = new StringBuilder(256); 9532 } else { 9533 r.append(' '); 9534 } 9535 r.append(a.info.name); 9536 } 9537 } 9538 if (r != null) { 9539 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9540 } 9541 9542 r = null; 9543 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9544 // Only system apps can hold shared libraries. 9545 if (pkg.libraryNames != null) { 9546 for (i=0; i<pkg.libraryNames.size(); i++) { 9547 String name = pkg.libraryNames.get(i); 9548 SharedLibraryEntry cur = mSharedLibraries.get(name); 9549 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9550 mSharedLibraries.remove(name); 9551 if (DEBUG_REMOVE && chatty) { 9552 if (r == null) { 9553 r = new StringBuilder(256); 9554 } else { 9555 r.append(' '); 9556 } 9557 r.append(name); 9558 } 9559 } 9560 } 9561 } 9562 } 9563 if (r != null) { 9564 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9565 } 9566 } 9567 9568 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9569 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9570 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9571 return true; 9572 } 9573 } 9574 return false; 9575 } 9576 9577 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9578 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9579 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9580 9581 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9582 // Update the parent permissions 9583 updatePermissionsLPw(pkg.packageName, pkg, flags); 9584 // Update the child permissions 9585 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9586 for (int i = 0; i < childCount; i++) { 9587 PackageParser.Package childPkg = pkg.childPackages.get(i); 9588 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9589 } 9590 } 9591 9592 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9593 int flags) { 9594 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9595 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9596 } 9597 9598 private void updatePermissionsLPw(String changingPkg, 9599 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9600 // Make sure there are no dangling permission trees. 9601 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9602 while (it.hasNext()) { 9603 final BasePermission bp = it.next(); 9604 if (bp.packageSetting == null) { 9605 // We may not yet have parsed the package, so just see if 9606 // we still know about its settings. 9607 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9608 } 9609 if (bp.packageSetting == null) { 9610 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9611 + " from package " + bp.sourcePackage); 9612 it.remove(); 9613 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9614 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9615 Slog.i(TAG, "Removing old permission tree: " + bp.name 9616 + " from package " + bp.sourcePackage); 9617 flags |= UPDATE_PERMISSIONS_ALL; 9618 it.remove(); 9619 } 9620 } 9621 } 9622 9623 // Make sure all dynamic permissions have been assigned to a package, 9624 // and make sure there are no dangling permissions. 9625 it = mSettings.mPermissions.values().iterator(); 9626 while (it.hasNext()) { 9627 final BasePermission bp = it.next(); 9628 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9629 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9630 + bp.name + " pkg=" + bp.sourcePackage 9631 + " info=" + bp.pendingInfo); 9632 if (bp.packageSetting == null && bp.pendingInfo != null) { 9633 final BasePermission tree = findPermissionTreeLP(bp.name); 9634 if (tree != null && tree.perm != null) { 9635 bp.packageSetting = tree.packageSetting; 9636 bp.perm = new PackageParser.Permission(tree.perm.owner, 9637 new PermissionInfo(bp.pendingInfo)); 9638 bp.perm.info.packageName = tree.perm.info.packageName; 9639 bp.perm.info.name = bp.name; 9640 bp.uid = tree.uid; 9641 } 9642 } 9643 } 9644 if (bp.packageSetting == null) { 9645 // We may not yet have parsed the package, so just see if 9646 // we still know about its settings. 9647 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9648 } 9649 if (bp.packageSetting == null) { 9650 Slog.w(TAG, "Removing dangling permission: " + bp.name 9651 + " from package " + bp.sourcePackage); 9652 it.remove(); 9653 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9654 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9655 Slog.i(TAG, "Removing old permission: " + bp.name 9656 + " from package " + bp.sourcePackage); 9657 flags |= UPDATE_PERMISSIONS_ALL; 9658 it.remove(); 9659 } 9660 } 9661 } 9662 9663 // Now update the permissions for all packages, in particular 9664 // replace the granted permissions of the system packages. 9665 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9666 for (PackageParser.Package pkg : mPackages.values()) { 9667 if (pkg != pkgInfo) { 9668 // Only replace for packages on requested volume 9669 final String volumeUuid = getVolumeUuidForPackage(pkg); 9670 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9671 && Objects.equals(replaceVolumeUuid, volumeUuid); 9672 grantPermissionsLPw(pkg, replace, changingPkg); 9673 } 9674 } 9675 } 9676 9677 if (pkgInfo != null) { 9678 // Only replace for packages on requested volume 9679 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9680 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9681 && Objects.equals(replaceVolumeUuid, volumeUuid); 9682 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9683 } 9684 } 9685 9686 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9687 String packageOfInterest) { 9688 // IMPORTANT: There are two types of permissions: install and runtime. 9689 // Install time permissions are granted when the app is installed to 9690 // all device users and users added in the future. Runtime permissions 9691 // are granted at runtime explicitly to specific users. Normal and signature 9692 // protected permissions are install time permissions. Dangerous permissions 9693 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9694 // otherwise they are runtime permissions. This function does not manage 9695 // runtime permissions except for the case an app targeting Lollipop MR1 9696 // being upgraded to target a newer SDK, in which case dangerous permissions 9697 // are transformed from install time to runtime ones. 9698 9699 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9700 if (ps == null) { 9701 return; 9702 } 9703 9704 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9705 9706 PermissionsState permissionsState = ps.getPermissionsState(); 9707 PermissionsState origPermissions = permissionsState; 9708 9709 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9710 9711 boolean runtimePermissionsRevoked = false; 9712 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9713 9714 boolean changedInstallPermission = false; 9715 9716 if (replace) { 9717 ps.installPermissionsFixed = false; 9718 if (!ps.isSharedUser()) { 9719 origPermissions = new PermissionsState(permissionsState); 9720 permissionsState.reset(); 9721 } else { 9722 // We need to know only about runtime permission changes since the 9723 // calling code always writes the install permissions state but 9724 // the runtime ones are written only if changed. The only cases of 9725 // changed runtime permissions here are promotion of an install to 9726 // runtime and revocation of a runtime from a shared user. 9727 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9728 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9729 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9730 runtimePermissionsRevoked = true; 9731 } 9732 } 9733 } 9734 9735 permissionsState.setGlobalGids(mGlobalGids); 9736 9737 final int N = pkg.requestedPermissions.size(); 9738 for (int i=0; i<N; i++) { 9739 final String name = pkg.requestedPermissions.get(i); 9740 final BasePermission bp = mSettings.mPermissions.get(name); 9741 9742 if (DEBUG_INSTALL) { 9743 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9744 } 9745 9746 if (bp == null || bp.packageSetting == null) { 9747 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9748 Slog.w(TAG, "Unknown permission " + name 9749 + " in package " + pkg.packageName); 9750 } 9751 continue; 9752 } 9753 9754 final String perm = bp.name; 9755 boolean allowedSig = false; 9756 int grant = GRANT_DENIED; 9757 9758 // Keep track of app op permissions. 9759 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9760 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9761 if (pkgs == null) { 9762 pkgs = new ArraySet<>(); 9763 mAppOpPermissionPackages.put(bp.name, pkgs); 9764 } 9765 pkgs.add(pkg.packageName); 9766 } 9767 9768 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9769 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9770 >= Build.VERSION_CODES.M; 9771 switch (level) { 9772 case PermissionInfo.PROTECTION_NORMAL: { 9773 // For all apps normal permissions are install time ones. 9774 grant = GRANT_INSTALL; 9775 } break; 9776 9777 case PermissionInfo.PROTECTION_DANGEROUS: { 9778 // If a permission review is required for legacy apps we represent 9779 // their permissions as always granted runtime ones since we need 9780 // to keep the review required permission flag per user while an 9781 // install permission's state is shared across all users. 9782 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9783 // For legacy apps dangerous permissions are install time ones. 9784 grant = GRANT_INSTALL; 9785 } else if (origPermissions.hasInstallPermission(bp.name)) { 9786 // For legacy apps that became modern, install becomes runtime. 9787 grant = GRANT_UPGRADE; 9788 } else if (mPromoteSystemApps 9789 && isSystemApp(ps) 9790 && mExistingSystemPackages.contains(ps.name)) { 9791 // For legacy system apps, install becomes runtime. 9792 // We cannot check hasInstallPermission() for system apps since those 9793 // permissions were granted implicitly and not persisted pre-M. 9794 grant = GRANT_UPGRADE; 9795 } else { 9796 // For modern apps keep runtime permissions unchanged. 9797 grant = GRANT_RUNTIME; 9798 } 9799 } break; 9800 9801 case PermissionInfo.PROTECTION_SIGNATURE: { 9802 // For all apps signature permissions are install time ones. 9803 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9804 if (allowedSig) { 9805 grant = GRANT_INSTALL; 9806 } 9807 } break; 9808 } 9809 9810 if (DEBUG_INSTALL) { 9811 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9812 } 9813 9814 if (grant != GRANT_DENIED) { 9815 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9816 // If this is an existing, non-system package, then 9817 // we can't add any new permissions to it. 9818 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9819 // Except... if this is a permission that was added 9820 // to the platform (note: need to only do this when 9821 // updating the platform). 9822 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9823 grant = GRANT_DENIED; 9824 } 9825 } 9826 } 9827 9828 switch (grant) { 9829 case GRANT_INSTALL: { 9830 // Revoke this as runtime permission to handle the case of 9831 // a runtime permission being downgraded to an install one. 9832 // Also in permission review mode we keep dangerous permissions 9833 // for legacy apps 9834 for (int userId : UserManagerService.getInstance().getUserIds()) { 9835 if (origPermissions.getRuntimePermissionState( 9836 bp.name, userId) != null) { 9837 // Revoke the runtime permission and clear the flags. 9838 origPermissions.revokeRuntimePermission(bp, userId); 9839 origPermissions.updatePermissionFlags(bp, userId, 9840 PackageManager.MASK_PERMISSION_FLAGS, 0); 9841 // If we revoked a permission permission, we have to write. 9842 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9843 changedRuntimePermissionUserIds, userId); 9844 } 9845 } 9846 // Grant an install permission. 9847 if (permissionsState.grantInstallPermission(bp) != 9848 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9849 changedInstallPermission = true; 9850 } 9851 } break; 9852 9853 case GRANT_RUNTIME: { 9854 // Grant previously granted runtime permissions. 9855 for (int userId : UserManagerService.getInstance().getUserIds()) { 9856 PermissionState permissionState = origPermissions 9857 .getRuntimePermissionState(bp.name, userId); 9858 int flags = permissionState != null 9859 ? permissionState.getFlags() : 0; 9860 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9861 if (permissionsState.grantRuntimePermission(bp, userId) == 9862 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9863 // If we cannot put the permission as it was, we have to write. 9864 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9865 changedRuntimePermissionUserIds, userId); 9866 } 9867 // If the app supports runtime permissions no need for a review. 9868 if (Build.PERMISSIONS_REVIEW_REQUIRED 9869 && appSupportsRuntimePermissions 9870 && (flags & PackageManager 9871 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9872 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9873 // Since we changed the flags, we have to write. 9874 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9875 changedRuntimePermissionUserIds, userId); 9876 } 9877 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9878 && !appSupportsRuntimePermissions) { 9879 // For legacy apps that need a permission review, every new 9880 // runtime permission is granted but it is pending a review. 9881 // We also need to review only platform defined runtime 9882 // permissions as these are the only ones the platform knows 9883 // how to disable the API to simulate revocation as legacy 9884 // apps don't expect to run with revoked permissions. 9885 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9886 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9887 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9888 // We changed the flags, hence have to write. 9889 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9890 changedRuntimePermissionUserIds, userId); 9891 } 9892 } 9893 if (permissionsState.grantRuntimePermission(bp, userId) 9894 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9895 // We changed the permission, hence have to write. 9896 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9897 changedRuntimePermissionUserIds, userId); 9898 } 9899 } 9900 // Propagate the permission flags. 9901 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9902 } 9903 } break; 9904 9905 case GRANT_UPGRADE: { 9906 // Grant runtime permissions for a previously held install permission. 9907 PermissionState permissionState = origPermissions 9908 .getInstallPermissionState(bp.name); 9909 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9910 9911 if (origPermissions.revokeInstallPermission(bp) 9912 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9913 // We will be transferring the permission flags, so clear them. 9914 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9915 PackageManager.MASK_PERMISSION_FLAGS, 0); 9916 changedInstallPermission = true; 9917 } 9918 9919 // If the permission is not to be promoted to runtime we ignore it and 9920 // also its other flags as they are not applicable to install permissions. 9921 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9922 for (int userId : currentUserIds) { 9923 if (permissionsState.grantRuntimePermission(bp, userId) != 9924 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9925 // Transfer the permission flags. 9926 permissionsState.updatePermissionFlags(bp, userId, 9927 flags, flags); 9928 // If we granted the permission, we have to write. 9929 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9930 changedRuntimePermissionUserIds, userId); 9931 } 9932 } 9933 } 9934 } break; 9935 9936 default: { 9937 if (packageOfInterest == null 9938 || packageOfInterest.equals(pkg.packageName)) { 9939 Slog.w(TAG, "Not granting permission " + perm 9940 + " to package " + pkg.packageName 9941 + " because it was previously installed without"); 9942 } 9943 } break; 9944 } 9945 } else { 9946 if (permissionsState.revokeInstallPermission(bp) != 9947 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9948 // Also drop the permission flags. 9949 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9950 PackageManager.MASK_PERMISSION_FLAGS, 0); 9951 changedInstallPermission = true; 9952 Slog.i(TAG, "Un-granting permission " + perm 9953 + " from package " + pkg.packageName 9954 + " (protectionLevel=" + bp.protectionLevel 9955 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9956 + ")"); 9957 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9958 // Don't print warning for app op permissions, since it is fine for them 9959 // not to be granted, there is a UI for the user to decide. 9960 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9961 Slog.w(TAG, "Not granting permission " + perm 9962 + " to package " + pkg.packageName 9963 + " (protectionLevel=" + bp.protectionLevel 9964 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9965 + ")"); 9966 } 9967 } 9968 } 9969 } 9970 9971 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9972 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9973 // This is the first that we have heard about this package, so the 9974 // permissions we have now selected are fixed until explicitly 9975 // changed. 9976 ps.installPermissionsFixed = true; 9977 } 9978 9979 // Persist the runtime permissions state for users with changes. If permissions 9980 // were revoked because no app in the shared user declares them we have to 9981 // write synchronously to avoid losing runtime permissions state. 9982 for (int userId : changedRuntimePermissionUserIds) { 9983 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9984 } 9985 9986 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9987 } 9988 9989 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9990 boolean allowed = false; 9991 final int NP = PackageParser.NEW_PERMISSIONS.length; 9992 for (int ip=0; ip<NP; ip++) { 9993 final PackageParser.NewPermissionInfo npi 9994 = PackageParser.NEW_PERMISSIONS[ip]; 9995 if (npi.name.equals(perm) 9996 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9997 allowed = true; 9998 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9999 + pkg.packageName); 10000 break; 10001 } 10002 } 10003 return allowed; 10004 } 10005 10006 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 10007 BasePermission bp, PermissionsState origPermissions) { 10008 boolean allowed; 10009 allowed = (compareSignatures( 10010 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 10011 == PackageManager.SIGNATURE_MATCH) 10012 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 10013 == PackageManager.SIGNATURE_MATCH); 10014 if (!allowed && (bp.protectionLevel 10015 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 10016 if (isSystemApp(pkg)) { 10017 // For updated system applications, a system permission 10018 // is granted only if it had been defined by the original application. 10019 if (pkg.isUpdatedSystemApp()) { 10020 final PackageSetting sysPs = mSettings 10021 .getDisabledSystemPkgLPr(pkg.packageName); 10022 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 10023 // If the original was granted this permission, we take 10024 // that grant decision as read and propagate it to the 10025 // update. 10026 if (sysPs.isPrivileged()) { 10027 allowed = true; 10028 } 10029 } else { 10030 // The system apk may have been updated with an older 10031 // version of the one on the data partition, but which 10032 // granted a new system permission that it didn't have 10033 // before. In this case we do want to allow the app to 10034 // now get the new permission if the ancestral apk is 10035 // privileged to get it. 10036 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 10037 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 10038 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 10039 allowed = true; 10040 break; 10041 } 10042 } 10043 } 10044 // Also if a privileged parent package on the system image or any of 10045 // its children requested a privileged permission, the updated child 10046 // packages can also get the permission. 10047 if (pkg.parentPackage != null) { 10048 final PackageSetting disabledSysParentPs = mSettings 10049 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10050 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10051 && disabledSysParentPs.isPrivileged()) { 10052 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10053 allowed = true; 10054 } else if (disabledSysParentPs.pkg.childPackages != null) { 10055 final int count = disabledSysParentPs.pkg.childPackages.size(); 10056 for (int i = 0; i < count; i++) { 10057 PackageParser.Package disabledSysChildPkg = 10058 disabledSysParentPs.pkg.childPackages.get(i); 10059 if (isPackageRequestingPermission(disabledSysChildPkg, 10060 perm)) { 10061 allowed = true; 10062 break; 10063 } 10064 } 10065 } 10066 } 10067 } 10068 } 10069 } else { 10070 allowed = isPrivilegedApp(pkg); 10071 } 10072 } 10073 } 10074 if (!allowed) { 10075 if (!allowed && (bp.protectionLevel 10076 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10077 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10078 // If this was a previously normal/dangerous permission that got moved 10079 // to a system permission as part of the runtime permission redesign, then 10080 // we still want to blindly grant it to old apps. 10081 allowed = true; 10082 } 10083 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10084 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10085 // If this permission is to be granted to the system installer and 10086 // this app is an installer, then it gets the permission. 10087 allowed = true; 10088 } 10089 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10090 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10091 // If this permission is to be granted to the system verifier and 10092 // this app is a verifier, then it gets the permission. 10093 allowed = true; 10094 } 10095 if (!allowed && (bp.protectionLevel 10096 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10097 && isSystemApp(pkg)) { 10098 // Any pre-installed system app is allowed to get this permission. 10099 allowed = true; 10100 } 10101 if (!allowed && (bp.protectionLevel 10102 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10103 // For development permissions, a development permission 10104 // is granted only if it was already granted. 10105 allowed = origPermissions.hasInstallPermission(perm); 10106 } 10107 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10108 && pkg.packageName.equals(mSetupWizardPackage)) { 10109 // If this permission is to be granted to the system setup wizard and 10110 // this app is a setup wizard, then it gets the permission. 10111 allowed = true; 10112 } 10113 } 10114 return allowed; 10115 } 10116 10117 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10118 final int permCount = pkg.requestedPermissions.size(); 10119 for (int j = 0; j < permCount; j++) { 10120 String requestedPermission = pkg.requestedPermissions.get(j); 10121 if (permission.equals(requestedPermission)) { 10122 return true; 10123 } 10124 } 10125 return false; 10126 } 10127 10128 final class ActivityIntentResolver 10129 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10130 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10131 boolean defaultOnly, int userId) { 10132 if (!sUserManager.exists(userId)) return null; 10133 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10134 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10135 } 10136 10137 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10138 int userId) { 10139 if (!sUserManager.exists(userId)) return null; 10140 mFlags = flags; 10141 return super.queryIntent(intent, resolvedType, 10142 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10143 } 10144 10145 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10146 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10147 if (!sUserManager.exists(userId)) return null; 10148 if (packageActivities == null) { 10149 return null; 10150 } 10151 mFlags = flags; 10152 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10153 final int N = packageActivities.size(); 10154 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10155 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10156 10157 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10158 for (int i = 0; i < N; ++i) { 10159 intentFilters = packageActivities.get(i).intents; 10160 if (intentFilters != null && intentFilters.size() > 0) { 10161 PackageParser.ActivityIntentInfo[] array = 10162 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10163 intentFilters.toArray(array); 10164 listCut.add(array); 10165 } 10166 } 10167 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10168 } 10169 10170 /** 10171 * Finds a privileged activity that matches the specified activity names. 10172 */ 10173 private PackageParser.Activity findMatchingActivity( 10174 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10175 for (PackageParser.Activity sysActivity : activityList) { 10176 if (sysActivity.info.name.equals(activityInfo.name)) { 10177 return sysActivity; 10178 } 10179 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10180 return sysActivity; 10181 } 10182 if (sysActivity.info.targetActivity != null) { 10183 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10184 return sysActivity; 10185 } 10186 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10187 return sysActivity; 10188 } 10189 } 10190 } 10191 return null; 10192 } 10193 10194 public class IterGenerator<E> { 10195 public Iterator<E> generate(ActivityIntentInfo info) { 10196 return null; 10197 } 10198 } 10199 10200 public class ActionIterGenerator extends IterGenerator<String> { 10201 @Override 10202 public Iterator<String> generate(ActivityIntentInfo info) { 10203 return info.actionsIterator(); 10204 } 10205 } 10206 10207 public class CategoriesIterGenerator extends IterGenerator<String> { 10208 @Override 10209 public Iterator<String> generate(ActivityIntentInfo info) { 10210 return info.categoriesIterator(); 10211 } 10212 } 10213 10214 public class SchemesIterGenerator extends IterGenerator<String> { 10215 @Override 10216 public Iterator<String> generate(ActivityIntentInfo info) { 10217 return info.schemesIterator(); 10218 } 10219 } 10220 10221 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10222 @Override 10223 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10224 return info.authoritiesIterator(); 10225 } 10226 } 10227 10228 /** 10229 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10230 * MODIFIED. Do not pass in a list that should not be changed. 10231 */ 10232 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10233 IterGenerator<T> generator, Iterator<T> searchIterator) { 10234 // loop through the set of actions; every one must be found in the intent filter 10235 while (searchIterator.hasNext()) { 10236 // we must have at least one filter in the list to consider a match 10237 if (intentList.size() == 0) { 10238 break; 10239 } 10240 10241 final T searchAction = searchIterator.next(); 10242 10243 // loop through the set of intent filters 10244 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10245 while (intentIter.hasNext()) { 10246 final ActivityIntentInfo intentInfo = intentIter.next(); 10247 boolean selectionFound = false; 10248 10249 // loop through the intent filter's selection criteria; at least one 10250 // of them must match the searched criteria 10251 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10252 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10253 final T intentSelection = intentSelectionIter.next(); 10254 if (intentSelection != null && intentSelection.equals(searchAction)) { 10255 selectionFound = true; 10256 break; 10257 } 10258 } 10259 10260 // the selection criteria wasn't found in this filter's set; this filter 10261 // is not a potential match 10262 if (!selectionFound) { 10263 intentIter.remove(); 10264 } 10265 } 10266 } 10267 } 10268 10269 private boolean isProtectedAction(ActivityIntentInfo filter) { 10270 final Iterator<String> actionsIter = filter.actionsIterator(); 10271 while (actionsIter != null && actionsIter.hasNext()) { 10272 final String filterAction = actionsIter.next(); 10273 if (PROTECTED_ACTIONS.contains(filterAction)) { 10274 return true; 10275 } 10276 } 10277 return false; 10278 } 10279 10280 /** 10281 * Adjusts the priority of the given intent filter according to policy. 10282 * <p> 10283 * <ul> 10284 * <li>The priority for non privileged applications is capped to '0'</li> 10285 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10286 * <li>The priority for unbundled updates to privileged applications is capped to the 10287 * priority defined on the system partition</li> 10288 * </ul> 10289 * <p> 10290 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10291 * allowed to obtain any priority on any action. 10292 */ 10293 private void adjustPriority( 10294 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10295 // nothing to do; priority is fine as-is 10296 if (intent.getPriority() <= 0) { 10297 return; 10298 } 10299 10300 final ActivityInfo activityInfo = intent.activity.info; 10301 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10302 10303 final boolean privilegedApp = 10304 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10305 if (!privilegedApp) { 10306 // non-privileged applications can never define a priority >0 10307 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10308 + " package: " + applicationInfo.packageName 10309 + " activity: " + intent.activity.className 10310 + " origPrio: " + intent.getPriority()); 10311 intent.setPriority(0); 10312 return; 10313 } 10314 10315 if (systemActivities == null) { 10316 // the system package is not disabled; we're parsing the system partition 10317 if (isProtectedAction(intent)) { 10318 if (mDeferProtectedFilters) { 10319 // We can't deal with these just yet. No component should ever obtain a 10320 // >0 priority for a protected actions, with ONE exception -- the setup 10321 // wizard. The setup wizard, however, cannot be known until we're able to 10322 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10323 // until all intent filters have been processed. Chicken, meet egg. 10324 // Let the filter temporarily have a high priority and rectify the 10325 // priorities after all system packages have been scanned. 10326 mProtectedFilters.add(intent); 10327 if (DEBUG_FILTERS) { 10328 Slog.i(TAG, "Protected action; save for later;" 10329 + " package: " + applicationInfo.packageName 10330 + " activity: " + intent.activity.className 10331 + " origPrio: " + intent.getPriority()); 10332 } 10333 return; 10334 } else { 10335 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10336 Slog.i(TAG, "No setup wizard;" 10337 + " All protected intents capped to priority 0"); 10338 } 10339 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10340 if (DEBUG_FILTERS) { 10341 Slog.i(TAG, "Found setup wizard;" 10342 + " allow priority " + intent.getPriority() + ";" 10343 + " package: " + intent.activity.info.packageName 10344 + " activity: " + intent.activity.className 10345 + " priority: " + intent.getPriority()); 10346 } 10347 // setup wizard gets whatever it wants 10348 return; 10349 } 10350 Slog.w(TAG, "Protected action; cap priority to 0;" 10351 + " package: " + intent.activity.info.packageName 10352 + " activity: " + intent.activity.className 10353 + " origPrio: " + intent.getPriority()); 10354 intent.setPriority(0); 10355 return; 10356 } 10357 } 10358 // privileged apps on the system image get whatever priority they request 10359 return; 10360 } 10361 10362 // privileged app unbundled update ... try to find the same activity 10363 final PackageParser.Activity foundActivity = 10364 findMatchingActivity(systemActivities, activityInfo); 10365 if (foundActivity == null) { 10366 // this is a new activity; it cannot obtain >0 priority 10367 if (DEBUG_FILTERS) { 10368 Slog.i(TAG, "New activity; cap priority to 0;" 10369 + " package: " + applicationInfo.packageName 10370 + " activity: " + intent.activity.className 10371 + " origPrio: " + intent.getPriority()); 10372 } 10373 intent.setPriority(0); 10374 return; 10375 } 10376 10377 // found activity, now check for filter equivalence 10378 10379 // a shallow copy is enough; we modify the list, not its contents 10380 final List<ActivityIntentInfo> intentListCopy = 10381 new ArrayList<>(foundActivity.intents); 10382 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10383 10384 // find matching action subsets 10385 final Iterator<String> actionsIterator = intent.actionsIterator(); 10386 if (actionsIterator != null) { 10387 getIntentListSubset( 10388 intentListCopy, new ActionIterGenerator(), actionsIterator); 10389 if (intentListCopy.size() == 0) { 10390 // no more intents to match; we're not equivalent 10391 if (DEBUG_FILTERS) { 10392 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10393 + " package: " + applicationInfo.packageName 10394 + " activity: " + intent.activity.className 10395 + " origPrio: " + intent.getPriority()); 10396 } 10397 intent.setPriority(0); 10398 return; 10399 } 10400 } 10401 10402 // find matching category subsets 10403 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10404 if (categoriesIterator != null) { 10405 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10406 categoriesIterator); 10407 if (intentListCopy.size() == 0) { 10408 // no more intents to match; we're not equivalent 10409 if (DEBUG_FILTERS) { 10410 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10411 + " package: " + applicationInfo.packageName 10412 + " activity: " + intent.activity.className 10413 + " origPrio: " + intent.getPriority()); 10414 } 10415 intent.setPriority(0); 10416 return; 10417 } 10418 } 10419 10420 // find matching schemes subsets 10421 final Iterator<String> schemesIterator = intent.schemesIterator(); 10422 if (schemesIterator != null) { 10423 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10424 schemesIterator); 10425 if (intentListCopy.size() == 0) { 10426 // no more intents to match; we're not equivalent 10427 if (DEBUG_FILTERS) { 10428 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10429 + " package: " + applicationInfo.packageName 10430 + " activity: " + intent.activity.className 10431 + " origPrio: " + intent.getPriority()); 10432 } 10433 intent.setPriority(0); 10434 return; 10435 } 10436 } 10437 10438 // find matching authorities subsets 10439 final Iterator<IntentFilter.AuthorityEntry> 10440 authoritiesIterator = intent.authoritiesIterator(); 10441 if (authoritiesIterator != null) { 10442 getIntentListSubset(intentListCopy, 10443 new AuthoritiesIterGenerator(), 10444 authoritiesIterator); 10445 if (intentListCopy.size() == 0) { 10446 // no more intents to match; we're not equivalent 10447 if (DEBUG_FILTERS) { 10448 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10449 + " package: " + applicationInfo.packageName 10450 + " activity: " + intent.activity.className 10451 + " origPrio: " + intent.getPriority()); 10452 } 10453 intent.setPriority(0); 10454 return; 10455 } 10456 } 10457 10458 // we found matching filter(s); app gets the max priority of all intents 10459 int cappedPriority = 0; 10460 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10461 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10462 } 10463 if (intent.getPriority() > cappedPriority) { 10464 if (DEBUG_FILTERS) { 10465 Slog.i(TAG, "Found matching filter(s);" 10466 + " cap priority to " + cappedPriority + ";" 10467 + " package: " + applicationInfo.packageName 10468 + " activity: " + intent.activity.className 10469 + " origPrio: " + intent.getPriority()); 10470 } 10471 intent.setPriority(cappedPriority); 10472 return; 10473 } 10474 // all this for nothing; the requested priority was <= what was on the system 10475 } 10476 10477 public final void addActivity(PackageParser.Activity a, String type) { 10478 mActivities.put(a.getComponentName(), a); 10479 if (DEBUG_SHOW_INFO) 10480 Log.v( 10481 TAG, " " + type + " " + 10482 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10483 if (DEBUG_SHOW_INFO) 10484 Log.v(TAG, " Class=" + a.info.name); 10485 final int NI = a.intents.size(); 10486 for (int j=0; j<NI; j++) { 10487 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10488 if ("activity".equals(type)) { 10489 final PackageSetting ps = 10490 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10491 final List<PackageParser.Activity> systemActivities = 10492 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10493 adjustPriority(systemActivities, intent); 10494 } 10495 if (DEBUG_SHOW_INFO) { 10496 Log.v(TAG, " IntentFilter:"); 10497 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10498 } 10499 if (!intent.debugCheck()) { 10500 Log.w(TAG, "==> For Activity " + a.info.name); 10501 } 10502 addFilter(intent); 10503 } 10504 } 10505 10506 public final void removeActivity(PackageParser.Activity a, String type) { 10507 mActivities.remove(a.getComponentName()); 10508 if (DEBUG_SHOW_INFO) { 10509 Log.v(TAG, " " + type + " " 10510 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10511 : a.info.name) + ":"); 10512 Log.v(TAG, " Class=" + a.info.name); 10513 } 10514 final int NI = a.intents.size(); 10515 for (int j=0; j<NI; j++) { 10516 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10517 if (DEBUG_SHOW_INFO) { 10518 Log.v(TAG, " IntentFilter:"); 10519 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10520 } 10521 removeFilter(intent); 10522 } 10523 } 10524 10525 @Override 10526 protected boolean allowFilterResult( 10527 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10528 ActivityInfo filterAi = filter.activity.info; 10529 for (int i=dest.size()-1; i>=0; i--) { 10530 ActivityInfo destAi = dest.get(i).activityInfo; 10531 if (destAi.name == filterAi.name 10532 && destAi.packageName == filterAi.packageName) { 10533 return false; 10534 } 10535 } 10536 return true; 10537 } 10538 10539 @Override 10540 protected ActivityIntentInfo[] newArray(int size) { 10541 return new ActivityIntentInfo[size]; 10542 } 10543 10544 @Override 10545 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10546 if (!sUserManager.exists(userId)) return true; 10547 PackageParser.Package p = filter.activity.owner; 10548 if (p != null) { 10549 PackageSetting ps = (PackageSetting)p.mExtras; 10550 if (ps != null) { 10551 // System apps are never considered stopped for purposes of 10552 // filtering, because there may be no way for the user to 10553 // actually re-launch them. 10554 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10555 && ps.getStopped(userId); 10556 } 10557 } 10558 return false; 10559 } 10560 10561 @Override 10562 protected boolean isPackageForFilter(String packageName, 10563 PackageParser.ActivityIntentInfo info) { 10564 return packageName.equals(info.activity.owner.packageName); 10565 } 10566 10567 @Override 10568 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10569 int match, int userId) { 10570 if (!sUserManager.exists(userId)) return null; 10571 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10572 return null; 10573 } 10574 final PackageParser.Activity activity = info.activity; 10575 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10576 if (ps == null) { 10577 return null; 10578 } 10579 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10580 ps.readUserState(userId), userId); 10581 if (ai == null) { 10582 return null; 10583 } 10584 final ResolveInfo res = new ResolveInfo(); 10585 res.activityInfo = ai; 10586 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10587 res.filter = info; 10588 } 10589 if (info != null) { 10590 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10591 } 10592 res.priority = info.getPriority(); 10593 res.preferredOrder = activity.owner.mPreferredOrder; 10594 //System.out.println("Result: " + res.activityInfo.className + 10595 // " = " + res.priority); 10596 res.match = match; 10597 res.isDefault = info.hasDefault; 10598 res.labelRes = info.labelRes; 10599 res.nonLocalizedLabel = info.nonLocalizedLabel; 10600 if (userNeedsBadging(userId)) { 10601 res.noResourceId = true; 10602 } else { 10603 res.icon = info.icon; 10604 } 10605 res.iconResourceId = info.icon; 10606 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10607 return res; 10608 } 10609 10610 @Override 10611 protected void sortResults(List<ResolveInfo> results) { 10612 Collections.sort(results, mResolvePrioritySorter); 10613 } 10614 10615 @Override 10616 protected void dumpFilter(PrintWriter out, String prefix, 10617 PackageParser.ActivityIntentInfo filter) { 10618 out.print(prefix); out.print( 10619 Integer.toHexString(System.identityHashCode(filter.activity))); 10620 out.print(' '); 10621 filter.activity.printComponentShortName(out); 10622 out.print(" filter "); 10623 out.println(Integer.toHexString(System.identityHashCode(filter))); 10624 } 10625 10626 @Override 10627 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10628 return filter.activity; 10629 } 10630 10631 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10632 PackageParser.Activity activity = (PackageParser.Activity)label; 10633 out.print(prefix); out.print( 10634 Integer.toHexString(System.identityHashCode(activity))); 10635 out.print(' '); 10636 activity.printComponentShortName(out); 10637 if (count > 1) { 10638 out.print(" ("); out.print(count); out.print(" filters)"); 10639 } 10640 out.println(); 10641 } 10642 10643 // Keys are String (activity class name), values are Activity. 10644 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10645 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10646 private int mFlags; 10647 } 10648 10649 private final class ServiceIntentResolver 10650 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10651 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10652 boolean defaultOnly, int userId) { 10653 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10654 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10655 } 10656 10657 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10658 int userId) { 10659 if (!sUserManager.exists(userId)) return null; 10660 mFlags = flags; 10661 return super.queryIntent(intent, resolvedType, 10662 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10663 } 10664 10665 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10666 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10667 if (!sUserManager.exists(userId)) return null; 10668 if (packageServices == null) { 10669 return null; 10670 } 10671 mFlags = flags; 10672 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10673 final int N = packageServices.size(); 10674 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10675 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10676 10677 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10678 for (int i = 0; i < N; ++i) { 10679 intentFilters = packageServices.get(i).intents; 10680 if (intentFilters != null && intentFilters.size() > 0) { 10681 PackageParser.ServiceIntentInfo[] array = 10682 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10683 intentFilters.toArray(array); 10684 listCut.add(array); 10685 } 10686 } 10687 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10688 } 10689 10690 public final void addService(PackageParser.Service s) { 10691 mServices.put(s.getComponentName(), s); 10692 if (DEBUG_SHOW_INFO) { 10693 Log.v(TAG, " " 10694 + (s.info.nonLocalizedLabel != null 10695 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10696 Log.v(TAG, " Class=" + s.info.name); 10697 } 10698 final int NI = s.intents.size(); 10699 int j; 10700 for (j=0; j<NI; j++) { 10701 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10702 if (DEBUG_SHOW_INFO) { 10703 Log.v(TAG, " IntentFilter:"); 10704 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10705 } 10706 if (!intent.debugCheck()) { 10707 Log.w(TAG, "==> For Service " + s.info.name); 10708 } 10709 addFilter(intent); 10710 } 10711 } 10712 10713 public final void removeService(PackageParser.Service s) { 10714 mServices.remove(s.getComponentName()); 10715 if (DEBUG_SHOW_INFO) { 10716 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10717 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10718 Log.v(TAG, " Class=" + s.info.name); 10719 } 10720 final int NI = s.intents.size(); 10721 int j; 10722 for (j=0; j<NI; j++) { 10723 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10724 if (DEBUG_SHOW_INFO) { 10725 Log.v(TAG, " IntentFilter:"); 10726 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10727 } 10728 removeFilter(intent); 10729 } 10730 } 10731 10732 @Override 10733 protected boolean allowFilterResult( 10734 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10735 ServiceInfo filterSi = filter.service.info; 10736 for (int i=dest.size()-1; i>=0; i--) { 10737 ServiceInfo destAi = dest.get(i).serviceInfo; 10738 if (destAi.name == filterSi.name 10739 && destAi.packageName == filterSi.packageName) { 10740 return false; 10741 } 10742 } 10743 return true; 10744 } 10745 10746 @Override 10747 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10748 return new PackageParser.ServiceIntentInfo[size]; 10749 } 10750 10751 @Override 10752 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10753 if (!sUserManager.exists(userId)) return true; 10754 PackageParser.Package p = filter.service.owner; 10755 if (p != null) { 10756 PackageSetting ps = (PackageSetting)p.mExtras; 10757 if (ps != null) { 10758 // System apps are never considered stopped for purposes of 10759 // filtering, because there may be no way for the user to 10760 // actually re-launch them. 10761 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10762 && ps.getStopped(userId); 10763 } 10764 } 10765 return false; 10766 } 10767 10768 @Override 10769 protected boolean isPackageForFilter(String packageName, 10770 PackageParser.ServiceIntentInfo info) { 10771 return packageName.equals(info.service.owner.packageName); 10772 } 10773 10774 @Override 10775 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10776 int match, int userId) { 10777 if (!sUserManager.exists(userId)) return null; 10778 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10779 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10780 return null; 10781 } 10782 final PackageParser.Service service = info.service; 10783 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10784 if (ps == null) { 10785 return null; 10786 } 10787 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10788 ps.readUserState(userId), userId); 10789 if (si == null) { 10790 return null; 10791 } 10792 final ResolveInfo res = new ResolveInfo(); 10793 res.serviceInfo = si; 10794 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10795 res.filter = filter; 10796 } 10797 res.priority = info.getPriority(); 10798 res.preferredOrder = service.owner.mPreferredOrder; 10799 res.match = match; 10800 res.isDefault = info.hasDefault; 10801 res.labelRes = info.labelRes; 10802 res.nonLocalizedLabel = info.nonLocalizedLabel; 10803 res.icon = info.icon; 10804 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10805 return res; 10806 } 10807 10808 @Override 10809 protected void sortResults(List<ResolveInfo> results) { 10810 Collections.sort(results, mResolvePrioritySorter); 10811 } 10812 10813 @Override 10814 protected void dumpFilter(PrintWriter out, String prefix, 10815 PackageParser.ServiceIntentInfo filter) { 10816 out.print(prefix); out.print( 10817 Integer.toHexString(System.identityHashCode(filter.service))); 10818 out.print(' '); 10819 filter.service.printComponentShortName(out); 10820 out.print(" filter "); 10821 out.println(Integer.toHexString(System.identityHashCode(filter))); 10822 } 10823 10824 @Override 10825 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10826 return filter.service; 10827 } 10828 10829 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10830 PackageParser.Service service = (PackageParser.Service)label; 10831 out.print(prefix); out.print( 10832 Integer.toHexString(System.identityHashCode(service))); 10833 out.print(' '); 10834 service.printComponentShortName(out); 10835 if (count > 1) { 10836 out.print(" ("); out.print(count); out.print(" filters)"); 10837 } 10838 out.println(); 10839 } 10840 10841// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10842// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10843// final List<ResolveInfo> retList = Lists.newArrayList(); 10844// while (i.hasNext()) { 10845// final ResolveInfo resolveInfo = (ResolveInfo) i; 10846// if (isEnabledLP(resolveInfo.serviceInfo)) { 10847// retList.add(resolveInfo); 10848// } 10849// } 10850// return retList; 10851// } 10852 10853 // Keys are String (activity class name), values are Activity. 10854 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10855 = new ArrayMap<ComponentName, PackageParser.Service>(); 10856 private int mFlags; 10857 }; 10858 10859 private final class ProviderIntentResolver 10860 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10861 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10862 boolean defaultOnly, int userId) { 10863 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10864 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10865 } 10866 10867 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10868 int userId) { 10869 if (!sUserManager.exists(userId)) 10870 return null; 10871 mFlags = flags; 10872 return super.queryIntent(intent, resolvedType, 10873 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10874 } 10875 10876 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10877 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10878 if (!sUserManager.exists(userId)) 10879 return null; 10880 if (packageProviders == null) { 10881 return null; 10882 } 10883 mFlags = flags; 10884 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10885 final int N = packageProviders.size(); 10886 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10887 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10888 10889 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10890 for (int i = 0; i < N; ++i) { 10891 intentFilters = packageProviders.get(i).intents; 10892 if (intentFilters != null && intentFilters.size() > 0) { 10893 PackageParser.ProviderIntentInfo[] array = 10894 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10895 intentFilters.toArray(array); 10896 listCut.add(array); 10897 } 10898 } 10899 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10900 } 10901 10902 public final void addProvider(PackageParser.Provider p) { 10903 if (mProviders.containsKey(p.getComponentName())) { 10904 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10905 return; 10906 } 10907 10908 mProviders.put(p.getComponentName(), p); 10909 if (DEBUG_SHOW_INFO) { 10910 Log.v(TAG, " " 10911 + (p.info.nonLocalizedLabel != null 10912 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10913 Log.v(TAG, " Class=" + p.info.name); 10914 } 10915 final int NI = p.intents.size(); 10916 int j; 10917 for (j = 0; j < NI; j++) { 10918 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10919 if (DEBUG_SHOW_INFO) { 10920 Log.v(TAG, " IntentFilter:"); 10921 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10922 } 10923 if (!intent.debugCheck()) { 10924 Log.w(TAG, "==> For Provider " + p.info.name); 10925 } 10926 addFilter(intent); 10927 } 10928 } 10929 10930 public final void removeProvider(PackageParser.Provider p) { 10931 mProviders.remove(p.getComponentName()); 10932 if (DEBUG_SHOW_INFO) { 10933 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10934 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10935 Log.v(TAG, " Class=" + p.info.name); 10936 } 10937 final int NI = p.intents.size(); 10938 int j; 10939 for (j = 0; j < NI; j++) { 10940 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10941 if (DEBUG_SHOW_INFO) { 10942 Log.v(TAG, " IntentFilter:"); 10943 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10944 } 10945 removeFilter(intent); 10946 } 10947 } 10948 10949 @Override 10950 protected boolean allowFilterResult( 10951 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10952 ProviderInfo filterPi = filter.provider.info; 10953 for (int i = dest.size() - 1; i >= 0; i--) { 10954 ProviderInfo destPi = dest.get(i).providerInfo; 10955 if (destPi.name == filterPi.name 10956 && destPi.packageName == filterPi.packageName) { 10957 return false; 10958 } 10959 } 10960 return true; 10961 } 10962 10963 @Override 10964 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10965 return new PackageParser.ProviderIntentInfo[size]; 10966 } 10967 10968 @Override 10969 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10970 if (!sUserManager.exists(userId)) 10971 return true; 10972 PackageParser.Package p = filter.provider.owner; 10973 if (p != null) { 10974 PackageSetting ps = (PackageSetting) p.mExtras; 10975 if (ps != null) { 10976 // System apps are never considered stopped for purposes of 10977 // filtering, because there may be no way for the user to 10978 // actually re-launch them. 10979 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10980 && ps.getStopped(userId); 10981 } 10982 } 10983 return false; 10984 } 10985 10986 @Override 10987 protected boolean isPackageForFilter(String packageName, 10988 PackageParser.ProviderIntentInfo info) { 10989 return packageName.equals(info.provider.owner.packageName); 10990 } 10991 10992 @Override 10993 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10994 int match, int userId) { 10995 if (!sUserManager.exists(userId)) 10996 return null; 10997 final PackageParser.ProviderIntentInfo info = filter; 10998 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10999 return null; 11000 } 11001 final PackageParser.Provider provider = info.provider; 11002 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 11003 if (ps == null) { 11004 return null; 11005 } 11006 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 11007 ps.readUserState(userId), userId); 11008 if (pi == null) { 11009 return null; 11010 } 11011 final ResolveInfo res = new ResolveInfo(); 11012 res.providerInfo = pi; 11013 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 11014 res.filter = filter; 11015 } 11016 res.priority = info.getPriority(); 11017 res.preferredOrder = provider.owner.mPreferredOrder; 11018 res.match = match; 11019 res.isDefault = info.hasDefault; 11020 res.labelRes = info.labelRes; 11021 res.nonLocalizedLabel = info.nonLocalizedLabel; 11022 res.icon = info.icon; 11023 res.system = res.providerInfo.applicationInfo.isSystemApp(); 11024 return res; 11025 } 11026 11027 @Override 11028 protected void sortResults(List<ResolveInfo> results) { 11029 Collections.sort(results, mResolvePrioritySorter); 11030 } 11031 11032 @Override 11033 protected void dumpFilter(PrintWriter out, String prefix, 11034 PackageParser.ProviderIntentInfo filter) { 11035 out.print(prefix); 11036 out.print( 11037 Integer.toHexString(System.identityHashCode(filter.provider))); 11038 out.print(' '); 11039 filter.provider.printComponentShortName(out); 11040 out.print(" filter "); 11041 out.println(Integer.toHexString(System.identityHashCode(filter))); 11042 } 11043 11044 @Override 11045 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11046 return filter.provider; 11047 } 11048 11049 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11050 PackageParser.Provider provider = (PackageParser.Provider)label; 11051 out.print(prefix); out.print( 11052 Integer.toHexString(System.identityHashCode(provider))); 11053 out.print(' '); 11054 provider.printComponentShortName(out); 11055 if (count > 1) { 11056 out.print(" ("); out.print(count); out.print(" filters)"); 11057 } 11058 out.println(); 11059 } 11060 11061 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11062 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11063 private int mFlags; 11064 } 11065 11066 private static final class EphemeralIntentResolver 11067 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11068 @Override 11069 protected EphemeralResolveIntentInfo[] newArray(int size) { 11070 return new EphemeralResolveIntentInfo[size]; 11071 } 11072 11073 @Override 11074 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11075 return true; 11076 } 11077 11078 @Override 11079 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11080 int userId) { 11081 if (!sUserManager.exists(userId)) { 11082 return null; 11083 } 11084 return info.getEphemeralResolveInfo(); 11085 } 11086 } 11087 11088 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11089 new Comparator<ResolveInfo>() { 11090 public int compare(ResolveInfo r1, ResolveInfo r2) { 11091 int v1 = r1.priority; 11092 int v2 = r2.priority; 11093 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11094 if (v1 != v2) { 11095 return (v1 > v2) ? -1 : 1; 11096 } 11097 v1 = r1.preferredOrder; 11098 v2 = r2.preferredOrder; 11099 if (v1 != v2) { 11100 return (v1 > v2) ? -1 : 1; 11101 } 11102 if (r1.isDefault != r2.isDefault) { 11103 return r1.isDefault ? -1 : 1; 11104 } 11105 v1 = r1.match; 11106 v2 = r2.match; 11107 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11108 if (v1 != v2) { 11109 return (v1 > v2) ? -1 : 1; 11110 } 11111 if (r1.system != r2.system) { 11112 return r1.system ? -1 : 1; 11113 } 11114 if (r1.activityInfo != null) { 11115 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11116 } 11117 if (r1.serviceInfo != null) { 11118 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11119 } 11120 if (r1.providerInfo != null) { 11121 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11122 } 11123 return 0; 11124 } 11125 }; 11126 11127 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11128 new Comparator<ProviderInfo>() { 11129 public int compare(ProviderInfo p1, ProviderInfo p2) { 11130 final int v1 = p1.initOrder; 11131 final int v2 = p2.initOrder; 11132 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11133 } 11134 }; 11135 11136 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11137 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11138 final int[] userIds) { 11139 mHandler.post(new Runnable() { 11140 @Override 11141 public void run() { 11142 try { 11143 final IActivityManager am = ActivityManagerNative.getDefault(); 11144 if (am == null) return; 11145 final int[] resolvedUserIds; 11146 if (userIds == null) { 11147 resolvedUserIds = am.getRunningUserIds(); 11148 } else { 11149 resolvedUserIds = userIds; 11150 } 11151 for (int id : resolvedUserIds) { 11152 final Intent intent = new Intent(action, 11153 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11154 if (extras != null) { 11155 intent.putExtras(extras); 11156 } 11157 if (targetPkg != null) { 11158 intent.setPackage(targetPkg); 11159 } 11160 // Modify the UID when posting to other users 11161 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11162 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11163 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11164 intent.putExtra(Intent.EXTRA_UID, uid); 11165 } 11166 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11167 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11168 if (DEBUG_BROADCASTS) { 11169 RuntimeException here = new RuntimeException("here"); 11170 here.fillInStackTrace(); 11171 Slog.d(TAG, "Sending to user " + id + ": " 11172 + intent.toShortString(false, true, false, false) 11173 + " " + intent.getExtras(), here); 11174 } 11175 am.broadcastIntent(null, intent, null, finishedReceiver, 11176 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11177 null, finishedReceiver != null, false, id); 11178 } 11179 } catch (RemoteException ex) { 11180 } 11181 } 11182 }); 11183 } 11184 11185 /** 11186 * Check if the external storage media is available. This is true if there 11187 * is a mounted external storage medium or if the external storage is 11188 * emulated. 11189 */ 11190 private boolean isExternalMediaAvailable() { 11191 return mMediaMounted || Environment.isExternalStorageEmulated(); 11192 } 11193 11194 @Override 11195 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11196 // writer 11197 synchronized (mPackages) { 11198 if (!isExternalMediaAvailable()) { 11199 // If the external storage is no longer mounted at this point, 11200 // the caller may not have been able to delete all of this 11201 // packages files and can not delete any more. Bail. 11202 return null; 11203 } 11204 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11205 if (lastPackage != null) { 11206 pkgs.remove(lastPackage); 11207 } 11208 if (pkgs.size() > 0) { 11209 return pkgs.get(0); 11210 } 11211 } 11212 return null; 11213 } 11214 11215 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11216 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11217 userId, andCode ? 1 : 0, packageName); 11218 if (mSystemReady) { 11219 msg.sendToTarget(); 11220 } else { 11221 if (mPostSystemReadyMessages == null) { 11222 mPostSystemReadyMessages = new ArrayList<>(); 11223 } 11224 mPostSystemReadyMessages.add(msg); 11225 } 11226 } 11227 11228 void startCleaningPackages() { 11229 // reader 11230 if (!isExternalMediaAvailable()) { 11231 return; 11232 } 11233 synchronized (mPackages) { 11234 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11235 return; 11236 } 11237 } 11238 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11239 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11240 IActivityManager am = ActivityManagerNative.getDefault(); 11241 if (am != null) { 11242 try { 11243 am.startService(null, intent, null, mContext.getOpPackageName(), 11244 UserHandle.USER_SYSTEM); 11245 } catch (RemoteException e) { 11246 } 11247 } 11248 } 11249 11250 @Override 11251 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11252 int installFlags, String installerPackageName, int userId) { 11253 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11254 11255 final int callingUid = Binder.getCallingUid(); 11256 enforceCrossUserPermission(callingUid, userId, 11257 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11258 11259 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11260 try { 11261 if (observer != null) { 11262 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11263 } 11264 } catch (RemoteException re) { 11265 } 11266 return; 11267 } 11268 11269 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11270 installFlags |= PackageManager.INSTALL_FROM_ADB; 11271 11272 } else { 11273 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11274 // about installerPackageName. 11275 11276 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11277 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11278 } 11279 11280 UserHandle user; 11281 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11282 user = UserHandle.ALL; 11283 } else { 11284 user = new UserHandle(userId); 11285 } 11286 11287 // Only system components can circumvent runtime permissions when installing. 11288 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11289 && mContext.checkCallingOrSelfPermission(Manifest.permission 11290 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11291 throw new SecurityException("You need the " 11292 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11293 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11294 } 11295 11296 final File originFile = new File(originPath); 11297 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11298 11299 final Message msg = mHandler.obtainMessage(INIT_COPY); 11300 final VerificationInfo verificationInfo = new VerificationInfo( 11301 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11302 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11303 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11304 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11305 null /*certificates*/); 11306 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11307 msg.obj = params; 11308 11309 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11310 System.identityHashCode(msg.obj)); 11311 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11312 System.identityHashCode(msg.obj)); 11313 11314 mHandler.sendMessage(msg); 11315 } 11316 11317 void installStage(String packageName, File stagedDir, String stagedCid, 11318 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11319 String installerPackageName, int installerUid, UserHandle user, 11320 Certificate[][] certificates) { 11321 if (DEBUG_EPHEMERAL) { 11322 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11323 Slog.d(TAG, "Ephemeral install of " + packageName); 11324 } 11325 } 11326 final VerificationInfo verificationInfo = new VerificationInfo( 11327 sessionParams.originatingUri, sessionParams.referrerUri, 11328 sessionParams.originatingUid, installerUid); 11329 11330 final OriginInfo origin; 11331 if (stagedDir != null) { 11332 origin = OriginInfo.fromStagedFile(stagedDir); 11333 } else { 11334 origin = OriginInfo.fromStagedContainer(stagedCid); 11335 } 11336 11337 final Message msg = mHandler.obtainMessage(INIT_COPY); 11338 final InstallParams params = new InstallParams(origin, null, observer, 11339 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11340 verificationInfo, user, sessionParams.abiOverride, 11341 sessionParams.grantedRuntimePermissions, certificates); 11342 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11343 msg.obj = params; 11344 11345 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11346 System.identityHashCode(msg.obj)); 11347 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11348 System.identityHashCode(msg.obj)); 11349 11350 mHandler.sendMessage(msg); 11351 } 11352 11353 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11354 int userId) { 11355 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11356 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11357 } 11358 11359 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11360 int appId, int userId) { 11361 Bundle extras = new Bundle(1); 11362 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11363 11364 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11365 packageName, extras, 0, null, null, new int[] {userId}); 11366 try { 11367 IActivityManager am = ActivityManagerNative.getDefault(); 11368 if (isSystem && am.isUserRunning(userId, 0)) { 11369 // The just-installed/enabled app is bundled on the system, so presumed 11370 // to be able to run automatically without needing an explicit launch. 11371 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11372 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11373 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11374 .setPackage(packageName); 11375 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11376 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11377 } 11378 } catch (RemoteException e) { 11379 // shouldn't happen 11380 Slog.w(TAG, "Unable to bootstrap installed package", e); 11381 } 11382 } 11383 11384 @Override 11385 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11386 int userId) { 11387 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11388 PackageSetting pkgSetting; 11389 final int uid = Binder.getCallingUid(); 11390 enforceCrossUserPermission(uid, userId, 11391 true /* requireFullPermission */, true /* checkShell */, 11392 "setApplicationHiddenSetting for user " + userId); 11393 11394 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11395 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11396 return false; 11397 } 11398 11399 long callingId = Binder.clearCallingIdentity(); 11400 try { 11401 boolean sendAdded = false; 11402 boolean sendRemoved = false; 11403 // writer 11404 synchronized (mPackages) { 11405 pkgSetting = mSettings.mPackages.get(packageName); 11406 if (pkgSetting == null) { 11407 return false; 11408 } 11409 if (pkgSetting.getHidden(userId) != hidden) { 11410 pkgSetting.setHidden(hidden, userId); 11411 mSettings.writePackageRestrictionsLPr(userId); 11412 if (hidden) { 11413 sendRemoved = true; 11414 } else { 11415 sendAdded = true; 11416 } 11417 } 11418 } 11419 if (sendAdded) { 11420 sendPackageAddedForUser(packageName, pkgSetting, userId); 11421 return true; 11422 } 11423 if (sendRemoved) { 11424 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11425 "hiding pkg"); 11426 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11427 return true; 11428 } 11429 } finally { 11430 Binder.restoreCallingIdentity(callingId); 11431 } 11432 return false; 11433 } 11434 11435 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11436 int userId) { 11437 final PackageRemovedInfo info = new PackageRemovedInfo(); 11438 info.removedPackage = packageName; 11439 info.removedUsers = new int[] {userId}; 11440 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11441 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11442 } 11443 11444 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11445 if (pkgList.length > 0) { 11446 Bundle extras = new Bundle(1); 11447 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11448 11449 sendPackageBroadcast( 11450 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11451 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11452 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11453 new int[] {userId}); 11454 } 11455 } 11456 11457 /** 11458 * Returns true if application is not found or there was an error. Otherwise it returns 11459 * the hidden state of the package for the given user. 11460 */ 11461 @Override 11462 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11463 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11464 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11465 true /* requireFullPermission */, false /* checkShell */, 11466 "getApplicationHidden for user " + userId); 11467 PackageSetting pkgSetting; 11468 long callingId = Binder.clearCallingIdentity(); 11469 try { 11470 // writer 11471 synchronized (mPackages) { 11472 pkgSetting = mSettings.mPackages.get(packageName); 11473 if (pkgSetting == null) { 11474 return true; 11475 } 11476 return pkgSetting.getHidden(userId); 11477 } 11478 } finally { 11479 Binder.restoreCallingIdentity(callingId); 11480 } 11481 } 11482 11483 /** 11484 * @hide 11485 */ 11486 @Override 11487 public int installExistingPackageAsUser(String packageName, int userId) { 11488 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11489 null); 11490 PackageSetting pkgSetting; 11491 final int uid = Binder.getCallingUid(); 11492 enforceCrossUserPermission(uid, userId, 11493 true /* requireFullPermission */, true /* checkShell */, 11494 "installExistingPackage for user " + userId); 11495 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11496 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11497 } 11498 11499 long callingId = Binder.clearCallingIdentity(); 11500 try { 11501 boolean installed = false; 11502 11503 // writer 11504 synchronized (mPackages) { 11505 pkgSetting = mSettings.mPackages.get(packageName); 11506 if (pkgSetting == null) { 11507 return PackageManager.INSTALL_FAILED_INVALID_URI; 11508 } 11509 if (!pkgSetting.getInstalled(userId)) { 11510 pkgSetting.setInstalled(true, userId); 11511 pkgSetting.setHidden(false, userId); 11512 mSettings.writePackageRestrictionsLPr(userId); 11513 installed = true; 11514 } 11515 } 11516 11517 if (installed) { 11518 if (pkgSetting.pkg != null) { 11519 synchronized (mInstallLock) { 11520 // We don't need to freeze for a brand new install 11521 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11522 } 11523 } 11524 sendPackageAddedForUser(packageName, pkgSetting, userId); 11525 } 11526 } finally { 11527 Binder.restoreCallingIdentity(callingId); 11528 } 11529 11530 return PackageManager.INSTALL_SUCCEEDED; 11531 } 11532 11533 boolean isUserRestricted(int userId, String restrictionKey) { 11534 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11535 if (restrictions.getBoolean(restrictionKey, false)) { 11536 Log.w(TAG, "User is restricted: " + restrictionKey); 11537 return true; 11538 } 11539 return false; 11540 } 11541 11542 @Override 11543 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11544 int userId) { 11545 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11546 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11547 true /* requireFullPermission */, true /* checkShell */, 11548 "setPackagesSuspended for user " + userId); 11549 11550 if (ArrayUtils.isEmpty(packageNames)) { 11551 return packageNames; 11552 } 11553 11554 // List of package names for whom the suspended state has changed. 11555 List<String> changedPackages = new ArrayList<>(packageNames.length); 11556 // List of package names for whom the suspended state is not set as requested in this 11557 // method. 11558 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11559 long callingId = Binder.clearCallingIdentity(); 11560 try { 11561 for (int i = 0; i < packageNames.length; i++) { 11562 String packageName = packageNames[i]; 11563 boolean changed = false; 11564 final int appId; 11565 synchronized (mPackages) { 11566 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11567 if (pkgSetting == null) { 11568 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11569 + "\". Skipping suspending/un-suspending."); 11570 unactionedPackages.add(packageName); 11571 continue; 11572 } 11573 appId = pkgSetting.appId; 11574 if (pkgSetting.getSuspended(userId) != suspended) { 11575 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11576 unactionedPackages.add(packageName); 11577 continue; 11578 } 11579 pkgSetting.setSuspended(suspended, userId); 11580 mSettings.writePackageRestrictionsLPr(userId); 11581 changed = true; 11582 changedPackages.add(packageName); 11583 } 11584 } 11585 11586 if (changed && suspended) { 11587 killApplication(packageName, UserHandle.getUid(userId, appId), 11588 "suspending package"); 11589 } 11590 } 11591 } finally { 11592 Binder.restoreCallingIdentity(callingId); 11593 } 11594 11595 if (!changedPackages.isEmpty()) { 11596 sendPackagesSuspendedForUser(changedPackages.toArray( 11597 new String[changedPackages.size()]), userId, suspended); 11598 } 11599 11600 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11601 } 11602 11603 @Override 11604 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11605 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11606 true /* requireFullPermission */, false /* checkShell */, 11607 "isPackageSuspendedForUser for user " + userId); 11608 synchronized (mPackages) { 11609 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11610 if (pkgSetting == null) { 11611 throw new IllegalArgumentException("Unknown target package: " + packageName); 11612 } 11613 return pkgSetting.getSuspended(userId); 11614 } 11615 } 11616 11617 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11618 if (isPackageDeviceAdmin(packageName, userId)) { 11619 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11620 + "\": has an active device admin"); 11621 return false; 11622 } 11623 11624 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11625 if (packageName.equals(activeLauncherPackageName)) { 11626 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11627 + "\": contains the active launcher"); 11628 return false; 11629 } 11630 11631 if (packageName.equals(mRequiredInstallerPackage)) { 11632 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11633 + "\": required for package installation"); 11634 return false; 11635 } 11636 11637 if (packageName.equals(mRequiredVerifierPackage)) { 11638 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11639 + "\": required for package verification"); 11640 return false; 11641 } 11642 11643 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11644 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11645 + "\": is the default dialer"); 11646 return false; 11647 } 11648 11649 return true; 11650 } 11651 11652 private String getActiveLauncherPackageName(int userId) { 11653 Intent intent = new Intent(Intent.ACTION_MAIN); 11654 intent.addCategory(Intent.CATEGORY_HOME); 11655 ResolveInfo resolveInfo = resolveIntent( 11656 intent, 11657 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11658 PackageManager.MATCH_DEFAULT_ONLY, 11659 userId); 11660 11661 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11662 } 11663 11664 private String getDefaultDialerPackageName(int userId) { 11665 synchronized (mPackages) { 11666 return mSettings.getDefaultDialerPackageNameLPw(userId); 11667 } 11668 } 11669 11670 @Override 11671 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11672 mContext.enforceCallingOrSelfPermission( 11673 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11674 "Only package verification agents can verify applications"); 11675 11676 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11677 final PackageVerificationResponse response = new PackageVerificationResponse( 11678 verificationCode, Binder.getCallingUid()); 11679 msg.arg1 = id; 11680 msg.obj = response; 11681 mHandler.sendMessage(msg); 11682 } 11683 11684 @Override 11685 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11686 long millisecondsToDelay) { 11687 mContext.enforceCallingOrSelfPermission( 11688 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11689 "Only package verification agents can extend verification timeouts"); 11690 11691 final PackageVerificationState state = mPendingVerification.get(id); 11692 final PackageVerificationResponse response = new PackageVerificationResponse( 11693 verificationCodeAtTimeout, Binder.getCallingUid()); 11694 11695 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11696 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11697 } 11698 if (millisecondsToDelay < 0) { 11699 millisecondsToDelay = 0; 11700 } 11701 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11702 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11703 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11704 } 11705 11706 if ((state != null) && !state.timeoutExtended()) { 11707 state.extendTimeout(); 11708 11709 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11710 msg.arg1 = id; 11711 msg.obj = response; 11712 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11713 } 11714 } 11715 11716 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11717 int verificationCode, UserHandle user) { 11718 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11719 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11720 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11721 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11722 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11723 11724 mContext.sendBroadcastAsUser(intent, user, 11725 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11726 } 11727 11728 private ComponentName matchComponentForVerifier(String packageName, 11729 List<ResolveInfo> receivers) { 11730 ActivityInfo targetReceiver = null; 11731 11732 final int NR = receivers.size(); 11733 for (int i = 0; i < NR; i++) { 11734 final ResolveInfo info = receivers.get(i); 11735 if (info.activityInfo == null) { 11736 continue; 11737 } 11738 11739 if (packageName.equals(info.activityInfo.packageName)) { 11740 targetReceiver = info.activityInfo; 11741 break; 11742 } 11743 } 11744 11745 if (targetReceiver == null) { 11746 return null; 11747 } 11748 11749 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11750 } 11751 11752 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11753 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11754 if (pkgInfo.verifiers.length == 0) { 11755 return null; 11756 } 11757 11758 final int N = pkgInfo.verifiers.length; 11759 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11760 for (int i = 0; i < N; i++) { 11761 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11762 11763 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11764 receivers); 11765 if (comp == null) { 11766 continue; 11767 } 11768 11769 final int verifierUid = getUidForVerifier(verifierInfo); 11770 if (verifierUid == -1) { 11771 continue; 11772 } 11773 11774 if (DEBUG_VERIFY) { 11775 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11776 + " with the correct signature"); 11777 } 11778 sufficientVerifiers.add(comp); 11779 verificationState.addSufficientVerifier(verifierUid); 11780 } 11781 11782 return sufficientVerifiers; 11783 } 11784 11785 private int getUidForVerifier(VerifierInfo verifierInfo) { 11786 synchronized (mPackages) { 11787 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11788 if (pkg == null) { 11789 return -1; 11790 } else if (pkg.mSignatures.length != 1) { 11791 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11792 + " has more than one signature; ignoring"); 11793 return -1; 11794 } 11795 11796 /* 11797 * If the public key of the package's signature does not match 11798 * our expected public key, then this is a different package and 11799 * we should skip. 11800 */ 11801 11802 final byte[] expectedPublicKey; 11803 try { 11804 final Signature verifierSig = pkg.mSignatures[0]; 11805 final PublicKey publicKey = verifierSig.getPublicKey(); 11806 expectedPublicKey = publicKey.getEncoded(); 11807 } catch (CertificateException e) { 11808 return -1; 11809 } 11810 11811 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11812 11813 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11814 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11815 + " does not have the expected public key; ignoring"); 11816 return -1; 11817 } 11818 11819 return pkg.applicationInfo.uid; 11820 } 11821 } 11822 11823 @Override 11824 public void finishPackageInstall(int token, boolean didLaunch) { 11825 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11826 11827 if (DEBUG_INSTALL) { 11828 Slog.v(TAG, "BM finishing package install for " + token); 11829 } 11830 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11831 11832 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11833 mHandler.sendMessage(msg); 11834 } 11835 11836 /** 11837 * Get the verification agent timeout. 11838 * 11839 * @return verification timeout in milliseconds 11840 */ 11841 private long getVerificationTimeout() { 11842 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11843 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11844 DEFAULT_VERIFICATION_TIMEOUT); 11845 } 11846 11847 /** 11848 * Get the default verification agent response code. 11849 * 11850 * @return default verification response code 11851 */ 11852 private int getDefaultVerificationResponse() { 11853 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11854 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11855 DEFAULT_VERIFICATION_RESPONSE); 11856 } 11857 11858 /** 11859 * Check whether or not package verification has been enabled. 11860 * 11861 * @return true if verification should be performed 11862 */ 11863 private boolean isVerificationEnabled(int userId, int installFlags) { 11864 if (!DEFAULT_VERIFY_ENABLE) { 11865 return false; 11866 } 11867 // Ephemeral apps don't get the full verification treatment 11868 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11869 if (DEBUG_EPHEMERAL) { 11870 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11871 } 11872 return false; 11873 } 11874 11875 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11876 11877 // Check if installing from ADB 11878 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11879 // Do not run verification in a test harness environment 11880 if (ActivityManager.isRunningInTestHarness()) { 11881 return false; 11882 } 11883 if (ensureVerifyAppsEnabled) { 11884 return true; 11885 } 11886 // Check if the developer does not want package verification for ADB installs 11887 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11888 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11889 return false; 11890 } 11891 } 11892 11893 if (ensureVerifyAppsEnabled) { 11894 return true; 11895 } 11896 11897 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11898 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11899 } 11900 11901 @Override 11902 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11903 throws RemoteException { 11904 mContext.enforceCallingOrSelfPermission( 11905 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11906 "Only intentfilter verification agents can verify applications"); 11907 11908 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11909 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11910 Binder.getCallingUid(), verificationCode, failedDomains); 11911 msg.arg1 = id; 11912 msg.obj = response; 11913 mHandler.sendMessage(msg); 11914 } 11915 11916 @Override 11917 public int getIntentVerificationStatus(String packageName, int userId) { 11918 synchronized (mPackages) { 11919 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11920 } 11921 } 11922 11923 @Override 11924 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11925 mContext.enforceCallingOrSelfPermission( 11926 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11927 11928 boolean result = false; 11929 synchronized (mPackages) { 11930 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11931 } 11932 if (result) { 11933 scheduleWritePackageRestrictionsLocked(userId); 11934 } 11935 return result; 11936 } 11937 11938 @Override 11939 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11940 String packageName) { 11941 synchronized (mPackages) { 11942 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11943 } 11944 } 11945 11946 @Override 11947 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11948 if (TextUtils.isEmpty(packageName)) { 11949 return ParceledListSlice.emptyList(); 11950 } 11951 synchronized (mPackages) { 11952 PackageParser.Package pkg = mPackages.get(packageName); 11953 if (pkg == null || pkg.activities == null) { 11954 return ParceledListSlice.emptyList(); 11955 } 11956 final int count = pkg.activities.size(); 11957 ArrayList<IntentFilter> result = new ArrayList<>(); 11958 for (int n=0; n<count; n++) { 11959 PackageParser.Activity activity = pkg.activities.get(n); 11960 if (activity.intents != null && activity.intents.size() > 0) { 11961 result.addAll(activity.intents); 11962 } 11963 } 11964 return new ParceledListSlice<>(result); 11965 } 11966 } 11967 11968 @Override 11969 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11970 mContext.enforceCallingOrSelfPermission( 11971 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11972 11973 synchronized (mPackages) { 11974 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11975 if (packageName != null) { 11976 result |= updateIntentVerificationStatus(packageName, 11977 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11978 userId); 11979 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11980 packageName, userId); 11981 } 11982 return result; 11983 } 11984 } 11985 11986 @Override 11987 public String getDefaultBrowserPackageName(int userId) { 11988 synchronized (mPackages) { 11989 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11990 } 11991 } 11992 11993 /** 11994 * Get the "allow unknown sources" setting. 11995 * 11996 * @return the current "allow unknown sources" setting 11997 */ 11998 private int getUnknownSourcesSettings() { 11999 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 12000 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 12001 -1); 12002 } 12003 12004 @Override 12005 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 12006 final int uid = Binder.getCallingUid(); 12007 // writer 12008 synchronized (mPackages) { 12009 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 12010 if (targetPackageSetting == null) { 12011 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 12012 } 12013 12014 PackageSetting installerPackageSetting; 12015 if (installerPackageName != null) { 12016 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 12017 if (installerPackageSetting == null) { 12018 throw new IllegalArgumentException("Unknown installer package: " 12019 + installerPackageName); 12020 } 12021 } else { 12022 installerPackageSetting = null; 12023 } 12024 12025 Signature[] callerSignature; 12026 Object obj = mSettings.getUserIdLPr(uid); 12027 if (obj != null) { 12028 if (obj instanceof SharedUserSetting) { 12029 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 12030 } else if (obj instanceof PackageSetting) { 12031 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 12032 } else { 12033 throw new SecurityException("Bad object " + obj + " for uid " + uid); 12034 } 12035 } else { 12036 throw new SecurityException("Unknown calling UID: " + uid); 12037 } 12038 12039 // Verify: can't set installerPackageName to a package that is 12040 // not signed with the same cert as the caller. 12041 if (installerPackageSetting != null) { 12042 if (compareSignatures(callerSignature, 12043 installerPackageSetting.signatures.mSignatures) 12044 != PackageManager.SIGNATURE_MATCH) { 12045 throw new SecurityException( 12046 "Caller does not have same cert as new installer package " 12047 + installerPackageName); 12048 } 12049 } 12050 12051 // Verify: if target already has an installer package, it must 12052 // be signed with the same cert as the caller. 12053 if (targetPackageSetting.installerPackageName != null) { 12054 PackageSetting setting = mSettings.mPackages.get( 12055 targetPackageSetting.installerPackageName); 12056 // If the currently set package isn't valid, then it's always 12057 // okay to change it. 12058 if (setting != null) { 12059 if (compareSignatures(callerSignature, 12060 setting.signatures.mSignatures) 12061 != PackageManager.SIGNATURE_MATCH) { 12062 throw new SecurityException( 12063 "Caller does not have same cert as old installer package " 12064 + targetPackageSetting.installerPackageName); 12065 } 12066 } 12067 } 12068 12069 // Okay! 12070 targetPackageSetting.installerPackageName = installerPackageName; 12071 if (installerPackageName != null) { 12072 mSettings.mInstallerPackages.add(installerPackageName); 12073 } 12074 scheduleWriteSettingsLocked(); 12075 } 12076 } 12077 12078 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12079 // Queue up an async operation since the package installation may take a little while. 12080 mHandler.post(new Runnable() { 12081 public void run() { 12082 mHandler.removeCallbacks(this); 12083 // Result object to be returned 12084 PackageInstalledInfo res = new PackageInstalledInfo(); 12085 res.setReturnCode(currentStatus); 12086 res.uid = -1; 12087 res.pkg = null; 12088 res.removedInfo = null; 12089 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12090 args.doPreInstall(res.returnCode); 12091 synchronized (mInstallLock) { 12092 installPackageTracedLI(args, res); 12093 } 12094 args.doPostInstall(res.returnCode, res.uid); 12095 } 12096 12097 // A restore should be performed at this point if (a) the install 12098 // succeeded, (b) the operation is not an update, and (c) the new 12099 // package has not opted out of backup participation. 12100 final boolean update = res.removedInfo != null 12101 && res.removedInfo.removedPackage != null; 12102 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12103 boolean doRestore = !update 12104 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12105 12106 // Set up the post-install work request bookkeeping. This will be used 12107 // and cleaned up by the post-install event handling regardless of whether 12108 // there's a restore pass performed. Token values are >= 1. 12109 int token; 12110 if (mNextInstallToken < 0) mNextInstallToken = 1; 12111 token = mNextInstallToken++; 12112 12113 PostInstallData data = new PostInstallData(args, res); 12114 mRunningInstalls.put(token, data); 12115 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12116 12117 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12118 // Pass responsibility to the Backup Manager. It will perform a 12119 // restore if appropriate, then pass responsibility back to the 12120 // Package Manager to run the post-install observer callbacks 12121 // and broadcasts. 12122 IBackupManager bm = IBackupManager.Stub.asInterface( 12123 ServiceManager.getService(Context.BACKUP_SERVICE)); 12124 if (bm != null) { 12125 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12126 + " to BM for possible restore"); 12127 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12128 try { 12129 // TODO: http://b/22388012 12130 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12131 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12132 } else { 12133 doRestore = false; 12134 } 12135 } catch (RemoteException e) { 12136 // can't happen; the backup manager is local 12137 } catch (Exception e) { 12138 Slog.e(TAG, "Exception trying to enqueue restore", e); 12139 doRestore = false; 12140 } 12141 } else { 12142 Slog.e(TAG, "Backup Manager not found!"); 12143 doRestore = false; 12144 } 12145 } 12146 12147 if (!doRestore) { 12148 // No restore possible, or the Backup Manager was mysteriously not 12149 // available -- just fire the post-install work request directly. 12150 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12151 12152 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12153 12154 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12155 mHandler.sendMessage(msg); 12156 } 12157 } 12158 }); 12159 } 12160 12161 /** 12162 * Callback from PackageSettings whenever an app is first transitioned out of the 12163 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12164 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12165 * here whether the app is the target of an ongoing install, and only send the 12166 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12167 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12168 * handling. 12169 */ 12170 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12171 // Serialize this with the rest of the install-process message chain. In the 12172 // restore-at-install case, this Runnable will necessarily run before the 12173 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12174 // are coherent. In the non-restore case, the app has already completed install 12175 // and been launched through some other means, so it is not in a problematic 12176 // state for observers to see the FIRST_LAUNCH signal. 12177 mHandler.post(new Runnable() { 12178 @Override 12179 public void run() { 12180 for (int i = 0; i < mRunningInstalls.size(); i++) { 12181 final PostInstallData data = mRunningInstalls.valueAt(i); 12182 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12183 // right package; but is it for the right user? 12184 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12185 if (userId == data.res.newUsers[uIndex]) { 12186 if (DEBUG_BACKUP) { 12187 Slog.i(TAG, "Package " + pkgName 12188 + " being restored so deferring FIRST_LAUNCH"); 12189 } 12190 return; 12191 } 12192 } 12193 } 12194 } 12195 // didn't find it, so not being restored 12196 if (DEBUG_BACKUP) { 12197 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12198 } 12199 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12200 } 12201 }); 12202 } 12203 12204 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12205 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12206 installerPkg, null, userIds); 12207 } 12208 12209 private abstract class HandlerParams { 12210 private static final int MAX_RETRIES = 4; 12211 12212 /** 12213 * Number of times startCopy() has been attempted and had a non-fatal 12214 * error. 12215 */ 12216 private int mRetries = 0; 12217 12218 /** User handle for the user requesting the information or installation. */ 12219 private final UserHandle mUser; 12220 String traceMethod; 12221 int traceCookie; 12222 12223 HandlerParams(UserHandle user) { 12224 mUser = user; 12225 } 12226 12227 UserHandle getUser() { 12228 return mUser; 12229 } 12230 12231 HandlerParams setTraceMethod(String traceMethod) { 12232 this.traceMethod = traceMethod; 12233 return this; 12234 } 12235 12236 HandlerParams setTraceCookie(int traceCookie) { 12237 this.traceCookie = traceCookie; 12238 return this; 12239 } 12240 12241 final boolean startCopy() { 12242 boolean res; 12243 try { 12244 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12245 12246 if (++mRetries > MAX_RETRIES) { 12247 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12248 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12249 handleServiceError(); 12250 return false; 12251 } else { 12252 handleStartCopy(); 12253 res = true; 12254 } 12255 } catch (RemoteException e) { 12256 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12257 mHandler.sendEmptyMessage(MCS_RECONNECT); 12258 res = false; 12259 } 12260 handleReturnCode(); 12261 return res; 12262 } 12263 12264 final void serviceError() { 12265 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12266 handleServiceError(); 12267 handleReturnCode(); 12268 } 12269 12270 abstract void handleStartCopy() throws RemoteException; 12271 abstract void handleServiceError(); 12272 abstract void handleReturnCode(); 12273 } 12274 12275 class MeasureParams extends HandlerParams { 12276 private final PackageStats mStats; 12277 private boolean mSuccess; 12278 12279 private final IPackageStatsObserver mObserver; 12280 12281 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12282 super(new UserHandle(stats.userHandle)); 12283 mObserver = observer; 12284 mStats = stats; 12285 } 12286 12287 @Override 12288 public String toString() { 12289 return "MeasureParams{" 12290 + Integer.toHexString(System.identityHashCode(this)) 12291 + " " + mStats.packageName + "}"; 12292 } 12293 12294 @Override 12295 void handleStartCopy() throws RemoteException { 12296 synchronized (mInstallLock) { 12297 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12298 } 12299 12300 if (mSuccess) { 12301 final boolean mounted; 12302 if (Environment.isExternalStorageEmulated()) { 12303 mounted = true; 12304 } else { 12305 final String status = Environment.getExternalStorageState(); 12306 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12307 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12308 } 12309 12310 if (mounted) { 12311 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12312 12313 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12314 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12315 12316 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12317 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12318 12319 // Always subtract cache size, since it's a subdirectory 12320 mStats.externalDataSize -= mStats.externalCacheSize; 12321 12322 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12323 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12324 12325 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12326 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12327 } 12328 } 12329 } 12330 12331 @Override 12332 void handleReturnCode() { 12333 if (mObserver != null) { 12334 try { 12335 mObserver.onGetStatsCompleted(mStats, mSuccess); 12336 } catch (RemoteException e) { 12337 Slog.i(TAG, "Observer no longer exists."); 12338 } 12339 } 12340 } 12341 12342 @Override 12343 void handleServiceError() { 12344 Slog.e(TAG, "Could not measure application " + mStats.packageName 12345 + " external storage"); 12346 } 12347 } 12348 12349 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12350 throws RemoteException { 12351 long result = 0; 12352 for (File path : paths) { 12353 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12354 } 12355 return result; 12356 } 12357 12358 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12359 for (File path : paths) { 12360 try { 12361 mcs.clearDirectory(path.getAbsolutePath()); 12362 } catch (RemoteException e) { 12363 } 12364 } 12365 } 12366 12367 static class OriginInfo { 12368 /** 12369 * Location where install is coming from, before it has been 12370 * copied/renamed into place. This could be a single monolithic APK 12371 * file, or a cluster directory. This location may be untrusted. 12372 */ 12373 final File file; 12374 final String cid; 12375 12376 /** 12377 * Flag indicating that {@link #file} or {@link #cid} has already been 12378 * staged, meaning downstream users don't need to defensively copy the 12379 * contents. 12380 */ 12381 final boolean staged; 12382 12383 /** 12384 * Flag indicating that {@link #file} or {@link #cid} is an already 12385 * installed app that is being moved. 12386 */ 12387 final boolean existing; 12388 12389 final String resolvedPath; 12390 final File resolvedFile; 12391 12392 static OriginInfo fromNothing() { 12393 return new OriginInfo(null, null, false, false); 12394 } 12395 12396 static OriginInfo fromUntrustedFile(File file) { 12397 return new OriginInfo(file, null, false, false); 12398 } 12399 12400 static OriginInfo fromExistingFile(File file) { 12401 return new OriginInfo(file, null, false, true); 12402 } 12403 12404 static OriginInfo fromStagedFile(File file) { 12405 return new OriginInfo(file, null, true, false); 12406 } 12407 12408 static OriginInfo fromStagedContainer(String cid) { 12409 return new OriginInfo(null, cid, true, false); 12410 } 12411 12412 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12413 this.file = file; 12414 this.cid = cid; 12415 this.staged = staged; 12416 this.existing = existing; 12417 12418 if (cid != null) { 12419 resolvedPath = PackageHelper.getSdDir(cid); 12420 resolvedFile = new File(resolvedPath); 12421 } else if (file != null) { 12422 resolvedPath = file.getAbsolutePath(); 12423 resolvedFile = file; 12424 } else { 12425 resolvedPath = null; 12426 resolvedFile = null; 12427 } 12428 } 12429 } 12430 12431 static class MoveInfo { 12432 final int moveId; 12433 final String fromUuid; 12434 final String toUuid; 12435 final String packageName; 12436 final String dataAppName; 12437 final int appId; 12438 final String seinfo; 12439 final int targetSdkVersion; 12440 12441 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12442 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12443 this.moveId = moveId; 12444 this.fromUuid = fromUuid; 12445 this.toUuid = toUuid; 12446 this.packageName = packageName; 12447 this.dataAppName = dataAppName; 12448 this.appId = appId; 12449 this.seinfo = seinfo; 12450 this.targetSdkVersion = targetSdkVersion; 12451 } 12452 } 12453 12454 static class VerificationInfo { 12455 /** A constant used to indicate that a uid value is not present. */ 12456 public static final int NO_UID = -1; 12457 12458 /** URI referencing where the package was downloaded from. */ 12459 final Uri originatingUri; 12460 12461 /** HTTP referrer URI associated with the originatingURI. */ 12462 final Uri referrer; 12463 12464 /** UID of the application that the install request originated from. */ 12465 final int originatingUid; 12466 12467 /** UID of application requesting the install */ 12468 final int installerUid; 12469 12470 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12471 this.originatingUri = originatingUri; 12472 this.referrer = referrer; 12473 this.originatingUid = originatingUid; 12474 this.installerUid = installerUid; 12475 } 12476 } 12477 12478 class InstallParams extends HandlerParams { 12479 final OriginInfo origin; 12480 final MoveInfo move; 12481 final IPackageInstallObserver2 observer; 12482 int installFlags; 12483 final String installerPackageName; 12484 final String volumeUuid; 12485 private InstallArgs mArgs; 12486 private int mRet; 12487 final String packageAbiOverride; 12488 final String[] grantedRuntimePermissions; 12489 final VerificationInfo verificationInfo; 12490 final Certificate[][] certificates; 12491 12492 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12493 int installFlags, String installerPackageName, String volumeUuid, 12494 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12495 String[] grantedPermissions, Certificate[][] certificates) { 12496 super(user); 12497 this.origin = origin; 12498 this.move = move; 12499 this.observer = observer; 12500 this.installFlags = installFlags; 12501 this.installerPackageName = installerPackageName; 12502 this.volumeUuid = volumeUuid; 12503 this.verificationInfo = verificationInfo; 12504 this.packageAbiOverride = packageAbiOverride; 12505 this.grantedRuntimePermissions = grantedPermissions; 12506 this.certificates = certificates; 12507 } 12508 12509 @Override 12510 public String toString() { 12511 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12512 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12513 } 12514 12515 private int installLocationPolicy(PackageInfoLite pkgLite) { 12516 String packageName = pkgLite.packageName; 12517 int installLocation = pkgLite.installLocation; 12518 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12519 // reader 12520 synchronized (mPackages) { 12521 // Currently installed package which the new package is attempting to replace or 12522 // null if no such package is installed. 12523 PackageParser.Package installedPkg = mPackages.get(packageName); 12524 // Package which currently owns the data which the new package will own if installed. 12525 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12526 // will be null whereas dataOwnerPkg will contain information about the package 12527 // which was uninstalled while keeping its data. 12528 PackageParser.Package dataOwnerPkg = installedPkg; 12529 if (dataOwnerPkg == null) { 12530 PackageSetting ps = mSettings.mPackages.get(packageName); 12531 if (ps != null) { 12532 dataOwnerPkg = ps.pkg; 12533 } 12534 } 12535 12536 if (dataOwnerPkg != null) { 12537 // If installed, the package will get access to data left on the device by its 12538 // predecessor. As a security measure, this is permited only if this is not a 12539 // version downgrade or if the predecessor package is marked as debuggable and 12540 // a downgrade is explicitly requested. 12541 // 12542 // On debuggable platform builds, downgrades are permitted even for 12543 // non-debuggable packages to make testing easier. Debuggable platform builds do 12544 // not offer security guarantees and thus it's OK to disable some security 12545 // mechanisms to make debugging/testing easier on those builds. However, even on 12546 // debuggable builds downgrades of packages are permitted only if requested via 12547 // installFlags. This is because we aim to keep the behavior of debuggable 12548 // platform builds as close as possible to the behavior of non-debuggable 12549 // platform builds. 12550 final boolean downgradeRequested = 12551 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12552 final boolean packageDebuggable = 12553 (dataOwnerPkg.applicationInfo.flags 12554 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12555 final boolean downgradePermitted = 12556 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12557 if (!downgradePermitted) { 12558 try { 12559 checkDowngrade(dataOwnerPkg, pkgLite); 12560 } catch (PackageManagerException e) { 12561 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12562 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12563 } 12564 } 12565 } 12566 12567 if (installedPkg != null) { 12568 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12569 // Check for updated system application. 12570 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12571 if (onSd) { 12572 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12573 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12574 } 12575 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12576 } else { 12577 if (onSd) { 12578 // Install flag overrides everything. 12579 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12580 } 12581 // If current upgrade specifies particular preference 12582 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12583 // Application explicitly specified internal. 12584 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12585 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12586 // App explictly prefers external. Let policy decide 12587 } else { 12588 // Prefer previous location 12589 if (isExternal(installedPkg)) { 12590 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12591 } 12592 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12593 } 12594 } 12595 } else { 12596 // Invalid install. Return error code 12597 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12598 } 12599 } 12600 } 12601 // All the special cases have been taken care of. 12602 // Return result based on recommended install location. 12603 if (onSd) { 12604 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12605 } 12606 return pkgLite.recommendedInstallLocation; 12607 } 12608 12609 /* 12610 * Invoke remote method to get package information and install 12611 * location values. Override install location based on default 12612 * policy if needed and then create install arguments based 12613 * on the install location. 12614 */ 12615 public void handleStartCopy() throws RemoteException { 12616 int ret = PackageManager.INSTALL_SUCCEEDED; 12617 12618 // If we're already staged, we've firmly committed to an install location 12619 if (origin.staged) { 12620 if (origin.file != null) { 12621 installFlags |= PackageManager.INSTALL_INTERNAL; 12622 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12623 } else if (origin.cid != null) { 12624 installFlags |= PackageManager.INSTALL_EXTERNAL; 12625 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12626 } else { 12627 throw new IllegalStateException("Invalid stage location"); 12628 } 12629 } 12630 12631 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12632 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12633 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12634 PackageInfoLite pkgLite = null; 12635 12636 if (onInt && onSd) { 12637 // Check if both bits are set. 12638 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12639 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12640 } else if (onSd && ephemeral) { 12641 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12642 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12643 } else { 12644 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12645 packageAbiOverride); 12646 12647 if (DEBUG_EPHEMERAL && ephemeral) { 12648 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12649 } 12650 12651 /* 12652 * If we have too little free space, try to free cache 12653 * before giving up. 12654 */ 12655 if (!origin.staged && pkgLite.recommendedInstallLocation 12656 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12657 // TODO: focus freeing disk space on the target device 12658 final StorageManager storage = StorageManager.from(mContext); 12659 final long lowThreshold = storage.getStorageLowBytes( 12660 Environment.getDataDirectory()); 12661 12662 final long sizeBytes = mContainerService.calculateInstalledSize( 12663 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12664 12665 try { 12666 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12667 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12668 installFlags, packageAbiOverride); 12669 } catch (InstallerException e) { 12670 Slog.w(TAG, "Failed to free cache", e); 12671 } 12672 12673 /* 12674 * The cache free must have deleted the file we 12675 * downloaded to install. 12676 * 12677 * TODO: fix the "freeCache" call to not delete 12678 * the file we care about. 12679 */ 12680 if (pkgLite.recommendedInstallLocation 12681 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12682 pkgLite.recommendedInstallLocation 12683 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12684 } 12685 } 12686 } 12687 12688 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12689 int loc = pkgLite.recommendedInstallLocation; 12690 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12691 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12692 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12693 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12694 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12695 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12696 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12697 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12698 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12699 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12700 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12701 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12702 } else { 12703 // Override with defaults if needed. 12704 loc = installLocationPolicy(pkgLite); 12705 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12706 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12707 } else if (!onSd && !onInt) { 12708 // Override install location with flags 12709 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12710 // Set the flag to install on external media. 12711 installFlags |= PackageManager.INSTALL_EXTERNAL; 12712 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12713 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12714 if (DEBUG_EPHEMERAL) { 12715 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12716 } 12717 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12718 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12719 |PackageManager.INSTALL_INTERNAL); 12720 } else { 12721 // Make sure the flag for installing on external 12722 // media is unset 12723 installFlags |= PackageManager.INSTALL_INTERNAL; 12724 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12725 } 12726 } 12727 } 12728 } 12729 12730 final InstallArgs args = createInstallArgs(this); 12731 mArgs = args; 12732 12733 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12734 // TODO: http://b/22976637 12735 // Apps installed for "all" users use the device owner to verify the app 12736 UserHandle verifierUser = getUser(); 12737 if (verifierUser == UserHandle.ALL) { 12738 verifierUser = UserHandle.SYSTEM; 12739 } 12740 12741 /* 12742 * Determine if we have any installed package verifiers. If we 12743 * do, then we'll defer to them to verify the packages. 12744 */ 12745 final int requiredUid = mRequiredVerifierPackage == null ? -1 12746 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12747 verifierUser.getIdentifier()); 12748 if (!origin.existing && requiredUid != -1 12749 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12750 final Intent verification = new Intent( 12751 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12752 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12753 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12754 PACKAGE_MIME_TYPE); 12755 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12756 12757 // Query all live verifiers based on current user state 12758 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12759 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12760 12761 if (DEBUG_VERIFY) { 12762 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12763 + verification.toString() + " with " + pkgLite.verifiers.length 12764 + " optional verifiers"); 12765 } 12766 12767 final int verificationId = mPendingVerificationToken++; 12768 12769 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12770 12771 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12772 installerPackageName); 12773 12774 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12775 installFlags); 12776 12777 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12778 pkgLite.packageName); 12779 12780 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12781 pkgLite.versionCode); 12782 12783 if (verificationInfo != null) { 12784 if (verificationInfo.originatingUri != null) { 12785 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12786 verificationInfo.originatingUri); 12787 } 12788 if (verificationInfo.referrer != null) { 12789 verification.putExtra(Intent.EXTRA_REFERRER, 12790 verificationInfo.referrer); 12791 } 12792 if (verificationInfo.originatingUid >= 0) { 12793 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12794 verificationInfo.originatingUid); 12795 } 12796 if (verificationInfo.installerUid >= 0) { 12797 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12798 verificationInfo.installerUid); 12799 } 12800 } 12801 12802 final PackageVerificationState verificationState = new PackageVerificationState( 12803 requiredUid, args); 12804 12805 mPendingVerification.append(verificationId, verificationState); 12806 12807 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12808 receivers, verificationState); 12809 12810 /* 12811 * If any sufficient verifiers were listed in the package 12812 * manifest, attempt to ask them. 12813 */ 12814 if (sufficientVerifiers != null) { 12815 final int N = sufficientVerifiers.size(); 12816 if (N == 0) { 12817 Slog.i(TAG, "Additional verifiers required, but none installed."); 12818 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12819 } else { 12820 for (int i = 0; i < N; i++) { 12821 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12822 12823 final Intent sufficientIntent = new Intent(verification); 12824 sufficientIntent.setComponent(verifierComponent); 12825 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12826 } 12827 } 12828 } 12829 12830 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12831 mRequiredVerifierPackage, receivers); 12832 if (ret == PackageManager.INSTALL_SUCCEEDED 12833 && mRequiredVerifierPackage != null) { 12834 Trace.asyncTraceBegin( 12835 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12836 /* 12837 * Send the intent to the required verification agent, 12838 * but only start the verification timeout after the 12839 * target BroadcastReceivers have run. 12840 */ 12841 verification.setComponent(requiredVerifierComponent); 12842 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12843 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12844 new BroadcastReceiver() { 12845 @Override 12846 public void onReceive(Context context, Intent intent) { 12847 final Message msg = mHandler 12848 .obtainMessage(CHECK_PENDING_VERIFICATION); 12849 msg.arg1 = verificationId; 12850 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12851 } 12852 }, null, 0, null, null); 12853 12854 /* 12855 * We don't want the copy to proceed until verification 12856 * succeeds, so null out this field. 12857 */ 12858 mArgs = null; 12859 } 12860 } else { 12861 /* 12862 * No package verification is enabled, so immediately start 12863 * the remote call to initiate copy using temporary file. 12864 */ 12865 ret = args.copyApk(mContainerService, true); 12866 } 12867 } 12868 12869 mRet = ret; 12870 } 12871 12872 @Override 12873 void handleReturnCode() { 12874 // If mArgs is null, then MCS couldn't be reached. When it 12875 // reconnects, it will try again to install. At that point, this 12876 // will succeed. 12877 if (mArgs != null) { 12878 processPendingInstall(mArgs, mRet); 12879 } 12880 } 12881 12882 @Override 12883 void handleServiceError() { 12884 mArgs = createInstallArgs(this); 12885 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12886 } 12887 12888 public boolean isForwardLocked() { 12889 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12890 } 12891 } 12892 12893 /** 12894 * Used during creation of InstallArgs 12895 * 12896 * @param installFlags package installation flags 12897 * @return true if should be installed on external storage 12898 */ 12899 private static boolean installOnExternalAsec(int installFlags) { 12900 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12901 return false; 12902 } 12903 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12904 return true; 12905 } 12906 return false; 12907 } 12908 12909 /** 12910 * Used during creation of InstallArgs 12911 * 12912 * @param installFlags package installation flags 12913 * @return true if should be installed as forward locked 12914 */ 12915 private static boolean installForwardLocked(int installFlags) { 12916 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12917 } 12918 12919 private InstallArgs createInstallArgs(InstallParams params) { 12920 if (params.move != null) { 12921 return new MoveInstallArgs(params); 12922 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12923 return new AsecInstallArgs(params); 12924 } else { 12925 return new FileInstallArgs(params); 12926 } 12927 } 12928 12929 /** 12930 * Create args that describe an existing installed package. Typically used 12931 * when cleaning up old installs, or used as a move source. 12932 */ 12933 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12934 String resourcePath, String[] instructionSets) { 12935 final boolean isInAsec; 12936 if (installOnExternalAsec(installFlags)) { 12937 /* Apps on SD card are always in ASEC containers. */ 12938 isInAsec = true; 12939 } else if (installForwardLocked(installFlags) 12940 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12941 /* 12942 * Forward-locked apps are only in ASEC containers if they're the 12943 * new style 12944 */ 12945 isInAsec = true; 12946 } else { 12947 isInAsec = false; 12948 } 12949 12950 if (isInAsec) { 12951 return new AsecInstallArgs(codePath, instructionSets, 12952 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12953 } else { 12954 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12955 } 12956 } 12957 12958 static abstract class InstallArgs { 12959 /** @see InstallParams#origin */ 12960 final OriginInfo origin; 12961 /** @see InstallParams#move */ 12962 final MoveInfo move; 12963 12964 final IPackageInstallObserver2 observer; 12965 // Always refers to PackageManager flags only 12966 final int installFlags; 12967 final String installerPackageName; 12968 final String volumeUuid; 12969 final UserHandle user; 12970 final String abiOverride; 12971 final String[] installGrantPermissions; 12972 /** If non-null, drop an async trace when the install completes */ 12973 final String traceMethod; 12974 final int traceCookie; 12975 final Certificate[][] certificates; 12976 12977 // The list of instruction sets supported by this app. This is currently 12978 // only used during the rmdex() phase to clean up resources. We can get rid of this 12979 // if we move dex files under the common app path. 12980 /* nullable */ String[] instructionSets; 12981 12982 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12983 int installFlags, String installerPackageName, String volumeUuid, 12984 UserHandle user, String[] instructionSets, 12985 String abiOverride, String[] installGrantPermissions, 12986 String traceMethod, int traceCookie, Certificate[][] certificates) { 12987 this.origin = origin; 12988 this.move = move; 12989 this.installFlags = installFlags; 12990 this.observer = observer; 12991 this.installerPackageName = installerPackageName; 12992 this.volumeUuid = volumeUuid; 12993 this.user = user; 12994 this.instructionSets = instructionSets; 12995 this.abiOverride = abiOverride; 12996 this.installGrantPermissions = installGrantPermissions; 12997 this.traceMethod = traceMethod; 12998 this.traceCookie = traceCookie; 12999 this.certificates = certificates; 13000 } 13001 13002 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 13003 abstract int doPreInstall(int status); 13004 13005 /** 13006 * Rename package into final resting place. All paths on the given 13007 * scanned package should be updated to reflect the rename. 13008 */ 13009 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 13010 abstract int doPostInstall(int status, int uid); 13011 13012 /** @see PackageSettingBase#codePathString */ 13013 abstract String getCodePath(); 13014 /** @see PackageSettingBase#resourcePathString */ 13015 abstract String getResourcePath(); 13016 13017 // Need installer lock especially for dex file removal. 13018 abstract void cleanUpResourcesLI(); 13019 abstract boolean doPostDeleteLI(boolean delete); 13020 13021 /** 13022 * Called before the source arguments are copied. This is used mostly 13023 * for MoveParams when it needs to read the source file to put it in the 13024 * destination. 13025 */ 13026 int doPreCopy() { 13027 return PackageManager.INSTALL_SUCCEEDED; 13028 } 13029 13030 /** 13031 * Called after the source arguments are copied. This is used mostly for 13032 * MoveParams when it needs to read the source file to put it in the 13033 * destination. 13034 */ 13035 int doPostCopy(int uid) { 13036 return PackageManager.INSTALL_SUCCEEDED; 13037 } 13038 13039 protected boolean isFwdLocked() { 13040 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 13041 } 13042 13043 protected boolean isExternalAsec() { 13044 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13045 } 13046 13047 protected boolean isEphemeral() { 13048 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13049 } 13050 13051 UserHandle getUser() { 13052 return user; 13053 } 13054 } 13055 13056 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13057 if (!allCodePaths.isEmpty()) { 13058 if (instructionSets == null) { 13059 throw new IllegalStateException("instructionSet == null"); 13060 } 13061 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13062 for (String codePath : allCodePaths) { 13063 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13064 try { 13065 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13066 } catch (InstallerException ignored) { 13067 } 13068 } 13069 } 13070 } 13071 } 13072 13073 /** 13074 * Logic to handle installation of non-ASEC applications, including copying 13075 * and renaming logic. 13076 */ 13077 class FileInstallArgs extends InstallArgs { 13078 private File codeFile; 13079 private File resourceFile; 13080 13081 // Example topology: 13082 // /data/app/com.example/base.apk 13083 // /data/app/com.example/split_foo.apk 13084 // /data/app/com.example/lib/arm/libfoo.so 13085 // /data/app/com.example/lib/arm64/libfoo.so 13086 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13087 13088 /** New install */ 13089 FileInstallArgs(InstallParams params) { 13090 super(params.origin, params.move, params.observer, params.installFlags, 13091 params.installerPackageName, params.volumeUuid, 13092 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13093 params.grantedRuntimePermissions, 13094 params.traceMethod, params.traceCookie, params.certificates); 13095 if (isFwdLocked()) { 13096 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13097 } 13098 } 13099 13100 /** Existing install */ 13101 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13102 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13103 null, null, null, 0, null /*certificates*/); 13104 this.codeFile = (codePath != null) ? new File(codePath) : null; 13105 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13106 } 13107 13108 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13109 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13110 try { 13111 return doCopyApk(imcs, temp); 13112 } finally { 13113 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13114 } 13115 } 13116 13117 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13118 if (origin.staged) { 13119 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13120 codeFile = origin.file; 13121 resourceFile = origin.file; 13122 return PackageManager.INSTALL_SUCCEEDED; 13123 } 13124 13125 try { 13126 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13127 final File tempDir = 13128 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13129 codeFile = tempDir; 13130 resourceFile = tempDir; 13131 } catch (IOException e) { 13132 Slog.w(TAG, "Failed to create copy file: " + e); 13133 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13134 } 13135 13136 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13137 @Override 13138 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13139 if (!FileUtils.isValidExtFilename(name)) { 13140 throw new IllegalArgumentException("Invalid filename: " + name); 13141 } 13142 try { 13143 final File file = new File(codeFile, name); 13144 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13145 O_RDWR | O_CREAT, 0644); 13146 Os.chmod(file.getAbsolutePath(), 0644); 13147 return new ParcelFileDescriptor(fd); 13148 } catch (ErrnoException e) { 13149 throw new RemoteException("Failed to open: " + e.getMessage()); 13150 } 13151 } 13152 }; 13153 13154 int ret = PackageManager.INSTALL_SUCCEEDED; 13155 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13156 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13157 Slog.e(TAG, "Failed to copy package"); 13158 return ret; 13159 } 13160 13161 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13162 NativeLibraryHelper.Handle handle = null; 13163 try { 13164 handle = NativeLibraryHelper.Handle.create(codeFile); 13165 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13166 abiOverride); 13167 } catch (IOException e) { 13168 Slog.e(TAG, "Copying native libraries failed", e); 13169 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13170 } finally { 13171 IoUtils.closeQuietly(handle); 13172 } 13173 13174 return ret; 13175 } 13176 13177 int doPreInstall(int status) { 13178 if (status != PackageManager.INSTALL_SUCCEEDED) { 13179 cleanUp(); 13180 } 13181 return status; 13182 } 13183 13184 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13185 if (status != PackageManager.INSTALL_SUCCEEDED) { 13186 cleanUp(); 13187 return false; 13188 } 13189 13190 final File targetDir = codeFile.getParentFile(); 13191 final File beforeCodeFile = codeFile; 13192 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13193 13194 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13195 try { 13196 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13197 } catch (ErrnoException e) { 13198 Slog.w(TAG, "Failed to rename", e); 13199 return false; 13200 } 13201 13202 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13203 Slog.w(TAG, "Failed to restorecon"); 13204 return false; 13205 } 13206 13207 // Reflect the rename internally 13208 codeFile = afterCodeFile; 13209 resourceFile = afterCodeFile; 13210 13211 // Reflect the rename in scanned details 13212 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13213 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13214 afterCodeFile, pkg.baseCodePath)); 13215 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13216 afterCodeFile, pkg.splitCodePaths)); 13217 13218 // Reflect the rename in app info 13219 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13220 pkg.setApplicationInfoCodePath(pkg.codePath); 13221 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13222 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13223 pkg.setApplicationInfoResourcePath(pkg.codePath); 13224 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13225 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13226 13227 return true; 13228 } 13229 13230 int doPostInstall(int status, int uid) { 13231 if (status != PackageManager.INSTALL_SUCCEEDED) { 13232 cleanUp(); 13233 } 13234 return status; 13235 } 13236 13237 @Override 13238 String getCodePath() { 13239 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13240 } 13241 13242 @Override 13243 String getResourcePath() { 13244 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13245 } 13246 13247 private boolean cleanUp() { 13248 if (codeFile == null || !codeFile.exists()) { 13249 return false; 13250 } 13251 13252 removeCodePathLI(codeFile); 13253 13254 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13255 resourceFile.delete(); 13256 } 13257 13258 return true; 13259 } 13260 13261 void cleanUpResourcesLI() { 13262 // Try enumerating all code paths before deleting 13263 List<String> allCodePaths = Collections.EMPTY_LIST; 13264 if (codeFile != null && codeFile.exists()) { 13265 try { 13266 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13267 allCodePaths = pkg.getAllCodePaths(); 13268 } catch (PackageParserException e) { 13269 // Ignored; we tried our best 13270 } 13271 } 13272 13273 cleanUp(); 13274 removeDexFiles(allCodePaths, instructionSets); 13275 } 13276 13277 boolean doPostDeleteLI(boolean delete) { 13278 // XXX err, shouldn't we respect the delete flag? 13279 cleanUpResourcesLI(); 13280 return true; 13281 } 13282 } 13283 13284 private boolean isAsecExternal(String cid) { 13285 final String asecPath = PackageHelper.getSdFilesystem(cid); 13286 return !asecPath.startsWith(mAsecInternalPath); 13287 } 13288 13289 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13290 PackageManagerException { 13291 if (copyRet < 0) { 13292 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13293 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13294 throw new PackageManagerException(copyRet, message); 13295 } 13296 } 13297 } 13298 13299 /** 13300 * Extract the MountService "container ID" from the full code path of an 13301 * .apk. 13302 */ 13303 static String cidFromCodePath(String fullCodePath) { 13304 int eidx = fullCodePath.lastIndexOf("/"); 13305 String subStr1 = fullCodePath.substring(0, eidx); 13306 int sidx = subStr1.lastIndexOf("/"); 13307 return subStr1.substring(sidx+1, eidx); 13308 } 13309 13310 /** 13311 * Logic to handle installation of ASEC applications, including copying and 13312 * renaming logic. 13313 */ 13314 class AsecInstallArgs extends InstallArgs { 13315 static final String RES_FILE_NAME = "pkg.apk"; 13316 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13317 13318 String cid; 13319 String packagePath; 13320 String resourcePath; 13321 13322 /** New install */ 13323 AsecInstallArgs(InstallParams params) { 13324 super(params.origin, params.move, params.observer, params.installFlags, 13325 params.installerPackageName, params.volumeUuid, 13326 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13327 params.grantedRuntimePermissions, 13328 params.traceMethod, params.traceCookie, params.certificates); 13329 } 13330 13331 /** Existing install */ 13332 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13333 boolean isExternal, boolean isForwardLocked) { 13334 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13335 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13336 instructionSets, null, null, null, 0, null /*certificates*/); 13337 // Hackily pretend we're still looking at a full code path 13338 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13339 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13340 } 13341 13342 // Extract cid from fullCodePath 13343 int eidx = fullCodePath.lastIndexOf("/"); 13344 String subStr1 = fullCodePath.substring(0, eidx); 13345 int sidx = subStr1.lastIndexOf("/"); 13346 cid = subStr1.substring(sidx+1, eidx); 13347 setMountPath(subStr1); 13348 } 13349 13350 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13351 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13352 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13353 instructionSets, null, null, null, 0, null /*certificates*/); 13354 this.cid = cid; 13355 setMountPath(PackageHelper.getSdDir(cid)); 13356 } 13357 13358 void createCopyFile() { 13359 cid = mInstallerService.allocateExternalStageCidLegacy(); 13360 } 13361 13362 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13363 if (origin.staged && origin.cid != null) { 13364 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13365 cid = origin.cid; 13366 setMountPath(PackageHelper.getSdDir(cid)); 13367 return PackageManager.INSTALL_SUCCEEDED; 13368 } 13369 13370 if (temp) { 13371 createCopyFile(); 13372 } else { 13373 /* 13374 * Pre-emptively destroy the container since it's destroyed if 13375 * copying fails due to it existing anyway. 13376 */ 13377 PackageHelper.destroySdDir(cid); 13378 } 13379 13380 final String newMountPath = imcs.copyPackageToContainer( 13381 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13382 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13383 13384 if (newMountPath != null) { 13385 setMountPath(newMountPath); 13386 return PackageManager.INSTALL_SUCCEEDED; 13387 } else { 13388 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13389 } 13390 } 13391 13392 @Override 13393 String getCodePath() { 13394 return packagePath; 13395 } 13396 13397 @Override 13398 String getResourcePath() { 13399 return resourcePath; 13400 } 13401 13402 int doPreInstall(int status) { 13403 if (status != PackageManager.INSTALL_SUCCEEDED) { 13404 // Destroy container 13405 PackageHelper.destroySdDir(cid); 13406 } else { 13407 boolean mounted = PackageHelper.isContainerMounted(cid); 13408 if (!mounted) { 13409 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13410 Process.SYSTEM_UID); 13411 if (newMountPath != null) { 13412 setMountPath(newMountPath); 13413 } else { 13414 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13415 } 13416 } 13417 } 13418 return status; 13419 } 13420 13421 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13422 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13423 String newMountPath = null; 13424 if (PackageHelper.isContainerMounted(cid)) { 13425 // Unmount the container 13426 if (!PackageHelper.unMountSdDir(cid)) { 13427 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13428 return false; 13429 } 13430 } 13431 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13432 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13433 " which might be stale. Will try to clean up."); 13434 // Clean up the stale container and proceed to recreate. 13435 if (!PackageHelper.destroySdDir(newCacheId)) { 13436 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13437 return false; 13438 } 13439 // Successfully cleaned up stale container. Try to rename again. 13440 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13441 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13442 + " inspite of cleaning it up."); 13443 return false; 13444 } 13445 } 13446 if (!PackageHelper.isContainerMounted(newCacheId)) { 13447 Slog.w(TAG, "Mounting container " + newCacheId); 13448 newMountPath = PackageHelper.mountSdDir(newCacheId, 13449 getEncryptKey(), Process.SYSTEM_UID); 13450 } else { 13451 newMountPath = PackageHelper.getSdDir(newCacheId); 13452 } 13453 if (newMountPath == null) { 13454 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13455 return false; 13456 } 13457 Log.i(TAG, "Succesfully renamed " + cid + 13458 " to " + newCacheId + 13459 " at new path: " + newMountPath); 13460 cid = newCacheId; 13461 13462 final File beforeCodeFile = new File(packagePath); 13463 setMountPath(newMountPath); 13464 final File afterCodeFile = new File(packagePath); 13465 13466 // Reflect the rename in scanned details 13467 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13468 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13469 afterCodeFile, pkg.baseCodePath)); 13470 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13471 afterCodeFile, pkg.splitCodePaths)); 13472 13473 // Reflect the rename in app info 13474 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13475 pkg.setApplicationInfoCodePath(pkg.codePath); 13476 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13477 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13478 pkg.setApplicationInfoResourcePath(pkg.codePath); 13479 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13480 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13481 13482 return true; 13483 } 13484 13485 private void setMountPath(String mountPath) { 13486 final File mountFile = new File(mountPath); 13487 13488 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13489 if (monolithicFile.exists()) { 13490 packagePath = monolithicFile.getAbsolutePath(); 13491 if (isFwdLocked()) { 13492 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13493 } else { 13494 resourcePath = packagePath; 13495 } 13496 } else { 13497 packagePath = mountFile.getAbsolutePath(); 13498 resourcePath = packagePath; 13499 } 13500 } 13501 13502 int doPostInstall(int status, int uid) { 13503 if (status != PackageManager.INSTALL_SUCCEEDED) { 13504 cleanUp(); 13505 } else { 13506 final int groupOwner; 13507 final String protectedFile; 13508 if (isFwdLocked()) { 13509 groupOwner = UserHandle.getSharedAppGid(uid); 13510 protectedFile = RES_FILE_NAME; 13511 } else { 13512 groupOwner = -1; 13513 protectedFile = null; 13514 } 13515 13516 if (uid < Process.FIRST_APPLICATION_UID 13517 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13518 Slog.e(TAG, "Failed to finalize " + cid); 13519 PackageHelper.destroySdDir(cid); 13520 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13521 } 13522 13523 boolean mounted = PackageHelper.isContainerMounted(cid); 13524 if (!mounted) { 13525 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13526 } 13527 } 13528 return status; 13529 } 13530 13531 private void cleanUp() { 13532 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13533 13534 // Destroy secure container 13535 PackageHelper.destroySdDir(cid); 13536 } 13537 13538 private List<String> getAllCodePaths() { 13539 final File codeFile = new File(getCodePath()); 13540 if (codeFile != null && codeFile.exists()) { 13541 try { 13542 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13543 return pkg.getAllCodePaths(); 13544 } catch (PackageParserException e) { 13545 // Ignored; we tried our best 13546 } 13547 } 13548 return Collections.EMPTY_LIST; 13549 } 13550 13551 void cleanUpResourcesLI() { 13552 // Enumerate all code paths before deleting 13553 cleanUpResourcesLI(getAllCodePaths()); 13554 } 13555 13556 private void cleanUpResourcesLI(List<String> allCodePaths) { 13557 cleanUp(); 13558 removeDexFiles(allCodePaths, instructionSets); 13559 } 13560 13561 String getPackageName() { 13562 return getAsecPackageName(cid); 13563 } 13564 13565 boolean doPostDeleteLI(boolean delete) { 13566 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13567 final List<String> allCodePaths = getAllCodePaths(); 13568 boolean mounted = PackageHelper.isContainerMounted(cid); 13569 if (mounted) { 13570 // Unmount first 13571 if (PackageHelper.unMountSdDir(cid)) { 13572 mounted = false; 13573 } 13574 } 13575 if (!mounted && delete) { 13576 cleanUpResourcesLI(allCodePaths); 13577 } 13578 return !mounted; 13579 } 13580 13581 @Override 13582 int doPreCopy() { 13583 if (isFwdLocked()) { 13584 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13585 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13586 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13587 } 13588 } 13589 13590 return PackageManager.INSTALL_SUCCEEDED; 13591 } 13592 13593 @Override 13594 int doPostCopy(int uid) { 13595 if (isFwdLocked()) { 13596 if (uid < Process.FIRST_APPLICATION_UID 13597 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13598 RES_FILE_NAME)) { 13599 Slog.e(TAG, "Failed to finalize " + cid); 13600 PackageHelper.destroySdDir(cid); 13601 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13602 } 13603 } 13604 13605 return PackageManager.INSTALL_SUCCEEDED; 13606 } 13607 } 13608 13609 /** 13610 * Logic to handle movement of existing installed applications. 13611 */ 13612 class MoveInstallArgs extends InstallArgs { 13613 private File codeFile; 13614 private File resourceFile; 13615 13616 /** New install */ 13617 MoveInstallArgs(InstallParams params) { 13618 super(params.origin, params.move, params.observer, params.installFlags, 13619 params.installerPackageName, params.volumeUuid, 13620 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13621 params.grantedRuntimePermissions, 13622 params.traceMethod, params.traceCookie, params.certificates); 13623 } 13624 13625 int copyApk(IMediaContainerService imcs, boolean temp) { 13626 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13627 + move.fromUuid + " to " + move.toUuid); 13628 synchronized (mInstaller) { 13629 try { 13630 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13631 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13632 } catch (InstallerException e) { 13633 Slog.w(TAG, "Failed to move app", e); 13634 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13635 } 13636 } 13637 13638 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13639 resourceFile = codeFile; 13640 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13641 13642 return PackageManager.INSTALL_SUCCEEDED; 13643 } 13644 13645 int doPreInstall(int status) { 13646 if (status != PackageManager.INSTALL_SUCCEEDED) { 13647 cleanUp(move.toUuid); 13648 } 13649 return status; 13650 } 13651 13652 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13653 if (status != PackageManager.INSTALL_SUCCEEDED) { 13654 cleanUp(move.toUuid); 13655 return false; 13656 } 13657 13658 // Reflect the move in app info 13659 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13660 pkg.setApplicationInfoCodePath(pkg.codePath); 13661 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13662 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13663 pkg.setApplicationInfoResourcePath(pkg.codePath); 13664 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13665 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13666 13667 return true; 13668 } 13669 13670 int doPostInstall(int status, int uid) { 13671 if (status == PackageManager.INSTALL_SUCCEEDED) { 13672 cleanUp(move.fromUuid); 13673 } else { 13674 cleanUp(move.toUuid); 13675 } 13676 return status; 13677 } 13678 13679 @Override 13680 String getCodePath() { 13681 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13682 } 13683 13684 @Override 13685 String getResourcePath() { 13686 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13687 } 13688 13689 private boolean cleanUp(String volumeUuid) { 13690 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13691 move.dataAppName); 13692 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13693 final int[] userIds = sUserManager.getUserIds(); 13694 synchronized (mInstallLock) { 13695 // Clean up both app data and code 13696 // All package moves are frozen until finished 13697 for (int userId : userIds) { 13698 try { 13699 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13700 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13701 } catch (InstallerException e) { 13702 Slog.w(TAG, String.valueOf(e)); 13703 } 13704 } 13705 removeCodePathLI(codeFile); 13706 } 13707 return true; 13708 } 13709 13710 void cleanUpResourcesLI() { 13711 throw new UnsupportedOperationException(); 13712 } 13713 13714 boolean doPostDeleteLI(boolean delete) { 13715 throw new UnsupportedOperationException(); 13716 } 13717 } 13718 13719 static String getAsecPackageName(String packageCid) { 13720 int idx = packageCid.lastIndexOf("-"); 13721 if (idx == -1) { 13722 return packageCid; 13723 } 13724 return packageCid.substring(0, idx); 13725 } 13726 13727 // Utility method used to create code paths based on package name and available index. 13728 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13729 String idxStr = ""; 13730 int idx = 1; 13731 // Fall back to default value of idx=1 if prefix is not 13732 // part of oldCodePath 13733 if (oldCodePath != null) { 13734 String subStr = oldCodePath; 13735 // Drop the suffix right away 13736 if (suffix != null && subStr.endsWith(suffix)) { 13737 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13738 } 13739 // If oldCodePath already contains prefix find out the 13740 // ending index to either increment or decrement. 13741 int sidx = subStr.lastIndexOf(prefix); 13742 if (sidx != -1) { 13743 subStr = subStr.substring(sidx + prefix.length()); 13744 if (subStr != null) { 13745 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13746 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13747 } 13748 try { 13749 idx = Integer.parseInt(subStr); 13750 if (idx <= 1) { 13751 idx++; 13752 } else { 13753 idx--; 13754 } 13755 } catch(NumberFormatException e) { 13756 } 13757 } 13758 } 13759 } 13760 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13761 return prefix + idxStr; 13762 } 13763 13764 private File getNextCodePath(File targetDir, String packageName) { 13765 int suffix = 1; 13766 File result; 13767 do { 13768 result = new File(targetDir, packageName + "-" + suffix); 13769 suffix++; 13770 } while (result.exists()); 13771 return result; 13772 } 13773 13774 // Utility method that returns the relative package path with respect 13775 // to the installation directory. Like say for /data/data/com.test-1.apk 13776 // string com.test-1 is returned. 13777 static String deriveCodePathName(String codePath) { 13778 if (codePath == null) { 13779 return null; 13780 } 13781 final File codeFile = new File(codePath); 13782 final String name = codeFile.getName(); 13783 if (codeFile.isDirectory()) { 13784 return name; 13785 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13786 final int lastDot = name.lastIndexOf('.'); 13787 return name.substring(0, lastDot); 13788 } else { 13789 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13790 return null; 13791 } 13792 } 13793 13794 static class PackageInstalledInfo { 13795 String name; 13796 int uid; 13797 // The set of users that originally had this package installed. 13798 int[] origUsers; 13799 // The set of users that now have this package installed. 13800 int[] newUsers; 13801 PackageParser.Package pkg; 13802 int returnCode; 13803 String returnMsg; 13804 PackageRemovedInfo removedInfo; 13805 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13806 13807 public void setError(int code, String msg) { 13808 setReturnCode(code); 13809 setReturnMessage(msg); 13810 Slog.w(TAG, msg); 13811 } 13812 13813 public void setError(String msg, PackageParserException e) { 13814 setReturnCode(e.error); 13815 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13816 Slog.w(TAG, msg, e); 13817 } 13818 13819 public void setError(String msg, PackageManagerException e) { 13820 returnCode = e.error; 13821 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13822 Slog.w(TAG, msg, e); 13823 } 13824 13825 public void setReturnCode(int returnCode) { 13826 this.returnCode = returnCode; 13827 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13828 for (int i = 0; i < childCount; i++) { 13829 addedChildPackages.valueAt(i).returnCode = returnCode; 13830 } 13831 } 13832 13833 private void setReturnMessage(String returnMsg) { 13834 this.returnMsg = returnMsg; 13835 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13836 for (int i = 0; i < childCount; i++) { 13837 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13838 } 13839 } 13840 13841 // In some error cases we want to convey more info back to the observer 13842 String origPackage; 13843 String origPermission; 13844 } 13845 13846 /* 13847 * Install a non-existing package. 13848 */ 13849 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13850 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13851 PackageInstalledInfo res) { 13852 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13853 13854 // Remember this for later, in case we need to rollback this install 13855 String pkgName = pkg.packageName; 13856 13857 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13858 13859 synchronized(mPackages) { 13860 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13861 // A package with the same name is already installed, though 13862 // it has been renamed to an older name. The package we 13863 // are trying to install should be installed as an update to 13864 // the existing one, but that has not been requested, so bail. 13865 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13866 + " without first uninstalling package running as " 13867 + mSettings.mRenamedPackages.get(pkgName)); 13868 return; 13869 } 13870 if (mPackages.containsKey(pkgName)) { 13871 // Don't allow installation over an existing package with the same name. 13872 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13873 + " without first uninstalling."); 13874 return; 13875 } 13876 } 13877 13878 try { 13879 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13880 System.currentTimeMillis(), user); 13881 13882 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13883 13884 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13885 prepareAppDataAfterInstallLIF(newPackage); 13886 13887 } else { 13888 // Remove package from internal structures, but keep around any 13889 // data that might have already existed 13890 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13891 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13892 } 13893 } catch (PackageManagerException e) { 13894 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13895 } 13896 13897 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13898 } 13899 13900 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13901 // Can't rotate keys during boot or if sharedUser. 13902 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13903 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13904 return false; 13905 } 13906 // app is using upgradeKeySets; make sure all are valid 13907 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13908 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13909 for (int i = 0; i < upgradeKeySets.length; i++) { 13910 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13911 Slog.wtf(TAG, "Package " 13912 + (oldPs.name != null ? oldPs.name : "<null>") 13913 + " contains upgrade-key-set reference to unknown key-set: " 13914 + upgradeKeySets[i] 13915 + " reverting to signatures check."); 13916 return false; 13917 } 13918 } 13919 return true; 13920 } 13921 13922 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13923 // Upgrade keysets are being used. Determine if new package has a superset of the 13924 // required keys. 13925 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13926 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13927 for (int i = 0; i < upgradeKeySets.length; i++) { 13928 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13929 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13930 return true; 13931 } 13932 } 13933 return false; 13934 } 13935 13936 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13937 try (DigestInputStream digestStream = 13938 new DigestInputStream(new FileInputStream(file), digest)) { 13939 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13940 } 13941 } 13942 13943 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13944 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13945 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13946 13947 final PackageParser.Package oldPackage; 13948 final String pkgName = pkg.packageName; 13949 final int[] allUsers; 13950 final int[] installedUsers; 13951 13952 synchronized(mPackages) { 13953 oldPackage = mPackages.get(pkgName); 13954 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13955 13956 // don't allow upgrade to target a release SDK from a pre-release SDK 13957 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13958 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13959 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13960 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13961 if (oldTargetsPreRelease 13962 && !newTargetsPreRelease 13963 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13964 Slog.w(TAG, "Can't install package targeting released sdk"); 13965 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13966 return; 13967 } 13968 13969 // don't allow an upgrade from full to ephemeral 13970 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13971 if (isEphemeral && !oldIsEphemeral) { 13972 // can't downgrade from full to ephemeral 13973 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13974 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13975 return; 13976 } 13977 13978 // verify signatures are valid 13979 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13980 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13981 if (!checkUpgradeKeySetLP(ps, pkg)) { 13982 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13983 "New package not signed by keys specified by upgrade-keysets: " 13984 + pkgName); 13985 return; 13986 } 13987 } else { 13988 // default to original signature matching 13989 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13990 != PackageManager.SIGNATURE_MATCH) { 13991 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13992 "New package has a different signature: " + pkgName); 13993 return; 13994 } 13995 } 13996 13997 // don't allow a system upgrade unless the upgrade hash matches 13998 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13999 byte[] digestBytes = null; 14000 try { 14001 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 14002 updateDigest(digest, new File(pkg.baseCodePath)); 14003 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 14004 for (String path : pkg.splitCodePaths) { 14005 updateDigest(digest, new File(path)); 14006 } 14007 } 14008 digestBytes = digest.digest(); 14009 } catch (NoSuchAlgorithmException | IOException e) { 14010 res.setError(INSTALL_FAILED_INVALID_APK, 14011 "Could not compute hash: " + pkgName); 14012 return; 14013 } 14014 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 14015 res.setError(INSTALL_FAILED_INVALID_APK, 14016 "New package fails restrict-update check: " + pkgName); 14017 return; 14018 } 14019 // retain upgrade restriction 14020 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 14021 } 14022 14023 // Check for shared user id changes 14024 String invalidPackageName = 14025 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 14026 if (invalidPackageName != null) { 14027 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 14028 "Package " + invalidPackageName + " tried to change user " 14029 + oldPackage.mSharedUserId); 14030 return; 14031 } 14032 14033 // In case of rollback, remember per-user/profile install state 14034 allUsers = sUserManager.getUserIds(); 14035 installedUsers = ps.queryInstalledUsers(allUsers, true); 14036 } 14037 14038 // Update what is removed 14039 res.removedInfo = new PackageRemovedInfo(); 14040 res.removedInfo.uid = oldPackage.applicationInfo.uid; 14041 res.removedInfo.removedPackage = oldPackage.packageName; 14042 res.removedInfo.isUpdate = true; 14043 res.removedInfo.origUsers = installedUsers; 14044 final int childCount = (oldPackage.childPackages != null) 14045 ? oldPackage.childPackages.size() : 0; 14046 for (int i = 0; i < childCount; i++) { 14047 boolean childPackageUpdated = false; 14048 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14049 if (res.addedChildPackages != null) { 14050 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14051 if (childRes != null) { 14052 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14053 childRes.removedInfo.removedPackage = childPkg.packageName; 14054 childRes.removedInfo.isUpdate = true; 14055 childPackageUpdated = true; 14056 } 14057 } 14058 if (!childPackageUpdated) { 14059 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14060 childRemovedRes.removedPackage = childPkg.packageName; 14061 childRemovedRes.isUpdate = false; 14062 childRemovedRes.dataRemoved = true; 14063 synchronized (mPackages) { 14064 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14065 if (childPs != null) { 14066 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14067 } 14068 } 14069 if (res.removedInfo.removedChildPackages == null) { 14070 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14071 } 14072 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14073 } 14074 } 14075 14076 boolean sysPkg = (isSystemApp(oldPackage)); 14077 if (sysPkg) { 14078 // Set the system/privileged flags as needed 14079 final boolean privileged = 14080 (oldPackage.applicationInfo.privateFlags 14081 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14082 final int systemPolicyFlags = policyFlags 14083 | PackageParser.PARSE_IS_SYSTEM 14084 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14085 14086 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14087 user, allUsers, installerPackageName, res); 14088 } else { 14089 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14090 user, allUsers, installerPackageName, res); 14091 } 14092 } 14093 14094 public List<String> getPreviousCodePaths(String packageName) { 14095 final PackageSetting ps = mSettings.mPackages.get(packageName); 14096 final List<String> result = new ArrayList<String>(); 14097 if (ps != null && ps.oldCodePaths != null) { 14098 result.addAll(ps.oldCodePaths); 14099 } 14100 return result; 14101 } 14102 14103 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14104 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14105 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14106 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14107 + deletedPackage); 14108 14109 String pkgName = deletedPackage.packageName; 14110 boolean deletedPkg = true; 14111 boolean addedPkg = false; 14112 boolean updatedSettings = false; 14113 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14114 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14115 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14116 14117 final long origUpdateTime = (pkg.mExtras != null) 14118 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14119 14120 // First delete the existing package while retaining the data directory 14121 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14122 res.removedInfo, true, pkg)) { 14123 // If the existing package wasn't successfully deleted 14124 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14125 deletedPkg = false; 14126 } else { 14127 // Successfully deleted the old package; proceed with replace. 14128 14129 // If deleted package lived in a container, give users a chance to 14130 // relinquish resources before killing. 14131 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14132 if (DEBUG_INSTALL) { 14133 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14134 } 14135 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14136 final ArrayList<String> pkgList = new ArrayList<String>(1); 14137 pkgList.add(deletedPackage.applicationInfo.packageName); 14138 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14139 } 14140 14141 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14142 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14143 clearAppProfilesLIF(pkg); 14144 14145 try { 14146 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14147 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14148 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14149 14150 // Update the in-memory copy of the previous code paths. 14151 PackageSetting ps = mSettings.mPackages.get(pkgName); 14152 if (!killApp) { 14153 if (ps.oldCodePaths == null) { 14154 ps.oldCodePaths = new ArraySet<>(); 14155 } 14156 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14157 if (deletedPackage.splitCodePaths != null) { 14158 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14159 } 14160 } else { 14161 ps.oldCodePaths = null; 14162 } 14163 if (ps.childPackageNames != null) { 14164 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14165 final String childPkgName = ps.childPackageNames.get(i); 14166 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14167 childPs.oldCodePaths = ps.oldCodePaths; 14168 } 14169 } 14170 prepareAppDataAfterInstallLIF(newPackage); 14171 addedPkg = true; 14172 } catch (PackageManagerException e) { 14173 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14174 } 14175 } 14176 14177 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14178 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14179 14180 // Revert all internal state mutations and added folders for the failed install 14181 if (addedPkg) { 14182 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14183 res.removedInfo, true, null); 14184 } 14185 14186 // Restore the old package 14187 if (deletedPkg) { 14188 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14189 File restoreFile = new File(deletedPackage.codePath); 14190 // Parse old package 14191 boolean oldExternal = isExternal(deletedPackage); 14192 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14193 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14194 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14195 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14196 try { 14197 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14198 null); 14199 } catch (PackageManagerException e) { 14200 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14201 + e.getMessage()); 14202 return; 14203 } 14204 14205 synchronized (mPackages) { 14206 // Ensure the installer package name up to date 14207 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14208 14209 // Update permissions for restored package 14210 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14211 14212 mSettings.writeLPr(); 14213 } 14214 14215 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14216 } 14217 } else { 14218 synchronized (mPackages) { 14219 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14220 if (ps != null) { 14221 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14222 if (res.removedInfo.removedChildPackages != null) { 14223 final int childCount = res.removedInfo.removedChildPackages.size(); 14224 // Iterate in reverse as we may modify the collection 14225 for (int i = childCount - 1; i >= 0; i--) { 14226 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14227 if (res.addedChildPackages.containsKey(childPackageName)) { 14228 res.removedInfo.removedChildPackages.removeAt(i); 14229 } else { 14230 PackageRemovedInfo childInfo = res.removedInfo 14231 .removedChildPackages.valueAt(i); 14232 childInfo.removedForAllUsers = mPackages.get( 14233 childInfo.removedPackage) == null; 14234 } 14235 } 14236 } 14237 } 14238 } 14239 } 14240 } 14241 14242 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14243 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14244 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14245 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14246 + ", old=" + deletedPackage); 14247 14248 final boolean disabledSystem; 14249 14250 // Remove existing system package 14251 removePackageLI(deletedPackage, true); 14252 14253 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14254 if (!disabledSystem) { 14255 // We didn't need to disable the .apk as a current system package, 14256 // which means we are replacing another update that is already 14257 // installed. We need to make sure to delete the older one's .apk. 14258 res.removedInfo.args = createInstallArgsForExisting(0, 14259 deletedPackage.applicationInfo.getCodePath(), 14260 deletedPackage.applicationInfo.getResourcePath(), 14261 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14262 } else { 14263 res.removedInfo.args = null; 14264 } 14265 14266 // Successfully disabled the old package. Now proceed with re-installation 14267 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14268 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14269 clearAppProfilesLIF(pkg); 14270 14271 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14272 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14273 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14274 14275 PackageParser.Package newPackage = null; 14276 try { 14277 // Add the package to the internal data structures 14278 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14279 14280 // Set the update and install times 14281 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14282 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14283 System.currentTimeMillis()); 14284 14285 // Update the package dynamic state if succeeded 14286 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14287 // Now that the install succeeded make sure we remove data 14288 // directories for any child package the update removed. 14289 final int deletedChildCount = (deletedPackage.childPackages != null) 14290 ? deletedPackage.childPackages.size() : 0; 14291 final int newChildCount = (newPackage.childPackages != null) 14292 ? newPackage.childPackages.size() : 0; 14293 for (int i = 0; i < deletedChildCount; i++) { 14294 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14295 boolean childPackageDeleted = true; 14296 for (int j = 0; j < newChildCount; j++) { 14297 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14298 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14299 childPackageDeleted = false; 14300 break; 14301 } 14302 } 14303 if (childPackageDeleted) { 14304 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14305 deletedChildPkg.packageName); 14306 if (ps != null && res.removedInfo.removedChildPackages != null) { 14307 PackageRemovedInfo removedChildRes = res.removedInfo 14308 .removedChildPackages.get(deletedChildPkg.packageName); 14309 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14310 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14311 } 14312 } 14313 } 14314 14315 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14316 prepareAppDataAfterInstallLIF(newPackage); 14317 } 14318 } catch (PackageManagerException e) { 14319 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14320 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14321 } 14322 14323 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14324 // Re installation failed. Restore old information 14325 // Remove new pkg information 14326 if (newPackage != null) { 14327 removeInstalledPackageLI(newPackage, true); 14328 } 14329 // Add back the old system package 14330 try { 14331 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14332 } catch (PackageManagerException e) { 14333 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14334 } 14335 14336 synchronized (mPackages) { 14337 if (disabledSystem) { 14338 enableSystemPackageLPw(deletedPackage); 14339 } 14340 14341 // Ensure the installer package name up to date 14342 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14343 14344 // Update permissions for restored package 14345 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14346 14347 mSettings.writeLPr(); 14348 } 14349 14350 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14351 + " after failed upgrade"); 14352 } 14353 } 14354 14355 /** 14356 * Checks whether the parent or any of the child packages have a change shared 14357 * user. For a package to be a valid update the shred users of the parent and 14358 * the children should match. We may later support changing child shared users. 14359 * @param oldPkg The updated package. 14360 * @param newPkg The update package. 14361 * @return The shared user that change between the versions. 14362 */ 14363 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14364 PackageParser.Package newPkg) { 14365 // Check parent shared user 14366 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14367 return newPkg.packageName; 14368 } 14369 // Check child shared users 14370 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14371 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14372 for (int i = 0; i < newChildCount; i++) { 14373 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14374 // If this child was present, did it have the same shared user? 14375 for (int j = 0; j < oldChildCount; j++) { 14376 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14377 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14378 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14379 return newChildPkg.packageName; 14380 } 14381 } 14382 } 14383 return null; 14384 } 14385 14386 private void removeNativeBinariesLI(PackageSetting ps) { 14387 // Remove the lib path for the parent package 14388 if (ps != null) { 14389 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14390 // Remove the lib path for the child packages 14391 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14392 for (int i = 0; i < childCount; i++) { 14393 PackageSetting childPs = null; 14394 synchronized (mPackages) { 14395 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14396 } 14397 if (childPs != null) { 14398 NativeLibraryHelper.removeNativeBinariesLI(childPs 14399 .legacyNativeLibraryPathString); 14400 } 14401 } 14402 } 14403 } 14404 14405 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14406 // Enable the parent package 14407 mSettings.enableSystemPackageLPw(pkg.packageName); 14408 // Enable the child packages 14409 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14410 for (int i = 0; i < childCount; i++) { 14411 PackageParser.Package childPkg = pkg.childPackages.get(i); 14412 mSettings.enableSystemPackageLPw(childPkg.packageName); 14413 } 14414 } 14415 14416 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14417 PackageParser.Package newPkg) { 14418 // Disable the parent package (parent always replaced) 14419 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14420 // Disable the child packages 14421 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14422 for (int i = 0; i < childCount; i++) { 14423 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14424 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14425 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14426 } 14427 return disabled; 14428 } 14429 14430 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14431 String installerPackageName) { 14432 // Enable the parent package 14433 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14434 // Enable the child packages 14435 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14436 for (int i = 0; i < childCount; i++) { 14437 PackageParser.Package childPkg = pkg.childPackages.get(i); 14438 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14439 } 14440 } 14441 14442 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14443 // Collect all used permissions in the UID 14444 ArraySet<String> usedPermissions = new ArraySet<>(); 14445 final int packageCount = su.packages.size(); 14446 for (int i = 0; i < packageCount; i++) { 14447 PackageSetting ps = su.packages.valueAt(i); 14448 if (ps.pkg == null) { 14449 continue; 14450 } 14451 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14452 for (int j = 0; j < requestedPermCount; j++) { 14453 String permission = ps.pkg.requestedPermissions.get(j); 14454 BasePermission bp = mSettings.mPermissions.get(permission); 14455 if (bp != null) { 14456 usedPermissions.add(permission); 14457 } 14458 } 14459 } 14460 14461 PermissionsState permissionsState = su.getPermissionsState(); 14462 // Prune install permissions 14463 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14464 final int installPermCount = installPermStates.size(); 14465 for (int i = installPermCount - 1; i >= 0; i--) { 14466 PermissionState permissionState = installPermStates.get(i); 14467 if (!usedPermissions.contains(permissionState.getName())) { 14468 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14469 if (bp != null) { 14470 permissionsState.revokeInstallPermission(bp); 14471 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14472 PackageManager.MASK_PERMISSION_FLAGS, 0); 14473 } 14474 } 14475 } 14476 14477 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14478 14479 // Prune runtime permissions 14480 for (int userId : allUserIds) { 14481 List<PermissionState> runtimePermStates = permissionsState 14482 .getRuntimePermissionStates(userId); 14483 final int runtimePermCount = runtimePermStates.size(); 14484 for (int i = runtimePermCount - 1; i >= 0; i--) { 14485 PermissionState permissionState = runtimePermStates.get(i); 14486 if (!usedPermissions.contains(permissionState.getName())) { 14487 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14488 if (bp != null) { 14489 permissionsState.revokeRuntimePermission(bp, userId); 14490 permissionsState.updatePermissionFlags(bp, userId, 14491 PackageManager.MASK_PERMISSION_FLAGS, 0); 14492 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14493 runtimePermissionChangedUserIds, userId); 14494 } 14495 } 14496 } 14497 } 14498 14499 return runtimePermissionChangedUserIds; 14500 } 14501 14502 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14503 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14504 // Update the parent package setting 14505 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14506 res, user); 14507 // Update the child packages setting 14508 final int childCount = (newPackage.childPackages != null) 14509 ? newPackage.childPackages.size() : 0; 14510 for (int i = 0; i < childCount; i++) { 14511 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14512 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14513 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14514 childRes.origUsers, childRes, user); 14515 } 14516 } 14517 14518 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14519 String installerPackageName, int[] allUsers, int[] installedForUsers, 14520 PackageInstalledInfo res, UserHandle user) { 14521 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14522 14523 String pkgName = newPackage.packageName; 14524 synchronized (mPackages) { 14525 //write settings. the installStatus will be incomplete at this stage. 14526 //note that the new package setting would have already been 14527 //added to mPackages. It hasn't been persisted yet. 14528 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14529 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14530 mSettings.writeLPr(); 14531 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14532 } 14533 14534 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14535 synchronized (mPackages) { 14536 updatePermissionsLPw(newPackage.packageName, newPackage, 14537 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14538 ? UPDATE_PERMISSIONS_ALL : 0)); 14539 // For system-bundled packages, we assume that installing an upgraded version 14540 // of the package implies that the user actually wants to run that new code, 14541 // so we enable the package. 14542 PackageSetting ps = mSettings.mPackages.get(pkgName); 14543 final int userId = user.getIdentifier(); 14544 if (ps != null) { 14545 if (isSystemApp(newPackage)) { 14546 if (DEBUG_INSTALL) { 14547 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14548 } 14549 // Enable system package for requested users 14550 if (res.origUsers != null) { 14551 for (int origUserId : res.origUsers) { 14552 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14553 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14554 origUserId, installerPackageName); 14555 } 14556 } 14557 } 14558 // Also convey the prior install/uninstall state 14559 if (allUsers != null && installedForUsers != null) { 14560 for (int currentUserId : allUsers) { 14561 final boolean installed = ArrayUtils.contains( 14562 installedForUsers, currentUserId); 14563 if (DEBUG_INSTALL) { 14564 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14565 } 14566 ps.setInstalled(installed, currentUserId); 14567 } 14568 // these install state changes will be persisted in the 14569 // upcoming call to mSettings.writeLPr(). 14570 } 14571 } 14572 // It's implied that when a user requests installation, they want the app to be 14573 // installed and enabled. 14574 if (userId != UserHandle.USER_ALL) { 14575 ps.setInstalled(true, userId); 14576 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14577 } 14578 } 14579 res.name = pkgName; 14580 res.uid = newPackage.applicationInfo.uid; 14581 res.pkg = newPackage; 14582 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14583 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14584 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14585 //to update install status 14586 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14587 mSettings.writeLPr(); 14588 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14589 } 14590 14591 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14592 } 14593 14594 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14595 try { 14596 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14597 installPackageLI(args, res); 14598 } finally { 14599 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14600 } 14601 } 14602 14603 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14604 final int installFlags = args.installFlags; 14605 final String installerPackageName = args.installerPackageName; 14606 final String volumeUuid = args.volumeUuid; 14607 final File tmpPackageFile = new File(args.getCodePath()); 14608 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14609 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14610 || (args.volumeUuid != null)); 14611 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14612 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14613 boolean replace = false; 14614 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14615 if (args.move != null) { 14616 // moving a complete application; perform an initial scan on the new install location 14617 scanFlags |= SCAN_INITIAL; 14618 } 14619 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14620 scanFlags |= SCAN_DONT_KILL_APP; 14621 } 14622 14623 // Result object to be returned 14624 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14625 14626 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14627 14628 // Sanity check 14629 if (ephemeral && (forwardLocked || onExternal)) { 14630 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14631 + " external=" + onExternal); 14632 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14633 return; 14634 } 14635 14636 // Retrieve PackageSettings and parse package 14637 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14638 | PackageParser.PARSE_ENFORCE_CODE 14639 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14640 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14641 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14642 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14643 PackageParser pp = new PackageParser(); 14644 pp.setSeparateProcesses(mSeparateProcesses); 14645 pp.setDisplayMetrics(mMetrics); 14646 14647 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14648 final PackageParser.Package pkg; 14649 try { 14650 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14651 } catch (PackageParserException e) { 14652 res.setError("Failed parse during installPackageLI", e); 14653 return; 14654 } finally { 14655 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14656 } 14657 14658 // If we are installing a clustered package add results for the children 14659 if (pkg.childPackages != null) { 14660 synchronized (mPackages) { 14661 final int childCount = pkg.childPackages.size(); 14662 for (int i = 0; i < childCount; i++) { 14663 PackageParser.Package childPkg = pkg.childPackages.get(i); 14664 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14665 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14666 childRes.pkg = childPkg; 14667 childRes.name = childPkg.packageName; 14668 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14669 if (childPs != null) { 14670 childRes.origUsers = childPs.queryInstalledUsers( 14671 sUserManager.getUserIds(), true); 14672 } 14673 if ((mPackages.containsKey(childPkg.packageName))) { 14674 childRes.removedInfo = new PackageRemovedInfo(); 14675 childRes.removedInfo.removedPackage = childPkg.packageName; 14676 } 14677 if (res.addedChildPackages == null) { 14678 res.addedChildPackages = new ArrayMap<>(); 14679 } 14680 res.addedChildPackages.put(childPkg.packageName, childRes); 14681 } 14682 } 14683 } 14684 14685 // If package doesn't declare API override, mark that we have an install 14686 // time CPU ABI override. 14687 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14688 pkg.cpuAbiOverride = args.abiOverride; 14689 } 14690 14691 String pkgName = res.name = pkg.packageName; 14692 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14693 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14694 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14695 return; 14696 } 14697 } 14698 14699 try { 14700 // either use what we've been given or parse directly from the APK 14701 if (args.certificates != null) { 14702 try { 14703 PackageParser.populateCertificates(pkg, args.certificates); 14704 } catch (PackageParserException e) { 14705 // there was something wrong with the certificates we were given; 14706 // try to pull them from the APK 14707 PackageParser.collectCertificates(pkg, parseFlags); 14708 } 14709 } else { 14710 PackageParser.collectCertificates(pkg, parseFlags); 14711 } 14712 } catch (PackageParserException e) { 14713 res.setError("Failed collect during installPackageLI", e); 14714 return; 14715 } 14716 14717 // Get rid of all references to package scan path via parser. 14718 pp = null; 14719 String oldCodePath = null; 14720 boolean systemApp = false; 14721 synchronized (mPackages) { 14722 // Check if installing already existing package 14723 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14724 String oldName = mSettings.mRenamedPackages.get(pkgName); 14725 if (pkg.mOriginalPackages != null 14726 && pkg.mOriginalPackages.contains(oldName) 14727 && mPackages.containsKey(oldName)) { 14728 // This package is derived from an original package, 14729 // and this device has been updating from that original 14730 // name. We must continue using the original name, so 14731 // rename the new package here. 14732 pkg.setPackageName(oldName); 14733 pkgName = pkg.packageName; 14734 replace = true; 14735 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14736 + oldName + " pkgName=" + pkgName); 14737 } else if (mPackages.containsKey(pkgName)) { 14738 // This package, under its official name, already exists 14739 // on the device; we should replace it. 14740 replace = true; 14741 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14742 } 14743 14744 // Child packages are installed through the parent package 14745 if (pkg.parentPackage != null) { 14746 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14747 "Package " + pkg.packageName + " is child of package " 14748 + pkg.parentPackage.parentPackage + ". Child packages " 14749 + "can be updated only through the parent package."); 14750 return; 14751 } 14752 14753 if (replace) { 14754 // Prevent apps opting out from runtime permissions 14755 PackageParser.Package oldPackage = mPackages.get(pkgName); 14756 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14757 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14758 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14759 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14760 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14761 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14762 + " doesn't support runtime permissions but the old" 14763 + " target SDK " + oldTargetSdk + " does."); 14764 return; 14765 } 14766 14767 // Prevent installing of child packages 14768 if (oldPackage.parentPackage != null) { 14769 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14770 "Package " + pkg.packageName + " is child of package " 14771 + oldPackage.parentPackage + ". Child packages " 14772 + "can be updated only through the parent package."); 14773 return; 14774 } 14775 } 14776 } 14777 14778 PackageSetting ps = mSettings.mPackages.get(pkgName); 14779 if (ps != null) { 14780 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14781 14782 // Quick sanity check that we're signed correctly if updating; 14783 // we'll check this again later when scanning, but we want to 14784 // bail early here before tripping over redefined permissions. 14785 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14786 if (!checkUpgradeKeySetLP(ps, pkg)) { 14787 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14788 + pkg.packageName + " upgrade keys do not match the " 14789 + "previously installed version"); 14790 return; 14791 } 14792 } else { 14793 try { 14794 verifySignaturesLP(ps, pkg); 14795 } catch (PackageManagerException e) { 14796 res.setError(e.error, e.getMessage()); 14797 return; 14798 } 14799 } 14800 14801 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14802 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14803 systemApp = (ps.pkg.applicationInfo.flags & 14804 ApplicationInfo.FLAG_SYSTEM) != 0; 14805 } 14806 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14807 } 14808 14809 // Check whether the newly-scanned package wants to define an already-defined perm 14810 int N = pkg.permissions.size(); 14811 for (int i = N-1; i >= 0; i--) { 14812 PackageParser.Permission perm = pkg.permissions.get(i); 14813 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14814 if (bp != null) { 14815 // If the defining package is signed with our cert, it's okay. This 14816 // also includes the "updating the same package" case, of course. 14817 // "updating same package" could also involve key-rotation. 14818 final boolean sigsOk; 14819 if (bp.sourcePackage.equals(pkg.packageName) 14820 && (bp.packageSetting instanceof PackageSetting) 14821 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14822 scanFlags))) { 14823 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14824 } else { 14825 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14826 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14827 } 14828 if (!sigsOk) { 14829 // If the owning package is the system itself, we log but allow 14830 // install to proceed; we fail the install on all other permission 14831 // redefinitions. 14832 if (!bp.sourcePackage.equals("android")) { 14833 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14834 + pkg.packageName + " attempting to redeclare permission " 14835 + perm.info.name + " already owned by " + bp.sourcePackage); 14836 res.origPermission = perm.info.name; 14837 res.origPackage = bp.sourcePackage; 14838 return; 14839 } else { 14840 Slog.w(TAG, "Package " + pkg.packageName 14841 + " attempting to redeclare system permission " 14842 + perm.info.name + "; ignoring new declaration"); 14843 pkg.permissions.remove(i); 14844 } 14845 } 14846 } 14847 } 14848 } 14849 14850 if (systemApp) { 14851 if (onExternal) { 14852 // Abort update; system app can't be replaced with app on sdcard 14853 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14854 "Cannot install updates to system apps on sdcard"); 14855 return; 14856 } else if (ephemeral) { 14857 // Abort update; system app can't be replaced with an ephemeral app 14858 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14859 "Cannot update a system app with an ephemeral app"); 14860 return; 14861 } 14862 } 14863 14864 if (args.move != null) { 14865 // We did an in-place move, so dex is ready to roll 14866 scanFlags |= SCAN_NO_DEX; 14867 scanFlags |= SCAN_MOVE; 14868 14869 synchronized (mPackages) { 14870 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14871 if (ps == null) { 14872 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14873 "Missing settings for moved package " + pkgName); 14874 } 14875 14876 // We moved the entire application as-is, so bring over the 14877 // previously derived ABI information. 14878 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14879 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14880 } 14881 14882 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14883 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14884 scanFlags |= SCAN_NO_DEX; 14885 14886 try { 14887 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14888 args.abiOverride : pkg.cpuAbiOverride); 14889 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14890 true /* extract libs */); 14891 } catch (PackageManagerException pme) { 14892 Slog.e(TAG, "Error deriving application ABI", pme); 14893 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14894 return; 14895 } 14896 14897 // Shared libraries for the package need to be updated. 14898 synchronized (mPackages) { 14899 try { 14900 updateSharedLibrariesLPw(pkg, null); 14901 } catch (PackageManagerException e) { 14902 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14903 } 14904 } 14905 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14906 // Do not run PackageDexOptimizer through the local performDexOpt 14907 // method because `pkg` is not in `mPackages` yet. 14908 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14909 null /* instructionSets */, false /* checkProfiles */, 14910 getCompilerFilterForReason(REASON_INSTALL)); 14911 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14912 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14913 String msg = "Extracting package failed for " + pkgName; 14914 res.setError(INSTALL_FAILED_DEXOPT, msg); 14915 return; 14916 } 14917 14918 // Notify BackgroundDexOptService that the package has been changed. 14919 // If this is an update of a package which used to fail to compile, 14920 // BDOS will remove it from its blacklist. 14921 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14922 } 14923 14924 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14925 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14926 return; 14927 } 14928 14929 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14930 14931 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14932 "installPackageLI")) { 14933 if (replace) { 14934 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14935 installerPackageName, res); 14936 } else { 14937 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14938 args.user, installerPackageName, volumeUuid, res); 14939 } 14940 } 14941 synchronized (mPackages) { 14942 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14943 if (ps != null) { 14944 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14945 } 14946 14947 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14948 for (int i = 0; i < childCount; i++) { 14949 PackageParser.Package childPkg = pkg.childPackages.get(i); 14950 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14951 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14952 if (childPs != null) { 14953 childRes.newUsers = childPs.queryInstalledUsers( 14954 sUserManager.getUserIds(), true); 14955 } 14956 } 14957 } 14958 } 14959 14960 private void startIntentFilterVerifications(int userId, boolean replacing, 14961 PackageParser.Package pkg) { 14962 if (mIntentFilterVerifierComponent == null) { 14963 Slog.w(TAG, "No IntentFilter verification will not be done as " 14964 + "there is no IntentFilterVerifier available!"); 14965 return; 14966 } 14967 14968 final int verifierUid = getPackageUid( 14969 mIntentFilterVerifierComponent.getPackageName(), 14970 MATCH_DEBUG_TRIAGED_MISSING, 14971 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14972 14973 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14974 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14975 mHandler.sendMessage(msg); 14976 14977 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14978 for (int i = 0; i < childCount; i++) { 14979 PackageParser.Package childPkg = pkg.childPackages.get(i); 14980 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14981 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14982 mHandler.sendMessage(msg); 14983 } 14984 } 14985 14986 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14987 PackageParser.Package pkg) { 14988 int size = pkg.activities.size(); 14989 if (size == 0) { 14990 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14991 "No activity, so no need to verify any IntentFilter!"); 14992 return; 14993 } 14994 14995 final boolean hasDomainURLs = hasDomainURLs(pkg); 14996 if (!hasDomainURLs) { 14997 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14998 "No domain URLs, so no need to verify any IntentFilter!"); 14999 return; 15000 } 15001 15002 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 15003 + " if any IntentFilter from the " + size 15004 + " Activities needs verification ..."); 15005 15006 int count = 0; 15007 final String packageName = pkg.packageName; 15008 15009 synchronized (mPackages) { 15010 // If this is a new install and we see that we've already run verification for this 15011 // package, we have nothing to do: it means the state was restored from backup. 15012 if (!replacing) { 15013 IntentFilterVerificationInfo ivi = 15014 mSettings.getIntentFilterVerificationLPr(packageName); 15015 if (ivi != null) { 15016 if (DEBUG_DOMAIN_VERIFICATION) { 15017 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 15018 + ivi.getStatusString()); 15019 } 15020 return; 15021 } 15022 } 15023 15024 // If any filters need to be verified, then all need to be. 15025 boolean needToVerify = false; 15026 for (PackageParser.Activity a : pkg.activities) { 15027 for (ActivityIntentInfo filter : a.intents) { 15028 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 15029 if (DEBUG_DOMAIN_VERIFICATION) { 15030 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 15031 } 15032 needToVerify = true; 15033 break; 15034 } 15035 } 15036 } 15037 15038 if (needToVerify) { 15039 final int verificationId = mIntentFilterVerificationToken++; 15040 for (PackageParser.Activity a : pkg.activities) { 15041 for (ActivityIntentInfo filter : a.intents) { 15042 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15043 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15044 "Verification needed for IntentFilter:" + filter.toString()); 15045 mIntentFilterVerifier.addOneIntentFilterVerification( 15046 verifierUid, userId, verificationId, filter, packageName); 15047 count++; 15048 } 15049 } 15050 } 15051 } 15052 } 15053 15054 if (count > 0) { 15055 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15056 + " IntentFilter verification" + (count > 1 ? "s" : "") 15057 + " for userId:" + userId); 15058 mIntentFilterVerifier.startVerifications(userId); 15059 } else { 15060 if (DEBUG_DOMAIN_VERIFICATION) { 15061 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15062 } 15063 } 15064 } 15065 15066 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15067 final ComponentName cn = filter.activity.getComponentName(); 15068 final String packageName = cn.getPackageName(); 15069 15070 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15071 packageName); 15072 if (ivi == null) { 15073 return true; 15074 } 15075 int status = ivi.getStatus(); 15076 switch (status) { 15077 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15078 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15079 return true; 15080 15081 default: 15082 // Nothing to do 15083 return false; 15084 } 15085 } 15086 15087 private static boolean isMultiArch(ApplicationInfo info) { 15088 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15089 } 15090 15091 private static boolean isExternal(PackageParser.Package pkg) { 15092 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15093 } 15094 15095 private static boolean isExternal(PackageSetting ps) { 15096 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15097 } 15098 15099 private static boolean isEphemeral(PackageParser.Package pkg) { 15100 return pkg.applicationInfo.isEphemeralApp(); 15101 } 15102 15103 private static boolean isEphemeral(PackageSetting ps) { 15104 return ps.pkg != null && isEphemeral(ps.pkg); 15105 } 15106 15107 private static boolean isSystemApp(PackageParser.Package pkg) { 15108 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15109 } 15110 15111 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15112 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15113 } 15114 15115 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15116 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15117 } 15118 15119 private static boolean isSystemApp(PackageSetting ps) { 15120 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15121 } 15122 15123 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15124 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15125 } 15126 15127 private int packageFlagsToInstallFlags(PackageSetting ps) { 15128 int installFlags = 0; 15129 if (isEphemeral(ps)) { 15130 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15131 } 15132 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15133 // This existing package was an external ASEC install when we have 15134 // the external flag without a UUID 15135 installFlags |= PackageManager.INSTALL_EXTERNAL; 15136 } 15137 if (ps.isForwardLocked()) { 15138 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15139 } 15140 return installFlags; 15141 } 15142 15143 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15144 if (isExternal(pkg)) { 15145 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15146 return StorageManager.UUID_PRIMARY_PHYSICAL; 15147 } else { 15148 return pkg.volumeUuid; 15149 } 15150 } else { 15151 return StorageManager.UUID_PRIVATE_INTERNAL; 15152 } 15153 } 15154 15155 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15156 if (isExternal(pkg)) { 15157 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15158 return mSettings.getExternalVersion(); 15159 } else { 15160 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15161 } 15162 } else { 15163 return mSettings.getInternalVersion(); 15164 } 15165 } 15166 15167 private void deleteTempPackageFiles() { 15168 final FilenameFilter filter = new FilenameFilter() { 15169 public boolean accept(File dir, String name) { 15170 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15171 } 15172 }; 15173 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15174 file.delete(); 15175 } 15176 } 15177 15178 @Override 15179 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15180 int flags) { 15181 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15182 flags); 15183 } 15184 15185 @Override 15186 public void deletePackage(final String packageName, 15187 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15188 mContext.enforceCallingOrSelfPermission( 15189 android.Manifest.permission.DELETE_PACKAGES, null); 15190 Preconditions.checkNotNull(packageName); 15191 Preconditions.checkNotNull(observer); 15192 final int uid = Binder.getCallingUid(); 15193 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15194 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15195 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15196 mContext.enforceCallingOrSelfPermission( 15197 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15198 "deletePackage for user " + userId); 15199 } 15200 15201 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15202 try { 15203 observer.onPackageDeleted(packageName, 15204 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15205 } catch (RemoteException re) { 15206 } 15207 return; 15208 } 15209 15210 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15211 try { 15212 observer.onPackageDeleted(packageName, 15213 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15214 } catch (RemoteException re) { 15215 } 15216 return; 15217 } 15218 15219 if (DEBUG_REMOVE) { 15220 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15221 + " deleteAllUsers: " + deleteAllUsers ); 15222 } 15223 // Queue up an async operation since the package deletion may take a little while. 15224 mHandler.post(new Runnable() { 15225 public void run() { 15226 mHandler.removeCallbacks(this); 15227 int returnCode; 15228 if (!deleteAllUsers) { 15229 returnCode = deletePackageX(packageName, userId, deleteFlags); 15230 } else { 15231 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15232 // If nobody is blocking uninstall, proceed with delete for all users 15233 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15234 returnCode = deletePackageX(packageName, userId, deleteFlags); 15235 } else { 15236 // Otherwise uninstall individually for users with blockUninstalls=false 15237 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15238 for (int userId : users) { 15239 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15240 returnCode = deletePackageX(packageName, userId, userFlags); 15241 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15242 Slog.w(TAG, "Package delete failed for user " + userId 15243 + ", returnCode " + returnCode); 15244 } 15245 } 15246 } 15247 // The app has only been marked uninstalled for certain users. 15248 // We still need to report that delete was blocked 15249 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15250 } 15251 } 15252 try { 15253 observer.onPackageDeleted(packageName, returnCode, null); 15254 } catch (RemoteException e) { 15255 Log.i(TAG, "Observer no longer exists."); 15256 } //end catch 15257 } //end run 15258 }); 15259 } 15260 15261 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15262 int[] result = EMPTY_INT_ARRAY; 15263 for (int userId : userIds) { 15264 if (getBlockUninstallForUser(packageName, userId)) { 15265 result = ArrayUtils.appendInt(result, userId); 15266 } 15267 } 15268 return result; 15269 } 15270 15271 @Override 15272 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15273 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15274 } 15275 15276 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15277 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15278 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15279 try { 15280 if (dpm != null) { 15281 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15282 /* callingUserOnly =*/ false); 15283 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15284 : deviceOwnerComponentName.getPackageName(); 15285 // Does the package contains the device owner? 15286 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15287 // this check is probably not needed, since DO should be registered as a device 15288 // admin on some user too. (Original bug for this: b/17657954) 15289 if (packageName.equals(deviceOwnerPackageName)) { 15290 return true; 15291 } 15292 // Does it contain a device admin for any user? 15293 int[] users; 15294 if (userId == UserHandle.USER_ALL) { 15295 users = sUserManager.getUserIds(); 15296 } else { 15297 users = new int[]{userId}; 15298 } 15299 for (int i = 0; i < users.length; ++i) { 15300 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15301 return true; 15302 } 15303 } 15304 } 15305 } catch (RemoteException e) { 15306 } 15307 return false; 15308 } 15309 15310 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15311 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15312 } 15313 15314 /** 15315 * This method is an internal method that could be get invoked either 15316 * to delete an installed package or to clean up a failed installation. 15317 * After deleting an installed package, a broadcast is sent to notify any 15318 * listeners that the package has been removed. For cleaning up a failed 15319 * installation, the broadcast is not necessary since the package's 15320 * installation wouldn't have sent the initial broadcast either 15321 * The key steps in deleting a package are 15322 * deleting the package information in internal structures like mPackages, 15323 * deleting the packages base directories through installd 15324 * updating mSettings to reflect current status 15325 * persisting settings for later use 15326 * sending a broadcast if necessary 15327 */ 15328 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15329 final PackageRemovedInfo info = new PackageRemovedInfo(); 15330 final boolean res; 15331 15332 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15333 ? UserHandle.ALL : new UserHandle(userId); 15334 15335 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15336 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15337 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15338 } 15339 15340 PackageSetting uninstalledPs = null; 15341 15342 // for the uninstall-updates case and restricted profiles, remember the per- 15343 // user handle installed state 15344 int[] allUsers; 15345 synchronized (mPackages) { 15346 uninstalledPs = mSettings.mPackages.get(packageName); 15347 if (uninstalledPs == null) { 15348 Slog.w(TAG, "Not removing non-existent package " + packageName); 15349 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15350 } 15351 allUsers = sUserManager.getUserIds(); 15352 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15353 } 15354 15355 synchronized (mInstallLock) { 15356 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15357 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15358 "deletePackageX")) { 15359 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15360 deleteFlags | REMOVE_CHATTY, info, true, null); 15361 } 15362 synchronized (mPackages) { 15363 if (res) { 15364 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15365 } 15366 } 15367 } 15368 15369 if (res) { 15370 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15371 info.sendPackageRemovedBroadcasts(killApp); 15372 info.sendSystemPackageUpdatedBroadcasts(); 15373 info.sendSystemPackageAppearedBroadcasts(); 15374 } 15375 // Force a gc here. 15376 Runtime.getRuntime().gc(); 15377 // Delete the resources here after sending the broadcast to let 15378 // other processes clean up before deleting resources. 15379 if (info.args != null) { 15380 synchronized (mInstallLock) { 15381 info.args.doPostDeleteLI(true); 15382 } 15383 } 15384 15385 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15386 } 15387 15388 class PackageRemovedInfo { 15389 String removedPackage; 15390 int uid = -1; 15391 int removedAppId = -1; 15392 int[] origUsers; 15393 int[] removedUsers = null; 15394 boolean isRemovedPackageSystemUpdate = false; 15395 boolean isUpdate; 15396 boolean dataRemoved; 15397 boolean removedForAllUsers; 15398 // Clean up resources deleted packages. 15399 InstallArgs args = null; 15400 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15401 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15402 15403 void sendPackageRemovedBroadcasts(boolean killApp) { 15404 sendPackageRemovedBroadcastInternal(killApp); 15405 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15406 for (int i = 0; i < childCount; i++) { 15407 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15408 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15409 } 15410 } 15411 15412 void sendSystemPackageUpdatedBroadcasts() { 15413 if (isRemovedPackageSystemUpdate) { 15414 sendSystemPackageUpdatedBroadcastsInternal(); 15415 final int childCount = (removedChildPackages != null) 15416 ? removedChildPackages.size() : 0; 15417 for (int i = 0; i < childCount; i++) { 15418 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15419 if (childInfo.isRemovedPackageSystemUpdate) { 15420 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15421 } 15422 } 15423 } 15424 } 15425 15426 void sendSystemPackageAppearedBroadcasts() { 15427 final int packageCount = (appearedChildPackages != null) 15428 ? appearedChildPackages.size() : 0; 15429 for (int i = 0; i < packageCount; i++) { 15430 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15431 for (int userId : installedInfo.newUsers) { 15432 sendPackageAddedForUser(installedInfo.name, true, 15433 UserHandle.getAppId(installedInfo.uid), userId); 15434 } 15435 } 15436 } 15437 15438 private void sendSystemPackageUpdatedBroadcastsInternal() { 15439 Bundle extras = new Bundle(2); 15440 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15441 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15442 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15443 extras, 0, null, null, null); 15444 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15445 extras, 0, null, null, null); 15446 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15447 null, 0, removedPackage, null, null); 15448 } 15449 15450 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15451 Bundle extras = new Bundle(2); 15452 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15453 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15454 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15455 if (isUpdate || isRemovedPackageSystemUpdate) { 15456 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15457 } 15458 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15459 if (removedPackage != null) { 15460 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15461 extras, 0, null, null, removedUsers); 15462 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15463 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15464 removedPackage, extras, 0, null, null, removedUsers); 15465 } 15466 } 15467 if (removedAppId >= 0) { 15468 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15469 removedUsers); 15470 } 15471 } 15472 } 15473 15474 /* 15475 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15476 * flag is not set, the data directory is removed as well. 15477 * make sure this flag is set for partially installed apps. If not its meaningless to 15478 * delete a partially installed application. 15479 */ 15480 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15481 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15482 String packageName = ps.name; 15483 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15484 // Retrieve object to delete permissions for shared user later on 15485 final PackageParser.Package deletedPkg; 15486 final PackageSetting deletedPs; 15487 // reader 15488 synchronized (mPackages) { 15489 deletedPkg = mPackages.get(packageName); 15490 deletedPs = mSettings.mPackages.get(packageName); 15491 if (outInfo != null) { 15492 outInfo.removedPackage = packageName; 15493 outInfo.removedUsers = deletedPs != null 15494 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15495 : null; 15496 } 15497 } 15498 15499 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15500 15501 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15502 final PackageParser.Package resolvedPkg; 15503 if (deletedPkg != null) { 15504 resolvedPkg = deletedPkg; 15505 } else { 15506 // We don't have a parsed package when it lives on an ejected 15507 // adopted storage device, so fake something together 15508 resolvedPkg = new PackageParser.Package(ps.name); 15509 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15510 } 15511 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15512 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15513 destroyAppProfilesLIF(resolvedPkg); 15514 if (outInfo != null) { 15515 outInfo.dataRemoved = true; 15516 } 15517 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15518 } 15519 15520 // writer 15521 synchronized (mPackages) { 15522 if (deletedPs != null) { 15523 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15524 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15525 clearDefaultBrowserIfNeeded(packageName); 15526 if (outInfo != null) { 15527 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15528 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15529 } 15530 updatePermissionsLPw(deletedPs.name, null, 0); 15531 if (deletedPs.sharedUser != null) { 15532 // Remove permissions associated with package. Since runtime 15533 // permissions are per user we have to kill the removed package 15534 // or packages running under the shared user of the removed 15535 // package if revoking the permissions requested only by the removed 15536 // package is successful and this causes a change in gids. 15537 for (int userId : UserManagerService.getInstance().getUserIds()) { 15538 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15539 userId); 15540 if (userIdToKill == UserHandle.USER_ALL 15541 || userIdToKill >= UserHandle.USER_SYSTEM) { 15542 // If gids changed for this user, kill all affected packages. 15543 mHandler.post(new Runnable() { 15544 @Override 15545 public void run() { 15546 // This has to happen with no lock held. 15547 killApplication(deletedPs.name, deletedPs.appId, 15548 KILL_APP_REASON_GIDS_CHANGED); 15549 } 15550 }); 15551 break; 15552 } 15553 } 15554 } 15555 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15556 } 15557 // make sure to preserve per-user disabled state if this removal was just 15558 // a downgrade of a system app to the factory package 15559 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15560 if (DEBUG_REMOVE) { 15561 Slog.d(TAG, "Propagating install state across downgrade"); 15562 } 15563 for (int userId : allUserHandles) { 15564 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15565 if (DEBUG_REMOVE) { 15566 Slog.d(TAG, " user " + userId + " => " + installed); 15567 } 15568 ps.setInstalled(installed, userId); 15569 } 15570 } 15571 } 15572 // can downgrade to reader 15573 if (writeSettings) { 15574 // Save settings now 15575 mSettings.writeLPr(); 15576 } 15577 } 15578 if (outInfo != null) { 15579 // A user ID was deleted here. Go through all users and remove it 15580 // from KeyStore. 15581 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15582 } 15583 } 15584 15585 static boolean locationIsPrivileged(File path) { 15586 try { 15587 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15588 .getCanonicalPath(); 15589 return path.getCanonicalPath().startsWith(privilegedAppDir); 15590 } catch (IOException e) { 15591 Slog.e(TAG, "Unable to access code path " + path); 15592 } 15593 return false; 15594 } 15595 15596 /* 15597 * Tries to delete system package. 15598 */ 15599 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15600 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15601 boolean writeSettings) { 15602 if (deletedPs.parentPackageName != null) { 15603 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15604 return false; 15605 } 15606 15607 final boolean applyUserRestrictions 15608 = (allUserHandles != null) && (outInfo.origUsers != null); 15609 final PackageSetting disabledPs; 15610 // Confirm if the system package has been updated 15611 // An updated system app can be deleted. This will also have to restore 15612 // the system pkg from system partition 15613 // reader 15614 synchronized (mPackages) { 15615 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15616 } 15617 15618 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15619 + " disabledPs=" + disabledPs); 15620 15621 if (disabledPs == null) { 15622 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15623 return false; 15624 } else if (DEBUG_REMOVE) { 15625 Slog.d(TAG, "Deleting system pkg from data partition"); 15626 } 15627 15628 if (DEBUG_REMOVE) { 15629 if (applyUserRestrictions) { 15630 Slog.d(TAG, "Remembering install states:"); 15631 for (int userId : allUserHandles) { 15632 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15633 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15634 } 15635 } 15636 } 15637 15638 // Delete the updated package 15639 outInfo.isRemovedPackageSystemUpdate = true; 15640 if (outInfo.removedChildPackages != null) { 15641 final int childCount = (deletedPs.childPackageNames != null) 15642 ? deletedPs.childPackageNames.size() : 0; 15643 for (int i = 0; i < childCount; i++) { 15644 String childPackageName = deletedPs.childPackageNames.get(i); 15645 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15646 .contains(childPackageName)) { 15647 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15648 childPackageName); 15649 if (childInfo != null) { 15650 childInfo.isRemovedPackageSystemUpdate = true; 15651 } 15652 } 15653 } 15654 } 15655 15656 if (disabledPs.versionCode < deletedPs.versionCode) { 15657 // Delete data for downgrades 15658 flags &= ~PackageManager.DELETE_KEEP_DATA; 15659 } else { 15660 // Preserve data by setting flag 15661 flags |= PackageManager.DELETE_KEEP_DATA; 15662 } 15663 15664 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15665 outInfo, writeSettings, disabledPs.pkg); 15666 if (!ret) { 15667 return false; 15668 } 15669 15670 // writer 15671 synchronized (mPackages) { 15672 // Reinstate the old system package 15673 enableSystemPackageLPw(disabledPs.pkg); 15674 // Remove any native libraries from the upgraded package. 15675 removeNativeBinariesLI(deletedPs); 15676 } 15677 15678 // Install the system package 15679 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15680 int parseFlags = mDefParseFlags 15681 | PackageParser.PARSE_MUST_BE_APK 15682 | PackageParser.PARSE_IS_SYSTEM 15683 | PackageParser.PARSE_IS_SYSTEM_DIR; 15684 if (locationIsPrivileged(disabledPs.codePath)) { 15685 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15686 } 15687 15688 final PackageParser.Package newPkg; 15689 try { 15690 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15691 } catch (PackageManagerException e) { 15692 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15693 + e.getMessage()); 15694 return false; 15695 } 15696 15697 prepareAppDataAfterInstallLIF(newPkg); 15698 15699 // writer 15700 synchronized (mPackages) { 15701 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15702 15703 // Propagate the permissions state as we do not want to drop on the floor 15704 // runtime permissions. The update permissions method below will take 15705 // care of removing obsolete permissions and grant install permissions. 15706 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15707 updatePermissionsLPw(newPkg.packageName, newPkg, 15708 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15709 15710 if (applyUserRestrictions) { 15711 if (DEBUG_REMOVE) { 15712 Slog.d(TAG, "Propagating install state across reinstall"); 15713 } 15714 for (int userId : allUserHandles) { 15715 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15716 if (DEBUG_REMOVE) { 15717 Slog.d(TAG, " user " + userId + " => " + installed); 15718 } 15719 ps.setInstalled(installed, userId); 15720 15721 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15722 } 15723 // Regardless of writeSettings we need to ensure that this restriction 15724 // state propagation is persisted 15725 mSettings.writeAllUsersPackageRestrictionsLPr(); 15726 } 15727 // can downgrade to reader here 15728 if (writeSettings) { 15729 mSettings.writeLPr(); 15730 } 15731 } 15732 return true; 15733 } 15734 15735 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15736 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15737 PackageRemovedInfo outInfo, boolean writeSettings, 15738 PackageParser.Package replacingPackage) { 15739 synchronized (mPackages) { 15740 if (outInfo != null) { 15741 outInfo.uid = ps.appId; 15742 } 15743 15744 if (outInfo != null && outInfo.removedChildPackages != null) { 15745 final int childCount = (ps.childPackageNames != null) 15746 ? ps.childPackageNames.size() : 0; 15747 for (int i = 0; i < childCount; i++) { 15748 String childPackageName = ps.childPackageNames.get(i); 15749 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15750 if (childPs == null) { 15751 return false; 15752 } 15753 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15754 childPackageName); 15755 if (childInfo != null) { 15756 childInfo.uid = childPs.appId; 15757 } 15758 } 15759 } 15760 } 15761 15762 // Delete package data from internal structures and also remove data if flag is set 15763 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15764 15765 // Delete the child packages data 15766 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15767 for (int i = 0; i < childCount; i++) { 15768 PackageSetting childPs; 15769 synchronized (mPackages) { 15770 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15771 } 15772 if (childPs != null) { 15773 PackageRemovedInfo childOutInfo = (outInfo != null 15774 && outInfo.removedChildPackages != null) 15775 ? outInfo.removedChildPackages.get(childPs.name) : null; 15776 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15777 && (replacingPackage != null 15778 && !replacingPackage.hasChildPackage(childPs.name)) 15779 ? flags & ~DELETE_KEEP_DATA : flags; 15780 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15781 deleteFlags, writeSettings); 15782 } 15783 } 15784 15785 // Delete application code and resources only for parent packages 15786 if (ps.parentPackageName == null) { 15787 if (deleteCodeAndResources && (outInfo != null)) { 15788 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15789 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15790 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15791 } 15792 } 15793 15794 return true; 15795 } 15796 15797 @Override 15798 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15799 int userId) { 15800 mContext.enforceCallingOrSelfPermission( 15801 android.Manifest.permission.DELETE_PACKAGES, null); 15802 synchronized (mPackages) { 15803 PackageSetting ps = mSettings.mPackages.get(packageName); 15804 if (ps == null) { 15805 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15806 return false; 15807 } 15808 if (!ps.getInstalled(userId)) { 15809 // Can't block uninstall for an app that is not installed or enabled. 15810 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15811 return false; 15812 } 15813 ps.setBlockUninstall(blockUninstall, userId); 15814 mSettings.writePackageRestrictionsLPr(userId); 15815 } 15816 return true; 15817 } 15818 15819 @Override 15820 public boolean getBlockUninstallForUser(String packageName, int userId) { 15821 synchronized (mPackages) { 15822 PackageSetting ps = mSettings.mPackages.get(packageName); 15823 if (ps == null) { 15824 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15825 return false; 15826 } 15827 return ps.getBlockUninstall(userId); 15828 } 15829 } 15830 15831 @Override 15832 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15833 int callingUid = Binder.getCallingUid(); 15834 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15835 throw new SecurityException( 15836 "setRequiredForSystemUser can only be run by the system or root"); 15837 } 15838 synchronized (mPackages) { 15839 PackageSetting ps = mSettings.mPackages.get(packageName); 15840 if (ps == null) { 15841 Log.w(TAG, "Package doesn't exist: " + packageName); 15842 return false; 15843 } 15844 if (systemUserApp) { 15845 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15846 } else { 15847 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15848 } 15849 mSettings.writeLPr(); 15850 } 15851 return true; 15852 } 15853 15854 /* 15855 * This method handles package deletion in general 15856 */ 15857 private boolean deletePackageLIF(String packageName, UserHandle user, 15858 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15859 PackageRemovedInfo outInfo, boolean writeSettings, 15860 PackageParser.Package replacingPackage) { 15861 if (packageName == null) { 15862 Slog.w(TAG, "Attempt to delete null packageName."); 15863 return false; 15864 } 15865 15866 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15867 15868 PackageSetting ps; 15869 15870 synchronized (mPackages) { 15871 ps = mSettings.mPackages.get(packageName); 15872 if (ps == null) { 15873 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15874 return false; 15875 } 15876 15877 if (ps.parentPackageName != null && (!isSystemApp(ps) 15878 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15879 if (DEBUG_REMOVE) { 15880 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15881 + ((user == null) ? UserHandle.USER_ALL : user)); 15882 } 15883 final int removedUserId = (user != null) ? user.getIdentifier() 15884 : UserHandle.USER_ALL; 15885 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15886 return false; 15887 } 15888 markPackageUninstalledForUserLPw(ps, user); 15889 scheduleWritePackageRestrictionsLocked(user); 15890 return true; 15891 } 15892 } 15893 15894 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15895 && user.getIdentifier() != UserHandle.USER_ALL)) { 15896 // The caller is asking that the package only be deleted for a single 15897 // user. To do this, we just mark its uninstalled state and delete 15898 // its data. If this is a system app, we only allow this to happen if 15899 // they have set the special DELETE_SYSTEM_APP which requests different 15900 // semantics than normal for uninstalling system apps. 15901 markPackageUninstalledForUserLPw(ps, user); 15902 15903 if (!isSystemApp(ps)) { 15904 // Do not uninstall the APK if an app should be cached 15905 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15906 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15907 // Other user still have this package installed, so all 15908 // we need to do is clear this user's data and save that 15909 // it is uninstalled. 15910 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15911 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15912 return false; 15913 } 15914 scheduleWritePackageRestrictionsLocked(user); 15915 return true; 15916 } else { 15917 // We need to set it back to 'installed' so the uninstall 15918 // broadcasts will be sent correctly. 15919 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15920 ps.setInstalled(true, user.getIdentifier()); 15921 } 15922 } else { 15923 // This is a system app, so we assume that the 15924 // other users still have this package installed, so all 15925 // we need to do is clear this user's data and save that 15926 // it is uninstalled. 15927 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15928 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15929 return false; 15930 } 15931 scheduleWritePackageRestrictionsLocked(user); 15932 return true; 15933 } 15934 } 15935 15936 // If we are deleting a composite package for all users, keep track 15937 // of result for each child. 15938 if (ps.childPackageNames != null && outInfo != null) { 15939 synchronized (mPackages) { 15940 final int childCount = ps.childPackageNames.size(); 15941 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15942 for (int i = 0; i < childCount; i++) { 15943 String childPackageName = ps.childPackageNames.get(i); 15944 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15945 childInfo.removedPackage = childPackageName; 15946 outInfo.removedChildPackages.put(childPackageName, childInfo); 15947 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15948 if (childPs != null) { 15949 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15950 } 15951 } 15952 } 15953 } 15954 15955 boolean ret = false; 15956 if (isSystemApp(ps)) { 15957 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15958 // When an updated system application is deleted we delete the existing resources 15959 // as well and fall back to existing code in system partition 15960 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15961 } else { 15962 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15963 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15964 outInfo, writeSettings, replacingPackage); 15965 } 15966 15967 // Take a note whether we deleted the package for all users 15968 if (outInfo != null) { 15969 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15970 if (outInfo.removedChildPackages != null) { 15971 synchronized (mPackages) { 15972 final int childCount = outInfo.removedChildPackages.size(); 15973 for (int i = 0; i < childCount; i++) { 15974 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15975 if (childInfo != null) { 15976 childInfo.removedForAllUsers = mPackages.get( 15977 childInfo.removedPackage) == null; 15978 } 15979 } 15980 } 15981 } 15982 // If we uninstalled an update to a system app there may be some 15983 // child packages that appeared as they are declared in the system 15984 // app but were not declared in the update. 15985 if (isSystemApp(ps)) { 15986 synchronized (mPackages) { 15987 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15988 final int childCount = (updatedPs.childPackageNames != null) 15989 ? updatedPs.childPackageNames.size() : 0; 15990 for (int i = 0; i < childCount; i++) { 15991 String childPackageName = updatedPs.childPackageNames.get(i); 15992 if (outInfo.removedChildPackages == null 15993 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15994 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15995 if (childPs == null) { 15996 continue; 15997 } 15998 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15999 installRes.name = childPackageName; 16000 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 16001 installRes.pkg = mPackages.get(childPackageName); 16002 installRes.uid = childPs.pkg.applicationInfo.uid; 16003 if (outInfo.appearedChildPackages == null) { 16004 outInfo.appearedChildPackages = new ArrayMap<>(); 16005 } 16006 outInfo.appearedChildPackages.put(childPackageName, installRes); 16007 } 16008 } 16009 } 16010 } 16011 } 16012 16013 return ret; 16014 } 16015 16016 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 16017 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 16018 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 16019 for (int nextUserId : userIds) { 16020 if (DEBUG_REMOVE) { 16021 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 16022 } 16023 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 16024 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 16025 false /*hidden*/, false /*suspended*/, null, null, null, 16026 false /*blockUninstall*/, 16027 ps.readUserState(nextUserId).domainVerificationStatus, 0); 16028 } 16029 } 16030 16031 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 16032 PackageRemovedInfo outInfo) { 16033 final PackageParser.Package pkg; 16034 synchronized (mPackages) { 16035 pkg = mPackages.get(ps.name); 16036 } 16037 16038 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 16039 : new int[] {userId}; 16040 for (int nextUserId : userIds) { 16041 if (DEBUG_REMOVE) { 16042 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16043 + nextUserId); 16044 } 16045 16046 destroyAppDataLIF(pkg, userId, 16047 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16048 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16049 schedulePackageCleaning(ps.name, nextUserId, false); 16050 synchronized (mPackages) { 16051 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16052 scheduleWritePackageRestrictionsLocked(nextUserId); 16053 } 16054 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16055 } 16056 } 16057 16058 if (outInfo != null) { 16059 outInfo.removedPackage = ps.name; 16060 outInfo.removedAppId = ps.appId; 16061 outInfo.removedUsers = userIds; 16062 } 16063 16064 return true; 16065 } 16066 16067 private final class ClearStorageConnection implements ServiceConnection { 16068 IMediaContainerService mContainerService; 16069 16070 @Override 16071 public void onServiceConnected(ComponentName name, IBinder service) { 16072 synchronized (this) { 16073 mContainerService = IMediaContainerService.Stub.asInterface(service); 16074 notifyAll(); 16075 } 16076 } 16077 16078 @Override 16079 public void onServiceDisconnected(ComponentName name) { 16080 } 16081 } 16082 16083 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16084 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16085 16086 final boolean mounted; 16087 if (Environment.isExternalStorageEmulated()) { 16088 mounted = true; 16089 } else { 16090 final String status = Environment.getExternalStorageState(); 16091 16092 mounted = status.equals(Environment.MEDIA_MOUNTED) 16093 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16094 } 16095 16096 if (!mounted) { 16097 return; 16098 } 16099 16100 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16101 int[] users; 16102 if (userId == UserHandle.USER_ALL) { 16103 users = sUserManager.getUserIds(); 16104 } else { 16105 users = new int[] { userId }; 16106 } 16107 final ClearStorageConnection conn = new ClearStorageConnection(); 16108 if (mContext.bindServiceAsUser( 16109 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16110 try { 16111 for (int curUser : users) { 16112 long timeout = SystemClock.uptimeMillis() + 5000; 16113 synchronized (conn) { 16114 long now = SystemClock.uptimeMillis(); 16115 while (conn.mContainerService == null && now < timeout) { 16116 try { 16117 conn.wait(timeout - now); 16118 } catch (InterruptedException e) { 16119 } 16120 } 16121 } 16122 if (conn.mContainerService == null) { 16123 return; 16124 } 16125 16126 final UserEnvironment userEnv = new UserEnvironment(curUser); 16127 clearDirectory(conn.mContainerService, 16128 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16129 if (allData) { 16130 clearDirectory(conn.mContainerService, 16131 userEnv.buildExternalStorageAppDataDirs(packageName)); 16132 clearDirectory(conn.mContainerService, 16133 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16134 } 16135 } 16136 } finally { 16137 mContext.unbindService(conn); 16138 } 16139 } 16140 } 16141 16142 @Override 16143 public void clearApplicationProfileData(String packageName) { 16144 enforceSystemOrRoot("Only the system can clear all profile data"); 16145 16146 final PackageParser.Package pkg; 16147 synchronized (mPackages) { 16148 pkg = mPackages.get(packageName); 16149 } 16150 16151 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16152 synchronized (mInstallLock) { 16153 clearAppProfilesLIF(pkg); 16154 } 16155 } 16156 } 16157 16158 @Override 16159 public void clearApplicationUserData(final String packageName, 16160 final IPackageDataObserver observer, final int userId) { 16161 mContext.enforceCallingOrSelfPermission( 16162 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16163 16164 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16165 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16166 16167 final DevicePolicyManagerInternal dpmi = LocalServices 16168 .getService(DevicePolicyManagerInternal.class); 16169 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16170 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16171 } 16172 // Queue up an async operation since the package deletion may take a little while. 16173 mHandler.post(new Runnable() { 16174 public void run() { 16175 mHandler.removeCallbacks(this); 16176 final boolean succeeded; 16177 try (PackageFreezer freezer = freezePackage(packageName, 16178 "clearApplicationUserData")) { 16179 synchronized (mInstallLock) { 16180 succeeded = clearApplicationUserDataLIF(packageName, userId); 16181 } 16182 clearExternalStorageDataSync(packageName, userId, true); 16183 } 16184 if (succeeded) { 16185 // invoke DeviceStorageMonitor's update method to clear any notifications 16186 DeviceStorageMonitorInternal dsm = LocalServices 16187 .getService(DeviceStorageMonitorInternal.class); 16188 if (dsm != null) { 16189 dsm.checkMemory(); 16190 } 16191 } 16192 if(observer != null) { 16193 try { 16194 observer.onRemoveCompleted(packageName, succeeded); 16195 } catch (RemoteException e) { 16196 Log.i(TAG, "Observer no longer exists."); 16197 } 16198 } //end if observer 16199 } //end run 16200 }); 16201 } 16202 16203 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16204 if (packageName == null) { 16205 Slog.w(TAG, "Attempt to delete null packageName."); 16206 return false; 16207 } 16208 16209 // Try finding details about the requested package 16210 PackageParser.Package pkg; 16211 synchronized (mPackages) { 16212 pkg = mPackages.get(packageName); 16213 if (pkg == null) { 16214 final PackageSetting ps = mSettings.mPackages.get(packageName); 16215 if (ps != null) { 16216 pkg = ps.pkg; 16217 } 16218 } 16219 16220 if (pkg == null) { 16221 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16222 return false; 16223 } 16224 16225 PackageSetting ps = (PackageSetting) pkg.mExtras; 16226 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16227 } 16228 16229 clearAppDataLIF(pkg, userId, 16230 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16231 16232 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16233 removeKeystoreDataIfNeeded(userId, appId); 16234 16235 final UserManager um = mContext.getSystemService(UserManager.class); 16236 final int flags; 16237 if (um.isUserUnlockingOrUnlocked(userId)) { 16238 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16239 } else if (um.isUserRunning(userId)) { 16240 flags = StorageManager.FLAG_STORAGE_DE; 16241 } else { 16242 flags = 0; 16243 } 16244 prepareAppDataContentsLIF(pkg, userId, flags); 16245 16246 return true; 16247 } 16248 16249 /** 16250 * Reverts user permission state changes (permissions and flags) in 16251 * all packages for a given user. 16252 * 16253 * @param userId The device user for which to do a reset. 16254 */ 16255 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16256 final int packageCount = mPackages.size(); 16257 for (int i = 0; i < packageCount; i++) { 16258 PackageParser.Package pkg = mPackages.valueAt(i); 16259 PackageSetting ps = (PackageSetting) pkg.mExtras; 16260 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16261 } 16262 } 16263 16264 private void resetNetworkPolicies(int userId) { 16265 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16266 } 16267 16268 /** 16269 * Reverts user permission state changes (permissions and flags). 16270 * 16271 * @param ps The package for which to reset. 16272 * @param userId The device user for which to do a reset. 16273 */ 16274 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16275 final PackageSetting ps, final int userId) { 16276 if (ps.pkg == null) { 16277 return; 16278 } 16279 16280 // These are flags that can change base on user actions. 16281 final int userSettableMask = FLAG_PERMISSION_USER_SET 16282 | FLAG_PERMISSION_USER_FIXED 16283 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16284 | FLAG_PERMISSION_REVIEW_REQUIRED; 16285 16286 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16287 | FLAG_PERMISSION_POLICY_FIXED; 16288 16289 boolean writeInstallPermissions = false; 16290 boolean writeRuntimePermissions = false; 16291 16292 final int permissionCount = ps.pkg.requestedPermissions.size(); 16293 for (int i = 0; i < permissionCount; i++) { 16294 String permission = ps.pkg.requestedPermissions.get(i); 16295 16296 BasePermission bp = mSettings.mPermissions.get(permission); 16297 if (bp == null) { 16298 continue; 16299 } 16300 16301 // If shared user we just reset the state to which only this app contributed. 16302 if (ps.sharedUser != null) { 16303 boolean used = false; 16304 final int packageCount = ps.sharedUser.packages.size(); 16305 for (int j = 0; j < packageCount; j++) { 16306 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16307 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16308 && pkg.pkg.requestedPermissions.contains(permission)) { 16309 used = true; 16310 break; 16311 } 16312 } 16313 if (used) { 16314 continue; 16315 } 16316 } 16317 16318 PermissionsState permissionsState = ps.getPermissionsState(); 16319 16320 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16321 16322 // Always clear the user settable flags. 16323 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16324 bp.name) != null; 16325 // If permission review is enabled and this is a legacy app, mark the 16326 // permission as requiring a review as this is the initial state. 16327 int flags = 0; 16328 if (Build.PERMISSIONS_REVIEW_REQUIRED 16329 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16330 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16331 } 16332 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16333 if (hasInstallState) { 16334 writeInstallPermissions = true; 16335 } else { 16336 writeRuntimePermissions = true; 16337 } 16338 } 16339 16340 // Below is only runtime permission handling. 16341 if (!bp.isRuntime()) { 16342 continue; 16343 } 16344 16345 // Never clobber system or policy. 16346 if ((oldFlags & policyOrSystemFlags) != 0) { 16347 continue; 16348 } 16349 16350 // If this permission was granted by default, make sure it is. 16351 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16352 if (permissionsState.grantRuntimePermission(bp, userId) 16353 != PERMISSION_OPERATION_FAILURE) { 16354 writeRuntimePermissions = true; 16355 } 16356 // If permission review is enabled the permissions for a legacy apps 16357 // are represented as constantly granted runtime ones, so don't revoke. 16358 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16359 // Otherwise, reset the permission. 16360 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16361 switch (revokeResult) { 16362 case PERMISSION_OPERATION_SUCCESS: 16363 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16364 writeRuntimePermissions = true; 16365 final int appId = ps.appId; 16366 mHandler.post(new Runnable() { 16367 @Override 16368 public void run() { 16369 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16370 } 16371 }); 16372 } break; 16373 } 16374 } 16375 } 16376 16377 // Synchronously write as we are taking permissions away. 16378 if (writeRuntimePermissions) { 16379 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16380 } 16381 16382 // Synchronously write as we are taking permissions away. 16383 if (writeInstallPermissions) { 16384 mSettings.writeLPr(); 16385 } 16386 } 16387 16388 /** 16389 * Remove entries from the keystore daemon. Will only remove it if the 16390 * {@code appId} is valid. 16391 */ 16392 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16393 if (appId < 0) { 16394 return; 16395 } 16396 16397 final KeyStore keyStore = KeyStore.getInstance(); 16398 if (keyStore != null) { 16399 if (userId == UserHandle.USER_ALL) { 16400 for (final int individual : sUserManager.getUserIds()) { 16401 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16402 } 16403 } else { 16404 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16405 } 16406 } else { 16407 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16408 } 16409 } 16410 16411 @Override 16412 public void deleteApplicationCacheFiles(final String packageName, 16413 final IPackageDataObserver observer) { 16414 final int userId = UserHandle.getCallingUserId(); 16415 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16416 } 16417 16418 @Override 16419 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16420 final IPackageDataObserver observer) { 16421 mContext.enforceCallingOrSelfPermission( 16422 android.Manifest.permission.DELETE_CACHE_FILES, null); 16423 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16424 /* requireFullPermission= */ true, /* checkShell= */ false, 16425 "delete application cache files"); 16426 16427 final PackageParser.Package pkg; 16428 synchronized (mPackages) { 16429 pkg = mPackages.get(packageName); 16430 } 16431 16432 // Queue up an async operation since the package deletion may take a little while. 16433 mHandler.post(new Runnable() { 16434 public void run() { 16435 synchronized (mInstallLock) { 16436 final int flags = StorageManager.FLAG_STORAGE_DE 16437 | StorageManager.FLAG_STORAGE_CE; 16438 // We're only clearing cache files, so we don't care if the 16439 // app is unfrozen and still able to run 16440 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16441 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16442 } 16443 clearExternalStorageDataSync(packageName, userId, false); 16444 if (observer != null) { 16445 try { 16446 observer.onRemoveCompleted(packageName, true); 16447 } catch (RemoteException e) { 16448 Log.i(TAG, "Observer no longer exists."); 16449 } 16450 } 16451 } 16452 }); 16453 } 16454 16455 @Override 16456 public void getPackageSizeInfo(final String packageName, int userHandle, 16457 final IPackageStatsObserver observer) { 16458 mContext.enforceCallingOrSelfPermission( 16459 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16460 if (packageName == null) { 16461 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16462 } 16463 16464 PackageStats stats = new PackageStats(packageName, userHandle); 16465 16466 /* 16467 * Queue up an async operation since the package measurement may take a 16468 * little while. 16469 */ 16470 Message msg = mHandler.obtainMessage(INIT_COPY); 16471 msg.obj = new MeasureParams(stats, observer); 16472 mHandler.sendMessage(msg); 16473 } 16474 16475 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16476 final PackageSetting ps; 16477 synchronized (mPackages) { 16478 ps = mSettings.mPackages.get(packageName); 16479 if (ps == null) { 16480 Slog.w(TAG, "Failed to find settings for " + packageName); 16481 return false; 16482 } 16483 } 16484 try { 16485 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16486 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16487 ps.getCeDataInode(userId), ps.codePathString, stats); 16488 } catch (InstallerException e) { 16489 Slog.w(TAG, String.valueOf(e)); 16490 return false; 16491 } 16492 16493 // For now, ignore code size of packages on system partition 16494 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16495 stats.codeSize = 0; 16496 } 16497 16498 return true; 16499 } 16500 16501 private int getUidTargetSdkVersionLockedLPr(int uid) { 16502 Object obj = mSettings.getUserIdLPr(uid); 16503 if (obj instanceof SharedUserSetting) { 16504 final SharedUserSetting sus = (SharedUserSetting) obj; 16505 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16506 final Iterator<PackageSetting> it = sus.packages.iterator(); 16507 while (it.hasNext()) { 16508 final PackageSetting ps = it.next(); 16509 if (ps.pkg != null) { 16510 int v = ps.pkg.applicationInfo.targetSdkVersion; 16511 if (v < vers) vers = v; 16512 } 16513 } 16514 return vers; 16515 } else if (obj instanceof PackageSetting) { 16516 final PackageSetting ps = (PackageSetting) obj; 16517 if (ps.pkg != null) { 16518 return ps.pkg.applicationInfo.targetSdkVersion; 16519 } 16520 } 16521 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16522 } 16523 16524 @Override 16525 public void addPreferredActivity(IntentFilter filter, int match, 16526 ComponentName[] set, ComponentName activity, int userId) { 16527 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16528 "Adding preferred"); 16529 } 16530 16531 private void addPreferredActivityInternal(IntentFilter filter, int match, 16532 ComponentName[] set, ComponentName activity, boolean always, int userId, 16533 String opname) { 16534 // writer 16535 int callingUid = Binder.getCallingUid(); 16536 enforceCrossUserPermission(callingUid, userId, 16537 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16538 if (filter.countActions() == 0) { 16539 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16540 return; 16541 } 16542 synchronized (mPackages) { 16543 if (mContext.checkCallingOrSelfPermission( 16544 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16545 != PackageManager.PERMISSION_GRANTED) { 16546 if (getUidTargetSdkVersionLockedLPr(callingUid) 16547 < Build.VERSION_CODES.FROYO) { 16548 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16549 + callingUid); 16550 return; 16551 } 16552 mContext.enforceCallingOrSelfPermission( 16553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16554 } 16555 16556 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16557 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16558 + userId + ":"); 16559 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16560 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16561 scheduleWritePackageRestrictionsLocked(userId); 16562 } 16563 } 16564 16565 @Override 16566 public void replacePreferredActivity(IntentFilter filter, int match, 16567 ComponentName[] set, ComponentName activity, int userId) { 16568 if (filter.countActions() != 1) { 16569 throw new IllegalArgumentException( 16570 "replacePreferredActivity expects filter to have only 1 action."); 16571 } 16572 if (filter.countDataAuthorities() != 0 16573 || filter.countDataPaths() != 0 16574 || filter.countDataSchemes() > 1 16575 || filter.countDataTypes() != 0) { 16576 throw new IllegalArgumentException( 16577 "replacePreferredActivity expects filter to have no data authorities, " + 16578 "paths, or types; and at most one scheme."); 16579 } 16580 16581 final int callingUid = Binder.getCallingUid(); 16582 enforceCrossUserPermission(callingUid, userId, 16583 true /* requireFullPermission */, false /* checkShell */, 16584 "replace preferred activity"); 16585 synchronized (mPackages) { 16586 if (mContext.checkCallingOrSelfPermission( 16587 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16588 != PackageManager.PERMISSION_GRANTED) { 16589 if (getUidTargetSdkVersionLockedLPr(callingUid) 16590 < Build.VERSION_CODES.FROYO) { 16591 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16592 + Binder.getCallingUid()); 16593 return; 16594 } 16595 mContext.enforceCallingOrSelfPermission( 16596 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16597 } 16598 16599 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16600 if (pir != null) { 16601 // Get all of the existing entries that exactly match this filter. 16602 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16603 if (existing != null && existing.size() == 1) { 16604 PreferredActivity cur = existing.get(0); 16605 if (DEBUG_PREFERRED) { 16606 Slog.i(TAG, "Checking replace of preferred:"); 16607 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16608 if (!cur.mPref.mAlways) { 16609 Slog.i(TAG, " -- CUR; not mAlways!"); 16610 } else { 16611 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16612 Slog.i(TAG, " -- CUR: mSet=" 16613 + Arrays.toString(cur.mPref.mSetComponents)); 16614 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16615 Slog.i(TAG, " -- NEW: mMatch=" 16616 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16617 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16618 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16619 } 16620 } 16621 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16622 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16623 && cur.mPref.sameSet(set)) { 16624 // Setting the preferred activity to what it happens to be already 16625 if (DEBUG_PREFERRED) { 16626 Slog.i(TAG, "Replacing with same preferred activity " 16627 + cur.mPref.mShortComponent + " for user " 16628 + userId + ":"); 16629 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16630 } 16631 return; 16632 } 16633 } 16634 16635 if (existing != null) { 16636 if (DEBUG_PREFERRED) { 16637 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16638 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16639 } 16640 for (int i = 0; i < existing.size(); i++) { 16641 PreferredActivity pa = existing.get(i); 16642 if (DEBUG_PREFERRED) { 16643 Slog.i(TAG, "Removing existing preferred activity " 16644 + pa.mPref.mComponent + ":"); 16645 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16646 } 16647 pir.removeFilter(pa); 16648 } 16649 } 16650 } 16651 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16652 "Replacing preferred"); 16653 } 16654 } 16655 16656 @Override 16657 public void clearPackagePreferredActivities(String packageName) { 16658 final int uid = Binder.getCallingUid(); 16659 // writer 16660 synchronized (mPackages) { 16661 PackageParser.Package pkg = mPackages.get(packageName); 16662 if (pkg == null || pkg.applicationInfo.uid != uid) { 16663 if (mContext.checkCallingOrSelfPermission( 16664 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16665 != PackageManager.PERMISSION_GRANTED) { 16666 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16667 < Build.VERSION_CODES.FROYO) { 16668 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16669 + Binder.getCallingUid()); 16670 return; 16671 } 16672 mContext.enforceCallingOrSelfPermission( 16673 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16674 } 16675 } 16676 16677 int user = UserHandle.getCallingUserId(); 16678 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16679 scheduleWritePackageRestrictionsLocked(user); 16680 } 16681 } 16682 } 16683 16684 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16685 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16686 ArrayList<PreferredActivity> removed = null; 16687 boolean changed = false; 16688 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16689 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16690 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16691 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16692 continue; 16693 } 16694 Iterator<PreferredActivity> it = pir.filterIterator(); 16695 while (it.hasNext()) { 16696 PreferredActivity pa = it.next(); 16697 // Mark entry for removal only if it matches the package name 16698 // and the entry is of type "always". 16699 if (packageName == null || 16700 (pa.mPref.mComponent.getPackageName().equals(packageName) 16701 && pa.mPref.mAlways)) { 16702 if (removed == null) { 16703 removed = new ArrayList<PreferredActivity>(); 16704 } 16705 removed.add(pa); 16706 } 16707 } 16708 if (removed != null) { 16709 for (int j=0; j<removed.size(); j++) { 16710 PreferredActivity pa = removed.get(j); 16711 pir.removeFilter(pa); 16712 } 16713 changed = true; 16714 } 16715 } 16716 return changed; 16717 } 16718 16719 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16720 private void clearIntentFilterVerificationsLPw(int userId) { 16721 final int packageCount = mPackages.size(); 16722 for (int i = 0; i < packageCount; i++) { 16723 PackageParser.Package pkg = mPackages.valueAt(i); 16724 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16725 } 16726 } 16727 16728 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16729 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16730 if (userId == UserHandle.USER_ALL) { 16731 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16732 sUserManager.getUserIds())) { 16733 for (int oneUserId : sUserManager.getUserIds()) { 16734 scheduleWritePackageRestrictionsLocked(oneUserId); 16735 } 16736 } 16737 } else { 16738 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16739 scheduleWritePackageRestrictionsLocked(userId); 16740 } 16741 } 16742 } 16743 16744 void clearDefaultBrowserIfNeeded(String packageName) { 16745 for (int oneUserId : sUserManager.getUserIds()) { 16746 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16747 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16748 if (packageName.equals(defaultBrowserPackageName)) { 16749 setDefaultBrowserPackageName(null, oneUserId); 16750 } 16751 } 16752 } 16753 16754 @Override 16755 public void resetApplicationPreferences(int userId) { 16756 mContext.enforceCallingOrSelfPermission( 16757 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16758 final long identity = Binder.clearCallingIdentity(); 16759 // writer 16760 try { 16761 synchronized (mPackages) { 16762 clearPackagePreferredActivitiesLPw(null, userId); 16763 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16764 // TODO: We have to reset the default SMS and Phone. This requires 16765 // significant refactoring to keep all default apps in the package 16766 // manager (cleaner but more work) or have the services provide 16767 // callbacks to the package manager to request a default app reset. 16768 applyFactoryDefaultBrowserLPw(userId); 16769 clearIntentFilterVerificationsLPw(userId); 16770 primeDomainVerificationsLPw(userId); 16771 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16772 scheduleWritePackageRestrictionsLocked(userId); 16773 } 16774 resetNetworkPolicies(userId); 16775 } finally { 16776 Binder.restoreCallingIdentity(identity); 16777 } 16778 } 16779 16780 @Override 16781 public int getPreferredActivities(List<IntentFilter> outFilters, 16782 List<ComponentName> outActivities, String packageName) { 16783 16784 int num = 0; 16785 final int userId = UserHandle.getCallingUserId(); 16786 // reader 16787 synchronized (mPackages) { 16788 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16789 if (pir != null) { 16790 final Iterator<PreferredActivity> it = pir.filterIterator(); 16791 while (it.hasNext()) { 16792 final PreferredActivity pa = it.next(); 16793 if (packageName == null 16794 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16795 && pa.mPref.mAlways)) { 16796 if (outFilters != null) { 16797 outFilters.add(new IntentFilter(pa)); 16798 } 16799 if (outActivities != null) { 16800 outActivities.add(pa.mPref.mComponent); 16801 } 16802 } 16803 } 16804 } 16805 } 16806 16807 return num; 16808 } 16809 16810 @Override 16811 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16812 int userId) { 16813 int callingUid = Binder.getCallingUid(); 16814 if (callingUid != Process.SYSTEM_UID) { 16815 throw new SecurityException( 16816 "addPersistentPreferredActivity can only be run by the system"); 16817 } 16818 if (filter.countActions() == 0) { 16819 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16820 return; 16821 } 16822 synchronized (mPackages) { 16823 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16824 ":"); 16825 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16826 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16827 new PersistentPreferredActivity(filter, activity)); 16828 scheduleWritePackageRestrictionsLocked(userId); 16829 } 16830 } 16831 16832 @Override 16833 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16834 int callingUid = Binder.getCallingUid(); 16835 if (callingUid != Process.SYSTEM_UID) { 16836 throw new SecurityException( 16837 "clearPackagePersistentPreferredActivities can only be run by the system"); 16838 } 16839 ArrayList<PersistentPreferredActivity> removed = null; 16840 boolean changed = false; 16841 synchronized (mPackages) { 16842 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16843 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16844 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16845 .valueAt(i); 16846 if (userId != thisUserId) { 16847 continue; 16848 } 16849 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16850 while (it.hasNext()) { 16851 PersistentPreferredActivity ppa = it.next(); 16852 // Mark entry for removal only if it matches the package name. 16853 if (ppa.mComponent.getPackageName().equals(packageName)) { 16854 if (removed == null) { 16855 removed = new ArrayList<PersistentPreferredActivity>(); 16856 } 16857 removed.add(ppa); 16858 } 16859 } 16860 if (removed != null) { 16861 for (int j=0; j<removed.size(); j++) { 16862 PersistentPreferredActivity ppa = removed.get(j); 16863 ppir.removeFilter(ppa); 16864 } 16865 changed = true; 16866 } 16867 } 16868 16869 if (changed) { 16870 scheduleWritePackageRestrictionsLocked(userId); 16871 } 16872 } 16873 } 16874 16875 /** 16876 * Common machinery for picking apart a restored XML blob and passing 16877 * it to a caller-supplied functor to be applied to the running system. 16878 */ 16879 private void restoreFromXml(XmlPullParser parser, int userId, 16880 String expectedStartTag, BlobXmlRestorer functor) 16881 throws IOException, XmlPullParserException { 16882 int type; 16883 while ((type = parser.next()) != XmlPullParser.START_TAG 16884 && type != XmlPullParser.END_DOCUMENT) { 16885 } 16886 if (type != XmlPullParser.START_TAG) { 16887 // oops didn't find a start tag?! 16888 if (DEBUG_BACKUP) { 16889 Slog.e(TAG, "Didn't find start tag during restore"); 16890 } 16891 return; 16892 } 16893Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16894 // this is supposed to be TAG_PREFERRED_BACKUP 16895 if (!expectedStartTag.equals(parser.getName())) { 16896 if (DEBUG_BACKUP) { 16897 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16898 } 16899 return; 16900 } 16901 16902 // skip interfering stuff, then we're aligned with the backing implementation 16903 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16904Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16905 functor.apply(parser, userId); 16906 } 16907 16908 private interface BlobXmlRestorer { 16909 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16910 } 16911 16912 /** 16913 * Non-Binder method, support for the backup/restore mechanism: write the 16914 * full set of preferred activities in its canonical XML format. Returns the 16915 * XML output as a byte array, or null if there is none. 16916 */ 16917 @Override 16918 public byte[] getPreferredActivityBackup(int userId) { 16919 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16920 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16921 } 16922 16923 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16924 try { 16925 final XmlSerializer serializer = new FastXmlSerializer(); 16926 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16927 serializer.startDocument(null, true); 16928 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16929 16930 synchronized (mPackages) { 16931 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16932 } 16933 16934 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16935 serializer.endDocument(); 16936 serializer.flush(); 16937 } catch (Exception e) { 16938 if (DEBUG_BACKUP) { 16939 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16940 } 16941 return null; 16942 } 16943 16944 return dataStream.toByteArray(); 16945 } 16946 16947 @Override 16948 public void restorePreferredActivities(byte[] backup, int userId) { 16949 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16950 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16951 } 16952 16953 try { 16954 final XmlPullParser parser = Xml.newPullParser(); 16955 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16956 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16957 new BlobXmlRestorer() { 16958 @Override 16959 public void apply(XmlPullParser parser, int userId) 16960 throws XmlPullParserException, IOException { 16961 synchronized (mPackages) { 16962 mSettings.readPreferredActivitiesLPw(parser, userId); 16963 } 16964 } 16965 } ); 16966 } catch (Exception e) { 16967 if (DEBUG_BACKUP) { 16968 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16969 } 16970 } 16971 } 16972 16973 /** 16974 * Non-Binder method, support for the backup/restore mechanism: write the 16975 * default browser (etc) settings in its canonical XML format. Returns the default 16976 * browser XML representation as a byte array, or null if there is none. 16977 */ 16978 @Override 16979 public byte[] getDefaultAppsBackup(int userId) { 16980 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16981 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16982 } 16983 16984 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16985 try { 16986 final XmlSerializer serializer = new FastXmlSerializer(); 16987 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16988 serializer.startDocument(null, true); 16989 serializer.startTag(null, TAG_DEFAULT_APPS); 16990 16991 synchronized (mPackages) { 16992 mSettings.writeDefaultAppsLPr(serializer, userId); 16993 } 16994 16995 serializer.endTag(null, TAG_DEFAULT_APPS); 16996 serializer.endDocument(); 16997 serializer.flush(); 16998 } catch (Exception e) { 16999 if (DEBUG_BACKUP) { 17000 Slog.e(TAG, "Unable to write default apps for backup", e); 17001 } 17002 return null; 17003 } 17004 17005 return dataStream.toByteArray(); 17006 } 17007 17008 @Override 17009 public void restoreDefaultApps(byte[] backup, int userId) { 17010 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17011 throw new SecurityException("Only the system may call restoreDefaultApps()"); 17012 } 17013 17014 try { 17015 final XmlPullParser parser = Xml.newPullParser(); 17016 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17017 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 17018 new BlobXmlRestorer() { 17019 @Override 17020 public void apply(XmlPullParser parser, int userId) 17021 throws XmlPullParserException, IOException { 17022 synchronized (mPackages) { 17023 mSettings.readDefaultAppsLPw(parser, userId); 17024 } 17025 } 17026 } ); 17027 } catch (Exception e) { 17028 if (DEBUG_BACKUP) { 17029 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 17030 } 17031 } 17032 } 17033 17034 @Override 17035 public byte[] getIntentFilterVerificationBackup(int userId) { 17036 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17037 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 17038 } 17039 17040 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17041 try { 17042 final XmlSerializer serializer = new FastXmlSerializer(); 17043 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17044 serializer.startDocument(null, true); 17045 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17046 17047 synchronized (mPackages) { 17048 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17049 } 17050 17051 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17052 serializer.endDocument(); 17053 serializer.flush(); 17054 } catch (Exception e) { 17055 if (DEBUG_BACKUP) { 17056 Slog.e(TAG, "Unable to write default apps for backup", e); 17057 } 17058 return null; 17059 } 17060 17061 return dataStream.toByteArray(); 17062 } 17063 17064 @Override 17065 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17066 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17067 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17068 } 17069 17070 try { 17071 final XmlPullParser parser = Xml.newPullParser(); 17072 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17073 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17074 new BlobXmlRestorer() { 17075 @Override 17076 public void apply(XmlPullParser parser, int userId) 17077 throws XmlPullParserException, IOException { 17078 synchronized (mPackages) { 17079 mSettings.readAllDomainVerificationsLPr(parser, userId); 17080 mSettings.writeLPr(); 17081 } 17082 } 17083 } ); 17084 } catch (Exception e) { 17085 if (DEBUG_BACKUP) { 17086 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17087 } 17088 } 17089 } 17090 17091 @Override 17092 public byte[] getPermissionGrantBackup(int userId) { 17093 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17094 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17095 } 17096 17097 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17098 try { 17099 final XmlSerializer serializer = new FastXmlSerializer(); 17100 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17101 serializer.startDocument(null, true); 17102 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17103 17104 synchronized (mPackages) { 17105 serializeRuntimePermissionGrantsLPr(serializer, userId); 17106 } 17107 17108 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17109 serializer.endDocument(); 17110 serializer.flush(); 17111 } catch (Exception e) { 17112 if (DEBUG_BACKUP) { 17113 Slog.e(TAG, "Unable to write default apps for backup", e); 17114 } 17115 return null; 17116 } 17117 17118 return dataStream.toByteArray(); 17119 } 17120 17121 @Override 17122 public void restorePermissionGrants(byte[] backup, int userId) { 17123 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17124 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17125 } 17126 17127 try { 17128 final XmlPullParser parser = Xml.newPullParser(); 17129 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17130 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17131 new BlobXmlRestorer() { 17132 @Override 17133 public void apply(XmlPullParser parser, int userId) 17134 throws XmlPullParserException, IOException { 17135 synchronized (mPackages) { 17136 processRestoredPermissionGrantsLPr(parser, userId); 17137 } 17138 } 17139 } ); 17140 } catch (Exception e) { 17141 if (DEBUG_BACKUP) { 17142 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17143 } 17144 } 17145 } 17146 17147 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17148 throws IOException { 17149 serializer.startTag(null, TAG_ALL_GRANTS); 17150 17151 final int N = mSettings.mPackages.size(); 17152 for (int i = 0; i < N; i++) { 17153 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17154 boolean pkgGrantsKnown = false; 17155 17156 PermissionsState packagePerms = ps.getPermissionsState(); 17157 17158 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17159 final int grantFlags = state.getFlags(); 17160 // only look at grants that are not system/policy fixed 17161 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17162 final boolean isGranted = state.isGranted(); 17163 // And only back up the user-twiddled state bits 17164 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17165 final String packageName = mSettings.mPackages.keyAt(i); 17166 if (!pkgGrantsKnown) { 17167 serializer.startTag(null, TAG_GRANT); 17168 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17169 pkgGrantsKnown = true; 17170 } 17171 17172 final boolean userSet = 17173 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17174 final boolean userFixed = 17175 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17176 final boolean revoke = 17177 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17178 17179 serializer.startTag(null, TAG_PERMISSION); 17180 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17181 if (isGranted) { 17182 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17183 } 17184 if (userSet) { 17185 serializer.attribute(null, ATTR_USER_SET, "true"); 17186 } 17187 if (userFixed) { 17188 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17189 } 17190 if (revoke) { 17191 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17192 } 17193 serializer.endTag(null, TAG_PERMISSION); 17194 } 17195 } 17196 } 17197 17198 if (pkgGrantsKnown) { 17199 serializer.endTag(null, TAG_GRANT); 17200 } 17201 } 17202 17203 serializer.endTag(null, TAG_ALL_GRANTS); 17204 } 17205 17206 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17207 throws XmlPullParserException, IOException { 17208 String pkgName = null; 17209 int outerDepth = parser.getDepth(); 17210 int type; 17211 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17212 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17213 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17214 continue; 17215 } 17216 17217 final String tagName = parser.getName(); 17218 if (tagName.equals(TAG_GRANT)) { 17219 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17220 if (DEBUG_BACKUP) { 17221 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17222 } 17223 } else if (tagName.equals(TAG_PERMISSION)) { 17224 17225 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17226 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17227 17228 int newFlagSet = 0; 17229 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17230 newFlagSet |= FLAG_PERMISSION_USER_SET; 17231 } 17232 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17233 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17234 } 17235 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17236 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17237 } 17238 if (DEBUG_BACKUP) { 17239 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17240 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17241 } 17242 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17243 if (ps != null) { 17244 // Already installed so we apply the grant immediately 17245 if (DEBUG_BACKUP) { 17246 Slog.v(TAG, " + already installed; applying"); 17247 } 17248 PermissionsState perms = ps.getPermissionsState(); 17249 BasePermission bp = mSettings.mPermissions.get(permName); 17250 if (bp != null) { 17251 if (isGranted) { 17252 perms.grantRuntimePermission(bp, userId); 17253 } 17254 if (newFlagSet != 0) { 17255 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17256 } 17257 } 17258 } else { 17259 // Need to wait for post-restore install to apply the grant 17260 if (DEBUG_BACKUP) { 17261 Slog.v(TAG, " - not yet installed; saving for later"); 17262 } 17263 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17264 isGranted, newFlagSet, userId); 17265 } 17266 } else { 17267 PackageManagerService.reportSettingsProblem(Log.WARN, 17268 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17269 XmlUtils.skipCurrentTag(parser); 17270 } 17271 } 17272 17273 scheduleWriteSettingsLocked(); 17274 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17275 } 17276 17277 @Override 17278 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17279 int sourceUserId, int targetUserId, int flags) { 17280 mContext.enforceCallingOrSelfPermission( 17281 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17282 int callingUid = Binder.getCallingUid(); 17283 enforceOwnerRights(ownerPackage, callingUid); 17284 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17285 if (intentFilter.countActions() == 0) { 17286 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17287 return; 17288 } 17289 synchronized (mPackages) { 17290 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17291 ownerPackage, targetUserId, flags); 17292 CrossProfileIntentResolver resolver = 17293 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17294 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17295 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17296 if (existing != null) { 17297 int size = existing.size(); 17298 for (int i = 0; i < size; i++) { 17299 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17300 return; 17301 } 17302 } 17303 } 17304 resolver.addFilter(newFilter); 17305 scheduleWritePackageRestrictionsLocked(sourceUserId); 17306 } 17307 } 17308 17309 @Override 17310 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17311 mContext.enforceCallingOrSelfPermission( 17312 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17313 int callingUid = Binder.getCallingUid(); 17314 enforceOwnerRights(ownerPackage, callingUid); 17315 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17316 synchronized (mPackages) { 17317 CrossProfileIntentResolver resolver = 17318 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17319 ArraySet<CrossProfileIntentFilter> set = 17320 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17321 for (CrossProfileIntentFilter filter : set) { 17322 if (filter.getOwnerPackage().equals(ownerPackage)) { 17323 resolver.removeFilter(filter); 17324 } 17325 } 17326 scheduleWritePackageRestrictionsLocked(sourceUserId); 17327 } 17328 } 17329 17330 // Enforcing that callingUid is owning pkg on userId 17331 private void enforceOwnerRights(String pkg, int callingUid) { 17332 // The system owns everything. 17333 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17334 return; 17335 } 17336 int callingUserId = UserHandle.getUserId(callingUid); 17337 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17338 if (pi == null) { 17339 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17340 + callingUserId); 17341 } 17342 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17343 throw new SecurityException("Calling uid " + callingUid 17344 + " does not own package " + pkg); 17345 } 17346 } 17347 17348 @Override 17349 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17350 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17351 } 17352 17353 private Intent getHomeIntent() { 17354 Intent intent = new Intent(Intent.ACTION_MAIN); 17355 intent.addCategory(Intent.CATEGORY_HOME); 17356 return intent; 17357 } 17358 17359 private IntentFilter getHomeFilter() { 17360 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17361 filter.addCategory(Intent.CATEGORY_HOME); 17362 filter.addCategory(Intent.CATEGORY_DEFAULT); 17363 return filter; 17364 } 17365 17366 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17367 int userId) { 17368 Intent intent = getHomeIntent(); 17369 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17370 PackageManager.GET_META_DATA, userId); 17371 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17372 true, false, false, userId); 17373 17374 allHomeCandidates.clear(); 17375 if (list != null) { 17376 for (ResolveInfo ri : list) { 17377 allHomeCandidates.add(ri); 17378 } 17379 } 17380 return (preferred == null || preferred.activityInfo == null) 17381 ? null 17382 : new ComponentName(preferred.activityInfo.packageName, 17383 preferred.activityInfo.name); 17384 } 17385 17386 @Override 17387 public void setHomeActivity(ComponentName comp, int userId) { 17388 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17389 getHomeActivitiesAsUser(homeActivities, userId); 17390 17391 boolean found = false; 17392 17393 final int size = homeActivities.size(); 17394 final ComponentName[] set = new ComponentName[size]; 17395 for (int i = 0; i < size; i++) { 17396 final ResolveInfo candidate = homeActivities.get(i); 17397 final ActivityInfo info = candidate.activityInfo; 17398 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17399 set[i] = activityName; 17400 if (!found && activityName.equals(comp)) { 17401 found = true; 17402 } 17403 } 17404 if (!found) { 17405 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17406 + userId); 17407 } 17408 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17409 set, comp, userId); 17410 } 17411 17412 private @Nullable String getSetupWizardPackageName() { 17413 final Intent intent = new Intent(Intent.ACTION_MAIN); 17414 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17415 17416 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17417 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17418 | MATCH_DISABLED_COMPONENTS, 17419 UserHandle.myUserId()); 17420 if (matches.size() == 1) { 17421 return matches.get(0).getComponentInfo().packageName; 17422 } else { 17423 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17424 + ": matches=" + matches); 17425 return null; 17426 } 17427 } 17428 17429 @Override 17430 public void setApplicationEnabledSetting(String appPackageName, 17431 int newState, int flags, int userId, String callingPackage) { 17432 if (!sUserManager.exists(userId)) return; 17433 if (callingPackage == null) { 17434 callingPackage = Integer.toString(Binder.getCallingUid()); 17435 } 17436 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17437 } 17438 17439 @Override 17440 public void setComponentEnabledSetting(ComponentName componentName, 17441 int newState, int flags, int userId) { 17442 if (!sUserManager.exists(userId)) return; 17443 setEnabledSetting(componentName.getPackageName(), 17444 componentName.getClassName(), newState, flags, userId, null); 17445 } 17446 17447 private void setEnabledSetting(final String packageName, String className, int newState, 17448 final int flags, int userId, String callingPackage) { 17449 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17450 || newState == COMPONENT_ENABLED_STATE_ENABLED 17451 || newState == COMPONENT_ENABLED_STATE_DISABLED 17452 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17453 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17454 throw new IllegalArgumentException("Invalid new component state: " 17455 + newState); 17456 } 17457 PackageSetting pkgSetting; 17458 final int uid = Binder.getCallingUid(); 17459 final int permission; 17460 if (uid == Process.SYSTEM_UID) { 17461 permission = PackageManager.PERMISSION_GRANTED; 17462 } else { 17463 permission = mContext.checkCallingOrSelfPermission( 17464 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17465 } 17466 enforceCrossUserPermission(uid, userId, 17467 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17468 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17469 boolean sendNow = false; 17470 boolean isApp = (className == null); 17471 String componentName = isApp ? packageName : className; 17472 int packageUid = -1; 17473 ArrayList<String> components; 17474 17475 // writer 17476 synchronized (mPackages) { 17477 pkgSetting = mSettings.mPackages.get(packageName); 17478 if (pkgSetting == null) { 17479 if (className == null) { 17480 throw new IllegalArgumentException("Unknown package: " + packageName); 17481 } 17482 throw new IllegalArgumentException( 17483 "Unknown component: " + packageName + "/" + className); 17484 } 17485 // Allow root and verify that userId is not being specified by a different user 17486 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17487 throw new SecurityException( 17488 "Permission Denial: attempt to change component state from pid=" 17489 + Binder.getCallingPid() 17490 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17491 } 17492 if (className == null) { 17493 // We're dealing with an application/package level state change 17494 if (pkgSetting.getEnabled(userId) == newState) { 17495 // Nothing to do 17496 return; 17497 } 17498 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17499 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17500 // Don't care about who enables an app. 17501 callingPackage = null; 17502 } 17503 pkgSetting.setEnabled(newState, userId, callingPackage); 17504 // pkgSetting.pkg.mSetEnabled = newState; 17505 } else { 17506 // We're dealing with a component level state change 17507 // First, verify that this is a valid class name. 17508 PackageParser.Package pkg = pkgSetting.pkg; 17509 if (pkg == null || !pkg.hasComponentClassName(className)) { 17510 if (pkg != null && 17511 pkg.applicationInfo.targetSdkVersion >= 17512 Build.VERSION_CODES.JELLY_BEAN) { 17513 throw new IllegalArgumentException("Component class " + className 17514 + " does not exist in " + packageName); 17515 } else { 17516 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17517 + className + " does not exist in " + packageName); 17518 } 17519 } 17520 switch (newState) { 17521 case COMPONENT_ENABLED_STATE_ENABLED: 17522 if (!pkgSetting.enableComponentLPw(className, userId)) { 17523 return; 17524 } 17525 break; 17526 case COMPONENT_ENABLED_STATE_DISABLED: 17527 if (!pkgSetting.disableComponentLPw(className, userId)) { 17528 return; 17529 } 17530 break; 17531 case COMPONENT_ENABLED_STATE_DEFAULT: 17532 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17533 return; 17534 } 17535 break; 17536 default: 17537 Slog.e(TAG, "Invalid new component state: " + newState); 17538 return; 17539 } 17540 } 17541 scheduleWritePackageRestrictionsLocked(userId); 17542 components = mPendingBroadcasts.get(userId, packageName); 17543 final boolean newPackage = components == null; 17544 if (newPackage) { 17545 components = new ArrayList<String>(); 17546 } 17547 if (!components.contains(componentName)) { 17548 components.add(componentName); 17549 } 17550 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17551 sendNow = true; 17552 // Purge entry from pending broadcast list if another one exists already 17553 // since we are sending one right away. 17554 mPendingBroadcasts.remove(userId, packageName); 17555 } else { 17556 if (newPackage) { 17557 mPendingBroadcasts.put(userId, packageName, components); 17558 } 17559 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17560 // Schedule a message 17561 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17562 } 17563 } 17564 } 17565 17566 long callingId = Binder.clearCallingIdentity(); 17567 try { 17568 if (sendNow) { 17569 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17570 sendPackageChangedBroadcast(packageName, 17571 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17572 } 17573 } finally { 17574 Binder.restoreCallingIdentity(callingId); 17575 } 17576 } 17577 17578 @Override 17579 public void flushPackageRestrictionsAsUser(int userId) { 17580 if (!sUserManager.exists(userId)) { 17581 return; 17582 } 17583 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17584 false /* checkShell */, "flushPackageRestrictions"); 17585 synchronized (mPackages) { 17586 mSettings.writePackageRestrictionsLPr(userId); 17587 mDirtyUsers.remove(userId); 17588 if (mDirtyUsers.isEmpty()) { 17589 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17590 } 17591 } 17592 } 17593 17594 private void sendPackageChangedBroadcast(String packageName, 17595 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17596 if (DEBUG_INSTALL) 17597 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17598 + componentNames); 17599 Bundle extras = new Bundle(4); 17600 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17601 String nameList[] = new String[componentNames.size()]; 17602 componentNames.toArray(nameList); 17603 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17604 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17605 extras.putInt(Intent.EXTRA_UID, packageUid); 17606 // If this is not reporting a change of the overall package, then only send it 17607 // to registered receivers. We don't want to launch a swath of apps for every 17608 // little component state change. 17609 final int flags = !componentNames.contains(packageName) 17610 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17611 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17612 new int[] {UserHandle.getUserId(packageUid)}); 17613 } 17614 17615 @Override 17616 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17617 if (!sUserManager.exists(userId)) return; 17618 final int uid = Binder.getCallingUid(); 17619 final int permission = mContext.checkCallingOrSelfPermission( 17620 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17621 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17622 enforceCrossUserPermission(uid, userId, 17623 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17624 // writer 17625 synchronized (mPackages) { 17626 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17627 allowedByPermission, uid, userId)) { 17628 scheduleWritePackageRestrictionsLocked(userId); 17629 } 17630 } 17631 } 17632 17633 @Override 17634 public String getInstallerPackageName(String packageName) { 17635 // reader 17636 synchronized (mPackages) { 17637 return mSettings.getInstallerPackageNameLPr(packageName); 17638 } 17639 } 17640 17641 public boolean isOrphaned(String packageName) { 17642 // reader 17643 synchronized (mPackages) { 17644 return mSettings.isOrphaned(packageName); 17645 } 17646 } 17647 17648 @Override 17649 public int getApplicationEnabledSetting(String packageName, int userId) { 17650 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17651 int uid = Binder.getCallingUid(); 17652 enforceCrossUserPermission(uid, userId, 17653 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17654 // reader 17655 synchronized (mPackages) { 17656 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17657 } 17658 } 17659 17660 @Override 17661 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17662 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17663 int uid = Binder.getCallingUid(); 17664 enforceCrossUserPermission(uid, userId, 17665 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17666 // reader 17667 synchronized (mPackages) { 17668 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17669 } 17670 } 17671 17672 @Override 17673 public void enterSafeMode() { 17674 enforceSystemOrRoot("Only the system can request entering safe mode"); 17675 17676 if (!mSystemReady) { 17677 mSafeMode = true; 17678 } 17679 } 17680 17681 @Override 17682 public void systemReady() { 17683 mSystemReady = true; 17684 17685 // Read the compatibilty setting when the system is ready. 17686 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17687 mContext.getContentResolver(), 17688 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17689 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17690 if (DEBUG_SETTINGS) { 17691 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17692 } 17693 17694 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17695 17696 synchronized (mPackages) { 17697 // Verify that all of the preferred activity components actually 17698 // exist. It is possible for applications to be updated and at 17699 // that point remove a previously declared activity component that 17700 // had been set as a preferred activity. We try to clean this up 17701 // the next time we encounter that preferred activity, but it is 17702 // possible for the user flow to never be able to return to that 17703 // situation so here we do a sanity check to make sure we haven't 17704 // left any junk around. 17705 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17706 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17707 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17708 removed.clear(); 17709 for (PreferredActivity pa : pir.filterSet()) { 17710 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17711 removed.add(pa); 17712 } 17713 } 17714 if (removed.size() > 0) { 17715 for (int r=0; r<removed.size(); r++) { 17716 PreferredActivity pa = removed.get(r); 17717 Slog.w(TAG, "Removing dangling preferred activity: " 17718 + pa.mPref.mComponent); 17719 pir.removeFilter(pa); 17720 } 17721 mSettings.writePackageRestrictionsLPr( 17722 mSettings.mPreferredActivities.keyAt(i)); 17723 } 17724 } 17725 17726 for (int userId : UserManagerService.getInstance().getUserIds()) { 17727 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17728 grantPermissionsUserIds = ArrayUtils.appendInt( 17729 grantPermissionsUserIds, userId); 17730 } 17731 } 17732 } 17733 sUserManager.systemReady(); 17734 17735 // If we upgraded grant all default permissions before kicking off. 17736 for (int userId : grantPermissionsUserIds) { 17737 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17738 } 17739 17740 // Kick off any messages waiting for system ready 17741 if (mPostSystemReadyMessages != null) { 17742 for (Message msg : mPostSystemReadyMessages) { 17743 msg.sendToTarget(); 17744 } 17745 mPostSystemReadyMessages = null; 17746 } 17747 17748 // Watch for external volumes that come and go over time 17749 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17750 storage.registerListener(mStorageListener); 17751 17752 mInstallerService.systemReady(); 17753 mPackageDexOptimizer.systemReady(); 17754 17755 MountServiceInternal mountServiceInternal = LocalServices.getService( 17756 MountServiceInternal.class); 17757 mountServiceInternal.addExternalStoragePolicy( 17758 new MountServiceInternal.ExternalStorageMountPolicy() { 17759 @Override 17760 public int getMountMode(int uid, String packageName) { 17761 if (Process.isIsolated(uid)) { 17762 return Zygote.MOUNT_EXTERNAL_NONE; 17763 } 17764 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17765 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17766 } 17767 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17768 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17769 } 17770 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17771 return Zygote.MOUNT_EXTERNAL_READ; 17772 } 17773 return Zygote.MOUNT_EXTERNAL_WRITE; 17774 } 17775 17776 @Override 17777 public boolean hasExternalStorage(int uid, String packageName) { 17778 return true; 17779 } 17780 }); 17781 17782 // Now that we're mostly running, clean up stale users and apps 17783 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17784 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17785 } 17786 17787 @Override 17788 public boolean isSafeMode() { 17789 return mSafeMode; 17790 } 17791 17792 @Override 17793 public boolean hasSystemUidErrors() { 17794 return mHasSystemUidErrors; 17795 } 17796 17797 static String arrayToString(int[] array) { 17798 StringBuffer buf = new StringBuffer(128); 17799 buf.append('['); 17800 if (array != null) { 17801 for (int i=0; i<array.length; i++) { 17802 if (i > 0) buf.append(", "); 17803 buf.append(array[i]); 17804 } 17805 } 17806 buf.append(']'); 17807 return buf.toString(); 17808 } 17809 17810 static class DumpState { 17811 public static final int DUMP_LIBS = 1 << 0; 17812 public static final int DUMP_FEATURES = 1 << 1; 17813 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17814 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17815 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17816 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17817 public static final int DUMP_PERMISSIONS = 1 << 6; 17818 public static final int DUMP_PACKAGES = 1 << 7; 17819 public static final int DUMP_SHARED_USERS = 1 << 8; 17820 public static final int DUMP_MESSAGES = 1 << 9; 17821 public static final int DUMP_PROVIDERS = 1 << 10; 17822 public static final int DUMP_VERIFIERS = 1 << 11; 17823 public static final int DUMP_PREFERRED = 1 << 12; 17824 public static final int DUMP_PREFERRED_XML = 1 << 13; 17825 public static final int DUMP_KEYSETS = 1 << 14; 17826 public static final int DUMP_VERSION = 1 << 15; 17827 public static final int DUMP_INSTALLS = 1 << 16; 17828 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17829 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17830 public static final int DUMP_FROZEN = 1 << 19; 17831 public static final int DUMP_DEXOPT = 1 << 20; 17832 17833 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17834 17835 private int mTypes; 17836 17837 private int mOptions; 17838 17839 private boolean mTitlePrinted; 17840 17841 private SharedUserSetting mSharedUser; 17842 17843 public boolean isDumping(int type) { 17844 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17845 return true; 17846 } 17847 17848 return (mTypes & type) != 0; 17849 } 17850 17851 public void setDump(int type) { 17852 mTypes |= type; 17853 } 17854 17855 public boolean isOptionEnabled(int option) { 17856 return (mOptions & option) != 0; 17857 } 17858 17859 public void setOptionEnabled(int option) { 17860 mOptions |= option; 17861 } 17862 17863 public boolean onTitlePrinted() { 17864 final boolean printed = mTitlePrinted; 17865 mTitlePrinted = true; 17866 return printed; 17867 } 17868 17869 public boolean getTitlePrinted() { 17870 return mTitlePrinted; 17871 } 17872 17873 public void setTitlePrinted(boolean enabled) { 17874 mTitlePrinted = enabled; 17875 } 17876 17877 public SharedUserSetting getSharedUser() { 17878 return mSharedUser; 17879 } 17880 17881 public void setSharedUser(SharedUserSetting user) { 17882 mSharedUser = user; 17883 } 17884 } 17885 17886 @Override 17887 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17888 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17889 (new PackageManagerShellCommand(this)).exec( 17890 this, in, out, err, args, resultReceiver); 17891 } 17892 17893 @Override 17894 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17895 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17896 != PackageManager.PERMISSION_GRANTED) { 17897 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17898 + Binder.getCallingPid() 17899 + ", uid=" + Binder.getCallingUid() 17900 + " without permission " 17901 + android.Manifest.permission.DUMP); 17902 return; 17903 } 17904 17905 DumpState dumpState = new DumpState(); 17906 boolean fullPreferred = false; 17907 boolean checkin = false; 17908 17909 String packageName = null; 17910 ArraySet<String> permissionNames = null; 17911 17912 int opti = 0; 17913 while (opti < args.length) { 17914 String opt = args[opti]; 17915 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17916 break; 17917 } 17918 opti++; 17919 17920 if ("-a".equals(opt)) { 17921 // Right now we only know how to print all. 17922 } else if ("-h".equals(opt)) { 17923 pw.println("Package manager dump options:"); 17924 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17925 pw.println(" --checkin: dump for a checkin"); 17926 pw.println(" -f: print details of intent filters"); 17927 pw.println(" -h: print this help"); 17928 pw.println(" cmd may be one of:"); 17929 pw.println(" l[ibraries]: list known shared libraries"); 17930 pw.println(" f[eatures]: list device features"); 17931 pw.println(" k[eysets]: print known keysets"); 17932 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17933 pw.println(" perm[issions]: dump permissions"); 17934 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17935 pw.println(" pref[erred]: print preferred package settings"); 17936 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17937 pw.println(" prov[iders]: dump content providers"); 17938 pw.println(" p[ackages]: dump installed packages"); 17939 pw.println(" s[hared-users]: dump shared user IDs"); 17940 pw.println(" m[essages]: print collected runtime messages"); 17941 pw.println(" v[erifiers]: print package verifier info"); 17942 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17943 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17944 pw.println(" version: print database version info"); 17945 pw.println(" write: write current settings now"); 17946 pw.println(" installs: details about install sessions"); 17947 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17948 pw.println(" dexopt: dump dexopt state"); 17949 pw.println(" <package.name>: info about given package"); 17950 return; 17951 } else if ("--checkin".equals(opt)) { 17952 checkin = true; 17953 } else if ("-f".equals(opt)) { 17954 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17955 } else { 17956 pw.println("Unknown argument: " + opt + "; use -h for help"); 17957 } 17958 } 17959 17960 // Is the caller requesting to dump a particular piece of data? 17961 if (opti < args.length) { 17962 String cmd = args[opti]; 17963 opti++; 17964 // Is this a package name? 17965 if ("android".equals(cmd) || cmd.contains(".")) { 17966 packageName = cmd; 17967 // When dumping a single package, we always dump all of its 17968 // filter information since the amount of data will be reasonable. 17969 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17970 } else if ("check-permission".equals(cmd)) { 17971 if (opti >= args.length) { 17972 pw.println("Error: check-permission missing permission argument"); 17973 return; 17974 } 17975 String perm = args[opti]; 17976 opti++; 17977 if (opti >= args.length) { 17978 pw.println("Error: check-permission missing package argument"); 17979 return; 17980 } 17981 String pkg = args[opti]; 17982 opti++; 17983 int user = UserHandle.getUserId(Binder.getCallingUid()); 17984 if (opti < args.length) { 17985 try { 17986 user = Integer.parseInt(args[opti]); 17987 } catch (NumberFormatException e) { 17988 pw.println("Error: check-permission user argument is not a number: " 17989 + args[opti]); 17990 return; 17991 } 17992 } 17993 pw.println(checkPermission(perm, pkg, user)); 17994 return; 17995 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17996 dumpState.setDump(DumpState.DUMP_LIBS); 17997 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17998 dumpState.setDump(DumpState.DUMP_FEATURES); 17999 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 18000 if (opti >= args.length) { 18001 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 18002 | DumpState.DUMP_SERVICE_RESOLVERS 18003 | DumpState.DUMP_RECEIVER_RESOLVERS 18004 | DumpState.DUMP_CONTENT_RESOLVERS); 18005 } else { 18006 while (opti < args.length) { 18007 String name = args[opti]; 18008 if ("a".equals(name) || "activity".equals(name)) { 18009 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 18010 } else if ("s".equals(name) || "service".equals(name)) { 18011 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 18012 } else if ("r".equals(name) || "receiver".equals(name)) { 18013 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 18014 } else if ("c".equals(name) || "content".equals(name)) { 18015 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 18016 } else { 18017 pw.println("Error: unknown resolver table type: " + name); 18018 return; 18019 } 18020 opti++; 18021 } 18022 } 18023 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 18024 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 18025 } else if ("permission".equals(cmd)) { 18026 if (opti >= args.length) { 18027 pw.println("Error: permission requires permission name"); 18028 return; 18029 } 18030 permissionNames = new ArraySet<>(); 18031 while (opti < args.length) { 18032 permissionNames.add(args[opti]); 18033 opti++; 18034 } 18035 dumpState.setDump(DumpState.DUMP_PERMISSIONS 18036 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 18037 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 18038 dumpState.setDump(DumpState.DUMP_PREFERRED); 18039 } else if ("preferred-xml".equals(cmd)) { 18040 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 18041 if (opti < args.length && "--full".equals(args[opti])) { 18042 fullPreferred = true; 18043 opti++; 18044 } 18045 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18046 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18047 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18048 dumpState.setDump(DumpState.DUMP_PACKAGES); 18049 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18050 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18051 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18052 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18053 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18054 dumpState.setDump(DumpState.DUMP_MESSAGES); 18055 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18056 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18057 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18058 || "intent-filter-verifiers".equals(cmd)) { 18059 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18060 } else if ("version".equals(cmd)) { 18061 dumpState.setDump(DumpState.DUMP_VERSION); 18062 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18063 dumpState.setDump(DumpState.DUMP_KEYSETS); 18064 } else if ("installs".equals(cmd)) { 18065 dumpState.setDump(DumpState.DUMP_INSTALLS); 18066 } else if ("frozen".equals(cmd)) { 18067 dumpState.setDump(DumpState.DUMP_FROZEN); 18068 } else if ("dexopt".equals(cmd)) { 18069 dumpState.setDump(DumpState.DUMP_DEXOPT); 18070 } else if ("write".equals(cmd)) { 18071 synchronized (mPackages) { 18072 mSettings.writeLPr(); 18073 pw.println("Settings written."); 18074 return; 18075 } 18076 } 18077 } 18078 18079 if (checkin) { 18080 pw.println("vers,1"); 18081 } 18082 18083 // reader 18084 synchronized (mPackages) { 18085 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18086 if (!checkin) { 18087 if (dumpState.onTitlePrinted()) 18088 pw.println(); 18089 pw.println("Database versions:"); 18090 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18091 } 18092 } 18093 18094 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18095 if (!checkin) { 18096 if (dumpState.onTitlePrinted()) 18097 pw.println(); 18098 pw.println("Verifiers:"); 18099 pw.print(" Required: "); 18100 pw.print(mRequiredVerifierPackage); 18101 pw.print(" (uid="); 18102 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18103 UserHandle.USER_SYSTEM)); 18104 pw.println(")"); 18105 } else if (mRequiredVerifierPackage != null) { 18106 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18107 pw.print(","); 18108 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18109 UserHandle.USER_SYSTEM)); 18110 } 18111 } 18112 18113 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18114 packageName == null) { 18115 if (mIntentFilterVerifierComponent != null) { 18116 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18117 if (!checkin) { 18118 if (dumpState.onTitlePrinted()) 18119 pw.println(); 18120 pw.println("Intent Filter Verifier:"); 18121 pw.print(" Using: "); 18122 pw.print(verifierPackageName); 18123 pw.print(" (uid="); 18124 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18125 UserHandle.USER_SYSTEM)); 18126 pw.println(")"); 18127 } else if (verifierPackageName != null) { 18128 pw.print("ifv,"); pw.print(verifierPackageName); 18129 pw.print(","); 18130 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18131 UserHandle.USER_SYSTEM)); 18132 } 18133 } else { 18134 pw.println(); 18135 pw.println("No Intent Filter Verifier available!"); 18136 } 18137 } 18138 18139 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18140 boolean printedHeader = false; 18141 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18142 while (it.hasNext()) { 18143 String name = it.next(); 18144 SharedLibraryEntry ent = mSharedLibraries.get(name); 18145 if (!checkin) { 18146 if (!printedHeader) { 18147 if (dumpState.onTitlePrinted()) 18148 pw.println(); 18149 pw.println("Libraries:"); 18150 printedHeader = true; 18151 } 18152 pw.print(" "); 18153 } else { 18154 pw.print("lib,"); 18155 } 18156 pw.print(name); 18157 if (!checkin) { 18158 pw.print(" -> "); 18159 } 18160 if (ent.path != null) { 18161 if (!checkin) { 18162 pw.print("(jar) "); 18163 pw.print(ent.path); 18164 } else { 18165 pw.print(",jar,"); 18166 pw.print(ent.path); 18167 } 18168 } else { 18169 if (!checkin) { 18170 pw.print("(apk) "); 18171 pw.print(ent.apk); 18172 } else { 18173 pw.print(",apk,"); 18174 pw.print(ent.apk); 18175 } 18176 } 18177 pw.println(); 18178 } 18179 } 18180 18181 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18182 if (dumpState.onTitlePrinted()) 18183 pw.println(); 18184 if (!checkin) { 18185 pw.println("Features:"); 18186 } 18187 18188 for (FeatureInfo feat : mAvailableFeatures.values()) { 18189 if (checkin) { 18190 pw.print("feat,"); 18191 pw.print(feat.name); 18192 pw.print(","); 18193 pw.println(feat.version); 18194 } else { 18195 pw.print(" "); 18196 pw.print(feat.name); 18197 if (feat.version > 0) { 18198 pw.print(" version="); 18199 pw.print(feat.version); 18200 } 18201 pw.println(); 18202 } 18203 } 18204 } 18205 18206 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18207 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18208 : "Activity Resolver Table:", " ", packageName, 18209 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18210 dumpState.setTitlePrinted(true); 18211 } 18212 } 18213 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18214 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18215 : "Receiver Resolver Table:", " ", packageName, 18216 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18217 dumpState.setTitlePrinted(true); 18218 } 18219 } 18220 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18221 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18222 : "Service Resolver Table:", " ", packageName, 18223 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18224 dumpState.setTitlePrinted(true); 18225 } 18226 } 18227 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18228 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18229 : "Provider Resolver Table:", " ", packageName, 18230 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18231 dumpState.setTitlePrinted(true); 18232 } 18233 } 18234 18235 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18236 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18237 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18238 int user = mSettings.mPreferredActivities.keyAt(i); 18239 if (pir.dump(pw, 18240 dumpState.getTitlePrinted() 18241 ? "\nPreferred Activities User " + user + ":" 18242 : "Preferred Activities User " + user + ":", " ", 18243 packageName, true, false)) { 18244 dumpState.setTitlePrinted(true); 18245 } 18246 } 18247 } 18248 18249 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18250 pw.flush(); 18251 FileOutputStream fout = new FileOutputStream(fd); 18252 BufferedOutputStream str = new BufferedOutputStream(fout); 18253 XmlSerializer serializer = new FastXmlSerializer(); 18254 try { 18255 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18256 serializer.startDocument(null, true); 18257 serializer.setFeature( 18258 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18259 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18260 serializer.endDocument(); 18261 serializer.flush(); 18262 } catch (IllegalArgumentException e) { 18263 pw.println("Failed writing: " + e); 18264 } catch (IllegalStateException e) { 18265 pw.println("Failed writing: " + e); 18266 } catch (IOException e) { 18267 pw.println("Failed writing: " + e); 18268 } 18269 } 18270 18271 if (!checkin 18272 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18273 && packageName == null) { 18274 pw.println(); 18275 int count = mSettings.mPackages.size(); 18276 if (count == 0) { 18277 pw.println("No applications!"); 18278 pw.println(); 18279 } else { 18280 final String prefix = " "; 18281 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18282 if (allPackageSettings.size() == 0) { 18283 pw.println("No domain preferred apps!"); 18284 pw.println(); 18285 } else { 18286 pw.println("App verification status:"); 18287 pw.println(); 18288 count = 0; 18289 for (PackageSetting ps : allPackageSettings) { 18290 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18291 if (ivi == null || ivi.getPackageName() == null) continue; 18292 pw.println(prefix + "Package: " + ivi.getPackageName()); 18293 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18294 pw.println(prefix + "Status: " + ivi.getStatusString()); 18295 pw.println(); 18296 count++; 18297 } 18298 if (count == 0) { 18299 pw.println(prefix + "No app verification established."); 18300 pw.println(); 18301 } 18302 for (int userId : sUserManager.getUserIds()) { 18303 pw.println("App linkages for user " + userId + ":"); 18304 pw.println(); 18305 count = 0; 18306 for (PackageSetting ps : allPackageSettings) { 18307 final long status = ps.getDomainVerificationStatusForUser(userId); 18308 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18309 continue; 18310 } 18311 pw.println(prefix + "Package: " + ps.name); 18312 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18313 String statusStr = IntentFilterVerificationInfo. 18314 getStatusStringFromValue(status); 18315 pw.println(prefix + "Status: " + statusStr); 18316 pw.println(); 18317 count++; 18318 } 18319 if (count == 0) { 18320 pw.println(prefix + "No configured app linkages."); 18321 pw.println(); 18322 } 18323 } 18324 } 18325 } 18326 } 18327 18328 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18329 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18330 if (packageName == null && permissionNames == null) { 18331 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18332 if (iperm == 0) { 18333 if (dumpState.onTitlePrinted()) 18334 pw.println(); 18335 pw.println("AppOp Permissions:"); 18336 } 18337 pw.print(" AppOp Permission "); 18338 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18339 pw.println(":"); 18340 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18341 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18342 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18343 } 18344 } 18345 } 18346 } 18347 18348 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18349 boolean printedSomething = false; 18350 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18351 if (packageName != null && !packageName.equals(p.info.packageName)) { 18352 continue; 18353 } 18354 if (!printedSomething) { 18355 if (dumpState.onTitlePrinted()) 18356 pw.println(); 18357 pw.println("Registered ContentProviders:"); 18358 printedSomething = true; 18359 } 18360 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18361 pw.print(" "); pw.println(p.toString()); 18362 } 18363 printedSomething = false; 18364 for (Map.Entry<String, PackageParser.Provider> entry : 18365 mProvidersByAuthority.entrySet()) { 18366 PackageParser.Provider p = entry.getValue(); 18367 if (packageName != null && !packageName.equals(p.info.packageName)) { 18368 continue; 18369 } 18370 if (!printedSomething) { 18371 if (dumpState.onTitlePrinted()) 18372 pw.println(); 18373 pw.println("ContentProvider Authorities:"); 18374 printedSomething = true; 18375 } 18376 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18377 pw.print(" "); pw.println(p.toString()); 18378 if (p.info != null && p.info.applicationInfo != null) { 18379 final String appInfo = p.info.applicationInfo.toString(); 18380 pw.print(" applicationInfo="); pw.println(appInfo); 18381 } 18382 } 18383 } 18384 18385 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18386 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18387 } 18388 18389 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18390 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18391 } 18392 18393 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18394 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18395 } 18396 18397 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18398 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18399 } 18400 18401 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18402 // XXX should handle packageName != null by dumping only install data that 18403 // the given package is involved with. 18404 if (dumpState.onTitlePrinted()) pw.println(); 18405 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18406 } 18407 18408 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18409 // XXX should handle packageName != null by dumping only install data that 18410 // the given package is involved with. 18411 if (dumpState.onTitlePrinted()) pw.println(); 18412 18413 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18414 ipw.println(); 18415 ipw.println("Frozen packages:"); 18416 ipw.increaseIndent(); 18417 if (mFrozenPackages.size() == 0) { 18418 ipw.println("(none)"); 18419 } else { 18420 for (int i = 0; i < mFrozenPackages.size(); i++) { 18421 ipw.println(mFrozenPackages.valueAt(i)); 18422 } 18423 } 18424 ipw.decreaseIndent(); 18425 } 18426 18427 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18428 if (dumpState.onTitlePrinted()) pw.println(); 18429 dumpDexoptStateLPr(pw, packageName); 18430 } 18431 18432 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18433 if (dumpState.onTitlePrinted()) pw.println(); 18434 mSettings.dumpReadMessagesLPr(pw, dumpState); 18435 18436 pw.println(); 18437 pw.println("Package warning messages:"); 18438 BufferedReader in = null; 18439 String line = null; 18440 try { 18441 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18442 while ((line = in.readLine()) != null) { 18443 if (line.contains("ignored: updated version")) continue; 18444 pw.println(line); 18445 } 18446 } catch (IOException ignored) { 18447 } finally { 18448 IoUtils.closeQuietly(in); 18449 } 18450 } 18451 18452 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18453 BufferedReader in = null; 18454 String line = null; 18455 try { 18456 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18457 while ((line = in.readLine()) != null) { 18458 if (line.contains("ignored: updated version")) continue; 18459 pw.print("msg,"); 18460 pw.println(line); 18461 } 18462 } catch (IOException ignored) { 18463 } finally { 18464 IoUtils.closeQuietly(in); 18465 } 18466 } 18467 } 18468 } 18469 18470 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18471 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18472 ipw.println(); 18473 ipw.println("Dexopt state:"); 18474 ipw.increaseIndent(); 18475 Collection<PackageParser.Package> packages = null; 18476 if (packageName != null) { 18477 PackageParser.Package targetPackage = mPackages.get(packageName); 18478 if (targetPackage != null) { 18479 packages = Collections.singletonList(targetPackage); 18480 } else { 18481 ipw.println("Unable to find package: " + packageName); 18482 return; 18483 } 18484 } else { 18485 packages = mPackages.values(); 18486 } 18487 18488 for (PackageParser.Package pkg : packages) { 18489 ipw.println("[" + pkg.packageName + "]"); 18490 ipw.increaseIndent(); 18491 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18492 ipw.decreaseIndent(); 18493 } 18494 } 18495 18496 private String dumpDomainString(String packageName) { 18497 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18498 .getList(); 18499 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18500 18501 ArraySet<String> result = new ArraySet<>(); 18502 if (iviList.size() > 0) { 18503 for (IntentFilterVerificationInfo ivi : iviList) { 18504 for (String host : ivi.getDomains()) { 18505 result.add(host); 18506 } 18507 } 18508 } 18509 if (filters != null && filters.size() > 0) { 18510 for (IntentFilter filter : filters) { 18511 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18512 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18513 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18514 result.addAll(filter.getHostsList()); 18515 } 18516 } 18517 } 18518 18519 StringBuilder sb = new StringBuilder(result.size() * 16); 18520 for (String domain : result) { 18521 if (sb.length() > 0) sb.append(" "); 18522 sb.append(domain); 18523 } 18524 return sb.toString(); 18525 } 18526 18527 // ------- apps on sdcard specific code ------- 18528 static final boolean DEBUG_SD_INSTALL = false; 18529 18530 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18531 18532 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18533 18534 private boolean mMediaMounted = false; 18535 18536 static String getEncryptKey() { 18537 try { 18538 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18539 SD_ENCRYPTION_KEYSTORE_NAME); 18540 if (sdEncKey == null) { 18541 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18542 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18543 if (sdEncKey == null) { 18544 Slog.e(TAG, "Failed to create encryption keys"); 18545 return null; 18546 } 18547 } 18548 return sdEncKey; 18549 } catch (NoSuchAlgorithmException nsae) { 18550 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18551 return null; 18552 } catch (IOException ioe) { 18553 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18554 return null; 18555 } 18556 } 18557 18558 /* 18559 * Update media status on PackageManager. 18560 */ 18561 @Override 18562 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18563 int callingUid = Binder.getCallingUid(); 18564 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18565 throw new SecurityException("Media status can only be updated by the system"); 18566 } 18567 // reader; this apparently protects mMediaMounted, but should probably 18568 // be a different lock in that case. 18569 synchronized (mPackages) { 18570 Log.i(TAG, "Updating external media status from " 18571 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18572 + (mediaStatus ? "mounted" : "unmounted")); 18573 if (DEBUG_SD_INSTALL) 18574 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18575 + ", mMediaMounted=" + mMediaMounted); 18576 if (mediaStatus == mMediaMounted) { 18577 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18578 : 0, -1); 18579 mHandler.sendMessage(msg); 18580 return; 18581 } 18582 mMediaMounted = mediaStatus; 18583 } 18584 // Queue up an async operation since the package installation may take a 18585 // little while. 18586 mHandler.post(new Runnable() { 18587 public void run() { 18588 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18589 } 18590 }); 18591 } 18592 18593 /** 18594 * Called by MountService when the initial ASECs to scan are available. 18595 * Should block until all the ASEC containers are finished being scanned. 18596 */ 18597 public void scanAvailableAsecs() { 18598 updateExternalMediaStatusInner(true, false, false); 18599 } 18600 18601 /* 18602 * Collect information of applications on external media, map them against 18603 * existing containers and update information based on current mount status. 18604 * Please note that we always have to report status if reportStatus has been 18605 * set to true especially when unloading packages. 18606 */ 18607 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18608 boolean externalStorage) { 18609 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18610 int[] uidArr = EmptyArray.INT; 18611 18612 final String[] list = PackageHelper.getSecureContainerList(); 18613 if (ArrayUtils.isEmpty(list)) { 18614 Log.i(TAG, "No secure containers found"); 18615 } else { 18616 // Process list of secure containers and categorize them 18617 // as active or stale based on their package internal state. 18618 18619 // reader 18620 synchronized (mPackages) { 18621 for (String cid : list) { 18622 // Leave stages untouched for now; installer service owns them 18623 if (PackageInstallerService.isStageName(cid)) continue; 18624 18625 if (DEBUG_SD_INSTALL) 18626 Log.i(TAG, "Processing container " + cid); 18627 String pkgName = getAsecPackageName(cid); 18628 if (pkgName == null) { 18629 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18630 continue; 18631 } 18632 if (DEBUG_SD_INSTALL) 18633 Log.i(TAG, "Looking for pkg : " + pkgName); 18634 18635 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18636 if (ps == null) { 18637 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18638 continue; 18639 } 18640 18641 /* 18642 * Skip packages that are not external if we're unmounting 18643 * external storage. 18644 */ 18645 if (externalStorage && !isMounted && !isExternal(ps)) { 18646 continue; 18647 } 18648 18649 final AsecInstallArgs args = new AsecInstallArgs(cid, 18650 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18651 // The package status is changed only if the code path 18652 // matches between settings and the container id. 18653 if (ps.codePathString != null 18654 && ps.codePathString.startsWith(args.getCodePath())) { 18655 if (DEBUG_SD_INSTALL) { 18656 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18657 + " at code path: " + ps.codePathString); 18658 } 18659 18660 // We do have a valid package installed on sdcard 18661 processCids.put(args, ps.codePathString); 18662 final int uid = ps.appId; 18663 if (uid != -1) { 18664 uidArr = ArrayUtils.appendInt(uidArr, uid); 18665 } 18666 } else { 18667 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18668 + ps.codePathString); 18669 } 18670 } 18671 } 18672 18673 Arrays.sort(uidArr); 18674 } 18675 18676 // Process packages with valid entries. 18677 if (isMounted) { 18678 if (DEBUG_SD_INSTALL) 18679 Log.i(TAG, "Loading packages"); 18680 loadMediaPackages(processCids, uidArr, externalStorage); 18681 startCleaningPackages(); 18682 mInstallerService.onSecureContainersAvailable(); 18683 } else { 18684 if (DEBUG_SD_INSTALL) 18685 Log.i(TAG, "Unloading packages"); 18686 unloadMediaPackages(processCids, uidArr, reportStatus); 18687 } 18688 } 18689 18690 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18691 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18692 final int size = infos.size(); 18693 final String[] packageNames = new String[size]; 18694 final int[] packageUids = new int[size]; 18695 for (int i = 0; i < size; i++) { 18696 final ApplicationInfo info = infos.get(i); 18697 packageNames[i] = info.packageName; 18698 packageUids[i] = info.uid; 18699 } 18700 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18701 finishedReceiver); 18702 } 18703 18704 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18705 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18706 sendResourcesChangedBroadcast(mediaStatus, replacing, 18707 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18708 } 18709 18710 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18711 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18712 int size = pkgList.length; 18713 if (size > 0) { 18714 // Send broadcasts here 18715 Bundle extras = new Bundle(); 18716 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18717 if (uidArr != null) { 18718 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18719 } 18720 if (replacing) { 18721 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18722 } 18723 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18724 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18725 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18726 } 18727 } 18728 18729 /* 18730 * Look at potentially valid container ids from processCids If package 18731 * information doesn't match the one on record or package scanning fails, 18732 * the cid is added to list of removeCids. We currently don't delete stale 18733 * containers. 18734 */ 18735 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18736 boolean externalStorage) { 18737 ArrayList<String> pkgList = new ArrayList<String>(); 18738 Set<AsecInstallArgs> keys = processCids.keySet(); 18739 18740 for (AsecInstallArgs args : keys) { 18741 String codePath = processCids.get(args); 18742 if (DEBUG_SD_INSTALL) 18743 Log.i(TAG, "Loading container : " + args.cid); 18744 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18745 try { 18746 // Make sure there are no container errors first. 18747 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18748 Slog.e(TAG, "Failed to mount cid : " + args.cid 18749 + " when installing from sdcard"); 18750 continue; 18751 } 18752 // Check code path here. 18753 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18754 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18755 + " does not match one in settings " + codePath); 18756 continue; 18757 } 18758 // Parse package 18759 int parseFlags = mDefParseFlags; 18760 if (args.isExternalAsec()) { 18761 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18762 } 18763 if (args.isFwdLocked()) { 18764 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18765 } 18766 18767 synchronized (mInstallLock) { 18768 PackageParser.Package pkg = null; 18769 try { 18770 // Sadly we don't know the package name yet to freeze it 18771 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18772 SCAN_IGNORE_FROZEN, 0, null); 18773 } catch (PackageManagerException e) { 18774 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18775 } 18776 // Scan the package 18777 if (pkg != null) { 18778 /* 18779 * TODO why is the lock being held? doPostInstall is 18780 * called in other places without the lock. This needs 18781 * to be straightened out. 18782 */ 18783 // writer 18784 synchronized (mPackages) { 18785 retCode = PackageManager.INSTALL_SUCCEEDED; 18786 pkgList.add(pkg.packageName); 18787 // Post process args 18788 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18789 pkg.applicationInfo.uid); 18790 } 18791 } else { 18792 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18793 } 18794 } 18795 18796 } finally { 18797 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18798 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18799 } 18800 } 18801 } 18802 // writer 18803 synchronized (mPackages) { 18804 // If the platform SDK has changed since the last time we booted, 18805 // we need to re-grant app permission to catch any new ones that 18806 // appear. This is really a hack, and means that apps can in some 18807 // cases get permissions that the user didn't initially explicitly 18808 // allow... it would be nice to have some better way to handle 18809 // this situation. 18810 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18811 : mSettings.getInternalVersion(); 18812 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18813 : StorageManager.UUID_PRIVATE_INTERNAL; 18814 18815 int updateFlags = UPDATE_PERMISSIONS_ALL; 18816 if (ver.sdkVersion != mSdkVersion) { 18817 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18818 + mSdkVersion + "; regranting permissions for external"); 18819 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18820 } 18821 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18822 18823 // Yay, everything is now upgraded 18824 ver.forceCurrent(); 18825 18826 // can downgrade to reader 18827 // Persist settings 18828 mSettings.writeLPr(); 18829 } 18830 // Send a broadcast to let everyone know we are done processing 18831 if (pkgList.size() > 0) { 18832 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18833 } 18834 } 18835 18836 /* 18837 * Utility method to unload a list of specified containers 18838 */ 18839 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18840 // Just unmount all valid containers. 18841 for (AsecInstallArgs arg : cidArgs) { 18842 synchronized (mInstallLock) { 18843 arg.doPostDeleteLI(false); 18844 } 18845 } 18846 } 18847 18848 /* 18849 * Unload packages mounted on external media. This involves deleting package 18850 * data from internal structures, sending broadcasts about disabled packages, 18851 * gc'ing to free up references, unmounting all secure containers 18852 * corresponding to packages on external media, and posting a 18853 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18854 * that we always have to post this message if status has been requested no 18855 * matter what. 18856 */ 18857 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18858 final boolean reportStatus) { 18859 if (DEBUG_SD_INSTALL) 18860 Log.i(TAG, "unloading media packages"); 18861 ArrayList<String> pkgList = new ArrayList<String>(); 18862 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18863 final Set<AsecInstallArgs> keys = processCids.keySet(); 18864 for (AsecInstallArgs args : keys) { 18865 String pkgName = args.getPackageName(); 18866 if (DEBUG_SD_INSTALL) 18867 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18868 // Delete package internally 18869 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18870 synchronized (mInstallLock) { 18871 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18872 final boolean res; 18873 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18874 "unloadMediaPackages")) { 18875 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18876 null); 18877 } 18878 if (res) { 18879 pkgList.add(pkgName); 18880 } else { 18881 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18882 failedList.add(args); 18883 } 18884 } 18885 } 18886 18887 // reader 18888 synchronized (mPackages) { 18889 // We didn't update the settings after removing each package; 18890 // write them now for all packages. 18891 mSettings.writeLPr(); 18892 } 18893 18894 // We have to absolutely send UPDATED_MEDIA_STATUS only 18895 // after confirming that all the receivers processed the ordered 18896 // broadcast when packages get disabled, force a gc to clean things up. 18897 // and unload all the containers. 18898 if (pkgList.size() > 0) { 18899 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18900 new IIntentReceiver.Stub() { 18901 public void performReceive(Intent intent, int resultCode, String data, 18902 Bundle extras, boolean ordered, boolean sticky, 18903 int sendingUser) throws RemoteException { 18904 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18905 reportStatus ? 1 : 0, 1, keys); 18906 mHandler.sendMessage(msg); 18907 } 18908 }); 18909 } else { 18910 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18911 keys); 18912 mHandler.sendMessage(msg); 18913 } 18914 } 18915 18916 private void loadPrivatePackages(final VolumeInfo vol) { 18917 mHandler.post(new Runnable() { 18918 @Override 18919 public void run() { 18920 loadPrivatePackagesInner(vol); 18921 } 18922 }); 18923 } 18924 18925 private void loadPrivatePackagesInner(VolumeInfo vol) { 18926 final String volumeUuid = vol.fsUuid; 18927 if (TextUtils.isEmpty(volumeUuid)) { 18928 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18929 return; 18930 } 18931 18932 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18933 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18934 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18935 18936 final VersionInfo ver; 18937 final List<PackageSetting> packages; 18938 synchronized (mPackages) { 18939 ver = mSettings.findOrCreateVersion(volumeUuid); 18940 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18941 } 18942 18943 for (PackageSetting ps : packages) { 18944 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18945 synchronized (mInstallLock) { 18946 final PackageParser.Package pkg; 18947 try { 18948 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18949 loaded.add(pkg.applicationInfo); 18950 18951 } catch (PackageManagerException e) { 18952 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18953 } 18954 18955 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18956 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18957 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18958 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18959 } 18960 } 18961 } 18962 18963 // Reconcile app data for all started/unlocked users 18964 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18965 final UserManager um = mContext.getSystemService(UserManager.class); 18966 for (UserInfo user : um.getUsers()) { 18967 final int flags; 18968 if (um.isUserUnlockingOrUnlocked(user.id)) { 18969 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18970 } else if (um.isUserRunning(user.id)) { 18971 flags = StorageManager.FLAG_STORAGE_DE; 18972 } else { 18973 continue; 18974 } 18975 18976 try { 18977 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18978 synchronized (mInstallLock) { 18979 reconcileAppsDataLI(volumeUuid, user.id, flags); 18980 } 18981 } catch (IllegalStateException e) { 18982 // Device was probably ejected, and we'll process that event momentarily 18983 Slog.w(TAG, "Failed to prepare storage: " + e); 18984 } 18985 } 18986 18987 synchronized (mPackages) { 18988 int updateFlags = UPDATE_PERMISSIONS_ALL; 18989 if (ver.sdkVersion != mSdkVersion) { 18990 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18991 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18992 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18993 } 18994 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18995 18996 // Yay, everything is now upgraded 18997 ver.forceCurrent(); 18998 18999 mSettings.writeLPr(); 19000 } 19001 19002 for (PackageFreezer freezer : freezers) { 19003 freezer.close(); 19004 } 19005 19006 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 19007 sendResourcesChangedBroadcast(true, false, loaded, null); 19008 } 19009 19010 private void unloadPrivatePackages(final VolumeInfo vol) { 19011 mHandler.post(new Runnable() { 19012 @Override 19013 public void run() { 19014 unloadPrivatePackagesInner(vol); 19015 } 19016 }); 19017 } 19018 19019 private void unloadPrivatePackagesInner(VolumeInfo vol) { 19020 final String volumeUuid = vol.fsUuid; 19021 if (TextUtils.isEmpty(volumeUuid)) { 19022 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 19023 return; 19024 } 19025 19026 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 19027 synchronized (mInstallLock) { 19028 synchronized (mPackages) { 19029 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 19030 for (PackageSetting ps : packages) { 19031 if (ps.pkg == null) continue; 19032 19033 final ApplicationInfo info = ps.pkg.applicationInfo; 19034 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 19035 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 19036 19037 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 19038 "unloadPrivatePackagesInner")) { 19039 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 19040 false, null)) { 19041 unloaded.add(info); 19042 } else { 19043 Slog.w(TAG, "Failed to unload " + ps.codePath); 19044 } 19045 } 19046 } 19047 19048 mSettings.writeLPr(); 19049 } 19050 } 19051 19052 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19053 sendResourcesChangedBroadcast(false, false, unloaded, null); 19054 } 19055 19056 /** 19057 * Prepare storage areas for given user on all mounted devices. 19058 */ 19059 void prepareUserData(int userId, int userSerial, int flags) { 19060 synchronized (mInstallLock) { 19061 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19062 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19063 final String volumeUuid = vol.getFsUuid(); 19064 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19065 } 19066 } 19067 } 19068 19069 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19070 boolean allowRecover) { 19071 // Prepare storage and verify that serial numbers are consistent; if 19072 // there's a mismatch we need to destroy to avoid leaking data 19073 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19074 try { 19075 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19076 19077 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19078 UserManagerService.enforceSerialNumber( 19079 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19080 } 19081 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19082 UserManagerService.enforceSerialNumber( 19083 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19084 } 19085 19086 synchronized (mInstallLock) { 19087 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19088 } 19089 } catch (Exception e) { 19090 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19091 + " because we failed to prepare: " + e); 19092 destroyUserDataLI(volumeUuid, userId, 19093 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19094 19095 if (allowRecover) { 19096 // Try one last time; if we fail again we're really in trouble 19097 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19098 } 19099 } 19100 } 19101 19102 /** 19103 * Destroy storage areas for given user on all mounted devices. 19104 */ 19105 void destroyUserData(int userId, int flags) { 19106 synchronized (mInstallLock) { 19107 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19108 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19109 final String volumeUuid = vol.getFsUuid(); 19110 destroyUserDataLI(volumeUuid, userId, flags); 19111 } 19112 } 19113 } 19114 19115 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19116 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19117 try { 19118 // Clean up app data, profile data, and media data 19119 mInstaller.destroyUserData(volumeUuid, userId, flags); 19120 19121 // Clean up system data 19122 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19123 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19124 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19125 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19126 } 19127 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19128 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19129 } 19130 } 19131 19132 // Data with special labels is now gone, so finish the job 19133 storage.destroyUserStorage(volumeUuid, userId, flags); 19134 19135 } catch (Exception e) { 19136 logCriticalInfo(Log.WARN, 19137 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19138 } 19139 } 19140 19141 /** 19142 * Examine all users present on given mounted volume, and destroy data 19143 * belonging to users that are no longer valid, or whose user ID has been 19144 * recycled. 19145 */ 19146 private void reconcileUsers(String volumeUuid) { 19147 final List<File> files = new ArrayList<>(); 19148 Collections.addAll(files, FileUtils 19149 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19150 Collections.addAll(files, FileUtils 19151 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19152 for (File file : files) { 19153 if (!file.isDirectory()) continue; 19154 19155 final int userId; 19156 final UserInfo info; 19157 try { 19158 userId = Integer.parseInt(file.getName()); 19159 info = sUserManager.getUserInfo(userId); 19160 } catch (NumberFormatException e) { 19161 Slog.w(TAG, "Invalid user directory " + file); 19162 continue; 19163 } 19164 19165 boolean destroyUser = false; 19166 if (info == null) { 19167 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19168 + " because no matching user was found"); 19169 destroyUser = true; 19170 } else if (!mOnlyCore) { 19171 try { 19172 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19173 } catch (IOException e) { 19174 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19175 + " because we failed to enforce serial number: " + e); 19176 destroyUser = true; 19177 } 19178 } 19179 19180 if (destroyUser) { 19181 synchronized (mInstallLock) { 19182 destroyUserDataLI(volumeUuid, userId, 19183 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19184 } 19185 } 19186 } 19187 } 19188 19189 private void assertPackageKnown(String volumeUuid, String packageName) 19190 throws PackageManagerException { 19191 synchronized (mPackages) { 19192 final PackageSetting ps = mSettings.mPackages.get(packageName); 19193 if (ps == null) { 19194 throw new PackageManagerException("Package " + packageName + " is unknown"); 19195 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19196 throw new PackageManagerException( 19197 "Package " + packageName + " found on unknown volume " + volumeUuid 19198 + "; expected volume " + ps.volumeUuid); 19199 } 19200 } 19201 } 19202 19203 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19204 throws PackageManagerException { 19205 synchronized (mPackages) { 19206 final PackageSetting ps = mSettings.mPackages.get(packageName); 19207 if (ps == null) { 19208 throw new PackageManagerException("Package " + packageName + " is unknown"); 19209 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19210 throw new PackageManagerException( 19211 "Package " + packageName + " found on unknown volume " + volumeUuid 19212 + "; expected volume " + ps.volumeUuid); 19213 } else if (!ps.getInstalled(userId)) { 19214 throw new PackageManagerException( 19215 "Package " + packageName + " not installed for user " + userId); 19216 } 19217 } 19218 } 19219 19220 /** 19221 * Examine all apps present on given mounted volume, and destroy apps that 19222 * aren't expected, either due to uninstallation or reinstallation on 19223 * another volume. 19224 */ 19225 private void reconcileApps(String volumeUuid) { 19226 final File[] files = FileUtils 19227 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19228 for (File file : files) { 19229 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19230 && !PackageInstallerService.isStageName(file.getName()); 19231 if (!isPackage) { 19232 // Ignore entries which are not packages 19233 continue; 19234 } 19235 19236 try { 19237 final PackageLite pkg = PackageParser.parsePackageLite(file, 19238 PackageParser.PARSE_MUST_BE_APK); 19239 assertPackageKnown(volumeUuid, pkg.packageName); 19240 19241 } catch (PackageParserException | PackageManagerException e) { 19242 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19243 synchronized (mInstallLock) { 19244 removeCodePathLI(file); 19245 } 19246 } 19247 } 19248 } 19249 19250 /** 19251 * Reconcile all app data for the given user. 19252 * <p> 19253 * Verifies that directories exist and that ownership and labeling is 19254 * correct for all installed apps on all mounted volumes. 19255 */ 19256 void reconcileAppsData(int userId, int flags) { 19257 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19258 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19259 final String volumeUuid = vol.getFsUuid(); 19260 synchronized (mInstallLock) { 19261 reconcileAppsDataLI(volumeUuid, userId, flags); 19262 } 19263 } 19264 } 19265 19266 /** 19267 * Reconcile all app data on given mounted volume. 19268 * <p> 19269 * Destroys app data that isn't expected, either due to uninstallation or 19270 * reinstallation on another volume. 19271 * <p> 19272 * Verifies that directories exist and that ownership and labeling is 19273 * correct for all installed apps. 19274 */ 19275 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19276 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19277 + Integer.toHexString(flags)); 19278 19279 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19280 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19281 19282 boolean restoreconNeeded = false; 19283 19284 // First look for stale data that doesn't belong, and check if things 19285 // have changed since we did our last restorecon 19286 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19287 if (StorageManager.isFileEncryptedNativeOrEmulated() 19288 && !StorageManager.isUserKeyUnlocked(userId)) { 19289 throw new RuntimeException( 19290 "Yikes, someone asked us to reconcile CE storage while " + userId 19291 + " was still locked; this would have caused massive data loss!"); 19292 } 19293 19294 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19295 19296 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19297 for (File file : files) { 19298 final String packageName = file.getName(); 19299 try { 19300 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19301 } catch (PackageManagerException e) { 19302 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19303 try { 19304 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19305 StorageManager.FLAG_STORAGE_CE, 0); 19306 } catch (InstallerException e2) { 19307 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19308 } 19309 } 19310 } 19311 } 19312 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19313 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19314 19315 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19316 for (File file : files) { 19317 final String packageName = file.getName(); 19318 try { 19319 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19320 } catch (PackageManagerException e) { 19321 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19322 try { 19323 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19324 StorageManager.FLAG_STORAGE_DE, 0); 19325 } catch (InstallerException e2) { 19326 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19327 } 19328 } 19329 } 19330 } 19331 19332 // Ensure that data directories are ready to roll for all packages 19333 // installed for this volume and user 19334 final List<PackageSetting> packages; 19335 synchronized (mPackages) { 19336 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19337 } 19338 int preparedCount = 0; 19339 for (PackageSetting ps : packages) { 19340 final String packageName = ps.name; 19341 if (ps.pkg == null) { 19342 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19343 // TODO: might be due to legacy ASEC apps; we should circle back 19344 // and reconcile again once they're scanned 19345 continue; 19346 } 19347 19348 if (ps.getInstalled(userId)) { 19349 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19350 19351 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19352 // We may have just shuffled around app data directories, so 19353 // prepare them one more time 19354 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19355 } 19356 19357 preparedCount++; 19358 } 19359 } 19360 19361 if (restoreconNeeded) { 19362 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19363 SELinuxMMAC.setRestoreconDone(ceDir); 19364 } 19365 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19366 SELinuxMMAC.setRestoreconDone(deDir); 19367 } 19368 } 19369 19370 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19371 + " packages; restoreconNeeded was " + restoreconNeeded); 19372 } 19373 19374 /** 19375 * Prepare app data for the given app just after it was installed or 19376 * upgraded. This method carefully only touches users that it's installed 19377 * for, and it forces a restorecon to handle any seinfo changes. 19378 * <p> 19379 * Verifies that directories exist and that ownership and labeling is 19380 * correct for all installed apps. If there is an ownership mismatch, it 19381 * will try recovering system apps by wiping data; third-party app data is 19382 * left intact. 19383 * <p> 19384 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19385 */ 19386 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19387 final PackageSetting ps; 19388 synchronized (mPackages) { 19389 ps = mSettings.mPackages.get(pkg.packageName); 19390 mSettings.writeKernelMappingLPr(ps); 19391 } 19392 19393 final UserManager um = mContext.getSystemService(UserManager.class); 19394 for (UserInfo user : um.getUsers()) { 19395 final int flags; 19396 if (um.isUserUnlockingOrUnlocked(user.id)) { 19397 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19398 } else if (um.isUserRunning(user.id)) { 19399 flags = StorageManager.FLAG_STORAGE_DE; 19400 } else { 19401 continue; 19402 } 19403 19404 if (ps.getInstalled(user.id)) { 19405 // Whenever an app changes, force a restorecon of its data 19406 // TODO: when user data is locked, mark that we're still dirty 19407 prepareAppDataLIF(pkg, user.id, flags, true); 19408 } 19409 } 19410 } 19411 19412 /** 19413 * Prepare app data for the given app. 19414 * <p> 19415 * Verifies that directories exist and that ownership and labeling is 19416 * correct for all installed apps. If there is an ownership mismatch, this 19417 * will try recovering system apps by wiping data; third-party app data is 19418 * left intact. 19419 */ 19420 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19421 boolean restoreconNeeded) { 19422 if (pkg == null) { 19423 Slog.wtf(TAG, "Package was null!", new Throwable()); 19424 return; 19425 } 19426 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19427 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19428 for (int i = 0; i < childCount; i++) { 19429 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19430 } 19431 } 19432 19433 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19434 boolean restoreconNeeded) { 19435 if (DEBUG_APP_DATA) { 19436 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19437 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19438 } 19439 19440 final String volumeUuid = pkg.volumeUuid; 19441 final String packageName = pkg.packageName; 19442 final ApplicationInfo app = pkg.applicationInfo; 19443 final int appId = UserHandle.getAppId(app.uid); 19444 19445 Preconditions.checkNotNull(app.seinfo); 19446 19447 try { 19448 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19449 appId, app.seinfo, app.targetSdkVersion); 19450 } catch (InstallerException e) { 19451 if (app.isSystemApp()) { 19452 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19453 + ", but trying to recover: " + e); 19454 destroyAppDataLeafLIF(pkg, userId, flags); 19455 try { 19456 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19457 appId, app.seinfo, app.targetSdkVersion); 19458 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19459 } catch (InstallerException e2) { 19460 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19461 } 19462 } else { 19463 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19464 } 19465 } 19466 19467 if (restoreconNeeded) { 19468 try { 19469 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19470 app.seinfo); 19471 } catch (InstallerException e) { 19472 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19473 } 19474 } 19475 19476 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19477 try { 19478 // CE storage is unlocked right now, so read out the inode and 19479 // remember for use later when it's locked 19480 // TODO: mark this structure as dirty so we persist it! 19481 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19482 StorageManager.FLAG_STORAGE_CE); 19483 synchronized (mPackages) { 19484 final PackageSetting ps = mSettings.mPackages.get(packageName); 19485 if (ps != null) { 19486 ps.setCeDataInode(ceDataInode, userId); 19487 } 19488 } 19489 } catch (InstallerException e) { 19490 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19491 } 19492 } 19493 19494 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19495 } 19496 19497 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19498 if (pkg == null) { 19499 Slog.wtf(TAG, "Package was null!", new Throwable()); 19500 return; 19501 } 19502 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19503 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19504 for (int i = 0; i < childCount; i++) { 19505 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19506 } 19507 } 19508 19509 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19510 final String volumeUuid = pkg.volumeUuid; 19511 final String packageName = pkg.packageName; 19512 final ApplicationInfo app = pkg.applicationInfo; 19513 19514 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19515 // Create a native library symlink only if we have native libraries 19516 // and if the native libraries are 32 bit libraries. We do not provide 19517 // this symlink for 64 bit libraries. 19518 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19519 final String nativeLibPath = app.nativeLibraryDir; 19520 try { 19521 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19522 nativeLibPath, userId); 19523 } catch (InstallerException e) { 19524 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19525 } 19526 } 19527 } 19528 } 19529 19530 /** 19531 * For system apps on non-FBE devices, this method migrates any existing 19532 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19533 * requested by the app. 19534 */ 19535 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19536 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19537 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19538 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19539 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19540 try { 19541 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19542 storageTarget); 19543 } catch (InstallerException e) { 19544 logCriticalInfo(Log.WARN, 19545 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19546 } 19547 return true; 19548 } else { 19549 return false; 19550 } 19551 } 19552 19553 public PackageFreezer freezePackage(String packageName, String killReason) { 19554 return new PackageFreezer(packageName, killReason); 19555 } 19556 19557 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19558 String killReason) { 19559 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19560 return new PackageFreezer(); 19561 } else { 19562 return freezePackage(packageName, killReason); 19563 } 19564 } 19565 19566 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19567 String killReason) { 19568 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19569 return new PackageFreezer(); 19570 } else { 19571 return freezePackage(packageName, killReason); 19572 } 19573 } 19574 19575 /** 19576 * Class that freezes and kills the given package upon creation, and 19577 * unfreezes it upon closing. This is typically used when doing surgery on 19578 * app code/data to prevent the app from running while you're working. 19579 */ 19580 private class PackageFreezer implements AutoCloseable { 19581 private final String mPackageName; 19582 private final PackageFreezer[] mChildren; 19583 19584 private final boolean mWeFroze; 19585 19586 private final AtomicBoolean mClosed = new AtomicBoolean(); 19587 private final CloseGuard mCloseGuard = CloseGuard.get(); 19588 19589 /** 19590 * Create and return a stub freezer that doesn't actually do anything, 19591 * typically used when someone requested 19592 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19593 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19594 */ 19595 public PackageFreezer() { 19596 mPackageName = null; 19597 mChildren = null; 19598 mWeFroze = false; 19599 mCloseGuard.open("close"); 19600 } 19601 19602 public PackageFreezer(String packageName, String killReason) { 19603 synchronized (mPackages) { 19604 mPackageName = packageName; 19605 mWeFroze = mFrozenPackages.add(mPackageName); 19606 19607 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19608 if (ps != null) { 19609 killApplication(ps.name, ps.appId, killReason); 19610 } 19611 19612 final PackageParser.Package p = mPackages.get(packageName); 19613 if (p != null && p.childPackages != null) { 19614 final int N = p.childPackages.size(); 19615 mChildren = new PackageFreezer[N]; 19616 for (int i = 0; i < N; i++) { 19617 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19618 killReason); 19619 } 19620 } else { 19621 mChildren = null; 19622 } 19623 } 19624 mCloseGuard.open("close"); 19625 } 19626 19627 @Override 19628 protected void finalize() throws Throwable { 19629 try { 19630 mCloseGuard.warnIfOpen(); 19631 close(); 19632 } finally { 19633 super.finalize(); 19634 } 19635 } 19636 19637 @Override 19638 public void close() { 19639 mCloseGuard.close(); 19640 if (mClosed.compareAndSet(false, true)) { 19641 synchronized (mPackages) { 19642 if (mWeFroze) { 19643 mFrozenPackages.remove(mPackageName); 19644 } 19645 19646 if (mChildren != null) { 19647 for (PackageFreezer freezer : mChildren) { 19648 freezer.close(); 19649 } 19650 } 19651 } 19652 } 19653 } 19654 } 19655 19656 /** 19657 * Verify that given package is currently frozen. 19658 */ 19659 private void checkPackageFrozen(String packageName) { 19660 synchronized (mPackages) { 19661 if (!mFrozenPackages.contains(packageName)) { 19662 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19663 } 19664 } 19665 } 19666 19667 @Override 19668 public int movePackage(final String packageName, final String volumeUuid) { 19669 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19670 19671 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19672 final int moveId = mNextMoveId.getAndIncrement(); 19673 mHandler.post(new Runnable() { 19674 @Override 19675 public void run() { 19676 try { 19677 movePackageInternal(packageName, volumeUuid, moveId, user); 19678 } catch (PackageManagerException e) { 19679 Slog.w(TAG, "Failed to move " + packageName, e); 19680 mMoveCallbacks.notifyStatusChanged(moveId, 19681 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19682 } 19683 } 19684 }); 19685 return moveId; 19686 } 19687 19688 private void movePackageInternal(final String packageName, final String volumeUuid, 19689 final int moveId, UserHandle user) throws PackageManagerException { 19690 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19691 final PackageManager pm = mContext.getPackageManager(); 19692 19693 final boolean currentAsec; 19694 final String currentVolumeUuid; 19695 final File codeFile; 19696 final String installerPackageName; 19697 final String packageAbiOverride; 19698 final int appId; 19699 final String seinfo; 19700 final String label; 19701 final int targetSdkVersion; 19702 final PackageFreezer freezer; 19703 final int[] installedUserIds; 19704 19705 // reader 19706 synchronized (mPackages) { 19707 final PackageParser.Package pkg = mPackages.get(packageName); 19708 final PackageSetting ps = mSettings.mPackages.get(packageName); 19709 if (pkg == null || ps == null) { 19710 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19711 } 19712 19713 if (pkg.applicationInfo.isSystemApp()) { 19714 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19715 "Cannot move system application"); 19716 } 19717 19718 if (pkg.applicationInfo.isExternalAsec()) { 19719 currentAsec = true; 19720 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19721 } else if (pkg.applicationInfo.isForwardLocked()) { 19722 currentAsec = true; 19723 currentVolumeUuid = "forward_locked"; 19724 } else { 19725 currentAsec = false; 19726 currentVolumeUuid = ps.volumeUuid; 19727 19728 final File probe = new File(pkg.codePath); 19729 final File probeOat = new File(probe, "oat"); 19730 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19731 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19732 "Move only supported for modern cluster style installs"); 19733 } 19734 } 19735 19736 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19737 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19738 "Package already moved to " + volumeUuid); 19739 } 19740 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19741 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19742 "Device admin cannot be moved"); 19743 } 19744 19745 if (mFrozenPackages.contains(packageName)) { 19746 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19747 "Failed to move already frozen package"); 19748 } 19749 19750 codeFile = new File(pkg.codePath); 19751 installerPackageName = ps.installerPackageName; 19752 packageAbiOverride = ps.cpuAbiOverrideString; 19753 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19754 seinfo = pkg.applicationInfo.seinfo; 19755 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19756 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19757 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19758 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19759 } 19760 19761 final Bundle extras = new Bundle(); 19762 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19763 extras.putString(Intent.EXTRA_TITLE, label); 19764 mMoveCallbacks.notifyCreated(moveId, extras); 19765 19766 int installFlags; 19767 final boolean moveCompleteApp; 19768 final File measurePath; 19769 19770 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19771 installFlags = INSTALL_INTERNAL; 19772 moveCompleteApp = !currentAsec; 19773 measurePath = Environment.getDataAppDirectory(volumeUuid); 19774 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19775 installFlags = INSTALL_EXTERNAL; 19776 moveCompleteApp = false; 19777 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19778 } else { 19779 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19780 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19781 || !volume.isMountedWritable()) { 19782 freezer.close(); 19783 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19784 "Move location not mounted private volume"); 19785 } 19786 19787 Preconditions.checkState(!currentAsec); 19788 19789 installFlags = INSTALL_INTERNAL; 19790 moveCompleteApp = true; 19791 measurePath = Environment.getDataAppDirectory(volumeUuid); 19792 } 19793 19794 final PackageStats stats = new PackageStats(null, -1); 19795 synchronized (mInstaller) { 19796 for (int userId : installedUserIds) { 19797 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19798 freezer.close(); 19799 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19800 "Failed to measure package size"); 19801 } 19802 } 19803 } 19804 19805 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19806 + stats.dataSize); 19807 19808 final long startFreeBytes = measurePath.getFreeSpace(); 19809 final long sizeBytes; 19810 if (moveCompleteApp) { 19811 sizeBytes = stats.codeSize + stats.dataSize; 19812 } else { 19813 sizeBytes = stats.codeSize; 19814 } 19815 19816 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19817 freezer.close(); 19818 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19819 "Not enough free space to move"); 19820 } 19821 19822 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19823 19824 final CountDownLatch installedLatch = new CountDownLatch(1); 19825 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19826 @Override 19827 public void onUserActionRequired(Intent intent) throws RemoteException { 19828 throw new IllegalStateException(); 19829 } 19830 19831 @Override 19832 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19833 Bundle extras) throws RemoteException { 19834 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19835 + PackageManager.installStatusToString(returnCode, msg)); 19836 19837 installedLatch.countDown(); 19838 freezer.close(); 19839 19840 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19841 switch (status) { 19842 case PackageInstaller.STATUS_SUCCESS: 19843 mMoveCallbacks.notifyStatusChanged(moveId, 19844 PackageManager.MOVE_SUCCEEDED); 19845 break; 19846 case PackageInstaller.STATUS_FAILURE_STORAGE: 19847 mMoveCallbacks.notifyStatusChanged(moveId, 19848 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19849 break; 19850 default: 19851 mMoveCallbacks.notifyStatusChanged(moveId, 19852 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19853 break; 19854 } 19855 } 19856 }; 19857 19858 final MoveInfo move; 19859 if (moveCompleteApp) { 19860 // Kick off a thread to report progress estimates 19861 new Thread() { 19862 @Override 19863 public void run() { 19864 while (true) { 19865 try { 19866 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19867 break; 19868 } 19869 } catch (InterruptedException ignored) { 19870 } 19871 19872 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19873 final int progress = 10 + (int) MathUtils.constrain( 19874 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19875 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19876 } 19877 } 19878 }.start(); 19879 19880 final String dataAppName = codeFile.getName(); 19881 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19882 dataAppName, appId, seinfo, targetSdkVersion); 19883 } else { 19884 move = null; 19885 } 19886 19887 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19888 19889 final Message msg = mHandler.obtainMessage(INIT_COPY); 19890 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19891 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19892 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19893 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19894 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19895 msg.obj = params; 19896 19897 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19898 System.identityHashCode(msg.obj)); 19899 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19900 System.identityHashCode(msg.obj)); 19901 19902 mHandler.sendMessage(msg); 19903 } 19904 19905 @Override 19906 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19907 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19908 19909 final int realMoveId = mNextMoveId.getAndIncrement(); 19910 final Bundle extras = new Bundle(); 19911 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19912 mMoveCallbacks.notifyCreated(realMoveId, extras); 19913 19914 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19915 @Override 19916 public void onCreated(int moveId, Bundle extras) { 19917 // Ignored 19918 } 19919 19920 @Override 19921 public void onStatusChanged(int moveId, int status, long estMillis) { 19922 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19923 } 19924 }; 19925 19926 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19927 storage.setPrimaryStorageUuid(volumeUuid, callback); 19928 return realMoveId; 19929 } 19930 19931 @Override 19932 public int getMoveStatus(int moveId) { 19933 mContext.enforceCallingOrSelfPermission( 19934 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19935 return mMoveCallbacks.mLastStatus.get(moveId); 19936 } 19937 19938 @Override 19939 public void registerMoveCallback(IPackageMoveObserver callback) { 19940 mContext.enforceCallingOrSelfPermission( 19941 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19942 mMoveCallbacks.register(callback); 19943 } 19944 19945 @Override 19946 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19947 mContext.enforceCallingOrSelfPermission( 19948 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19949 mMoveCallbacks.unregister(callback); 19950 } 19951 19952 @Override 19953 public boolean setInstallLocation(int loc) { 19954 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19955 null); 19956 if (getInstallLocation() == loc) { 19957 return true; 19958 } 19959 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19960 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19961 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19962 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19963 return true; 19964 } 19965 return false; 19966 } 19967 19968 @Override 19969 public int getInstallLocation() { 19970 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19971 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19972 PackageHelper.APP_INSTALL_AUTO); 19973 } 19974 19975 /** Called by UserManagerService */ 19976 void cleanUpUser(UserManagerService userManager, int userHandle) { 19977 synchronized (mPackages) { 19978 mDirtyUsers.remove(userHandle); 19979 mUserNeedsBadging.delete(userHandle); 19980 mSettings.removeUserLPw(userHandle); 19981 mPendingBroadcasts.remove(userHandle); 19982 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19983 removeUnusedPackagesLPw(userManager, userHandle); 19984 } 19985 } 19986 19987 /** 19988 * We're removing userHandle and would like to remove any downloaded packages 19989 * that are no longer in use by any other user. 19990 * @param userHandle the user being removed 19991 */ 19992 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19993 final boolean DEBUG_CLEAN_APKS = false; 19994 int [] users = userManager.getUserIds(); 19995 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19996 while (psit.hasNext()) { 19997 PackageSetting ps = psit.next(); 19998 if (ps.pkg == null) { 19999 continue; 20000 } 20001 final String packageName = ps.pkg.packageName; 20002 // Skip over if system app 20003 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 20004 continue; 20005 } 20006 if (DEBUG_CLEAN_APKS) { 20007 Slog.i(TAG, "Checking package " + packageName); 20008 } 20009 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 20010 if (keep) { 20011 if (DEBUG_CLEAN_APKS) { 20012 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 20013 } 20014 } else { 20015 for (int i = 0; i < users.length; i++) { 20016 if (users[i] != userHandle && ps.getInstalled(users[i])) { 20017 keep = true; 20018 if (DEBUG_CLEAN_APKS) { 20019 Slog.i(TAG, " Keeping package " + packageName + " for user " 20020 + users[i]); 20021 } 20022 break; 20023 } 20024 } 20025 } 20026 if (!keep) { 20027 if (DEBUG_CLEAN_APKS) { 20028 Slog.i(TAG, " Removing package " + packageName); 20029 } 20030 mHandler.post(new Runnable() { 20031 public void run() { 20032 deletePackageX(packageName, userHandle, 0); 20033 } //end run 20034 }); 20035 } 20036 } 20037 } 20038 20039 /** Called by UserManagerService */ 20040 void createNewUser(int userHandle) { 20041 synchronized (mInstallLock) { 20042 mSettings.createNewUserLI(this, mInstaller, userHandle); 20043 } 20044 synchronized (mPackages) { 20045 applyFactoryDefaultBrowserLPw(userHandle); 20046 primeDomainVerificationsLPw(userHandle); 20047 } 20048 } 20049 20050 void newUserCreated(final int userHandle) { 20051 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20052 // If permission review for legacy apps is required, we represent 20053 // dagerous permissions for such apps as always granted runtime 20054 // permissions to keep per user flag state whether review is needed. 20055 // Hence, if a new user is added we have to propagate dangerous 20056 // permission grants for these legacy apps. 20057 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20058 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20059 | UPDATE_PERMISSIONS_REPLACE_ALL); 20060 } 20061 } 20062 20063 @Override 20064 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20065 mContext.enforceCallingOrSelfPermission( 20066 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20067 "Only package verification agents can read the verifier device identity"); 20068 20069 synchronized (mPackages) { 20070 return mSettings.getVerifierDeviceIdentityLPw(); 20071 } 20072 } 20073 20074 @Override 20075 public void setPermissionEnforced(String permission, boolean enforced) { 20076 // TODO: Now that we no longer change GID for storage, this should to away. 20077 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20078 "setPermissionEnforced"); 20079 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20080 synchronized (mPackages) { 20081 if (mSettings.mReadExternalStorageEnforced == null 20082 || mSettings.mReadExternalStorageEnforced != enforced) { 20083 mSettings.mReadExternalStorageEnforced = enforced; 20084 mSettings.writeLPr(); 20085 } 20086 } 20087 // kill any non-foreground processes so we restart them and 20088 // grant/revoke the GID. 20089 final IActivityManager am = ActivityManagerNative.getDefault(); 20090 if (am != null) { 20091 final long token = Binder.clearCallingIdentity(); 20092 try { 20093 am.killProcessesBelowForeground("setPermissionEnforcement"); 20094 } catch (RemoteException e) { 20095 } finally { 20096 Binder.restoreCallingIdentity(token); 20097 } 20098 } 20099 } else { 20100 throw new IllegalArgumentException("No selective enforcement for " + permission); 20101 } 20102 } 20103 20104 @Override 20105 @Deprecated 20106 public boolean isPermissionEnforced(String permission) { 20107 return true; 20108 } 20109 20110 @Override 20111 public boolean isStorageLow() { 20112 final long token = Binder.clearCallingIdentity(); 20113 try { 20114 final DeviceStorageMonitorInternal 20115 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20116 if (dsm != null) { 20117 return dsm.isMemoryLow(); 20118 } else { 20119 return false; 20120 } 20121 } finally { 20122 Binder.restoreCallingIdentity(token); 20123 } 20124 } 20125 20126 @Override 20127 public IPackageInstaller getPackageInstaller() { 20128 return mInstallerService; 20129 } 20130 20131 private boolean userNeedsBadging(int userId) { 20132 int index = mUserNeedsBadging.indexOfKey(userId); 20133 if (index < 0) { 20134 final UserInfo userInfo; 20135 final long token = Binder.clearCallingIdentity(); 20136 try { 20137 userInfo = sUserManager.getUserInfo(userId); 20138 } finally { 20139 Binder.restoreCallingIdentity(token); 20140 } 20141 final boolean b; 20142 if (userInfo != null && userInfo.isManagedProfile()) { 20143 b = true; 20144 } else { 20145 b = false; 20146 } 20147 mUserNeedsBadging.put(userId, b); 20148 return b; 20149 } 20150 return mUserNeedsBadging.valueAt(index); 20151 } 20152 20153 @Override 20154 public KeySet getKeySetByAlias(String packageName, String alias) { 20155 if (packageName == null || alias == null) { 20156 return null; 20157 } 20158 synchronized(mPackages) { 20159 final PackageParser.Package pkg = mPackages.get(packageName); 20160 if (pkg == null) { 20161 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20162 throw new IllegalArgumentException("Unknown package: " + packageName); 20163 } 20164 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20165 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20166 } 20167 } 20168 20169 @Override 20170 public KeySet getSigningKeySet(String packageName) { 20171 if (packageName == null) { 20172 return null; 20173 } 20174 synchronized(mPackages) { 20175 final PackageParser.Package pkg = mPackages.get(packageName); 20176 if (pkg == null) { 20177 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20178 throw new IllegalArgumentException("Unknown package: " + packageName); 20179 } 20180 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20181 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20182 throw new SecurityException("May not access signing KeySet of other apps."); 20183 } 20184 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20185 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20186 } 20187 } 20188 20189 @Override 20190 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20191 if (packageName == null || ks == null) { 20192 return false; 20193 } 20194 synchronized(mPackages) { 20195 final PackageParser.Package pkg = mPackages.get(packageName); 20196 if (pkg == null) { 20197 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20198 throw new IllegalArgumentException("Unknown package: " + packageName); 20199 } 20200 IBinder ksh = ks.getToken(); 20201 if (ksh instanceof KeySetHandle) { 20202 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20203 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20204 } 20205 return false; 20206 } 20207 } 20208 20209 @Override 20210 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20211 if (packageName == null || ks == null) { 20212 return false; 20213 } 20214 synchronized(mPackages) { 20215 final PackageParser.Package pkg = mPackages.get(packageName); 20216 if (pkg == null) { 20217 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20218 throw new IllegalArgumentException("Unknown package: " + packageName); 20219 } 20220 IBinder ksh = ks.getToken(); 20221 if (ksh instanceof KeySetHandle) { 20222 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20223 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20224 } 20225 return false; 20226 } 20227 } 20228 20229 private void deletePackageIfUnusedLPr(final String packageName) { 20230 PackageSetting ps = mSettings.mPackages.get(packageName); 20231 if (ps == null) { 20232 return; 20233 } 20234 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20235 // TODO Implement atomic delete if package is unused 20236 // It is currently possible that the package will be deleted even if it is installed 20237 // after this method returns. 20238 mHandler.post(new Runnable() { 20239 public void run() { 20240 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20241 } 20242 }); 20243 } 20244 } 20245 20246 /** 20247 * Check and throw if the given before/after packages would be considered a 20248 * downgrade. 20249 */ 20250 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20251 throws PackageManagerException { 20252 if (after.versionCode < before.mVersionCode) { 20253 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20254 "Update version code " + after.versionCode + " is older than current " 20255 + before.mVersionCode); 20256 } else if (after.versionCode == before.mVersionCode) { 20257 if (after.baseRevisionCode < before.baseRevisionCode) { 20258 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20259 "Update base revision code " + after.baseRevisionCode 20260 + " is older than current " + before.baseRevisionCode); 20261 } 20262 20263 if (!ArrayUtils.isEmpty(after.splitNames)) { 20264 for (int i = 0; i < after.splitNames.length; i++) { 20265 final String splitName = after.splitNames[i]; 20266 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20267 if (j != -1) { 20268 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20269 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20270 "Update split " + splitName + " revision code " 20271 + after.splitRevisionCodes[i] + " is older than current " 20272 + before.splitRevisionCodes[j]); 20273 } 20274 } 20275 } 20276 } 20277 } 20278 } 20279 20280 private static class MoveCallbacks extends Handler { 20281 private static final int MSG_CREATED = 1; 20282 private static final int MSG_STATUS_CHANGED = 2; 20283 20284 private final RemoteCallbackList<IPackageMoveObserver> 20285 mCallbacks = new RemoteCallbackList<>(); 20286 20287 private final SparseIntArray mLastStatus = new SparseIntArray(); 20288 20289 public MoveCallbacks(Looper looper) { 20290 super(looper); 20291 } 20292 20293 public void register(IPackageMoveObserver callback) { 20294 mCallbacks.register(callback); 20295 } 20296 20297 public void unregister(IPackageMoveObserver callback) { 20298 mCallbacks.unregister(callback); 20299 } 20300 20301 @Override 20302 public void handleMessage(Message msg) { 20303 final SomeArgs args = (SomeArgs) msg.obj; 20304 final int n = mCallbacks.beginBroadcast(); 20305 for (int i = 0; i < n; i++) { 20306 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20307 try { 20308 invokeCallback(callback, msg.what, args); 20309 } catch (RemoteException ignored) { 20310 } 20311 } 20312 mCallbacks.finishBroadcast(); 20313 args.recycle(); 20314 } 20315 20316 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20317 throws RemoteException { 20318 switch (what) { 20319 case MSG_CREATED: { 20320 callback.onCreated(args.argi1, (Bundle) args.arg2); 20321 break; 20322 } 20323 case MSG_STATUS_CHANGED: { 20324 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20325 break; 20326 } 20327 } 20328 } 20329 20330 private void notifyCreated(int moveId, Bundle extras) { 20331 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20332 20333 final SomeArgs args = SomeArgs.obtain(); 20334 args.argi1 = moveId; 20335 args.arg2 = extras; 20336 obtainMessage(MSG_CREATED, args).sendToTarget(); 20337 } 20338 20339 private void notifyStatusChanged(int moveId, int status) { 20340 notifyStatusChanged(moveId, status, -1); 20341 } 20342 20343 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20344 Slog.v(TAG, "Move " + moveId + " status " + status); 20345 20346 final SomeArgs args = SomeArgs.obtain(); 20347 args.argi1 = moveId; 20348 args.argi2 = status; 20349 args.arg3 = estMillis; 20350 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20351 20352 synchronized (mLastStatus) { 20353 mLastStatus.put(moveId, status); 20354 } 20355 } 20356 } 20357 20358 private final static class OnPermissionChangeListeners extends Handler { 20359 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20360 20361 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20362 new RemoteCallbackList<>(); 20363 20364 public OnPermissionChangeListeners(Looper looper) { 20365 super(looper); 20366 } 20367 20368 @Override 20369 public void handleMessage(Message msg) { 20370 switch (msg.what) { 20371 case MSG_ON_PERMISSIONS_CHANGED: { 20372 final int uid = msg.arg1; 20373 handleOnPermissionsChanged(uid); 20374 } break; 20375 } 20376 } 20377 20378 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20379 mPermissionListeners.register(listener); 20380 20381 } 20382 20383 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20384 mPermissionListeners.unregister(listener); 20385 } 20386 20387 public void onPermissionsChanged(int uid) { 20388 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20389 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20390 } 20391 } 20392 20393 private void handleOnPermissionsChanged(int uid) { 20394 final int count = mPermissionListeners.beginBroadcast(); 20395 try { 20396 for (int i = 0; i < count; i++) { 20397 IOnPermissionsChangeListener callback = mPermissionListeners 20398 .getBroadcastItem(i); 20399 try { 20400 callback.onPermissionsChanged(uid); 20401 } catch (RemoteException e) { 20402 Log.e(TAG, "Permission listener is dead", e); 20403 } 20404 } 20405 } finally { 20406 mPermissionListeners.finishBroadcast(); 20407 } 20408 } 20409 } 20410 20411 private class PackageManagerInternalImpl extends PackageManagerInternal { 20412 @Override 20413 public void setLocationPackagesProvider(PackagesProvider provider) { 20414 synchronized (mPackages) { 20415 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20416 } 20417 } 20418 20419 @Override 20420 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20421 synchronized (mPackages) { 20422 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20423 } 20424 } 20425 20426 @Override 20427 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20428 synchronized (mPackages) { 20429 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20430 } 20431 } 20432 20433 @Override 20434 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20435 synchronized (mPackages) { 20436 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20437 } 20438 } 20439 20440 @Override 20441 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20442 synchronized (mPackages) { 20443 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20444 } 20445 } 20446 20447 @Override 20448 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20449 synchronized (mPackages) { 20450 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20451 } 20452 } 20453 20454 @Override 20455 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20456 synchronized (mPackages) { 20457 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20458 packageName, userId); 20459 } 20460 } 20461 20462 @Override 20463 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20464 synchronized (mPackages) { 20465 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20466 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20467 packageName, userId); 20468 } 20469 } 20470 20471 @Override 20472 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20473 synchronized (mPackages) { 20474 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20475 packageName, userId); 20476 } 20477 } 20478 20479 @Override 20480 public void setKeepUninstalledPackages(final List<String> packageList) { 20481 Preconditions.checkNotNull(packageList); 20482 List<String> removedFromList = null; 20483 synchronized (mPackages) { 20484 if (mKeepUninstalledPackages != null) { 20485 final int packagesCount = mKeepUninstalledPackages.size(); 20486 for (int i = 0; i < packagesCount; i++) { 20487 String oldPackage = mKeepUninstalledPackages.get(i); 20488 if (packageList != null && packageList.contains(oldPackage)) { 20489 continue; 20490 } 20491 if (removedFromList == null) { 20492 removedFromList = new ArrayList<>(); 20493 } 20494 removedFromList.add(oldPackage); 20495 } 20496 } 20497 mKeepUninstalledPackages = new ArrayList<>(packageList); 20498 if (removedFromList != null) { 20499 final int removedCount = removedFromList.size(); 20500 for (int i = 0; i < removedCount; i++) { 20501 deletePackageIfUnusedLPr(removedFromList.get(i)); 20502 } 20503 } 20504 } 20505 } 20506 20507 @Override 20508 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20509 synchronized (mPackages) { 20510 // If we do not support permission review, done. 20511 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20512 return false; 20513 } 20514 20515 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20516 if (packageSetting == null) { 20517 return false; 20518 } 20519 20520 // Permission review applies only to apps not supporting the new permission model. 20521 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20522 return false; 20523 } 20524 20525 // Legacy apps have the permission and get user consent on launch. 20526 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20527 return permissionsState.isPermissionReviewRequired(userId); 20528 } 20529 } 20530 20531 @Override 20532 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20533 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20534 } 20535 20536 @Override 20537 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20538 int userId) { 20539 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20540 } 20541 } 20542 20543 @Override 20544 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20545 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20546 synchronized (mPackages) { 20547 final long identity = Binder.clearCallingIdentity(); 20548 try { 20549 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20550 packageNames, userId); 20551 } finally { 20552 Binder.restoreCallingIdentity(identity); 20553 } 20554 } 20555 } 20556 20557 private static void enforceSystemOrPhoneCaller(String tag) { 20558 int callingUid = Binder.getCallingUid(); 20559 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20560 throw new SecurityException( 20561 "Cannot call " + tag + " from UID " + callingUid); 20562 } 20563 } 20564 20565 boolean isHistoricalPackageUsageAvailable() { 20566 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20567 } 20568 20569 /** 20570 * Return a <b>copy</b> of the collection of packages known to the package manager. 20571 * @return A copy of the values of mPackages. 20572 */ 20573 Collection<PackageParser.Package> getPackages() { 20574 synchronized (mPackages) { 20575 return new ArrayList<>(mPackages.values()); 20576 } 20577 } 20578 20579 /** 20580 * Logs process start information (including base APK hash) to the security log. 20581 * @hide 20582 */ 20583 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20584 String apkFile, int pid) { 20585 if (!SecurityLog.isLoggingEnabled()) { 20586 return; 20587 } 20588 Bundle data = new Bundle(); 20589 data.putLong("startTimestamp", System.currentTimeMillis()); 20590 data.putString("processName", processName); 20591 data.putInt("uid", uid); 20592 data.putString("seinfo", seinfo); 20593 data.putString("apkFile", apkFile); 20594 data.putInt("pid", pid); 20595 Message msg = mProcessLoggingHandler.obtainMessage( 20596 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20597 msg.setData(data); 20598 mProcessLoggingHandler.sendMessage(msg); 20599 } 20600} 20601