PackageManagerService.java revision 966210b7218a99f57d7e9b40f7d2c0ff69151776
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.INetworkPolicyManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.util.jar.StrictJarFile; 221import android.view.Display; 222 223import com.android.internal.R; 224import com.android.internal.annotations.GuardedBy; 225import com.android.internal.app.IMediaContainerService; 226import com.android.internal.app.ResolverActivity; 227import com.android.internal.content.NativeLibraryHelper; 228import com.android.internal.content.PackageHelper; 229import com.android.internal.logging.MetricsLogger; 230import com.android.internal.os.IParcelFileDescriptorFactory; 231import com.android.internal.os.InstallerConnection.InstallerException; 232import com.android.internal.os.SomeArgs; 233import com.android.internal.os.Zygote; 234import com.android.internal.telephony.CarrierAppUtils; 235import com.android.internal.util.ArrayUtils; 236import com.android.internal.util.FastPrintWriter; 237import com.android.internal.util.FastXmlSerializer; 238import com.android.internal.util.IndentingPrintWriter; 239import com.android.internal.util.Preconditions; 240import com.android.internal.util.XmlUtils; 241import com.android.server.EventLogTags; 242import com.android.server.FgThread; 243import com.android.server.IntentResolver; 244import com.android.server.LocalServices; 245import com.android.server.ServiceThread; 246import com.android.server.SystemConfig; 247import com.android.server.Watchdog; 248import com.android.server.net.NetworkPolicyManagerInternal; 249import com.android.server.pm.PermissionsState.PermissionState; 250import com.android.server.pm.Settings.DatabaseVersion; 251import com.android.server.pm.Settings.VersionInfo; 252import com.android.server.storage.DeviceStorageMonitorInternal; 253 254import dalvik.system.CloseGuard; 255import dalvik.system.DexFile; 256import dalvik.system.VMRuntime; 257 258import libcore.io.IoUtils; 259import libcore.util.EmptyArray; 260 261import org.xmlpull.v1.XmlPullParser; 262import org.xmlpull.v1.XmlPullParserException; 263import org.xmlpull.v1.XmlSerializer; 264 265import java.io.BufferedInputStream; 266import java.io.BufferedOutputStream; 267import java.io.BufferedReader; 268import java.io.ByteArrayInputStream; 269import java.io.ByteArrayOutputStream; 270import java.io.File; 271import java.io.FileDescriptor; 272import java.io.FileInputStream; 273import java.io.FileNotFoundException; 274import java.io.FileOutputStream; 275import java.io.FileReader; 276import java.io.FilenameFilter; 277import java.io.IOException; 278import java.io.InputStream; 279import java.io.PrintWriter; 280import java.nio.charset.StandardCharsets; 281import java.security.DigestInputStream; 282import java.security.MessageDigest; 283import java.security.NoSuchAlgorithmException; 284import java.security.PublicKey; 285import java.security.cert.Certificate; 286import java.security.cert.CertificateEncodingException; 287import java.security.cert.CertificateException; 288import java.text.SimpleDateFormat; 289import java.util.ArrayList; 290import java.util.Arrays; 291import java.util.Collection; 292import java.util.Collections; 293import java.util.Comparator; 294import java.util.Date; 295import java.util.HashSet; 296import java.util.Iterator; 297import java.util.List; 298import java.util.Map; 299import java.util.Objects; 300import java.util.Set; 301import java.util.concurrent.CountDownLatch; 302import java.util.concurrent.TimeUnit; 303import java.util.concurrent.atomic.AtomicBoolean; 304import java.util.concurrent.atomic.AtomicInteger; 305import java.util.concurrent.atomic.AtomicLong; 306 307/** 308 * Keep track of all those APKs everywhere. 309 * <p> 310 * Internally there are two important locks: 311 * <ul> 312 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 313 * and other related state. It is a fine-grained lock that should only be held 314 * momentarily, as it's one of the most contended locks in the system. 315 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 316 * operations typically involve heavy lifting of application data on disk. Since 317 * {@code installd} is single-threaded, and it's operations can often be slow, 318 * this lock should never be acquired while already holding {@link #mPackages}. 319 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 320 * holding {@link #mInstallLock}. 321 * </ul> 322 * Many internal methods rely on the caller to hold the appropriate locks, and 323 * this contract is expressed through method name suffixes: 324 * <ul> 325 * <li>fooLI(): the caller must hold {@link #mInstallLock} 326 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 327 * being modified must be frozen 328 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 329 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 330 * </ul> 331 * <p> 332 * Because this class is very central to the platform's security; please run all 333 * CTS and unit tests whenever making modifications: 334 * 335 * <pre> 336 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 337 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 338 * </pre> 339 */ 340public class PackageManagerService extends IPackageManager.Stub { 341 static final String TAG = "PackageManager"; 342 static final boolean DEBUG_SETTINGS = false; 343 static final boolean DEBUG_PREFERRED = false; 344 static final boolean DEBUG_UPGRADE = false; 345 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 346 private static final boolean DEBUG_BACKUP = false; 347 private static final boolean DEBUG_INSTALL = false; 348 private static final boolean DEBUG_REMOVE = false; 349 private static final boolean DEBUG_BROADCASTS = false; 350 private static final boolean DEBUG_SHOW_INFO = false; 351 private static final boolean DEBUG_PACKAGE_INFO = false; 352 private static final boolean DEBUG_INTENT_MATCHING = false; 353 private static final boolean DEBUG_PACKAGE_SCANNING = false; 354 private static final boolean DEBUG_VERIFY = false; 355 private static final boolean DEBUG_FILTERS = false; 356 357 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 358 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 359 // user, but by default initialize to this. 360 static final boolean DEBUG_DEXOPT = false; 361 362 private static final boolean DEBUG_ABI_SELECTION = false; 363 private static final boolean DEBUG_EPHEMERAL = false; 364 private static final boolean DEBUG_TRIAGED_MISSING = false; 365 private static final boolean DEBUG_APP_DATA = false; 366 367 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 368 369 private static final boolean DISABLE_EPHEMERAL_APPS = true; 370 371 private static final int RADIO_UID = Process.PHONE_UID; 372 private static final int LOG_UID = Process.LOG_UID; 373 private static final int NFC_UID = Process.NFC_UID; 374 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 375 private static final int SHELL_UID = Process.SHELL_UID; 376 377 // Cap the size of permission trees that 3rd party apps can define 378 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 379 380 // Suffix used during package installation when copying/moving 381 // package apks to install directory. 382 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 383 384 static final int SCAN_NO_DEX = 1<<1; 385 static final int SCAN_FORCE_DEX = 1<<2; 386 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 387 static final int SCAN_NEW_INSTALL = 1<<4; 388 static final int SCAN_NO_PATHS = 1<<5; 389 static final int SCAN_UPDATE_TIME = 1<<6; 390 static final int SCAN_DEFER_DEX = 1<<7; 391 static final int SCAN_BOOTING = 1<<8; 392 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 393 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 394 static final int SCAN_REPLACING = 1<<11; 395 static final int SCAN_REQUIRE_KNOWN = 1<<12; 396 static final int SCAN_MOVE = 1<<13; 397 static final int SCAN_INITIAL = 1<<14; 398 static final int SCAN_CHECK_ONLY = 1<<15; 399 static final int SCAN_DONT_KILL_APP = 1<<17; 400 static final int SCAN_IGNORE_FROZEN = 1<<18; 401 402 static final int REMOVE_CHATTY = 1<<16; 403 404 private static final int[] EMPTY_INT_ARRAY = new int[0]; 405 406 /** 407 * Timeout (in milliseconds) after which the watchdog should declare that 408 * our handler thread is wedged. The usual default for such things is one 409 * minute but we sometimes do very lengthy I/O operations on this thread, 410 * such as installing multi-gigabyte applications, so ours needs to be longer. 411 */ 412 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 413 414 /** 415 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 416 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 417 * settings entry if available, otherwise we use the hardcoded default. If it's been 418 * more than this long since the last fstrim, we force one during the boot sequence. 419 * 420 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 421 * one gets run at the next available charging+idle time. This final mandatory 422 * no-fstrim check kicks in only of the other scheduling criteria is never met. 423 */ 424 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 425 426 /** 427 * Whether verification is enabled by default. 428 */ 429 private static final boolean DEFAULT_VERIFY_ENABLE = true; 430 431 /** 432 * The default maximum time to wait for the verification agent to return in 433 * milliseconds. 434 */ 435 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 436 437 /** 438 * The default response for package verification timeout. 439 * 440 * This can be either PackageManager.VERIFICATION_ALLOW or 441 * PackageManager.VERIFICATION_REJECT. 442 */ 443 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 444 445 static final String PLATFORM_PACKAGE_NAME = "android"; 446 447 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 448 449 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 450 DEFAULT_CONTAINER_PACKAGE, 451 "com.android.defcontainer.DefaultContainerService"); 452 453 private static final String KILL_APP_REASON_GIDS_CHANGED = 454 "permission grant or revoke changed gids"; 455 456 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 457 "permissions revoked"; 458 459 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 460 461 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 462 463 /** Permission grant: not grant the permission. */ 464 private static final int GRANT_DENIED = 1; 465 466 /** Permission grant: grant the permission as an install permission. */ 467 private static final int GRANT_INSTALL = 2; 468 469 /** Permission grant: grant the permission as a runtime one. */ 470 private static final int GRANT_RUNTIME = 3; 471 472 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 473 private static final int GRANT_UPGRADE = 4; 474 475 /** Canonical intent used to identify what counts as a "web browser" app */ 476 private static final Intent sBrowserIntent; 477 static { 478 sBrowserIntent = new Intent(); 479 sBrowserIntent.setAction(Intent.ACTION_VIEW); 480 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 481 sBrowserIntent.setData(Uri.parse("http:")); 482 } 483 484 /** 485 * The set of all protected actions [i.e. those actions for which a high priority 486 * intent filter is disallowed]. 487 */ 488 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 489 static { 490 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 491 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 492 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 493 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 494 } 495 496 // Compilation reasons. 497 public static final int REASON_FIRST_BOOT = 0; 498 public static final int REASON_BOOT = 1; 499 public static final int REASON_INSTALL = 2; 500 public static final int REASON_BACKGROUND_DEXOPT = 3; 501 public static final int REASON_AB_OTA = 4; 502 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 503 public static final int REASON_SHARED_APK = 6; 504 public static final int REASON_FORCED_DEXOPT = 7; 505 506 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 507 508 /** Special library name that skips shared libraries check during compilation. */ 509 private static final String SKIP_SHARED_LIBRARY_CHECK = "&"; 510 511 final ServiceThread mHandlerThread; 512 513 final PackageHandler mHandler; 514 515 private final ProcessLoggingHandler mProcessLoggingHandler; 516 517 /** 518 * Messages for {@link #mHandler} that need to wait for system ready before 519 * being dispatched. 520 */ 521 private ArrayList<Message> mPostSystemReadyMessages; 522 523 final int mSdkVersion = Build.VERSION.SDK_INT; 524 525 final Context mContext; 526 final boolean mFactoryTest; 527 final boolean mOnlyCore; 528 final DisplayMetrics mMetrics; 529 final int mDefParseFlags; 530 final String[] mSeparateProcesses; 531 final boolean mIsUpgrade; 532 final boolean mIsPreNUpgrade; 533 534 /** The location for ASEC container files on internal storage. */ 535 final String mAsecInternalPath; 536 537 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 538 // LOCK HELD. Can be called with mInstallLock held. 539 @GuardedBy("mInstallLock") 540 final Installer mInstaller; 541 542 /** Directory where installed third-party apps stored */ 543 final File mAppInstallDir; 544 final File mEphemeralInstallDir; 545 546 /** 547 * Directory to which applications installed internally have their 548 * 32 bit native libraries copied. 549 */ 550 private File mAppLib32InstallDir; 551 552 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 553 // apps. 554 final File mDrmAppPrivateInstallDir; 555 556 // ---------------------------------------------------------------- 557 558 // Lock for state used when installing and doing other long running 559 // operations. Methods that must be called with this lock held have 560 // the suffix "LI". 561 final Object mInstallLock = new Object(); 562 563 // ---------------------------------------------------------------- 564 565 // Keys are String (package name), values are Package. This also serves 566 // as the lock for the global state. Methods that must be called with 567 // this lock held have the prefix "LP". 568 @GuardedBy("mPackages") 569 final ArrayMap<String, PackageParser.Package> mPackages = 570 new ArrayMap<String, PackageParser.Package>(); 571 572 final ArrayMap<String, Set<String>> mKnownCodebase = 573 new ArrayMap<String, Set<String>>(); 574 575 // Tracks available target package names -> overlay package paths. 576 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 577 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 578 579 /** 580 * Tracks new system packages [received in an OTA] that we expect to 581 * find updated user-installed versions. Keys are package name, values 582 * are package location. 583 */ 584 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 585 /** 586 * Tracks high priority intent filters for protected actions. During boot, certain 587 * filter actions are protected and should never be allowed to have a high priority 588 * intent filter for them. However, there is one, and only one exception -- the 589 * setup wizard. It must be able to define a high priority intent filter for these 590 * actions to ensure there are no escapes from the wizard. We need to delay processing 591 * of these during boot as we need to look at all of the system packages in order 592 * to know which component is the setup wizard. 593 */ 594 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 595 /** 596 * Whether or not processing protected filters should be deferred. 597 */ 598 private boolean mDeferProtectedFilters = true; 599 600 /** 601 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 602 */ 603 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 604 /** 605 * Whether or not system app permissions should be promoted from install to runtime. 606 */ 607 boolean mPromoteSystemApps; 608 609 @GuardedBy("mPackages") 610 final Settings mSettings; 611 612 /** 613 * Set of package names that are currently "frozen", which means active 614 * surgery is being done on the code/data for that package. The platform 615 * will refuse to launch frozen packages to avoid race conditions. 616 * 617 * @see PackageFreezer 618 */ 619 @GuardedBy("mPackages") 620 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 621 622 boolean mRestoredSettings; 623 624 // System configuration read by SystemConfig. 625 final int[] mGlobalGids; 626 final SparseArray<ArraySet<String>> mSystemPermissions; 627 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 628 629 // If mac_permissions.xml was found for seinfo labeling. 630 boolean mFoundPolicyFile; 631 632 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 633 634 public static final class SharedLibraryEntry { 635 public final String path; 636 public final String apk; 637 638 SharedLibraryEntry(String _path, String _apk) { 639 path = _path; 640 apk = _apk; 641 } 642 } 643 644 // Currently known shared libraries. 645 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 646 new ArrayMap<String, SharedLibraryEntry>(); 647 648 // All available activities, for your resolving pleasure. 649 final ActivityIntentResolver mActivities = 650 new ActivityIntentResolver(); 651 652 // All available receivers, for your resolving pleasure. 653 final ActivityIntentResolver mReceivers = 654 new ActivityIntentResolver(); 655 656 // All available services, for your resolving pleasure. 657 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 658 659 // All available providers, for your resolving pleasure. 660 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 661 662 // Mapping from provider base names (first directory in content URI codePath) 663 // to the provider information. 664 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 665 new ArrayMap<String, PackageParser.Provider>(); 666 667 // Mapping from instrumentation class names to info about them. 668 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 669 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 670 671 // Mapping from permission names to info about them. 672 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 673 new ArrayMap<String, PackageParser.PermissionGroup>(); 674 675 // Packages whose data we have transfered into another package, thus 676 // should no longer exist. 677 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 678 679 // Broadcast actions that are only available to the system. 680 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 681 682 /** List of packages waiting for verification. */ 683 final SparseArray<PackageVerificationState> mPendingVerification 684 = new SparseArray<PackageVerificationState>(); 685 686 /** Set of packages associated with each app op permission. */ 687 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 688 689 final PackageInstallerService mInstallerService; 690 691 private final PackageDexOptimizer mPackageDexOptimizer; 692 693 private AtomicInteger mNextMoveId = new AtomicInteger(); 694 private final MoveCallbacks mMoveCallbacks; 695 696 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 697 698 // Cache of users who need badging. 699 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 700 701 /** Token for keys in mPendingVerification. */ 702 private int mPendingVerificationToken = 0; 703 704 volatile boolean mSystemReady; 705 volatile boolean mSafeMode; 706 volatile boolean mHasSystemUidErrors; 707 708 ApplicationInfo mAndroidApplication; 709 final ActivityInfo mResolveActivity = new ActivityInfo(); 710 final ResolveInfo mResolveInfo = new ResolveInfo(); 711 ComponentName mResolveComponentName; 712 PackageParser.Package mPlatformPackage; 713 ComponentName mCustomResolverComponentName; 714 715 boolean mResolverReplaced = false; 716 717 private final @Nullable ComponentName mIntentFilterVerifierComponent; 718 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 719 720 private int mIntentFilterVerificationToken = 0; 721 722 /** Component that knows whether or not an ephemeral application exists */ 723 final ComponentName mEphemeralResolverComponent; 724 /** The service connection to the ephemeral resolver */ 725 final EphemeralResolverConnection mEphemeralResolverConnection; 726 727 /** Component used to install ephemeral applications */ 728 final ComponentName mEphemeralInstallerComponent; 729 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 730 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 731 732 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 733 = new SparseArray<IntentFilterVerificationState>(); 734 735 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 736 new DefaultPermissionGrantPolicy(this); 737 738 // List of packages names to keep cached, even if they are uninstalled for all users 739 private List<String> mKeepUninstalledPackages; 740 741 private static class IFVerificationParams { 742 PackageParser.Package pkg; 743 boolean replacing; 744 int userId; 745 int verifierUid; 746 747 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 748 int _userId, int _verifierUid) { 749 pkg = _pkg; 750 replacing = _replacing; 751 userId = _userId; 752 replacing = _replacing; 753 verifierUid = _verifierUid; 754 } 755 } 756 757 private interface IntentFilterVerifier<T extends IntentFilter> { 758 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 759 T filter, String packageName); 760 void startVerifications(int userId); 761 void receiveVerificationResponse(int verificationId); 762 } 763 764 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 765 private Context mContext; 766 private ComponentName mIntentFilterVerifierComponent; 767 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 768 769 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 770 mContext = context; 771 mIntentFilterVerifierComponent = verifierComponent; 772 } 773 774 private String getDefaultScheme() { 775 return IntentFilter.SCHEME_HTTPS; 776 } 777 778 @Override 779 public void startVerifications(int userId) { 780 // Launch verifications requests 781 int count = mCurrentIntentFilterVerifications.size(); 782 for (int n=0; n<count; n++) { 783 int verificationId = mCurrentIntentFilterVerifications.get(n); 784 final IntentFilterVerificationState ivs = 785 mIntentFilterVerificationStates.get(verificationId); 786 787 String packageName = ivs.getPackageName(); 788 789 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 790 final int filterCount = filters.size(); 791 ArraySet<String> domainsSet = new ArraySet<>(); 792 for (int m=0; m<filterCount; m++) { 793 PackageParser.ActivityIntentInfo filter = filters.get(m); 794 domainsSet.addAll(filter.getHostsList()); 795 } 796 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 797 synchronized (mPackages) { 798 if (mSettings.createIntentFilterVerificationIfNeededLPw( 799 packageName, domainsList) != null) { 800 scheduleWriteSettingsLocked(); 801 } 802 } 803 sendVerificationRequest(userId, verificationId, ivs); 804 } 805 mCurrentIntentFilterVerifications.clear(); 806 } 807 808 private void sendVerificationRequest(int userId, int verificationId, 809 IntentFilterVerificationState ivs) { 810 811 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 812 verificationIntent.putExtra( 813 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 814 verificationId); 815 verificationIntent.putExtra( 816 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 817 getDefaultScheme()); 818 verificationIntent.putExtra( 819 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 820 ivs.getHostsString()); 821 verificationIntent.putExtra( 822 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 823 ivs.getPackageName()); 824 verificationIntent.setComponent(mIntentFilterVerifierComponent); 825 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 826 827 UserHandle user = new UserHandle(userId); 828 mContext.sendBroadcastAsUser(verificationIntent, user); 829 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 830 "Sending IntentFilter verification broadcast"); 831 } 832 833 public void receiveVerificationResponse(int verificationId) { 834 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 835 836 final boolean verified = ivs.isVerified(); 837 838 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 839 final int count = filters.size(); 840 if (DEBUG_DOMAIN_VERIFICATION) { 841 Slog.i(TAG, "Received verification response " + verificationId 842 + " for " + count + " filters, verified=" + verified); 843 } 844 for (int n=0; n<count; n++) { 845 PackageParser.ActivityIntentInfo filter = filters.get(n); 846 filter.setVerified(verified); 847 848 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 849 + " verified with result:" + verified + " and hosts:" 850 + ivs.getHostsString()); 851 } 852 853 mIntentFilterVerificationStates.remove(verificationId); 854 855 final String packageName = ivs.getPackageName(); 856 IntentFilterVerificationInfo ivi = null; 857 858 synchronized (mPackages) { 859 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 860 } 861 if (ivi == null) { 862 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 863 + verificationId + " packageName:" + packageName); 864 return; 865 } 866 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 867 "Updating IntentFilterVerificationInfo for package " + packageName 868 +" verificationId:" + verificationId); 869 870 synchronized (mPackages) { 871 if (verified) { 872 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 873 } else { 874 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 875 } 876 scheduleWriteSettingsLocked(); 877 878 final int userId = ivs.getUserId(); 879 if (userId != UserHandle.USER_ALL) { 880 final int userStatus = 881 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 882 883 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 884 boolean needUpdate = false; 885 886 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 887 // already been set by the User thru the Disambiguation dialog 888 switch (userStatus) { 889 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 890 if (verified) { 891 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 892 } else { 893 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 894 } 895 needUpdate = true; 896 break; 897 898 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 899 if (verified) { 900 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 901 needUpdate = true; 902 } 903 break; 904 905 default: 906 // Nothing to do 907 } 908 909 if (needUpdate) { 910 mSettings.updateIntentFilterVerificationStatusLPw( 911 packageName, updatedStatus, userId); 912 scheduleWritePackageRestrictionsLocked(userId); 913 } 914 } 915 } 916 } 917 918 @Override 919 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 920 ActivityIntentInfo filter, String packageName) { 921 if (!hasValidDomains(filter)) { 922 return false; 923 } 924 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 925 if (ivs == null) { 926 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 927 packageName); 928 } 929 if (DEBUG_DOMAIN_VERIFICATION) { 930 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 931 } 932 ivs.addFilter(filter); 933 return true; 934 } 935 936 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 937 int userId, int verificationId, String packageName) { 938 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 939 verifierUid, userId, packageName); 940 ivs.setPendingState(); 941 synchronized (mPackages) { 942 mIntentFilterVerificationStates.append(verificationId, ivs); 943 mCurrentIntentFilterVerifications.add(verificationId); 944 } 945 return ivs; 946 } 947 } 948 949 private static boolean hasValidDomains(ActivityIntentInfo filter) { 950 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 951 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 952 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 953 } 954 955 // Set of pending broadcasts for aggregating enable/disable of components. 956 static class PendingPackageBroadcasts { 957 // for each user id, a map of <package name -> components within that package> 958 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 959 960 public PendingPackageBroadcasts() { 961 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 962 } 963 964 public ArrayList<String> get(int userId, String packageName) { 965 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 966 return packages.get(packageName); 967 } 968 969 public void put(int userId, String packageName, ArrayList<String> components) { 970 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 971 packages.put(packageName, components); 972 } 973 974 public void remove(int userId, String packageName) { 975 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 976 if (packages != null) { 977 packages.remove(packageName); 978 } 979 } 980 981 public void remove(int userId) { 982 mUidMap.remove(userId); 983 } 984 985 public int userIdCount() { 986 return mUidMap.size(); 987 } 988 989 public int userIdAt(int n) { 990 return mUidMap.keyAt(n); 991 } 992 993 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 994 return mUidMap.get(userId); 995 } 996 997 public int size() { 998 // total number of pending broadcast entries across all userIds 999 int num = 0; 1000 for (int i = 0; i< mUidMap.size(); i++) { 1001 num += mUidMap.valueAt(i).size(); 1002 } 1003 return num; 1004 } 1005 1006 public void clear() { 1007 mUidMap.clear(); 1008 } 1009 1010 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1011 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1012 if (map == null) { 1013 map = new ArrayMap<String, ArrayList<String>>(); 1014 mUidMap.put(userId, map); 1015 } 1016 return map; 1017 } 1018 } 1019 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1020 1021 // Service Connection to remote media container service to copy 1022 // package uri's from external media onto secure containers 1023 // or internal storage. 1024 private IMediaContainerService mContainerService = null; 1025 1026 static final int SEND_PENDING_BROADCAST = 1; 1027 static final int MCS_BOUND = 3; 1028 static final int END_COPY = 4; 1029 static final int INIT_COPY = 5; 1030 static final int MCS_UNBIND = 6; 1031 static final int START_CLEANING_PACKAGE = 7; 1032 static final int FIND_INSTALL_LOC = 8; 1033 static final int POST_INSTALL = 9; 1034 static final int MCS_RECONNECT = 10; 1035 static final int MCS_GIVE_UP = 11; 1036 static final int UPDATED_MEDIA_STATUS = 12; 1037 static final int WRITE_SETTINGS = 13; 1038 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1039 static final int PACKAGE_VERIFIED = 15; 1040 static final int CHECK_PENDING_VERIFICATION = 16; 1041 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1042 static final int INTENT_FILTER_VERIFIED = 18; 1043 1044 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1045 1046 // Delay time in millisecs 1047 static final int BROADCAST_DELAY = 10 * 1000; 1048 1049 static UserManagerService sUserManager; 1050 1051 // Stores a list of users whose package restrictions file needs to be updated 1052 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1053 1054 final private DefaultContainerConnection mDefContainerConn = 1055 new DefaultContainerConnection(); 1056 class DefaultContainerConnection implements ServiceConnection { 1057 public void onServiceConnected(ComponentName name, IBinder service) { 1058 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1059 IMediaContainerService imcs = 1060 IMediaContainerService.Stub.asInterface(service); 1061 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1062 } 1063 1064 public void onServiceDisconnected(ComponentName name) { 1065 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1066 } 1067 } 1068 1069 // Recordkeeping of restore-after-install operations that are currently in flight 1070 // between the Package Manager and the Backup Manager 1071 static class PostInstallData { 1072 public InstallArgs args; 1073 public PackageInstalledInfo res; 1074 1075 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1076 args = _a; 1077 res = _r; 1078 } 1079 } 1080 1081 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1082 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1083 1084 // XML tags for backup/restore of various bits of state 1085 private static final String TAG_PREFERRED_BACKUP = "pa"; 1086 private static final String TAG_DEFAULT_APPS = "da"; 1087 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1088 1089 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1090 private static final String TAG_ALL_GRANTS = "rt-grants"; 1091 private static final String TAG_GRANT = "grant"; 1092 private static final String ATTR_PACKAGE_NAME = "pkg"; 1093 1094 private static final String TAG_PERMISSION = "perm"; 1095 private static final String ATTR_PERMISSION_NAME = "name"; 1096 private static final String ATTR_IS_GRANTED = "g"; 1097 private static final String ATTR_USER_SET = "set"; 1098 private static final String ATTR_USER_FIXED = "fixed"; 1099 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1100 1101 // System/policy permission grants are not backed up 1102 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1103 FLAG_PERMISSION_POLICY_FIXED 1104 | FLAG_PERMISSION_SYSTEM_FIXED 1105 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1106 1107 // And we back up these user-adjusted states 1108 private static final int USER_RUNTIME_GRANT_MASK = 1109 FLAG_PERMISSION_USER_SET 1110 | FLAG_PERMISSION_USER_FIXED 1111 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1112 1113 final @Nullable String mRequiredVerifierPackage; 1114 final @NonNull String mRequiredInstallerPackage; 1115 final @Nullable String mSetupWizardPackage; 1116 final @NonNull String mServicesSystemSharedLibraryPackageName; 1117 final @NonNull String mSharedSystemSharedLibraryPackageName; 1118 1119 private final PackageUsage mPackageUsage = new PackageUsage(); 1120 1121 private class PackageUsage { 1122 private static final int WRITE_INTERVAL 1123 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1124 1125 private final Object mFileLock = new Object(); 1126 private final AtomicLong mLastWritten = new AtomicLong(0); 1127 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1128 1129 private boolean mIsHistoricalPackageUsageAvailable = true; 1130 1131 boolean isHistoricalPackageUsageAvailable() { 1132 return mIsHistoricalPackageUsageAvailable; 1133 } 1134 1135 void write(boolean force) { 1136 if (force) { 1137 writeInternal(); 1138 return; 1139 } 1140 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1141 && !DEBUG_DEXOPT) { 1142 return; 1143 } 1144 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1145 new Thread("PackageUsage_DiskWriter") { 1146 @Override 1147 public void run() { 1148 try { 1149 writeInternal(); 1150 } finally { 1151 mBackgroundWriteRunning.set(false); 1152 } 1153 } 1154 }.start(); 1155 } 1156 } 1157 1158 private void writeInternal() { 1159 synchronized (mPackages) { 1160 synchronized (mFileLock) { 1161 AtomicFile file = getFile(); 1162 FileOutputStream f = null; 1163 try { 1164 f = file.startWrite(); 1165 BufferedOutputStream out = new BufferedOutputStream(f); 1166 FileUtils.setPermissions(file.getBaseFile().getPath(), 1167 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1168 StringBuilder sb = new StringBuilder(); 1169 1170 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1171 sb.append('\n'); 1172 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1173 1174 for (PackageParser.Package pkg : mPackages.values()) { 1175 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1176 continue; 1177 } 1178 sb.setLength(0); 1179 sb.append(pkg.packageName); 1180 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1181 sb.append(' '); 1182 sb.append(usageTimeInMillis); 1183 } 1184 sb.append('\n'); 1185 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1186 } 1187 out.flush(); 1188 file.finishWrite(f); 1189 } catch (IOException e) { 1190 if (f != null) { 1191 file.failWrite(f); 1192 } 1193 Log.e(TAG, "Failed to write package usage times", e); 1194 } 1195 } 1196 } 1197 mLastWritten.set(SystemClock.elapsedRealtime()); 1198 } 1199 1200 void readLP() { 1201 synchronized (mFileLock) { 1202 AtomicFile file = getFile(); 1203 BufferedInputStream in = null; 1204 try { 1205 in = new BufferedInputStream(file.openRead()); 1206 StringBuffer sb = new StringBuffer(); 1207 1208 String firstLine = readLine(in, sb); 1209 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1210 readVersion1LP(in, sb); 1211 } else { 1212 readVersion0LP(in, sb, firstLine); 1213 } 1214 } catch (FileNotFoundException expected) { 1215 mIsHistoricalPackageUsageAvailable = false; 1216 } catch (IOException e) { 1217 Log.w(TAG, "Failed to read package usage times", e); 1218 } finally { 1219 IoUtils.closeQuietly(in); 1220 } 1221 } 1222 mLastWritten.set(SystemClock.elapsedRealtime()); 1223 } 1224 1225 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1226 throws IOException { 1227 // Initial version of the file had no version number and stored one 1228 // package-timestamp pair per line. 1229 // Note that the first line has already been read from the InputStream. 1230 for (String line = firstLine; line != null; line = readLine(in, sb)) { 1231 String[] tokens = line.split(" "); 1232 if (tokens.length != 2) { 1233 throw new IOException("Failed to parse " + line + 1234 " as package-timestamp pair."); 1235 } 1236 1237 String packageName = tokens[0]; 1238 PackageParser.Package pkg = mPackages.get(packageName); 1239 if (pkg == null) { 1240 continue; 1241 } 1242 1243 long timestamp = parseAsLong(tokens[1]); 1244 for (int reason = 0; 1245 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1246 reason++) { 1247 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1248 } 1249 } 1250 } 1251 1252 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1253 // Version 1 of the file started with the corresponding version 1254 // number and then stored a package name and eight timestamps per line. 1255 String line; 1256 while ((line = readLine(in, sb)) != null) { 1257 String[] tokens = line.split(" "); 1258 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1259 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1260 } 1261 1262 String packageName = tokens[0]; 1263 PackageParser.Package pkg = mPackages.get(packageName); 1264 if (pkg == null) { 1265 continue; 1266 } 1267 1268 for (int reason = 0; 1269 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1270 reason++) { 1271 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1272 } 1273 } 1274 } 1275 1276 private long parseAsLong(String token) throws IOException { 1277 try { 1278 return Long.parseLong(token); 1279 } catch (NumberFormatException e) { 1280 throw new IOException("Failed to parse " + token + " as a long.", e); 1281 } 1282 } 1283 1284 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1285 return readToken(in, sb, '\n'); 1286 } 1287 1288 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1289 throws IOException { 1290 sb.setLength(0); 1291 while (true) { 1292 int ch = in.read(); 1293 if (ch == -1) { 1294 if (sb.length() == 0) { 1295 return null; 1296 } 1297 throw new IOException("Unexpected EOF"); 1298 } 1299 if (ch == endOfToken) { 1300 return sb.toString(); 1301 } 1302 sb.append((char)ch); 1303 } 1304 } 1305 1306 private AtomicFile getFile() { 1307 File dataDir = Environment.getDataDirectory(); 1308 File systemDir = new File(dataDir, "system"); 1309 File fname = new File(systemDir, "package-usage.list"); 1310 return new AtomicFile(fname); 1311 } 1312 1313 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1314 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1315 } 1316 1317 class PackageHandler extends Handler { 1318 private boolean mBound = false; 1319 final ArrayList<HandlerParams> mPendingInstalls = 1320 new ArrayList<HandlerParams>(); 1321 1322 private boolean connectToService() { 1323 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1324 " DefaultContainerService"); 1325 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1326 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1327 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1328 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1329 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1330 mBound = true; 1331 return true; 1332 } 1333 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1334 return false; 1335 } 1336 1337 private void disconnectService() { 1338 mContainerService = null; 1339 mBound = false; 1340 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1341 mContext.unbindService(mDefContainerConn); 1342 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1343 } 1344 1345 PackageHandler(Looper looper) { 1346 super(looper); 1347 } 1348 1349 public void handleMessage(Message msg) { 1350 try { 1351 doHandleMessage(msg); 1352 } finally { 1353 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1354 } 1355 } 1356 1357 void doHandleMessage(Message msg) { 1358 switch (msg.what) { 1359 case INIT_COPY: { 1360 HandlerParams params = (HandlerParams) msg.obj; 1361 int idx = mPendingInstalls.size(); 1362 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1363 // If a bind was already initiated we dont really 1364 // need to do anything. The pending install 1365 // will be processed later on. 1366 if (!mBound) { 1367 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1368 System.identityHashCode(mHandler)); 1369 // If this is the only one pending we might 1370 // have to bind to the service again. 1371 if (!connectToService()) { 1372 Slog.e(TAG, "Failed to bind to media container service"); 1373 params.serviceError(); 1374 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1375 System.identityHashCode(mHandler)); 1376 if (params.traceMethod != null) { 1377 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1378 params.traceCookie); 1379 } 1380 return; 1381 } else { 1382 // Once we bind to the service, the first 1383 // pending request will be processed. 1384 mPendingInstalls.add(idx, params); 1385 } 1386 } else { 1387 mPendingInstalls.add(idx, params); 1388 // Already bound to the service. Just make 1389 // sure we trigger off processing the first request. 1390 if (idx == 0) { 1391 mHandler.sendEmptyMessage(MCS_BOUND); 1392 } 1393 } 1394 break; 1395 } 1396 case MCS_BOUND: { 1397 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1398 if (msg.obj != null) { 1399 mContainerService = (IMediaContainerService) msg.obj; 1400 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1401 System.identityHashCode(mHandler)); 1402 } 1403 if (mContainerService == null) { 1404 if (!mBound) { 1405 // Something seriously wrong since we are not bound and we are not 1406 // waiting for connection. Bail out. 1407 Slog.e(TAG, "Cannot bind to media container service"); 1408 for (HandlerParams params : mPendingInstalls) { 1409 // Indicate service bind error 1410 params.serviceError(); 1411 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1412 System.identityHashCode(params)); 1413 if (params.traceMethod != null) { 1414 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1415 params.traceMethod, params.traceCookie); 1416 } 1417 return; 1418 } 1419 mPendingInstalls.clear(); 1420 } else { 1421 Slog.w(TAG, "Waiting to connect to media container service"); 1422 } 1423 } else if (mPendingInstalls.size() > 0) { 1424 HandlerParams params = mPendingInstalls.get(0); 1425 if (params != null) { 1426 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1427 System.identityHashCode(params)); 1428 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1429 if (params.startCopy()) { 1430 // We are done... look for more work or to 1431 // go idle. 1432 if (DEBUG_SD_INSTALL) Log.i(TAG, 1433 "Checking for more work or unbind..."); 1434 // Delete pending install 1435 if (mPendingInstalls.size() > 0) { 1436 mPendingInstalls.remove(0); 1437 } 1438 if (mPendingInstalls.size() == 0) { 1439 if (mBound) { 1440 if (DEBUG_SD_INSTALL) Log.i(TAG, 1441 "Posting delayed MCS_UNBIND"); 1442 removeMessages(MCS_UNBIND); 1443 Message ubmsg = obtainMessage(MCS_UNBIND); 1444 // Unbind after a little delay, to avoid 1445 // continual thrashing. 1446 sendMessageDelayed(ubmsg, 10000); 1447 } 1448 } else { 1449 // There are more pending requests in queue. 1450 // Just post MCS_BOUND message to trigger processing 1451 // of next pending install. 1452 if (DEBUG_SD_INSTALL) Log.i(TAG, 1453 "Posting MCS_BOUND for next work"); 1454 mHandler.sendEmptyMessage(MCS_BOUND); 1455 } 1456 } 1457 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1458 } 1459 } else { 1460 // Should never happen ideally. 1461 Slog.w(TAG, "Empty queue"); 1462 } 1463 break; 1464 } 1465 case MCS_RECONNECT: { 1466 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1467 if (mPendingInstalls.size() > 0) { 1468 if (mBound) { 1469 disconnectService(); 1470 } 1471 if (!connectToService()) { 1472 Slog.e(TAG, "Failed to bind to media container service"); 1473 for (HandlerParams params : mPendingInstalls) { 1474 // Indicate service bind error 1475 params.serviceError(); 1476 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1477 System.identityHashCode(params)); 1478 } 1479 mPendingInstalls.clear(); 1480 } 1481 } 1482 break; 1483 } 1484 case MCS_UNBIND: { 1485 // If there is no actual work left, then time to unbind. 1486 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1487 1488 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1489 if (mBound) { 1490 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1491 1492 disconnectService(); 1493 } 1494 } else if (mPendingInstalls.size() > 0) { 1495 // There are more pending requests in queue. 1496 // Just post MCS_BOUND message to trigger processing 1497 // of next pending install. 1498 mHandler.sendEmptyMessage(MCS_BOUND); 1499 } 1500 1501 break; 1502 } 1503 case MCS_GIVE_UP: { 1504 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1505 HandlerParams params = mPendingInstalls.remove(0); 1506 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1507 System.identityHashCode(params)); 1508 break; 1509 } 1510 case SEND_PENDING_BROADCAST: { 1511 String packages[]; 1512 ArrayList<String> components[]; 1513 int size = 0; 1514 int uids[]; 1515 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1516 synchronized (mPackages) { 1517 if (mPendingBroadcasts == null) { 1518 return; 1519 } 1520 size = mPendingBroadcasts.size(); 1521 if (size <= 0) { 1522 // Nothing to be done. Just return 1523 return; 1524 } 1525 packages = new String[size]; 1526 components = new ArrayList[size]; 1527 uids = new int[size]; 1528 int i = 0; // filling out the above arrays 1529 1530 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1531 int packageUserId = mPendingBroadcasts.userIdAt(n); 1532 Iterator<Map.Entry<String, ArrayList<String>>> it 1533 = mPendingBroadcasts.packagesForUserId(packageUserId) 1534 .entrySet().iterator(); 1535 while (it.hasNext() && i < size) { 1536 Map.Entry<String, ArrayList<String>> ent = it.next(); 1537 packages[i] = ent.getKey(); 1538 components[i] = ent.getValue(); 1539 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1540 uids[i] = (ps != null) 1541 ? UserHandle.getUid(packageUserId, ps.appId) 1542 : -1; 1543 i++; 1544 } 1545 } 1546 size = i; 1547 mPendingBroadcasts.clear(); 1548 } 1549 // Send broadcasts 1550 for (int i = 0; i < size; i++) { 1551 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1552 } 1553 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1554 break; 1555 } 1556 case START_CLEANING_PACKAGE: { 1557 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1558 final String packageName = (String)msg.obj; 1559 final int userId = msg.arg1; 1560 final boolean andCode = msg.arg2 != 0; 1561 synchronized (mPackages) { 1562 if (userId == UserHandle.USER_ALL) { 1563 int[] users = sUserManager.getUserIds(); 1564 for (int user : users) { 1565 mSettings.addPackageToCleanLPw( 1566 new PackageCleanItem(user, packageName, andCode)); 1567 } 1568 } else { 1569 mSettings.addPackageToCleanLPw( 1570 new PackageCleanItem(userId, packageName, andCode)); 1571 } 1572 } 1573 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1574 startCleaningPackages(); 1575 } break; 1576 case POST_INSTALL: { 1577 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1578 1579 PostInstallData data = mRunningInstalls.get(msg.arg1); 1580 final boolean didRestore = (msg.arg2 != 0); 1581 mRunningInstalls.delete(msg.arg1); 1582 1583 if (data != null) { 1584 InstallArgs args = data.args; 1585 PackageInstalledInfo parentRes = data.res; 1586 1587 final boolean grantPermissions = (args.installFlags 1588 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1589 final boolean killApp = (args.installFlags 1590 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1591 final String[] grantedPermissions = args.installGrantPermissions; 1592 1593 // Handle the parent package 1594 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1595 grantedPermissions, didRestore, args.installerPackageName, 1596 args.observer); 1597 1598 // Handle the child packages 1599 final int childCount = (parentRes.addedChildPackages != null) 1600 ? parentRes.addedChildPackages.size() : 0; 1601 for (int i = 0; i < childCount; i++) { 1602 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1603 handlePackagePostInstall(childRes, grantPermissions, killApp, 1604 grantedPermissions, false, args.installerPackageName, 1605 args.observer); 1606 } 1607 1608 // Log tracing if needed 1609 if (args.traceMethod != null) { 1610 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1611 args.traceCookie); 1612 } 1613 } else { 1614 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1615 } 1616 1617 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1618 } break; 1619 case UPDATED_MEDIA_STATUS: { 1620 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1621 boolean reportStatus = msg.arg1 == 1; 1622 boolean doGc = msg.arg2 == 1; 1623 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1624 if (doGc) { 1625 // Force a gc to clear up stale containers. 1626 Runtime.getRuntime().gc(); 1627 } 1628 if (msg.obj != null) { 1629 @SuppressWarnings("unchecked") 1630 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1631 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1632 // Unload containers 1633 unloadAllContainers(args); 1634 } 1635 if (reportStatus) { 1636 try { 1637 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1638 PackageHelper.getMountService().finishMediaUpdate(); 1639 } catch (RemoteException e) { 1640 Log.e(TAG, "MountService not running?"); 1641 } 1642 } 1643 } break; 1644 case WRITE_SETTINGS: { 1645 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1646 synchronized (mPackages) { 1647 removeMessages(WRITE_SETTINGS); 1648 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1649 mSettings.writeLPr(); 1650 mDirtyUsers.clear(); 1651 } 1652 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1653 } break; 1654 case WRITE_PACKAGE_RESTRICTIONS: { 1655 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1656 synchronized (mPackages) { 1657 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1658 for (int userId : mDirtyUsers) { 1659 mSettings.writePackageRestrictionsLPr(userId); 1660 } 1661 mDirtyUsers.clear(); 1662 } 1663 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1664 } break; 1665 case CHECK_PENDING_VERIFICATION: { 1666 final int verificationId = msg.arg1; 1667 final PackageVerificationState state = mPendingVerification.get(verificationId); 1668 1669 if ((state != null) && !state.timeoutExtended()) { 1670 final InstallArgs args = state.getInstallArgs(); 1671 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1672 1673 Slog.i(TAG, "Verification timed out for " + originUri); 1674 mPendingVerification.remove(verificationId); 1675 1676 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1677 1678 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1679 Slog.i(TAG, "Continuing with installation of " + originUri); 1680 state.setVerifierResponse(Binder.getCallingUid(), 1681 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1682 broadcastPackageVerified(verificationId, originUri, 1683 PackageManager.VERIFICATION_ALLOW, 1684 state.getInstallArgs().getUser()); 1685 try { 1686 ret = args.copyApk(mContainerService, true); 1687 } catch (RemoteException e) { 1688 Slog.e(TAG, "Could not contact the ContainerService"); 1689 } 1690 } else { 1691 broadcastPackageVerified(verificationId, originUri, 1692 PackageManager.VERIFICATION_REJECT, 1693 state.getInstallArgs().getUser()); 1694 } 1695 1696 Trace.asyncTraceEnd( 1697 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1698 1699 processPendingInstall(args, ret); 1700 mHandler.sendEmptyMessage(MCS_UNBIND); 1701 } 1702 break; 1703 } 1704 case PACKAGE_VERIFIED: { 1705 final int verificationId = msg.arg1; 1706 1707 final PackageVerificationState state = mPendingVerification.get(verificationId); 1708 if (state == null) { 1709 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1710 break; 1711 } 1712 1713 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1714 1715 state.setVerifierResponse(response.callerUid, response.code); 1716 1717 if (state.isVerificationComplete()) { 1718 mPendingVerification.remove(verificationId); 1719 1720 final InstallArgs args = state.getInstallArgs(); 1721 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1722 1723 int ret; 1724 if (state.isInstallAllowed()) { 1725 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1726 broadcastPackageVerified(verificationId, originUri, 1727 response.code, state.getInstallArgs().getUser()); 1728 try { 1729 ret = args.copyApk(mContainerService, true); 1730 } catch (RemoteException e) { 1731 Slog.e(TAG, "Could not contact the ContainerService"); 1732 } 1733 } else { 1734 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1735 } 1736 1737 Trace.asyncTraceEnd( 1738 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1739 1740 processPendingInstall(args, ret); 1741 mHandler.sendEmptyMessage(MCS_UNBIND); 1742 } 1743 1744 break; 1745 } 1746 case START_INTENT_FILTER_VERIFICATIONS: { 1747 IFVerificationParams params = (IFVerificationParams) msg.obj; 1748 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1749 params.replacing, params.pkg); 1750 break; 1751 } 1752 case INTENT_FILTER_VERIFIED: { 1753 final int verificationId = msg.arg1; 1754 1755 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1756 verificationId); 1757 if (state == null) { 1758 Slog.w(TAG, "Invalid IntentFilter verification token " 1759 + verificationId + " received"); 1760 break; 1761 } 1762 1763 final int userId = state.getUserId(); 1764 1765 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1766 "Processing IntentFilter verification with token:" 1767 + verificationId + " and userId:" + userId); 1768 1769 final IntentFilterVerificationResponse response = 1770 (IntentFilterVerificationResponse) msg.obj; 1771 1772 state.setVerifierResponse(response.callerUid, response.code); 1773 1774 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1775 "IntentFilter verification with token:" + verificationId 1776 + " and userId:" + userId 1777 + " is settings verifier response with response code:" 1778 + response.code); 1779 1780 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1781 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1782 + response.getFailedDomainsString()); 1783 } 1784 1785 if (state.isVerificationComplete()) { 1786 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1787 } else { 1788 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1789 "IntentFilter verification with token:" + verificationId 1790 + " was not said to be complete"); 1791 } 1792 1793 break; 1794 } 1795 } 1796 } 1797 } 1798 1799 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1800 boolean killApp, String[] grantedPermissions, 1801 boolean launchedForRestore, String installerPackage, 1802 IPackageInstallObserver2 installObserver) { 1803 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1804 // Send the removed broadcasts 1805 if (res.removedInfo != null) { 1806 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1807 } 1808 1809 // Now that we successfully installed the package, grant runtime 1810 // permissions if requested before broadcasting the install. 1811 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1812 >= Build.VERSION_CODES.M) { 1813 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1814 } 1815 1816 final boolean update = res.removedInfo != null 1817 && res.removedInfo.removedPackage != null; 1818 1819 // If this is the first time we have child packages for a disabled privileged 1820 // app that had no children, we grant requested runtime permissions to the new 1821 // children if the parent on the system image had them already granted. 1822 if (res.pkg.parentPackage != null) { 1823 synchronized (mPackages) { 1824 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1825 } 1826 } 1827 1828 synchronized (mPackages) { 1829 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1830 } 1831 1832 final String packageName = res.pkg.applicationInfo.packageName; 1833 Bundle extras = new Bundle(1); 1834 extras.putInt(Intent.EXTRA_UID, res.uid); 1835 1836 // Determine the set of users who are adding this package for 1837 // the first time vs. those who are seeing an update. 1838 int[] firstUsers = EMPTY_INT_ARRAY; 1839 int[] updateUsers = EMPTY_INT_ARRAY; 1840 if (res.origUsers == null || res.origUsers.length == 0) { 1841 firstUsers = res.newUsers; 1842 } else { 1843 for (int newUser : res.newUsers) { 1844 boolean isNew = true; 1845 for (int origUser : res.origUsers) { 1846 if (origUser == newUser) { 1847 isNew = false; 1848 break; 1849 } 1850 } 1851 if (isNew) { 1852 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1853 } else { 1854 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1855 } 1856 } 1857 } 1858 1859 // Send installed broadcasts if the install/update is not ephemeral 1860 if (!isEphemeral(res.pkg)) { 1861 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1862 1863 // Send added for users that see the package for the first time 1864 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1865 extras, 0 /*flags*/, null /*targetPackage*/, 1866 null /*finishedReceiver*/, firstUsers); 1867 1868 // Send added for users that don't see the package for the first time 1869 if (update) { 1870 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1871 } 1872 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1873 extras, 0 /*flags*/, null /*targetPackage*/, 1874 null /*finishedReceiver*/, updateUsers); 1875 1876 // Send replaced for users that don't see the package for the first time 1877 if (update) { 1878 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1879 packageName, extras, 0 /*flags*/, 1880 null /*targetPackage*/, null /*finishedReceiver*/, 1881 updateUsers); 1882 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1883 null /*package*/, null /*extras*/, 0 /*flags*/, 1884 packageName /*targetPackage*/, 1885 null /*finishedReceiver*/, updateUsers); 1886 } else if (launchedForRestore && !isSystemApp(res.pkg)) { 1887 // First-install and we did a restore, so we're responsible for the 1888 // first-launch broadcast. 1889 if (DEBUG_BACKUP) { 1890 Slog.i(TAG, "Post-restore of " + packageName 1891 + " sending FIRST_LAUNCH in " + Arrays.toString(firstUsers)); 1892 } 1893 sendFirstLaunchBroadcast(packageName, installerPackage, firstUsers); 1894 } 1895 1896 // Send broadcast package appeared if forward locked/external for all users 1897 // treat asec-hosted packages like removable media on upgrade 1898 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1899 if (DEBUG_INSTALL) { 1900 Slog.i(TAG, "upgrading pkg " + res.pkg 1901 + " is ASEC-hosted -> AVAILABLE"); 1902 } 1903 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1904 ArrayList<String> pkgList = new ArrayList<>(1); 1905 pkgList.add(packageName); 1906 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1907 } 1908 } 1909 1910 // Work that needs to happen on first install within each user 1911 if (firstUsers != null && firstUsers.length > 0) { 1912 synchronized (mPackages) { 1913 for (int userId : firstUsers) { 1914 // If this app is a browser and it's newly-installed for some 1915 // users, clear any default-browser state in those users. The 1916 // app's nature doesn't depend on the user, so we can just check 1917 // its browser nature in any user and generalize. 1918 if (packageIsBrowser(packageName, userId)) { 1919 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1920 } 1921 1922 // We may also need to apply pending (restored) runtime 1923 // permission grants within these users. 1924 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1925 } 1926 } 1927 } 1928 1929 // Log current value of "unknown sources" setting 1930 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1931 getUnknownSourcesSettings()); 1932 1933 // Force a gc to clear up things 1934 Runtime.getRuntime().gc(); 1935 1936 // Remove the replaced package's older resources safely now 1937 // We delete after a gc for applications on sdcard. 1938 if (res.removedInfo != null && res.removedInfo.args != null) { 1939 synchronized (mInstallLock) { 1940 res.removedInfo.args.doPostDeleteLI(true); 1941 } 1942 } 1943 } 1944 1945 // If someone is watching installs - notify them 1946 if (installObserver != null) { 1947 try { 1948 Bundle extras = extrasForInstallResult(res); 1949 installObserver.onPackageInstalled(res.name, res.returnCode, 1950 res.returnMsg, extras); 1951 } catch (RemoteException e) { 1952 Slog.i(TAG, "Observer no longer exists."); 1953 } 1954 } 1955 } 1956 1957 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1958 PackageParser.Package pkg) { 1959 if (pkg.parentPackage == null) { 1960 return; 1961 } 1962 if (pkg.requestedPermissions == null) { 1963 return; 1964 } 1965 final PackageSetting disabledSysParentPs = mSettings 1966 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1967 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1968 || !disabledSysParentPs.isPrivileged() 1969 || (disabledSysParentPs.childPackageNames != null 1970 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1971 return; 1972 } 1973 final int[] allUserIds = sUserManager.getUserIds(); 1974 final int permCount = pkg.requestedPermissions.size(); 1975 for (int i = 0; i < permCount; i++) { 1976 String permission = pkg.requestedPermissions.get(i); 1977 BasePermission bp = mSettings.mPermissions.get(permission); 1978 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1979 continue; 1980 } 1981 for (int userId : allUserIds) { 1982 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1983 permission, userId)) { 1984 grantRuntimePermission(pkg.packageName, permission, userId); 1985 } 1986 } 1987 } 1988 } 1989 1990 private StorageEventListener mStorageListener = new StorageEventListener() { 1991 @Override 1992 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1993 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1994 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1995 final String volumeUuid = vol.getFsUuid(); 1996 1997 // Clean up any users or apps that were removed or recreated 1998 // while this volume was missing 1999 reconcileUsers(volumeUuid); 2000 reconcileApps(volumeUuid); 2001 2002 // Clean up any install sessions that expired or were 2003 // cancelled while this volume was missing 2004 mInstallerService.onPrivateVolumeMounted(volumeUuid); 2005 2006 loadPrivatePackages(vol); 2007 2008 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2009 unloadPrivatePackages(vol); 2010 } 2011 } 2012 2013 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 2014 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2015 updateExternalMediaStatus(true, false); 2016 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2017 updateExternalMediaStatus(false, false); 2018 } 2019 } 2020 } 2021 2022 @Override 2023 public void onVolumeForgotten(String fsUuid) { 2024 if (TextUtils.isEmpty(fsUuid)) { 2025 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2026 return; 2027 } 2028 2029 // Remove any apps installed on the forgotten volume 2030 synchronized (mPackages) { 2031 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2032 for (PackageSetting ps : packages) { 2033 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2034 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2035 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2036 } 2037 2038 mSettings.onVolumeForgotten(fsUuid); 2039 mSettings.writeLPr(); 2040 } 2041 } 2042 }; 2043 2044 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2045 String[] grantedPermissions) { 2046 for (int userId : userIds) { 2047 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2048 } 2049 2050 // We could have touched GID membership, so flush out packages.list 2051 synchronized (mPackages) { 2052 mSettings.writePackageListLPr(); 2053 } 2054 } 2055 2056 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2057 String[] grantedPermissions) { 2058 SettingBase sb = (SettingBase) pkg.mExtras; 2059 if (sb == null) { 2060 return; 2061 } 2062 2063 PermissionsState permissionsState = sb.getPermissionsState(); 2064 2065 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2066 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2067 2068 for (String permission : pkg.requestedPermissions) { 2069 final BasePermission bp; 2070 synchronized (mPackages) { 2071 bp = mSettings.mPermissions.get(permission); 2072 } 2073 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2074 && (grantedPermissions == null 2075 || ArrayUtils.contains(grantedPermissions, permission))) { 2076 final int flags = permissionsState.getPermissionFlags(permission, userId); 2077 // Installer cannot change immutable permissions. 2078 if ((flags & immutableFlags) == 0) { 2079 grantRuntimePermission(pkg.packageName, permission, userId); 2080 } 2081 } 2082 } 2083 } 2084 2085 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2086 Bundle extras = null; 2087 switch (res.returnCode) { 2088 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2089 extras = new Bundle(); 2090 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2091 res.origPermission); 2092 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2093 res.origPackage); 2094 break; 2095 } 2096 case PackageManager.INSTALL_SUCCEEDED: { 2097 extras = new Bundle(); 2098 extras.putBoolean(Intent.EXTRA_REPLACING, 2099 res.removedInfo != null && res.removedInfo.removedPackage != null); 2100 break; 2101 } 2102 } 2103 return extras; 2104 } 2105 2106 void scheduleWriteSettingsLocked() { 2107 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2108 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2109 } 2110 } 2111 2112 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2113 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2114 scheduleWritePackageRestrictionsLocked(userId); 2115 } 2116 2117 void scheduleWritePackageRestrictionsLocked(int userId) { 2118 final int[] userIds = (userId == UserHandle.USER_ALL) 2119 ? sUserManager.getUserIds() : new int[]{userId}; 2120 for (int nextUserId : userIds) { 2121 if (!sUserManager.exists(nextUserId)) return; 2122 mDirtyUsers.add(nextUserId); 2123 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2124 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2125 } 2126 } 2127 } 2128 2129 public static PackageManagerService main(Context context, Installer installer, 2130 boolean factoryTest, boolean onlyCore) { 2131 // Self-check for initial settings. 2132 PackageManagerServiceCompilerMapping.checkProperties(); 2133 2134 PackageManagerService m = new PackageManagerService(context, installer, 2135 factoryTest, onlyCore); 2136 m.enableSystemUserPackages(); 2137 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2138 // disabled after already being started. 2139 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2140 UserHandle.USER_SYSTEM); 2141 ServiceManager.addService("package", m); 2142 return m; 2143 } 2144 2145 private void enableSystemUserPackages() { 2146 if (!UserManager.isSplitSystemUser()) { 2147 return; 2148 } 2149 // For system user, enable apps based on the following conditions: 2150 // - app is whitelisted or belong to one of these groups: 2151 // -- system app which has no launcher icons 2152 // -- system app which has INTERACT_ACROSS_USERS permission 2153 // -- system IME app 2154 // - app is not in the blacklist 2155 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2156 Set<String> enableApps = new ArraySet<>(); 2157 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2158 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2159 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2160 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2161 enableApps.addAll(wlApps); 2162 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2163 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2164 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2165 enableApps.removeAll(blApps); 2166 Log.i(TAG, "Applications installed for system user: " + enableApps); 2167 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2168 UserHandle.SYSTEM); 2169 final int allAppsSize = allAps.size(); 2170 synchronized (mPackages) { 2171 for (int i = 0; i < allAppsSize; i++) { 2172 String pName = allAps.get(i); 2173 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2174 // Should not happen, but we shouldn't be failing if it does 2175 if (pkgSetting == null) { 2176 continue; 2177 } 2178 boolean install = enableApps.contains(pName); 2179 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2180 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2181 + " for system user"); 2182 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2183 } 2184 } 2185 } 2186 } 2187 2188 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2189 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2190 Context.DISPLAY_SERVICE); 2191 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2192 } 2193 2194 public PackageManagerService(Context context, Installer installer, 2195 boolean factoryTest, boolean onlyCore) { 2196 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2197 SystemClock.uptimeMillis()); 2198 2199 if (mSdkVersion <= 0) { 2200 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2201 } 2202 2203 mContext = context; 2204 mFactoryTest = factoryTest; 2205 mOnlyCore = onlyCore; 2206 mMetrics = new DisplayMetrics(); 2207 mSettings = new Settings(mPackages); 2208 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2209 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2210 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2211 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2212 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2213 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2214 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2215 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2216 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2217 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2218 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2219 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2220 2221 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2222 if (separateProcesses != null && separateProcesses.length() > 0) { 2223 if ("*".equals(separateProcesses)) { 2224 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2225 mSeparateProcesses = null; 2226 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2227 } else { 2228 mDefParseFlags = 0; 2229 mSeparateProcesses = separateProcesses.split(","); 2230 Slog.w(TAG, "Running with debug.separate_processes: " 2231 + separateProcesses); 2232 } 2233 } else { 2234 mDefParseFlags = 0; 2235 mSeparateProcesses = null; 2236 } 2237 2238 mInstaller = installer; 2239 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2240 "*dexopt*"); 2241 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2242 2243 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2244 FgThread.get().getLooper()); 2245 2246 getDefaultDisplayMetrics(context, mMetrics); 2247 2248 SystemConfig systemConfig = SystemConfig.getInstance(); 2249 mGlobalGids = systemConfig.getGlobalGids(); 2250 mSystemPermissions = systemConfig.getSystemPermissions(); 2251 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2252 2253 synchronized (mInstallLock) { 2254 // writer 2255 synchronized (mPackages) { 2256 mHandlerThread = new ServiceThread(TAG, 2257 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2258 mHandlerThread.start(); 2259 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2260 mProcessLoggingHandler = new ProcessLoggingHandler(); 2261 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2262 2263 File dataDir = Environment.getDataDirectory(); 2264 mAppInstallDir = new File(dataDir, "app"); 2265 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2266 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2267 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2268 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2269 2270 sUserManager = new UserManagerService(context, this, mPackages); 2271 2272 // Propagate permission configuration in to package manager. 2273 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2274 = systemConfig.getPermissions(); 2275 for (int i=0; i<permConfig.size(); i++) { 2276 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2277 BasePermission bp = mSettings.mPermissions.get(perm.name); 2278 if (bp == null) { 2279 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2280 mSettings.mPermissions.put(perm.name, bp); 2281 } 2282 if (perm.gids != null) { 2283 bp.setGids(perm.gids, perm.perUser); 2284 } 2285 } 2286 2287 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2288 for (int i=0; i<libConfig.size(); i++) { 2289 mSharedLibraries.put(libConfig.keyAt(i), 2290 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2291 } 2292 2293 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2294 2295 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2296 2297 String customResolverActivity = Resources.getSystem().getString( 2298 R.string.config_customResolverActivity); 2299 if (TextUtils.isEmpty(customResolverActivity)) { 2300 customResolverActivity = null; 2301 } else { 2302 mCustomResolverComponentName = ComponentName.unflattenFromString( 2303 customResolverActivity); 2304 } 2305 2306 long startTime = SystemClock.uptimeMillis(); 2307 2308 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2309 startTime); 2310 2311 // Set flag to monitor and not change apk file paths when 2312 // scanning install directories. 2313 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2314 2315 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2316 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2317 2318 if (bootClassPath == null) { 2319 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2320 } 2321 2322 if (systemServerClassPath == null) { 2323 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2324 } 2325 2326 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2327 final String[] dexCodeInstructionSets = 2328 getDexCodeInstructionSets( 2329 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2330 2331 /** 2332 * Ensure all external libraries have had dexopt run on them. 2333 */ 2334 if (mSharedLibraries.size() > 0) { 2335 // NOTE: For now, we're compiling these system "shared libraries" 2336 // (and framework jars) into all available architectures. It's possible 2337 // to compile them only when we come across an app that uses them (there's 2338 // already logic for that in scanPackageLI) but that adds some complexity. 2339 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2340 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2341 final String lib = libEntry.path; 2342 if (lib == null) { 2343 continue; 2344 } 2345 2346 try { 2347 // Shared libraries do not have profiles so we perform a full 2348 // AOT compilation (if needed). 2349 int dexoptNeeded = DexFile.getDexOptNeeded( 2350 lib, dexCodeInstructionSet, 2351 getCompilerFilterForReason(REASON_SHARED_APK), 2352 false /* newProfile */); 2353 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2354 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2355 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2356 getCompilerFilterForReason(REASON_SHARED_APK), 2357 StorageManager.UUID_PRIVATE_INTERNAL, 2358 SKIP_SHARED_LIBRARY_CHECK); 2359 } 2360 } catch (FileNotFoundException e) { 2361 Slog.w(TAG, "Library not found: " + lib); 2362 } catch (IOException | InstallerException e) { 2363 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2364 + e.getMessage()); 2365 } 2366 } 2367 } 2368 } 2369 2370 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2371 2372 final VersionInfo ver = mSettings.getInternalVersion(); 2373 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2374 2375 // when upgrading from pre-M, promote system app permissions from install to runtime 2376 mPromoteSystemApps = 2377 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2378 2379 // save off the names of pre-existing system packages prior to scanning; we don't 2380 // want to automatically grant runtime permissions for new system apps 2381 if (mPromoteSystemApps) { 2382 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2383 while (pkgSettingIter.hasNext()) { 2384 PackageSetting ps = pkgSettingIter.next(); 2385 if (isSystemApp(ps)) { 2386 mExistingSystemPackages.add(ps.name); 2387 } 2388 } 2389 } 2390 2391 // When upgrading from pre-N, we need to handle package extraction like first boot, 2392 // as there is no profiling data available. 2393 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2394 mSettings.setNWorkDone(); 2395 2396 // Collect vendor overlay packages. 2397 // (Do this before scanning any apps.) 2398 // For security and version matching reason, only consider 2399 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2400 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2401 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2402 | PackageParser.PARSE_IS_SYSTEM 2403 | PackageParser.PARSE_IS_SYSTEM_DIR 2404 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2405 2406 // Find base frameworks (resource packages without code). 2407 scanDirTracedLI(frameworkDir, mDefParseFlags 2408 | PackageParser.PARSE_IS_SYSTEM 2409 | PackageParser.PARSE_IS_SYSTEM_DIR 2410 | PackageParser.PARSE_IS_PRIVILEGED, 2411 scanFlags | SCAN_NO_DEX, 0); 2412 2413 // Collected privileged system packages. 2414 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2415 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2416 | PackageParser.PARSE_IS_SYSTEM 2417 | PackageParser.PARSE_IS_SYSTEM_DIR 2418 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2419 2420 // Collect ordinary system packages. 2421 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2422 scanDirTracedLI(systemAppDir, mDefParseFlags 2423 | PackageParser.PARSE_IS_SYSTEM 2424 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2425 2426 // Collect all vendor packages. 2427 File vendorAppDir = new File("/vendor/app"); 2428 try { 2429 vendorAppDir = vendorAppDir.getCanonicalFile(); 2430 } catch (IOException e) { 2431 // failed to look up canonical path, continue with original one 2432 } 2433 scanDirTracedLI(vendorAppDir, mDefParseFlags 2434 | PackageParser.PARSE_IS_SYSTEM 2435 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2436 2437 // Collect all OEM packages. 2438 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2439 scanDirTracedLI(oemAppDir, mDefParseFlags 2440 | PackageParser.PARSE_IS_SYSTEM 2441 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2442 2443 // Prune any system packages that no longer exist. 2444 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2445 if (!mOnlyCore) { 2446 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2447 while (psit.hasNext()) { 2448 PackageSetting ps = psit.next(); 2449 2450 /* 2451 * If this is not a system app, it can't be a 2452 * disable system app. 2453 */ 2454 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2455 continue; 2456 } 2457 2458 /* 2459 * If the package is scanned, it's not erased. 2460 */ 2461 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2462 if (scannedPkg != null) { 2463 /* 2464 * If the system app is both scanned and in the 2465 * disabled packages list, then it must have been 2466 * added via OTA. Remove it from the currently 2467 * scanned package so the previously user-installed 2468 * application can be scanned. 2469 */ 2470 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2471 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2472 + ps.name + "; removing system app. Last known codePath=" 2473 + ps.codePathString + ", installStatus=" + ps.installStatus 2474 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2475 + scannedPkg.mVersionCode); 2476 removePackageLI(scannedPkg, true); 2477 mExpectingBetter.put(ps.name, ps.codePath); 2478 } 2479 2480 continue; 2481 } 2482 2483 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2484 psit.remove(); 2485 logCriticalInfo(Log.WARN, "System package " + ps.name 2486 + " no longer exists; it's data will be wiped"); 2487 // Actual deletion of code and data will be handled by later 2488 // reconciliation step 2489 } else { 2490 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2491 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2492 possiblyDeletedUpdatedSystemApps.add(ps.name); 2493 } 2494 } 2495 } 2496 } 2497 2498 //look for any incomplete package installations 2499 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2500 for (int i = 0; i < deletePkgsList.size(); i++) { 2501 // Actual deletion of code and data will be handled by later 2502 // reconciliation step 2503 final String packageName = deletePkgsList.get(i).name; 2504 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2505 synchronized (mPackages) { 2506 mSettings.removePackageLPw(packageName); 2507 } 2508 } 2509 2510 //delete tmp files 2511 deleteTempPackageFiles(); 2512 2513 // Remove any shared userIDs that have no associated packages 2514 mSettings.pruneSharedUsersLPw(); 2515 2516 if (!mOnlyCore) { 2517 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2518 SystemClock.uptimeMillis()); 2519 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2520 2521 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2522 | PackageParser.PARSE_FORWARD_LOCK, 2523 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2524 2525 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2526 | PackageParser.PARSE_IS_EPHEMERAL, 2527 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2528 2529 /** 2530 * Remove disable package settings for any updated system 2531 * apps that were removed via an OTA. If they're not a 2532 * previously-updated app, remove them completely. 2533 * Otherwise, just revoke their system-level permissions. 2534 */ 2535 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2536 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2537 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2538 2539 String msg; 2540 if (deletedPkg == null) { 2541 msg = "Updated system package " + deletedAppName 2542 + " no longer exists; it's data will be wiped"; 2543 // Actual deletion of code and data will be handled by later 2544 // reconciliation step 2545 } else { 2546 msg = "Updated system app + " + deletedAppName 2547 + " no longer present; removing system privileges for " 2548 + deletedAppName; 2549 2550 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2551 2552 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2553 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2554 } 2555 logCriticalInfo(Log.WARN, msg); 2556 } 2557 2558 /** 2559 * Make sure all system apps that we expected to appear on 2560 * the userdata partition actually showed up. If they never 2561 * appeared, crawl back and revive the system version. 2562 */ 2563 for (int i = 0; i < mExpectingBetter.size(); i++) { 2564 final String packageName = mExpectingBetter.keyAt(i); 2565 if (!mPackages.containsKey(packageName)) { 2566 final File scanFile = mExpectingBetter.valueAt(i); 2567 2568 logCriticalInfo(Log.WARN, "Expected better " + packageName 2569 + " but never showed up; reverting to system"); 2570 2571 int reparseFlags = mDefParseFlags; 2572 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2573 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2574 | PackageParser.PARSE_IS_SYSTEM_DIR 2575 | PackageParser.PARSE_IS_PRIVILEGED; 2576 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2577 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2578 | PackageParser.PARSE_IS_SYSTEM_DIR; 2579 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2580 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2581 | PackageParser.PARSE_IS_SYSTEM_DIR; 2582 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2583 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2584 | PackageParser.PARSE_IS_SYSTEM_DIR; 2585 } else { 2586 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2587 continue; 2588 } 2589 2590 mSettings.enableSystemPackageLPw(packageName); 2591 2592 try { 2593 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2594 } catch (PackageManagerException e) { 2595 Slog.e(TAG, "Failed to parse original system package: " 2596 + e.getMessage()); 2597 } 2598 } 2599 } 2600 } 2601 mExpectingBetter.clear(); 2602 2603 // Resolve protected action filters. Only the setup wizard is allowed to 2604 // have a high priority filter for these actions. 2605 mSetupWizardPackage = getSetupWizardPackageName(); 2606 if (mProtectedFilters.size() > 0) { 2607 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2608 Slog.i(TAG, "No setup wizard;" 2609 + " All protected intents capped to priority 0"); 2610 } 2611 for (ActivityIntentInfo filter : mProtectedFilters) { 2612 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2613 if (DEBUG_FILTERS) { 2614 Slog.i(TAG, "Found setup wizard;" 2615 + " allow priority " + filter.getPriority() + ";" 2616 + " package: " + filter.activity.info.packageName 2617 + " activity: " + filter.activity.className 2618 + " priority: " + filter.getPriority()); 2619 } 2620 // skip setup wizard; allow it to keep the high priority filter 2621 continue; 2622 } 2623 Slog.w(TAG, "Protected action; cap priority to 0;" 2624 + " package: " + filter.activity.info.packageName 2625 + " activity: " + filter.activity.className 2626 + " origPrio: " + filter.getPriority()); 2627 filter.setPriority(0); 2628 } 2629 } 2630 mDeferProtectedFilters = false; 2631 mProtectedFilters.clear(); 2632 2633 // Now that we know all of the shared libraries, update all clients to have 2634 // the correct library paths. 2635 updateAllSharedLibrariesLPw(); 2636 2637 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2638 // NOTE: We ignore potential failures here during a system scan (like 2639 // the rest of the commands above) because there's precious little we 2640 // can do about it. A settings error is reported, though. 2641 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2642 false /* boot complete */); 2643 } 2644 2645 // Now that we know all the packages we are keeping, 2646 // read and update their last usage times. 2647 mPackageUsage.readLP(); 2648 2649 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2650 SystemClock.uptimeMillis()); 2651 Slog.i(TAG, "Time to scan packages: " 2652 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2653 + " seconds"); 2654 2655 // If the platform SDK has changed since the last time we booted, 2656 // we need to re-grant app permission to catch any new ones that 2657 // appear. This is really a hack, and means that apps can in some 2658 // cases get permissions that the user didn't initially explicitly 2659 // allow... it would be nice to have some better way to handle 2660 // this situation. 2661 int updateFlags = UPDATE_PERMISSIONS_ALL; 2662 if (ver.sdkVersion != mSdkVersion) { 2663 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2664 + mSdkVersion + "; regranting permissions for internal storage"); 2665 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2666 } 2667 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2668 ver.sdkVersion = mSdkVersion; 2669 2670 // If this is the first boot or an update from pre-M, and it is a normal 2671 // boot, then we need to initialize the default preferred apps across 2672 // all defined users. 2673 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2674 for (UserInfo user : sUserManager.getUsers(true)) { 2675 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2676 applyFactoryDefaultBrowserLPw(user.id); 2677 primeDomainVerificationsLPw(user.id); 2678 } 2679 } 2680 2681 // Prepare storage for system user really early during boot, 2682 // since core system apps like SettingsProvider and SystemUI 2683 // can't wait for user to start 2684 final int storageFlags; 2685 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2686 storageFlags = StorageManager.FLAG_STORAGE_DE; 2687 } else { 2688 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2689 } 2690 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2691 storageFlags); 2692 2693 // If this is first boot after an OTA, and a normal boot, then 2694 // we need to clear code cache directories. 2695 if (mIsUpgrade && !onlyCore) { 2696 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2697 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2698 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2699 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2700 // No apps are running this early, so no need to freeze 2701 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2702 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2703 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2704 } 2705 clearAppProfilesLIF(ps.pkg); 2706 } 2707 ver.fingerprint = Build.FINGERPRINT; 2708 } 2709 2710 checkDefaultBrowser(); 2711 2712 // clear only after permissions and other defaults have been updated 2713 mExistingSystemPackages.clear(); 2714 mPromoteSystemApps = false; 2715 2716 // All the changes are done during package scanning. 2717 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2718 2719 // can downgrade to reader 2720 mSettings.writeLPr(); 2721 2722 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2723 SystemClock.uptimeMillis()); 2724 2725 if (!mOnlyCore) { 2726 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2727 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2728 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2729 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2730 mIntentFilterVerifierComponent); 2731 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2732 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2733 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2734 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2735 } else { 2736 mRequiredVerifierPackage = null; 2737 mRequiredInstallerPackage = null; 2738 mIntentFilterVerifierComponent = null; 2739 mIntentFilterVerifier = null; 2740 mServicesSystemSharedLibraryPackageName = null; 2741 mSharedSystemSharedLibraryPackageName = null; 2742 } 2743 2744 mInstallerService = new PackageInstallerService(context, this); 2745 2746 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2747 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2748 // both the installer and resolver must be present to enable ephemeral 2749 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2750 if (DEBUG_EPHEMERAL) { 2751 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2752 + " installer:" + ephemeralInstallerComponent); 2753 } 2754 mEphemeralResolverComponent = ephemeralResolverComponent; 2755 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2756 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2757 mEphemeralResolverConnection = 2758 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2759 } else { 2760 if (DEBUG_EPHEMERAL) { 2761 final String missingComponent = 2762 (ephemeralResolverComponent == null) 2763 ? (ephemeralInstallerComponent == null) 2764 ? "resolver and installer" 2765 : "resolver" 2766 : "installer"; 2767 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2768 } 2769 mEphemeralResolverComponent = null; 2770 mEphemeralInstallerComponent = null; 2771 mEphemeralResolverConnection = null; 2772 } 2773 2774 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2775 } // synchronized (mPackages) 2776 } // synchronized (mInstallLock) 2777 2778 // Now after opening every single application zip, make sure they 2779 // are all flushed. Not really needed, but keeps things nice and 2780 // tidy. 2781 Runtime.getRuntime().gc(); 2782 2783 // The initial scanning above does many calls into installd while 2784 // holding the mPackages lock, but we're mostly interested in yelling 2785 // once we have a booted system. 2786 mInstaller.setWarnIfHeld(mPackages); 2787 2788 // Expose private service for system components to use. 2789 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2790 } 2791 2792 @Override 2793 public boolean isFirstBoot() { 2794 return !mRestoredSettings; 2795 } 2796 2797 @Override 2798 public boolean isOnlyCoreApps() { 2799 return mOnlyCore; 2800 } 2801 2802 @Override 2803 public boolean isUpgrade() { 2804 return mIsUpgrade; 2805 } 2806 2807 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2808 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2809 2810 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2811 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2812 UserHandle.USER_SYSTEM); 2813 if (matches.size() == 1) { 2814 return matches.get(0).getComponentInfo().packageName; 2815 } else { 2816 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2817 return null; 2818 } 2819 } 2820 2821 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2822 synchronized (mPackages) { 2823 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2824 if (libraryEntry == null) { 2825 throw new IllegalStateException("Missing required shared library:" + libraryName); 2826 } 2827 return libraryEntry.apk; 2828 } 2829 } 2830 2831 private @NonNull String getRequiredInstallerLPr() { 2832 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2833 intent.addCategory(Intent.CATEGORY_DEFAULT); 2834 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2835 2836 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2837 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2838 UserHandle.USER_SYSTEM); 2839 if (matches.size() == 1) { 2840 ResolveInfo resolveInfo = matches.get(0); 2841 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2842 throw new RuntimeException("The installer must be a privileged app"); 2843 } 2844 return matches.get(0).getComponentInfo().packageName; 2845 } else { 2846 throw new RuntimeException("There must be exactly one installer; found " + matches); 2847 } 2848 } 2849 2850 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2851 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2852 2853 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2854 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2855 UserHandle.USER_SYSTEM); 2856 ResolveInfo best = null; 2857 final int N = matches.size(); 2858 for (int i = 0; i < N; i++) { 2859 final ResolveInfo cur = matches.get(i); 2860 final String packageName = cur.getComponentInfo().packageName; 2861 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2862 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2863 continue; 2864 } 2865 2866 if (best == null || cur.priority > best.priority) { 2867 best = cur; 2868 } 2869 } 2870 2871 if (best != null) { 2872 return best.getComponentInfo().getComponentName(); 2873 } else { 2874 throw new RuntimeException("There must be at least one intent filter verifier"); 2875 } 2876 } 2877 2878 private @Nullable ComponentName getEphemeralResolverLPr() { 2879 final String[] packageArray = 2880 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2881 if (packageArray.length == 0) { 2882 if (DEBUG_EPHEMERAL) { 2883 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2884 } 2885 return null; 2886 } 2887 2888 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2889 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2890 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2891 UserHandle.USER_SYSTEM); 2892 2893 final int N = resolvers.size(); 2894 if (N == 0) { 2895 if (DEBUG_EPHEMERAL) { 2896 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2897 } 2898 return null; 2899 } 2900 2901 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2902 for (int i = 0; i < N; i++) { 2903 final ResolveInfo info = resolvers.get(i); 2904 2905 if (info.serviceInfo == null) { 2906 continue; 2907 } 2908 2909 final String packageName = info.serviceInfo.packageName; 2910 if (!possiblePackages.contains(packageName)) { 2911 if (DEBUG_EPHEMERAL) { 2912 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2913 + " pkg: " + packageName + ", info:" + info); 2914 } 2915 continue; 2916 } 2917 2918 if (DEBUG_EPHEMERAL) { 2919 Slog.v(TAG, "Ephemeral resolver found;" 2920 + " pkg: " + packageName + ", info:" + info); 2921 } 2922 return new ComponentName(packageName, info.serviceInfo.name); 2923 } 2924 if (DEBUG_EPHEMERAL) { 2925 Slog.v(TAG, "Ephemeral resolver NOT found"); 2926 } 2927 return null; 2928 } 2929 2930 private @Nullable ComponentName getEphemeralInstallerLPr() { 2931 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2932 intent.addCategory(Intent.CATEGORY_DEFAULT); 2933 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2934 2935 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2936 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2937 UserHandle.USER_SYSTEM); 2938 if (matches.size() == 0) { 2939 return null; 2940 } else if (matches.size() == 1) { 2941 return matches.get(0).getComponentInfo().getComponentName(); 2942 } else { 2943 throw new RuntimeException( 2944 "There must be at most one ephemeral installer; found " + matches); 2945 } 2946 } 2947 2948 private void primeDomainVerificationsLPw(int userId) { 2949 if (DEBUG_DOMAIN_VERIFICATION) { 2950 Slog.d(TAG, "Priming domain verifications in user " + userId); 2951 } 2952 2953 SystemConfig systemConfig = SystemConfig.getInstance(); 2954 ArraySet<String> packages = systemConfig.getLinkedApps(); 2955 ArraySet<String> domains = new ArraySet<String>(); 2956 2957 for (String packageName : packages) { 2958 PackageParser.Package pkg = mPackages.get(packageName); 2959 if (pkg != null) { 2960 if (!pkg.isSystemApp()) { 2961 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2962 continue; 2963 } 2964 2965 domains.clear(); 2966 for (PackageParser.Activity a : pkg.activities) { 2967 for (ActivityIntentInfo filter : a.intents) { 2968 if (hasValidDomains(filter)) { 2969 domains.addAll(filter.getHostsList()); 2970 } 2971 } 2972 } 2973 2974 if (domains.size() > 0) { 2975 if (DEBUG_DOMAIN_VERIFICATION) { 2976 Slog.v(TAG, " + " + packageName); 2977 } 2978 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2979 // state w.r.t. the formal app-linkage "no verification attempted" state; 2980 // and then 'always' in the per-user state actually used for intent resolution. 2981 final IntentFilterVerificationInfo ivi; 2982 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2983 new ArrayList<String>(domains)); 2984 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2985 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2986 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2987 } else { 2988 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2989 + "' does not handle web links"); 2990 } 2991 } else { 2992 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2993 } 2994 } 2995 2996 scheduleWritePackageRestrictionsLocked(userId); 2997 scheduleWriteSettingsLocked(); 2998 } 2999 3000 private void applyFactoryDefaultBrowserLPw(int userId) { 3001 // The default browser app's package name is stored in a string resource, 3002 // with a product-specific overlay used for vendor customization. 3003 String browserPkg = mContext.getResources().getString( 3004 com.android.internal.R.string.default_browser); 3005 if (!TextUtils.isEmpty(browserPkg)) { 3006 // non-empty string => required to be a known package 3007 PackageSetting ps = mSettings.mPackages.get(browserPkg); 3008 if (ps == null) { 3009 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 3010 browserPkg = null; 3011 } else { 3012 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3013 } 3014 } 3015 3016 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3017 // default. If there's more than one, just leave everything alone. 3018 if (browserPkg == null) { 3019 calculateDefaultBrowserLPw(userId); 3020 } 3021 } 3022 3023 private void calculateDefaultBrowserLPw(int userId) { 3024 List<String> allBrowsers = resolveAllBrowserApps(userId); 3025 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3026 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3027 } 3028 3029 private List<String> resolveAllBrowserApps(int userId) { 3030 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3031 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3032 PackageManager.MATCH_ALL, userId); 3033 3034 final int count = list.size(); 3035 List<String> result = new ArrayList<String>(count); 3036 for (int i=0; i<count; i++) { 3037 ResolveInfo info = list.get(i); 3038 if (info.activityInfo == null 3039 || !info.handleAllWebDataURI 3040 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3041 || result.contains(info.activityInfo.packageName)) { 3042 continue; 3043 } 3044 result.add(info.activityInfo.packageName); 3045 } 3046 3047 return result; 3048 } 3049 3050 private boolean packageIsBrowser(String packageName, int userId) { 3051 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3052 PackageManager.MATCH_ALL, userId); 3053 final int N = list.size(); 3054 for (int i = 0; i < N; i++) { 3055 ResolveInfo info = list.get(i); 3056 if (packageName.equals(info.activityInfo.packageName)) { 3057 return true; 3058 } 3059 } 3060 return false; 3061 } 3062 3063 private void checkDefaultBrowser() { 3064 final int myUserId = UserHandle.myUserId(); 3065 final String packageName = getDefaultBrowserPackageName(myUserId); 3066 if (packageName != null) { 3067 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3068 if (info == null) { 3069 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3070 synchronized (mPackages) { 3071 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3072 } 3073 } 3074 } 3075 } 3076 3077 @Override 3078 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3079 throws RemoteException { 3080 try { 3081 return super.onTransact(code, data, reply, flags); 3082 } catch (RuntimeException e) { 3083 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3084 Slog.wtf(TAG, "Package Manager Crash", e); 3085 } 3086 throw e; 3087 } 3088 } 3089 3090 static int[] appendInts(int[] cur, int[] add) { 3091 if (add == null) return cur; 3092 if (cur == null) return add; 3093 final int N = add.length; 3094 for (int i=0; i<N; i++) { 3095 cur = appendInt(cur, add[i]); 3096 } 3097 return cur; 3098 } 3099 3100 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3101 if (!sUserManager.exists(userId)) return null; 3102 if (ps == null) { 3103 return null; 3104 } 3105 final PackageParser.Package p = ps.pkg; 3106 if (p == null) { 3107 return null; 3108 } 3109 3110 final PermissionsState permissionsState = ps.getPermissionsState(); 3111 3112 final int[] gids = permissionsState.computeGids(userId); 3113 final Set<String> permissions = permissionsState.getPermissions(userId); 3114 final PackageUserState state = ps.readUserState(userId); 3115 3116 return PackageParser.generatePackageInfo(p, gids, flags, 3117 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3118 } 3119 3120 @Override 3121 public void checkPackageStartable(String packageName, int userId) { 3122 final boolean userKeyUnlocked = StorageManager.isUserKeyUnlocked(userId); 3123 3124 synchronized (mPackages) { 3125 final PackageSetting ps = mSettings.mPackages.get(packageName); 3126 if (ps == null) { 3127 throw new SecurityException("Package " + packageName + " was not found!"); 3128 } 3129 3130 if (!ps.getInstalled(userId)) { 3131 throw new SecurityException( 3132 "Package " + packageName + " was not installed for user " + userId + "!"); 3133 } 3134 3135 if (mSafeMode && !ps.isSystem()) { 3136 throw new SecurityException("Package " + packageName + " not a system app!"); 3137 } 3138 3139 if (mFrozenPackages.contains(packageName)) { 3140 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3141 } 3142 3143 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3144 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3145 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3146 } 3147 } 3148 } 3149 3150 @Override 3151 public boolean isPackageAvailable(String packageName, int userId) { 3152 if (!sUserManager.exists(userId)) return false; 3153 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3154 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3155 synchronized (mPackages) { 3156 PackageParser.Package p = mPackages.get(packageName); 3157 if (p != null) { 3158 final PackageSetting ps = (PackageSetting) p.mExtras; 3159 if (ps != null) { 3160 final PackageUserState state = ps.readUserState(userId); 3161 if (state != null) { 3162 return PackageParser.isAvailable(state); 3163 } 3164 } 3165 } 3166 } 3167 return false; 3168 } 3169 3170 @Override 3171 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3172 if (!sUserManager.exists(userId)) return null; 3173 flags = updateFlagsForPackage(flags, userId, packageName); 3174 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3175 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3176 // reader 3177 synchronized (mPackages) { 3178 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3179 PackageParser.Package p = null; 3180 if (matchFactoryOnly) { 3181 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3182 if (ps != null) { 3183 return generatePackageInfo(ps, flags, userId); 3184 } 3185 } 3186 if (p == null) { 3187 p = mPackages.get(packageName); 3188 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3189 return null; 3190 } 3191 } 3192 if (DEBUG_PACKAGE_INFO) 3193 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3194 if (p != null) { 3195 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3196 } 3197 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3198 final PackageSetting ps = mSettings.mPackages.get(packageName); 3199 return generatePackageInfo(ps, flags, userId); 3200 } 3201 } 3202 return null; 3203 } 3204 3205 @Override 3206 public String[] currentToCanonicalPackageNames(String[] names) { 3207 String[] out = new String[names.length]; 3208 // reader 3209 synchronized (mPackages) { 3210 for (int i=names.length-1; i>=0; i--) { 3211 PackageSetting ps = mSettings.mPackages.get(names[i]); 3212 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3213 } 3214 } 3215 return out; 3216 } 3217 3218 @Override 3219 public String[] canonicalToCurrentPackageNames(String[] names) { 3220 String[] out = new String[names.length]; 3221 // reader 3222 synchronized (mPackages) { 3223 for (int i=names.length-1; i>=0; i--) { 3224 String cur = mSettings.mRenamedPackages.get(names[i]); 3225 out[i] = cur != null ? cur : names[i]; 3226 } 3227 } 3228 return out; 3229 } 3230 3231 @Override 3232 public int getPackageUid(String packageName, int flags, int userId) { 3233 if (!sUserManager.exists(userId)) return -1; 3234 flags = updateFlagsForPackage(flags, userId, packageName); 3235 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3236 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3237 3238 // reader 3239 synchronized (mPackages) { 3240 final PackageParser.Package p = mPackages.get(packageName); 3241 if (p != null && p.isMatch(flags)) { 3242 return UserHandle.getUid(userId, p.applicationInfo.uid); 3243 } 3244 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3245 final PackageSetting ps = mSettings.mPackages.get(packageName); 3246 if (ps != null && ps.isMatch(flags)) { 3247 return UserHandle.getUid(userId, ps.appId); 3248 } 3249 } 3250 } 3251 3252 return -1; 3253 } 3254 3255 @Override 3256 public int[] getPackageGids(String packageName, int flags, int userId) { 3257 if (!sUserManager.exists(userId)) return null; 3258 flags = updateFlagsForPackage(flags, userId, packageName); 3259 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3260 false /* requireFullPermission */, false /* checkShell */, 3261 "getPackageGids"); 3262 3263 // reader 3264 synchronized (mPackages) { 3265 final PackageParser.Package p = mPackages.get(packageName); 3266 if (p != null && p.isMatch(flags)) { 3267 PackageSetting ps = (PackageSetting) p.mExtras; 3268 return ps.getPermissionsState().computeGids(userId); 3269 } 3270 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3271 final PackageSetting ps = mSettings.mPackages.get(packageName); 3272 if (ps != null && ps.isMatch(flags)) { 3273 return ps.getPermissionsState().computeGids(userId); 3274 } 3275 } 3276 } 3277 3278 return null; 3279 } 3280 3281 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3282 if (bp.perm != null) { 3283 return PackageParser.generatePermissionInfo(bp.perm, flags); 3284 } 3285 PermissionInfo pi = new PermissionInfo(); 3286 pi.name = bp.name; 3287 pi.packageName = bp.sourcePackage; 3288 pi.nonLocalizedLabel = bp.name; 3289 pi.protectionLevel = bp.protectionLevel; 3290 return pi; 3291 } 3292 3293 @Override 3294 public PermissionInfo getPermissionInfo(String name, int flags) { 3295 // reader 3296 synchronized (mPackages) { 3297 final BasePermission p = mSettings.mPermissions.get(name); 3298 if (p != null) { 3299 return generatePermissionInfo(p, flags); 3300 } 3301 return null; 3302 } 3303 } 3304 3305 @Override 3306 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3307 int flags) { 3308 // reader 3309 synchronized (mPackages) { 3310 if (group != null && !mPermissionGroups.containsKey(group)) { 3311 // This is thrown as NameNotFoundException 3312 return null; 3313 } 3314 3315 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3316 for (BasePermission p : mSettings.mPermissions.values()) { 3317 if (group == null) { 3318 if (p.perm == null || p.perm.info.group == null) { 3319 out.add(generatePermissionInfo(p, flags)); 3320 } 3321 } else { 3322 if (p.perm != null && group.equals(p.perm.info.group)) { 3323 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3324 } 3325 } 3326 } 3327 return new ParceledListSlice<>(out); 3328 } 3329 } 3330 3331 @Override 3332 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3333 // reader 3334 synchronized (mPackages) { 3335 return PackageParser.generatePermissionGroupInfo( 3336 mPermissionGroups.get(name), flags); 3337 } 3338 } 3339 3340 @Override 3341 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3342 // reader 3343 synchronized (mPackages) { 3344 final int N = mPermissionGroups.size(); 3345 ArrayList<PermissionGroupInfo> out 3346 = new ArrayList<PermissionGroupInfo>(N); 3347 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3348 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3349 } 3350 return new ParceledListSlice<>(out); 3351 } 3352 } 3353 3354 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3355 int userId) { 3356 if (!sUserManager.exists(userId)) return null; 3357 PackageSetting ps = mSettings.mPackages.get(packageName); 3358 if (ps != null) { 3359 if (ps.pkg == null) { 3360 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3361 if (pInfo != null) { 3362 return pInfo.applicationInfo; 3363 } 3364 return null; 3365 } 3366 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3367 ps.readUserState(userId), userId); 3368 } 3369 return null; 3370 } 3371 3372 @Override 3373 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3374 if (!sUserManager.exists(userId)) return null; 3375 flags = updateFlagsForApplication(flags, userId, packageName); 3376 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3377 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3378 // writer 3379 synchronized (mPackages) { 3380 PackageParser.Package p = mPackages.get(packageName); 3381 if (DEBUG_PACKAGE_INFO) Log.v( 3382 TAG, "getApplicationInfo " + packageName 3383 + ": " + p); 3384 if (p != null) { 3385 PackageSetting ps = mSettings.mPackages.get(packageName); 3386 if (ps == null) return null; 3387 // Note: isEnabledLP() does not apply here - always return info 3388 return PackageParser.generateApplicationInfo( 3389 p, flags, ps.readUserState(userId), userId); 3390 } 3391 if ("android".equals(packageName)||"system".equals(packageName)) { 3392 return mAndroidApplication; 3393 } 3394 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3395 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3396 } 3397 } 3398 return null; 3399 } 3400 3401 @Override 3402 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3403 final IPackageDataObserver observer) { 3404 mContext.enforceCallingOrSelfPermission( 3405 android.Manifest.permission.CLEAR_APP_CACHE, null); 3406 // Queue up an async operation since clearing cache may take a little while. 3407 mHandler.post(new Runnable() { 3408 public void run() { 3409 mHandler.removeCallbacks(this); 3410 boolean success = true; 3411 synchronized (mInstallLock) { 3412 try { 3413 mInstaller.freeCache(volumeUuid, freeStorageSize); 3414 } catch (InstallerException e) { 3415 Slog.w(TAG, "Couldn't clear application caches: " + e); 3416 success = false; 3417 } 3418 } 3419 if (observer != null) { 3420 try { 3421 observer.onRemoveCompleted(null, success); 3422 } catch (RemoteException e) { 3423 Slog.w(TAG, "RemoveException when invoking call back"); 3424 } 3425 } 3426 } 3427 }); 3428 } 3429 3430 @Override 3431 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3432 final IntentSender pi) { 3433 mContext.enforceCallingOrSelfPermission( 3434 android.Manifest.permission.CLEAR_APP_CACHE, null); 3435 // Queue up an async operation since clearing cache may take a little while. 3436 mHandler.post(new Runnable() { 3437 public void run() { 3438 mHandler.removeCallbacks(this); 3439 boolean success = true; 3440 synchronized (mInstallLock) { 3441 try { 3442 mInstaller.freeCache(volumeUuid, freeStorageSize); 3443 } catch (InstallerException e) { 3444 Slog.w(TAG, "Couldn't clear application caches: " + e); 3445 success = false; 3446 } 3447 } 3448 if(pi != null) { 3449 try { 3450 // Callback via pending intent 3451 int code = success ? 1 : 0; 3452 pi.sendIntent(null, code, null, 3453 null, null); 3454 } catch (SendIntentException e1) { 3455 Slog.i(TAG, "Failed to send pending intent"); 3456 } 3457 } 3458 } 3459 }); 3460 } 3461 3462 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3463 synchronized (mInstallLock) { 3464 try { 3465 mInstaller.freeCache(volumeUuid, freeStorageSize); 3466 } catch (InstallerException e) { 3467 throw new IOException("Failed to free enough space", e); 3468 } 3469 } 3470 } 3471 3472 /** 3473 * Update given flags based on encryption status of current user. 3474 */ 3475 private int updateFlags(int flags, int userId) { 3476 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3477 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3478 // Caller expressed an explicit opinion about what encryption 3479 // aware/unaware components they want to see, so fall through and 3480 // give them what they want 3481 } else { 3482 // Caller expressed no opinion, so match based on user state 3483 if (StorageManager.isUserKeyUnlocked(userId)) { 3484 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3485 } else { 3486 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3487 } 3488 } 3489 return flags; 3490 } 3491 3492 /** 3493 * Update given flags when being used to request {@link PackageInfo}. 3494 */ 3495 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3496 boolean triaged = true; 3497 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3498 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3499 // Caller is asking for component details, so they'd better be 3500 // asking for specific encryption matching behavior, or be triaged 3501 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3502 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3503 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3504 triaged = false; 3505 } 3506 } 3507 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3508 | PackageManager.MATCH_SYSTEM_ONLY 3509 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3510 triaged = false; 3511 } 3512 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3513 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3514 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3515 } 3516 return updateFlags(flags, userId); 3517 } 3518 3519 /** 3520 * Update given flags when being used to request {@link ApplicationInfo}. 3521 */ 3522 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3523 return updateFlagsForPackage(flags, userId, cookie); 3524 } 3525 3526 /** 3527 * Update given flags when being used to request {@link ComponentInfo}. 3528 */ 3529 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3530 if (cookie instanceof Intent) { 3531 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3532 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3533 } 3534 } 3535 3536 boolean triaged = true; 3537 // Caller is asking for component details, so they'd better be 3538 // asking for specific encryption matching behavior, or be triaged 3539 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3540 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3541 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3542 triaged = false; 3543 } 3544 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3545 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3546 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3547 } 3548 3549 return updateFlags(flags, userId); 3550 } 3551 3552 /** 3553 * Update given flags when being used to request {@link ResolveInfo}. 3554 */ 3555 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3556 // Safe mode means we shouldn't match any third-party components 3557 if (mSafeMode) { 3558 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3559 } 3560 3561 return updateFlagsForComponent(flags, userId, cookie); 3562 } 3563 3564 @Override 3565 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3566 if (!sUserManager.exists(userId)) return null; 3567 flags = updateFlagsForComponent(flags, userId, component); 3568 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3569 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3570 synchronized (mPackages) { 3571 PackageParser.Activity a = mActivities.mActivities.get(component); 3572 3573 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3574 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3575 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3576 if (ps == null) return null; 3577 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3578 userId); 3579 } 3580 if (mResolveComponentName.equals(component)) { 3581 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3582 new PackageUserState(), userId); 3583 } 3584 } 3585 return null; 3586 } 3587 3588 @Override 3589 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3590 String resolvedType) { 3591 synchronized (mPackages) { 3592 if (component.equals(mResolveComponentName)) { 3593 // The resolver supports EVERYTHING! 3594 return true; 3595 } 3596 PackageParser.Activity a = mActivities.mActivities.get(component); 3597 if (a == null) { 3598 return false; 3599 } 3600 for (int i=0; i<a.intents.size(); i++) { 3601 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3602 intent.getData(), intent.getCategories(), TAG) >= 0) { 3603 return true; 3604 } 3605 } 3606 return false; 3607 } 3608 } 3609 3610 @Override 3611 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3612 if (!sUserManager.exists(userId)) return null; 3613 flags = updateFlagsForComponent(flags, userId, component); 3614 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3615 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3616 synchronized (mPackages) { 3617 PackageParser.Activity a = mReceivers.mActivities.get(component); 3618 if (DEBUG_PACKAGE_INFO) Log.v( 3619 TAG, "getReceiverInfo " + component + ": " + a); 3620 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3621 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3622 if (ps == null) return null; 3623 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3624 userId); 3625 } 3626 } 3627 return null; 3628 } 3629 3630 @Override 3631 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3632 if (!sUserManager.exists(userId)) return null; 3633 flags = updateFlagsForComponent(flags, userId, component); 3634 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3635 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3636 synchronized (mPackages) { 3637 PackageParser.Service s = mServices.mServices.get(component); 3638 if (DEBUG_PACKAGE_INFO) Log.v( 3639 TAG, "getServiceInfo " + component + ": " + s); 3640 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3641 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3642 if (ps == null) return null; 3643 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3644 userId); 3645 } 3646 } 3647 return null; 3648 } 3649 3650 @Override 3651 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3652 if (!sUserManager.exists(userId)) return null; 3653 flags = updateFlagsForComponent(flags, userId, component); 3654 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3655 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3656 synchronized (mPackages) { 3657 PackageParser.Provider p = mProviders.mProviders.get(component); 3658 if (DEBUG_PACKAGE_INFO) Log.v( 3659 TAG, "getProviderInfo " + component + ": " + p); 3660 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3661 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3662 if (ps == null) return null; 3663 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3664 userId); 3665 } 3666 } 3667 return null; 3668 } 3669 3670 @Override 3671 public String[] getSystemSharedLibraryNames() { 3672 Set<String> libSet; 3673 synchronized (mPackages) { 3674 libSet = mSharedLibraries.keySet(); 3675 int size = libSet.size(); 3676 if (size > 0) { 3677 String[] libs = new String[size]; 3678 libSet.toArray(libs); 3679 return libs; 3680 } 3681 } 3682 return null; 3683 } 3684 3685 @Override 3686 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3687 synchronized (mPackages) { 3688 return mServicesSystemSharedLibraryPackageName; 3689 } 3690 } 3691 3692 @Override 3693 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3694 synchronized (mPackages) { 3695 return mSharedSystemSharedLibraryPackageName; 3696 } 3697 } 3698 3699 @Override 3700 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3701 synchronized (mPackages) { 3702 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3703 3704 final FeatureInfo fi = new FeatureInfo(); 3705 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3706 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3707 res.add(fi); 3708 3709 return new ParceledListSlice<>(res); 3710 } 3711 } 3712 3713 @Override 3714 public boolean hasSystemFeature(String name, int version) { 3715 synchronized (mPackages) { 3716 final FeatureInfo feat = mAvailableFeatures.get(name); 3717 if (feat == null) { 3718 return false; 3719 } else { 3720 return feat.version >= version; 3721 } 3722 } 3723 } 3724 3725 @Override 3726 public int checkPermission(String permName, String pkgName, int userId) { 3727 if (!sUserManager.exists(userId)) { 3728 return PackageManager.PERMISSION_DENIED; 3729 } 3730 3731 synchronized (mPackages) { 3732 final PackageParser.Package p = mPackages.get(pkgName); 3733 if (p != null && p.mExtras != null) { 3734 final PackageSetting ps = (PackageSetting) p.mExtras; 3735 final PermissionsState permissionsState = ps.getPermissionsState(); 3736 if (permissionsState.hasPermission(permName, userId)) { 3737 return PackageManager.PERMISSION_GRANTED; 3738 } 3739 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3740 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3741 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3742 return PackageManager.PERMISSION_GRANTED; 3743 } 3744 } 3745 } 3746 3747 return PackageManager.PERMISSION_DENIED; 3748 } 3749 3750 @Override 3751 public int checkUidPermission(String permName, int uid) { 3752 final int userId = UserHandle.getUserId(uid); 3753 3754 if (!sUserManager.exists(userId)) { 3755 return PackageManager.PERMISSION_DENIED; 3756 } 3757 3758 synchronized (mPackages) { 3759 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3760 if (obj != null) { 3761 final SettingBase ps = (SettingBase) obj; 3762 final PermissionsState permissionsState = ps.getPermissionsState(); 3763 if (permissionsState.hasPermission(permName, userId)) { 3764 return PackageManager.PERMISSION_GRANTED; 3765 } 3766 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3767 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3768 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3769 return PackageManager.PERMISSION_GRANTED; 3770 } 3771 } else { 3772 ArraySet<String> perms = mSystemPermissions.get(uid); 3773 if (perms != null) { 3774 if (perms.contains(permName)) { 3775 return PackageManager.PERMISSION_GRANTED; 3776 } 3777 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3778 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3779 return PackageManager.PERMISSION_GRANTED; 3780 } 3781 } 3782 } 3783 } 3784 3785 return PackageManager.PERMISSION_DENIED; 3786 } 3787 3788 @Override 3789 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3790 if (UserHandle.getCallingUserId() != userId) { 3791 mContext.enforceCallingPermission( 3792 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3793 "isPermissionRevokedByPolicy for user " + userId); 3794 } 3795 3796 if (checkPermission(permission, packageName, userId) 3797 == PackageManager.PERMISSION_GRANTED) { 3798 return false; 3799 } 3800 3801 final long identity = Binder.clearCallingIdentity(); 3802 try { 3803 final int flags = getPermissionFlags(permission, packageName, userId); 3804 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3805 } finally { 3806 Binder.restoreCallingIdentity(identity); 3807 } 3808 } 3809 3810 @Override 3811 public String getPermissionControllerPackageName() { 3812 synchronized (mPackages) { 3813 return mRequiredInstallerPackage; 3814 } 3815 } 3816 3817 /** 3818 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3819 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3820 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3821 * @param message the message to log on security exception 3822 */ 3823 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3824 boolean checkShell, String message) { 3825 if (userId < 0) { 3826 throw new IllegalArgumentException("Invalid userId " + userId); 3827 } 3828 if (checkShell) { 3829 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3830 } 3831 if (userId == UserHandle.getUserId(callingUid)) return; 3832 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3833 if (requireFullPermission) { 3834 mContext.enforceCallingOrSelfPermission( 3835 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3836 } else { 3837 try { 3838 mContext.enforceCallingOrSelfPermission( 3839 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3840 } catch (SecurityException se) { 3841 mContext.enforceCallingOrSelfPermission( 3842 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3843 } 3844 } 3845 } 3846 } 3847 3848 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3849 if (callingUid == Process.SHELL_UID) { 3850 if (userHandle >= 0 3851 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3852 throw new SecurityException("Shell does not have permission to access user " 3853 + userHandle); 3854 } else if (userHandle < 0) { 3855 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3856 + Debug.getCallers(3)); 3857 } 3858 } 3859 } 3860 3861 private BasePermission findPermissionTreeLP(String permName) { 3862 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3863 if (permName.startsWith(bp.name) && 3864 permName.length() > bp.name.length() && 3865 permName.charAt(bp.name.length()) == '.') { 3866 return bp; 3867 } 3868 } 3869 return null; 3870 } 3871 3872 private BasePermission checkPermissionTreeLP(String permName) { 3873 if (permName != null) { 3874 BasePermission bp = findPermissionTreeLP(permName); 3875 if (bp != null) { 3876 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3877 return bp; 3878 } 3879 throw new SecurityException("Calling uid " 3880 + Binder.getCallingUid() 3881 + " is not allowed to add to permission tree " 3882 + bp.name + " owned by uid " + bp.uid); 3883 } 3884 } 3885 throw new SecurityException("No permission tree found for " + permName); 3886 } 3887 3888 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3889 if (s1 == null) { 3890 return s2 == null; 3891 } 3892 if (s2 == null) { 3893 return false; 3894 } 3895 if (s1.getClass() != s2.getClass()) { 3896 return false; 3897 } 3898 return s1.equals(s2); 3899 } 3900 3901 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3902 if (pi1.icon != pi2.icon) return false; 3903 if (pi1.logo != pi2.logo) return false; 3904 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3905 if (!compareStrings(pi1.name, pi2.name)) return false; 3906 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3907 // We'll take care of setting this one. 3908 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3909 // These are not currently stored in settings. 3910 //if (!compareStrings(pi1.group, pi2.group)) return false; 3911 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3912 //if (pi1.labelRes != pi2.labelRes) return false; 3913 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3914 return true; 3915 } 3916 3917 int permissionInfoFootprint(PermissionInfo info) { 3918 int size = info.name.length(); 3919 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3920 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3921 return size; 3922 } 3923 3924 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3925 int size = 0; 3926 for (BasePermission perm : mSettings.mPermissions.values()) { 3927 if (perm.uid == tree.uid) { 3928 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3929 } 3930 } 3931 return size; 3932 } 3933 3934 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3935 // We calculate the max size of permissions defined by this uid and throw 3936 // if that plus the size of 'info' would exceed our stated maximum. 3937 if (tree.uid != Process.SYSTEM_UID) { 3938 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3939 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3940 throw new SecurityException("Permission tree size cap exceeded"); 3941 } 3942 } 3943 } 3944 3945 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3946 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3947 throw new SecurityException("Label must be specified in permission"); 3948 } 3949 BasePermission tree = checkPermissionTreeLP(info.name); 3950 BasePermission bp = mSettings.mPermissions.get(info.name); 3951 boolean added = bp == null; 3952 boolean changed = true; 3953 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3954 if (added) { 3955 enforcePermissionCapLocked(info, tree); 3956 bp = new BasePermission(info.name, tree.sourcePackage, 3957 BasePermission.TYPE_DYNAMIC); 3958 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3959 throw new SecurityException( 3960 "Not allowed to modify non-dynamic permission " 3961 + info.name); 3962 } else { 3963 if (bp.protectionLevel == fixedLevel 3964 && bp.perm.owner.equals(tree.perm.owner) 3965 && bp.uid == tree.uid 3966 && comparePermissionInfos(bp.perm.info, info)) { 3967 changed = false; 3968 } 3969 } 3970 bp.protectionLevel = fixedLevel; 3971 info = new PermissionInfo(info); 3972 info.protectionLevel = fixedLevel; 3973 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3974 bp.perm.info.packageName = tree.perm.info.packageName; 3975 bp.uid = tree.uid; 3976 if (added) { 3977 mSettings.mPermissions.put(info.name, bp); 3978 } 3979 if (changed) { 3980 if (!async) { 3981 mSettings.writeLPr(); 3982 } else { 3983 scheduleWriteSettingsLocked(); 3984 } 3985 } 3986 return added; 3987 } 3988 3989 @Override 3990 public boolean addPermission(PermissionInfo info) { 3991 synchronized (mPackages) { 3992 return addPermissionLocked(info, false); 3993 } 3994 } 3995 3996 @Override 3997 public boolean addPermissionAsync(PermissionInfo info) { 3998 synchronized (mPackages) { 3999 return addPermissionLocked(info, true); 4000 } 4001 } 4002 4003 @Override 4004 public void removePermission(String name) { 4005 synchronized (mPackages) { 4006 checkPermissionTreeLP(name); 4007 BasePermission bp = mSettings.mPermissions.get(name); 4008 if (bp != null) { 4009 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4010 throw new SecurityException( 4011 "Not allowed to modify non-dynamic permission " 4012 + name); 4013 } 4014 mSettings.mPermissions.remove(name); 4015 mSettings.writeLPr(); 4016 } 4017 } 4018 } 4019 4020 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4021 BasePermission bp) { 4022 int index = pkg.requestedPermissions.indexOf(bp.name); 4023 if (index == -1) { 4024 throw new SecurityException("Package " + pkg.packageName 4025 + " has not requested permission " + bp.name); 4026 } 4027 if (!bp.isRuntime() && !bp.isDevelopment()) { 4028 throw new SecurityException("Permission " + bp.name 4029 + " is not a changeable permission type"); 4030 } 4031 } 4032 4033 @Override 4034 public void grantRuntimePermission(String packageName, String name, final int userId) { 4035 if (!sUserManager.exists(userId)) { 4036 Log.e(TAG, "No such user:" + userId); 4037 return; 4038 } 4039 4040 mContext.enforceCallingOrSelfPermission( 4041 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4042 "grantRuntimePermission"); 4043 4044 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4045 true /* requireFullPermission */, true /* checkShell */, 4046 "grantRuntimePermission"); 4047 4048 final int uid; 4049 final SettingBase sb; 4050 4051 synchronized (mPackages) { 4052 final PackageParser.Package pkg = mPackages.get(packageName); 4053 if (pkg == null) { 4054 throw new IllegalArgumentException("Unknown package: " + packageName); 4055 } 4056 4057 final BasePermission bp = mSettings.mPermissions.get(name); 4058 if (bp == null) { 4059 throw new IllegalArgumentException("Unknown permission: " + name); 4060 } 4061 4062 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4063 4064 // If a permission review is required for legacy apps we represent 4065 // their permissions as always granted runtime ones since we need 4066 // to keep the review required permission flag per user while an 4067 // install permission's state is shared across all users. 4068 if (Build.PERMISSIONS_REVIEW_REQUIRED 4069 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4070 && bp.isRuntime()) { 4071 return; 4072 } 4073 4074 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4075 sb = (SettingBase) pkg.mExtras; 4076 if (sb == null) { 4077 throw new IllegalArgumentException("Unknown package: " + packageName); 4078 } 4079 4080 final PermissionsState permissionsState = sb.getPermissionsState(); 4081 4082 final int flags = permissionsState.getPermissionFlags(name, userId); 4083 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4084 throw new SecurityException("Cannot grant system fixed permission " 4085 + name + " for package " + packageName); 4086 } 4087 4088 if (bp.isDevelopment()) { 4089 // Development permissions must be handled specially, since they are not 4090 // normal runtime permissions. For now they apply to all users. 4091 if (permissionsState.grantInstallPermission(bp) != 4092 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4093 scheduleWriteSettingsLocked(); 4094 } 4095 return; 4096 } 4097 4098 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4099 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4100 return; 4101 } 4102 4103 final int result = permissionsState.grantRuntimePermission(bp, userId); 4104 switch (result) { 4105 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4106 return; 4107 } 4108 4109 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4110 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4111 mHandler.post(new Runnable() { 4112 @Override 4113 public void run() { 4114 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4115 } 4116 }); 4117 } 4118 break; 4119 } 4120 4121 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4122 4123 // Not critical if that is lost - app has to request again. 4124 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4125 } 4126 4127 // Only need to do this if user is initialized. Otherwise it's a new user 4128 // and there are no processes running as the user yet and there's no need 4129 // to make an expensive call to remount processes for the changed permissions. 4130 if (READ_EXTERNAL_STORAGE.equals(name) 4131 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4132 final long token = Binder.clearCallingIdentity(); 4133 try { 4134 if (sUserManager.isInitialized(userId)) { 4135 MountServiceInternal mountServiceInternal = LocalServices.getService( 4136 MountServiceInternal.class); 4137 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4138 } 4139 } finally { 4140 Binder.restoreCallingIdentity(token); 4141 } 4142 } 4143 } 4144 4145 @Override 4146 public void revokeRuntimePermission(String packageName, String name, int userId) { 4147 if (!sUserManager.exists(userId)) { 4148 Log.e(TAG, "No such user:" + userId); 4149 return; 4150 } 4151 4152 mContext.enforceCallingOrSelfPermission( 4153 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4154 "revokeRuntimePermission"); 4155 4156 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4157 true /* requireFullPermission */, true /* checkShell */, 4158 "revokeRuntimePermission"); 4159 4160 final int appId; 4161 4162 synchronized (mPackages) { 4163 final PackageParser.Package pkg = mPackages.get(packageName); 4164 if (pkg == null) { 4165 throw new IllegalArgumentException("Unknown package: " + packageName); 4166 } 4167 4168 final BasePermission bp = mSettings.mPermissions.get(name); 4169 if (bp == null) { 4170 throw new IllegalArgumentException("Unknown permission: " + name); 4171 } 4172 4173 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4174 4175 // If a permission review is required for legacy apps we represent 4176 // their permissions as always granted runtime ones since we need 4177 // to keep the review required permission flag per user while an 4178 // install permission's state is shared across all users. 4179 if (Build.PERMISSIONS_REVIEW_REQUIRED 4180 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4181 && bp.isRuntime()) { 4182 return; 4183 } 4184 4185 SettingBase sb = (SettingBase) pkg.mExtras; 4186 if (sb == null) { 4187 throw new IllegalArgumentException("Unknown package: " + packageName); 4188 } 4189 4190 final PermissionsState permissionsState = sb.getPermissionsState(); 4191 4192 final int flags = permissionsState.getPermissionFlags(name, userId); 4193 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4194 throw new SecurityException("Cannot revoke system fixed permission " 4195 + name + " for package " + packageName); 4196 } 4197 4198 if (bp.isDevelopment()) { 4199 // Development permissions must be handled specially, since they are not 4200 // normal runtime permissions. For now they apply to all users. 4201 if (permissionsState.revokeInstallPermission(bp) != 4202 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4203 scheduleWriteSettingsLocked(); 4204 } 4205 return; 4206 } 4207 4208 if (permissionsState.revokeRuntimePermission(bp, userId) == 4209 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4210 return; 4211 } 4212 4213 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4214 4215 // Critical, after this call app should never have the permission. 4216 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4217 4218 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4219 } 4220 4221 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4222 } 4223 4224 @Override 4225 public void resetRuntimePermissions() { 4226 mContext.enforceCallingOrSelfPermission( 4227 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4228 "revokeRuntimePermission"); 4229 4230 int callingUid = Binder.getCallingUid(); 4231 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4232 mContext.enforceCallingOrSelfPermission( 4233 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4234 "resetRuntimePermissions"); 4235 } 4236 4237 synchronized (mPackages) { 4238 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4239 for (int userId : UserManagerService.getInstance().getUserIds()) { 4240 final int packageCount = mPackages.size(); 4241 for (int i = 0; i < packageCount; i++) { 4242 PackageParser.Package pkg = mPackages.valueAt(i); 4243 if (!(pkg.mExtras instanceof PackageSetting)) { 4244 continue; 4245 } 4246 PackageSetting ps = (PackageSetting) pkg.mExtras; 4247 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4248 } 4249 } 4250 } 4251 } 4252 4253 @Override 4254 public int getPermissionFlags(String name, String packageName, int userId) { 4255 if (!sUserManager.exists(userId)) { 4256 return 0; 4257 } 4258 4259 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4260 4261 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4262 true /* requireFullPermission */, false /* checkShell */, 4263 "getPermissionFlags"); 4264 4265 synchronized (mPackages) { 4266 final PackageParser.Package pkg = mPackages.get(packageName); 4267 if (pkg == null) { 4268 throw new IllegalArgumentException("Unknown package: " + packageName); 4269 } 4270 4271 final BasePermission bp = mSettings.mPermissions.get(name); 4272 if (bp == null) { 4273 throw new IllegalArgumentException("Unknown permission: " + name); 4274 } 4275 4276 SettingBase sb = (SettingBase) pkg.mExtras; 4277 if (sb == null) { 4278 throw new IllegalArgumentException("Unknown package: " + packageName); 4279 } 4280 4281 PermissionsState permissionsState = sb.getPermissionsState(); 4282 return permissionsState.getPermissionFlags(name, userId); 4283 } 4284 } 4285 4286 @Override 4287 public void updatePermissionFlags(String name, String packageName, int flagMask, 4288 int flagValues, int userId) { 4289 if (!sUserManager.exists(userId)) { 4290 return; 4291 } 4292 4293 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4294 4295 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4296 true /* requireFullPermission */, true /* checkShell */, 4297 "updatePermissionFlags"); 4298 4299 // Only the system can change these flags and nothing else. 4300 if (getCallingUid() != Process.SYSTEM_UID) { 4301 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4302 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4303 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4304 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4305 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4306 } 4307 4308 synchronized (mPackages) { 4309 final PackageParser.Package pkg = mPackages.get(packageName); 4310 if (pkg == null) { 4311 throw new IllegalArgumentException("Unknown package: " + packageName); 4312 } 4313 4314 final BasePermission bp = mSettings.mPermissions.get(name); 4315 if (bp == null) { 4316 throw new IllegalArgumentException("Unknown permission: " + name); 4317 } 4318 4319 SettingBase sb = (SettingBase) pkg.mExtras; 4320 if (sb == null) { 4321 throw new IllegalArgumentException("Unknown package: " + packageName); 4322 } 4323 4324 PermissionsState permissionsState = sb.getPermissionsState(); 4325 4326 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4327 4328 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4329 // Install and runtime permissions are stored in different places, 4330 // so figure out what permission changed and persist the change. 4331 if (permissionsState.getInstallPermissionState(name) != null) { 4332 scheduleWriteSettingsLocked(); 4333 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4334 || hadState) { 4335 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4336 } 4337 } 4338 } 4339 } 4340 4341 /** 4342 * Update the permission flags for all packages and runtime permissions of a user in order 4343 * to allow device or profile owner to remove POLICY_FIXED. 4344 */ 4345 @Override 4346 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4347 if (!sUserManager.exists(userId)) { 4348 return; 4349 } 4350 4351 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4352 4353 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4354 true /* requireFullPermission */, true /* checkShell */, 4355 "updatePermissionFlagsForAllApps"); 4356 4357 // Only the system can change system fixed flags. 4358 if (getCallingUid() != Process.SYSTEM_UID) { 4359 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4360 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4361 } 4362 4363 synchronized (mPackages) { 4364 boolean changed = false; 4365 final int packageCount = mPackages.size(); 4366 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4367 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4368 SettingBase sb = (SettingBase) pkg.mExtras; 4369 if (sb == null) { 4370 continue; 4371 } 4372 PermissionsState permissionsState = sb.getPermissionsState(); 4373 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4374 userId, flagMask, flagValues); 4375 } 4376 if (changed) { 4377 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4378 } 4379 } 4380 } 4381 4382 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4383 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4384 != PackageManager.PERMISSION_GRANTED 4385 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4386 != PackageManager.PERMISSION_GRANTED) { 4387 throw new SecurityException(message + " requires " 4388 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4389 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4390 } 4391 } 4392 4393 @Override 4394 public boolean shouldShowRequestPermissionRationale(String permissionName, 4395 String packageName, int userId) { 4396 if (UserHandle.getCallingUserId() != userId) { 4397 mContext.enforceCallingPermission( 4398 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4399 "canShowRequestPermissionRationale for user " + userId); 4400 } 4401 4402 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4403 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4404 return false; 4405 } 4406 4407 if (checkPermission(permissionName, packageName, userId) 4408 == PackageManager.PERMISSION_GRANTED) { 4409 return false; 4410 } 4411 4412 final int flags; 4413 4414 final long identity = Binder.clearCallingIdentity(); 4415 try { 4416 flags = getPermissionFlags(permissionName, 4417 packageName, userId); 4418 } finally { 4419 Binder.restoreCallingIdentity(identity); 4420 } 4421 4422 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4423 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4424 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4425 4426 if ((flags & fixedFlags) != 0) { 4427 return false; 4428 } 4429 4430 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4431 } 4432 4433 @Override 4434 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4435 mContext.enforceCallingOrSelfPermission( 4436 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4437 "addOnPermissionsChangeListener"); 4438 4439 synchronized (mPackages) { 4440 mOnPermissionChangeListeners.addListenerLocked(listener); 4441 } 4442 } 4443 4444 @Override 4445 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4446 synchronized (mPackages) { 4447 mOnPermissionChangeListeners.removeListenerLocked(listener); 4448 } 4449 } 4450 4451 @Override 4452 public boolean isProtectedBroadcast(String actionName) { 4453 synchronized (mPackages) { 4454 if (mProtectedBroadcasts.contains(actionName)) { 4455 return true; 4456 } else if (actionName != null) { 4457 // TODO: remove these terrible hacks 4458 if (actionName.startsWith("android.net.netmon.lingerExpired") 4459 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4460 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4461 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4462 return true; 4463 } 4464 } 4465 } 4466 return false; 4467 } 4468 4469 @Override 4470 public int checkSignatures(String pkg1, String pkg2) { 4471 synchronized (mPackages) { 4472 final PackageParser.Package p1 = mPackages.get(pkg1); 4473 final PackageParser.Package p2 = mPackages.get(pkg2); 4474 if (p1 == null || p1.mExtras == null 4475 || p2 == null || p2.mExtras == null) { 4476 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4477 } 4478 return compareSignatures(p1.mSignatures, p2.mSignatures); 4479 } 4480 } 4481 4482 @Override 4483 public int checkUidSignatures(int uid1, int uid2) { 4484 // Map to base uids. 4485 uid1 = UserHandle.getAppId(uid1); 4486 uid2 = UserHandle.getAppId(uid2); 4487 // reader 4488 synchronized (mPackages) { 4489 Signature[] s1; 4490 Signature[] s2; 4491 Object obj = mSettings.getUserIdLPr(uid1); 4492 if (obj != null) { 4493 if (obj instanceof SharedUserSetting) { 4494 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4495 } else if (obj instanceof PackageSetting) { 4496 s1 = ((PackageSetting)obj).signatures.mSignatures; 4497 } else { 4498 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4499 } 4500 } else { 4501 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4502 } 4503 obj = mSettings.getUserIdLPr(uid2); 4504 if (obj != null) { 4505 if (obj instanceof SharedUserSetting) { 4506 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4507 } else if (obj instanceof PackageSetting) { 4508 s2 = ((PackageSetting)obj).signatures.mSignatures; 4509 } else { 4510 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4511 } 4512 } else { 4513 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4514 } 4515 return compareSignatures(s1, s2); 4516 } 4517 } 4518 4519 /** 4520 * This method should typically only be used when granting or revoking 4521 * permissions, since the app may immediately restart after this call. 4522 * <p> 4523 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4524 * guard your work against the app being relaunched. 4525 */ 4526 private void killUid(int appId, int userId, String reason) { 4527 final long identity = Binder.clearCallingIdentity(); 4528 try { 4529 IActivityManager am = ActivityManagerNative.getDefault(); 4530 if (am != null) { 4531 try { 4532 am.killUid(appId, userId, reason); 4533 } catch (RemoteException e) { 4534 /* ignore - same process */ 4535 } 4536 } 4537 } finally { 4538 Binder.restoreCallingIdentity(identity); 4539 } 4540 } 4541 4542 /** 4543 * Compares two sets of signatures. Returns: 4544 * <br /> 4545 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4546 * <br /> 4547 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4548 * <br /> 4549 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4550 * <br /> 4551 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4552 * <br /> 4553 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4554 */ 4555 static int compareSignatures(Signature[] s1, Signature[] s2) { 4556 if (s1 == null) { 4557 return s2 == null 4558 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4559 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4560 } 4561 4562 if (s2 == null) { 4563 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4564 } 4565 4566 if (s1.length != s2.length) { 4567 return PackageManager.SIGNATURE_NO_MATCH; 4568 } 4569 4570 // Since both signature sets are of size 1, we can compare without HashSets. 4571 if (s1.length == 1) { 4572 return s1[0].equals(s2[0]) ? 4573 PackageManager.SIGNATURE_MATCH : 4574 PackageManager.SIGNATURE_NO_MATCH; 4575 } 4576 4577 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4578 for (Signature sig : s1) { 4579 set1.add(sig); 4580 } 4581 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4582 for (Signature sig : s2) { 4583 set2.add(sig); 4584 } 4585 // Make sure s2 contains all signatures in s1. 4586 if (set1.equals(set2)) { 4587 return PackageManager.SIGNATURE_MATCH; 4588 } 4589 return PackageManager.SIGNATURE_NO_MATCH; 4590 } 4591 4592 /** 4593 * If the database version for this type of package (internal storage or 4594 * external storage) is less than the version where package signatures 4595 * were updated, return true. 4596 */ 4597 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4598 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4599 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4600 } 4601 4602 /** 4603 * Used for backward compatibility to make sure any packages with 4604 * certificate chains get upgraded to the new style. {@code existingSigs} 4605 * will be in the old format (since they were stored on disk from before the 4606 * system upgrade) and {@code scannedSigs} will be in the newer format. 4607 */ 4608 private int compareSignaturesCompat(PackageSignatures existingSigs, 4609 PackageParser.Package scannedPkg) { 4610 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4611 return PackageManager.SIGNATURE_NO_MATCH; 4612 } 4613 4614 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4615 for (Signature sig : existingSigs.mSignatures) { 4616 existingSet.add(sig); 4617 } 4618 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4619 for (Signature sig : scannedPkg.mSignatures) { 4620 try { 4621 Signature[] chainSignatures = sig.getChainSignatures(); 4622 for (Signature chainSig : chainSignatures) { 4623 scannedCompatSet.add(chainSig); 4624 } 4625 } catch (CertificateEncodingException e) { 4626 scannedCompatSet.add(sig); 4627 } 4628 } 4629 /* 4630 * Make sure the expanded scanned set contains all signatures in the 4631 * existing one. 4632 */ 4633 if (scannedCompatSet.equals(existingSet)) { 4634 // Migrate the old signatures to the new scheme. 4635 existingSigs.assignSignatures(scannedPkg.mSignatures); 4636 // The new KeySets will be re-added later in the scanning process. 4637 synchronized (mPackages) { 4638 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4639 } 4640 return PackageManager.SIGNATURE_MATCH; 4641 } 4642 return PackageManager.SIGNATURE_NO_MATCH; 4643 } 4644 4645 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4646 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4647 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4648 } 4649 4650 private int compareSignaturesRecover(PackageSignatures existingSigs, 4651 PackageParser.Package scannedPkg) { 4652 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4653 return PackageManager.SIGNATURE_NO_MATCH; 4654 } 4655 4656 String msg = null; 4657 try { 4658 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4659 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4660 + scannedPkg.packageName); 4661 return PackageManager.SIGNATURE_MATCH; 4662 } 4663 } catch (CertificateException e) { 4664 msg = e.getMessage(); 4665 } 4666 4667 logCriticalInfo(Log.INFO, 4668 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4669 return PackageManager.SIGNATURE_NO_MATCH; 4670 } 4671 4672 @Override 4673 public List<String> getAllPackages() { 4674 synchronized (mPackages) { 4675 return new ArrayList<String>(mPackages.keySet()); 4676 } 4677 } 4678 4679 @Override 4680 public String[] getPackagesForUid(int uid) { 4681 uid = UserHandle.getAppId(uid); 4682 // reader 4683 synchronized (mPackages) { 4684 Object obj = mSettings.getUserIdLPr(uid); 4685 if (obj instanceof SharedUserSetting) { 4686 final SharedUserSetting sus = (SharedUserSetting) obj; 4687 final int N = sus.packages.size(); 4688 final String[] res = new String[N]; 4689 final Iterator<PackageSetting> it = sus.packages.iterator(); 4690 int i = 0; 4691 while (it.hasNext()) { 4692 res[i++] = it.next().name; 4693 } 4694 return res; 4695 } else if (obj instanceof PackageSetting) { 4696 final PackageSetting ps = (PackageSetting) obj; 4697 return new String[] { ps.name }; 4698 } 4699 } 4700 return null; 4701 } 4702 4703 @Override 4704 public String getNameForUid(int uid) { 4705 // reader 4706 synchronized (mPackages) { 4707 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4708 if (obj instanceof SharedUserSetting) { 4709 final SharedUserSetting sus = (SharedUserSetting) obj; 4710 return sus.name + ":" + sus.userId; 4711 } else if (obj instanceof PackageSetting) { 4712 final PackageSetting ps = (PackageSetting) obj; 4713 return ps.name; 4714 } 4715 } 4716 return null; 4717 } 4718 4719 @Override 4720 public int getUidForSharedUser(String sharedUserName) { 4721 if(sharedUserName == null) { 4722 return -1; 4723 } 4724 // reader 4725 synchronized (mPackages) { 4726 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4727 if (suid == null) { 4728 return -1; 4729 } 4730 return suid.userId; 4731 } 4732 } 4733 4734 @Override 4735 public int getFlagsForUid(int uid) { 4736 synchronized (mPackages) { 4737 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4738 if (obj instanceof SharedUserSetting) { 4739 final SharedUserSetting sus = (SharedUserSetting) obj; 4740 return sus.pkgFlags; 4741 } else if (obj instanceof PackageSetting) { 4742 final PackageSetting ps = (PackageSetting) obj; 4743 return ps.pkgFlags; 4744 } 4745 } 4746 return 0; 4747 } 4748 4749 @Override 4750 public int getPrivateFlagsForUid(int uid) { 4751 synchronized (mPackages) { 4752 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4753 if (obj instanceof SharedUserSetting) { 4754 final SharedUserSetting sus = (SharedUserSetting) obj; 4755 return sus.pkgPrivateFlags; 4756 } else if (obj instanceof PackageSetting) { 4757 final PackageSetting ps = (PackageSetting) obj; 4758 return ps.pkgPrivateFlags; 4759 } 4760 } 4761 return 0; 4762 } 4763 4764 @Override 4765 public boolean isUidPrivileged(int uid) { 4766 uid = UserHandle.getAppId(uid); 4767 // reader 4768 synchronized (mPackages) { 4769 Object obj = mSettings.getUserIdLPr(uid); 4770 if (obj instanceof SharedUserSetting) { 4771 final SharedUserSetting sus = (SharedUserSetting) obj; 4772 final Iterator<PackageSetting> it = sus.packages.iterator(); 4773 while (it.hasNext()) { 4774 if (it.next().isPrivileged()) { 4775 return true; 4776 } 4777 } 4778 } else if (obj instanceof PackageSetting) { 4779 final PackageSetting ps = (PackageSetting) obj; 4780 return ps.isPrivileged(); 4781 } 4782 } 4783 return false; 4784 } 4785 4786 @Override 4787 public String[] getAppOpPermissionPackages(String permissionName) { 4788 synchronized (mPackages) { 4789 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4790 if (pkgs == null) { 4791 return null; 4792 } 4793 return pkgs.toArray(new String[pkgs.size()]); 4794 } 4795 } 4796 4797 @Override 4798 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4799 int flags, int userId) { 4800 try { 4801 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4802 4803 if (!sUserManager.exists(userId)) return null; 4804 flags = updateFlagsForResolve(flags, userId, intent); 4805 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4806 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4807 4808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4809 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4810 flags, userId); 4811 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4812 4813 final ResolveInfo bestChoice = 4814 chooseBestActivity(intent, resolvedType, flags, query, userId); 4815 4816 if (isEphemeralAllowed(intent, query, userId)) { 4817 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4818 final EphemeralResolveInfo ai = 4819 getEphemeralResolveInfo(intent, resolvedType, userId); 4820 if (ai != null) { 4821 if (DEBUG_EPHEMERAL) { 4822 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4823 } 4824 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4825 bestChoice.ephemeralResolveInfo = ai; 4826 } 4827 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4828 } 4829 return bestChoice; 4830 } finally { 4831 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4832 } 4833 } 4834 4835 @Override 4836 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4837 IntentFilter filter, int match, ComponentName activity) { 4838 final int userId = UserHandle.getCallingUserId(); 4839 if (DEBUG_PREFERRED) { 4840 Log.v(TAG, "setLastChosenActivity intent=" + intent 4841 + " resolvedType=" + resolvedType 4842 + " flags=" + flags 4843 + " filter=" + filter 4844 + " match=" + match 4845 + " activity=" + activity); 4846 filter.dump(new PrintStreamPrinter(System.out), " "); 4847 } 4848 intent.setComponent(null); 4849 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4850 userId); 4851 // Find any earlier preferred or last chosen entries and nuke them 4852 findPreferredActivity(intent, resolvedType, 4853 flags, query, 0, false, true, false, userId); 4854 // Add the new activity as the last chosen for this filter 4855 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4856 "Setting last chosen"); 4857 } 4858 4859 @Override 4860 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4861 final int userId = UserHandle.getCallingUserId(); 4862 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4863 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4864 userId); 4865 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4866 false, false, false, userId); 4867 } 4868 4869 4870 private boolean isEphemeralAllowed( 4871 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4872 // Short circuit and return early if possible. 4873 if (DISABLE_EPHEMERAL_APPS) { 4874 return false; 4875 } 4876 final int callingUser = UserHandle.getCallingUserId(); 4877 if (callingUser != UserHandle.USER_SYSTEM) { 4878 return false; 4879 } 4880 if (mEphemeralResolverConnection == null) { 4881 return false; 4882 } 4883 if (intent.getComponent() != null) { 4884 return false; 4885 } 4886 if (intent.getPackage() != null) { 4887 return false; 4888 } 4889 final boolean isWebUri = hasWebURI(intent); 4890 if (!isWebUri) { 4891 return false; 4892 } 4893 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4894 synchronized (mPackages) { 4895 final int count = resolvedActivites.size(); 4896 for (int n = 0; n < count; n++) { 4897 ResolveInfo info = resolvedActivites.get(n); 4898 String packageName = info.activityInfo.packageName; 4899 PackageSetting ps = mSettings.mPackages.get(packageName); 4900 if (ps != null) { 4901 // Try to get the status from User settings first 4902 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4903 int status = (int) (packedStatus >> 32); 4904 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4905 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4906 if (DEBUG_EPHEMERAL) { 4907 Slog.v(TAG, "DENY ephemeral apps;" 4908 + " pkg: " + packageName + ", status: " + status); 4909 } 4910 return false; 4911 } 4912 } 4913 } 4914 } 4915 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4916 return true; 4917 } 4918 4919 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4920 int userId) { 4921 MessageDigest digest = null; 4922 try { 4923 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4924 } catch (NoSuchAlgorithmException e) { 4925 // If we can't create a digest, ignore ephemeral apps. 4926 return null; 4927 } 4928 4929 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4930 final byte[] digestBytes = digest.digest(hostBytes); 4931 int shaPrefix = 4932 digestBytes[0] << 24 4933 | digestBytes[1] << 16 4934 | digestBytes[2] << 8 4935 | digestBytes[3] << 0; 4936 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4937 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4938 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4939 // No hash prefix match; there are no ephemeral apps for this domain. 4940 return null; 4941 } 4942 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4943 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4944 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4945 continue; 4946 } 4947 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4948 // No filters; this should never happen. 4949 if (filters.isEmpty()) { 4950 continue; 4951 } 4952 // We have a domain match; resolve the filters to see if anything matches. 4953 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4954 for (int j = filters.size() - 1; j >= 0; --j) { 4955 final EphemeralResolveIntentInfo intentInfo = 4956 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4957 ephemeralResolver.addFilter(intentInfo); 4958 } 4959 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4960 intent, resolvedType, false /*defaultOnly*/, userId); 4961 if (!matchedResolveInfoList.isEmpty()) { 4962 return matchedResolveInfoList.get(0); 4963 } 4964 } 4965 // Hash or filter mis-match; no ephemeral apps for this domain. 4966 return null; 4967 } 4968 4969 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4970 int flags, List<ResolveInfo> query, int userId) { 4971 if (query != null) { 4972 final int N = query.size(); 4973 if (N == 1) { 4974 return query.get(0); 4975 } else if (N > 1) { 4976 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4977 // If there is more than one activity with the same priority, 4978 // then let the user decide between them. 4979 ResolveInfo r0 = query.get(0); 4980 ResolveInfo r1 = query.get(1); 4981 if (DEBUG_INTENT_MATCHING || debug) { 4982 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4983 + r1.activityInfo.name + "=" + r1.priority); 4984 } 4985 // If the first activity has a higher priority, or a different 4986 // default, then it is always desirable to pick it. 4987 if (r0.priority != r1.priority 4988 || r0.preferredOrder != r1.preferredOrder 4989 || r0.isDefault != r1.isDefault) { 4990 return query.get(0); 4991 } 4992 // If we have saved a preference for a preferred activity for 4993 // this Intent, use that. 4994 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4995 flags, query, r0.priority, true, false, debug, userId); 4996 if (ri != null) { 4997 return ri; 4998 } 4999 ri = new ResolveInfo(mResolveInfo); 5000 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5001 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5002 ri.activityInfo.applicationInfo = new ApplicationInfo( 5003 ri.activityInfo.applicationInfo); 5004 if (userId != 0) { 5005 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5006 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5007 } 5008 // Make sure that the resolver is displayable in car mode 5009 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5010 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5011 return ri; 5012 } 5013 } 5014 return null; 5015 } 5016 5017 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5018 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5019 final int N = query.size(); 5020 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5021 .get(userId); 5022 // Get the list of persistent preferred activities that handle the intent 5023 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5024 List<PersistentPreferredActivity> pprefs = ppir != null 5025 ? ppir.queryIntent(intent, resolvedType, 5026 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5027 : null; 5028 if (pprefs != null && pprefs.size() > 0) { 5029 final int M = pprefs.size(); 5030 for (int i=0; i<M; i++) { 5031 final PersistentPreferredActivity ppa = pprefs.get(i); 5032 if (DEBUG_PREFERRED || debug) { 5033 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5034 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5035 + "\n component=" + ppa.mComponent); 5036 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5037 } 5038 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5039 flags | MATCH_DISABLED_COMPONENTS, userId); 5040 if (DEBUG_PREFERRED || debug) { 5041 Slog.v(TAG, "Found persistent preferred activity:"); 5042 if (ai != null) { 5043 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5044 } else { 5045 Slog.v(TAG, " null"); 5046 } 5047 } 5048 if (ai == null) { 5049 // This previously registered persistent preferred activity 5050 // component is no longer known. Ignore it and do NOT remove it. 5051 continue; 5052 } 5053 for (int j=0; j<N; j++) { 5054 final ResolveInfo ri = query.get(j); 5055 if (!ri.activityInfo.applicationInfo.packageName 5056 .equals(ai.applicationInfo.packageName)) { 5057 continue; 5058 } 5059 if (!ri.activityInfo.name.equals(ai.name)) { 5060 continue; 5061 } 5062 // Found a persistent preference that can handle the intent. 5063 if (DEBUG_PREFERRED || debug) { 5064 Slog.v(TAG, "Returning persistent preferred activity: " + 5065 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5066 } 5067 return ri; 5068 } 5069 } 5070 } 5071 return null; 5072 } 5073 5074 // TODO: handle preferred activities missing while user has amnesia 5075 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5076 List<ResolveInfo> query, int priority, boolean always, 5077 boolean removeMatches, boolean debug, int userId) { 5078 if (!sUserManager.exists(userId)) return null; 5079 flags = updateFlagsForResolve(flags, userId, intent); 5080 // writer 5081 synchronized (mPackages) { 5082 if (intent.getSelector() != null) { 5083 intent = intent.getSelector(); 5084 } 5085 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5086 5087 // Try to find a matching persistent preferred activity. 5088 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5089 debug, userId); 5090 5091 // If a persistent preferred activity matched, use it. 5092 if (pri != null) { 5093 return pri; 5094 } 5095 5096 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5097 // Get the list of preferred activities that handle the intent 5098 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5099 List<PreferredActivity> prefs = pir != null 5100 ? pir.queryIntent(intent, resolvedType, 5101 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5102 : null; 5103 if (prefs != null && prefs.size() > 0) { 5104 boolean changed = false; 5105 try { 5106 // First figure out how good the original match set is. 5107 // We will only allow preferred activities that came 5108 // from the same match quality. 5109 int match = 0; 5110 5111 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5112 5113 final int N = query.size(); 5114 for (int j=0; j<N; j++) { 5115 final ResolveInfo ri = query.get(j); 5116 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5117 + ": 0x" + Integer.toHexString(match)); 5118 if (ri.match > match) { 5119 match = ri.match; 5120 } 5121 } 5122 5123 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5124 + Integer.toHexString(match)); 5125 5126 match &= IntentFilter.MATCH_CATEGORY_MASK; 5127 final int M = prefs.size(); 5128 for (int i=0; i<M; i++) { 5129 final PreferredActivity pa = prefs.get(i); 5130 if (DEBUG_PREFERRED || debug) { 5131 Slog.v(TAG, "Checking PreferredActivity ds=" 5132 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5133 + "\n component=" + pa.mPref.mComponent); 5134 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5135 } 5136 if (pa.mPref.mMatch != match) { 5137 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5138 + Integer.toHexString(pa.mPref.mMatch)); 5139 continue; 5140 } 5141 // If it's not an "always" type preferred activity and that's what we're 5142 // looking for, skip it. 5143 if (always && !pa.mPref.mAlways) { 5144 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5145 continue; 5146 } 5147 final ActivityInfo ai = getActivityInfo( 5148 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5149 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5150 userId); 5151 if (DEBUG_PREFERRED || debug) { 5152 Slog.v(TAG, "Found preferred activity:"); 5153 if (ai != null) { 5154 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5155 } else { 5156 Slog.v(TAG, " null"); 5157 } 5158 } 5159 if (ai == null) { 5160 // This previously registered preferred activity 5161 // component is no longer known. Most likely an update 5162 // to the app was installed and in the new version this 5163 // component no longer exists. Clean it up by removing 5164 // it from the preferred activities list, and skip it. 5165 Slog.w(TAG, "Removing dangling preferred activity: " 5166 + pa.mPref.mComponent); 5167 pir.removeFilter(pa); 5168 changed = true; 5169 continue; 5170 } 5171 for (int j=0; j<N; j++) { 5172 final ResolveInfo ri = query.get(j); 5173 if (!ri.activityInfo.applicationInfo.packageName 5174 .equals(ai.applicationInfo.packageName)) { 5175 continue; 5176 } 5177 if (!ri.activityInfo.name.equals(ai.name)) { 5178 continue; 5179 } 5180 5181 if (removeMatches) { 5182 pir.removeFilter(pa); 5183 changed = true; 5184 if (DEBUG_PREFERRED) { 5185 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5186 } 5187 break; 5188 } 5189 5190 // Okay we found a previously set preferred or last chosen app. 5191 // If the result set is different from when this 5192 // was created, we need to clear it and re-ask the 5193 // user their preference, if we're looking for an "always" type entry. 5194 if (always && !pa.mPref.sameSet(query)) { 5195 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5196 + intent + " type " + resolvedType); 5197 if (DEBUG_PREFERRED) { 5198 Slog.v(TAG, "Removing preferred activity since set changed " 5199 + pa.mPref.mComponent); 5200 } 5201 pir.removeFilter(pa); 5202 // Re-add the filter as a "last chosen" entry (!always) 5203 PreferredActivity lastChosen = new PreferredActivity( 5204 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5205 pir.addFilter(lastChosen); 5206 changed = true; 5207 return null; 5208 } 5209 5210 // Yay! Either the set matched or we're looking for the last chosen 5211 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5212 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5213 return ri; 5214 } 5215 } 5216 } finally { 5217 if (changed) { 5218 if (DEBUG_PREFERRED) { 5219 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5220 } 5221 scheduleWritePackageRestrictionsLocked(userId); 5222 } 5223 } 5224 } 5225 } 5226 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5227 return null; 5228 } 5229 5230 /* 5231 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5232 */ 5233 @Override 5234 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5235 int targetUserId) { 5236 mContext.enforceCallingOrSelfPermission( 5237 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5238 List<CrossProfileIntentFilter> matches = 5239 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5240 if (matches != null) { 5241 int size = matches.size(); 5242 for (int i = 0; i < size; i++) { 5243 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5244 } 5245 } 5246 if (hasWebURI(intent)) { 5247 // cross-profile app linking works only towards the parent. 5248 final UserInfo parent = getProfileParent(sourceUserId); 5249 synchronized(mPackages) { 5250 int flags = updateFlagsForResolve(0, parent.id, intent); 5251 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5252 intent, resolvedType, flags, sourceUserId, parent.id); 5253 return xpDomainInfo != null; 5254 } 5255 } 5256 return false; 5257 } 5258 5259 private UserInfo getProfileParent(int userId) { 5260 final long identity = Binder.clearCallingIdentity(); 5261 try { 5262 return sUserManager.getProfileParent(userId); 5263 } finally { 5264 Binder.restoreCallingIdentity(identity); 5265 } 5266 } 5267 5268 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5269 String resolvedType, int userId) { 5270 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5271 if (resolver != null) { 5272 return resolver.queryIntent(intent, resolvedType, false, userId); 5273 } 5274 return null; 5275 } 5276 5277 @Override 5278 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5279 String resolvedType, int flags, int userId) { 5280 try { 5281 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5282 5283 return new ParceledListSlice<>( 5284 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5285 } finally { 5286 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5287 } 5288 } 5289 5290 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5291 String resolvedType, int flags, int userId) { 5292 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5293 flags = updateFlagsForResolve(flags, userId, intent); 5294 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5295 false /* requireFullPermission */, false /* checkShell */, 5296 "query intent activities"); 5297 ComponentName comp = intent.getComponent(); 5298 if (comp == null) { 5299 if (intent.getSelector() != null) { 5300 intent = intent.getSelector(); 5301 comp = intent.getComponent(); 5302 } 5303 } 5304 5305 if (comp != null) { 5306 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5307 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5308 if (ai != null) { 5309 final ResolveInfo ri = new ResolveInfo(); 5310 ri.activityInfo = ai; 5311 list.add(ri); 5312 } 5313 return list; 5314 } 5315 5316 // reader 5317 synchronized (mPackages) { 5318 final String pkgName = intent.getPackage(); 5319 if (pkgName == null) { 5320 List<CrossProfileIntentFilter> matchingFilters = 5321 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5322 // Check for results that need to skip the current profile. 5323 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5324 resolvedType, flags, userId); 5325 if (xpResolveInfo != null) { 5326 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5327 result.add(xpResolveInfo); 5328 return filterIfNotSystemUser(result, userId); 5329 } 5330 5331 // Check for results in the current profile. 5332 List<ResolveInfo> result = mActivities.queryIntent( 5333 intent, resolvedType, flags, userId); 5334 result = filterIfNotSystemUser(result, userId); 5335 5336 // Check for cross profile results. 5337 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5338 xpResolveInfo = queryCrossProfileIntents( 5339 matchingFilters, intent, resolvedType, flags, userId, 5340 hasNonNegativePriorityResult); 5341 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5342 boolean isVisibleToUser = filterIfNotSystemUser( 5343 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5344 if (isVisibleToUser) { 5345 result.add(xpResolveInfo); 5346 Collections.sort(result, mResolvePrioritySorter); 5347 } 5348 } 5349 if (hasWebURI(intent)) { 5350 CrossProfileDomainInfo xpDomainInfo = null; 5351 final UserInfo parent = getProfileParent(userId); 5352 if (parent != null) { 5353 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5354 flags, userId, parent.id); 5355 } 5356 if (xpDomainInfo != null) { 5357 if (xpResolveInfo != null) { 5358 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5359 // in the result. 5360 result.remove(xpResolveInfo); 5361 } 5362 if (result.size() == 0) { 5363 result.add(xpDomainInfo.resolveInfo); 5364 return result; 5365 } 5366 } else if (result.size() <= 1) { 5367 return result; 5368 } 5369 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5370 xpDomainInfo, userId); 5371 Collections.sort(result, mResolvePrioritySorter); 5372 } 5373 return result; 5374 } 5375 final PackageParser.Package pkg = mPackages.get(pkgName); 5376 if (pkg != null) { 5377 return filterIfNotSystemUser( 5378 mActivities.queryIntentForPackage( 5379 intent, resolvedType, flags, pkg.activities, userId), 5380 userId); 5381 } 5382 return new ArrayList<ResolveInfo>(); 5383 } 5384 } 5385 5386 private static class CrossProfileDomainInfo { 5387 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5388 ResolveInfo resolveInfo; 5389 /* Best domain verification status of the activities found in the other profile */ 5390 int bestDomainVerificationStatus; 5391 } 5392 5393 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5394 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5395 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5396 sourceUserId)) { 5397 return null; 5398 } 5399 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5400 resolvedType, flags, parentUserId); 5401 5402 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5403 return null; 5404 } 5405 CrossProfileDomainInfo result = null; 5406 int size = resultTargetUser.size(); 5407 for (int i = 0; i < size; i++) { 5408 ResolveInfo riTargetUser = resultTargetUser.get(i); 5409 // Intent filter verification is only for filters that specify a host. So don't return 5410 // those that handle all web uris. 5411 if (riTargetUser.handleAllWebDataURI) { 5412 continue; 5413 } 5414 String packageName = riTargetUser.activityInfo.packageName; 5415 PackageSetting ps = mSettings.mPackages.get(packageName); 5416 if (ps == null) { 5417 continue; 5418 } 5419 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5420 int status = (int)(verificationState >> 32); 5421 if (result == null) { 5422 result = new CrossProfileDomainInfo(); 5423 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5424 sourceUserId, parentUserId); 5425 result.bestDomainVerificationStatus = status; 5426 } else { 5427 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5428 result.bestDomainVerificationStatus); 5429 } 5430 } 5431 // Don't consider matches with status NEVER across profiles. 5432 if (result != null && result.bestDomainVerificationStatus 5433 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5434 return null; 5435 } 5436 return result; 5437 } 5438 5439 /** 5440 * Verification statuses are ordered from the worse to the best, except for 5441 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5442 */ 5443 private int bestDomainVerificationStatus(int status1, int status2) { 5444 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5445 return status2; 5446 } 5447 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5448 return status1; 5449 } 5450 return (int) MathUtils.max(status1, status2); 5451 } 5452 5453 private boolean isUserEnabled(int userId) { 5454 long callingId = Binder.clearCallingIdentity(); 5455 try { 5456 UserInfo userInfo = sUserManager.getUserInfo(userId); 5457 return userInfo != null && userInfo.isEnabled(); 5458 } finally { 5459 Binder.restoreCallingIdentity(callingId); 5460 } 5461 } 5462 5463 /** 5464 * Filter out activities with systemUserOnly flag set, when current user is not System. 5465 * 5466 * @return filtered list 5467 */ 5468 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5469 if (userId == UserHandle.USER_SYSTEM) { 5470 return resolveInfos; 5471 } 5472 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5473 ResolveInfo info = resolveInfos.get(i); 5474 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5475 resolveInfos.remove(i); 5476 } 5477 } 5478 return resolveInfos; 5479 } 5480 5481 /** 5482 * @param resolveInfos list of resolve infos in descending priority order 5483 * @return if the list contains a resolve info with non-negative priority 5484 */ 5485 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5486 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5487 } 5488 5489 private static boolean hasWebURI(Intent intent) { 5490 if (intent.getData() == null) { 5491 return false; 5492 } 5493 final String scheme = intent.getScheme(); 5494 if (TextUtils.isEmpty(scheme)) { 5495 return false; 5496 } 5497 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5498 } 5499 5500 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5501 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5502 int userId) { 5503 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5504 5505 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5506 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5507 candidates.size()); 5508 } 5509 5510 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5511 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5512 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5513 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5514 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5515 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5516 5517 synchronized (mPackages) { 5518 final int count = candidates.size(); 5519 // First, try to use linked apps. Partition the candidates into four lists: 5520 // one for the final results, one for the "do not use ever", one for "undefined status" 5521 // and finally one for "browser app type". 5522 for (int n=0; n<count; n++) { 5523 ResolveInfo info = candidates.get(n); 5524 String packageName = info.activityInfo.packageName; 5525 PackageSetting ps = mSettings.mPackages.get(packageName); 5526 if (ps != null) { 5527 // Add to the special match all list (Browser use case) 5528 if (info.handleAllWebDataURI) { 5529 matchAllList.add(info); 5530 continue; 5531 } 5532 // Try to get the status from User settings first 5533 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5534 int status = (int)(packedStatus >> 32); 5535 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5536 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5537 if (DEBUG_DOMAIN_VERIFICATION) { 5538 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5539 + " : linkgen=" + linkGeneration); 5540 } 5541 // Use link-enabled generation as preferredOrder, i.e. 5542 // prefer newly-enabled over earlier-enabled. 5543 info.preferredOrder = linkGeneration; 5544 alwaysList.add(info); 5545 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5546 if (DEBUG_DOMAIN_VERIFICATION) { 5547 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5548 } 5549 neverList.add(info); 5550 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5551 if (DEBUG_DOMAIN_VERIFICATION) { 5552 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5553 } 5554 alwaysAskList.add(info); 5555 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5556 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5557 if (DEBUG_DOMAIN_VERIFICATION) { 5558 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5559 } 5560 undefinedList.add(info); 5561 } 5562 } 5563 } 5564 5565 // We'll want to include browser possibilities in a few cases 5566 boolean includeBrowser = false; 5567 5568 // First try to add the "always" resolution(s) for the current user, if any 5569 if (alwaysList.size() > 0) { 5570 result.addAll(alwaysList); 5571 } else { 5572 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5573 result.addAll(undefinedList); 5574 // Maybe add one for the other profile. 5575 if (xpDomainInfo != null && ( 5576 xpDomainInfo.bestDomainVerificationStatus 5577 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5578 result.add(xpDomainInfo.resolveInfo); 5579 } 5580 includeBrowser = true; 5581 } 5582 5583 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5584 // If there were 'always' entries their preferred order has been set, so we also 5585 // back that off to make the alternatives equivalent 5586 if (alwaysAskList.size() > 0) { 5587 for (ResolveInfo i : result) { 5588 i.preferredOrder = 0; 5589 } 5590 result.addAll(alwaysAskList); 5591 includeBrowser = true; 5592 } 5593 5594 if (includeBrowser) { 5595 // Also add browsers (all of them or only the default one) 5596 if (DEBUG_DOMAIN_VERIFICATION) { 5597 Slog.v(TAG, " ...including browsers in candidate set"); 5598 } 5599 if ((matchFlags & MATCH_ALL) != 0) { 5600 result.addAll(matchAllList); 5601 } else { 5602 // Browser/generic handling case. If there's a default browser, go straight 5603 // to that (but only if there is no other higher-priority match). 5604 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5605 int maxMatchPrio = 0; 5606 ResolveInfo defaultBrowserMatch = null; 5607 final int numCandidates = matchAllList.size(); 5608 for (int n = 0; n < numCandidates; n++) { 5609 ResolveInfo info = matchAllList.get(n); 5610 // track the highest overall match priority... 5611 if (info.priority > maxMatchPrio) { 5612 maxMatchPrio = info.priority; 5613 } 5614 // ...and the highest-priority default browser match 5615 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5616 if (defaultBrowserMatch == null 5617 || (defaultBrowserMatch.priority < info.priority)) { 5618 if (debug) { 5619 Slog.v(TAG, "Considering default browser match " + info); 5620 } 5621 defaultBrowserMatch = info; 5622 } 5623 } 5624 } 5625 if (defaultBrowserMatch != null 5626 && defaultBrowserMatch.priority >= maxMatchPrio 5627 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5628 { 5629 if (debug) { 5630 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5631 } 5632 result.add(defaultBrowserMatch); 5633 } else { 5634 result.addAll(matchAllList); 5635 } 5636 } 5637 5638 // If there is nothing selected, add all candidates and remove the ones that the user 5639 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5640 if (result.size() == 0) { 5641 result.addAll(candidates); 5642 result.removeAll(neverList); 5643 } 5644 } 5645 } 5646 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5647 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5648 result.size()); 5649 for (ResolveInfo info : result) { 5650 Slog.v(TAG, " + " + info.activityInfo); 5651 } 5652 } 5653 return result; 5654 } 5655 5656 // Returns a packed value as a long: 5657 // 5658 // high 'int'-sized word: link status: undefined/ask/never/always. 5659 // low 'int'-sized word: relative priority among 'always' results. 5660 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5661 long result = ps.getDomainVerificationStatusForUser(userId); 5662 // if none available, get the master status 5663 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5664 if (ps.getIntentFilterVerificationInfo() != null) { 5665 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5666 } 5667 } 5668 return result; 5669 } 5670 5671 private ResolveInfo querySkipCurrentProfileIntents( 5672 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5673 int flags, int sourceUserId) { 5674 if (matchingFilters != null) { 5675 int size = matchingFilters.size(); 5676 for (int i = 0; i < size; i ++) { 5677 CrossProfileIntentFilter filter = matchingFilters.get(i); 5678 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5679 // Checking if there are activities in the target user that can handle the 5680 // intent. 5681 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5682 resolvedType, flags, sourceUserId); 5683 if (resolveInfo != null) { 5684 return resolveInfo; 5685 } 5686 } 5687 } 5688 } 5689 return null; 5690 } 5691 5692 // Return matching ResolveInfo in target user if any. 5693 private ResolveInfo queryCrossProfileIntents( 5694 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5695 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5696 if (matchingFilters != null) { 5697 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5698 // match the same intent. For performance reasons, it is better not to 5699 // run queryIntent twice for the same userId 5700 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5701 int size = matchingFilters.size(); 5702 for (int i = 0; i < size; i++) { 5703 CrossProfileIntentFilter filter = matchingFilters.get(i); 5704 int targetUserId = filter.getTargetUserId(); 5705 boolean skipCurrentProfile = 5706 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5707 boolean skipCurrentProfileIfNoMatchFound = 5708 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5709 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5710 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5711 // Checking if there are activities in the target user that can handle the 5712 // intent. 5713 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5714 resolvedType, flags, sourceUserId); 5715 if (resolveInfo != null) return resolveInfo; 5716 alreadyTriedUserIds.put(targetUserId, true); 5717 } 5718 } 5719 } 5720 return null; 5721 } 5722 5723 /** 5724 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5725 * will forward the intent to the filter's target user. 5726 * Otherwise, returns null. 5727 */ 5728 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5729 String resolvedType, int flags, int sourceUserId) { 5730 int targetUserId = filter.getTargetUserId(); 5731 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5732 resolvedType, flags, targetUserId); 5733 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5734 // If all the matches in the target profile are suspended, return null. 5735 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5736 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5737 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5738 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5739 targetUserId); 5740 } 5741 } 5742 } 5743 return null; 5744 } 5745 5746 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5747 int sourceUserId, int targetUserId) { 5748 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5749 long ident = Binder.clearCallingIdentity(); 5750 boolean targetIsProfile; 5751 try { 5752 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5753 } finally { 5754 Binder.restoreCallingIdentity(ident); 5755 } 5756 String className; 5757 if (targetIsProfile) { 5758 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5759 } else { 5760 className = FORWARD_INTENT_TO_PARENT; 5761 } 5762 ComponentName forwardingActivityComponentName = new ComponentName( 5763 mAndroidApplication.packageName, className); 5764 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5765 sourceUserId); 5766 if (!targetIsProfile) { 5767 forwardingActivityInfo.showUserIcon = targetUserId; 5768 forwardingResolveInfo.noResourceId = true; 5769 } 5770 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5771 forwardingResolveInfo.priority = 0; 5772 forwardingResolveInfo.preferredOrder = 0; 5773 forwardingResolveInfo.match = 0; 5774 forwardingResolveInfo.isDefault = true; 5775 forwardingResolveInfo.filter = filter; 5776 forwardingResolveInfo.targetUserId = targetUserId; 5777 return forwardingResolveInfo; 5778 } 5779 5780 @Override 5781 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5782 Intent[] specifics, String[] specificTypes, Intent intent, 5783 String resolvedType, int flags, int userId) { 5784 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5785 specificTypes, intent, resolvedType, flags, userId)); 5786 } 5787 5788 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5789 Intent[] specifics, String[] specificTypes, Intent intent, 5790 String resolvedType, int flags, int userId) { 5791 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5792 flags = updateFlagsForResolve(flags, userId, intent); 5793 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5794 false /* requireFullPermission */, false /* checkShell */, 5795 "query intent activity options"); 5796 final String resultsAction = intent.getAction(); 5797 5798 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5799 | PackageManager.GET_RESOLVED_FILTER, userId); 5800 5801 if (DEBUG_INTENT_MATCHING) { 5802 Log.v(TAG, "Query " + intent + ": " + results); 5803 } 5804 5805 int specificsPos = 0; 5806 int N; 5807 5808 // todo: note that the algorithm used here is O(N^2). This 5809 // isn't a problem in our current environment, but if we start running 5810 // into situations where we have more than 5 or 10 matches then this 5811 // should probably be changed to something smarter... 5812 5813 // First we go through and resolve each of the specific items 5814 // that were supplied, taking care of removing any corresponding 5815 // duplicate items in the generic resolve list. 5816 if (specifics != null) { 5817 for (int i=0; i<specifics.length; i++) { 5818 final Intent sintent = specifics[i]; 5819 if (sintent == null) { 5820 continue; 5821 } 5822 5823 if (DEBUG_INTENT_MATCHING) { 5824 Log.v(TAG, "Specific #" + i + ": " + sintent); 5825 } 5826 5827 String action = sintent.getAction(); 5828 if (resultsAction != null && resultsAction.equals(action)) { 5829 // If this action was explicitly requested, then don't 5830 // remove things that have it. 5831 action = null; 5832 } 5833 5834 ResolveInfo ri = null; 5835 ActivityInfo ai = null; 5836 5837 ComponentName comp = sintent.getComponent(); 5838 if (comp == null) { 5839 ri = resolveIntent( 5840 sintent, 5841 specificTypes != null ? specificTypes[i] : null, 5842 flags, userId); 5843 if (ri == null) { 5844 continue; 5845 } 5846 if (ri == mResolveInfo) { 5847 // ACK! Must do something better with this. 5848 } 5849 ai = ri.activityInfo; 5850 comp = new ComponentName(ai.applicationInfo.packageName, 5851 ai.name); 5852 } else { 5853 ai = getActivityInfo(comp, flags, userId); 5854 if (ai == null) { 5855 continue; 5856 } 5857 } 5858 5859 // Look for any generic query activities that are duplicates 5860 // of this specific one, and remove them from the results. 5861 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5862 N = results.size(); 5863 int j; 5864 for (j=specificsPos; j<N; j++) { 5865 ResolveInfo sri = results.get(j); 5866 if ((sri.activityInfo.name.equals(comp.getClassName()) 5867 && sri.activityInfo.applicationInfo.packageName.equals( 5868 comp.getPackageName())) 5869 || (action != null && sri.filter.matchAction(action))) { 5870 results.remove(j); 5871 if (DEBUG_INTENT_MATCHING) Log.v( 5872 TAG, "Removing duplicate item from " + j 5873 + " due to specific " + specificsPos); 5874 if (ri == null) { 5875 ri = sri; 5876 } 5877 j--; 5878 N--; 5879 } 5880 } 5881 5882 // Add this specific item to its proper place. 5883 if (ri == null) { 5884 ri = new ResolveInfo(); 5885 ri.activityInfo = ai; 5886 } 5887 results.add(specificsPos, ri); 5888 ri.specificIndex = i; 5889 specificsPos++; 5890 } 5891 } 5892 5893 // Now we go through the remaining generic results and remove any 5894 // duplicate actions that are found here. 5895 N = results.size(); 5896 for (int i=specificsPos; i<N-1; i++) { 5897 final ResolveInfo rii = results.get(i); 5898 if (rii.filter == null) { 5899 continue; 5900 } 5901 5902 // Iterate over all of the actions of this result's intent 5903 // filter... typically this should be just one. 5904 final Iterator<String> it = rii.filter.actionsIterator(); 5905 if (it == null) { 5906 continue; 5907 } 5908 while (it.hasNext()) { 5909 final String action = it.next(); 5910 if (resultsAction != null && resultsAction.equals(action)) { 5911 // If this action was explicitly requested, then don't 5912 // remove things that have it. 5913 continue; 5914 } 5915 for (int j=i+1; j<N; j++) { 5916 final ResolveInfo rij = results.get(j); 5917 if (rij.filter != null && rij.filter.hasAction(action)) { 5918 results.remove(j); 5919 if (DEBUG_INTENT_MATCHING) Log.v( 5920 TAG, "Removing duplicate item from " + j 5921 + " due to action " + action + " at " + i); 5922 j--; 5923 N--; 5924 } 5925 } 5926 } 5927 5928 // If the caller didn't request filter information, drop it now 5929 // so we don't have to marshall/unmarshall it. 5930 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5931 rii.filter = null; 5932 } 5933 } 5934 5935 // Filter out the caller activity if so requested. 5936 if (caller != null) { 5937 N = results.size(); 5938 for (int i=0; i<N; i++) { 5939 ActivityInfo ainfo = results.get(i).activityInfo; 5940 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5941 && caller.getClassName().equals(ainfo.name)) { 5942 results.remove(i); 5943 break; 5944 } 5945 } 5946 } 5947 5948 // If the caller didn't request filter information, 5949 // drop them now so we don't have to 5950 // marshall/unmarshall it. 5951 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5952 N = results.size(); 5953 for (int i=0; i<N; i++) { 5954 results.get(i).filter = null; 5955 } 5956 } 5957 5958 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5959 return results; 5960 } 5961 5962 @Override 5963 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5964 String resolvedType, int flags, int userId) { 5965 return new ParceledListSlice<>( 5966 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5967 } 5968 5969 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5970 String resolvedType, int flags, int userId) { 5971 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5972 flags = updateFlagsForResolve(flags, userId, intent); 5973 ComponentName comp = intent.getComponent(); 5974 if (comp == null) { 5975 if (intent.getSelector() != null) { 5976 intent = intent.getSelector(); 5977 comp = intent.getComponent(); 5978 } 5979 } 5980 if (comp != null) { 5981 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5982 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5983 if (ai != null) { 5984 ResolveInfo ri = new ResolveInfo(); 5985 ri.activityInfo = ai; 5986 list.add(ri); 5987 } 5988 return list; 5989 } 5990 5991 // reader 5992 synchronized (mPackages) { 5993 String pkgName = intent.getPackage(); 5994 if (pkgName == null) { 5995 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5996 } 5997 final PackageParser.Package pkg = mPackages.get(pkgName); 5998 if (pkg != null) { 5999 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6000 userId); 6001 } 6002 return Collections.emptyList(); 6003 } 6004 } 6005 6006 @Override 6007 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6008 if (!sUserManager.exists(userId)) return null; 6009 flags = updateFlagsForResolve(flags, userId, intent); 6010 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6011 if (query != null) { 6012 if (query.size() >= 1) { 6013 // If there is more than one service with the same priority, 6014 // just arbitrarily pick the first one. 6015 return query.get(0); 6016 } 6017 } 6018 return null; 6019 } 6020 6021 @Override 6022 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6023 String resolvedType, int flags, int userId) { 6024 return new ParceledListSlice<>( 6025 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6026 } 6027 6028 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6029 String resolvedType, int flags, int userId) { 6030 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6031 flags = updateFlagsForResolve(flags, userId, intent); 6032 ComponentName comp = intent.getComponent(); 6033 if (comp == null) { 6034 if (intent.getSelector() != null) { 6035 intent = intent.getSelector(); 6036 comp = intent.getComponent(); 6037 } 6038 } 6039 if (comp != null) { 6040 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6041 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6042 if (si != null) { 6043 final ResolveInfo ri = new ResolveInfo(); 6044 ri.serviceInfo = si; 6045 list.add(ri); 6046 } 6047 return list; 6048 } 6049 6050 // reader 6051 synchronized (mPackages) { 6052 String pkgName = intent.getPackage(); 6053 if (pkgName == null) { 6054 return mServices.queryIntent(intent, resolvedType, flags, userId); 6055 } 6056 final PackageParser.Package pkg = mPackages.get(pkgName); 6057 if (pkg != null) { 6058 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6059 userId); 6060 } 6061 return Collections.emptyList(); 6062 } 6063 } 6064 6065 @Override 6066 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6067 String resolvedType, int flags, int userId) { 6068 return new ParceledListSlice<>( 6069 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6070 } 6071 6072 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6073 Intent intent, String resolvedType, int flags, int userId) { 6074 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6075 flags = updateFlagsForResolve(flags, userId, intent); 6076 ComponentName comp = intent.getComponent(); 6077 if (comp == null) { 6078 if (intent.getSelector() != null) { 6079 intent = intent.getSelector(); 6080 comp = intent.getComponent(); 6081 } 6082 } 6083 if (comp != null) { 6084 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6085 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6086 if (pi != null) { 6087 final ResolveInfo ri = new ResolveInfo(); 6088 ri.providerInfo = pi; 6089 list.add(ri); 6090 } 6091 return list; 6092 } 6093 6094 // reader 6095 synchronized (mPackages) { 6096 String pkgName = intent.getPackage(); 6097 if (pkgName == null) { 6098 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6099 } 6100 final PackageParser.Package pkg = mPackages.get(pkgName); 6101 if (pkg != null) { 6102 return mProviders.queryIntentForPackage( 6103 intent, resolvedType, flags, pkg.providers, userId); 6104 } 6105 return Collections.emptyList(); 6106 } 6107 } 6108 6109 @Override 6110 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6111 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6112 flags = updateFlagsForPackage(flags, userId, null); 6113 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6114 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6115 true /* requireFullPermission */, false /* checkShell */, 6116 "get installed packages"); 6117 6118 // writer 6119 synchronized (mPackages) { 6120 ArrayList<PackageInfo> list; 6121 if (listUninstalled) { 6122 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6123 for (PackageSetting ps : mSettings.mPackages.values()) { 6124 final PackageInfo pi; 6125 if (ps.pkg != null) { 6126 pi = generatePackageInfo(ps, flags, userId); 6127 } else { 6128 pi = generatePackageInfo(ps, flags, userId); 6129 } 6130 if (pi != null) { 6131 list.add(pi); 6132 } 6133 } 6134 } else { 6135 list = new ArrayList<PackageInfo>(mPackages.size()); 6136 for (PackageParser.Package p : mPackages.values()) { 6137 final PackageInfo pi = 6138 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6139 if (pi != null) { 6140 list.add(pi); 6141 } 6142 } 6143 } 6144 6145 return new ParceledListSlice<PackageInfo>(list); 6146 } 6147 } 6148 6149 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6150 String[] permissions, boolean[] tmp, int flags, int userId) { 6151 int numMatch = 0; 6152 final PermissionsState permissionsState = ps.getPermissionsState(); 6153 for (int i=0; i<permissions.length; i++) { 6154 final String permission = permissions[i]; 6155 if (permissionsState.hasPermission(permission, userId)) { 6156 tmp[i] = true; 6157 numMatch++; 6158 } else { 6159 tmp[i] = false; 6160 } 6161 } 6162 if (numMatch == 0) { 6163 return; 6164 } 6165 final PackageInfo pi; 6166 if (ps.pkg != null) { 6167 pi = generatePackageInfo(ps, flags, userId); 6168 } else { 6169 pi = generatePackageInfo(ps, flags, userId); 6170 } 6171 // The above might return null in cases of uninstalled apps or install-state 6172 // skew across users/profiles. 6173 if (pi != null) { 6174 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6175 if (numMatch == permissions.length) { 6176 pi.requestedPermissions = permissions; 6177 } else { 6178 pi.requestedPermissions = new String[numMatch]; 6179 numMatch = 0; 6180 for (int i=0; i<permissions.length; i++) { 6181 if (tmp[i]) { 6182 pi.requestedPermissions[numMatch] = permissions[i]; 6183 numMatch++; 6184 } 6185 } 6186 } 6187 } 6188 list.add(pi); 6189 } 6190 } 6191 6192 @Override 6193 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6194 String[] permissions, int flags, int userId) { 6195 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6196 flags = updateFlagsForPackage(flags, userId, permissions); 6197 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6198 6199 // writer 6200 synchronized (mPackages) { 6201 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6202 boolean[] tmpBools = new boolean[permissions.length]; 6203 if (listUninstalled) { 6204 for (PackageSetting ps : mSettings.mPackages.values()) { 6205 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6206 } 6207 } else { 6208 for (PackageParser.Package pkg : mPackages.values()) { 6209 PackageSetting ps = (PackageSetting)pkg.mExtras; 6210 if (ps != null) { 6211 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6212 userId); 6213 } 6214 } 6215 } 6216 6217 return new ParceledListSlice<PackageInfo>(list); 6218 } 6219 } 6220 6221 @Override 6222 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6223 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6224 flags = updateFlagsForApplication(flags, userId, null); 6225 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6226 6227 // writer 6228 synchronized (mPackages) { 6229 ArrayList<ApplicationInfo> list; 6230 if (listUninstalled) { 6231 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6232 for (PackageSetting ps : mSettings.mPackages.values()) { 6233 ApplicationInfo ai; 6234 if (ps.pkg != null) { 6235 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6236 ps.readUserState(userId), userId); 6237 } else { 6238 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6239 } 6240 if (ai != null) { 6241 list.add(ai); 6242 } 6243 } 6244 } else { 6245 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6246 for (PackageParser.Package p : mPackages.values()) { 6247 if (p.mExtras != null) { 6248 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6249 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6250 if (ai != null) { 6251 list.add(ai); 6252 } 6253 } 6254 } 6255 } 6256 6257 return new ParceledListSlice<ApplicationInfo>(list); 6258 } 6259 } 6260 6261 @Override 6262 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6263 if (DISABLE_EPHEMERAL_APPS) { 6264 return null; 6265 } 6266 6267 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6268 "getEphemeralApplications"); 6269 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6270 true /* requireFullPermission */, false /* checkShell */, 6271 "getEphemeralApplications"); 6272 synchronized (mPackages) { 6273 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6274 .getEphemeralApplicationsLPw(userId); 6275 if (ephemeralApps != null) { 6276 return new ParceledListSlice<>(ephemeralApps); 6277 } 6278 } 6279 return null; 6280 } 6281 6282 @Override 6283 public boolean isEphemeralApplication(String packageName, int userId) { 6284 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6285 true /* requireFullPermission */, false /* checkShell */, 6286 "isEphemeral"); 6287 if (DISABLE_EPHEMERAL_APPS) { 6288 return false; 6289 } 6290 6291 if (!isCallerSameApp(packageName)) { 6292 return false; 6293 } 6294 synchronized (mPackages) { 6295 PackageParser.Package pkg = mPackages.get(packageName); 6296 if (pkg != null) { 6297 return pkg.applicationInfo.isEphemeralApp(); 6298 } 6299 } 6300 return false; 6301 } 6302 6303 @Override 6304 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6305 if (DISABLE_EPHEMERAL_APPS) { 6306 return null; 6307 } 6308 6309 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6310 true /* requireFullPermission */, false /* checkShell */, 6311 "getCookie"); 6312 if (!isCallerSameApp(packageName)) { 6313 return null; 6314 } 6315 synchronized (mPackages) { 6316 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6317 packageName, userId); 6318 } 6319 } 6320 6321 @Override 6322 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6323 if (DISABLE_EPHEMERAL_APPS) { 6324 return true; 6325 } 6326 6327 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6328 true /* requireFullPermission */, true /* checkShell */, 6329 "setCookie"); 6330 if (!isCallerSameApp(packageName)) { 6331 return false; 6332 } 6333 synchronized (mPackages) { 6334 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6335 packageName, cookie, userId); 6336 } 6337 } 6338 6339 @Override 6340 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6341 if (DISABLE_EPHEMERAL_APPS) { 6342 return null; 6343 } 6344 6345 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6346 "getEphemeralApplicationIcon"); 6347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6348 true /* requireFullPermission */, false /* checkShell */, 6349 "getEphemeralApplicationIcon"); 6350 synchronized (mPackages) { 6351 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6352 packageName, userId); 6353 } 6354 } 6355 6356 private boolean isCallerSameApp(String packageName) { 6357 PackageParser.Package pkg = mPackages.get(packageName); 6358 return pkg != null 6359 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6360 } 6361 6362 @Override 6363 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6364 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6365 } 6366 6367 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6368 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6369 6370 // reader 6371 synchronized (mPackages) { 6372 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6373 final int userId = UserHandle.getCallingUserId(); 6374 while (i.hasNext()) { 6375 final PackageParser.Package p = i.next(); 6376 if (p.applicationInfo == null) continue; 6377 6378 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6379 && !p.applicationInfo.isDirectBootAware(); 6380 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6381 && p.applicationInfo.isDirectBootAware(); 6382 6383 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6384 && (!mSafeMode || isSystemApp(p)) 6385 && (matchesUnaware || matchesAware)) { 6386 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6387 if (ps != null) { 6388 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6389 ps.readUserState(userId), userId); 6390 if (ai != null) { 6391 finalList.add(ai); 6392 } 6393 } 6394 } 6395 } 6396 } 6397 6398 return finalList; 6399 } 6400 6401 @Override 6402 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6403 if (!sUserManager.exists(userId)) return null; 6404 flags = updateFlagsForComponent(flags, userId, name); 6405 // reader 6406 synchronized (mPackages) { 6407 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6408 PackageSetting ps = provider != null 6409 ? mSettings.mPackages.get(provider.owner.packageName) 6410 : null; 6411 return ps != null 6412 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6413 ? PackageParser.generateProviderInfo(provider, flags, 6414 ps.readUserState(userId), userId) 6415 : null; 6416 } 6417 } 6418 6419 /** 6420 * @deprecated 6421 */ 6422 @Deprecated 6423 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6424 // reader 6425 synchronized (mPackages) { 6426 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6427 .entrySet().iterator(); 6428 final int userId = UserHandle.getCallingUserId(); 6429 while (i.hasNext()) { 6430 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6431 PackageParser.Provider p = entry.getValue(); 6432 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6433 6434 if (ps != null && p.syncable 6435 && (!mSafeMode || (p.info.applicationInfo.flags 6436 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6437 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6438 ps.readUserState(userId), userId); 6439 if (info != null) { 6440 outNames.add(entry.getKey()); 6441 outInfo.add(info); 6442 } 6443 } 6444 } 6445 } 6446 } 6447 6448 @Override 6449 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6450 int uid, int flags) { 6451 final int userId = processName != null ? UserHandle.getUserId(uid) 6452 : UserHandle.getCallingUserId(); 6453 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6454 flags = updateFlagsForComponent(flags, userId, processName); 6455 6456 ArrayList<ProviderInfo> finalList = null; 6457 // reader 6458 synchronized (mPackages) { 6459 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6460 while (i.hasNext()) { 6461 final PackageParser.Provider p = i.next(); 6462 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6463 if (ps != null && p.info.authority != null 6464 && (processName == null 6465 || (p.info.processName.equals(processName) 6466 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6467 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6468 if (finalList == null) { 6469 finalList = new ArrayList<ProviderInfo>(3); 6470 } 6471 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6472 ps.readUserState(userId), userId); 6473 if (info != null) { 6474 finalList.add(info); 6475 } 6476 } 6477 } 6478 } 6479 6480 if (finalList != null) { 6481 Collections.sort(finalList, mProviderInitOrderSorter); 6482 return new ParceledListSlice<ProviderInfo>(finalList); 6483 } 6484 6485 return ParceledListSlice.emptyList(); 6486 } 6487 6488 @Override 6489 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6490 // reader 6491 synchronized (mPackages) { 6492 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6493 return PackageParser.generateInstrumentationInfo(i, flags); 6494 } 6495 } 6496 6497 @Override 6498 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6499 String targetPackage, int flags) { 6500 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6501 } 6502 6503 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6504 int flags) { 6505 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6506 6507 // reader 6508 synchronized (mPackages) { 6509 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6510 while (i.hasNext()) { 6511 final PackageParser.Instrumentation p = i.next(); 6512 if (targetPackage == null 6513 || targetPackage.equals(p.info.targetPackage)) { 6514 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6515 flags); 6516 if (ii != null) { 6517 finalList.add(ii); 6518 } 6519 } 6520 } 6521 } 6522 6523 return finalList; 6524 } 6525 6526 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6527 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6528 if (overlays == null) { 6529 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6530 return; 6531 } 6532 for (PackageParser.Package opkg : overlays.values()) { 6533 // Not much to do if idmap fails: we already logged the error 6534 // and we certainly don't want to abort installation of pkg simply 6535 // because an overlay didn't fit properly. For these reasons, 6536 // ignore the return value of createIdmapForPackagePairLI. 6537 createIdmapForPackagePairLI(pkg, opkg); 6538 } 6539 } 6540 6541 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6542 PackageParser.Package opkg) { 6543 if (!opkg.mTrustedOverlay) { 6544 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6545 opkg.baseCodePath + ": overlay not trusted"); 6546 return false; 6547 } 6548 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6549 if (overlaySet == null) { 6550 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6551 opkg.baseCodePath + " but target package has no known overlays"); 6552 return false; 6553 } 6554 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6555 // TODO: generate idmap for split APKs 6556 try { 6557 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6558 } catch (InstallerException e) { 6559 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6560 + opkg.baseCodePath); 6561 return false; 6562 } 6563 PackageParser.Package[] overlayArray = 6564 overlaySet.values().toArray(new PackageParser.Package[0]); 6565 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6566 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6567 return p1.mOverlayPriority - p2.mOverlayPriority; 6568 } 6569 }; 6570 Arrays.sort(overlayArray, cmp); 6571 6572 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6573 int i = 0; 6574 for (PackageParser.Package p : overlayArray) { 6575 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6576 } 6577 return true; 6578 } 6579 6580 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6581 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6582 try { 6583 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6584 } finally { 6585 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6586 } 6587 } 6588 6589 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6590 final File[] files = dir.listFiles(); 6591 if (ArrayUtils.isEmpty(files)) { 6592 Log.d(TAG, "No files in app dir " + dir); 6593 return; 6594 } 6595 6596 if (DEBUG_PACKAGE_SCANNING) { 6597 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6598 + " flags=0x" + Integer.toHexString(parseFlags)); 6599 } 6600 6601 for (File file : files) { 6602 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6603 && !PackageInstallerService.isStageName(file.getName()); 6604 if (!isPackage) { 6605 // Ignore entries which are not packages 6606 continue; 6607 } 6608 try { 6609 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6610 scanFlags, currentTime, null); 6611 } catch (PackageManagerException e) { 6612 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6613 6614 // Delete invalid userdata apps 6615 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6616 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6617 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6618 removeCodePathLI(file); 6619 } 6620 } 6621 } 6622 } 6623 6624 private static File getSettingsProblemFile() { 6625 File dataDir = Environment.getDataDirectory(); 6626 File systemDir = new File(dataDir, "system"); 6627 File fname = new File(systemDir, "uiderrors.txt"); 6628 return fname; 6629 } 6630 6631 static void reportSettingsProblem(int priority, String msg) { 6632 logCriticalInfo(priority, msg); 6633 } 6634 6635 static void logCriticalInfo(int priority, String msg) { 6636 Slog.println(priority, TAG, msg); 6637 EventLogTags.writePmCriticalInfo(msg); 6638 try { 6639 File fname = getSettingsProblemFile(); 6640 FileOutputStream out = new FileOutputStream(fname, true); 6641 PrintWriter pw = new FastPrintWriter(out); 6642 SimpleDateFormat formatter = new SimpleDateFormat(); 6643 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6644 pw.println(dateString + ": " + msg); 6645 pw.close(); 6646 FileUtils.setPermissions( 6647 fname.toString(), 6648 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6649 -1, -1); 6650 } catch (java.io.IOException e) { 6651 } 6652 } 6653 6654 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6655 final int policyFlags) throws PackageManagerException { 6656 if (ps != null 6657 && ps.codePath.equals(srcFile) 6658 && ps.timeStamp == srcFile.lastModified() 6659 && !isCompatSignatureUpdateNeeded(pkg) 6660 && !isRecoverSignatureUpdateNeeded(pkg)) { 6661 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6662 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6663 ArraySet<PublicKey> signingKs; 6664 synchronized (mPackages) { 6665 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6666 } 6667 if (ps.signatures.mSignatures != null 6668 && ps.signatures.mSignatures.length != 0 6669 && signingKs != null) { 6670 // Optimization: reuse the existing cached certificates 6671 // if the package appears to be unchanged. 6672 pkg.mSignatures = ps.signatures.mSignatures; 6673 pkg.mSigningKeys = signingKs; 6674 return; 6675 } 6676 6677 Slog.w(TAG, "PackageSetting for " + ps.name 6678 + " is missing signatures. Collecting certs again to recover them."); 6679 } else { 6680 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6681 } 6682 6683 try { 6684 PackageParser.collectCertificates(pkg, policyFlags); 6685 } catch (PackageParserException e) { 6686 throw PackageManagerException.from(e); 6687 } 6688 } 6689 6690 /** 6691 * Traces a package scan. 6692 * @see #scanPackageLI(File, int, int, long, UserHandle) 6693 */ 6694 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6695 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6696 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6697 try { 6698 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6699 } finally { 6700 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6701 } 6702 } 6703 6704 /** 6705 * Scans a package and returns the newly parsed package. 6706 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6707 */ 6708 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6709 long currentTime, UserHandle user) throws PackageManagerException { 6710 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6711 PackageParser pp = new PackageParser(); 6712 pp.setSeparateProcesses(mSeparateProcesses); 6713 pp.setOnlyCoreApps(mOnlyCore); 6714 pp.setDisplayMetrics(mMetrics); 6715 6716 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6717 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6718 } 6719 6720 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6721 final PackageParser.Package pkg; 6722 try { 6723 pkg = pp.parsePackage(scanFile, parseFlags); 6724 } catch (PackageParserException e) { 6725 throw PackageManagerException.from(e); 6726 } finally { 6727 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6728 } 6729 6730 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6731 } 6732 6733 /** 6734 * Scans a package and returns the newly parsed package. 6735 * @throws PackageManagerException on a parse error. 6736 */ 6737 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6738 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6739 throws PackageManagerException { 6740 // If the package has children and this is the first dive in the function 6741 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6742 // packages (parent and children) would be successfully scanned before the 6743 // actual scan since scanning mutates internal state and we want to atomically 6744 // install the package and its children. 6745 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6746 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6747 scanFlags |= SCAN_CHECK_ONLY; 6748 } 6749 } else { 6750 scanFlags &= ~SCAN_CHECK_ONLY; 6751 } 6752 6753 // Scan the parent 6754 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6755 scanFlags, currentTime, user); 6756 6757 // Scan the children 6758 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6759 for (int i = 0; i < childCount; i++) { 6760 PackageParser.Package childPackage = pkg.childPackages.get(i); 6761 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6762 currentTime, user); 6763 } 6764 6765 6766 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6767 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6768 } 6769 6770 return scannedPkg; 6771 } 6772 6773 /** 6774 * Scans a package and returns the newly parsed package. 6775 * @throws PackageManagerException on a parse error. 6776 */ 6777 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6778 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6779 throws PackageManagerException { 6780 PackageSetting ps = null; 6781 PackageSetting updatedPkg; 6782 // reader 6783 synchronized (mPackages) { 6784 // Look to see if we already know about this package. 6785 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6786 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6787 // This package has been renamed to its original name. Let's 6788 // use that. 6789 ps = mSettings.peekPackageLPr(oldName); 6790 } 6791 // If there was no original package, see one for the real package name. 6792 if (ps == null) { 6793 ps = mSettings.peekPackageLPr(pkg.packageName); 6794 } 6795 // Check to see if this package could be hiding/updating a system 6796 // package. Must look for it either under the original or real 6797 // package name depending on our state. 6798 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6799 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6800 6801 // If this is a package we don't know about on the system partition, we 6802 // may need to remove disabled child packages on the system partition 6803 // or may need to not add child packages if the parent apk is updated 6804 // on the data partition and no longer defines this child package. 6805 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6806 // If this is a parent package for an updated system app and this system 6807 // app got an OTA update which no longer defines some of the child packages 6808 // we have to prune them from the disabled system packages. 6809 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6810 if (disabledPs != null) { 6811 final int scannedChildCount = (pkg.childPackages != null) 6812 ? pkg.childPackages.size() : 0; 6813 final int disabledChildCount = disabledPs.childPackageNames != null 6814 ? disabledPs.childPackageNames.size() : 0; 6815 for (int i = 0; i < disabledChildCount; i++) { 6816 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6817 boolean disabledPackageAvailable = false; 6818 for (int j = 0; j < scannedChildCount; j++) { 6819 PackageParser.Package childPkg = pkg.childPackages.get(j); 6820 if (childPkg.packageName.equals(disabledChildPackageName)) { 6821 disabledPackageAvailable = true; 6822 break; 6823 } 6824 } 6825 if (!disabledPackageAvailable) { 6826 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6827 } 6828 } 6829 } 6830 } 6831 } 6832 6833 boolean updatedPkgBetter = false; 6834 // First check if this is a system package that may involve an update 6835 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6836 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6837 // it needs to drop FLAG_PRIVILEGED. 6838 if (locationIsPrivileged(scanFile)) { 6839 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6840 } else { 6841 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6842 } 6843 6844 if (ps != null && !ps.codePath.equals(scanFile)) { 6845 // The path has changed from what was last scanned... check the 6846 // version of the new path against what we have stored to determine 6847 // what to do. 6848 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6849 if (pkg.mVersionCode <= ps.versionCode) { 6850 // The system package has been updated and the code path does not match 6851 // Ignore entry. Skip it. 6852 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6853 + " ignored: updated version " + ps.versionCode 6854 + " better than this " + pkg.mVersionCode); 6855 if (!updatedPkg.codePath.equals(scanFile)) { 6856 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6857 + ps.name + " changing from " + updatedPkg.codePathString 6858 + " to " + scanFile); 6859 updatedPkg.codePath = scanFile; 6860 updatedPkg.codePathString = scanFile.toString(); 6861 updatedPkg.resourcePath = scanFile; 6862 updatedPkg.resourcePathString = scanFile.toString(); 6863 } 6864 updatedPkg.pkg = pkg; 6865 updatedPkg.versionCode = pkg.mVersionCode; 6866 6867 // Update the disabled system child packages to point to the package too. 6868 final int childCount = updatedPkg.childPackageNames != null 6869 ? updatedPkg.childPackageNames.size() : 0; 6870 for (int i = 0; i < childCount; i++) { 6871 String childPackageName = updatedPkg.childPackageNames.get(i); 6872 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6873 childPackageName); 6874 if (updatedChildPkg != null) { 6875 updatedChildPkg.pkg = pkg; 6876 updatedChildPkg.versionCode = pkg.mVersionCode; 6877 } 6878 } 6879 6880 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6881 + scanFile + " ignored: updated version " + ps.versionCode 6882 + " better than this " + pkg.mVersionCode); 6883 } else { 6884 // The current app on the system partition is better than 6885 // what we have updated to on the data partition; switch 6886 // back to the system partition version. 6887 // At this point, its safely assumed that package installation for 6888 // apps in system partition will go through. If not there won't be a working 6889 // version of the app 6890 // writer 6891 synchronized (mPackages) { 6892 // Just remove the loaded entries from package lists. 6893 mPackages.remove(ps.name); 6894 } 6895 6896 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6897 + " reverting from " + ps.codePathString 6898 + ": new version " + pkg.mVersionCode 6899 + " better than installed " + ps.versionCode); 6900 6901 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6902 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6903 synchronized (mInstallLock) { 6904 args.cleanUpResourcesLI(); 6905 } 6906 synchronized (mPackages) { 6907 mSettings.enableSystemPackageLPw(ps.name); 6908 } 6909 updatedPkgBetter = true; 6910 } 6911 } 6912 } 6913 6914 if (updatedPkg != null) { 6915 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6916 // initially 6917 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6918 6919 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6920 // flag set initially 6921 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6922 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6923 } 6924 } 6925 6926 // Verify certificates against what was last scanned 6927 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6928 6929 /* 6930 * A new system app appeared, but we already had a non-system one of the 6931 * same name installed earlier. 6932 */ 6933 boolean shouldHideSystemApp = false; 6934 if (updatedPkg == null && ps != null 6935 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6936 /* 6937 * Check to make sure the signatures match first. If they don't, 6938 * wipe the installed application and its data. 6939 */ 6940 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6941 != PackageManager.SIGNATURE_MATCH) { 6942 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6943 + " signatures don't match existing userdata copy; removing"); 6944 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6945 "scanPackageInternalLI")) { 6946 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6947 } 6948 ps = null; 6949 } else { 6950 /* 6951 * If the newly-added system app is an older version than the 6952 * already installed version, hide it. It will be scanned later 6953 * and re-added like an update. 6954 */ 6955 if (pkg.mVersionCode <= ps.versionCode) { 6956 shouldHideSystemApp = true; 6957 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6958 + " but new version " + pkg.mVersionCode + " better than installed " 6959 + ps.versionCode + "; hiding system"); 6960 } else { 6961 /* 6962 * The newly found system app is a newer version that the 6963 * one previously installed. Simply remove the 6964 * already-installed application and replace it with our own 6965 * while keeping the application data. 6966 */ 6967 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6968 + " reverting from " + ps.codePathString + ": new version " 6969 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6970 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6971 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6972 synchronized (mInstallLock) { 6973 args.cleanUpResourcesLI(); 6974 } 6975 } 6976 } 6977 } 6978 6979 // The apk is forward locked (not public) if its code and resources 6980 // are kept in different files. (except for app in either system or 6981 // vendor path). 6982 // TODO grab this value from PackageSettings 6983 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6984 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6985 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6986 } 6987 } 6988 6989 // TODO: extend to support forward-locked splits 6990 String resourcePath = null; 6991 String baseResourcePath = null; 6992 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6993 if (ps != null && ps.resourcePathString != null) { 6994 resourcePath = ps.resourcePathString; 6995 baseResourcePath = ps.resourcePathString; 6996 } else { 6997 // Should not happen at all. Just log an error. 6998 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6999 } 7000 } else { 7001 resourcePath = pkg.codePath; 7002 baseResourcePath = pkg.baseCodePath; 7003 } 7004 7005 // Set application objects path explicitly. 7006 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7007 pkg.setApplicationInfoCodePath(pkg.codePath); 7008 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7009 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7010 pkg.setApplicationInfoResourcePath(resourcePath); 7011 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7012 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7013 7014 // Note that we invoke the following method only if we are about to unpack an application 7015 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7016 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7017 7018 /* 7019 * If the system app should be overridden by a previously installed 7020 * data, hide the system app now and let the /data/app scan pick it up 7021 * again. 7022 */ 7023 if (shouldHideSystemApp) { 7024 synchronized (mPackages) { 7025 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7026 } 7027 } 7028 7029 return scannedPkg; 7030 } 7031 7032 private static String fixProcessName(String defProcessName, 7033 String processName, int uid) { 7034 if (processName == null) { 7035 return defProcessName; 7036 } 7037 return processName; 7038 } 7039 7040 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7041 throws PackageManagerException { 7042 if (pkgSetting.signatures.mSignatures != null) { 7043 // Already existing package. Make sure signatures match 7044 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7045 == PackageManager.SIGNATURE_MATCH; 7046 if (!match) { 7047 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7048 == PackageManager.SIGNATURE_MATCH; 7049 } 7050 if (!match) { 7051 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7052 == PackageManager.SIGNATURE_MATCH; 7053 } 7054 if (!match) { 7055 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7056 + pkg.packageName + " signatures do not match the " 7057 + "previously installed version; ignoring!"); 7058 } 7059 } 7060 7061 // Check for shared user signatures 7062 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7063 // Already existing package. Make sure signatures match 7064 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7065 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7066 if (!match) { 7067 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7068 == PackageManager.SIGNATURE_MATCH; 7069 } 7070 if (!match) { 7071 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7072 == PackageManager.SIGNATURE_MATCH; 7073 } 7074 if (!match) { 7075 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7076 "Package " + pkg.packageName 7077 + " has no signatures that match those in shared user " 7078 + pkgSetting.sharedUser.name + "; ignoring!"); 7079 } 7080 } 7081 } 7082 7083 /** 7084 * Enforces that only the system UID or root's UID can call a method exposed 7085 * via Binder. 7086 * 7087 * @param message used as message if SecurityException is thrown 7088 * @throws SecurityException if the caller is not system or root 7089 */ 7090 private static final void enforceSystemOrRoot(String message) { 7091 final int uid = Binder.getCallingUid(); 7092 if (uid != Process.SYSTEM_UID && uid != 0) { 7093 throw new SecurityException(message); 7094 } 7095 } 7096 7097 @Override 7098 public void performFstrimIfNeeded() { 7099 enforceSystemOrRoot("Only the system can request fstrim"); 7100 7101 // Before everything else, see whether we need to fstrim. 7102 try { 7103 IMountService ms = PackageHelper.getMountService(); 7104 if (ms != null) { 7105 final boolean isUpgrade = isUpgrade(); 7106 boolean doTrim = isUpgrade; 7107 if (doTrim) { 7108 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7109 } else { 7110 final long interval = android.provider.Settings.Global.getLong( 7111 mContext.getContentResolver(), 7112 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7113 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7114 if (interval > 0) { 7115 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7116 if (timeSinceLast > interval) { 7117 doTrim = true; 7118 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7119 + "; running immediately"); 7120 } 7121 } 7122 } 7123 if (doTrim) { 7124 if (!isFirstBoot()) { 7125 try { 7126 ActivityManagerNative.getDefault().showBootMessage( 7127 mContext.getResources().getString( 7128 R.string.android_upgrading_fstrim), true); 7129 } catch (RemoteException e) { 7130 } 7131 } 7132 ms.runMaintenance(); 7133 } 7134 } else { 7135 Slog.e(TAG, "Mount service unavailable!"); 7136 } 7137 } catch (RemoteException e) { 7138 // Can't happen; MountService is local 7139 } 7140 } 7141 7142 @Override 7143 public void updatePackagesIfNeeded() { 7144 enforceSystemOrRoot("Only the system can request package update"); 7145 7146 // We need to re-extract after an OTA. 7147 boolean causeUpgrade = isUpgrade(); 7148 7149 // First boot or factory reset. 7150 // Note: we also handle devices that are upgrading to N right now as if it is their 7151 // first boot, as they do not have profile data. 7152 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7153 7154 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7155 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7156 7157 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7158 return; 7159 } 7160 7161 List<PackageParser.Package> pkgs; 7162 synchronized (mPackages) { 7163 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7164 } 7165 7166 int numberOfPackagesVisited = 0; 7167 int numberOfPackagesOptimized = 0; 7168 int numberOfPackagesSkipped = 0; 7169 int numberOfPackagesFailed = 0; 7170 final int numberOfPackagesToDexopt = pkgs.size(); 7171 final long startTime = System.nanoTime(); 7172 7173 for (PackageParser.Package pkg : pkgs) { 7174 numberOfPackagesVisited++; 7175 7176 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7177 if (DEBUG_DEXOPT) { 7178 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7179 } 7180 numberOfPackagesSkipped++; 7181 continue; 7182 } 7183 7184 if (DEBUG_DEXOPT) { 7185 Log.i(TAG, "Updating app " + numberOfPackagesVisited + " of " + 7186 numberOfPackagesToDexopt + ": " + pkg.packageName); 7187 } 7188 7189 if (mIsPreNUpgrade) { 7190 try { 7191 ActivityManagerNative.getDefault().showBootMessage( 7192 mContext.getResources().getString(R.string.android_upgrading_apk, 7193 numberOfPackagesVisited, numberOfPackagesToDexopt), true); 7194 } catch (RemoteException e) { 7195 } 7196 } 7197 7198 // checkProfiles is false to avoid merging profiles during boot which 7199 // might interfere with background compilation (b/28612421). 7200 // Unfortunately this will also means that "pm.dexopt.boot=speed-profile" will 7201 // behave differently than "pm.dexopt.bg-dexopt=speed-profile" but that's a 7202 // trade-off worth doing to save boot time work. 7203 int dexOptStatus = performDexOptTraced(pkg.packageName, 7204 null /* instructionSet */, 7205 false /* checkProfiles */, 7206 getCompilerFilterForReason(causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT), 7207 false /* force */); 7208 switch (dexOptStatus) { 7209 case PackageDexOptimizer.DEX_OPT_PERFORMED: 7210 numberOfPackagesOptimized++; 7211 break; 7212 case PackageDexOptimizer.DEX_OPT_SKIPPED: 7213 numberOfPackagesSkipped++; 7214 break; 7215 case PackageDexOptimizer.DEX_OPT_FAILED: 7216 numberOfPackagesFailed++; 7217 break; 7218 default: 7219 Log.e(TAG, "Unexpected dexopt return code " + dexOptStatus); 7220 break; 7221 } 7222 } 7223 7224 final int elapsedTimeMs = (int) TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - startTime); 7225 // Report the elapsed time in deci-seconds (tenths of a second) rounded upwards 7226 // (e.g. 1234 ms will become 13ds). This will help provide histograms at a more reasonable 7227 // granularity. 7228 final int elapsedTimeDs = ((elapsedTimeMs + 99) / 100); 7229 MetricsLogger.histogram(mContext, "opt_dialog_num_dexopted", numberOfPackagesOptimized); 7230 MetricsLogger.histogram(mContext, "opt_dialog_num_skipped", numberOfPackagesSkipped); 7231 MetricsLogger.histogram(mContext, "opt_dialog_num_failed", numberOfPackagesFailed); 7232 MetricsLogger.histogram(mContext, "opt_dialog_num_total", getOptimizablePackages().size()); 7233 MetricsLogger.histogram(mContext, "opt_dialog_time_decis", elapsedTimeDs); 7234 } 7235 7236 @Override 7237 public void notifyPackageUse(String packageName, int reason) { 7238 synchronized (mPackages) { 7239 PackageParser.Package p = mPackages.get(packageName); 7240 if (p == null) { 7241 return; 7242 } 7243 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7244 } 7245 } 7246 7247 // TODO: this is not used nor needed. Delete it. 7248 @Override 7249 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7250 int dexOptStatus = performDexOptTraced(packageName, instructionSet, 7251 false /* checkProfiles */, getFullCompilerFilter(), false /* force */); 7252 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7253 } 7254 7255 @Override 7256 public boolean performDexOpt(String packageName, String instructionSet, 7257 boolean checkProfiles, int compileReason, boolean force) { 7258 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7259 getCompilerFilterForReason(compileReason), force); 7260 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7261 } 7262 7263 @Override 7264 public boolean performDexOptMode(String packageName, String instructionSet, 7265 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7266 int dexOptStatus = performDexOptTraced(packageName, instructionSet, checkProfiles, 7267 targetCompilerFilter, force); 7268 return dexOptStatus != PackageDexOptimizer.DEX_OPT_FAILED; 7269 } 7270 7271 private int performDexOptTraced(String packageName, String instructionSet, 7272 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7273 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7274 try { 7275 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7276 targetCompilerFilter, force); 7277 } finally { 7278 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7279 } 7280 } 7281 7282 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7283 // if the package can now be considered up to date for the given filter. 7284 private int performDexOptInternal(String packageName, String instructionSet, 7285 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7286 PackageParser.Package p; 7287 final String targetInstructionSet; 7288 synchronized (mPackages) { 7289 p = mPackages.get(packageName); 7290 if (p == null) { 7291 // Package could not be found. Report failure. 7292 return PackageDexOptimizer.DEX_OPT_FAILED; 7293 } 7294 mPackageUsage.write(false); 7295 7296 targetInstructionSet = instructionSet != null ? instructionSet : 7297 getPrimaryInstructionSet(p.applicationInfo); 7298 } 7299 long callingId = Binder.clearCallingIdentity(); 7300 try { 7301 synchronized (mInstallLock) { 7302 final String[] instructionSets = new String[] { targetInstructionSet }; 7303 return performDexOptInternalWithDependenciesLI(p, instructionSets, checkProfiles, 7304 targetCompilerFilter, force); 7305 } 7306 } finally { 7307 Binder.restoreCallingIdentity(callingId); 7308 } 7309 } 7310 7311 public ArraySet<String> getOptimizablePackages() { 7312 ArraySet<String> pkgs = new ArraySet<String>(); 7313 synchronized (mPackages) { 7314 for (PackageParser.Package p : mPackages.values()) { 7315 if (PackageDexOptimizer.canOptimizePackage(p)) { 7316 pkgs.add(p.packageName); 7317 } 7318 } 7319 } 7320 return pkgs; 7321 } 7322 7323 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7324 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7325 boolean force) { 7326 // Select the dex optimizer based on the force parameter. 7327 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7328 // allocate an object here. 7329 PackageDexOptimizer pdo = force 7330 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7331 : mPackageDexOptimizer; 7332 7333 // Optimize all dependencies first. Note: we ignore the return value and march on 7334 // on errors. 7335 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7336 if (!deps.isEmpty()) { 7337 for (PackageParser.Package depPackage : deps) { 7338 // TODO: Analyze and investigate if we (should) profile libraries. 7339 // Currently this will do a full compilation of the library by default. 7340 pdo.performDexOpt(depPackage, null /* sharedLibraries */, instructionSets, 7341 false /* checkProfiles */, 7342 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7343 } 7344 } 7345 7346 return pdo.performDexOpt(p, p.usesLibraryFiles, instructionSets, checkProfiles, 7347 targetCompilerFilter); 7348 } 7349 7350 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7351 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7352 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7353 Set<String> collectedNames = new HashSet<>(); 7354 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7355 7356 retValue.remove(p); 7357 7358 return retValue; 7359 } else { 7360 return Collections.emptyList(); 7361 } 7362 } 7363 7364 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7365 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7366 if (!collectedNames.contains(p.packageName)) { 7367 collectedNames.add(p.packageName); 7368 collected.add(p); 7369 7370 if (p.usesLibraries != null) { 7371 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7372 } 7373 if (p.usesOptionalLibraries != null) { 7374 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7375 collectedNames); 7376 } 7377 } 7378 } 7379 7380 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7381 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7382 for (String libName : libs) { 7383 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7384 if (libPkg != null) { 7385 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7386 } 7387 } 7388 } 7389 7390 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7391 synchronized (mPackages) { 7392 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7393 if (lib != null && lib.apk != null) { 7394 return mPackages.get(lib.apk); 7395 } 7396 } 7397 return null; 7398 } 7399 7400 public void shutdown() { 7401 mPackageUsage.write(true); 7402 } 7403 7404 @Override 7405 public void forceDexOpt(String packageName) { 7406 enforceSystemOrRoot("forceDexOpt"); 7407 7408 PackageParser.Package pkg; 7409 synchronized (mPackages) { 7410 pkg = mPackages.get(packageName); 7411 if (pkg == null) { 7412 throw new IllegalArgumentException("Unknown package: " + packageName); 7413 } 7414 } 7415 7416 synchronized (mInstallLock) { 7417 final String[] instructionSets = new String[] { 7418 getPrimaryInstructionSet(pkg.applicationInfo) }; 7419 7420 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7421 7422 // Whoever is calling forceDexOpt wants a fully compiled package. 7423 // Don't use profiles since that may cause compilation to be skipped. 7424 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7425 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7426 true /* force */); 7427 7428 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7429 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7430 throw new IllegalStateException("Failed to dexopt: " + res); 7431 } 7432 } 7433 } 7434 7435 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7436 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7437 Slog.w(TAG, "Unable to update from " + oldPkg.name 7438 + " to " + newPkg.packageName 7439 + ": old package not in system partition"); 7440 return false; 7441 } else if (mPackages.get(oldPkg.name) != null) { 7442 Slog.w(TAG, "Unable to update from " + oldPkg.name 7443 + " to " + newPkg.packageName 7444 + ": old package still exists"); 7445 return false; 7446 } 7447 return true; 7448 } 7449 7450 void removeCodePathLI(File codePath) { 7451 if (codePath.isDirectory()) { 7452 try { 7453 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7454 } catch (InstallerException e) { 7455 Slog.w(TAG, "Failed to remove code path", e); 7456 } 7457 } else { 7458 codePath.delete(); 7459 } 7460 } 7461 7462 private int[] resolveUserIds(int userId) { 7463 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7464 } 7465 7466 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7467 if (pkg == null) { 7468 Slog.wtf(TAG, "Package was null!", new Throwable()); 7469 return; 7470 } 7471 clearAppDataLeafLIF(pkg, userId, flags); 7472 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7473 for (int i = 0; i < childCount; i++) { 7474 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7475 } 7476 } 7477 7478 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7479 final PackageSetting ps; 7480 synchronized (mPackages) { 7481 ps = mSettings.mPackages.get(pkg.packageName); 7482 } 7483 for (int realUserId : resolveUserIds(userId)) { 7484 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7485 try { 7486 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7487 ceDataInode); 7488 } catch (InstallerException e) { 7489 Slog.w(TAG, String.valueOf(e)); 7490 } 7491 } 7492 } 7493 7494 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7495 if (pkg == null) { 7496 Slog.wtf(TAG, "Package was null!", new Throwable()); 7497 return; 7498 } 7499 destroyAppDataLeafLIF(pkg, userId, flags); 7500 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7501 for (int i = 0; i < childCount; i++) { 7502 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7503 } 7504 } 7505 7506 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7507 final PackageSetting ps; 7508 synchronized (mPackages) { 7509 ps = mSettings.mPackages.get(pkg.packageName); 7510 } 7511 for (int realUserId : resolveUserIds(userId)) { 7512 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7513 try { 7514 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7515 ceDataInode); 7516 } catch (InstallerException e) { 7517 Slog.w(TAG, String.valueOf(e)); 7518 } 7519 } 7520 } 7521 7522 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7523 if (pkg == null) { 7524 Slog.wtf(TAG, "Package was null!", new Throwable()); 7525 return; 7526 } 7527 destroyAppProfilesLeafLIF(pkg); 7528 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7529 for (int i = 0; i < childCount; i++) { 7530 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7531 } 7532 } 7533 7534 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7535 try { 7536 mInstaller.destroyAppProfiles(pkg.packageName); 7537 } catch (InstallerException e) { 7538 Slog.w(TAG, String.valueOf(e)); 7539 } 7540 } 7541 7542 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7543 if (pkg == null) { 7544 Slog.wtf(TAG, "Package was null!", new Throwable()); 7545 return; 7546 } 7547 clearAppProfilesLeafLIF(pkg); 7548 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7549 for (int i = 0; i < childCount; i++) { 7550 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7551 } 7552 } 7553 7554 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7555 try { 7556 mInstaller.clearAppProfiles(pkg.packageName); 7557 } catch (InstallerException e) { 7558 Slog.w(TAG, String.valueOf(e)); 7559 } 7560 } 7561 7562 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7563 long lastUpdateTime) { 7564 // Set parent install/update time 7565 PackageSetting ps = (PackageSetting) pkg.mExtras; 7566 if (ps != null) { 7567 ps.firstInstallTime = firstInstallTime; 7568 ps.lastUpdateTime = lastUpdateTime; 7569 } 7570 // Set children install/update time 7571 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7572 for (int i = 0; i < childCount; i++) { 7573 PackageParser.Package childPkg = pkg.childPackages.get(i); 7574 ps = (PackageSetting) childPkg.mExtras; 7575 if (ps != null) { 7576 ps.firstInstallTime = firstInstallTime; 7577 ps.lastUpdateTime = lastUpdateTime; 7578 } 7579 } 7580 } 7581 7582 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7583 PackageParser.Package changingLib) { 7584 if (file.path != null) { 7585 usesLibraryFiles.add(file.path); 7586 return; 7587 } 7588 PackageParser.Package p = mPackages.get(file.apk); 7589 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7590 // If we are doing this while in the middle of updating a library apk, 7591 // then we need to make sure to use that new apk for determining the 7592 // dependencies here. (We haven't yet finished committing the new apk 7593 // to the package manager state.) 7594 if (p == null || p.packageName.equals(changingLib.packageName)) { 7595 p = changingLib; 7596 } 7597 } 7598 if (p != null) { 7599 usesLibraryFiles.addAll(p.getAllCodePaths()); 7600 } 7601 } 7602 7603 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7604 PackageParser.Package changingLib) throws PackageManagerException { 7605 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7606 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7607 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7608 for (int i=0; i<N; i++) { 7609 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7610 if (file == null) { 7611 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7612 "Package " + pkg.packageName + " requires unavailable shared library " 7613 + pkg.usesLibraries.get(i) + "; failing!"); 7614 } 7615 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7616 } 7617 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7618 for (int i=0; i<N; i++) { 7619 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7620 if (file == null) { 7621 Slog.w(TAG, "Package " + pkg.packageName 7622 + " desires unavailable shared library " 7623 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7624 } else { 7625 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7626 } 7627 } 7628 N = usesLibraryFiles.size(); 7629 if (N > 0) { 7630 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7631 } else { 7632 pkg.usesLibraryFiles = null; 7633 } 7634 } 7635 } 7636 7637 private static boolean hasString(List<String> list, List<String> which) { 7638 if (list == null) { 7639 return false; 7640 } 7641 for (int i=list.size()-1; i>=0; i--) { 7642 for (int j=which.size()-1; j>=0; j--) { 7643 if (which.get(j).equals(list.get(i))) { 7644 return true; 7645 } 7646 } 7647 } 7648 return false; 7649 } 7650 7651 private void updateAllSharedLibrariesLPw() { 7652 for (PackageParser.Package pkg : mPackages.values()) { 7653 try { 7654 updateSharedLibrariesLPw(pkg, null); 7655 } catch (PackageManagerException e) { 7656 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7657 } 7658 } 7659 } 7660 7661 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7662 PackageParser.Package changingPkg) { 7663 ArrayList<PackageParser.Package> res = null; 7664 for (PackageParser.Package pkg : mPackages.values()) { 7665 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7666 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7667 if (res == null) { 7668 res = new ArrayList<PackageParser.Package>(); 7669 } 7670 res.add(pkg); 7671 try { 7672 updateSharedLibrariesLPw(pkg, changingPkg); 7673 } catch (PackageManagerException e) { 7674 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7675 } 7676 } 7677 } 7678 return res; 7679 } 7680 7681 /** 7682 * Derive the value of the {@code cpuAbiOverride} based on the provided 7683 * value and an optional stored value from the package settings. 7684 */ 7685 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7686 String cpuAbiOverride = null; 7687 7688 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7689 cpuAbiOverride = null; 7690 } else if (abiOverride != null) { 7691 cpuAbiOverride = abiOverride; 7692 } else if (settings != null) { 7693 cpuAbiOverride = settings.cpuAbiOverrideString; 7694 } 7695 7696 return cpuAbiOverride; 7697 } 7698 7699 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7700 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7701 throws PackageManagerException { 7702 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7703 // If the package has children and this is the first dive in the function 7704 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7705 // whether all packages (parent and children) would be successfully scanned 7706 // before the actual scan since scanning mutates internal state and we want 7707 // to atomically install the package and its children. 7708 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7709 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7710 scanFlags |= SCAN_CHECK_ONLY; 7711 } 7712 } else { 7713 scanFlags &= ~SCAN_CHECK_ONLY; 7714 } 7715 7716 final PackageParser.Package scannedPkg; 7717 try { 7718 // Scan the parent 7719 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7720 // Scan the children 7721 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7722 for (int i = 0; i < childCount; i++) { 7723 PackageParser.Package childPkg = pkg.childPackages.get(i); 7724 scanPackageLI(childPkg, policyFlags, 7725 scanFlags, currentTime, user); 7726 } 7727 } finally { 7728 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7729 } 7730 7731 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7732 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7733 } 7734 7735 return scannedPkg; 7736 } 7737 7738 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7739 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7740 boolean success = false; 7741 try { 7742 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7743 currentTime, user); 7744 success = true; 7745 return res; 7746 } finally { 7747 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7748 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7749 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7750 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7751 destroyAppProfilesLIF(pkg); 7752 } 7753 } 7754 } 7755 7756 /** 7757 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7758 */ 7759 private static boolean apkHasCode(String fileName) { 7760 StrictJarFile jarFile = null; 7761 try { 7762 jarFile = new StrictJarFile(fileName, 7763 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7764 return jarFile.findEntry("classes.dex") != null; 7765 } catch (IOException ignore) { 7766 } finally { 7767 try { 7768 jarFile.close(); 7769 } catch (IOException ignore) {} 7770 } 7771 return false; 7772 } 7773 7774 /** 7775 * Enforces code policy for the package. This ensures that if an APK has 7776 * declared hasCode="true" in its manifest that the APK actually contains 7777 * code. 7778 * 7779 * @throws PackageManagerException If bytecode could not be found when it should exist 7780 */ 7781 private static void enforceCodePolicy(PackageParser.Package pkg) 7782 throws PackageManagerException { 7783 final boolean shouldHaveCode = 7784 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7785 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7786 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7787 "Package " + pkg.baseCodePath + " code is missing"); 7788 } 7789 7790 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7791 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7792 final boolean splitShouldHaveCode = 7793 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7794 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7795 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7796 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7797 } 7798 } 7799 } 7800 } 7801 7802 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7803 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7804 throws PackageManagerException { 7805 final File scanFile = new File(pkg.codePath); 7806 if (pkg.applicationInfo.getCodePath() == null || 7807 pkg.applicationInfo.getResourcePath() == null) { 7808 // Bail out. The resource and code paths haven't been set. 7809 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7810 "Code and resource paths haven't been set correctly"); 7811 } 7812 7813 // Apply policy 7814 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7815 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7816 if (pkg.applicationInfo.isDirectBootAware()) { 7817 // we're direct boot aware; set for all components 7818 for (PackageParser.Service s : pkg.services) { 7819 s.info.encryptionAware = s.info.directBootAware = true; 7820 } 7821 for (PackageParser.Provider p : pkg.providers) { 7822 p.info.encryptionAware = p.info.directBootAware = true; 7823 } 7824 for (PackageParser.Activity a : pkg.activities) { 7825 a.info.encryptionAware = a.info.directBootAware = true; 7826 } 7827 for (PackageParser.Activity r : pkg.receivers) { 7828 r.info.encryptionAware = r.info.directBootAware = true; 7829 } 7830 } 7831 } else { 7832 // Only allow system apps to be flagged as core apps. 7833 pkg.coreApp = false; 7834 // clear flags not applicable to regular apps 7835 pkg.applicationInfo.privateFlags &= 7836 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7837 pkg.applicationInfo.privateFlags &= 7838 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7839 } 7840 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7841 7842 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7843 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7844 } 7845 7846 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7847 enforceCodePolicy(pkg); 7848 } 7849 7850 if (mCustomResolverComponentName != null && 7851 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7852 setUpCustomResolverActivity(pkg); 7853 } 7854 7855 if (pkg.packageName.equals("android")) { 7856 synchronized (mPackages) { 7857 if (mAndroidApplication != null) { 7858 Slog.w(TAG, "*************************************************"); 7859 Slog.w(TAG, "Core android package being redefined. Skipping."); 7860 Slog.w(TAG, " file=" + scanFile); 7861 Slog.w(TAG, "*************************************************"); 7862 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7863 "Core android package being redefined. Skipping."); 7864 } 7865 7866 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7867 // Set up information for our fall-back user intent resolution activity. 7868 mPlatformPackage = pkg; 7869 pkg.mVersionCode = mSdkVersion; 7870 mAndroidApplication = pkg.applicationInfo; 7871 7872 if (!mResolverReplaced) { 7873 mResolveActivity.applicationInfo = mAndroidApplication; 7874 mResolveActivity.name = ResolverActivity.class.getName(); 7875 mResolveActivity.packageName = mAndroidApplication.packageName; 7876 mResolveActivity.processName = "system:ui"; 7877 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7878 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7879 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7880 mResolveActivity.theme = R.style.Theme_Material_Dialog_Alert; 7881 mResolveActivity.exported = true; 7882 mResolveActivity.enabled = true; 7883 mResolveActivity.resizeMode = ActivityInfo.RESIZE_MODE_RESIZEABLE; 7884 mResolveActivity.configChanges = ActivityInfo.CONFIG_SCREEN_SIZE 7885 | ActivityInfo.CONFIG_SMALLEST_SCREEN_SIZE 7886 | ActivityInfo.CONFIG_SCREEN_LAYOUT 7887 | ActivityInfo.CONFIG_ORIENTATION 7888 | ActivityInfo.CONFIG_KEYBOARD 7889 | ActivityInfo.CONFIG_KEYBOARD_HIDDEN; 7890 mResolveInfo.activityInfo = mResolveActivity; 7891 mResolveInfo.priority = 0; 7892 mResolveInfo.preferredOrder = 0; 7893 mResolveInfo.match = 0; 7894 mResolveComponentName = new ComponentName( 7895 mAndroidApplication.packageName, mResolveActivity.name); 7896 } 7897 } 7898 } 7899 } 7900 7901 if (DEBUG_PACKAGE_SCANNING) { 7902 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7903 Log.d(TAG, "Scanning package " + pkg.packageName); 7904 } 7905 7906 synchronized (mPackages) { 7907 if (mPackages.containsKey(pkg.packageName) 7908 || mSharedLibraries.containsKey(pkg.packageName)) { 7909 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7910 "Application package " + pkg.packageName 7911 + " already installed. Skipping duplicate."); 7912 } 7913 7914 // If we're only installing presumed-existing packages, require that the 7915 // scanned APK is both already known and at the path previously established 7916 // for it. Previously unknown packages we pick up normally, but if we have an 7917 // a priori expectation about this package's install presence, enforce it. 7918 // With a singular exception for new system packages. When an OTA contains 7919 // a new system package, we allow the codepath to change from a system location 7920 // to the user-installed location. If we don't allow this change, any newer, 7921 // user-installed version of the application will be ignored. 7922 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7923 if (mExpectingBetter.containsKey(pkg.packageName)) { 7924 logCriticalInfo(Log.WARN, 7925 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7926 } else { 7927 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7928 if (known != null) { 7929 if (DEBUG_PACKAGE_SCANNING) { 7930 Log.d(TAG, "Examining " + pkg.codePath 7931 + " and requiring known paths " + known.codePathString 7932 + " & " + known.resourcePathString); 7933 } 7934 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7935 || !pkg.applicationInfo.getResourcePath().equals( 7936 known.resourcePathString)) { 7937 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7938 "Application package " + pkg.packageName 7939 + " found at " + pkg.applicationInfo.getCodePath() 7940 + " but expected at " + known.codePathString 7941 + "; ignoring."); 7942 } 7943 } 7944 } 7945 } 7946 } 7947 7948 // Initialize package source and resource directories 7949 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7950 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7951 7952 SharedUserSetting suid = null; 7953 PackageSetting pkgSetting = null; 7954 7955 if (!isSystemApp(pkg)) { 7956 // Only system apps can use these features. 7957 pkg.mOriginalPackages = null; 7958 pkg.mRealPackage = null; 7959 pkg.mAdoptPermissions = null; 7960 } 7961 7962 // Getting the package setting may have a side-effect, so if we 7963 // are only checking if scan would succeed, stash a copy of the 7964 // old setting to restore at the end. 7965 PackageSetting nonMutatedPs = null; 7966 7967 // writer 7968 synchronized (mPackages) { 7969 if (pkg.mSharedUserId != null) { 7970 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7971 if (suid == null) { 7972 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7973 "Creating application package " + pkg.packageName 7974 + " for shared user failed"); 7975 } 7976 if (DEBUG_PACKAGE_SCANNING) { 7977 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7978 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7979 + "): packages=" + suid.packages); 7980 } 7981 } 7982 7983 // Check if we are renaming from an original package name. 7984 PackageSetting origPackage = null; 7985 String realName = null; 7986 if (pkg.mOriginalPackages != null) { 7987 // This package may need to be renamed to a previously 7988 // installed name. Let's check on that... 7989 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7990 if (pkg.mOriginalPackages.contains(renamed)) { 7991 // This package had originally been installed as the 7992 // original name, and we have already taken care of 7993 // transitioning to the new one. Just update the new 7994 // one to continue using the old name. 7995 realName = pkg.mRealPackage; 7996 if (!pkg.packageName.equals(renamed)) { 7997 // Callers into this function may have already taken 7998 // care of renaming the package; only do it here if 7999 // it is not already done. 8000 pkg.setPackageName(renamed); 8001 } 8002 8003 } else { 8004 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 8005 if ((origPackage = mSettings.peekPackageLPr( 8006 pkg.mOriginalPackages.get(i))) != null) { 8007 // We do have the package already installed under its 8008 // original name... should we use it? 8009 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 8010 // New package is not compatible with original. 8011 origPackage = null; 8012 continue; 8013 } else if (origPackage.sharedUser != null) { 8014 // Make sure uid is compatible between packages. 8015 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 8016 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 8017 + " to " + pkg.packageName + ": old uid " 8018 + origPackage.sharedUser.name 8019 + " differs from " + pkg.mSharedUserId); 8020 origPackage = null; 8021 continue; 8022 } 8023 // TODO: Add case when shared user id is added [b/28144775] 8024 } else { 8025 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 8026 + pkg.packageName + " to old name " + origPackage.name); 8027 } 8028 break; 8029 } 8030 } 8031 } 8032 } 8033 8034 if (mTransferedPackages.contains(pkg.packageName)) { 8035 Slog.w(TAG, "Package " + pkg.packageName 8036 + " was transferred to another, but its .apk remains"); 8037 } 8038 8039 // See comments in nonMutatedPs declaration 8040 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8041 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8042 if (foundPs != null) { 8043 nonMutatedPs = new PackageSetting(foundPs); 8044 } 8045 } 8046 8047 // Just create the setting, don't add it yet. For already existing packages 8048 // the PkgSetting exists already and doesn't have to be created. 8049 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8050 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8051 pkg.applicationInfo.primaryCpuAbi, 8052 pkg.applicationInfo.secondaryCpuAbi, 8053 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8054 user, false); 8055 if (pkgSetting == null) { 8056 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8057 "Creating application package " + pkg.packageName + " failed"); 8058 } 8059 8060 if (pkgSetting.origPackage != null) { 8061 // If we are first transitioning from an original package, 8062 // fix up the new package's name now. We need to do this after 8063 // looking up the package under its new name, so getPackageLP 8064 // can take care of fiddling things correctly. 8065 pkg.setPackageName(origPackage.name); 8066 8067 // File a report about this. 8068 String msg = "New package " + pkgSetting.realName 8069 + " renamed to replace old package " + pkgSetting.name; 8070 reportSettingsProblem(Log.WARN, msg); 8071 8072 // Make a note of it. 8073 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8074 mTransferedPackages.add(origPackage.name); 8075 } 8076 8077 // No longer need to retain this. 8078 pkgSetting.origPackage = null; 8079 } 8080 8081 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8082 // Make a note of it. 8083 mTransferedPackages.add(pkg.packageName); 8084 } 8085 8086 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8087 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8088 } 8089 8090 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8091 // Check all shared libraries and map to their actual file path. 8092 // We only do this here for apps not on a system dir, because those 8093 // are the only ones that can fail an install due to this. We 8094 // will take care of the system apps by updating all of their 8095 // library paths after the scan is done. 8096 updateSharedLibrariesLPw(pkg, null); 8097 } 8098 8099 if (mFoundPolicyFile) { 8100 SELinuxMMAC.assignSeinfoValue(pkg); 8101 } 8102 8103 pkg.applicationInfo.uid = pkgSetting.appId; 8104 pkg.mExtras = pkgSetting; 8105 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8106 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8107 // We just determined the app is signed correctly, so bring 8108 // over the latest parsed certs. 8109 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8110 } else { 8111 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8112 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8113 "Package " + pkg.packageName + " upgrade keys do not match the " 8114 + "previously installed version"); 8115 } else { 8116 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8117 String msg = "System package " + pkg.packageName 8118 + " signature changed; retaining data."; 8119 reportSettingsProblem(Log.WARN, msg); 8120 } 8121 } 8122 } else { 8123 try { 8124 verifySignaturesLP(pkgSetting, pkg); 8125 // We just determined the app is signed correctly, so bring 8126 // over the latest parsed certs. 8127 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8128 } catch (PackageManagerException e) { 8129 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8130 throw e; 8131 } 8132 // The signature has changed, but this package is in the system 8133 // image... let's recover! 8134 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8135 // However... if this package is part of a shared user, but it 8136 // doesn't match the signature of the shared user, let's fail. 8137 // What this means is that you can't change the signatures 8138 // associated with an overall shared user, which doesn't seem all 8139 // that unreasonable. 8140 if (pkgSetting.sharedUser != null) { 8141 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8142 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8143 throw new PackageManagerException( 8144 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8145 "Signature mismatch for shared user: " 8146 + pkgSetting.sharedUser); 8147 } 8148 } 8149 // File a report about this. 8150 String msg = "System package " + pkg.packageName 8151 + " signature changed; retaining data."; 8152 reportSettingsProblem(Log.WARN, msg); 8153 } 8154 } 8155 // Verify that this new package doesn't have any content providers 8156 // that conflict with existing packages. Only do this if the 8157 // package isn't already installed, since we don't want to break 8158 // things that are installed. 8159 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8160 final int N = pkg.providers.size(); 8161 int i; 8162 for (i=0; i<N; i++) { 8163 PackageParser.Provider p = pkg.providers.get(i); 8164 if (p.info.authority != null) { 8165 String names[] = p.info.authority.split(";"); 8166 for (int j = 0; j < names.length; j++) { 8167 if (mProvidersByAuthority.containsKey(names[j])) { 8168 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8169 final String otherPackageName = 8170 ((other != null && other.getComponentName() != null) ? 8171 other.getComponentName().getPackageName() : "?"); 8172 throw new PackageManagerException( 8173 INSTALL_FAILED_CONFLICTING_PROVIDER, 8174 "Can't install because provider name " + names[j] 8175 + " (in package " + pkg.applicationInfo.packageName 8176 + ") is already used by " + otherPackageName); 8177 } 8178 } 8179 } 8180 } 8181 } 8182 8183 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8184 // This package wants to adopt ownership of permissions from 8185 // another package. 8186 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8187 final String origName = pkg.mAdoptPermissions.get(i); 8188 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8189 if (orig != null) { 8190 if (verifyPackageUpdateLPr(orig, pkg)) { 8191 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8192 + pkg.packageName); 8193 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8194 } 8195 } 8196 } 8197 } 8198 } 8199 8200 final String pkgName = pkg.packageName; 8201 8202 final long scanFileTime = scanFile.lastModified(); 8203 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8204 pkg.applicationInfo.processName = fixProcessName( 8205 pkg.applicationInfo.packageName, 8206 pkg.applicationInfo.processName, 8207 pkg.applicationInfo.uid); 8208 8209 if (pkg != mPlatformPackage) { 8210 // Get all of our default paths setup 8211 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8212 } 8213 8214 final String path = scanFile.getPath(); 8215 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8216 8217 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8218 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8219 8220 // Some system apps still use directory structure for native libraries 8221 // in which case we might end up not detecting abi solely based on apk 8222 // structure. Try to detect abi based on directory structure. 8223 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8224 pkg.applicationInfo.primaryCpuAbi == null) { 8225 setBundledAppAbisAndRoots(pkg, pkgSetting); 8226 setNativeLibraryPaths(pkg); 8227 } 8228 8229 } else { 8230 if ((scanFlags & SCAN_MOVE) != 0) { 8231 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8232 // but we already have this packages package info in the PackageSetting. We just 8233 // use that and derive the native library path based on the new codepath. 8234 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8235 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8236 } 8237 8238 // Set native library paths again. For moves, the path will be updated based on the 8239 // ABIs we've determined above. For non-moves, the path will be updated based on the 8240 // ABIs we determined during compilation, but the path will depend on the final 8241 // package path (after the rename away from the stage path). 8242 setNativeLibraryPaths(pkg); 8243 } 8244 8245 // This is a special case for the "system" package, where the ABI is 8246 // dictated by the zygote configuration (and init.rc). We should keep track 8247 // of this ABI so that we can deal with "normal" applications that run under 8248 // the same UID correctly. 8249 if (mPlatformPackage == pkg) { 8250 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8251 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8252 } 8253 8254 // If there's a mismatch between the abi-override in the package setting 8255 // and the abiOverride specified for the install. Warn about this because we 8256 // would've already compiled the app without taking the package setting into 8257 // account. 8258 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8259 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8260 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8261 " for package " + pkg.packageName); 8262 } 8263 } 8264 8265 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8266 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8267 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8268 8269 // Copy the derived override back to the parsed package, so that we can 8270 // update the package settings accordingly. 8271 pkg.cpuAbiOverride = cpuAbiOverride; 8272 8273 if (DEBUG_ABI_SELECTION) { 8274 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8275 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8276 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8277 } 8278 8279 // Push the derived path down into PackageSettings so we know what to 8280 // clean up at uninstall time. 8281 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8282 8283 if (DEBUG_ABI_SELECTION) { 8284 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8285 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8286 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8287 } 8288 8289 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8290 // We don't do this here during boot because we can do it all 8291 // at once after scanning all existing packages. 8292 // 8293 // We also do this *before* we perform dexopt on this package, so that 8294 // we can avoid redundant dexopts, and also to make sure we've got the 8295 // code and package path correct. 8296 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8297 pkg, true /* boot complete */); 8298 } 8299 8300 if (mFactoryTest && pkg.requestedPermissions.contains( 8301 android.Manifest.permission.FACTORY_TEST)) { 8302 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8303 } 8304 8305 ArrayList<PackageParser.Package> clientLibPkgs = null; 8306 8307 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8308 if (nonMutatedPs != null) { 8309 synchronized (mPackages) { 8310 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8311 } 8312 } 8313 return pkg; 8314 } 8315 8316 // Only privileged apps and updated privileged apps can add child packages. 8317 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8318 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8319 throw new PackageManagerException("Only privileged apps and updated " 8320 + "privileged apps can add child packages. Ignoring package " 8321 + pkg.packageName); 8322 } 8323 final int childCount = pkg.childPackages.size(); 8324 for (int i = 0; i < childCount; i++) { 8325 PackageParser.Package childPkg = pkg.childPackages.get(i); 8326 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8327 childPkg.packageName)) { 8328 throw new PackageManagerException("Cannot override a child package of " 8329 + "another disabled system app. Ignoring package " + pkg.packageName); 8330 } 8331 } 8332 } 8333 8334 // writer 8335 synchronized (mPackages) { 8336 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8337 // Only system apps can add new shared libraries. 8338 if (pkg.libraryNames != null) { 8339 for (int i=0; i<pkg.libraryNames.size(); i++) { 8340 String name = pkg.libraryNames.get(i); 8341 boolean allowed = false; 8342 if (pkg.isUpdatedSystemApp()) { 8343 // New library entries can only be added through the 8344 // system image. This is important to get rid of a lot 8345 // of nasty edge cases: for example if we allowed a non- 8346 // system update of the app to add a library, then uninstalling 8347 // the update would make the library go away, and assumptions 8348 // we made such as through app install filtering would now 8349 // have allowed apps on the device which aren't compatible 8350 // with it. Better to just have the restriction here, be 8351 // conservative, and create many fewer cases that can negatively 8352 // impact the user experience. 8353 final PackageSetting sysPs = mSettings 8354 .getDisabledSystemPkgLPr(pkg.packageName); 8355 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8356 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8357 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8358 allowed = true; 8359 break; 8360 } 8361 } 8362 } 8363 } else { 8364 allowed = true; 8365 } 8366 if (allowed) { 8367 if (!mSharedLibraries.containsKey(name)) { 8368 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8369 } else if (!name.equals(pkg.packageName)) { 8370 Slog.w(TAG, "Package " + pkg.packageName + " library " 8371 + name + " already exists; skipping"); 8372 } 8373 } else { 8374 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8375 + name + " that is not declared on system image; skipping"); 8376 } 8377 } 8378 if ((scanFlags & SCAN_BOOTING) == 0) { 8379 // If we are not booting, we need to update any applications 8380 // that are clients of our shared library. If we are booting, 8381 // this will all be done once the scan is complete. 8382 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8383 } 8384 } 8385 } 8386 } 8387 8388 if ((scanFlags & SCAN_BOOTING) != 0) { 8389 // No apps can run during boot scan, so they don't need to be frozen 8390 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8391 // Caller asked to not kill app, so it's probably not frozen 8392 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8393 // Caller asked us to ignore frozen check for some reason; they 8394 // probably didn't know the package name 8395 } else { 8396 // We're doing major surgery on this package, so it better be frozen 8397 // right now to keep it from launching 8398 checkPackageFrozen(pkgName); 8399 } 8400 8401 // Also need to kill any apps that are dependent on the library. 8402 if (clientLibPkgs != null) { 8403 for (int i=0; i<clientLibPkgs.size(); i++) { 8404 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8405 killApplication(clientPkg.applicationInfo.packageName, 8406 clientPkg.applicationInfo.uid, "update lib"); 8407 } 8408 } 8409 8410 // Make sure we're not adding any bogus keyset info 8411 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8412 ksms.assertScannedPackageValid(pkg); 8413 8414 // writer 8415 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8416 8417 boolean createIdmapFailed = false; 8418 synchronized (mPackages) { 8419 // We don't expect installation to fail beyond this point 8420 8421 // Add the new setting to mSettings 8422 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8423 // Add the new setting to mPackages 8424 mPackages.put(pkg.applicationInfo.packageName, pkg); 8425 // Make sure we don't accidentally delete its data. 8426 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8427 while (iter.hasNext()) { 8428 PackageCleanItem item = iter.next(); 8429 if (pkgName.equals(item.packageName)) { 8430 iter.remove(); 8431 } 8432 } 8433 8434 // Take care of first install / last update times. 8435 if (currentTime != 0) { 8436 if (pkgSetting.firstInstallTime == 0) { 8437 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8438 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8439 pkgSetting.lastUpdateTime = currentTime; 8440 } 8441 } else if (pkgSetting.firstInstallTime == 0) { 8442 // We need *something*. Take time time stamp of the file. 8443 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8444 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8445 if (scanFileTime != pkgSetting.timeStamp) { 8446 // A package on the system image has changed; consider this 8447 // to be an update. 8448 pkgSetting.lastUpdateTime = scanFileTime; 8449 } 8450 } 8451 8452 // Add the package's KeySets to the global KeySetManagerService 8453 ksms.addScannedPackageLPw(pkg); 8454 8455 int N = pkg.providers.size(); 8456 StringBuilder r = null; 8457 int i; 8458 for (i=0; i<N; i++) { 8459 PackageParser.Provider p = pkg.providers.get(i); 8460 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8461 p.info.processName, pkg.applicationInfo.uid); 8462 mProviders.addProvider(p); 8463 p.syncable = p.info.isSyncable; 8464 if (p.info.authority != null) { 8465 String names[] = p.info.authority.split(";"); 8466 p.info.authority = null; 8467 for (int j = 0; j < names.length; j++) { 8468 if (j == 1 && p.syncable) { 8469 // We only want the first authority for a provider to possibly be 8470 // syncable, so if we already added this provider using a different 8471 // authority clear the syncable flag. We copy the provider before 8472 // changing it because the mProviders object contains a reference 8473 // to a provider that we don't want to change. 8474 // Only do this for the second authority since the resulting provider 8475 // object can be the same for all future authorities for this provider. 8476 p = new PackageParser.Provider(p); 8477 p.syncable = false; 8478 } 8479 if (!mProvidersByAuthority.containsKey(names[j])) { 8480 mProvidersByAuthority.put(names[j], p); 8481 if (p.info.authority == null) { 8482 p.info.authority = names[j]; 8483 } else { 8484 p.info.authority = p.info.authority + ";" + names[j]; 8485 } 8486 if (DEBUG_PACKAGE_SCANNING) { 8487 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8488 Log.d(TAG, "Registered content provider: " + names[j] 8489 + ", className = " + p.info.name + ", isSyncable = " 8490 + p.info.isSyncable); 8491 } 8492 } else { 8493 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8494 Slog.w(TAG, "Skipping provider name " + names[j] + 8495 " (in package " + pkg.applicationInfo.packageName + 8496 "): name already used by " 8497 + ((other != null && other.getComponentName() != null) 8498 ? other.getComponentName().getPackageName() : "?")); 8499 } 8500 } 8501 } 8502 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8503 if (r == null) { 8504 r = new StringBuilder(256); 8505 } else { 8506 r.append(' '); 8507 } 8508 r.append(p.info.name); 8509 } 8510 } 8511 if (r != null) { 8512 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8513 } 8514 8515 N = pkg.services.size(); 8516 r = null; 8517 for (i=0; i<N; i++) { 8518 PackageParser.Service s = pkg.services.get(i); 8519 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8520 s.info.processName, pkg.applicationInfo.uid); 8521 mServices.addService(s); 8522 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8523 if (r == null) { 8524 r = new StringBuilder(256); 8525 } else { 8526 r.append(' '); 8527 } 8528 r.append(s.info.name); 8529 } 8530 } 8531 if (r != null) { 8532 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8533 } 8534 8535 N = pkg.receivers.size(); 8536 r = null; 8537 for (i=0; i<N; i++) { 8538 PackageParser.Activity a = pkg.receivers.get(i); 8539 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8540 a.info.processName, pkg.applicationInfo.uid); 8541 mReceivers.addActivity(a, "receiver"); 8542 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8543 if (r == null) { 8544 r = new StringBuilder(256); 8545 } else { 8546 r.append(' '); 8547 } 8548 r.append(a.info.name); 8549 } 8550 } 8551 if (r != null) { 8552 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8553 } 8554 8555 N = pkg.activities.size(); 8556 r = null; 8557 for (i=0; i<N; i++) { 8558 PackageParser.Activity a = pkg.activities.get(i); 8559 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8560 a.info.processName, pkg.applicationInfo.uid); 8561 mActivities.addActivity(a, "activity"); 8562 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8563 if (r == null) { 8564 r = new StringBuilder(256); 8565 } else { 8566 r.append(' '); 8567 } 8568 r.append(a.info.name); 8569 } 8570 } 8571 if (r != null) { 8572 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8573 } 8574 8575 N = pkg.permissionGroups.size(); 8576 r = null; 8577 for (i=0; i<N; i++) { 8578 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8579 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8580 if (cur == null) { 8581 mPermissionGroups.put(pg.info.name, pg); 8582 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8583 if (r == null) { 8584 r = new StringBuilder(256); 8585 } else { 8586 r.append(' '); 8587 } 8588 r.append(pg.info.name); 8589 } 8590 } else { 8591 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8592 + pg.info.packageName + " ignored: original from " 8593 + cur.info.packageName); 8594 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8595 if (r == null) { 8596 r = new StringBuilder(256); 8597 } else { 8598 r.append(' '); 8599 } 8600 r.append("DUP:"); 8601 r.append(pg.info.name); 8602 } 8603 } 8604 } 8605 if (r != null) { 8606 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8607 } 8608 8609 N = pkg.permissions.size(); 8610 r = null; 8611 for (i=0; i<N; i++) { 8612 PackageParser.Permission p = pkg.permissions.get(i); 8613 8614 // Assume by default that we did not install this permission into the system. 8615 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8616 8617 // Now that permission groups have a special meaning, we ignore permission 8618 // groups for legacy apps to prevent unexpected behavior. In particular, 8619 // permissions for one app being granted to someone just becase they happen 8620 // to be in a group defined by another app (before this had no implications). 8621 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8622 p.group = mPermissionGroups.get(p.info.group); 8623 // Warn for a permission in an unknown group. 8624 if (p.info.group != null && p.group == null) { 8625 Slog.w(TAG, "Permission " + p.info.name + " from package " 8626 + p.info.packageName + " in an unknown group " + p.info.group); 8627 } 8628 } 8629 8630 ArrayMap<String, BasePermission> permissionMap = 8631 p.tree ? mSettings.mPermissionTrees 8632 : mSettings.mPermissions; 8633 BasePermission bp = permissionMap.get(p.info.name); 8634 8635 // Allow system apps to redefine non-system permissions 8636 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8637 final boolean currentOwnerIsSystem = (bp.perm != null 8638 && isSystemApp(bp.perm.owner)); 8639 if (isSystemApp(p.owner)) { 8640 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8641 // It's a built-in permission and no owner, take ownership now 8642 bp.packageSetting = pkgSetting; 8643 bp.perm = p; 8644 bp.uid = pkg.applicationInfo.uid; 8645 bp.sourcePackage = p.info.packageName; 8646 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8647 } else if (!currentOwnerIsSystem) { 8648 String msg = "New decl " + p.owner + " of permission " 8649 + p.info.name + " is system; overriding " + bp.sourcePackage; 8650 reportSettingsProblem(Log.WARN, msg); 8651 bp = null; 8652 } 8653 } 8654 } 8655 8656 if (bp == null) { 8657 bp = new BasePermission(p.info.name, p.info.packageName, 8658 BasePermission.TYPE_NORMAL); 8659 permissionMap.put(p.info.name, bp); 8660 } 8661 8662 if (bp.perm == null) { 8663 if (bp.sourcePackage == null 8664 || bp.sourcePackage.equals(p.info.packageName)) { 8665 BasePermission tree = findPermissionTreeLP(p.info.name); 8666 if (tree == null 8667 || tree.sourcePackage.equals(p.info.packageName)) { 8668 bp.packageSetting = pkgSetting; 8669 bp.perm = p; 8670 bp.uid = pkg.applicationInfo.uid; 8671 bp.sourcePackage = p.info.packageName; 8672 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8673 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8674 if (r == null) { 8675 r = new StringBuilder(256); 8676 } else { 8677 r.append(' '); 8678 } 8679 r.append(p.info.name); 8680 } 8681 } else { 8682 Slog.w(TAG, "Permission " + p.info.name + " from package " 8683 + p.info.packageName + " ignored: base tree " 8684 + tree.name + " is from package " 8685 + tree.sourcePackage); 8686 } 8687 } else { 8688 Slog.w(TAG, "Permission " + p.info.name + " from package " 8689 + p.info.packageName + " ignored: original from " 8690 + bp.sourcePackage); 8691 } 8692 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8693 if (r == null) { 8694 r = new StringBuilder(256); 8695 } else { 8696 r.append(' '); 8697 } 8698 r.append("DUP:"); 8699 r.append(p.info.name); 8700 } 8701 if (bp.perm == p) { 8702 bp.protectionLevel = p.info.protectionLevel; 8703 } 8704 } 8705 8706 if (r != null) { 8707 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8708 } 8709 8710 N = pkg.instrumentation.size(); 8711 r = null; 8712 for (i=0; i<N; i++) { 8713 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8714 a.info.packageName = pkg.applicationInfo.packageName; 8715 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8716 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8717 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8718 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8719 a.info.dataDir = pkg.applicationInfo.dataDir; 8720 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8721 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8722 8723 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8724 // need other information about the application, like the ABI and what not ? 8725 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8726 mInstrumentation.put(a.getComponentName(), a); 8727 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8728 if (r == null) { 8729 r = new StringBuilder(256); 8730 } else { 8731 r.append(' '); 8732 } 8733 r.append(a.info.name); 8734 } 8735 } 8736 if (r != null) { 8737 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8738 } 8739 8740 if (pkg.protectedBroadcasts != null) { 8741 N = pkg.protectedBroadcasts.size(); 8742 for (i=0; i<N; i++) { 8743 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8744 } 8745 } 8746 8747 pkgSetting.setTimeStamp(scanFileTime); 8748 8749 // Create idmap files for pairs of (packages, overlay packages). 8750 // Note: "android", ie framework-res.apk, is handled by native layers. 8751 if (pkg.mOverlayTarget != null) { 8752 // This is an overlay package. 8753 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8754 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8755 mOverlays.put(pkg.mOverlayTarget, 8756 new ArrayMap<String, PackageParser.Package>()); 8757 } 8758 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8759 map.put(pkg.packageName, pkg); 8760 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8761 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8762 createIdmapFailed = true; 8763 } 8764 } 8765 } else if (mOverlays.containsKey(pkg.packageName) && 8766 !pkg.packageName.equals("android")) { 8767 // This is a regular package, with one or more known overlay packages. 8768 createIdmapsForPackageLI(pkg); 8769 } 8770 } 8771 8772 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8773 8774 if (createIdmapFailed) { 8775 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8776 "scanPackageLI failed to createIdmap"); 8777 } 8778 return pkg; 8779 } 8780 8781 /** 8782 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8783 * is derived purely on the basis of the contents of {@code scanFile} and 8784 * {@code cpuAbiOverride}. 8785 * 8786 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8787 */ 8788 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8789 String cpuAbiOverride, boolean extractLibs) 8790 throws PackageManagerException { 8791 // TODO: We can probably be smarter about this stuff. For installed apps, 8792 // we can calculate this information at install time once and for all. For 8793 // system apps, we can probably assume that this information doesn't change 8794 // after the first boot scan. As things stand, we do lots of unnecessary work. 8795 8796 // Give ourselves some initial paths; we'll come back for another 8797 // pass once we've determined ABI below. 8798 setNativeLibraryPaths(pkg); 8799 8800 // We would never need to extract libs for forward-locked and external packages, 8801 // since the container service will do it for us. We shouldn't attempt to 8802 // extract libs from system app when it was not updated. 8803 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8804 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8805 extractLibs = false; 8806 } 8807 8808 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8809 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8810 8811 NativeLibraryHelper.Handle handle = null; 8812 try { 8813 handle = NativeLibraryHelper.Handle.create(pkg); 8814 // TODO(multiArch): This can be null for apps that didn't go through the 8815 // usual installation process. We can calculate it again, like we 8816 // do during install time. 8817 // 8818 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8819 // unnecessary. 8820 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8821 8822 // Null out the abis so that they can be recalculated. 8823 pkg.applicationInfo.primaryCpuAbi = null; 8824 pkg.applicationInfo.secondaryCpuAbi = null; 8825 if (isMultiArch(pkg.applicationInfo)) { 8826 // Warn if we've set an abiOverride for multi-lib packages.. 8827 // By definition, we need to copy both 32 and 64 bit libraries for 8828 // such packages. 8829 if (pkg.cpuAbiOverride != null 8830 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8831 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8832 } 8833 8834 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8835 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8836 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8837 if (extractLibs) { 8838 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8839 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8840 useIsaSpecificSubdirs); 8841 } else { 8842 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8843 } 8844 } 8845 8846 maybeThrowExceptionForMultiArchCopy( 8847 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8848 8849 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8850 if (extractLibs) { 8851 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8852 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8853 useIsaSpecificSubdirs); 8854 } else { 8855 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8856 } 8857 } 8858 8859 maybeThrowExceptionForMultiArchCopy( 8860 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8861 8862 if (abi64 >= 0) { 8863 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8864 } 8865 8866 if (abi32 >= 0) { 8867 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8868 if (abi64 >= 0) { 8869 if (pkg.use32bitAbi) { 8870 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8871 pkg.applicationInfo.primaryCpuAbi = abi; 8872 } else { 8873 pkg.applicationInfo.secondaryCpuAbi = abi; 8874 } 8875 } else { 8876 pkg.applicationInfo.primaryCpuAbi = abi; 8877 } 8878 } 8879 8880 } else { 8881 String[] abiList = (cpuAbiOverride != null) ? 8882 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8883 8884 // Enable gross and lame hacks for apps that are built with old 8885 // SDK tools. We must scan their APKs for renderscript bitcode and 8886 // not launch them if it's present. Don't bother checking on devices 8887 // that don't have 64 bit support. 8888 boolean needsRenderScriptOverride = false; 8889 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8890 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8891 abiList = Build.SUPPORTED_32_BIT_ABIS; 8892 needsRenderScriptOverride = true; 8893 } 8894 8895 final int copyRet; 8896 if (extractLibs) { 8897 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8898 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8899 } else { 8900 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8901 } 8902 8903 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8904 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8905 "Error unpackaging native libs for app, errorCode=" + copyRet); 8906 } 8907 8908 if (copyRet >= 0) { 8909 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8910 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8911 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8912 } else if (needsRenderScriptOverride) { 8913 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8914 } 8915 } 8916 } catch (IOException ioe) { 8917 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8918 } finally { 8919 IoUtils.closeQuietly(handle); 8920 } 8921 8922 // Now that we've calculated the ABIs and determined if it's an internal app, 8923 // we will go ahead and populate the nativeLibraryPath. 8924 setNativeLibraryPaths(pkg); 8925 } 8926 8927 /** 8928 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8929 * i.e, so that all packages can be run inside a single process if required. 8930 * 8931 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8932 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8933 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8934 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8935 * updating a package that belongs to a shared user. 8936 * 8937 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8938 * adds unnecessary complexity. 8939 */ 8940 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8941 PackageParser.Package scannedPackage, boolean bootComplete) { 8942 String requiredInstructionSet = null; 8943 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8944 requiredInstructionSet = VMRuntime.getInstructionSet( 8945 scannedPackage.applicationInfo.primaryCpuAbi); 8946 } 8947 8948 PackageSetting requirer = null; 8949 for (PackageSetting ps : packagesForUser) { 8950 // If packagesForUser contains scannedPackage, we skip it. This will happen 8951 // when scannedPackage is an update of an existing package. Without this check, 8952 // we will never be able to change the ABI of any package belonging to a shared 8953 // user, even if it's compatible with other packages. 8954 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8955 if (ps.primaryCpuAbiString == null) { 8956 continue; 8957 } 8958 8959 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8960 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8961 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8962 // this but there's not much we can do. 8963 String errorMessage = "Instruction set mismatch, " 8964 + ((requirer == null) ? "[caller]" : requirer) 8965 + " requires " + requiredInstructionSet + " whereas " + ps 8966 + " requires " + instructionSet; 8967 Slog.w(TAG, errorMessage); 8968 } 8969 8970 if (requiredInstructionSet == null) { 8971 requiredInstructionSet = instructionSet; 8972 requirer = ps; 8973 } 8974 } 8975 } 8976 8977 if (requiredInstructionSet != null) { 8978 String adjustedAbi; 8979 if (requirer != null) { 8980 // requirer != null implies that either scannedPackage was null or that scannedPackage 8981 // did not require an ABI, in which case we have to adjust scannedPackage to match 8982 // the ABI of the set (which is the same as requirer's ABI) 8983 adjustedAbi = requirer.primaryCpuAbiString; 8984 if (scannedPackage != null) { 8985 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8986 } 8987 } else { 8988 // requirer == null implies that we're updating all ABIs in the set to 8989 // match scannedPackage. 8990 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8991 } 8992 8993 for (PackageSetting ps : packagesForUser) { 8994 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8995 if (ps.primaryCpuAbiString != null) { 8996 continue; 8997 } 8998 8999 ps.primaryCpuAbiString = adjustedAbi; 9000 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9001 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9002 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9003 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9004 + " (requirer=" 9005 + (requirer == null ? "null" : requirer.pkg.packageName) 9006 + ", scannedPackage=" 9007 + (scannedPackage != null ? scannedPackage.packageName : "null") 9008 + ")"); 9009 try { 9010 mInstaller.rmdex(ps.codePathString, 9011 getDexCodeInstructionSet(getPreferredInstructionSet())); 9012 } catch (InstallerException ignored) { 9013 } 9014 } 9015 } 9016 } 9017 } 9018 } 9019 9020 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9021 synchronized (mPackages) { 9022 mResolverReplaced = true; 9023 // Set up information for custom user intent resolution activity. 9024 mResolveActivity.applicationInfo = pkg.applicationInfo; 9025 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9026 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9027 mResolveActivity.processName = pkg.applicationInfo.packageName; 9028 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9029 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9030 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9031 mResolveActivity.theme = 0; 9032 mResolveActivity.exported = true; 9033 mResolveActivity.enabled = true; 9034 mResolveInfo.activityInfo = mResolveActivity; 9035 mResolveInfo.priority = 0; 9036 mResolveInfo.preferredOrder = 0; 9037 mResolveInfo.match = 0; 9038 mResolveComponentName = mCustomResolverComponentName; 9039 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9040 mResolveComponentName); 9041 } 9042 } 9043 9044 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9045 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9046 9047 // Set up information for ephemeral installer activity 9048 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9049 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9050 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9051 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9052 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9053 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9054 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9055 mEphemeralInstallerActivity.theme = 0; 9056 mEphemeralInstallerActivity.exported = true; 9057 mEphemeralInstallerActivity.enabled = true; 9058 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9059 mEphemeralInstallerInfo.priority = 0; 9060 mEphemeralInstallerInfo.preferredOrder = 0; 9061 mEphemeralInstallerInfo.match = 0; 9062 9063 if (DEBUG_EPHEMERAL) { 9064 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9065 } 9066 } 9067 9068 private static String calculateBundledApkRoot(final String codePathString) { 9069 final File codePath = new File(codePathString); 9070 final File codeRoot; 9071 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9072 codeRoot = Environment.getRootDirectory(); 9073 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9074 codeRoot = Environment.getOemDirectory(); 9075 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9076 codeRoot = Environment.getVendorDirectory(); 9077 } else { 9078 // Unrecognized code path; take its top real segment as the apk root: 9079 // e.g. /something/app/blah.apk => /something 9080 try { 9081 File f = codePath.getCanonicalFile(); 9082 File parent = f.getParentFile(); // non-null because codePath is a file 9083 File tmp; 9084 while ((tmp = parent.getParentFile()) != null) { 9085 f = parent; 9086 parent = tmp; 9087 } 9088 codeRoot = f; 9089 Slog.w(TAG, "Unrecognized code path " 9090 + codePath + " - using " + codeRoot); 9091 } catch (IOException e) { 9092 // Can't canonicalize the code path -- shenanigans? 9093 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9094 return Environment.getRootDirectory().getPath(); 9095 } 9096 } 9097 return codeRoot.getPath(); 9098 } 9099 9100 /** 9101 * Derive and set the location of native libraries for the given package, 9102 * which varies depending on where and how the package was installed. 9103 */ 9104 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9105 final ApplicationInfo info = pkg.applicationInfo; 9106 final String codePath = pkg.codePath; 9107 final File codeFile = new File(codePath); 9108 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9109 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9110 9111 info.nativeLibraryRootDir = null; 9112 info.nativeLibraryRootRequiresIsa = false; 9113 info.nativeLibraryDir = null; 9114 info.secondaryNativeLibraryDir = null; 9115 9116 if (isApkFile(codeFile)) { 9117 // Monolithic install 9118 if (bundledApp) { 9119 // If "/system/lib64/apkname" exists, assume that is the per-package 9120 // native library directory to use; otherwise use "/system/lib/apkname". 9121 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9122 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9123 getPrimaryInstructionSet(info)); 9124 9125 // This is a bundled system app so choose the path based on the ABI. 9126 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9127 // is just the default path. 9128 final String apkName = deriveCodePathName(codePath); 9129 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9130 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9131 apkName).getAbsolutePath(); 9132 9133 if (info.secondaryCpuAbi != null) { 9134 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9135 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9136 secondaryLibDir, apkName).getAbsolutePath(); 9137 } 9138 } else if (asecApp) { 9139 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9140 .getAbsolutePath(); 9141 } else { 9142 final String apkName = deriveCodePathName(codePath); 9143 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9144 .getAbsolutePath(); 9145 } 9146 9147 info.nativeLibraryRootRequiresIsa = false; 9148 info.nativeLibraryDir = info.nativeLibraryRootDir; 9149 } else { 9150 // Cluster install 9151 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9152 info.nativeLibraryRootRequiresIsa = true; 9153 9154 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9155 getPrimaryInstructionSet(info)).getAbsolutePath(); 9156 9157 if (info.secondaryCpuAbi != null) { 9158 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9159 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9160 } 9161 } 9162 } 9163 9164 /** 9165 * Calculate the abis and roots for a bundled app. These can uniquely 9166 * be determined from the contents of the system partition, i.e whether 9167 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9168 * of this information, and instead assume that the system was built 9169 * sensibly. 9170 */ 9171 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9172 PackageSetting pkgSetting) { 9173 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9174 9175 // If "/system/lib64/apkname" exists, assume that is the per-package 9176 // native library directory to use; otherwise use "/system/lib/apkname". 9177 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9178 setBundledAppAbi(pkg, apkRoot, apkName); 9179 // pkgSetting might be null during rescan following uninstall of updates 9180 // to a bundled app, so accommodate that possibility. The settings in 9181 // that case will be established later from the parsed package. 9182 // 9183 // If the settings aren't null, sync them up with what we've just derived. 9184 // note that apkRoot isn't stored in the package settings. 9185 if (pkgSetting != null) { 9186 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9187 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9188 } 9189 } 9190 9191 /** 9192 * Deduces the ABI of a bundled app and sets the relevant fields on the 9193 * parsed pkg object. 9194 * 9195 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9196 * under which system libraries are installed. 9197 * @param apkName the name of the installed package. 9198 */ 9199 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9200 final File codeFile = new File(pkg.codePath); 9201 9202 final boolean has64BitLibs; 9203 final boolean has32BitLibs; 9204 if (isApkFile(codeFile)) { 9205 // Monolithic install 9206 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9207 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9208 } else { 9209 // Cluster install 9210 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9211 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9212 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9213 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9214 has64BitLibs = (new File(rootDir, isa)).exists(); 9215 } else { 9216 has64BitLibs = false; 9217 } 9218 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9219 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9220 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9221 has32BitLibs = (new File(rootDir, isa)).exists(); 9222 } else { 9223 has32BitLibs = false; 9224 } 9225 } 9226 9227 if (has64BitLibs && !has32BitLibs) { 9228 // The package has 64 bit libs, but not 32 bit libs. Its primary 9229 // ABI should be 64 bit. We can safely assume here that the bundled 9230 // native libraries correspond to the most preferred ABI in the list. 9231 9232 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9233 pkg.applicationInfo.secondaryCpuAbi = null; 9234 } else if (has32BitLibs && !has64BitLibs) { 9235 // The package has 32 bit libs but not 64 bit libs. Its primary 9236 // ABI should be 32 bit. 9237 9238 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9239 pkg.applicationInfo.secondaryCpuAbi = null; 9240 } else if (has32BitLibs && has64BitLibs) { 9241 // The application has both 64 and 32 bit bundled libraries. We check 9242 // here that the app declares multiArch support, and warn if it doesn't. 9243 // 9244 // We will be lenient here and record both ABIs. The primary will be the 9245 // ABI that's higher on the list, i.e, a device that's configured to prefer 9246 // 64 bit apps will see a 64 bit primary ABI, 9247 9248 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9249 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9250 } 9251 9252 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9253 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9254 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9255 } else { 9256 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9257 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9258 } 9259 } else { 9260 pkg.applicationInfo.primaryCpuAbi = null; 9261 pkg.applicationInfo.secondaryCpuAbi = null; 9262 } 9263 } 9264 9265 private void killApplication(String pkgName, int appId, String reason) { 9266 // Request the ActivityManager to kill the process(only for existing packages) 9267 // so that we do not end up in a confused state while the user is still using the older 9268 // version of the application while the new one gets installed. 9269 final long token = Binder.clearCallingIdentity(); 9270 try { 9271 IActivityManager am = ActivityManagerNative.getDefault(); 9272 if (am != null) { 9273 try { 9274 am.killApplicationWithAppId(pkgName, appId, reason); 9275 } catch (RemoteException e) { 9276 } 9277 } 9278 } finally { 9279 Binder.restoreCallingIdentity(token); 9280 } 9281 } 9282 9283 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9284 // Remove the parent package setting 9285 PackageSetting ps = (PackageSetting) pkg.mExtras; 9286 if (ps != null) { 9287 removePackageLI(ps, chatty); 9288 } 9289 // Remove the child package setting 9290 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9291 for (int i = 0; i < childCount; i++) { 9292 PackageParser.Package childPkg = pkg.childPackages.get(i); 9293 ps = (PackageSetting) childPkg.mExtras; 9294 if (ps != null) { 9295 removePackageLI(ps, chatty); 9296 } 9297 } 9298 } 9299 9300 void removePackageLI(PackageSetting ps, boolean chatty) { 9301 if (DEBUG_INSTALL) { 9302 if (chatty) 9303 Log.d(TAG, "Removing package " + ps.name); 9304 } 9305 9306 // writer 9307 synchronized (mPackages) { 9308 mPackages.remove(ps.name); 9309 final PackageParser.Package pkg = ps.pkg; 9310 if (pkg != null) { 9311 cleanPackageDataStructuresLILPw(pkg, chatty); 9312 } 9313 } 9314 } 9315 9316 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9317 if (DEBUG_INSTALL) { 9318 if (chatty) 9319 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9320 } 9321 9322 // writer 9323 synchronized (mPackages) { 9324 // Remove the parent package 9325 mPackages.remove(pkg.applicationInfo.packageName); 9326 cleanPackageDataStructuresLILPw(pkg, chatty); 9327 9328 // Remove the child packages 9329 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9330 for (int i = 0; i < childCount; i++) { 9331 PackageParser.Package childPkg = pkg.childPackages.get(i); 9332 mPackages.remove(childPkg.applicationInfo.packageName); 9333 cleanPackageDataStructuresLILPw(childPkg, chatty); 9334 } 9335 } 9336 } 9337 9338 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9339 int N = pkg.providers.size(); 9340 StringBuilder r = null; 9341 int i; 9342 for (i=0; i<N; i++) { 9343 PackageParser.Provider p = pkg.providers.get(i); 9344 mProviders.removeProvider(p); 9345 if (p.info.authority == null) { 9346 9347 /* There was another ContentProvider with this authority when 9348 * this app was installed so this authority is null, 9349 * Ignore it as we don't have to unregister the provider. 9350 */ 9351 continue; 9352 } 9353 String names[] = p.info.authority.split(";"); 9354 for (int j = 0; j < names.length; j++) { 9355 if (mProvidersByAuthority.get(names[j]) == p) { 9356 mProvidersByAuthority.remove(names[j]); 9357 if (DEBUG_REMOVE) { 9358 if (chatty) 9359 Log.d(TAG, "Unregistered content provider: " + names[j] 9360 + ", className = " + p.info.name + ", isSyncable = " 9361 + p.info.isSyncable); 9362 } 9363 } 9364 } 9365 if (DEBUG_REMOVE && chatty) { 9366 if (r == null) { 9367 r = new StringBuilder(256); 9368 } else { 9369 r.append(' '); 9370 } 9371 r.append(p.info.name); 9372 } 9373 } 9374 if (r != null) { 9375 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9376 } 9377 9378 N = pkg.services.size(); 9379 r = null; 9380 for (i=0; i<N; i++) { 9381 PackageParser.Service s = pkg.services.get(i); 9382 mServices.removeService(s); 9383 if (chatty) { 9384 if (r == null) { 9385 r = new StringBuilder(256); 9386 } else { 9387 r.append(' '); 9388 } 9389 r.append(s.info.name); 9390 } 9391 } 9392 if (r != null) { 9393 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9394 } 9395 9396 N = pkg.receivers.size(); 9397 r = null; 9398 for (i=0; i<N; i++) { 9399 PackageParser.Activity a = pkg.receivers.get(i); 9400 mReceivers.removeActivity(a, "receiver"); 9401 if (DEBUG_REMOVE && chatty) { 9402 if (r == null) { 9403 r = new StringBuilder(256); 9404 } else { 9405 r.append(' '); 9406 } 9407 r.append(a.info.name); 9408 } 9409 } 9410 if (r != null) { 9411 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9412 } 9413 9414 N = pkg.activities.size(); 9415 r = null; 9416 for (i=0; i<N; i++) { 9417 PackageParser.Activity a = pkg.activities.get(i); 9418 mActivities.removeActivity(a, "activity"); 9419 if (DEBUG_REMOVE && chatty) { 9420 if (r == null) { 9421 r = new StringBuilder(256); 9422 } else { 9423 r.append(' '); 9424 } 9425 r.append(a.info.name); 9426 } 9427 } 9428 if (r != null) { 9429 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9430 } 9431 9432 N = pkg.permissions.size(); 9433 r = null; 9434 for (i=0; i<N; i++) { 9435 PackageParser.Permission p = pkg.permissions.get(i); 9436 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9437 if (bp == null) { 9438 bp = mSettings.mPermissionTrees.get(p.info.name); 9439 } 9440 if (bp != null && bp.perm == p) { 9441 bp.perm = null; 9442 if (DEBUG_REMOVE && chatty) { 9443 if (r == null) { 9444 r = new StringBuilder(256); 9445 } else { 9446 r.append(' '); 9447 } 9448 r.append(p.info.name); 9449 } 9450 } 9451 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9452 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9453 if (appOpPkgs != null) { 9454 appOpPkgs.remove(pkg.packageName); 9455 } 9456 } 9457 } 9458 if (r != null) { 9459 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9460 } 9461 9462 N = pkg.requestedPermissions.size(); 9463 r = null; 9464 for (i=0; i<N; i++) { 9465 String perm = pkg.requestedPermissions.get(i); 9466 BasePermission bp = mSettings.mPermissions.get(perm); 9467 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9468 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9469 if (appOpPkgs != null) { 9470 appOpPkgs.remove(pkg.packageName); 9471 if (appOpPkgs.isEmpty()) { 9472 mAppOpPermissionPackages.remove(perm); 9473 } 9474 } 9475 } 9476 } 9477 if (r != null) { 9478 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9479 } 9480 9481 N = pkg.instrumentation.size(); 9482 r = null; 9483 for (i=0; i<N; i++) { 9484 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9485 mInstrumentation.remove(a.getComponentName()); 9486 if (DEBUG_REMOVE && chatty) { 9487 if (r == null) { 9488 r = new StringBuilder(256); 9489 } else { 9490 r.append(' '); 9491 } 9492 r.append(a.info.name); 9493 } 9494 } 9495 if (r != null) { 9496 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9497 } 9498 9499 r = null; 9500 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9501 // Only system apps can hold shared libraries. 9502 if (pkg.libraryNames != null) { 9503 for (i=0; i<pkg.libraryNames.size(); i++) { 9504 String name = pkg.libraryNames.get(i); 9505 SharedLibraryEntry cur = mSharedLibraries.get(name); 9506 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9507 mSharedLibraries.remove(name); 9508 if (DEBUG_REMOVE && chatty) { 9509 if (r == null) { 9510 r = new StringBuilder(256); 9511 } else { 9512 r.append(' '); 9513 } 9514 r.append(name); 9515 } 9516 } 9517 } 9518 } 9519 } 9520 if (r != null) { 9521 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9522 } 9523 } 9524 9525 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9526 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9527 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9528 return true; 9529 } 9530 } 9531 return false; 9532 } 9533 9534 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9535 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9536 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9537 9538 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9539 // Update the parent permissions 9540 updatePermissionsLPw(pkg.packageName, pkg, flags); 9541 // Update the child permissions 9542 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9543 for (int i = 0; i < childCount; i++) { 9544 PackageParser.Package childPkg = pkg.childPackages.get(i); 9545 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9546 } 9547 } 9548 9549 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9550 int flags) { 9551 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9552 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9553 } 9554 9555 private void updatePermissionsLPw(String changingPkg, 9556 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9557 // Make sure there are no dangling permission trees. 9558 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9559 while (it.hasNext()) { 9560 final BasePermission bp = it.next(); 9561 if (bp.packageSetting == null) { 9562 // We may not yet have parsed the package, so just see if 9563 // we still know about its settings. 9564 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9565 } 9566 if (bp.packageSetting == null) { 9567 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9568 + " from package " + bp.sourcePackage); 9569 it.remove(); 9570 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9571 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9572 Slog.i(TAG, "Removing old permission tree: " + bp.name 9573 + " from package " + bp.sourcePackage); 9574 flags |= UPDATE_PERMISSIONS_ALL; 9575 it.remove(); 9576 } 9577 } 9578 } 9579 9580 // Make sure all dynamic permissions have been assigned to a package, 9581 // and make sure there are no dangling permissions. 9582 it = mSettings.mPermissions.values().iterator(); 9583 while (it.hasNext()) { 9584 final BasePermission bp = it.next(); 9585 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9586 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9587 + bp.name + " pkg=" + bp.sourcePackage 9588 + " info=" + bp.pendingInfo); 9589 if (bp.packageSetting == null && bp.pendingInfo != null) { 9590 final BasePermission tree = findPermissionTreeLP(bp.name); 9591 if (tree != null && tree.perm != null) { 9592 bp.packageSetting = tree.packageSetting; 9593 bp.perm = new PackageParser.Permission(tree.perm.owner, 9594 new PermissionInfo(bp.pendingInfo)); 9595 bp.perm.info.packageName = tree.perm.info.packageName; 9596 bp.perm.info.name = bp.name; 9597 bp.uid = tree.uid; 9598 } 9599 } 9600 } 9601 if (bp.packageSetting == null) { 9602 // We may not yet have parsed the package, so just see if 9603 // we still know about its settings. 9604 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9605 } 9606 if (bp.packageSetting == null) { 9607 Slog.w(TAG, "Removing dangling permission: " + bp.name 9608 + " from package " + bp.sourcePackage); 9609 it.remove(); 9610 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9611 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9612 Slog.i(TAG, "Removing old permission: " + bp.name 9613 + " from package " + bp.sourcePackage); 9614 flags |= UPDATE_PERMISSIONS_ALL; 9615 it.remove(); 9616 } 9617 } 9618 } 9619 9620 // Now update the permissions for all packages, in particular 9621 // replace the granted permissions of the system packages. 9622 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9623 for (PackageParser.Package pkg : mPackages.values()) { 9624 if (pkg != pkgInfo) { 9625 // Only replace for packages on requested volume 9626 final String volumeUuid = getVolumeUuidForPackage(pkg); 9627 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9628 && Objects.equals(replaceVolumeUuid, volumeUuid); 9629 grantPermissionsLPw(pkg, replace, changingPkg); 9630 } 9631 } 9632 } 9633 9634 if (pkgInfo != null) { 9635 // Only replace for packages on requested volume 9636 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9637 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9638 && Objects.equals(replaceVolumeUuid, volumeUuid); 9639 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9640 } 9641 } 9642 9643 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9644 String packageOfInterest) { 9645 // IMPORTANT: There are two types of permissions: install and runtime. 9646 // Install time permissions are granted when the app is installed to 9647 // all device users and users added in the future. Runtime permissions 9648 // are granted at runtime explicitly to specific users. Normal and signature 9649 // protected permissions are install time permissions. Dangerous permissions 9650 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9651 // otherwise they are runtime permissions. This function does not manage 9652 // runtime permissions except for the case an app targeting Lollipop MR1 9653 // being upgraded to target a newer SDK, in which case dangerous permissions 9654 // are transformed from install time to runtime ones. 9655 9656 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9657 if (ps == null) { 9658 return; 9659 } 9660 9661 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9662 9663 PermissionsState permissionsState = ps.getPermissionsState(); 9664 PermissionsState origPermissions = permissionsState; 9665 9666 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9667 9668 boolean runtimePermissionsRevoked = false; 9669 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9670 9671 boolean changedInstallPermission = false; 9672 9673 if (replace) { 9674 ps.installPermissionsFixed = false; 9675 if (!ps.isSharedUser()) { 9676 origPermissions = new PermissionsState(permissionsState); 9677 permissionsState.reset(); 9678 } else { 9679 // We need to know only about runtime permission changes since the 9680 // calling code always writes the install permissions state but 9681 // the runtime ones are written only if changed. The only cases of 9682 // changed runtime permissions here are promotion of an install to 9683 // runtime and revocation of a runtime from a shared user. 9684 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9685 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9686 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9687 runtimePermissionsRevoked = true; 9688 } 9689 } 9690 } 9691 9692 permissionsState.setGlobalGids(mGlobalGids); 9693 9694 final int N = pkg.requestedPermissions.size(); 9695 for (int i=0; i<N; i++) { 9696 final String name = pkg.requestedPermissions.get(i); 9697 final BasePermission bp = mSettings.mPermissions.get(name); 9698 9699 if (DEBUG_INSTALL) { 9700 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9701 } 9702 9703 if (bp == null || bp.packageSetting == null) { 9704 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9705 Slog.w(TAG, "Unknown permission " + name 9706 + " in package " + pkg.packageName); 9707 } 9708 continue; 9709 } 9710 9711 final String perm = bp.name; 9712 boolean allowedSig = false; 9713 int grant = GRANT_DENIED; 9714 9715 // Keep track of app op permissions. 9716 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9717 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9718 if (pkgs == null) { 9719 pkgs = new ArraySet<>(); 9720 mAppOpPermissionPackages.put(bp.name, pkgs); 9721 } 9722 pkgs.add(pkg.packageName); 9723 } 9724 9725 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9726 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9727 >= Build.VERSION_CODES.M; 9728 switch (level) { 9729 case PermissionInfo.PROTECTION_NORMAL: { 9730 // For all apps normal permissions are install time ones. 9731 grant = GRANT_INSTALL; 9732 } break; 9733 9734 case PermissionInfo.PROTECTION_DANGEROUS: { 9735 // If a permission review is required for legacy apps we represent 9736 // their permissions as always granted runtime ones since we need 9737 // to keep the review required permission flag per user while an 9738 // install permission's state is shared across all users. 9739 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9740 // For legacy apps dangerous permissions are install time ones. 9741 grant = GRANT_INSTALL; 9742 } else if (origPermissions.hasInstallPermission(bp.name)) { 9743 // For legacy apps that became modern, install becomes runtime. 9744 grant = GRANT_UPGRADE; 9745 } else if (mPromoteSystemApps 9746 && isSystemApp(ps) 9747 && mExistingSystemPackages.contains(ps.name)) { 9748 // For legacy system apps, install becomes runtime. 9749 // We cannot check hasInstallPermission() for system apps since those 9750 // permissions were granted implicitly and not persisted pre-M. 9751 grant = GRANT_UPGRADE; 9752 } else { 9753 // For modern apps keep runtime permissions unchanged. 9754 grant = GRANT_RUNTIME; 9755 } 9756 } break; 9757 9758 case PermissionInfo.PROTECTION_SIGNATURE: { 9759 // For all apps signature permissions are install time ones. 9760 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9761 if (allowedSig) { 9762 grant = GRANT_INSTALL; 9763 } 9764 } break; 9765 } 9766 9767 if (DEBUG_INSTALL) { 9768 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9769 } 9770 9771 if (grant != GRANT_DENIED) { 9772 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9773 // If this is an existing, non-system package, then 9774 // we can't add any new permissions to it. 9775 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9776 // Except... if this is a permission that was added 9777 // to the platform (note: need to only do this when 9778 // updating the platform). 9779 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9780 grant = GRANT_DENIED; 9781 } 9782 } 9783 } 9784 9785 switch (grant) { 9786 case GRANT_INSTALL: { 9787 // Revoke this as runtime permission to handle the case of 9788 // a runtime permission being downgraded to an install one. 9789 // Also in permission review mode we keep dangerous permissions 9790 // for legacy apps 9791 for (int userId : UserManagerService.getInstance().getUserIds()) { 9792 if (origPermissions.getRuntimePermissionState( 9793 bp.name, userId) != null) { 9794 // Revoke the runtime permission and clear the flags. 9795 origPermissions.revokeRuntimePermission(bp, userId); 9796 origPermissions.updatePermissionFlags(bp, userId, 9797 PackageManager.MASK_PERMISSION_FLAGS, 0); 9798 // If we revoked a permission permission, we have to write. 9799 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9800 changedRuntimePermissionUserIds, userId); 9801 } 9802 } 9803 // Grant an install permission. 9804 if (permissionsState.grantInstallPermission(bp) != 9805 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9806 changedInstallPermission = true; 9807 } 9808 } break; 9809 9810 case GRANT_RUNTIME: { 9811 // Grant previously granted runtime permissions. 9812 for (int userId : UserManagerService.getInstance().getUserIds()) { 9813 PermissionState permissionState = origPermissions 9814 .getRuntimePermissionState(bp.name, userId); 9815 int flags = permissionState != null 9816 ? permissionState.getFlags() : 0; 9817 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9818 if (permissionsState.grantRuntimePermission(bp, userId) == 9819 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9820 // If we cannot put the permission as it was, we have to write. 9821 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9822 changedRuntimePermissionUserIds, userId); 9823 } 9824 // If the app supports runtime permissions no need for a review. 9825 if (Build.PERMISSIONS_REVIEW_REQUIRED 9826 && appSupportsRuntimePermissions 9827 && (flags & PackageManager 9828 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9829 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9830 // Since we changed the flags, we have to write. 9831 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9832 changedRuntimePermissionUserIds, userId); 9833 } 9834 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9835 && !appSupportsRuntimePermissions) { 9836 // For legacy apps that need a permission review, every new 9837 // runtime permission is granted but it is pending a review. 9838 // We also need to review only platform defined runtime 9839 // permissions as these are the only ones the platform knows 9840 // how to disable the API to simulate revocation as legacy 9841 // apps don't expect to run with revoked permissions. 9842 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9843 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9844 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9845 // We changed the flags, hence have to write. 9846 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9847 changedRuntimePermissionUserIds, userId); 9848 } 9849 } 9850 if (permissionsState.grantRuntimePermission(bp, userId) 9851 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9852 // We changed the permission, hence have to write. 9853 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9854 changedRuntimePermissionUserIds, userId); 9855 } 9856 } 9857 // Propagate the permission flags. 9858 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9859 } 9860 } break; 9861 9862 case GRANT_UPGRADE: { 9863 // Grant runtime permissions for a previously held install permission. 9864 PermissionState permissionState = origPermissions 9865 .getInstallPermissionState(bp.name); 9866 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9867 9868 if (origPermissions.revokeInstallPermission(bp) 9869 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9870 // We will be transferring the permission flags, so clear them. 9871 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9872 PackageManager.MASK_PERMISSION_FLAGS, 0); 9873 changedInstallPermission = true; 9874 } 9875 9876 // If the permission is not to be promoted to runtime we ignore it and 9877 // also its other flags as they are not applicable to install permissions. 9878 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9879 for (int userId : currentUserIds) { 9880 if (permissionsState.grantRuntimePermission(bp, userId) != 9881 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9882 // Transfer the permission flags. 9883 permissionsState.updatePermissionFlags(bp, userId, 9884 flags, flags); 9885 // If we granted the permission, we have to write. 9886 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9887 changedRuntimePermissionUserIds, userId); 9888 } 9889 } 9890 } 9891 } break; 9892 9893 default: { 9894 if (packageOfInterest == null 9895 || packageOfInterest.equals(pkg.packageName)) { 9896 Slog.w(TAG, "Not granting permission " + perm 9897 + " to package " + pkg.packageName 9898 + " because it was previously installed without"); 9899 } 9900 } break; 9901 } 9902 } else { 9903 if (permissionsState.revokeInstallPermission(bp) != 9904 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9905 // Also drop the permission flags. 9906 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9907 PackageManager.MASK_PERMISSION_FLAGS, 0); 9908 changedInstallPermission = true; 9909 Slog.i(TAG, "Un-granting permission " + perm 9910 + " from package " + pkg.packageName 9911 + " (protectionLevel=" + bp.protectionLevel 9912 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9913 + ")"); 9914 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9915 // Don't print warning for app op permissions, since it is fine for them 9916 // not to be granted, there is a UI for the user to decide. 9917 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9918 Slog.w(TAG, "Not granting permission " + perm 9919 + " to package " + pkg.packageName 9920 + " (protectionLevel=" + bp.protectionLevel 9921 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9922 + ")"); 9923 } 9924 } 9925 } 9926 } 9927 9928 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9929 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9930 // This is the first that we have heard about this package, so the 9931 // permissions we have now selected are fixed until explicitly 9932 // changed. 9933 ps.installPermissionsFixed = true; 9934 } 9935 9936 // Persist the runtime permissions state for users with changes. If permissions 9937 // were revoked because no app in the shared user declares them we have to 9938 // write synchronously to avoid losing runtime permissions state. 9939 for (int userId : changedRuntimePermissionUserIds) { 9940 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9941 } 9942 9943 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9944 } 9945 9946 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9947 boolean allowed = false; 9948 final int NP = PackageParser.NEW_PERMISSIONS.length; 9949 for (int ip=0; ip<NP; ip++) { 9950 final PackageParser.NewPermissionInfo npi 9951 = PackageParser.NEW_PERMISSIONS[ip]; 9952 if (npi.name.equals(perm) 9953 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9954 allowed = true; 9955 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9956 + pkg.packageName); 9957 break; 9958 } 9959 } 9960 return allowed; 9961 } 9962 9963 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9964 BasePermission bp, PermissionsState origPermissions) { 9965 boolean allowed; 9966 allowed = (compareSignatures( 9967 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9968 == PackageManager.SIGNATURE_MATCH) 9969 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9970 == PackageManager.SIGNATURE_MATCH); 9971 if (!allowed && (bp.protectionLevel 9972 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9973 if (isSystemApp(pkg)) { 9974 // For updated system applications, a system permission 9975 // is granted only if it had been defined by the original application. 9976 if (pkg.isUpdatedSystemApp()) { 9977 final PackageSetting sysPs = mSettings 9978 .getDisabledSystemPkgLPr(pkg.packageName); 9979 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9980 // If the original was granted this permission, we take 9981 // that grant decision as read and propagate it to the 9982 // update. 9983 if (sysPs.isPrivileged()) { 9984 allowed = true; 9985 } 9986 } else { 9987 // The system apk may have been updated with an older 9988 // version of the one on the data partition, but which 9989 // granted a new system permission that it didn't have 9990 // before. In this case we do want to allow the app to 9991 // now get the new permission if the ancestral apk is 9992 // privileged to get it. 9993 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9994 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9995 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9996 allowed = true; 9997 break; 9998 } 9999 } 10000 } 10001 // Also if a privileged parent package on the system image or any of 10002 // its children requested a privileged permission, the updated child 10003 // packages can also get the permission. 10004 if (pkg.parentPackage != null) { 10005 final PackageSetting disabledSysParentPs = mSettings 10006 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10007 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10008 && disabledSysParentPs.isPrivileged()) { 10009 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10010 allowed = true; 10011 } else if (disabledSysParentPs.pkg.childPackages != null) { 10012 final int count = disabledSysParentPs.pkg.childPackages.size(); 10013 for (int i = 0; i < count; i++) { 10014 PackageParser.Package disabledSysChildPkg = 10015 disabledSysParentPs.pkg.childPackages.get(i); 10016 if (isPackageRequestingPermission(disabledSysChildPkg, 10017 perm)) { 10018 allowed = true; 10019 break; 10020 } 10021 } 10022 } 10023 } 10024 } 10025 } 10026 } else { 10027 allowed = isPrivilegedApp(pkg); 10028 } 10029 } 10030 } 10031 if (!allowed) { 10032 if (!allowed && (bp.protectionLevel 10033 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10034 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10035 // If this was a previously normal/dangerous permission that got moved 10036 // to a system permission as part of the runtime permission redesign, then 10037 // we still want to blindly grant it to old apps. 10038 allowed = true; 10039 } 10040 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10041 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10042 // If this permission is to be granted to the system installer and 10043 // this app is an installer, then it gets the permission. 10044 allowed = true; 10045 } 10046 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10047 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10048 // If this permission is to be granted to the system verifier and 10049 // this app is a verifier, then it gets the permission. 10050 allowed = true; 10051 } 10052 if (!allowed && (bp.protectionLevel 10053 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10054 && isSystemApp(pkg)) { 10055 // Any pre-installed system app is allowed to get this permission. 10056 allowed = true; 10057 } 10058 if (!allowed && (bp.protectionLevel 10059 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10060 // For development permissions, a development permission 10061 // is granted only if it was already granted. 10062 allowed = origPermissions.hasInstallPermission(perm); 10063 } 10064 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10065 && pkg.packageName.equals(mSetupWizardPackage)) { 10066 // If this permission is to be granted to the system setup wizard and 10067 // this app is a setup wizard, then it gets the permission. 10068 allowed = true; 10069 } 10070 } 10071 return allowed; 10072 } 10073 10074 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10075 final int permCount = pkg.requestedPermissions.size(); 10076 for (int j = 0; j < permCount; j++) { 10077 String requestedPermission = pkg.requestedPermissions.get(j); 10078 if (permission.equals(requestedPermission)) { 10079 return true; 10080 } 10081 } 10082 return false; 10083 } 10084 10085 final class ActivityIntentResolver 10086 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10087 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10088 boolean defaultOnly, int userId) { 10089 if (!sUserManager.exists(userId)) return null; 10090 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10091 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10092 } 10093 10094 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10095 int userId) { 10096 if (!sUserManager.exists(userId)) return null; 10097 mFlags = flags; 10098 return super.queryIntent(intent, resolvedType, 10099 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10100 } 10101 10102 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10103 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10104 if (!sUserManager.exists(userId)) return null; 10105 if (packageActivities == null) { 10106 return null; 10107 } 10108 mFlags = flags; 10109 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10110 final int N = packageActivities.size(); 10111 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10112 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10113 10114 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10115 for (int i = 0; i < N; ++i) { 10116 intentFilters = packageActivities.get(i).intents; 10117 if (intentFilters != null && intentFilters.size() > 0) { 10118 PackageParser.ActivityIntentInfo[] array = 10119 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10120 intentFilters.toArray(array); 10121 listCut.add(array); 10122 } 10123 } 10124 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10125 } 10126 10127 /** 10128 * Finds a privileged activity that matches the specified activity names. 10129 */ 10130 private PackageParser.Activity findMatchingActivity( 10131 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10132 for (PackageParser.Activity sysActivity : activityList) { 10133 if (sysActivity.info.name.equals(activityInfo.name)) { 10134 return sysActivity; 10135 } 10136 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10137 return sysActivity; 10138 } 10139 if (sysActivity.info.targetActivity != null) { 10140 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10141 return sysActivity; 10142 } 10143 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10144 return sysActivity; 10145 } 10146 } 10147 } 10148 return null; 10149 } 10150 10151 public class IterGenerator<E> { 10152 public Iterator<E> generate(ActivityIntentInfo info) { 10153 return null; 10154 } 10155 } 10156 10157 public class ActionIterGenerator extends IterGenerator<String> { 10158 @Override 10159 public Iterator<String> generate(ActivityIntentInfo info) { 10160 return info.actionsIterator(); 10161 } 10162 } 10163 10164 public class CategoriesIterGenerator extends IterGenerator<String> { 10165 @Override 10166 public Iterator<String> generate(ActivityIntentInfo info) { 10167 return info.categoriesIterator(); 10168 } 10169 } 10170 10171 public class SchemesIterGenerator extends IterGenerator<String> { 10172 @Override 10173 public Iterator<String> generate(ActivityIntentInfo info) { 10174 return info.schemesIterator(); 10175 } 10176 } 10177 10178 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10179 @Override 10180 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10181 return info.authoritiesIterator(); 10182 } 10183 } 10184 10185 /** 10186 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10187 * MODIFIED. Do not pass in a list that should not be changed. 10188 */ 10189 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10190 IterGenerator<T> generator, Iterator<T> searchIterator) { 10191 // loop through the set of actions; every one must be found in the intent filter 10192 while (searchIterator.hasNext()) { 10193 // we must have at least one filter in the list to consider a match 10194 if (intentList.size() == 0) { 10195 break; 10196 } 10197 10198 final T searchAction = searchIterator.next(); 10199 10200 // loop through the set of intent filters 10201 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10202 while (intentIter.hasNext()) { 10203 final ActivityIntentInfo intentInfo = intentIter.next(); 10204 boolean selectionFound = false; 10205 10206 // loop through the intent filter's selection criteria; at least one 10207 // of them must match the searched criteria 10208 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10209 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10210 final T intentSelection = intentSelectionIter.next(); 10211 if (intentSelection != null && intentSelection.equals(searchAction)) { 10212 selectionFound = true; 10213 break; 10214 } 10215 } 10216 10217 // the selection criteria wasn't found in this filter's set; this filter 10218 // is not a potential match 10219 if (!selectionFound) { 10220 intentIter.remove(); 10221 } 10222 } 10223 } 10224 } 10225 10226 private boolean isProtectedAction(ActivityIntentInfo filter) { 10227 final Iterator<String> actionsIter = filter.actionsIterator(); 10228 while (actionsIter != null && actionsIter.hasNext()) { 10229 final String filterAction = actionsIter.next(); 10230 if (PROTECTED_ACTIONS.contains(filterAction)) { 10231 return true; 10232 } 10233 } 10234 return false; 10235 } 10236 10237 /** 10238 * Adjusts the priority of the given intent filter according to policy. 10239 * <p> 10240 * <ul> 10241 * <li>The priority for non privileged applications is capped to '0'</li> 10242 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10243 * <li>The priority for unbundled updates to privileged applications is capped to the 10244 * priority defined on the system partition</li> 10245 * </ul> 10246 * <p> 10247 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10248 * allowed to obtain any priority on any action. 10249 */ 10250 private void adjustPriority( 10251 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10252 // nothing to do; priority is fine as-is 10253 if (intent.getPriority() <= 0) { 10254 return; 10255 } 10256 10257 final ActivityInfo activityInfo = intent.activity.info; 10258 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10259 10260 final boolean privilegedApp = 10261 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10262 if (!privilegedApp) { 10263 // non-privileged applications can never define a priority >0 10264 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10265 + " package: " + applicationInfo.packageName 10266 + " activity: " + intent.activity.className 10267 + " origPrio: " + intent.getPriority()); 10268 intent.setPriority(0); 10269 return; 10270 } 10271 10272 if (systemActivities == null) { 10273 // the system package is not disabled; we're parsing the system partition 10274 if (isProtectedAction(intent)) { 10275 if (mDeferProtectedFilters) { 10276 // We can't deal with these just yet. No component should ever obtain a 10277 // >0 priority for a protected actions, with ONE exception -- the setup 10278 // wizard. The setup wizard, however, cannot be known until we're able to 10279 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10280 // until all intent filters have been processed. Chicken, meet egg. 10281 // Let the filter temporarily have a high priority and rectify the 10282 // priorities after all system packages have been scanned. 10283 mProtectedFilters.add(intent); 10284 if (DEBUG_FILTERS) { 10285 Slog.i(TAG, "Protected action; save for later;" 10286 + " package: " + applicationInfo.packageName 10287 + " activity: " + intent.activity.className 10288 + " origPrio: " + intent.getPriority()); 10289 } 10290 return; 10291 } else { 10292 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10293 Slog.i(TAG, "No setup wizard;" 10294 + " All protected intents capped to priority 0"); 10295 } 10296 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10297 if (DEBUG_FILTERS) { 10298 Slog.i(TAG, "Found setup wizard;" 10299 + " allow priority " + intent.getPriority() + ";" 10300 + " package: " + intent.activity.info.packageName 10301 + " activity: " + intent.activity.className 10302 + " priority: " + intent.getPriority()); 10303 } 10304 // setup wizard gets whatever it wants 10305 return; 10306 } 10307 Slog.w(TAG, "Protected action; cap priority to 0;" 10308 + " package: " + intent.activity.info.packageName 10309 + " activity: " + intent.activity.className 10310 + " origPrio: " + intent.getPriority()); 10311 intent.setPriority(0); 10312 return; 10313 } 10314 } 10315 // privileged apps on the system image get whatever priority they request 10316 return; 10317 } 10318 10319 // privileged app unbundled update ... try to find the same activity 10320 final PackageParser.Activity foundActivity = 10321 findMatchingActivity(systemActivities, activityInfo); 10322 if (foundActivity == null) { 10323 // this is a new activity; it cannot obtain >0 priority 10324 if (DEBUG_FILTERS) { 10325 Slog.i(TAG, "New activity; cap priority to 0;" 10326 + " package: " + applicationInfo.packageName 10327 + " activity: " + intent.activity.className 10328 + " origPrio: " + intent.getPriority()); 10329 } 10330 intent.setPriority(0); 10331 return; 10332 } 10333 10334 // found activity, now check for filter equivalence 10335 10336 // a shallow copy is enough; we modify the list, not its contents 10337 final List<ActivityIntentInfo> intentListCopy = 10338 new ArrayList<>(foundActivity.intents); 10339 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10340 10341 // find matching action subsets 10342 final Iterator<String> actionsIterator = intent.actionsIterator(); 10343 if (actionsIterator != null) { 10344 getIntentListSubset( 10345 intentListCopy, new ActionIterGenerator(), actionsIterator); 10346 if (intentListCopy.size() == 0) { 10347 // no more intents to match; we're not equivalent 10348 if (DEBUG_FILTERS) { 10349 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10350 + " package: " + applicationInfo.packageName 10351 + " activity: " + intent.activity.className 10352 + " origPrio: " + intent.getPriority()); 10353 } 10354 intent.setPriority(0); 10355 return; 10356 } 10357 } 10358 10359 // find matching category subsets 10360 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10361 if (categoriesIterator != null) { 10362 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10363 categoriesIterator); 10364 if (intentListCopy.size() == 0) { 10365 // no more intents to match; we're not equivalent 10366 if (DEBUG_FILTERS) { 10367 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10368 + " package: " + applicationInfo.packageName 10369 + " activity: " + intent.activity.className 10370 + " origPrio: " + intent.getPriority()); 10371 } 10372 intent.setPriority(0); 10373 return; 10374 } 10375 } 10376 10377 // find matching schemes subsets 10378 final Iterator<String> schemesIterator = intent.schemesIterator(); 10379 if (schemesIterator != null) { 10380 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10381 schemesIterator); 10382 if (intentListCopy.size() == 0) { 10383 // no more intents to match; we're not equivalent 10384 if (DEBUG_FILTERS) { 10385 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10386 + " package: " + applicationInfo.packageName 10387 + " activity: " + intent.activity.className 10388 + " origPrio: " + intent.getPriority()); 10389 } 10390 intent.setPriority(0); 10391 return; 10392 } 10393 } 10394 10395 // find matching authorities subsets 10396 final Iterator<IntentFilter.AuthorityEntry> 10397 authoritiesIterator = intent.authoritiesIterator(); 10398 if (authoritiesIterator != null) { 10399 getIntentListSubset(intentListCopy, 10400 new AuthoritiesIterGenerator(), 10401 authoritiesIterator); 10402 if (intentListCopy.size() == 0) { 10403 // no more intents to match; we're not equivalent 10404 if (DEBUG_FILTERS) { 10405 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10406 + " package: " + applicationInfo.packageName 10407 + " activity: " + intent.activity.className 10408 + " origPrio: " + intent.getPriority()); 10409 } 10410 intent.setPriority(0); 10411 return; 10412 } 10413 } 10414 10415 // we found matching filter(s); app gets the max priority of all intents 10416 int cappedPriority = 0; 10417 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10418 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10419 } 10420 if (intent.getPriority() > cappedPriority) { 10421 if (DEBUG_FILTERS) { 10422 Slog.i(TAG, "Found matching filter(s);" 10423 + " cap priority to " + cappedPriority + ";" 10424 + " package: " + applicationInfo.packageName 10425 + " activity: " + intent.activity.className 10426 + " origPrio: " + intent.getPriority()); 10427 } 10428 intent.setPriority(cappedPriority); 10429 return; 10430 } 10431 // all this for nothing; the requested priority was <= what was on the system 10432 } 10433 10434 public final void addActivity(PackageParser.Activity a, String type) { 10435 mActivities.put(a.getComponentName(), a); 10436 if (DEBUG_SHOW_INFO) 10437 Log.v( 10438 TAG, " " + type + " " + 10439 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10440 if (DEBUG_SHOW_INFO) 10441 Log.v(TAG, " Class=" + a.info.name); 10442 final int NI = a.intents.size(); 10443 for (int j=0; j<NI; j++) { 10444 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10445 if ("activity".equals(type)) { 10446 final PackageSetting ps = 10447 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10448 final List<PackageParser.Activity> systemActivities = 10449 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10450 adjustPriority(systemActivities, intent); 10451 } 10452 if (DEBUG_SHOW_INFO) { 10453 Log.v(TAG, " IntentFilter:"); 10454 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10455 } 10456 if (!intent.debugCheck()) { 10457 Log.w(TAG, "==> For Activity " + a.info.name); 10458 } 10459 addFilter(intent); 10460 } 10461 } 10462 10463 public final void removeActivity(PackageParser.Activity a, String type) { 10464 mActivities.remove(a.getComponentName()); 10465 if (DEBUG_SHOW_INFO) { 10466 Log.v(TAG, " " + type + " " 10467 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10468 : a.info.name) + ":"); 10469 Log.v(TAG, " Class=" + a.info.name); 10470 } 10471 final int NI = a.intents.size(); 10472 for (int j=0; j<NI; j++) { 10473 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10474 if (DEBUG_SHOW_INFO) { 10475 Log.v(TAG, " IntentFilter:"); 10476 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10477 } 10478 removeFilter(intent); 10479 } 10480 } 10481 10482 @Override 10483 protected boolean allowFilterResult( 10484 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10485 ActivityInfo filterAi = filter.activity.info; 10486 for (int i=dest.size()-1; i>=0; i--) { 10487 ActivityInfo destAi = dest.get(i).activityInfo; 10488 if (destAi.name == filterAi.name 10489 && destAi.packageName == filterAi.packageName) { 10490 return false; 10491 } 10492 } 10493 return true; 10494 } 10495 10496 @Override 10497 protected ActivityIntentInfo[] newArray(int size) { 10498 return new ActivityIntentInfo[size]; 10499 } 10500 10501 @Override 10502 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10503 if (!sUserManager.exists(userId)) return true; 10504 PackageParser.Package p = filter.activity.owner; 10505 if (p != null) { 10506 PackageSetting ps = (PackageSetting)p.mExtras; 10507 if (ps != null) { 10508 // System apps are never considered stopped for purposes of 10509 // filtering, because there may be no way for the user to 10510 // actually re-launch them. 10511 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10512 && ps.getStopped(userId); 10513 } 10514 } 10515 return false; 10516 } 10517 10518 @Override 10519 protected boolean isPackageForFilter(String packageName, 10520 PackageParser.ActivityIntentInfo info) { 10521 return packageName.equals(info.activity.owner.packageName); 10522 } 10523 10524 @Override 10525 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10526 int match, int userId) { 10527 if (!sUserManager.exists(userId)) return null; 10528 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10529 return null; 10530 } 10531 final PackageParser.Activity activity = info.activity; 10532 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10533 if (ps == null) { 10534 return null; 10535 } 10536 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10537 ps.readUserState(userId), userId); 10538 if (ai == null) { 10539 return null; 10540 } 10541 final ResolveInfo res = new ResolveInfo(); 10542 res.activityInfo = ai; 10543 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10544 res.filter = info; 10545 } 10546 if (info != null) { 10547 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10548 } 10549 res.priority = info.getPriority(); 10550 res.preferredOrder = activity.owner.mPreferredOrder; 10551 //System.out.println("Result: " + res.activityInfo.className + 10552 // " = " + res.priority); 10553 res.match = match; 10554 res.isDefault = info.hasDefault; 10555 res.labelRes = info.labelRes; 10556 res.nonLocalizedLabel = info.nonLocalizedLabel; 10557 if (userNeedsBadging(userId)) { 10558 res.noResourceId = true; 10559 } else { 10560 res.icon = info.icon; 10561 } 10562 res.iconResourceId = info.icon; 10563 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10564 return res; 10565 } 10566 10567 @Override 10568 protected void sortResults(List<ResolveInfo> results) { 10569 Collections.sort(results, mResolvePrioritySorter); 10570 } 10571 10572 @Override 10573 protected void dumpFilter(PrintWriter out, String prefix, 10574 PackageParser.ActivityIntentInfo filter) { 10575 out.print(prefix); out.print( 10576 Integer.toHexString(System.identityHashCode(filter.activity))); 10577 out.print(' '); 10578 filter.activity.printComponentShortName(out); 10579 out.print(" filter "); 10580 out.println(Integer.toHexString(System.identityHashCode(filter))); 10581 } 10582 10583 @Override 10584 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10585 return filter.activity; 10586 } 10587 10588 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10589 PackageParser.Activity activity = (PackageParser.Activity)label; 10590 out.print(prefix); out.print( 10591 Integer.toHexString(System.identityHashCode(activity))); 10592 out.print(' '); 10593 activity.printComponentShortName(out); 10594 if (count > 1) { 10595 out.print(" ("); out.print(count); out.print(" filters)"); 10596 } 10597 out.println(); 10598 } 10599 10600 // Keys are String (activity class name), values are Activity. 10601 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10602 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10603 private int mFlags; 10604 } 10605 10606 private final class ServiceIntentResolver 10607 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10608 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10609 boolean defaultOnly, int userId) { 10610 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10611 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10612 } 10613 10614 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10615 int userId) { 10616 if (!sUserManager.exists(userId)) return null; 10617 mFlags = flags; 10618 return super.queryIntent(intent, resolvedType, 10619 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10620 } 10621 10622 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10623 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10624 if (!sUserManager.exists(userId)) return null; 10625 if (packageServices == null) { 10626 return null; 10627 } 10628 mFlags = flags; 10629 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10630 final int N = packageServices.size(); 10631 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10632 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10633 10634 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10635 for (int i = 0; i < N; ++i) { 10636 intentFilters = packageServices.get(i).intents; 10637 if (intentFilters != null && intentFilters.size() > 0) { 10638 PackageParser.ServiceIntentInfo[] array = 10639 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10640 intentFilters.toArray(array); 10641 listCut.add(array); 10642 } 10643 } 10644 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10645 } 10646 10647 public final void addService(PackageParser.Service s) { 10648 mServices.put(s.getComponentName(), s); 10649 if (DEBUG_SHOW_INFO) { 10650 Log.v(TAG, " " 10651 + (s.info.nonLocalizedLabel != null 10652 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10653 Log.v(TAG, " Class=" + s.info.name); 10654 } 10655 final int NI = s.intents.size(); 10656 int j; 10657 for (j=0; j<NI; j++) { 10658 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10659 if (DEBUG_SHOW_INFO) { 10660 Log.v(TAG, " IntentFilter:"); 10661 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10662 } 10663 if (!intent.debugCheck()) { 10664 Log.w(TAG, "==> For Service " + s.info.name); 10665 } 10666 addFilter(intent); 10667 } 10668 } 10669 10670 public final void removeService(PackageParser.Service s) { 10671 mServices.remove(s.getComponentName()); 10672 if (DEBUG_SHOW_INFO) { 10673 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10674 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10675 Log.v(TAG, " Class=" + s.info.name); 10676 } 10677 final int NI = s.intents.size(); 10678 int j; 10679 for (j=0; j<NI; j++) { 10680 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10681 if (DEBUG_SHOW_INFO) { 10682 Log.v(TAG, " IntentFilter:"); 10683 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10684 } 10685 removeFilter(intent); 10686 } 10687 } 10688 10689 @Override 10690 protected boolean allowFilterResult( 10691 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10692 ServiceInfo filterSi = filter.service.info; 10693 for (int i=dest.size()-1; i>=0; i--) { 10694 ServiceInfo destAi = dest.get(i).serviceInfo; 10695 if (destAi.name == filterSi.name 10696 && destAi.packageName == filterSi.packageName) { 10697 return false; 10698 } 10699 } 10700 return true; 10701 } 10702 10703 @Override 10704 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10705 return new PackageParser.ServiceIntentInfo[size]; 10706 } 10707 10708 @Override 10709 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10710 if (!sUserManager.exists(userId)) return true; 10711 PackageParser.Package p = filter.service.owner; 10712 if (p != null) { 10713 PackageSetting ps = (PackageSetting)p.mExtras; 10714 if (ps != null) { 10715 // System apps are never considered stopped for purposes of 10716 // filtering, because there may be no way for the user to 10717 // actually re-launch them. 10718 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10719 && ps.getStopped(userId); 10720 } 10721 } 10722 return false; 10723 } 10724 10725 @Override 10726 protected boolean isPackageForFilter(String packageName, 10727 PackageParser.ServiceIntentInfo info) { 10728 return packageName.equals(info.service.owner.packageName); 10729 } 10730 10731 @Override 10732 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10733 int match, int userId) { 10734 if (!sUserManager.exists(userId)) return null; 10735 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10736 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10737 return null; 10738 } 10739 final PackageParser.Service service = info.service; 10740 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10741 if (ps == null) { 10742 return null; 10743 } 10744 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10745 ps.readUserState(userId), userId); 10746 if (si == null) { 10747 return null; 10748 } 10749 final ResolveInfo res = new ResolveInfo(); 10750 res.serviceInfo = si; 10751 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10752 res.filter = filter; 10753 } 10754 res.priority = info.getPriority(); 10755 res.preferredOrder = service.owner.mPreferredOrder; 10756 res.match = match; 10757 res.isDefault = info.hasDefault; 10758 res.labelRes = info.labelRes; 10759 res.nonLocalizedLabel = info.nonLocalizedLabel; 10760 res.icon = info.icon; 10761 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10762 return res; 10763 } 10764 10765 @Override 10766 protected void sortResults(List<ResolveInfo> results) { 10767 Collections.sort(results, mResolvePrioritySorter); 10768 } 10769 10770 @Override 10771 protected void dumpFilter(PrintWriter out, String prefix, 10772 PackageParser.ServiceIntentInfo filter) { 10773 out.print(prefix); out.print( 10774 Integer.toHexString(System.identityHashCode(filter.service))); 10775 out.print(' '); 10776 filter.service.printComponentShortName(out); 10777 out.print(" filter "); 10778 out.println(Integer.toHexString(System.identityHashCode(filter))); 10779 } 10780 10781 @Override 10782 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10783 return filter.service; 10784 } 10785 10786 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10787 PackageParser.Service service = (PackageParser.Service)label; 10788 out.print(prefix); out.print( 10789 Integer.toHexString(System.identityHashCode(service))); 10790 out.print(' '); 10791 service.printComponentShortName(out); 10792 if (count > 1) { 10793 out.print(" ("); out.print(count); out.print(" filters)"); 10794 } 10795 out.println(); 10796 } 10797 10798// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10799// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10800// final List<ResolveInfo> retList = Lists.newArrayList(); 10801// while (i.hasNext()) { 10802// final ResolveInfo resolveInfo = (ResolveInfo) i; 10803// if (isEnabledLP(resolveInfo.serviceInfo)) { 10804// retList.add(resolveInfo); 10805// } 10806// } 10807// return retList; 10808// } 10809 10810 // Keys are String (activity class name), values are Activity. 10811 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10812 = new ArrayMap<ComponentName, PackageParser.Service>(); 10813 private int mFlags; 10814 }; 10815 10816 private final class ProviderIntentResolver 10817 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10818 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10819 boolean defaultOnly, int userId) { 10820 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10821 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10822 } 10823 10824 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10825 int userId) { 10826 if (!sUserManager.exists(userId)) 10827 return null; 10828 mFlags = flags; 10829 return super.queryIntent(intent, resolvedType, 10830 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10831 } 10832 10833 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10834 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10835 if (!sUserManager.exists(userId)) 10836 return null; 10837 if (packageProviders == null) { 10838 return null; 10839 } 10840 mFlags = flags; 10841 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10842 final int N = packageProviders.size(); 10843 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10844 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10845 10846 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10847 for (int i = 0; i < N; ++i) { 10848 intentFilters = packageProviders.get(i).intents; 10849 if (intentFilters != null && intentFilters.size() > 0) { 10850 PackageParser.ProviderIntentInfo[] array = 10851 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10852 intentFilters.toArray(array); 10853 listCut.add(array); 10854 } 10855 } 10856 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10857 } 10858 10859 public final void addProvider(PackageParser.Provider p) { 10860 if (mProviders.containsKey(p.getComponentName())) { 10861 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10862 return; 10863 } 10864 10865 mProviders.put(p.getComponentName(), p); 10866 if (DEBUG_SHOW_INFO) { 10867 Log.v(TAG, " " 10868 + (p.info.nonLocalizedLabel != null 10869 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10870 Log.v(TAG, " Class=" + p.info.name); 10871 } 10872 final int NI = p.intents.size(); 10873 int j; 10874 for (j = 0; j < NI; j++) { 10875 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10876 if (DEBUG_SHOW_INFO) { 10877 Log.v(TAG, " IntentFilter:"); 10878 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10879 } 10880 if (!intent.debugCheck()) { 10881 Log.w(TAG, "==> For Provider " + p.info.name); 10882 } 10883 addFilter(intent); 10884 } 10885 } 10886 10887 public final void removeProvider(PackageParser.Provider p) { 10888 mProviders.remove(p.getComponentName()); 10889 if (DEBUG_SHOW_INFO) { 10890 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10891 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10892 Log.v(TAG, " Class=" + p.info.name); 10893 } 10894 final int NI = p.intents.size(); 10895 int j; 10896 for (j = 0; j < NI; j++) { 10897 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10898 if (DEBUG_SHOW_INFO) { 10899 Log.v(TAG, " IntentFilter:"); 10900 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10901 } 10902 removeFilter(intent); 10903 } 10904 } 10905 10906 @Override 10907 protected boolean allowFilterResult( 10908 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10909 ProviderInfo filterPi = filter.provider.info; 10910 for (int i = dest.size() - 1; i >= 0; i--) { 10911 ProviderInfo destPi = dest.get(i).providerInfo; 10912 if (destPi.name == filterPi.name 10913 && destPi.packageName == filterPi.packageName) { 10914 return false; 10915 } 10916 } 10917 return true; 10918 } 10919 10920 @Override 10921 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10922 return new PackageParser.ProviderIntentInfo[size]; 10923 } 10924 10925 @Override 10926 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10927 if (!sUserManager.exists(userId)) 10928 return true; 10929 PackageParser.Package p = filter.provider.owner; 10930 if (p != null) { 10931 PackageSetting ps = (PackageSetting) p.mExtras; 10932 if (ps != null) { 10933 // System apps are never considered stopped for purposes of 10934 // filtering, because there may be no way for the user to 10935 // actually re-launch them. 10936 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10937 && ps.getStopped(userId); 10938 } 10939 } 10940 return false; 10941 } 10942 10943 @Override 10944 protected boolean isPackageForFilter(String packageName, 10945 PackageParser.ProviderIntentInfo info) { 10946 return packageName.equals(info.provider.owner.packageName); 10947 } 10948 10949 @Override 10950 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10951 int match, int userId) { 10952 if (!sUserManager.exists(userId)) 10953 return null; 10954 final PackageParser.ProviderIntentInfo info = filter; 10955 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10956 return null; 10957 } 10958 final PackageParser.Provider provider = info.provider; 10959 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10960 if (ps == null) { 10961 return null; 10962 } 10963 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10964 ps.readUserState(userId), userId); 10965 if (pi == null) { 10966 return null; 10967 } 10968 final ResolveInfo res = new ResolveInfo(); 10969 res.providerInfo = pi; 10970 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10971 res.filter = filter; 10972 } 10973 res.priority = info.getPriority(); 10974 res.preferredOrder = provider.owner.mPreferredOrder; 10975 res.match = match; 10976 res.isDefault = info.hasDefault; 10977 res.labelRes = info.labelRes; 10978 res.nonLocalizedLabel = info.nonLocalizedLabel; 10979 res.icon = info.icon; 10980 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10981 return res; 10982 } 10983 10984 @Override 10985 protected void sortResults(List<ResolveInfo> results) { 10986 Collections.sort(results, mResolvePrioritySorter); 10987 } 10988 10989 @Override 10990 protected void dumpFilter(PrintWriter out, String prefix, 10991 PackageParser.ProviderIntentInfo filter) { 10992 out.print(prefix); 10993 out.print( 10994 Integer.toHexString(System.identityHashCode(filter.provider))); 10995 out.print(' '); 10996 filter.provider.printComponentShortName(out); 10997 out.print(" filter "); 10998 out.println(Integer.toHexString(System.identityHashCode(filter))); 10999 } 11000 11001 @Override 11002 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11003 return filter.provider; 11004 } 11005 11006 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11007 PackageParser.Provider provider = (PackageParser.Provider)label; 11008 out.print(prefix); out.print( 11009 Integer.toHexString(System.identityHashCode(provider))); 11010 out.print(' '); 11011 provider.printComponentShortName(out); 11012 if (count > 1) { 11013 out.print(" ("); out.print(count); out.print(" filters)"); 11014 } 11015 out.println(); 11016 } 11017 11018 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11019 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11020 private int mFlags; 11021 } 11022 11023 private static final class EphemeralIntentResolver 11024 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11025 @Override 11026 protected EphemeralResolveIntentInfo[] newArray(int size) { 11027 return new EphemeralResolveIntentInfo[size]; 11028 } 11029 11030 @Override 11031 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11032 return true; 11033 } 11034 11035 @Override 11036 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11037 int userId) { 11038 if (!sUserManager.exists(userId)) { 11039 return null; 11040 } 11041 return info.getEphemeralResolveInfo(); 11042 } 11043 } 11044 11045 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11046 new Comparator<ResolveInfo>() { 11047 public int compare(ResolveInfo r1, ResolveInfo r2) { 11048 int v1 = r1.priority; 11049 int v2 = r2.priority; 11050 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11051 if (v1 != v2) { 11052 return (v1 > v2) ? -1 : 1; 11053 } 11054 v1 = r1.preferredOrder; 11055 v2 = r2.preferredOrder; 11056 if (v1 != v2) { 11057 return (v1 > v2) ? -1 : 1; 11058 } 11059 if (r1.isDefault != r2.isDefault) { 11060 return r1.isDefault ? -1 : 1; 11061 } 11062 v1 = r1.match; 11063 v2 = r2.match; 11064 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11065 if (v1 != v2) { 11066 return (v1 > v2) ? -1 : 1; 11067 } 11068 if (r1.system != r2.system) { 11069 return r1.system ? -1 : 1; 11070 } 11071 if (r1.activityInfo != null) { 11072 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11073 } 11074 if (r1.serviceInfo != null) { 11075 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11076 } 11077 if (r1.providerInfo != null) { 11078 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11079 } 11080 return 0; 11081 } 11082 }; 11083 11084 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11085 new Comparator<ProviderInfo>() { 11086 public int compare(ProviderInfo p1, ProviderInfo p2) { 11087 final int v1 = p1.initOrder; 11088 final int v2 = p2.initOrder; 11089 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11090 } 11091 }; 11092 11093 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11094 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11095 final int[] userIds) { 11096 mHandler.post(new Runnable() { 11097 @Override 11098 public void run() { 11099 try { 11100 final IActivityManager am = ActivityManagerNative.getDefault(); 11101 if (am == null) return; 11102 final int[] resolvedUserIds; 11103 if (userIds == null) { 11104 resolvedUserIds = am.getRunningUserIds(); 11105 } else { 11106 resolvedUserIds = userIds; 11107 } 11108 for (int id : resolvedUserIds) { 11109 final Intent intent = new Intent(action, 11110 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11111 if (extras != null) { 11112 intent.putExtras(extras); 11113 } 11114 if (targetPkg != null) { 11115 intent.setPackage(targetPkg); 11116 } 11117 // Modify the UID when posting to other users 11118 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11119 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11120 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11121 intent.putExtra(Intent.EXTRA_UID, uid); 11122 } 11123 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11124 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11125 if (DEBUG_BROADCASTS) { 11126 RuntimeException here = new RuntimeException("here"); 11127 here.fillInStackTrace(); 11128 Slog.d(TAG, "Sending to user " + id + ": " 11129 + intent.toShortString(false, true, false, false) 11130 + " " + intent.getExtras(), here); 11131 } 11132 am.broadcastIntent(null, intent, null, finishedReceiver, 11133 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11134 null, finishedReceiver != null, false, id); 11135 } 11136 } catch (RemoteException ex) { 11137 } 11138 } 11139 }); 11140 } 11141 11142 /** 11143 * Check if the external storage media is available. This is true if there 11144 * is a mounted external storage medium or if the external storage is 11145 * emulated. 11146 */ 11147 private boolean isExternalMediaAvailable() { 11148 return mMediaMounted || Environment.isExternalStorageEmulated(); 11149 } 11150 11151 @Override 11152 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11153 // writer 11154 synchronized (mPackages) { 11155 if (!isExternalMediaAvailable()) { 11156 // If the external storage is no longer mounted at this point, 11157 // the caller may not have been able to delete all of this 11158 // packages files and can not delete any more. Bail. 11159 return null; 11160 } 11161 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11162 if (lastPackage != null) { 11163 pkgs.remove(lastPackage); 11164 } 11165 if (pkgs.size() > 0) { 11166 return pkgs.get(0); 11167 } 11168 } 11169 return null; 11170 } 11171 11172 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11173 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11174 userId, andCode ? 1 : 0, packageName); 11175 if (mSystemReady) { 11176 msg.sendToTarget(); 11177 } else { 11178 if (mPostSystemReadyMessages == null) { 11179 mPostSystemReadyMessages = new ArrayList<>(); 11180 } 11181 mPostSystemReadyMessages.add(msg); 11182 } 11183 } 11184 11185 void startCleaningPackages() { 11186 // reader 11187 if (!isExternalMediaAvailable()) { 11188 return; 11189 } 11190 synchronized (mPackages) { 11191 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11192 return; 11193 } 11194 } 11195 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11196 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11197 IActivityManager am = ActivityManagerNative.getDefault(); 11198 if (am != null) { 11199 try { 11200 am.startService(null, intent, null, mContext.getOpPackageName(), 11201 UserHandle.USER_SYSTEM); 11202 } catch (RemoteException e) { 11203 } 11204 } 11205 } 11206 11207 @Override 11208 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11209 int installFlags, String installerPackageName, int userId) { 11210 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11211 11212 final int callingUid = Binder.getCallingUid(); 11213 enforceCrossUserPermission(callingUid, userId, 11214 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11215 11216 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11217 try { 11218 if (observer != null) { 11219 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11220 } 11221 } catch (RemoteException re) { 11222 } 11223 return; 11224 } 11225 11226 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11227 installFlags |= PackageManager.INSTALL_FROM_ADB; 11228 11229 } else { 11230 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11231 // about installerPackageName. 11232 11233 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11234 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11235 } 11236 11237 UserHandle user; 11238 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11239 user = UserHandle.ALL; 11240 } else { 11241 user = new UserHandle(userId); 11242 } 11243 11244 // Only system components can circumvent runtime permissions when installing. 11245 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11246 && mContext.checkCallingOrSelfPermission(Manifest.permission 11247 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11248 throw new SecurityException("You need the " 11249 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11250 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11251 } 11252 11253 final File originFile = new File(originPath); 11254 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11255 11256 final Message msg = mHandler.obtainMessage(INIT_COPY); 11257 final VerificationInfo verificationInfo = new VerificationInfo( 11258 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11259 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11260 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11261 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11262 null /*certificates*/); 11263 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11264 msg.obj = params; 11265 11266 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11267 System.identityHashCode(msg.obj)); 11268 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11269 System.identityHashCode(msg.obj)); 11270 11271 mHandler.sendMessage(msg); 11272 } 11273 11274 void installStage(String packageName, File stagedDir, String stagedCid, 11275 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11276 String installerPackageName, int installerUid, UserHandle user, 11277 Certificate[][] certificates) { 11278 if (DEBUG_EPHEMERAL) { 11279 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11280 Slog.d(TAG, "Ephemeral install of " + packageName); 11281 } 11282 } 11283 final VerificationInfo verificationInfo = new VerificationInfo( 11284 sessionParams.originatingUri, sessionParams.referrerUri, 11285 sessionParams.originatingUid, installerUid); 11286 11287 final OriginInfo origin; 11288 if (stagedDir != null) { 11289 origin = OriginInfo.fromStagedFile(stagedDir); 11290 } else { 11291 origin = OriginInfo.fromStagedContainer(stagedCid); 11292 } 11293 11294 final Message msg = mHandler.obtainMessage(INIT_COPY); 11295 final InstallParams params = new InstallParams(origin, null, observer, 11296 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11297 verificationInfo, user, sessionParams.abiOverride, 11298 sessionParams.grantedRuntimePermissions, certificates); 11299 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11300 msg.obj = params; 11301 11302 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11303 System.identityHashCode(msg.obj)); 11304 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11305 System.identityHashCode(msg.obj)); 11306 11307 mHandler.sendMessage(msg); 11308 } 11309 11310 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11311 int userId) { 11312 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11313 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11314 } 11315 11316 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11317 int appId, int userId) { 11318 Bundle extras = new Bundle(1); 11319 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11320 11321 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11322 packageName, extras, 0, null, null, new int[] {userId}); 11323 try { 11324 IActivityManager am = ActivityManagerNative.getDefault(); 11325 if (isSystem && am.isUserRunning(userId, 0)) { 11326 // The just-installed/enabled app is bundled on the system, so presumed 11327 // to be able to run automatically without needing an explicit launch. 11328 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11329 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11330 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11331 .setPackage(packageName); 11332 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11333 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11334 } 11335 } catch (RemoteException e) { 11336 // shouldn't happen 11337 Slog.w(TAG, "Unable to bootstrap installed package", e); 11338 } 11339 } 11340 11341 @Override 11342 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11343 int userId) { 11344 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11345 PackageSetting pkgSetting; 11346 final int uid = Binder.getCallingUid(); 11347 enforceCrossUserPermission(uid, userId, 11348 true /* requireFullPermission */, true /* checkShell */, 11349 "setApplicationHiddenSetting for user " + userId); 11350 11351 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11352 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11353 return false; 11354 } 11355 11356 long callingId = Binder.clearCallingIdentity(); 11357 try { 11358 boolean sendAdded = false; 11359 boolean sendRemoved = false; 11360 // writer 11361 synchronized (mPackages) { 11362 pkgSetting = mSettings.mPackages.get(packageName); 11363 if (pkgSetting == null) { 11364 return false; 11365 } 11366 if (pkgSetting.getHidden(userId) != hidden) { 11367 pkgSetting.setHidden(hidden, userId); 11368 mSettings.writePackageRestrictionsLPr(userId); 11369 if (hidden) { 11370 sendRemoved = true; 11371 } else { 11372 sendAdded = true; 11373 } 11374 } 11375 } 11376 if (sendAdded) { 11377 sendPackageAddedForUser(packageName, pkgSetting, userId); 11378 return true; 11379 } 11380 if (sendRemoved) { 11381 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11382 "hiding pkg"); 11383 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11384 return true; 11385 } 11386 } finally { 11387 Binder.restoreCallingIdentity(callingId); 11388 } 11389 return false; 11390 } 11391 11392 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11393 int userId) { 11394 final PackageRemovedInfo info = new PackageRemovedInfo(); 11395 info.removedPackage = packageName; 11396 info.removedUsers = new int[] {userId}; 11397 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11398 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11399 } 11400 11401 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11402 if (pkgList.length > 0) { 11403 Bundle extras = new Bundle(1); 11404 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11405 11406 sendPackageBroadcast( 11407 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11408 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11409 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11410 new int[] {userId}); 11411 } 11412 } 11413 11414 /** 11415 * Returns true if application is not found or there was an error. Otherwise it returns 11416 * the hidden state of the package for the given user. 11417 */ 11418 @Override 11419 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11420 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11421 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11422 true /* requireFullPermission */, false /* checkShell */, 11423 "getApplicationHidden for user " + userId); 11424 PackageSetting pkgSetting; 11425 long callingId = Binder.clearCallingIdentity(); 11426 try { 11427 // writer 11428 synchronized (mPackages) { 11429 pkgSetting = mSettings.mPackages.get(packageName); 11430 if (pkgSetting == null) { 11431 return true; 11432 } 11433 return pkgSetting.getHidden(userId); 11434 } 11435 } finally { 11436 Binder.restoreCallingIdentity(callingId); 11437 } 11438 } 11439 11440 /** 11441 * @hide 11442 */ 11443 @Override 11444 public int installExistingPackageAsUser(String packageName, int userId) { 11445 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11446 null); 11447 PackageSetting pkgSetting; 11448 final int uid = Binder.getCallingUid(); 11449 enforceCrossUserPermission(uid, userId, 11450 true /* requireFullPermission */, true /* checkShell */, 11451 "installExistingPackage for user " + userId); 11452 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11453 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11454 } 11455 11456 long callingId = Binder.clearCallingIdentity(); 11457 try { 11458 boolean installed = false; 11459 11460 // writer 11461 synchronized (mPackages) { 11462 pkgSetting = mSettings.mPackages.get(packageName); 11463 if (pkgSetting == null) { 11464 return PackageManager.INSTALL_FAILED_INVALID_URI; 11465 } 11466 if (!pkgSetting.getInstalled(userId)) { 11467 pkgSetting.setInstalled(true, userId); 11468 pkgSetting.setHidden(false, userId); 11469 mSettings.writePackageRestrictionsLPr(userId); 11470 installed = true; 11471 } 11472 } 11473 11474 if (installed) { 11475 if (pkgSetting.pkg != null) { 11476 synchronized (mInstallLock) { 11477 // We don't need to freeze for a brand new install 11478 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11479 } 11480 } 11481 sendPackageAddedForUser(packageName, pkgSetting, userId); 11482 } 11483 } finally { 11484 Binder.restoreCallingIdentity(callingId); 11485 } 11486 11487 return PackageManager.INSTALL_SUCCEEDED; 11488 } 11489 11490 boolean isUserRestricted(int userId, String restrictionKey) { 11491 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11492 if (restrictions.getBoolean(restrictionKey, false)) { 11493 Log.w(TAG, "User is restricted: " + restrictionKey); 11494 return true; 11495 } 11496 return false; 11497 } 11498 11499 @Override 11500 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11501 int userId) { 11502 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11503 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11504 true /* requireFullPermission */, true /* checkShell */, 11505 "setPackagesSuspended for user " + userId); 11506 11507 if (ArrayUtils.isEmpty(packageNames)) { 11508 return packageNames; 11509 } 11510 11511 // List of package names for whom the suspended state has changed. 11512 List<String> changedPackages = new ArrayList<>(packageNames.length); 11513 // List of package names for whom the suspended state is not set as requested in this 11514 // method. 11515 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11516 long callingId = Binder.clearCallingIdentity(); 11517 try { 11518 for (int i = 0; i < packageNames.length; i++) { 11519 String packageName = packageNames[i]; 11520 boolean changed = false; 11521 final int appId; 11522 synchronized (mPackages) { 11523 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11524 if (pkgSetting == null) { 11525 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11526 + "\". Skipping suspending/un-suspending."); 11527 unactionedPackages.add(packageName); 11528 continue; 11529 } 11530 appId = pkgSetting.appId; 11531 if (pkgSetting.getSuspended(userId) != suspended) { 11532 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11533 unactionedPackages.add(packageName); 11534 continue; 11535 } 11536 pkgSetting.setSuspended(suspended, userId); 11537 mSettings.writePackageRestrictionsLPr(userId); 11538 changed = true; 11539 changedPackages.add(packageName); 11540 } 11541 } 11542 11543 if (changed && suspended) { 11544 killApplication(packageName, UserHandle.getUid(userId, appId), 11545 "suspending package"); 11546 } 11547 } 11548 } finally { 11549 Binder.restoreCallingIdentity(callingId); 11550 } 11551 11552 if (!changedPackages.isEmpty()) { 11553 sendPackagesSuspendedForUser(changedPackages.toArray( 11554 new String[changedPackages.size()]), userId, suspended); 11555 } 11556 11557 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11558 } 11559 11560 @Override 11561 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11562 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11563 true /* requireFullPermission */, false /* checkShell */, 11564 "isPackageSuspendedForUser for user " + userId); 11565 synchronized (mPackages) { 11566 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11567 if (pkgSetting == null) { 11568 throw new IllegalArgumentException("Unknown target package: " + packageName); 11569 } 11570 return pkgSetting.getSuspended(userId); 11571 } 11572 } 11573 11574 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11575 if (isPackageDeviceAdmin(packageName, userId)) { 11576 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11577 + "\": has an active device admin"); 11578 return false; 11579 } 11580 11581 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11582 if (packageName.equals(activeLauncherPackageName)) { 11583 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11584 + "\": contains the active launcher"); 11585 return false; 11586 } 11587 11588 if (packageName.equals(mRequiredInstallerPackage)) { 11589 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11590 + "\": required for package installation"); 11591 return false; 11592 } 11593 11594 if (packageName.equals(mRequiredVerifierPackage)) { 11595 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11596 + "\": required for package verification"); 11597 return false; 11598 } 11599 11600 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11601 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11602 + "\": is the default dialer"); 11603 return false; 11604 } 11605 11606 return true; 11607 } 11608 11609 private String getActiveLauncherPackageName(int userId) { 11610 Intent intent = new Intent(Intent.ACTION_MAIN); 11611 intent.addCategory(Intent.CATEGORY_HOME); 11612 ResolveInfo resolveInfo = resolveIntent( 11613 intent, 11614 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11615 PackageManager.MATCH_DEFAULT_ONLY, 11616 userId); 11617 11618 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11619 } 11620 11621 private String getDefaultDialerPackageName(int userId) { 11622 synchronized (mPackages) { 11623 return mSettings.getDefaultDialerPackageNameLPw(userId); 11624 } 11625 } 11626 11627 @Override 11628 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11629 mContext.enforceCallingOrSelfPermission( 11630 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11631 "Only package verification agents can verify applications"); 11632 11633 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11634 final PackageVerificationResponse response = new PackageVerificationResponse( 11635 verificationCode, Binder.getCallingUid()); 11636 msg.arg1 = id; 11637 msg.obj = response; 11638 mHandler.sendMessage(msg); 11639 } 11640 11641 @Override 11642 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11643 long millisecondsToDelay) { 11644 mContext.enforceCallingOrSelfPermission( 11645 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11646 "Only package verification agents can extend verification timeouts"); 11647 11648 final PackageVerificationState state = mPendingVerification.get(id); 11649 final PackageVerificationResponse response = new PackageVerificationResponse( 11650 verificationCodeAtTimeout, Binder.getCallingUid()); 11651 11652 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11653 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11654 } 11655 if (millisecondsToDelay < 0) { 11656 millisecondsToDelay = 0; 11657 } 11658 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11659 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11660 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11661 } 11662 11663 if ((state != null) && !state.timeoutExtended()) { 11664 state.extendTimeout(); 11665 11666 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11667 msg.arg1 = id; 11668 msg.obj = response; 11669 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11670 } 11671 } 11672 11673 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11674 int verificationCode, UserHandle user) { 11675 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11676 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11677 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11678 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11679 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11680 11681 mContext.sendBroadcastAsUser(intent, user, 11682 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11683 } 11684 11685 private ComponentName matchComponentForVerifier(String packageName, 11686 List<ResolveInfo> receivers) { 11687 ActivityInfo targetReceiver = null; 11688 11689 final int NR = receivers.size(); 11690 for (int i = 0; i < NR; i++) { 11691 final ResolveInfo info = receivers.get(i); 11692 if (info.activityInfo == null) { 11693 continue; 11694 } 11695 11696 if (packageName.equals(info.activityInfo.packageName)) { 11697 targetReceiver = info.activityInfo; 11698 break; 11699 } 11700 } 11701 11702 if (targetReceiver == null) { 11703 return null; 11704 } 11705 11706 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11707 } 11708 11709 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11710 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11711 if (pkgInfo.verifiers.length == 0) { 11712 return null; 11713 } 11714 11715 final int N = pkgInfo.verifiers.length; 11716 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11717 for (int i = 0; i < N; i++) { 11718 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11719 11720 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11721 receivers); 11722 if (comp == null) { 11723 continue; 11724 } 11725 11726 final int verifierUid = getUidForVerifier(verifierInfo); 11727 if (verifierUid == -1) { 11728 continue; 11729 } 11730 11731 if (DEBUG_VERIFY) { 11732 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11733 + " with the correct signature"); 11734 } 11735 sufficientVerifiers.add(comp); 11736 verificationState.addSufficientVerifier(verifierUid); 11737 } 11738 11739 return sufficientVerifiers; 11740 } 11741 11742 private int getUidForVerifier(VerifierInfo verifierInfo) { 11743 synchronized (mPackages) { 11744 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11745 if (pkg == null) { 11746 return -1; 11747 } else if (pkg.mSignatures.length != 1) { 11748 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11749 + " has more than one signature; ignoring"); 11750 return -1; 11751 } 11752 11753 /* 11754 * If the public key of the package's signature does not match 11755 * our expected public key, then this is a different package and 11756 * we should skip. 11757 */ 11758 11759 final byte[] expectedPublicKey; 11760 try { 11761 final Signature verifierSig = pkg.mSignatures[0]; 11762 final PublicKey publicKey = verifierSig.getPublicKey(); 11763 expectedPublicKey = publicKey.getEncoded(); 11764 } catch (CertificateException e) { 11765 return -1; 11766 } 11767 11768 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11769 11770 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11771 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11772 + " does not have the expected public key; ignoring"); 11773 return -1; 11774 } 11775 11776 return pkg.applicationInfo.uid; 11777 } 11778 } 11779 11780 @Override 11781 public void finishPackageInstall(int token, boolean didLaunch) { 11782 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11783 11784 if (DEBUG_INSTALL) { 11785 Slog.v(TAG, "BM finishing package install for " + token); 11786 } 11787 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11788 11789 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11790 mHandler.sendMessage(msg); 11791 } 11792 11793 /** 11794 * Get the verification agent timeout. 11795 * 11796 * @return verification timeout in milliseconds 11797 */ 11798 private long getVerificationTimeout() { 11799 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11800 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11801 DEFAULT_VERIFICATION_TIMEOUT); 11802 } 11803 11804 /** 11805 * Get the default verification agent response code. 11806 * 11807 * @return default verification response code 11808 */ 11809 private int getDefaultVerificationResponse() { 11810 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11811 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11812 DEFAULT_VERIFICATION_RESPONSE); 11813 } 11814 11815 /** 11816 * Check whether or not package verification has been enabled. 11817 * 11818 * @return true if verification should be performed 11819 */ 11820 private boolean isVerificationEnabled(int userId, int installFlags) { 11821 if (!DEFAULT_VERIFY_ENABLE) { 11822 return false; 11823 } 11824 // Ephemeral apps don't get the full verification treatment 11825 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11826 if (DEBUG_EPHEMERAL) { 11827 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11828 } 11829 return false; 11830 } 11831 11832 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11833 11834 // Check if installing from ADB 11835 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11836 // Do not run verification in a test harness environment 11837 if (ActivityManager.isRunningInTestHarness()) { 11838 return false; 11839 } 11840 if (ensureVerifyAppsEnabled) { 11841 return true; 11842 } 11843 // Check if the developer does not want package verification for ADB installs 11844 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11845 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11846 return false; 11847 } 11848 } 11849 11850 if (ensureVerifyAppsEnabled) { 11851 return true; 11852 } 11853 11854 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11855 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11856 } 11857 11858 @Override 11859 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11860 throws RemoteException { 11861 mContext.enforceCallingOrSelfPermission( 11862 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11863 "Only intentfilter verification agents can verify applications"); 11864 11865 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11866 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11867 Binder.getCallingUid(), verificationCode, failedDomains); 11868 msg.arg1 = id; 11869 msg.obj = response; 11870 mHandler.sendMessage(msg); 11871 } 11872 11873 @Override 11874 public int getIntentVerificationStatus(String packageName, int userId) { 11875 synchronized (mPackages) { 11876 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11877 } 11878 } 11879 11880 @Override 11881 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11882 mContext.enforceCallingOrSelfPermission( 11883 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11884 11885 boolean result = false; 11886 synchronized (mPackages) { 11887 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11888 } 11889 if (result) { 11890 scheduleWritePackageRestrictionsLocked(userId); 11891 } 11892 return result; 11893 } 11894 11895 @Override 11896 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11897 String packageName) { 11898 synchronized (mPackages) { 11899 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11900 } 11901 } 11902 11903 @Override 11904 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11905 if (TextUtils.isEmpty(packageName)) { 11906 return ParceledListSlice.emptyList(); 11907 } 11908 synchronized (mPackages) { 11909 PackageParser.Package pkg = mPackages.get(packageName); 11910 if (pkg == null || pkg.activities == null) { 11911 return ParceledListSlice.emptyList(); 11912 } 11913 final int count = pkg.activities.size(); 11914 ArrayList<IntentFilter> result = new ArrayList<>(); 11915 for (int n=0; n<count; n++) { 11916 PackageParser.Activity activity = pkg.activities.get(n); 11917 if (activity.intents != null && activity.intents.size() > 0) { 11918 result.addAll(activity.intents); 11919 } 11920 } 11921 return new ParceledListSlice<>(result); 11922 } 11923 } 11924 11925 @Override 11926 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11927 mContext.enforceCallingOrSelfPermission( 11928 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11929 11930 synchronized (mPackages) { 11931 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11932 if (packageName != null) { 11933 result |= updateIntentVerificationStatus(packageName, 11934 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11935 userId); 11936 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11937 packageName, userId); 11938 } 11939 return result; 11940 } 11941 } 11942 11943 @Override 11944 public String getDefaultBrowserPackageName(int userId) { 11945 synchronized (mPackages) { 11946 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11947 } 11948 } 11949 11950 /** 11951 * Get the "allow unknown sources" setting. 11952 * 11953 * @return the current "allow unknown sources" setting 11954 */ 11955 private int getUnknownSourcesSettings() { 11956 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11957 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11958 -1); 11959 } 11960 11961 @Override 11962 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11963 final int uid = Binder.getCallingUid(); 11964 // writer 11965 synchronized (mPackages) { 11966 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11967 if (targetPackageSetting == null) { 11968 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11969 } 11970 11971 PackageSetting installerPackageSetting; 11972 if (installerPackageName != null) { 11973 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11974 if (installerPackageSetting == null) { 11975 throw new IllegalArgumentException("Unknown installer package: " 11976 + installerPackageName); 11977 } 11978 } else { 11979 installerPackageSetting = null; 11980 } 11981 11982 Signature[] callerSignature; 11983 Object obj = mSettings.getUserIdLPr(uid); 11984 if (obj != null) { 11985 if (obj instanceof SharedUserSetting) { 11986 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11987 } else if (obj instanceof PackageSetting) { 11988 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11989 } else { 11990 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11991 } 11992 } else { 11993 throw new SecurityException("Unknown calling UID: " + uid); 11994 } 11995 11996 // Verify: can't set installerPackageName to a package that is 11997 // not signed with the same cert as the caller. 11998 if (installerPackageSetting != null) { 11999 if (compareSignatures(callerSignature, 12000 installerPackageSetting.signatures.mSignatures) 12001 != PackageManager.SIGNATURE_MATCH) { 12002 throw new SecurityException( 12003 "Caller does not have same cert as new installer package " 12004 + installerPackageName); 12005 } 12006 } 12007 12008 // Verify: if target already has an installer package, it must 12009 // be signed with the same cert as the caller. 12010 if (targetPackageSetting.installerPackageName != null) { 12011 PackageSetting setting = mSettings.mPackages.get( 12012 targetPackageSetting.installerPackageName); 12013 // If the currently set package isn't valid, then it's always 12014 // okay to change it. 12015 if (setting != null) { 12016 if (compareSignatures(callerSignature, 12017 setting.signatures.mSignatures) 12018 != PackageManager.SIGNATURE_MATCH) { 12019 throw new SecurityException( 12020 "Caller does not have same cert as old installer package " 12021 + targetPackageSetting.installerPackageName); 12022 } 12023 } 12024 } 12025 12026 // Okay! 12027 targetPackageSetting.installerPackageName = installerPackageName; 12028 if (installerPackageName != null) { 12029 mSettings.mInstallerPackages.add(installerPackageName); 12030 } 12031 scheduleWriteSettingsLocked(); 12032 } 12033 } 12034 12035 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12036 // Queue up an async operation since the package installation may take a little while. 12037 mHandler.post(new Runnable() { 12038 public void run() { 12039 mHandler.removeCallbacks(this); 12040 // Result object to be returned 12041 PackageInstalledInfo res = new PackageInstalledInfo(); 12042 res.setReturnCode(currentStatus); 12043 res.uid = -1; 12044 res.pkg = null; 12045 res.removedInfo = null; 12046 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12047 args.doPreInstall(res.returnCode); 12048 synchronized (mInstallLock) { 12049 installPackageTracedLI(args, res); 12050 } 12051 args.doPostInstall(res.returnCode, res.uid); 12052 } 12053 12054 // A restore should be performed at this point if (a) the install 12055 // succeeded, (b) the operation is not an update, and (c) the new 12056 // package has not opted out of backup participation. 12057 final boolean update = res.removedInfo != null 12058 && res.removedInfo.removedPackage != null; 12059 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12060 boolean doRestore = !update 12061 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12062 12063 // Set up the post-install work request bookkeeping. This will be used 12064 // and cleaned up by the post-install event handling regardless of whether 12065 // there's a restore pass performed. Token values are >= 1. 12066 int token; 12067 if (mNextInstallToken < 0) mNextInstallToken = 1; 12068 token = mNextInstallToken++; 12069 12070 PostInstallData data = new PostInstallData(args, res); 12071 mRunningInstalls.put(token, data); 12072 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12073 12074 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12075 // Pass responsibility to the Backup Manager. It will perform a 12076 // restore if appropriate, then pass responsibility back to the 12077 // Package Manager to run the post-install observer callbacks 12078 // and broadcasts. 12079 IBackupManager bm = IBackupManager.Stub.asInterface( 12080 ServiceManager.getService(Context.BACKUP_SERVICE)); 12081 if (bm != null) { 12082 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12083 + " to BM for possible restore"); 12084 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12085 try { 12086 // TODO: http://b/22388012 12087 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12088 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12089 } else { 12090 doRestore = false; 12091 } 12092 } catch (RemoteException e) { 12093 // can't happen; the backup manager is local 12094 } catch (Exception e) { 12095 Slog.e(TAG, "Exception trying to enqueue restore", e); 12096 doRestore = false; 12097 } 12098 } else { 12099 Slog.e(TAG, "Backup Manager not found!"); 12100 doRestore = false; 12101 } 12102 } 12103 12104 if (!doRestore) { 12105 // No restore possible, or the Backup Manager was mysteriously not 12106 // available -- just fire the post-install work request directly. 12107 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12108 12109 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12110 12111 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12112 mHandler.sendMessage(msg); 12113 } 12114 } 12115 }); 12116 } 12117 12118 /** 12119 * Callback from PackageSettings whenever an app is first transitioned out of the 12120 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12121 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12122 * here whether the app is the target of an ongoing install, and only send the 12123 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12124 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12125 * handling. 12126 */ 12127 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12128 // Serialize this with the rest of the install-process message chain. In the 12129 // restore-at-install case, this Runnable will necessarily run before the 12130 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12131 // are coherent. In the non-restore case, the app has already completed install 12132 // and been launched through some other means, so it is not in a problematic 12133 // state for observers to see the FIRST_LAUNCH signal. 12134 mHandler.post(new Runnable() { 12135 @Override 12136 public void run() { 12137 for (int i = 0; i < mRunningInstalls.size(); i++) { 12138 final PostInstallData data = mRunningInstalls.valueAt(i); 12139 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12140 // right package; but is it for the right user? 12141 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12142 if (userId == data.res.newUsers[uIndex]) { 12143 if (DEBUG_BACKUP) { 12144 Slog.i(TAG, "Package " + pkgName 12145 + " being restored so deferring FIRST_LAUNCH"); 12146 } 12147 return; 12148 } 12149 } 12150 } 12151 } 12152 // didn't find it, so not being restored 12153 if (DEBUG_BACKUP) { 12154 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12155 } 12156 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12157 } 12158 }); 12159 } 12160 12161 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12162 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12163 installerPkg, null, userIds); 12164 } 12165 12166 private abstract class HandlerParams { 12167 private static final int MAX_RETRIES = 4; 12168 12169 /** 12170 * Number of times startCopy() has been attempted and had a non-fatal 12171 * error. 12172 */ 12173 private int mRetries = 0; 12174 12175 /** User handle for the user requesting the information or installation. */ 12176 private final UserHandle mUser; 12177 String traceMethod; 12178 int traceCookie; 12179 12180 HandlerParams(UserHandle user) { 12181 mUser = user; 12182 } 12183 12184 UserHandle getUser() { 12185 return mUser; 12186 } 12187 12188 HandlerParams setTraceMethod(String traceMethod) { 12189 this.traceMethod = traceMethod; 12190 return this; 12191 } 12192 12193 HandlerParams setTraceCookie(int traceCookie) { 12194 this.traceCookie = traceCookie; 12195 return this; 12196 } 12197 12198 final boolean startCopy() { 12199 boolean res; 12200 try { 12201 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12202 12203 if (++mRetries > MAX_RETRIES) { 12204 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12205 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12206 handleServiceError(); 12207 return false; 12208 } else { 12209 handleStartCopy(); 12210 res = true; 12211 } 12212 } catch (RemoteException e) { 12213 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12214 mHandler.sendEmptyMessage(MCS_RECONNECT); 12215 res = false; 12216 } 12217 handleReturnCode(); 12218 return res; 12219 } 12220 12221 final void serviceError() { 12222 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12223 handleServiceError(); 12224 handleReturnCode(); 12225 } 12226 12227 abstract void handleStartCopy() throws RemoteException; 12228 abstract void handleServiceError(); 12229 abstract void handleReturnCode(); 12230 } 12231 12232 class MeasureParams extends HandlerParams { 12233 private final PackageStats mStats; 12234 private boolean mSuccess; 12235 12236 private final IPackageStatsObserver mObserver; 12237 12238 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12239 super(new UserHandle(stats.userHandle)); 12240 mObserver = observer; 12241 mStats = stats; 12242 } 12243 12244 @Override 12245 public String toString() { 12246 return "MeasureParams{" 12247 + Integer.toHexString(System.identityHashCode(this)) 12248 + " " + mStats.packageName + "}"; 12249 } 12250 12251 @Override 12252 void handleStartCopy() throws RemoteException { 12253 synchronized (mInstallLock) { 12254 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12255 } 12256 12257 if (mSuccess) { 12258 final boolean mounted; 12259 if (Environment.isExternalStorageEmulated()) { 12260 mounted = true; 12261 } else { 12262 final String status = Environment.getExternalStorageState(); 12263 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12264 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12265 } 12266 12267 if (mounted) { 12268 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12269 12270 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12271 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12272 12273 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12274 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12275 12276 // Always subtract cache size, since it's a subdirectory 12277 mStats.externalDataSize -= mStats.externalCacheSize; 12278 12279 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12280 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12281 12282 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12283 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12284 } 12285 } 12286 } 12287 12288 @Override 12289 void handleReturnCode() { 12290 if (mObserver != null) { 12291 try { 12292 mObserver.onGetStatsCompleted(mStats, mSuccess); 12293 } catch (RemoteException e) { 12294 Slog.i(TAG, "Observer no longer exists."); 12295 } 12296 } 12297 } 12298 12299 @Override 12300 void handleServiceError() { 12301 Slog.e(TAG, "Could not measure application " + mStats.packageName 12302 + " external storage"); 12303 } 12304 } 12305 12306 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12307 throws RemoteException { 12308 long result = 0; 12309 for (File path : paths) { 12310 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12311 } 12312 return result; 12313 } 12314 12315 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12316 for (File path : paths) { 12317 try { 12318 mcs.clearDirectory(path.getAbsolutePath()); 12319 } catch (RemoteException e) { 12320 } 12321 } 12322 } 12323 12324 static class OriginInfo { 12325 /** 12326 * Location where install is coming from, before it has been 12327 * copied/renamed into place. This could be a single monolithic APK 12328 * file, or a cluster directory. This location may be untrusted. 12329 */ 12330 final File file; 12331 final String cid; 12332 12333 /** 12334 * Flag indicating that {@link #file} or {@link #cid} has already been 12335 * staged, meaning downstream users don't need to defensively copy the 12336 * contents. 12337 */ 12338 final boolean staged; 12339 12340 /** 12341 * Flag indicating that {@link #file} or {@link #cid} is an already 12342 * installed app that is being moved. 12343 */ 12344 final boolean existing; 12345 12346 final String resolvedPath; 12347 final File resolvedFile; 12348 12349 static OriginInfo fromNothing() { 12350 return new OriginInfo(null, null, false, false); 12351 } 12352 12353 static OriginInfo fromUntrustedFile(File file) { 12354 return new OriginInfo(file, null, false, false); 12355 } 12356 12357 static OriginInfo fromExistingFile(File file) { 12358 return new OriginInfo(file, null, false, true); 12359 } 12360 12361 static OriginInfo fromStagedFile(File file) { 12362 return new OriginInfo(file, null, true, false); 12363 } 12364 12365 static OriginInfo fromStagedContainer(String cid) { 12366 return new OriginInfo(null, cid, true, false); 12367 } 12368 12369 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12370 this.file = file; 12371 this.cid = cid; 12372 this.staged = staged; 12373 this.existing = existing; 12374 12375 if (cid != null) { 12376 resolvedPath = PackageHelper.getSdDir(cid); 12377 resolvedFile = new File(resolvedPath); 12378 } else if (file != null) { 12379 resolvedPath = file.getAbsolutePath(); 12380 resolvedFile = file; 12381 } else { 12382 resolvedPath = null; 12383 resolvedFile = null; 12384 } 12385 } 12386 } 12387 12388 static class MoveInfo { 12389 final int moveId; 12390 final String fromUuid; 12391 final String toUuid; 12392 final String packageName; 12393 final String dataAppName; 12394 final int appId; 12395 final String seinfo; 12396 final int targetSdkVersion; 12397 12398 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12399 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12400 this.moveId = moveId; 12401 this.fromUuid = fromUuid; 12402 this.toUuid = toUuid; 12403 this.packageName = packageName; 12404 this.dataAppName = dataAppName; 12405 this.appId = appId; 12406 this.seinfo = seinfo; 12407 this.targetSdkVersion = targetSdkVersion; 12408 } 12409 } 12410 12411 static class VerificationInfo { 12412 /** A constant used to indicate that a uid value is not present. */ 12413 public static final int NO_UID = -1; 12414 12415 /** URI referencing where the package was downloaded from. */ 12416 final Uri originatingUri; 12417 12418 /** HTTP referrer URI associated with the originatingURI. */ 12419 final Uri referrer; 12420 12421 /** UID of the application that the install request originated from. */ 12422 final int originatingUid; 12423 12424 /** UID of application requesting the install */ 12425 final int installerUid; 12426 12427 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12428 this.originatingUri = originatingUri; 12429 this.referrer = referrer; 12430 this.originatingUid = originatingUid; 12431 this.installerUid = installerUid; 12432 } 12433 } 12434 12435 class InstallParams extends HandlerParams { 12436 final OriginInfo origin; 12437 final MoveInfo move; 12438 final IPackageInstallObserver2 observer; 12439 int installFlags; 12440 final String installerPackageName; 12441 final String volumeUuid; 12442 private InstallArgs mArgs; 12443 private int mRet; 12444 final String packageAbiOverride; 12445 final String[] grantedRuntimePermissions; 12446 final VerificationInfo verificationInfo; 12447 final Certificate[][] certificates; 12448 12449 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12450 int installFlags, String installerPackageName, String volumeUuid, 12451 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12452 String[] grantedPermissions, Certificate[][] certificates) { 12453 super(user); 12454 this.origin = origin; 12455 this.move = move; 12456 this.observer = observer; 12457 this.installFlags = installFlags; 12458 this.installerPackageName = installerPackageName; 12459 this.volumeUuid = volumeUuid; 12460 this.verificationInfo = verificationInfo; 12461 this.packageAbiOverride = packageAbiOverride; 12462 this.grantedRuntimePermissions = grantedPermissions; 12463 this.certificates = certificates; 12464 } 12465 12466 @Override 12467 public String toString() { 12468 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12469 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12470 } 12471 12472 private int installLocationPolicy(PackageInfoLite pkgLite) { 12473 String packageName = pkgLite.packageName; 12474 int installLocation = pkgLite.installLocation; 12475 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12476 // reader 12477 synchronized (mPackages) { 12478 // Currently installed package which the new package is attempting to replace or 12479 // null if no such package is installed. 12480 PackageParser.Package installedPkg = mPackages.get(packageName); 12481 // Package which currently owns the data which the new package will own if installed. 12482 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12483 // will be null whereas dataOwnerPkg will contain information about the package 12484 // which was uninstalled while keeping its data. 12485 PackageParser.Package dataOwnerPkg = installedPkg; 12486 if (dataOwnerPkg == null) { 12487 PackageSetting ps = mSettings.mPackages.get(packageName); 12488 if (ps != null) { 12489 dataOwnerPkg = ps.pkg; 12490 } 12491 } 12492 12493 if (dataOwnerPkg != null) { 12494 // If installed, the package will get access to data left on the device by its 12495 // predecessor. As a security measure, this is permited only if this is not a 12496 // version downgrade or if the predecessor package is marked as debuggable and 12497 // a downgrade is explicitly requested. 12498 // 12499 // On debuggable platform builds, downgrades are permitted even for 12500 // non-debuggable packages to make testing easier. Debuggable platform builds do 12501 // not offer security guarantees and thus it's OK to disable some security 12502 // mechanisms to make debugging/testing easier on those builds. However, even on 12503 // debuggable builds downgrades of packages are permitted only if requested via 12504 // installFlags. This is because we aim to keep the behavior of debuggable 12505 // platform builds as close as possible to the behavior of non-debuggable 12506 // platform builds. 12507 final boolean downgradeRequested = 12508 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12509 final boolean packageDebuggable = 12510 (dataOwnerPkg.applicationInfo.flags 12511 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12512 final boolean downgradePermitted = 12513 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12514 if (!downgradePermitted) { 12515 try { 12516 checkDowngrade(dataOwnerPkg, pkgLite); 12517 } catch (PackageManagerException e) { 12518 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12519 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12520 } 12521 } 12522 } 12523 12524 if (installedPkg != null) { 12525 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12526 // Check for updated system application. 12527 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12528 if (onSd) { 12529 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12530 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12531 } 12532 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12533 } else { 12534 if (onSd) { 12535 // Install flag overrides everything. 12536 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12537 } 12538 // If current upgrade specifies particular preference 12539 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12540 // Application explicitly specified internal. 12541 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12542 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12543 // App explictly prefers external. Let policy decide 12544 } else { 12545 // Prefer previous location 12546 if (isExternal(installedPkg)) { 12547 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12548 } 12549 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12550 } 12551 } 12552 } else { 12553 // Invalid install. Return error code 12554 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12555 } 12556 } 12557 } 12558 // All the special cases have been taken care of. 12559 // Return result based on recommended install location. 12560 if (onSd) { 12561 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12562 } 12563 return pkgLite.recommendedInstallLocation; 12564 } 12565 12566 /* 12567 * Invoke remote method to get package information and install 12568 * location values. Override install location based on default 12569 * policy if needed and then create install arguments based 12570 * on the install location. 12571 */ 12572 public void handleStartCopy() throws RemoteException { 12573 int ret = PackageManager.INSTALL_SUCCEEDED; 12574 12575 // If we're already staged, we've firmly committed to an install location 12576 if (origin.staged) { 12577 if (origin.file != null) { 12578 installFlags |= PackageManager.INSTALL_INTERNAL; 12579 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12580 } else if (origin.cid != null) { 12581 installFlags |= PackageManager.INSTALL_EXTERNAL; 12582 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12583 } else { 12584 throw new IllegalStateException("Invalid stage location"); 12585 } 12586 } 12587 12588 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12589 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12590 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12591 PackageInfoLite pkgLite = null; 12592 12593 if (onInt && onSd) { 12594 // Check if both bits are set. 12595 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12596 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12597 } else if (onSd && ephemeral) { 12598 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12599 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12600 } else { 12601 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12602 packageAbiOverride); 12603 12604 if (DEBUG_EPHEMERAL && ephemeral) { 12605 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12606 } 12607 12608 /* 12609 * If we have too little free space, try to free cache 12610 * before giving up. 12611 */ 12612 if (!origin.staged && pkgLite.recommendedInstallLocation 12613 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12614 // TODO: focus freeing disk space on the target device 12615 final StorageManager storage = StorageManager.from(mContext); 12616 final long lowThreshold = storage.getStorageLowBytes( 12617 Environment.getDataDirectory()); 12618 12619 final long sizeBytes = mContainerService.calculateInstalledSize( 12620 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12621 12622 try { 12623 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12624 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12625 installFlags, packageAbiOverride); 12626 } catch (InstallerException e) { 12627 Slog.w(TAG, "Failed to free cache", e); 12628 } 12629 12630 /* 12631 * The cache free must have deleted the file we 12632 * downloaded to install. 12633 * 12634 * TODO: fix the "freeCache" call to not delete 12635 * the file we care about. 12636 */ 12637 if (pkgLite.recommendedInstallLocation 12638 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12639 pkgLite.recommendedInstallLocation 12640 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12641 } 12642 } 12643 } 12644 12645 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12646 int loc = pkgLite.recommendedInstallLocation; 12647 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12648 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12649 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12650 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12651 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12652 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12653 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12654 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12655 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12656 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12657 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12658 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12659 } else { 12660 // Override with defaults if needed. 12661 loc = installLocationPolicy(pkgLite); 12662 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12663 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12664 } else if (!onSd && !onInt) { 12665 // Override install location with flags 12666 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12667 // Set the flag to install on external media. 12668 installFlags |= PackageManager.INSTALL_EXTERNAL; 12669 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12670 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12671 if (DEBUG_EPHEMERAL) { 12672 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12673 } 12674 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12675 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12676 |PackageManager.INSTALL_INTERNAL); 12677 } else { 12678 // Make sure the flag for installing on external 12679 // media is unset 12680 installFlags |= PackageManager.INSTALL_INTERNAL; 12681 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12682 } 12683 } 12684 } 12685 } 12686 12687 final InstallArgs args = createInstallArgs(this); 12688 mArgs = args; 12689 12690 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12691 // TODO: http://b/22976637 12692 // Apps installed for "all" users use the device owner to verify the app 12693 UserHandle verifierUser = getUser(); 12694 if (verifierUser == UserHandle.ALL) { 12695 verifierUser = UserHandle.SYSTEM; 12696 } 12697 12698 /* 12699 * Determine if we have any installed package verifiers. If we 12700 * do, then we'll defer to them to verify the packages. 12701 */ 12702 final int requiredUid = mRequiredVerifierPackage == null ? -1 12703 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12704 verifierUser.getIdentifier()); 12705 if (!origin.existing && requiredUid != -1 12706 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12707 final Intent verification = new Intent( 12708 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12709 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12710 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12711 PACKAGE_MIME_TYPE); 12712 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12713 12714 // Query all live verifiers based on current user state 12715 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12716 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12717 12718 if (DEBUG_VERIFY) { 12719 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12720 + verification.toString() + " with " + pkgLite.verifiers.length 12721 + " optional verifiers"); 12722 } 12723 12724 final int verificationId = mPendingVerificationToken++; 12725 12726 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12727 12728 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12729 installerPackageName); 12730 12731 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12732 installFlags); 12733 12734 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12735 pkgLite.packageName); 12736 12737 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12738 pkgLite.versionCode); 12739 12740 if (verificationInfo != null) { 12741 if (verificationInfo.originatingUri != null) { 12742 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12743 verificationInfo.originatingUri); 12744 } 12745 if (verificationInfo.referrer != null) { 12746 verification.putExtra(Intent.EXTRA_REFERRER, 12747 verificationInfo.referrer); 12748 } 12749 if (verificationInfo.originatingUid >= 0) { 12750 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12751 verificationInfo.originatingUid); 12752 } 12753 if (verificationInfo.installerUid >= 0) { 12754 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12755 verificationInfo.installerUid); 12756 } 12757 } 12758 12759 final PackageVerificationState verificationState = new PackageVerificationState( 12760 requiredUid, args); 12761 12762 mPendingVerification.append(verificationId, verificationState); 12763 12764 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12765 receivers, verificationState); 12766 12767 /* 12768 * If any sufficient verifiers were listed in the package 12769 * manifest, attempt to ask them. 12770 */ 12771 if (sufficientVerifiers != null) { 12772 final int N = sufficientVerifiers.size(); 12773 if (N == 0) { 12774 Slog.i(TAG, "Additional verifiers required, but none installed."); 12775 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12776 } else { 12777 for (int i = 0; i < N; i++) { 12778 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12779 12780 final Intent sufficientIntent = new Intent(verification); 12781 sufficientIntent.setComponent(verifierComponent); 12782 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12783 } 12784 } 12785 } 12786 12787 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12788 mRequiredVerifierPackage, receivers); 12789 if (ret == PackageManager.INSTALL_SUCCEEDED 12790 && mRequiredVerifierPackage != null) { 12791 Trace.asyncTraceBegin( 12792 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12793 /* 12794 * Send the intent to the required verification agent, 12795 * but only start the verification timeout after the 12796 * target BroadcastReceivers have run. 12797 */ 12798 verification.setComponent(requiredVerifierComponent); 12799 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12800 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12801 new BroadcastReceiver() { 12802 @Override 12803 public void onReceive(Context context, Intent intent) { 12804 final Message msg = mHandler 12805 .obtainMessage(CHECK_PENDING_VERIFICATION); 12806 msg.arg1 = verificationId; 12807 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12808 } 12809 }, null, 0, null, null); 12810 12811 /* 12812 * We don't want the copy to proceed until verification 12813 * succeeds, so null out this field. 12814 */ 12815 mArgs = null; 12816 } 12817 } else { 12818 /* 12819 * No package verification is enabled, so immediately start 12820 * the remote call to initiate copy using temporary file. 12821 */ 12822 ret = args.copyApk(mContainerService, true); 12823 } 12824 } 12825 12826 mRet = ret; 12827 } 12828 12829 @Override 12830 void handleReturnCode() { 12831 // If mArgs is null, then MCS couldn't be reached. When it 12832 // reconnects, it will try again to install. At that point, this 12833 // will succeed. 12834 if (mArgs != null) { 12835 processPendingInstall(mArgs, mRet); 12836 } 12837 } 12838 12839 @Override 12840 void handleServiceError() { 12841 mArgs = createInstallArgs(this); 12842 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12843 } 12844 12845 public boolean isForwardLocked() { 12846 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12847 } 12848 } 12849 12850 /** 12851 * Used during creation of InstallArgs 12852 * 12853 * @param installFlags package installation flags 12854 * @return true if should be installed on external storage 12855 */ 12856 private static boolean installOnExternalAsec(int installFlags) { 12857 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12858 return false; 12859 } 12860 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12861 return true; 12862 } 12863 return false; 12864 } 12865 12866 /** 12867 * Used during creation of InstallArgs 12868 * 12869 * @param installFlags package installation flags 12870 * @return true if should be installed as forward locked 12871 */ 12872 private static boolean installForwardLocked(int installFlags) { 12873 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12874 } 12875 12876 private InstallArgs createInstallArgs(InstallParams params) { 12877 if (params.move != null) { 12878 return new MoveInstallArgs(params); 12879 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12880 return new AsecInstallArgs(params); 12881 } else { 12882 return new FileInstallArgs(params); 12883 } 12884 } 12885 12886 /** 12887 * Create args that describe an existing installed package. Typically used 12888 * when cleaning up old installs, or used as a move source. 12889 */ 12890 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12891 String resourcePath, String[] instructionSets) { 12892 final boolean isInAsec; 12893 if (installOnExternalAsec(installFlags)) { 12894 /* Apps on SD card are always in ASEC containers. */ 12895 isInAsec = true; 12896 } else if (installForwardLocked(installFlags) 12897 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12898 /* 12899 * Forward-locked apps are only in ASEC containers if they're the 12900 * new style 12901 */ 12902 isInAsec = true; 12903 } else { 12904 isInAsec = false; 12905 } 12906 12907 if (isInAsec) { 12908 return new AsecInstallArgs(codePath, instructionSets, 12909 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12910 } else { 12911 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12912 } 12913 } 12914 12915 static abstract class InstallArgs { 12916 /** @see InstallParams#origin */ 12917 final OriginInfo origin; 12918 /** @see InstallParams#move */ 12919 final MoveInfo move; 12920 12921 final IPackageInstallObserver2 observer; 12922 // Always refers to PackageManager flags only 12923 final int installFlags; 12924 final String installerPackageName; 12925 final String volumeUuid; 12926 final UserHandle user; 12927 final String abiOverride; 12928 final String[] installGrantPermissions; 12929 /** If non-null, drop an async trace when the install completes */ 12930 final String traceMethod; 12931 final int traceCookie; 12932 final Certificate[][] certificates; 12933 12934 // The list of instruction sets supported by this app. This is currently 12935 // only used during the rmdex() phase to clean up resources. We can get rid of this 12936 // if we move dex files under the common app path. 12937 /* nullable */ String[] instructionSets; 12938 12939 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12940 int installFlags, String installerPackageName, String volumeUuid, 12941 UserHandle user, String[] instructionSets, 12942 String abiOverride, String[] installGrantPermissions, 12943 String traceMethod, int traceCookie, Certificate[][] certificates) { 12944 this.origin = origin; 12945 this.move = move; 12946 this.installFlags = installFlags; 12947 this.observer = observer; 12948 this.installerPackageName = installerPackageName; 12949 this.volumeUuid = volumeUuid; 12950 this.user = user; 12951 this.instructionSets = instructionSets; 12952 this.abiOverride = abiOverride; 12953 this.installGrantPermissions = installGrantPermissions; 12954 this.traceMethod = traceMethod; 12955 this.traceCookie = traceCookie; 12956 this.certificates = certificates; 12957 } 12958 12959 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12960 abstract int doPreInstall(int status); 12961 12962 /** 12963 * Rename package into final resting place. All paths on the given 12964 * scanned package should be updated to reflect the rename. 12965 */ 12966 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12967 abstract int doPostInstall(int status, int uid); 12968 12969 /** @see PackageSettingBase#codePathString */ 12970 abstract String getCodePath(); 12971 /** @see PackageSettingBase#resourcePathString */ 12972 abstract String getResourcePath(); 12973 12974 // Need installer lock especially for dex file removal. 12975 abstract void cleanUpResourcesLI(); 12976 abstract boolean doPostDeleteLI(boolean delete); 12977 12978 /** 12979 * Called before the source arguments are copied. This is used mostly 12980 * for MoveParams when it needs to read the source file to put it in the 12981 * destination. 12982 */ 12983 int doPreCopy() { 12984 return PackageManager.INSTALL_SUCCEEDED; 12985 } 12986 12987 /** 12988 * Called after the source arguments are copied. This is used mostly for 12989 * MoveParams when it needs to read the source file to put it in the 12990 * destination. 12991 */ 12992 int doPostCopy(int uid) { 12993 return PackageManager.INSTALL_SUCCEEDED; 12994 } 12995 12996 protected boolean isFwdLocked() { 12997 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12998 } 12999 13000 protected boolean isExternalAsec() { 13001 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13002 } 13003 13004 protected boolean isEphemeral() { 13005 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13006 } 13007 13008 UserHandle getUser() { 13009 return user; 13010 } 13011 } 13012 13013 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13014 if (!allCodePaths.isEmpty()) { 13015 if (instructionSets == null) { 13016 throw new IllegalStateException("instructionSet == null"); 13017 } 13018 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13019 for (String codePath : allCodePaths) { 13020 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13021 try { 13022 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13023 } catch (InstallerException ignored) { 13024 } 13025 } 13026 } 13027 } 13028 } 13029 13030 /** 13031 * Logic to handle installation of non-ASEC applications, including copying 13032 * and renaming logic. 13033 */ 13034 class FileInstallArgs extends InstallArgs { 13035 private File codeFile; 13036 private File resourceFile; 13037 13038 // Example topology: 13039 // /data/app/com.example/base.apk 13040 // /data/app/com.example/split_foo.apk 13041 // /data/app/com.example/lib/arm/libfoo.so 13042 // /data/app/com.example/lib/arm64/libfoo.so 13043 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13044 13045 /** New install */ 13046 FileInstallArgs(InstallParams params) { 13047 super(params.origin, params.move, params.observer, params.installFlags, 13048 params.installerPackageName, params.volumeUuid, 13049 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13050 params.grantedRuntimePermissions, 13051 params.traceMethod, params.traceCookie, params.certificates); 13052 if (isFwdLocked()) { 13053 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13054 } 13055 } 13056 13057 /** Existing install */ 13058 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13059 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13060 null, null, null, 0, null /*certificates*/); 13061 this.codeFile = (codePath != null) ? new File(codePath) : null; 13062 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13063 } 13064 13065 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13066 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13067 try { 13068 return doCopyApk(imcs, temp); 13069 } finally { 13070 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13071 } 13072 } 13073 13074 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13075 if (origin.staged) { 13076 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13077 codeFile = origin.file; 13078 resourceFile = origin.file; 13079 return PackageManager.INSTALL_SUCCEEDED; 13080 } 13081 13082 try { 13083 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13084 final File tempDir = 13085 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13086 codeFile = tempDir; 13087 resourceFile = tempDir; 13088 } catch (IOException e) { 13089 Slog.w(TAG, "Failed to create copy file: " + e); 13090 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13091 } 13092 13093 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13094 @Override 13095 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13096 if (!FileUtils.isValidExtFilename(name)) { 13097 throw new IllegalArgumentException("Invalid filename: " + name); 13098 } 13099 try { 13100 final File file = new File(codeFile, name); 13101 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13102 O_RDWR | O_CREAT, 0644); 13103 Os.chmod(file.getAbsolutePath(), 0644); 13104 return new ParcelFileDescriptor(fd); 13105 } catch (ErrnoException e) { 13106 throw new RemoteException("Failed to open: " + e.getMessage()); 13107 } 13108 } 13109 }; 13110 13111 int ret = PackageManager.INSTALL_SUCCEEDED; 13112 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13113 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13114 Slog.e(TAG, "Failed to copy package"); 13115 return ret; 13116 } 13117 13118 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13119 NativeLibraryHelper.Handle handle = null; 13120 try { 13121 handle = NativeLibraryHelper.Handle.create(codeFile); 13122 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13123 abiOverride); 13124 } catch (IOException e) { 13125 Slog.e(TAG, "Copying native libraries failed", e); 13126 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13127 } finally { 13128 IoUtils.closeQuietly(handle); 13129 } 13130 13131 return ret; 13132 } 13133 13134 int doPreInstall(int status) { 13135 if (status != PackageManager.INSTALL_SUCCEEDED) { 13136 cleanUp(); 13137 } 13138 return status; 13139 } 13140 13141 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13142 if (status != PackageManager.INSTALL_SUCCEEDED) { 13143 cleanUp(); 13144 return false; 13145 } 13146 13147 final File targetDir = codeFile.getParentFile(); 13148 final File beforeCodeFile = codeFile; 13149 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13150 13151 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13152 try { 13153 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13154 } catch (ErrnoException e) { 13155 Slog.w(TAG, "Failed to rename", e); 13156 return false; 13157 } 13158 13159 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13160 Slog.w(TAG, "Failed to restorecon"); 13161 return false; 13162 } 13163 13164 // Reflect the rename internally 13165 codeFile = afterCodeFile; 13166 resourceFile = afterCodeFile; 13167 13168 // Reflect the rename in scanned details 13169 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13170 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13171 afterCodeFile, pkg.baseCodePath)); 13172 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13173 afterCodeFile, pkg.splitCodePaths)); 13174 13175 // Reflect the rename in app info 13176 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13177 pkg.setApplicationInfoCodePath(pkg.codePath); 13178 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13179 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13180 pkg.setApplicationInfoResourcePath(pkg.codePath); 13181 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13182 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13183 13184 return true; 13185 } 13186 13187 int doPostInstall(int status, int uid) { 13188 if (status != PackageManager.INSTALL_SUCCEEDED) { 13189 cleanUp(); 13190 } 13191 return status; 13192 } 13193 13194 @Override 13195 String getCodePath() { 13196 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13197 } 13198 13199 @Override 13200 String getResourcePath() { 13201 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13202 } 13203 13204 private boolean cleanUp() { 13205 if (codeFile == null || !codeFile.exists()) { 13206 return false; 13207 } 13208 13209 removeCodePathLI(codeFile); 13210 13211 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13212 resourceFile.delete(); 13213 } 13214 13215 return true; 13216 } 13217 13218 void cleanUpResourcesLI() { 13219 // Try enumerating all code paths before deleting 13220 List<String> allCodePaths = Collections.EMPTY_LIST; 13221 if (codeFile != null && codeFile.exists()) { 13222 try { 13223 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13224 allCodePaths = pkg.getAllCodePaths(); 13225 } catch (PackageParserException e) { 13226 // Ignored; we tried our best 13227 } 13228 } 13229 13230 cleanUp(); 13231 removeDexFiles(allCodePaths, instructionSets); 13232 } 13233 13234 boolean doPostDeleteLI(boolean delete) { 13235 // XXX err, shouldn't we respect the delete flag? 13236 cleanUpResourcesLI(); 13237 return true; 13238 } 13239 } 13240 13241 private boolean isAsecExternal(String cid) { 13242 final String asecPath = PackageHelper.getSdFilesystem(cid); 13243 return !asecPath.startsWith(mAsecInternalPath); 13244 } 13245 13246 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13247 PackageManagerException { 13248 if (copyRet < 0) { 13249 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13250 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13251 throw new PackageManagerException(copyRet, message); 13252 } 13253 } 13254 } 13255 13256 /** 13257 * Extract the MountService "container ID" from the full code path of an 13258 * .apk. 13259 */ 13260 static String cidFromCodePath(String fullCodePath) { 13261 int eidx = fullCodePath.lastIndexOf("/"); 13262 String subStr1 = fullCodePath.substring(0, eidx); 13263 int sidx = subStr1.lastIndexOf("/"); 13264 return subStr1.substring(sidx+1, eidx); 13265 } 13266 13267 /** 13268 * Logic to handle installation of ASEC applications, including copying and 13269 * renaming logic. 13270 */ 13271 class AsecInstallArgs extends InstallArgs { 13272 static final String RES_FILE_NAME = "pkg.apk"; 13273 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13274 13275 String cid; 13276 String packagePath; 13277 String resourcePath; 13278 13279 /** New install */ 13280 AsecInstallArgs(InstallParams params) { 13281 super(params.origin, params.move, params.observer, params.installFlags, 13282 params.installerPackageName, params.volumeUuid, 13283 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13284 params.grantedRuntimePermissions, 13285 params.traceMethod, params.traceCookie, params.certificates); 13286 } 13287 13288 /** Existing install */ 13289 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13290 boolean isExternal, boolean isForwardLocked) { 13291 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13292 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13293 instructionSets, null, null, null, 0, null /*certificates*/); 13294 // Hackily pretend we're still looking at a full code path 13295 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13296 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13297 } 13298 13299 // Extract cid from fullCodePath 13300 int eidx = fullCodePath.lastIndexOf("/"); 13301 String subStr1 = fullCodePath.substring(0, eidx); 13302 int sidx = subStr1.lastIndexOf("/"); 13303 cid = subStr1.substring(sidx+1, eidx); 13304 setMountPath(subStr1); 13305 } 13306 13307 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13308 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13309 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13310 instructionSets, null, null, null, 0, null /*certificates*/); 13311 this.cid = cid; 13312 setMountPath(PackageHelper.getSdDir(cid)); 13313 } 13314 13315 void createCopyFile() { 13316 cid = mInstallerService.allocateExternalStageCidLegacy(); 13317 } 13318 13319 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13320 if (origin.staged && origin.cid != null) { 13321 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13322 cid = origin.cid; 13323 setMountPath(PackageHelper.getSdDir(cid)); 13324 return PackageManager.INSTALL_SUCCEEDED; 13325 } 13326 13327 if (temp) { 13328 createCopyFile(); 13329 } else { 13330 /* 13331 * Pre-emptively destroy the container since it's destroyed if 13332 * copying fails due to it existing anyway. 13333 */ 13334 PackageHelper.destroySdDir(cid); 13335 } 13336 13337 final String newMountPath = imcs.copyPackageToContainer( 13338 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13339 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13340 13341 if (newMountPath != null) { 13342 setMountPath(newMountPath); 13343 return PackageManager.INSTALL_SUCCEEDED; 13344 } else { 13345 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13346 } 13347 } 13348 13349 @Override 13350 String getCodePath() { 13351 return packagePath; 13352 } 13353 13354 @Override 13355 String getResourcePath() { 13356 return resourcePath; 13357 } 13358 13359 int doPreInstall(int status) { 13360 if (status != PackageManager.INSTALL_SUCCEEDED) { 13361 // Destroy container 13362 PackageHelper.destroySdDir(cid); 13363 } else { 13364 boolean mounted = PackageHelper.isContainerMounted(cid); 13365 if (!mounted) { 13366 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13367 Process.SYSTEM_UID); 13368 if (newMountPath != null) { 13369 setMountPath(newMountPath); 13370 } else { 13371 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13372 } 13373 } 13374 } 13375 return status; 13376 } 13377 13378 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13379 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13380 String newMountPath = null; 13381 if (PackageHelper.isContainerMounted(cid)) { 13382 // Unmount the container 13383 if (!PackageHelper.unMountSdDir(cid)) { 13384 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13385 return false; 13386 } 13387 } 13388 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13389 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13390 " which might be stale. Will try to clean up."); 13391 // Clean up the stale container and proceed to recreate. 13392 if (!PackageHelper.destroySdDir(newCacheId)) { 13393 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13394 return false; 13395 } 13396 // Successfully cleaned up stale container. Try to rename again. 13397 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13398 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13399 + " inspite of cleaning it up."); 13400 return false; 13401 } 13402 } 13403 if (!PackageHelper.isContainerMounted(newCacheId)) { 13404 Slog.w(TAG, "Mounting container " + newCacheId); 13405 newMountPath = PackageHelper.mountSdDir(newCacheId, 13406 getEncryptKey(), Process.SYSTEM_UID); 13407 } else { 13408 newMountPath = PackageHelper.getSdDir(newCacheId); 13409 } 13410 if (newMountPath == null) { 13411 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13412 return false; 13413 } 13414 Log.i(TAG, "Succesfully renamed " + cid + 13415 " to " + newCacheId + 13416 " at new path: " + newMountPath); 13417 cid = newCacheId; 13418 13419 final File beforeCodeFile = new File(packagePath); 13420 setMountPath(newMountPath); 13421 final File afterCodeFile = new File(packagePath); 13422 13423 // Reflect the rename in scanned details 13424 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13425 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13426 afterCodeFile, pkg.baseCodePath)); 13427 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13428 afterCodeFile, pkg.splitCodePaths)); 13429 13430 // Reflect the rename in app info 13431 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13432 pkg.setApplicationInfoCodePath(pkg.codePath); 13433 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13434 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13435 pkg.setApplicationInfoResourcePath(pkg.codePath); 13436 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13437 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13438 13439 return true; 13440 } 13441 13442 private void setMountPath(String mountPath) { 13443 final File mountFile = new File(mountPath); 13444 13445 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13446 if (monolithicFile.exists()) { 13447 packagePath = monolithicFile.getAbsolutePath(); 13448 if (isFwdLocked()) { 13449 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13450 } else { 13451 resourcePath = packagePath; 13452 } 13453 } else { 13454 packagePath = mountFile.getAbsolutePath(); 13455 resourcePath = packagePath; 13456 } 13457 } 13458 13459 int doPostInstall(int status, int uid) { 13460 if (status != PackageManager.INSTALL_SUCCEEDED) { 13461 cleanUp(); 13462 } else { 13463 final int groupOwner; 13464 final String protectedFile; 13465 if (isFwdLocked()) { 13466 groupOwner = UserHandle.getSharedAppGid(uid); 13467 protectedFile = RES_FILE_NAME; 13468 } else { 13469 groupOwner = -1; 13470 protectedFile = null; 13471 } 13472 13473 if (uid < Process.FIRST_APPLICATION_UID 13474 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13475 Slog.e(TAG, "Failed to finalize " + cid); 13476 PackageHelper.destroySdDir(cid); 13477 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13478 } 13479 13480 boolean mounted = PackageHelper.isContainerMounted(cid); 13481 if (!mounted) { 13482 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13483 } 13484 } 13485 return status; 13486 } 13487 13488 private void cleanUp() { 13489 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13490 13491 // Destroy secure container 13492 PackageHelper.destroySdDir(cid); 13493 } 13494 13495 private List<String> getAllCodePaths() { 13496 final File codeFile = new File(getCodePath()); 13497 if (codeFile != null && codeFile.exists()) { 13498 try { 13499 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13500 return pkg.getAllCodePaths(); 13501 } catch (PackageParserException e) { 13502 // Ignored; we tried our best 13503 } 13504 } 13505 return Collections.EMPTY_LIST; 13506 } 13507 13508 void cleanUpResourcesLI() { 13509 // Enumerate all code paths before deleting 13510 cleanUpResourcesLI(getAllCodePaths()); 13511 } 13512 13513 private void cleanUpResourcesLI(List<String> allCodePaths) { 13514 cleanUp(); 13515 removeDexFiles(allCodePaths, instructionSets); 13516 } 13517 13518 String getPackageName() { 13519 return getAsecPackageName(cid); 13520 } 13521 13522 boolean doPostDeleteLI(boolean delete) { 13523 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13524 final List<String> allCodePaths = getAllCodePaths(); 13525 boolean mounted = PackageHelper.isContainerMounted(cid); 13526 if (mounted) { 13527 // Unmount first 13528 if (PackageHelper.unMountSdDir(cid)) { 13529 mounted = false; 13530 } 13531 } 13532 if (!mounted && delete) { 13533 cleanUpResourcesLI(allCodePaths); 13534 } 13535 return !mounted; 13536 } 13537 13538 @Override 13539 int doPreCopy() { 13540 if (isFwdLocked()) { 13541 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13542 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13543 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13544 } 13545 } 13546 13547 return PackageManager.INSTALL_SUCCEEDED; 13548 } 13549 13550 @Override 13551 int doPostCopy(int uid) { 13552 if (isFwdLocked()) { 13553 if (uid < Process.FIRST_APPLICATION_UID 13554 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13555 RES_FILE_NAME)) { 13556 Slog.e(TAG, "Failed to finalize " + cid); 13557 PackageHelper.destroySdDir(cid); 13558 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13559 } 13560 } 13561 13562 return PackageManager.INSTALL_SUCCEEDED; 13563 } 13564 } 13565 13566 /** 13567 * Logic to handle movement of existing installed applications. 13568 */ 13569 class MoveInstallArgs extends InstallArgs { 13570 private File codeFile; 13571 private File resourceFile; 13572 13573 /** New install */ 13574 MoveInstallArgs(InstallParams params) { 13575 super(params.origin, params.move, params.observer, params.installFlags, 13576 params.installerPackageName, params.volumeUuid, 13577 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13578 params.grantedRuntimePermissions, 13579 params.traceMethod, params.traceCookie, params.certificates); 13580 } 13581 13582 int copyApk(IMediaContainerService imcs, boolean temp) { 13583 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13584 + move.fromUuid + " to " + move.toUuid); 13585 synchronized (mInstaller) { 13586 try { 13587 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13588 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13589 } catch (InstallerException e) { 13590 Slog.w(TAG, "Failed to move app", e); 13591 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13592 } 13593 } 13594 13595 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13596 resourceFile = codeFile; 13597 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13598 13599 return PackageManager.INSTALL_SUCCEEDED; 13600 } 13601 13602 int doPreInstall(int status) { 13603 if (status != PackageManager.INSTALL_SUCCEEDED) { 13604 cleanUp(move.toUuid); 13605 } 13606 return status; 13607 } 13608 13609 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13610 if (status != PackageManager.INSTALL_SUCCEEDED) { 13611 cleanUp(move.toUuid); 13612 return false; 13613 } 13614 13615 // Reflect the move in app info 13616 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13617 pkg.setApplicationInfoCodePath(pkg.codePath); 13618 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13619 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13620 pkg.setApplicationInfoResourcePath(pkg.codePath); 13621 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13622 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13623 13624 return true; 13625 } 13626 13627 int doPostInstall(int status, int uid) { 13628 if (status == PackageManager.INSTALL_SUCCEEDED) { 13629 cleanUp(move.fromUuid); 13630 } else { 13631 cleanUp(move.toUuid); 13632 } 13633 return status; 13634 } 13635 13636 @Override 13637 String getCodePath() { 13638 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13639 } 13640 13641 @Override 13642 String getResourcePath() { 13643 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13644 } 13645 13646 private boolean cleanUp(String volumeUuid) { 13647 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13648 move.dataAppName); 13649 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13650 final int[] userIds = sUserManager.getUserIds(); 13651 synchronized (mInstallLock) { 13652 // Clean up both app data and code 13653 // All package moves are frozen until finished 13654 for (int userId : userIds) { 13655 try { 13656 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13657 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13658 } catch (InstallerException e) { 13659 Slog.w(TAG, String.valueOf(e)); 13660 } 13661 } 13662 removeCodePathLI(codeFile); 13663 } 13664 return true; 13665 } 13666 13667 void cleanUpResourcesLI() { 13668 throw new UnsupportedOperationException(); 13669 } 13670 13671 boolean doPostDeleteLI(boolean delete) { 13672 throw new UnsupportedOperationException(); 13673 } 13674 } 13675 13676 static String getAsecPackageName(String packageCid) { 13677 int idx = packageCid.lastIndexOf("-"); 13678 if (idx == -1) { 13679 return packageCid; 13680 } 13681 return packageCid.substring(0, idx); 13682 } 13683 13684 // Utility method used to create code paths based on package name and available index. 13685 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13686 String idxStr = ""; 13687 int idx = 1; 13688 // Fall back to default value of idx=1 if prefix is not 13689 // part of oldCodePath 13690 if (oldCodePath != null) { 13691 String subStr = oldCodePath; 13692 // Drop the suffix right away 13693 if (suffix != null && subStr.endsWith(suffix)) { 13694 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13695 } 13696 // If oldCodePath already contains prefix find out the 13697 // ending index to either increment or decrement. 13698 int sidx = subStr.lastIndexOf(prefix); 13699 if (sidx != -1) { 13700 subStr = subStr.substring(sidx + prefix.length()); 13701 if (subStr != null) { 13702 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13703 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13704 } 13705 try { 13706 idx = Integer.parseInt(subStr); 13707 if (idx <= 1) { 13708 idx++; 13709 } else { 13710 idx--; 13711 } 13712 } catch(NumberFormatException e) { 13713 } 13714 } 13715 } 13716 } 13717 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13718 return prefix + idxStr; 13719 } 13720 13721 private File getNextCodePath(File targetDir, String packageName) { 13722 int suffix = 1; 13723 File result; 13724 do { 13725 result = new File(targetDir, packageName + "-" + suffix); 13726 suffix++; 13727 } while (result.exists()); 13728 return result; 13729 } 13730 13731 // Utility method that returns the relative package path with respect 13732 // to the installation directory. Like say for /data/data/com.test-1.apk 13733 // string com.test-1 is returned. 13734 static String deriveCodePathName(String codePath) { 13735 if (codePath == null) { 13736 return null; 13737 } 13738 final File codeFile = new File(codePath); 13739 final String name = codeFile.getName(); 13740 if (codeFile.isDirectory()) { 13741 return name; 13742 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13743 final int lastDot = name.lastIndexOf('.'); 13744 return name.substring(0, lastDot); 13745 } else { 13746 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13747 return null; 13748 } 13749 } 13750 13751 static class PackageInstalledInfo { 13752 String name; 13753 int uid; 13754 // The set of users that originally had this package installed. 13755 int[] origUsers; 13756 // The set of users that now have this package installed. 13757 int[] newUsers; 13758 PackageParser.Package pkg; 13759 int returnCode; 13760 String returnMsg; 13761 PackageRemovedInfo removedInfo; 13762 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13763 13764 public void setError(int code, String msg) { 13765 setReturnCode(code); 13766 setReturnMessage(msg); 13767 Slog.w(TAG, msg); 13768 } 13769 13770 public void setError(String msg, PackageParserException e) { 13771 setReturnCode(e.error); 13772 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13773 Slog.w(TAG, msg, e); 13774 } 13775 13776 public void setError(String msg, PackageManagerException e) { 13777 returnCode = e.error; 13778 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13779 Slog.w(TAG, msg, e); 13780 } 13781 13782 public void setReturnCode(int returnCode) { 13783 this.returnCode = returnCode; 13784 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13785 for (int i = 0; i < childCount; i++) { 13786 addedChildPackages.valueAt(i).returnCode = returnCode; 13787 } 13788 } 13789 13790 private void setReturnMessage(String returnMsg) { 13791 this.returnMsg = returnMsg; 13792 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13793 for (int i = 0; i < childCount; i++) { 13794 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13795 } 13796 } 13797 13798 // In some error cases we want to convey more info back to the observer 13799 String origPackage; 13800 String origPermission; 13801 } 13802 13803 /* 13804 * Install a non-existing package. 13805 */ 13806 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13807 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13808 PackageInstalledInfo res) { 13809 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13810 13811 // Remember this for later, in case we need to rollback this install 13812 String pkgName = pkg.packageName; 13813 13814 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13815 13816 synchronized(mPackages) { 13817 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13818 // A package with the same name is already installed, though 13819 // it has been renamed to an older name. The package we 13820 // are trying to install should be installed as an update to 13821 // the existing one, but that has not been requested, so bail. 13822 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13823 + " without first uninstalling package running as " 13824 + mSettings.mRenamedPackages.get(pkgName)); 13825 return; 13826 } 13827 if (mPackages.containsKey(pkgName)) { 13828 // Don't allow installation over an existing package with the same name. 13829 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13830 + " without first uninstalling."); 13831 return; 13832 } 13833 } 13834 13835 try { 13836 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13837 System.currentTimeMillis(), user); 13838 13839 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13840 13841 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13842 prepareAppDataAfterInstallLIF(newPackage); 13843 13844 } else { 13845 // Remove package from internal structures, but keep around any 13846 // data that might have already existed 13847 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13848 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13849 } 13850 } catch (PackageManagerException e) { 13851 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13852 } 13853 13854 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13855 } 13856 13857 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13858 // Can't rotate keys during boot or if sharedUser. 13859 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13860 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13861 return false; 13862 } 13863 // app is using upgradeKeySets; make sure all are valid 13864 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13865 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13866 for (int i = 0; i < upgradeKeySets.length; i++) { 13867 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13868 Slog.wtf(TAG, "Package " 13869 + (oldPs.name != null ? oldPs.name : "<null>") 13870 + " contains upgrade-key-set reference to unknown key-set: " 13871 + upgradeKeySets[i] 13872 + " reverting to signatures check."); 13873 return false; 13874 } 13875 } 13876 return true; 13877 } 13878 13879 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13880 // Upgrade keysets are being used. Determine if new package has a superset of the 13881 // required keys. 13882 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13883 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13884 for (int i = 0; i < upgradeKeySets.length; i++) { 13885 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13886 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13887 return true; 13888 } 13889 } 13890 return false; 13891 } 13892 13893 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13894 try (DigestInputStream digestStream = 13895 new DigestInputStream(new FileInputStream(file), digest)) { 13896 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13897 } 13898 } 13899 13900 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13901 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13902 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13903 13904 final PackageParser.Package oldPackage; 13905 final String pkgName = pkg.packageName; 13906 final int[] allUsers; 13907 final int[] installedUsers; 13908 13909 synchronized(mPackages) { 13910 oldPackage = mPackages.get(pkgName); 13911 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13912 13913 // don't allow upgrade to target a release SDK from a pre-release SDK 13914 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13915 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13916 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13917 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13918 if (oldTargetsPreRelease 13919 && !newTargetsPreRelease 13920 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13921 Slog.w(TAG, "Can't install package targeting released sdk"); 13922 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13923 return; 13924 } 13925 13926 // don't allow an upgrade from full to ephemeral 13927 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13928 if (isEphemeral && !oldIsEphemeral) { 13929 // can't downgrade from full to ephemeral 13930 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13931 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13932 return; 13933 } 13934 13935 // verify signatures are valid 13936 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13937 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13938 if (!checkUpgradeKeySetLP(ps, pkg)) { 13939 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13940 "New package not signed by keys specified by upgrade-keysets: " 13941 + pkgName); 13942 return; 13943 } 13944 } else { 13945 // default to original signature matching 13946 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13947 != PackageManager.SIGNATURE_MATCH) { 13948 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13949 "New package has a different signature: " + pkgName); 13950 return; 13951 } 13952 } 13953 13954 // don't allow a system upgrade unless the upgrade hash matches 13955 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13956 byte[] digestBytes = null; 13957 try { 13958 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13959 updateDigest(digest, new File(pkg.baseCodePath)); 13960 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13961 for (String path : pkg.splitCodePaths) { 13962 updateDigest(digest, new File(path)); 13963 } 13964 } 13965 digestBytes = digest.digest(); 13966 } catch (NoSuchAlgorithmException | IOException e) { 13967 res.setError(INSTALL_FAILED_INVALID_APK, 13968 "Could not compute hash: " + pkgName); 13969 return; 13970 } 13971 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13972 res.setError(INSTALL_FAILED_INVALID_APK, 13973 "New package fails restrict-update check: " + pkgName); 13974 return; 13975 } 13976 // retain upgrade restriction 13977 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13978 } 13979 13980 // Check for shared user id changes 13981 String invalidPackageName = 13982 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13983 if (invalidPackageName != null) { 13984 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13985 "Package " + invalidPackageName + " tried to change user " 13986 + oldPackage.mSharedUserId); 13987 return; 13988 } 13989 13990 // In case of rollback, remember per-user/profile install state 13991 allUsers = sUserManager.getUserIds(); 13992 installedUsers = ps.queryInstalledUsers(allUsers, true); 13993 } 13994 13995 // Update what is removed 13996 res.removedInfo = new PackageRemovedInfo(); 13997 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13998 res.removedInfo.removedPackage = oldPackage.packageName; 13999 res.removedInfo.isUpdate = true; 14000 res.removedInfo.origUsers = installedUsers; 14001 final int childCount = (oldPackage.childPackages != null) 14002 ? oldPackage.childPackages.size() : 0; 14003 for (int i = 0; i < childCount; i++) { 14004 boolean childPackageUpdated = false; 14005 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14006 if (res.addedChildPackages != null) { 14007 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14008 if (childRes != null) { 14009 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14010 childRes.removedInfo.removedPackage = childPkg.packageName; 14011 childRes.removedInfo.isUpdate = true; 14012 childPackageUpdated = true; 14013 } 14014 } 14015 if (!childPackageUpdated) { 14016 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14017 childRemovedRes.removedPackage = childPkg.packageName; 14018 childRemovedRes.isUpdate = false; 14019 childRemovedRes.dataRemoved = true; 14020 synchronized (mPackages) { 14021 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14022 if (childPs != null) { 14023 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14024 } 14025 } 14026 if (res.removedInfo.removedChildPackages == null) { 14027 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14028 } 14029 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14030 } 14031 } 14032 14033 boolean sysPkg = (isSystemApp(oldPackage)); 14034 if (sysPkg) { 14035 // Set the system/privileged flags as needed 14036 final boolean privileged = 14037 (oldPackage.applicationInfo.privateFlags 14038 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14039 final int systemPolicyFlags = policyFlags 14040 | PackageParser.PARSE_IS_SYSTEM 14041 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14042 14043 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14044 user, allUsers, installerPackageName, res); 14045 } else { 14046 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14047 user, allUsers, installerPackageName, res); 14048 } 14049 } 14050 14051 public List<String> getPreviousCodePaths(String packageName) { 14052 final PackageSetting ps = mSettings.mPackages.get(packageName); 14053 final List<String> result = new ArrayList<String>(); 14054 if (ps != null && ps.oldCodePaths != null) { 14055 result.addAll(ps.oldCodePaths); 14056 } 14057 return result; 14058 } 14059 14060 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14061 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14062 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14063 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14064 + deletedPackage); 14065 14066 String pkgName = deletedPackage.packageName; 14067 boolean deletedPkg = true; 14068 boolean addedPkg = false; 14069 boolean updatedSettings = false; 14070 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14071 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14072 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14073 14074 final long origUpdateTime = (pkg.mExtras != null) 14075 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14076 14077 // First delete the existing package while retaining the data directory 14078 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14079 res.removedInfo, true, pkg)) { 14080 // If the existing package wasn't successfully deleted 14081 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14082 deletedPkg = false; 14083 } else { 14084 // Successfully deleted the old package; proceed with replace. 14085 14086 // If deleted package lived in a container, give users a chance to 14087 // relinquish resources before killing. 14088 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14089 if (DEBUG_INSTALL) { 14090 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14091 } 14092 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14093 final ArrayList<String> pkgList = new ArrayList<String>(1); 14094 pkgList.add(deletedPackage.applicationInfo.packageName); 14095 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14096 } 14097 14098 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14099 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14100 clearAppProfilesLIF(pkg); 14101 14102 try { 14103 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14104 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14105 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14106 14107 // Update the in-memory copy of the previous code paths. 14108 PackageSetting ps = mSettings.mPackages.get(pkgName); 14109 if (!killApp) { 14110 if (ps.oldCodePaths == null) { 14111 ps.oldCodePaths = new ArraySet<>(); 14112 } 14113 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14114 if (deletedPackage.splitCodePaths != null) { 14115 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14116 } 14117 } else { 14118 ps.oldCodePaths = null; 14119 } 14120 if (ps.childPackageNames != null) { 14121 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14122 final String childPkgName = ps.childPackageNames.get(i); 14123 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14124 childPs.oldCodePaths = ps.oldCodePaths; 14125 } 14126 } 14127 prepareAppDataAfterInstallLIF(newPackage); 14128 addedPkg = true; 14129 } catch (PackageManagerException e) { 14130 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14131 } 14132 } 14133 14134 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14135 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14136 14137 // Revert all internal state mutations and added folders for the failed install 14138 if (addedPkg) { 14139 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14140 res.removedInfo, true, null); 14141 } 14142 14143 // Restore the old package 14144 if (deletedPkg) { 14145 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14146 File restoreFile = new File(deletedPackage.codePath); 14147 // Parse old package 14148 boolean oldExternal = isExternal(deletedPackage); 14149 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14150 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14151 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14152 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14153 try { 14154 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14155 null); 14156 } catch (PackageManagerException e) { 14157 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14158 + e.getMessage()); 14159 return; 14160 } 14161 14162 synchronized (mPackages) { 14163 // Ensure the installer package name up to date 14164 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14165 14166 // Update permissions for restored package 14167 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14168 14169 mSettings.writeLPr(); 14170 } 14171 14172 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14173 } 14174 } else { 14175 synchronized (mPackages) { 14176 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14177 if (ps != null) { 14178 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14179 if (res.removedInfo.removedChildPackages != null) { 14180 final int childCount = res.removedInfo.removedChildPackages.size(); 14181 // Iterate in reverse as we may modify the collection 14182 for (int i = childCount - 1; i >= 0; i--) { 14183 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14184 if (res.addedChildPackages.containsKey(childPackageName)) { 14185 res.removedInfo.removedChildPackages.removeAt(i); 14186 } else { 14187 PackageRemovedInfo childInfo = res.removedInfo 14188 .removedChildPackages.valueAt(i); 14189 childInfo.removedForAllUsers = mPackages.get( 14190 childInfo.removedPackage) == null; 14191 } 14192 } 14193 } 14194 } 14195 } 14196 } 14197 } 14198 14199 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14200 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14201 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14202 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14203 + ", old=" + deletedPackage); 14204 14205 final boolean disabledSystem; 14206 14207 // Remove existing system package 14208 removePackageLI(deletedPackage, true); 14209 14210 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14211 if (!disabledSystem) { 14212 // We didn't need to disable the .apk as a current system package, 14213 // which means we are replacing another update that is already 14214 // installed. We need to make sure to delete the older one's .apk. 14215 res.removedInfo.args = createInstallArgsForExisting(0, 14216 deletedPackage.applicationInfo.getCodePath(), 14217 deletedPackage.applicationInfo.getResourcePath(), 14218 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14219 } else { 14220 res.removedInfo.args = null; 14221 } 14222 14223 // Successfully disabled the old package. Now proceed with re-installation 14224 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14225 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14226 clearAppProfilesLIF(pkg); 14227 14228 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14229 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14230 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14231 14232 PackageParser.Package newPackage = null; 14233 try { 14234 // Add the package to the internal data structures 14235 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14236 14237 // Set the update and install times 14238 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14239 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14240 System.currentTimeMillis()); 14241 14242 // Update the package dynamic state if succeeded 14243 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14244 // Now that the install succeeded make sure we remove data 14245 // directories for any child package the update removed. 14246 final int deletedChildCount = (deletedPackage.childPackages != null) 14247 ? deletedPackage.childPackages.size() : 0; 14248 final int newChildCount = (newPackage.childPackages != null) 14249 ? newPackage.childPackages.size() : 0; 14250 for (int i = 0; i < deletedChildCount; i++) { 14251 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14252 boolean childPackageDeleted = true; 14253 for (int j = 0; j < newChildCount; j++) { 14254 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14255 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14256 childPackageDeleted = false; 14257 break; 14258 } 14259 } 14260 if (childPackageDeleted) { 14261 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14262 deletedChildPkg.packageName); 14263 if (ps != null && res.removedInfo.removedChildPackages != null) { 14264 PackageRemovedInfo removedChildRes = res.removedInfo 14265 .removedChildPackages.get(deletedChildPkg.packageName); 14266 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14267 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14268 } 14269 } 14270 } 14271 14272 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14273 prepareAppDataAfterInstallLIF(newPackage); 14274 } 14275 } catch (PackageManagerException e) { 14276 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14277 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14278 } 14279 14280 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14281 // Re installation failed. Restore old information 14282 // Remove new pkg information 14283 if (newPackage != null) { 14284 removeInstalledPackageLI(newPackage, true); 14285 } 14286 // Add back the old system package 14287 try { 14288 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14289 } catch (PackageManagerException e) { 14290 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14291 } 14292 14293 synchronized (mPackages) { 14294 if (disabledSystem) { 14295 enableSystemPackageLPw(deletedPackage); 14296 } 14297 14298 // Ensure the installer package name up to date 14299 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14300 14301 // Update permissions for restored package 14302 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14303 14304 mSettings.writeLPr(); 14305 } 14306 14307 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14308 + " after failed upgrade"); 14309 } 14310 } 14311 14312 /** 14313 * Checks whether the parent or any of the child packages have a change shared 14314 * user. For a package to be a valid update the shred users of the parent and 14315 * the children should match. We may later support changing child shared users. 14316 * @param oldPkg The updated package. 14317 * @param newPkg The update package. 14318 * @return The shared user that change between the versions. 14319 */ 14320 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14321 PackageParser.Package newPkg) { 14322 // Check parent shared user 14323 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14324 return newPkg.packageName; 14325 } 14326 // Check child shared users 14327 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14328 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14329 for (int i = 0; i < newChildCount; i++) { 14330 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14331 // If this child was present, did it have the same shared user? 14332 for (int j = 0; j < oldChildCount; j++) { 14333 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14334 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14335 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14336 return newChildPkg.packageName; 14337 } 14338 } 14339 } 14340 return null; 14341 } 14342 14343 private void removeNativeBinariesLI(PackageSetting ps) { 14344 // Remove the lib path for the parent package 14345 if (ps != null) { 14346 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14347 // Remove the lib path for the child packages 14348 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14349 for (int i = 0; i < childCount; i++) { 14350 PackageSetting childPs = null; 14351 synchronized (mPackages) { 14352 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14353 } 14354 if (childPs != null) { 14355 NativeLibraryHelper.removeNativeBinariesLI(childPs 14356 .legacyNativeLibraryPathString); 14357 } 14358 } 14359 } 14360 } 14361 14362 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14363 // Enable the parent package 14364 mSettings.enableSystemPackageLPw(pkg.packageName); 14365 // Enable the child packages 14366 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14367 for (int i = 0; i < childCount; i++) { 14368 PackageParser.Package childPkg = pkg.childPackages.get(i); 14369 mSettings.enableSystemPackageLPw(childPkg.packageName); 14370 } 14371 } 14372 14373 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14374 PackageParser.Package newPkg) { 14375 // Disable the parent package (parent always replaced) 14376 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14377 // Disable the child packages 14378 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14379 for (int i = 0; i < childCount; i++) { 14380 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14381 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14382 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14383 } 14384 return disabled; 14385 } 14386 14387 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14388 String installerPackageName) { 14389 // Enable the parent package 14390 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14391 // Enable the child packages 14392 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14393 for (int i = 0; i < childCount; i++) { 14394 PackageParser.Package childPkg = pkg.childPackages.get(i); 14395 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14396 } 14397 } 14398 14399 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14400 // Collect all used permissions in the UID 14401 ArraySet<String> usedPermissions = new ArraySet<>(); 14402 final int packageCount = su.packages.size(); 14403 for (int i = 0; i < packageCount; i++) { 14404 PackageSetting ps = su.packages.valueAt(i); 14405 if (ps.pkg == null) { 14406 continue; 14407 } 14408 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14409 for (int j = 0; j < requestedPermCount; j++) { 14410 String permission = ps.pkg.requestedPermissions.get(j); 14411 BasePermission bp = mSettings.mPermissions.get(permission); 14412 if (bp != null) { 14413 usedPermissions.add(permission); 14414 } 14415 } 14416 } 14417 14418 PermissionsState permissionsState = su.getPermissionsState(); 14419 // Prune install permissions 14420 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14421 final int installPermCount = installPermStates.size(); 14422 for (int i = installPermCount - 1; i >= 0; i--) { 14423 PermissionState permissionState = installPermStates.get(i); 14424 if (!usedPermissions.contains(permissionState.getName())) { 14425 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14426 if (bp != null) { 14427 permissionsState.revokeInstallPermission(bp); 14428 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14429 PackageManager.MASK_PERMISSION_FLAGS, 0); 14430 } 14431 } 14432 } 14433 14434 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14435 14436 // Prune runtime permissions 14437 for (int userId : allUserIds) { 14438 List<PermissionState> runtimePermStates = permissionsState 14439 .getRuntimePermissionStates(userId); 14440 final int runtimePermCount = runtimePermStates.size(); 14441 for (int i = runtimePermCount - 1; i >= 0; i--) { 14442 PermissionState permissionState = runtimePermStates.get(i); 14443 if (!usedPermissions.contains(permissionState.getName())) { 14444 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14445 if (bp != null) { 14446 permissionsState.revokeRuntimePermission(bp, userId); 14447 permissionsState.updatePermissionFlags(bp, userId, 14448 PackageManager.MASK_PERMISSION_FLAGS, 0); 14449 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14450 runtimePermissionChangedUserIds, userId); 14451 } 14452 } 14453 } 14454 } 14455 14456 return runtimePermissionChangedUserIds; 14457 } 14458 14459 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14460 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14461 // Update the parent package setting 14462 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14463 res, user); 14464 // Update the child packages setting 14465 final int childCount = (newPackage.childPackages != null) 14466 ? newPackage.childPackages.size() : 0; 14467 for (int i = 0; i < childCount; i++) { 14468 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14469 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14470 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14471 childRes.origUsers, childRes, user); 14472 } 14473 } 14474 14475 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14476 String installerPackageName, int[] allUsers, int[] installedForUsers, 14477 PackageInstalledInfo res, UserHandle user) { 14478 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14479 14480 String pkgName = newPackage.packageName; 14481 synchronized (mPackages) { 14482 //write settings. the installStatus will be incomplete at this stage. 14483 //note that the new package setting would have already been 14484 //added to mPackages. It hasn't been persisted yet. 14485 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14486 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14487 mSettings.writeLPr(); 14488 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14489 } 14490 14491 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14492 synchronized (mPackages) { 14493 updatePermissionsLPw(newPackage.packageName, newPackage, 14494 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14495 ? UPDATE_PERMISSIONS_ALL : 0)); 14496 // For system-bundled packages, we assume that installing an upgraded version 14497 // of the package implies that the user actually wants to run that new code, 14498 // so we enable the package. 14499 PackageSetting ps = mSettings.mPackages.get(pkgName); 14500 final int userId = user.getIdentifier(); 14501 if (ps != null) { 14502 if (isSystemApp(newPackage)) { 14503 if (DEBUG_INSTALL) { 14504 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14505 } 14506 // Enable system package for requested users 14507 if (res.origUsers != null) { 14508 for (int origUserId : res.origUsers) { 14509 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14510 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14511 origUserId, installerPackageName); 14512 } 14513 } 14514 } 14515 // Also convey the prior install/uninstall state 14516 if (allUsers != null && installedForUsers != null) { 14517 for (int currentUserId : allUsers) { 14518 final boolean installed = ArrayUtils.contains( 14519 installedForUsers, currentUserId); 14520 if (DEBUG_INSTALL) { 14521 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14522 } 14523 ps.setInstalled(installed, currentUserId); 14524 } 14525 // these install state changes will be persisted in the 14526 // upcoming call to mSettings.writeLPr(). 14527 } 14528 } 14529 // It's implied that when a user requests installation, they want the app to be 14530 // installed and enabled. 14531 if (userId != UserHandle.USER_ALL) { 14532 ps.setInstalled(true, userId); 14533 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14534 } 14535 } 14536 res.name = pkgName; 14537 res.uid = newPackage.applicationInfo.uid; 14538 res.pkg = newPackage; 14539 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14540 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14541 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14542 //to update install status 14543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14544 mSettings.writeLPr(); 14545 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14546 } 14547 14548 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14549 } 14550 14551 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14552 try { 14553 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14554 installPackageLI(args, res); 14555 } finally { 14556 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14557 } 14558 } 14559 14560 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14561 final int installFlags = args.installFlags; 14562 final String installerPackageName = args.installerPackageName; 14563 final String volumeUuid = args.volumeUuid; 14564 final File tmpPackageFile = new File(args.getCodePath()); 14565 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14566 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14567 || (args.volumeUuid != null)); 14568 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14569 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14570 boolean replace = false; 14571 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14572 if (args.move != null) { 14573 // moving a complete application; perform an initial scan on the new install location 14574 scanFlags |= SCAN_INITIAL; 14575 } 14576 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14577 scanFlags |= SCAN_DONT_KILL_APP; 14578 } 14579 14580 // Result object to be returned 14581 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14582 14583 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14584 14585 // Sanity check 14586 if (ephemeral && (forwardLocked || onExternal)) { 14587 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14588 + " external=" + onExternal); 14589 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14590 return; 14591 } 14592 14593 // Retrieve PackageSettings and parse package 14594 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14595 | PackageParser.PARSE_ENFORCE_CODE 14596 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14597 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14598 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14599 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14600 PackageParser pp = new PackageParser(); 14601 pp.setSeparateProcesses(mSeparateProcesses); 14602 pp.setDisplayMetrics(mMetrics); 14603 14604 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14605 final PackageParser.Package pkg; 14606 try { 14607 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14608 } catch (PackageParserException e) { 14609 res.setError("Failed parse during installPackageLI", e); 14610 return; 14611 } finally { 14612 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14613 } 14614 14615 // If we are installing a clustered package add results for the children 14616 if (pkg.childPackages != null) { 14617 synchronized (mPackages) { 14618 final int childCount = pkg.childPackages.size(); 14619 for (int i = 0; i < childCount; i++) { 14620 PackageParser.Package childPkg = pkg.childPackages.get(i); 14621 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14622 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14623 childRes.pkg = childPkg; 14624 childRes.name = childPkg.packageName; 14625 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14626 if (childPs != null) { 14627 childRes.origUsers = childPs.queryInstalledUsers( 14628 sUserManager.getUserIds(), true); 14629 } 14630 if ((mPackages.containsKey(childPkg.packageName))) { 14631 childRes.removedInfo = new PackageRemovedInfo(); 14632 childRes.removedInfo.removedPackage = childPkg.packageName; 14633 } 14634 if (res.addedChildPackages == null) { 14635 res.addedChildPackages = new ArrayMap<>(); 14636 } 14637 res.addedChildPackages.put(childPkg.packageName, childRes); 14638 } 14639 } 14640 } 14641 14642 // If package doesn't declare API override, mark that we have an install 14643 // time CPU ABI override. 14644 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14645 pkg.cpuAbiOverride = args.abiOverride; 14646 } 14647 14648 String pkgName = res.name = pkg.packageName; 14649 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14650 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14651 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14652 return; 14653 } 14654 } 14655 14656 try { 14657 // either use what we've been given or parse directly from the APK 14658 if (args.certificates != null) { 14659 try { 14660 PackageParser.populateCertificates(pkg, args.certificates); 14661 } catch (PackageParserException e) { 14662 // there was something wrong with the certificates we were given; 14663 // try to pull them from the APK 14664 PackageParser.collectCertificates(pkg, parseFlags); 14665 } 14666 } else { 14667 PackageParser.collectCertificates(pkg, parseFlags); 14668 } 14669 } catch (PackageParserException e) { 14670 res.setError("Failed collect during installPackageLI", e); 14671 return; 14672 } 14673 14674 // Get rid of all references to package scan path via parser. 14675 pp = null; 14676 String oldCodePath = null; 14677 boolean systemApp = false; 14678 synchronized (mPackages) { 14679 // Check if installing already existing package 14680 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14681 String oldName = mSettings.mRenamedPackages.get(pkgName); 14682 if (pkg.mOriginalPackages != null 14683 && pkg.mOriginalPackages.contains(oldName) 14684 && mPackages.containsKey(oldName)) { 14685 // This package is derived from an original package, 14686 // and this device has been updating from that original 14687 // name. We must continue using the original name, so 14688 // rename the new package here. 14689 pkg.setPackageName(oldName); 14690 pkgName = pkg.packageName; 14691 replace = true; 14692 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14693 + oldName + " pkgName=" + pkgName); 14694 } else if (mPackages.containsKey(pkgName)) { 14695 // This package, under its official name, already exists 14696 // on the device; we should replace it. 14697 replace = true; 14698 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14699 } 14700 14701 // Child packages are installed through the parent package 14702 if (pkg.parentPackage != null) { 14703 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14704 "Package " + pkg.packageName + " is child of package " 14705 + pkg.parentPackage.parentPackage + ". Child packages " 14706 + "can be updated only through the parent package."); 14707 return; 14708 } 14709 14710 if (replace) { 14711 // Prevent apps opting out from runtime permissions 14712 PackageParser.Package oldPackage = mPackages.get(pkgName); 14713 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14714 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14715 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14716 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14717 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14718 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14719 + " doesn't support runtime permissions but the old" 14720 + " target SDK " + oldTargetSdk + " does."); 14721 return; 14722 } 14723 14724 // Prevent installing of child packages 14725 if (oldPackage.parentPackage != null) { 14726 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14727 "Package " + pkg.packageName + " is child of package " 14728 + oldPackage.parentPackage + ". Child packages " 14729 + "can be updated only through the parent package."); 14730 return; 14731 } 14732 } 14733 } 14734 14735 PackageSetting ps = mSettings.mPackages.get(pkgName); 14736 if (ps != null) { 14737 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14738 14739 // Quick sanity check that we're signed correctly if updating; 14740 // we'll check this again later when scanning, but we want to 14741 // bail early here before tripping over redefined permissions. 14742 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14743 if (!checkUpgradeKeySetLP(ps, pkg)) { 14744 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14745 + pkg.packageName + " upgrade keys do not match the " 14746 + "previously installed version"); 14747 return; 14748 } 14749 } else { 14750 try { 14751 verifySignaturesLP(ps, pkg); 14752 } catch (PackageManagerException e) { 14753 res.setError(e.error, e.getMessage()); 14754 return; 14755 } 14756 } 14757 14758 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14759 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14760 systemApp = (ps.pkg.applicationInfo.flags & 14761 ApplicationInfo.FLAG_SYSTEM) != 0; 14762 } 14763 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14764 } 14765 14766 // Check whether the newly-scanned package wants to define an already-defined perm 14767 int N = pkg.permissions.size(); 14768 for (int i = N-1; i >= 0; i--) { 14769 PackageParser.Permission perm = pkg.permissions.get(i); 14770 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14771 if (bp != null) { 14772 // If the defining package is signed with our cert, it's okay. This 14773 // also includes the "updating the same package" case, of course. 14774 // "updating same package" could also involve key-rotation. 14775 final boolean sigsOk; 14776 if (bp.sourcePackage.equals(pkg.packageName) 14777 && (bp.packageSetting instanceof PackageSetting) 14778 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14779 scanFlags))) { 14780 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14781 } else { 14782 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14783 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14784 } 14785 if (!sigsOk) { 14786 // If the owning package is the system itself, we log but allow 14787 // install to proceed; we fail the install on all other permission 14788 // redefinitions. 14789 if (!bp.sourcePackage.equals("android")) { 14790 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14791 + pkg.packageName + " attempting to redeclare permission " 14792 + perm.info.name + " already owned by " + bp.sourcePackage); 14793 res.origPermission = perm.info.name; 14794 res.origPackage = bp.sourcePackage; 14795 return; 14796 } else { 14797 Slog.w(TAG, "Package " + pkg.packageName 14798 + " attempting to redeclare system permission " 14799 + perm.info.name + "; ignoring new declaration"); 14800 pkg.permissions.remove(i); 14801 } 14802 } 14803 } 14804 } 14805 } 14806 14807 if (systemApp) { 14808 if (onExternal) { 14809 // Abort update; system app can't be replaced with app on sdcard 14810 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14811 "Cannot install updates to system apps on sdcard"); 14812 return; 14813 } else if (ephemeral) { 14814 // Abort update; system app can't be replaced with an ephemeral app 14815 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14816 "Cannot update a system app with an ephemeral app"); 14817 return; 14818 } 14819 } 14820 14821 if (args.move != null) { 14822 // We did an in-place move, so dex is ready to roll 14823 scanFlags |= SCAN_NO_DEX; 14824 scanFlags |= SCAN_MOVE; 14825 14826 synchronized (mPackages) { 14827 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14828 if (ps == null) { 14829 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14830 "Missing settings for moved package " + pkgName); 14831 } 14832 14833 // We moved the entire application as-is, so bring over the 14834 // previously derived ABI information. 14835 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14836 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14837 } 14838 14839 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14840 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14841 scanFlags |= SCAN_NO_DEX; 14842 14843 try { 14844 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14845 args.abiOverride : pkg.cpuAbiOverride); 14846 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14847 true /* extract libs */); 14848 } catch (PackageManagerException pme) { 14849 Slog.e(TAG, "Error deriving application ABI", pme); 14850 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14851 return; 14852 } 14853 14854 // Shared libraries for the package need to be updated. 14855 synchronized (mPackages) { 14856 try { 14857 updateSharedLibrariesLPw(pkg, null); 14858 } catch (PackageManagerException e) { 14859 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14860 } 14861 } 14862 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14863 // Do not run PackageDexOptimizer through the local performDexOpt 14864 // method because `pkg` is not in `mPackages` yet. 14865 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14866 null /* instructionSets */, false /* checkProfiles */, 14867 getCompilerFilterForReason(REASON_INSTALL)); 14868 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14869 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14870 String msg = "Extracting package failed for " + pkgName; 14871 res.setError(INSTALL_FAILED_DEXOPT, msg); 14872 return; 14873 } 14874 14875 // Notify BackgroundDexOptService that the package has been changed. 14876 // If this is an update of a package which used to fail to compile, 14877 // BDOS will remove it from its blacklist. 14878 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14879 } 14880 14881 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14882 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14883 return; 14884 } 14885 14886 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14887 14888 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14889 "installPackageLI")) { 14890 if (replace) { 14891 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14892 installerPackageName, res); 14893 } else { 14894 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14895 args.user, installerPackageName, volumeUuid, res); 14896 } 14897 } 14898 synchronized (mPackages) { 14899 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14900 if (ps != null) { 14901 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14902 } 14903 14904 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14905 for (int i = 0; i < childCount; i++) { 14906 PackageParser.Package childPkg = pkg.childPackages.get(i); 14907 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14908 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14909 if (childPs != null) { 14910 childRes.newUsers = childPs.queryInstalledUsers( 14911 sUserManager.getUserIds(), true); 14912 } 14913 } 14914 } 14915 } 14916 14917 private void startIntentFilterVerifications(int userId, boolean replacing, 14918 PackageParser.Package pkg) { 14919 if (mIntentFilterVerifierComponent == null) { 14920 Slog.w(TAG, "No IntentFilter verification will not be done as " 14921 + "there is no IntentFilterVerifier available!"); 14922 return; 14923 } 14924 14925 final int verifierUid = getPackageUid( 14926 mIntentFilterVerifierComponent.getPackageName(), 14927 MATCH_DEBUG_TRIAGED_MISSING, 14928 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14929 14930 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14931 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14932 mHandler.sendMessage(msg); 14933 14934 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14935 for (int i = 0; i < childCount; i++) { 14936 PackageParser.Package childPkg = pkg.childPackages.get(i); 14937 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14938 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14939 mHandler.sendMessage(msg); 14940 } 14941 } 14942 14943 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14944 PackageParser.Package pkg) { 14945 int size = pkg.activities.size(); 14946 if (size == 0) { 14947 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14948 "No activity, so no need to verify any IntentFilter!"); 14949 return; 14950 } 14951 14952 final boolean hasDomainURLs = hasDomainURLs(pkg); 14953 if (!hasDomainURLs) { 14954 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14955 "No domain URLs, so no need to verify any IntentFilter!"); 14956 return; 14957 } 14958 14959 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14960 + " if any IntentFilter from the " + size 14961 + " Activities needs verification ..."); 14962 14963 int count = 0; 14964 final String packageName = pkg.packageName; 14965 14966 synchronized (mPackages) { 14967 // If this is a new install and we see that we've already run verification for this 14968 // package, we have nothing to do: it means the state was restored from backup. 14969 if (!replacing) { 14970 IntentFilterVerificationInfo ivi = 14971 mSettings.getIntentFilterVerificationLPr(packageName); 14972 if (ivi != null) { 14973 if (DEBUG_DOMAIN_VERIFICATION) { 14974 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14975 + ivi.getStatusString()); 14976 } 14977 return; 14978 } 14979 } 14980 14981 // If any filters need to be verified, then all need to be. 14982 boolean needToVerify = false; 14983 for (PackageParser.Activity a : pkg.activities) { 14984 for (ActivityIntentInfo filter : a.intents) { 14985 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14986 if (DEBUG_DOMAIN_VERIFICATION) { 14987 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14988 } 14989 needToVerify = true; 14990 break; 14991 } 14992 } 14993 } 14994 14995 if (needToVerify) { 14996 final int verificationId = mIntentFilterVerificationToken++; 14997 for (PackageParser.Activity a : pkg.activities) { 14998 for (ActivityIntentInfo filter : a.intents) { 14999 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 15000 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15001 "Verification needed for IntentFilter:" + filter.toString()); 15002 mIntentFilterVerifier.addOneIntentFilterVerification( 15003 verifierUid, userId, verificationId, filter, packageName); 15004 count++; 15005 } 15006 } 15007 } 15008 } 15009 } 15010 15011 if (count > 0) { 15012 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15013 + " IntentFilter verification" + (count > 1 ? "s" : "") 15014 + " for userId:" + userId); 15015 mIntentFilterVerifier.startVerifications(userId); 15016 } else { 15017 if (DEBUG_DOMAIN_VERIFICATION) { 15018 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15019 } 15020 } 15021 } 15022 15023 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15024 final ComponentName cn = filter.activity.getComponentName(); 15025 final String packageName = cn.getPackageName(); 15026 15027 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15028 packageName); 15029 if (ivi == null) { 15030 return true; 15031 } 15032 int status = ivi.getStatus(); 15033 switch (status) { 15034 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15035 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15036 return true; 15037 15038 default: 15039 // Nothing to do 15040 return false; 15041 } 15042 } 15043 15044 private static boolean isMultiArch(ApplicationInfo info) { 15045 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15046 } 15047 15048 private static boolean isExternal(PackageParser.Package pkg) { 15049 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15050 } 15051 15052 private static boolean isExternal(PackageSetting ps) { 15053 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15054 } 15055 15056 private static boolean isEphemeral(PackageParser.Package pkg) { 15057 return pkg.applicationInfo.isEphemeralApp(); 15058 } 15059 15060 private static boolean isEphemeral(PackageSetting ps) { 15061 return ps.pkg != null && isEphemeral(ps.pkg); 15062 } 15063 15064 private static boolean isSystemApp(PackageParser.Package pkg) { 15065 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15066 } 15067 15068 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15069 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15070 } 15071 15072 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15073 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15074 } 15075 15076 private static boolean isSystemApp(PackageSetting ps) { 15077 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15078 } 15079 15080 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15081 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15082 } 15083 15084 private int packageFlagsToInstallFlags(PackageSetting ps) { 15085 int installFlags = 0; 15086 if (isEphemeral(ps)) { 15087 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15088 } 15089 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15090 // This existing package was an external ASEC install when we have 15091 // the external flag without a UUID 15092 installFlags |= PackageManager.INSTALL_EXTERNAL; 15093 } 15094 if (ps.isForwardLocked()) { 15095 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15096 } 15097 return installFlags; 15098 } 15099 15100 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15101 if (isExternal(pkg)) { 15102 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15103 return StorageManager.UUID_PRIMARY_PHYSICAL; 15104 } else { 15105 return pkg.volumeUuid; 15106 } 15107 } else { 15108 return StorageManager.UUID_PRIVATE_INTERNAL; 15109 } 15110 } 15111 15112 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15113 if (isExternal(pkg)) { 15114 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15115 return mSettings.getExternalVersion(); 15116 } else { 15117 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15118 } 15119 } else { 15120 return mSettings.getInternalVersion(); 15121 } 15122 } 15123 15124 private void deleteTempPackageFiles() { 15125 final FilenameFilter filter = new FilenameFilter() { 15126 public boolean accept(File dir, String name) { 15127 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15128 } 15129 }; 15130 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15131 file.delete(); 15132 } 15133 } 15134 15135 @Override 15136 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15137 int flags) { 15138 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15139 flags); 15140 } 15141 15142 @Override 15143 public void deletePackage(final String packageName, 15144 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15145 mContext.enforceCallingOrSelfPermission( 15146 android.Manifest.permission.DELETE_PACKAGES, null); 15147 Preconditions.checkNotNull(packageName); 15148 Preconditions.checkNotNull(observer); 15149 final int uid = Binder.getCallingUid(); 15150 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15151 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15152 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15153 mContext.enforceCallingOrSelfPermission( 15154 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15155 "deletePackage for user " + userId); 15156 } 15157 15158 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15159 try { 15160 observer.onPackageDeleted(packageName, 15161 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15162 } catch (RemoteException re) { 15163 } 15164 return; 15165 } 15166 15167 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15168 try { 15169 observer.onPackageDeleted(packageName, 15170 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15171 } catch (RemoteException re) { 15172 } 15173 return; 15174 } 15175 15176 if (DEBUG_REMOVE) { 15177 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15178 + " deleteAllUsers: " + deleteAllUsers ); 15179 } 15180 // Queue up an async operation since the package deletion may take a little while. 15181 mHandler.post(new Runnable() { 15182 public void run() { 15183 mHandler.removeCallbacks(this); 15184 int returnCode; 15185 if (!deleteAllUsers) { 15186 returnCode = deletePackageX(packageName, userId, deleteFlags); 15187 } else { 15188 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15189 // If nobody is blocking uninstall, proceed with delete for all users 15190 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15191 returnCode = deletePackageX(packageName, userId, deleteFlags); 15192 } else { 15193 // Otherwise uninstall individually for users with blockUninstalls=false 15194 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15195 for (int userId : users) { 15196 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15197 returnCode = deletePackageX(packageName, userId, userFlags); 15198 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15199 Slog.w(TAG, "Package delete failed for user " + userId 15200 + ", returnCode " + returnCode); 15201 } 15202 } 15203 } 15204 // The app has only been marked uninstalled for certain users. 15205 // We still need to report that delete was blocked 15206 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15207 } 15208 } 15209 try { 15210 observer.onPackageDeleted(packageName, returnCode, null); 15211 } catch (RemoteException e) { 15212 Log.i(TAG, "Observer no longer exists."); 15213 } //end catch 15214 } //end run 15215 }); 15216 } 15217 15218 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15219 int[] result = EMPTY_INT_ARRAY; 15220 for (int userId : userIds) { 15221 if (getBlockUninstallForUser(packageName, userId)) { 15222 result = ArrayUtils.appendInt(result, userId); 15223 } 15224 } 15225 return result; 15226 } 15227 15228 @Override 15229 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15230 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15231 } 15232 15233 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15234 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15235 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15236 try { 15237 if (dpm != null) { 15238 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15239 /* callingUserOnly =*/ false); 15240 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15241 : deviceOwnerComponentName.getPackageName(); 15242 // Does the package contains the device owner? 15243 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15244 // this check is probably not needed, since DO should be registered as a device 15245 // admin on some user too. (Original bug for this: b/17657954) 15246 if (packageName.equals(deviceOwnerPackageName)) { 15247 return true; 15248 } 15249 // Does it contain a device admin for any user? 15250 int[] users; 15251 if (userId == UserHandle.USER_ALL) { 15252 users = sUserManager.getUserIds(); 15253 } else { 15254 users = new int[]{userId}; 15255 } 15256 for (int i = 0; i < users.length; ++i) { 15257 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15258 return true; 15259 } 15260 } 15261 } 15262 } catch (RemoteException e) { 15263 } 15264 return false; 15265 } 15266 15267 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15268 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15269 } 15270 15271 /** 15272 * This method is an internal method that could be get invoked either 15273 * to delete an installed package or to clean up a failed installation. 15274 * After deleting an installed package, a broadcast is sent to notify any 15275 * listeners that the package has been removed. For cleaning up a failed 15276 * installation, the broadcast is not necessary since the package's 15277 * installation wouldn't have sent the initial broadcast either 15278 * The key steps in deleting a package are 15279 * deleting the package information in internal structures like mPackages, 15280 * deleting the packages base directories through installd 15281 * updating mSettings to reflect current status 15282 * persisting settings for later use 15283 * sending a broadcast if necessary 15284 */ 15285 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15286 final PackageRemovedInfo info = new PackageRemovedInfo(); 15287 final boolean res; 15288 15289 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15290 ? UserHandle.ALL : new UserHandle(userId); 15291 15292 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15293 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15294 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15295 } 15296 15297 PackageSetting uninstalledPs = null; 15298 15299 // for the uninstall-updates case and restricted profiles, remember the per- 15300 // user handle installed state 15301 int[] allUsers; 15302 synchronized (mPackages) { 15303 uninstalledPs = mSettings.mPackages.get(packageName); 15304 if (uninstalledPs == null) { 15305 Slog.w(TAG, "Not removing non-existent package " + packageName); 15306 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15307 } 15308 allUsers = sUserManager.getUserIds(); 15309 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15310 } 15311 15312 synchronized (mInstallLock) { 15313 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15314 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15315 "deletePackageX")) { 15316 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15317 deleteFlags | REMOVE_CHATTY, info, true, null); 15318 } 15319 synchronized (mPackages) { 15320 if (res) { 15321 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15322 } 15323 } 15324 } 15325 15326 if (res) { 15327 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15328 info.sendPackageRemovedBroadcasts(killApp); 15329 info.sendSystemPackageUpdatedBroadcasts(); 15330 info.sendSystemPackageAppearedBroadcasts(); 15331 } 15332 // Force a gc here. 15333 Runtime.getRuntime().gc(); 15334 // Delete the resources here after sending the broadcast to let 15335 // other processes clean up before deleting resources. 15336 if (info.args != null) { 15337 synchronized (mInstallLock) { 15338 info.args.doPostDeleteLI(true); 15339 } 15340 } 15341 15342 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15343 } 15344 15345 class PackageRemovedInfo { 15346 String removedPackage; 15347 int uid = -1; 15348 int removedAppId = -1; 15349 int[] origUsers; 15350 int[] removedUsers = null; 15351 boolean isRemovedPackageSystemUpdate = false; 15352 boolean isUpdate; 15353 boolean dataRemoved; 15354 boolean removedForAllUsers; 15355 // Clean up resources deleted packages. 15356 InstallArgs args = null; 15357 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15358 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15359 15360 void sendPackageRemovedBroadcasts(boolean killApp) { 15361 sendPackageRemovedBroadcastInternal(killApp); 15362 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15363 for (int i = 0; i < childCount; i++) { 15364 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15365 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15366 } 15367 } 15368 15369 void sendSystemPackageUpdatedBroadcasts() { 15370 if (isRemovedPackageSystemUpdate) { 15371 sendSystemPackageUpdatedBroadcastsInternal(); 15372 final int childCount = (removedChildPackages != null) 15373 ? removedChildPackages.size() : 0; 15374 for (int i = 0; i < childCount; i++) { 15375 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15376 if (childInfo.isRemovedPackageSystemUpdate) { 15377 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15378 } 15379 } 15380 } 15381 } 15382 15383 void sendSystemPackageAppearedBroadcasts() { 15384 final int packageCount = (appearedChildPackages != null) 15385 ? appearedChildPackages.size() : 0; 15386 for (int i = 0; i < packageCount; i++) { 15387 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15388 for (int userId : installedInfo.newUsers) { 15389 sendPackageAddedForUser(installedInfo.name, true, 15390 UserHandle.getAppId(installedInfo.uid), userId); 15391 } 15392 } 15393 } 15394 15395 private void sendSystemPackageUpdatedBroadcastsInternal() { 15396 Bundle extras = new Bundle(2); 15397 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15398 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15399 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15400 extras, 0, null, null, null); 15401 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15402 extras, 0, null, null, null); 15403 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15404 null, 0, removedPackage, null, null); 15405 } 15406 15407 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15408 Bundle extras = new Bundle(2); 15409 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15410 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15411 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15412 if (isUpdate || isRemovedPackageSystemUpdate) { 15413 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15414 } 15415 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15416 if (removedPackage != null) { 15417 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15418 extras, 0, null, null, removedUsers); 15419 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15420 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15421 removedPackage, extras, 0, null, null, removedUsers); 15422 } 15423 } 15424 if (removedAppId >= 0) { 15425 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15426 removedUsers); 15427 } 15428 } 15429 } 15430 15431 /* 15432 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15433 * flag is not set, the data directory is removed as well. 15434 * make sure this flag is set for partially installed apps. If not its meaningless to 15435 * delete a partially installed application. 15436 */ 15437 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15438 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15439 String packageName = ps.name; 15440 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15441 // Retrieve object to delete permissions for shared user later on 15442 final PackageParser.Package deletedPkg; 15443 final PackageSetting deletedPs; 15444 // reader 15445 synchronized (mPackages) { 15446 deletedPkg = mPackages.get(packageName); 15447 deletedPs = mSettings.mPackages.get(packageName); 15448 if (outInfo != null) { 15449 outInfo.removedPackage = packageName; 15450 outInfo.removedUsers = deletedPs != null 15451 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15452 : null; 15453 } 15454 } 15455 15456 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15457 15458 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15459 final PackageParser.Package resolvedPkg; 15460 if (deletedPkg != null) { 15461 resolvedPkg = deletedPkg; 15462 } else { 15463 // We don't have a parsed package when it lives on an ejected 15464 // adopted storage device, so fake something together 15465 resolvedPkg = new PackageParser.Package(ps.name); 15466 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15467 } 15468 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15469 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15470 destroyAppProfilesLIF(resolvedPkg); 15471 if (outInfo != null) { 15472 outInfo.dataRemoved = true; 15473 } 15474 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15475 } 15476 15477 // writer 15478 synchronized (mPackages) { 15479 if (deletedPs != null) { 15480 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15481 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15482 clearDefaultBrowserIfNeeded(packageName); 15483 if (outInfo != null) { 15484 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15485 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15486 } 15487 updatePermissionsLPw(deletedPs.name, null, 0); 15488 if (deletedPs.sharedUser != null) { 15489 // Remove permissions associated with package. Since runtime 15490 // permissions are per user we have to kill the removed package 15491 // or packages running under the shared user of the removed 15492 // package if revoking the permissions requested only by the removed 15493 // package is successful and this causes a change in gids. 15494 for (int userId : UserManagerService.getInstance().getUserIds()) { 15495 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15496 userId); 15497 if (userIdToKill == UserHandle.USER_ALL 15498 || userIdToKill >= UserHandle.USER_SYSTEM) { 15499 // If gids changed for this user, kill all affected packages. 15500 mHandler.post(new Runnable() { 15501 @Override 15502 public void run() { 15503 // This has to happen with no lock held. 15504 killApplication(deletedPs.name, deletedPs.appId, 15505 KILL_APP_REASON_GIDS_CHANGED); 15506 } 15507 }); 15508 break; 15509 } 15510 } 15511 } 15512 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15513 } 15514 // make sure to preserve per-user disabled state if this removal was just 15515 // a downgrade of a system app to the factory package 15516 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15517 if (DEBUG_REMOVE) { 15518 Slog.d(TAG, "Propagating install state across downgrade"); 15519 } 15520 for (int userId : allUserHandles) { 15521 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15522 if (DEBUG_REMOVE) { 15523 Slog.d(TAG, " user " + userId + " => " + installed); 15524 } 15525 ps.setInstalled(installed, userId); 15526 } 15527 } 15528 } 15529 // can downgrade to reader 15530 if (writeSettings) { 15531 // Save settings now 15532 mSettings.writeLPr(); 15533 } 15534 } 15535 if (outInfo != null) { 15536 // A user ID was deleted here. Go through all users and remove it 15537 // from KeyStore. 15538 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15539 } 15540 } 15541 15542 static boolean locationIsPrivileged(File path) { 15543 try { 15544 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15545 .getCanonicalPath(); 15546 return path.getCanonicalPath().startsWith(privilegedAppDir); 15547 } catch (IOException e) { 15548 Slog.e(TAG, "Unable to access code path " + path); 15549 } 15550 return false; 15551 } 15552 15553 /* 15554 * Tries to delete system package. 15555 */ 15556 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15557 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15558 boolean writeSettings) { 15559 if (deletedPs.parentPackageName != null) { 15560 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15561 return false; 15562 } 15563 15564 final boolean applyUserRestrictions 15565 = (allUserHandles != null) && (outInfo.origUsers != null); 15566 final PackageSetting disabledPs; 15567 // Confirm if the system package has been updated 15568 // An updated system app can be deleted. This will also have to restore 15569 // the system pkg from system partition 15570 // reader 15571 synchronized (mPackages) { 15572 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15573 } 15574 15575 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15576 + " disabledPs=" + disabledPs); 15577 15578 if (disabledPs == null) { 15579 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15580 return false; 15581 } else if (DEBUG_REMOVE) { 15582 Slog.d(TAG, "Deleting system pkg from data partition"); 15583 } 15584 15585 if (DEBUG_REMOVE) { 15586 if (applyUserRestrictions) { 15587 Slog.d(TAG, "Remembering install states:"); 15588 for (int userId : allUserHandles) { 15589 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15590 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15591 } 15592 } 15593 } 15594 15595 // Delete the updated package 15596 outInfo.isRemovedPackageSystemUpdate = true; 15597 if (outInfo.removedChildPackages != null) { 15598 final int childCount = (deletedPs.childPackageNames != null) 15599 ? deletedPs.childPackageNames.size() : 0; 15600 for (int i = 0; i < childCount; i++) { 15601 String childPackageName = deletedPs.childPackageNames.get(i); 15602 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15603 .contains(childPackageName)) { 15604 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15605 childPackageName); 15606 if (childInfo != null) { 15607 childInfo.isRemovedPackageSystemUpdate = true; 15608 } 15609 } 15610 } 15611 } 15612 15613 if (disabledPs.versionCode < deletedPs.versionCode) { 15614 // Delete data for downgrades 15615 flags &= ~PackageManager.DELETE_KEEP_DATA; 15616 } else { 15617 // Preserve data by setting flag 15618 flags |= PackageManager.DELETE_KEEP_DATA; 15619 } 15620 15621 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15622 outInfo, writeSettings, disabledPs.pkg); 15623 if (!ret) { 15624 return false; 15625 } 15626 15627 // writer 15628 synchronized (mPackages) { 15629 // Reinstate the old system package 15630 enableSystemPackageLPw(disabledPs.pkg); 15631 // Remove any native libraries from the upgraded package. 15632 removeNativeBinariesLI(deletedPs); 15633 } 15634 15635 // Install the system package 15636 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15637 int parseFlags = mDefParseFlags 15638 | PackageParser.PARSE_MUST_BE_APK 15639 | PackageParser.PARSE_IS_SYSTEM 15640 | PackageParser.PARSE_IS_SYSTEM_DIR; 15641 if (locationIsPrivileged(disabledPs.codePath)) { 15642 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15643 } 15644 15645 final PackageParser.Package newPkg; 15646 try { 15647 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15648 } catch (PackageManagerException e) { 15649 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15650 + e.getMessage()); 15651 return false; 15652 } 15653 15654 prepareAppDataAfterInstallLIF(newPkg); 15655 15656 // writer 15657 synchronized (mPackages) { 15658 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15659 15660 // Propagate the permissions state as we do not want to drop on the floor 15661 // runtime permissions. The update permissions method below will take 15662 // care of removing obsolete permissions and grant install permissions. 15663 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15664 updatePermissionsLPw(newPkg.packageName, newPkg, 15665 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15666 15667 if (applyUserRestrictions) { 15668 if (DEBUG_REMOVE) { 15669 Slog.d(TAG, "Propagating install state across reinstall"); 15670 } 15671 for (int userId : allUserHandles) { 15672 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15673 if (DEBUG_REMOVE) { 15674 Slog.d(TAG, " user " + userId + " => " + installed); 15675 } 15676 ps.setInstalled(installed, userId); 15677 15678 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15679 } 15680 // Regardless of writeSettings we need to ensure that this restriction 15681 // state propagation is persisted 15682 mSettings.writeAllUsersPackageRestrictionsLPr(); 15683 } 15684 // can downgrade to reader here 15685 if (writeSettings) { 15686 mSettings.writeLPr(); 15687 } 15688 } 15689 return true; 15690 } 15691 15692 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15693 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15694 PackageRemovedInfo outInfo, boolean writeSettings, 15695 PackageParser.Package replacingPackage) { 15696 synchronized (mPackages) { 15697 if (outInfo != null) { 15698 outInfo.uid = ps.appId; 15699 } 15700 15701 if (outInfo != null && outInfo.removedChildPackages != null) { 15702 final int childCount = (ps.childPackageNames != null) 15703 ? ps.childPackageNames.size() : 0; 15704 for (int i = 0; i < childCount; i++) { 15705 String childPackageName = ps.childPackageNames.get(i); 15706 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15707 if (childPs == null) { 15708 return false; 15709 } 15710 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15711 childPackageName); 15712 if (childInfo != null) { 15713 childInfo.uid = childPs.appId; 15714 } 15715 } 15716 } 15717 } 15718 15719 // Delete package data from internal structures and also remove data if flag is set 15720 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15721 15722 // Delete the child packages data 15723 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15724 for (int i = 0; i < childCount; i++) { 15725 PackageSetting childPs; 15726 synchronized (mPackages) { 15727 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15728 } 15729 if (childPs != null) { 15730 PackageRemovedInfo childOutInfo = (outInfo != null 15731 && outInfo.removedChildPackages != null) 15732 ? outInfo.removedChildPackages.get(childPs.name) : null; 15733 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15734 && (replacingPackage != null 15735 && !replacingPackage.hasChildPackage(childPs.name)) 15736 ? flags & ~DELETE_KEEP_DATA : flags; 15737 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15738 deleteFlags, writeSettings); 15739 } 15740 } 15741 15742 // Delete application code and resources only for parent packages 15743 if (ps.parentPackageName == null) { 15744 if (deleteCodeAndResources && (outInfo != null)) { 15745 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15746 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15747 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15748 } 15749 } 15750 15751 return true; 15752 } 15753 15754 @Override 15755 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15756 int userId) { 15757 mContext.enforceCallingOrSelfPermission( 15758 android.Manifest.permission.DELETE_PACKAGES, null); 15759 synchronized (mPackages) { 15760 PackageSetting ps = mSettings.mPackages.get(packageName); 15761 if (ps == null) { 15762 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15763 return false; 15764 } 15765 if (!ps.getInstalled(userId)) { 15766 // Can't block uninstall for an app that is not installed or enabled. 15767 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15768 return false; 15769 } 15770 ps.setBlockUninstall(blockUninstall, userId); 15771 mSettings.writePackageRestrictionsLPr(userId); 15772 } 15773 return true; 15774 } 15775 15776 @Override 15777 public boolean getBlockUninstallForUser(String packageName, int userId) { 15778 synchronized (mPackages) { 15779 PackageSetting ps = mSettings.mPackages.get(packageName); 15780 if (ps == null) { 15781 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15782 return false; 15783 } 15784 return ps.getBlockUninstall(userId); 15785 } 15786 } 15787 15788 @Override 15789 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15790 int callingUid = Binder.getCallingUid(); 15791 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15792 throw new SecurityException( 15793 "setRequiredForSystemUser can only be run by the system or root"); 15794 } 15795 synchronized (mPackages) { 15796 PackageSetting ps = mSettings.mPackages.get(packageName); 15797 if (ps == null) { 15798 Log.w(TAG, "Package doesn't exist: " + packageName); 15799 return false; 15800 } 15801 if (systemUserApp) { 15802 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15803 } else { 15804 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15805 } 15806 mSettings.writeLPr(); 15807 } 15808 return true; 15809 } 15810 15811 /* 15812 * This method handles package deletion in general 15813 */ 15814 private boolean deletePackageLIF(String packageName, UserHandle user, 15815 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15816 PackageRemovedInfo outInfo, boolean writeSettings, 15817 PackageParser.Package replacingPackage) { 15818 if (packageName == null) { 15819 Slog.w(TAG, "Attempt to delete null packageName."); 15820 return false; 15821 } 15822 15823 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15824 15825 PackageSetting ps; 15826 15827 synchronized (mPackages) { 15828 ps = mSettings.mPackages.get(packageName); 15829 if (ps == null) { 15830 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15831 return false; 15832 } 15833 15834 if (ps.parentPackageName != null && (!isSystemApp(ps) 15835 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15836 if (DEBUG_REMOVE) { 15837 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15838 + ((user == null) ? UserHandle.USER_ALL : user)); 15839 } 15840 final int removedUserId = (user != null) ? user.getIdentifier() 15841 : UserHandle.USER_ALL; 15842 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15843 return false; 15844 } 15845 markPackageUninstalledForUserLPw(ps, user); 15846 scheduleWritePackageRestrictionsLocked(user); 15847 return true; 15848 } 15849 } 15850 15851 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15852 && user.getIdentifier() != UserHandle.USER_ALL)) { 15853 // The caller is asking that the package only be deleted for a single 15854 // user. To do this, we just mark its uninstalled state and delete 15855 // its data. If this is a system app, we only allow this to happen if 15856 // they have set the special DELETE_SYSTEM_APP which requests different 15857 // semantics than normal for uninstalling system apps. 15858 markPackageUninstalledForUserLPw(ps, user); 15859 15860 if (!isSystemApp(ps)) { 15861 // Do not uninstall the APK if an app should be cached 15862 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15863 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15864 // Other user still have this package installed, so all 15865 // we need to do is clear this user's data and save that 15866 // it is uninstalled. 15867 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15868 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15869 return false; 15870 } 15871 scheduleWritePackageRestrictionsLocked(user); 15872 return true; 15873 } else { 15874 // We need to set it back to 'installed' so the uninstall 15875 // broadcasts will be sent correctly. 15876 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15877 ps.setInstalled(true, user.getIdentifier()); 15878 } 15879 } else { 15880 // This is a system app, so we assume that the 15881 // other users still have this package installed, so all 15882 // we need to do is clear this user's data and save that 15883 // it is uninstalled. 15884 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15885 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15886 return false; 15887 } 15888 scheduleWritePackageRestrictionsLocked(user); 15889 return true; 15890 } 15891 } 15892 15893 // If we are deleting a composite package for all users, keep track 15894 // of result for each child. 15895 if (ps.childPackageNames != null && outInfo != null) { 15896 synchronized (mPackages) { 15897 final int childCount = ps.childPackageNames.size(); 15898 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15899 for (int i = 0; i < childCount; i++) { 15900 String childPackageName = ps.childPackageNames.get(i); 15901 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15902 childInfo.removedPackage = childPackageName; 15903 outInfo.removedChildPackages.put(childPackageName, childInfo); 15904 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15905 if (childPs != null) { 15906 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15907 } 15908 } 15909 } 15910 } 15911 15912 boolean ret = false; 15913 if (isSystemApp(ps)) { 15914 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15915 // When an updated system application is deleted we delete the existing resources 15916 // as well and fall back to existing code in system partition 15917 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15918 } else { 15919 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15920 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15921 outInfo, writeSettings, replacingPackage); 15922 } 15923 15924 // Take a note whether we deleted the package for all users 15925 if (outInfo != null) { 15926 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15927 if (outInfo.removedChildPackages != null) { 15928 synchronized (mPackages) { 15929 final int childCount = outInfo.removedChildPackages.size(); 15930 for (int i = 0; i < childCount; i++) { 15931 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15932 if (childInfo != null) { 15933 childInfo.removedForAllUsers = mPackages.get( 15934 childInfo.removedPackage) == null; 15935 } 15936 } 15937 } 15938 } 15939 // If we uninstalled an update to a system app there may be some 15940 // child packages that appeared as they are declared in the system 15941 // app but were not declared in the update. 15942 if (isSystemApp(ps)) { 15943 synchronized (mPackages) { 15944 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15945 final int childCount = (updatedPs.childPackageNames != null) 15946 ? updatedPs.childPackageNames.size() : 0; 15947 for (int i = 0; i < childCount; i++) { 15948 String childPackageName = updatedPs.childPackageNames.get(i); 15949 if (outInfo.removedChildPackages == null 15950 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15951 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15952 if (childPs == null) { 15953 continue; 15954 } 15955 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15956 installRes.name = childPackageName; 15957 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15958 installRes.pkg = mPackages.get(childPackageName); 15959 installRes.uid = childPs.pkg.applicationInfo.uid; 15960 if (outInfo.appearedChildPackages == null) { 15961 outInfo.appearedChildPackages = new ArrayMap<>(); 15962 } 15963 outInfo.appearedChildPackages.put(childPackageName, installRes); 15964 } 15965 } 15966 } 15967 } 15968 } 15969 15970 return ret; 15971 } 15972 15973 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15974 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15975 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15976 for (int nextUserId : userIds) { 15977 if (DEBUG_REMOVE) { 15978 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15979 } 15980 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15981 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15982 false /*hidden*/, false /*suspended*/, null, null, null, 15983 false /*blockUninstall*/, 15984 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15985 } 15986 } 15987 15988 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15989 PackageRemovedInfo outInfo) { 15990 final PackageParser.Package pkg; 15991 synchronized (mPackages) { 15992 pkg = mPackages.get(ps.name); 15993 } 15994 15995 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15996 : new int[] {userId}; 15997 for (int nextUserId : userIds) { 15998 if (DEBUG_REMOVE) { 15999 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 16000 + nextUserId); 16001 } 16002 16003 destroyAppDataLIF(pkg, userId, 16004 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16005 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16006 schedulePackageCleaning(ps.name, nextUserId, false); 16007 synchronized (mPackages) { 16008 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16009 scheduleWritePackageRestrictionsLocked(nextUserId); 16010 } 16011 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16012 } 16013 } 16014 16015 if (outInfo != null) { 16016 outInfo.removedPackage = ps.name; 16017 outInfo.removedAppId = ps.appId; 16018 outInfo.removedUsers = userIds; 16019 } 16020 16021 return true; 16022 } 16023 16024 private final class ClearStorageConnection implements ServiceConnection { 16025 IMediaContainerService mContainerService; 16026 16027 @Override 16028 public void onServiceConnected(ComponentName name, IBinder service) { 16029 synchronized (this) { 16030 mContainerService = IMediaContainerService.Stub.asInterface(service); 16031 notifyAll(); 16032 } 16033 } 16034 16035 @Override 16036 public void onServiceDisconnected(ComponentName name) { 16037 } 16038 } 16039 16040 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16041 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16042 16043 final boolean mounted; 16044 if (Environment.isExternalStorageEmulated()) { 16045 mounted = true; 16046 } else { 16047 final String status = Environment.getExternalStorageState(); 16048 16049 mounted = status.equals(Environment.MEDIA_MOUNTED) 16050 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16051 } 16052 16053 if (!mounted) { 16054 return; 16055 } 16056 16057 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16058 int[] users; 16059 if (userId == UserHandle.USER_ALL) { 16060 users = sUserManager.getUserIds(); 16061 } else { 16062 users = new int[] { userId }; 16063 } 16064 final ClearStorageConnection conn = new ClearStorageConnection(); 16065 if (mContext.bindServiceAsUser( 16066 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16067 try { 16068 for (int curUser : users) { 16069 long timeout = SystemClock.uptimeMillis() + 5000; 16070 synchronized (conn) { 16071 long now = SystemClock.uptimeMillis(); 16072 while (conn.mContainerService == null && now < timeout) { 16073 try { 16074 conn.wait(timeout - now); 16075 } catch (InterruptedException e) { 16076 } 16077 } 16078 } 16079 if (conn.mContainerService == null) { 16080 return; 16081 } 16082 16083 final UserEnvironment userEnv = new UserEnvironment(curUser); 16084 clearDirectory(conn.mContainerService, 16085 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16086 if (allData) { 16087 clearDirectory(conn.mContainerService, 16088 userEnv.buildExternalStorageAppDataDirs(packageName)); 16089 clearDirectory(conn.mContainerService, 16090 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16091 } 16092 } 16093 } finally { 16094 mContext.unbindService(conn); 16095 } 16096 } 16097 } 16098 16099 @Override 16100 public void clearApplicationProfileData(String packageName) { 16101 enforceSystemOrRoot("Only the system can clear all profile data"); 16102 16103 final PackageParser.Package pkg; 16104 synchronized (mPackages) { 16105 pkg = mPackages.get(packageName); 16106 } 16107 16108 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16109 synchronized (mInstallLock) { 16110 clearAppProfilesLIF(pkg); 16111 } 16112 } 16113 } 16114 16115 @Override 16116 public void clearApplicationUserData(final String packageName, 16117 final IPackageDataObserver observer, final int userId) { 16118 mContext.enforceCallingOrSelfPermission( 16119 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16120 16121 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16122 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16123 16124 final DevicePolicyManagerInternal dpmi = LocalServices 16125 .getService(DevicePolicyManagerInternal.class); 16126 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16127 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16128 } 16129 // Queue up an async operation since the package deletion may take a little while. 16130 mHandler.post(new Runnable() { 16131 public void run() { 16132 mHandler.removeCallbacks(this); 16133 final boolean succeeded; 16134 try (PackageFreezer freezer = freezePackage(packageName, 16135 "clearApplicationUserData")) { 16136 synchronized (mInstallLock) { 16137 succeeded = clearApplicationUserDataLIF(packageName, userId); 16138 } 16139 clearExternalStorageDataSync(packageName, userId, true); 16140 } 16141 if (succeeded) { 16142 // invoke DeviceStorageMonitor's update method to clear any notifications 16143 DeviceStorageMonitorInternal dsm = LocalServices 16144 .getService(DeviceStorageMonitorInternal.class); 16145 if (dsm != null) { 16146 dsm.checkMemory(); 16147 } 16148 } 16149 if(observer != null) { 16150 try { 16151 observer.onRemoveCompleted(packageName, succeeded); 16152 } catch (RemoteException e) { 16153 Log.i(TAG, "Observer no longer exists."); 16154 } 16155 } //end if observer 16156 } //end run 16157 }); 16158 } 16159 16160 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16161 if (packageName == null) { 16162 Slog.w(TAG, "Attempt to delete null packageName."); 16163 return false; 16164 } 16165 16166 // Try finding details about the requested package 16167 PackageParser.Package pkg; 16168 synchronized (mPackages) { 16169 pkg = mPackages.get(packageName); 16170 if (pkg == null) { 16171 final PackageSetting ps = mSettings.mPackages.get(packageName); 16172 if (ps != null) { 16173 pkg = ps.pkg; 16174 } 16175 } 16176 16177 if (pkg == null) { 16178 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16179 return false; 16180 } 16181 16182 PackageSetting ps = (PackageSetting) pkg.mExtras; 16183 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16184 } 16185 16186 clearAppDataLIF(pkg, userId, 16187 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16188 16189 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16190 removeKeystoreDataIfNeeded(userId, appId); 16191 16192 final UserManager um = mContext.getSystemService(UserManager.class); 16193 final int flags; 16194 if (um.isUserUnlockingOrUnlocked(userId)) { 16195 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16196 } else if (um.isUserRunning(userId)) { 16197 flags = StorageManager.FLAG_STORAGE_DE; 16198 } else { 16199 flags = 0; 16200 } 16201 prepareAppDataContentsLIF(pkg, userId, flags); 16202 16203 return true; 16204 } 16205 16206 /** 16207 * Reverts user permission state changes (permissions and flags) in 16208 * all packages for a given user. 16209 * 16210 * @param userId The device user for which to do a reset. 16211 */ 16212 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16213 final int packageCount = mPackages.size(); 16214 for (int i = 0; i < packageCount; i++) { 16215 PackageParser.Package pkg = mPackages.valueAt(i); 16216 PackageSetting ps = (PackageSetting) pkg.mExtras; 16217 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16218 } 16219 } 16220 16221 private void resetNetworkPolicies(int userId) { 16222 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16223 } 16224 16225 /** 16226 * Reverts user permission state changes (permissions and flags). 16227 * 16228 * @param ps The package for which to reset. 16229 * @param userId The device user for which to do a reset. 16230 */ 16231 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16232 final PackageSetting ps, final int userId) { 16233 if (ps.pkg == null) { 16234 return; 16235 } 16236 16237 // These are flags that can change base on user actions. 16238 final int userSettableMask = FLAG_PERMISSION_USER_SET 16239 | FLAG_PERMISSION_USER_FIXED 16240 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16241 | FLAG_PERMISSION_REVIEW_REQUIRED; 16242 16243 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16244 | FLAG_PERMISSION_POLICY_FIXED; 16245 16246 boolean writeInstallPermissions = false; 16247 boolean writeRuntimePermissions = false; 16248 16249 final int permissionCount = ps.pkg.requestedPermissions.size(); 16250 for (int i = 0; i < permissionCount; i++) { 16251 String permission = ps.pkg.requestedPermissions.get(i); 16252 16253 BasePermission bp = mSettings.mPermissions.get(permission); 16254 if (bp == null) { 16255 continue; 16256 } 16257 16258 // If shared user we just reset the state to which only this app contributed. 16259 if (ps.sharedUser != null) { 16260 boolean used = false; 16261 final int packageCount = ps.sharedUser.packages.size(); 16262 for (int j = 0; j < packageCount; j++) { 16263 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16264 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16265 && pkg.pkg.requestedPermissions.contains(permission)) { 16266 used = true; 16267 break; 16268 } 16269 } 16270 if (used) { 16271 continue; 16272 } 16273 } 16274 16275 PermissionsState permissionsState = ps.getPermissionsState(); 16276 16277 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16278 16279 // Always clear the user settable flags. 16280 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16281 bp.name) != null; 16282 // If permission review is enabled and this is a legacy app, mark the 16283 // permission as requiring a review as this is the initial state. 16284 int flags = 0; 16285 if (Build.PERMISSIONS_REVIEW_REQUIRED 16286 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16287 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16288 } 16289 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16290 if (hasInstallState) { 16291 writeInstallPermissions = true; 16292 } else { 16293 writeRuntimePermissions = true; 16294 } 16295 } 16296 16297 // Below is only runtime permission handling. 16298 if (!bp.isRuntime()) { 16299 continue; 16300 } 16301 16302 // Never clobber system or policy. 16303 if ((oldFlags & policyOrSystemFlags) != 0) { 16304 continue; 16305 } 16306 16307 // If this permission was granted by default, make sure it is. 16308 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16309 if (permissionsState.grantRuntimePermission(bp, userId) 16310 != PERMISSION_OPERATION_FAILURE) { 16311 writeRuntimePermissions = true; 16312 } 16313 // If permission review is enabled the permissions for a legacy apps 16314 // are represented as constantly granted runtime ones, so don't revoke. 16315 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16316 // Otherwise, reset the permission. 16317 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16318 switch (revokeResult) { 16319 case PERMISSION_OPERATION_SUCCESS: 16320 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16321 writeRuntimePermissions = true; 16322 final int appId = ps.appId; 16323 mHandler.post(new Runnable() { 16324 @Override 16325 public void run() { 16326 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16327 } 16328 }); 16329 } break; 16330 } 16331 } 16332 } 16333 16334 // Synchronously write as we are taking permissions away. 16335 if (writeRuntimePermissions) { 16336 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16337 } 16338 16339 // Synchronously write as we are taking permissions away. 16340 if (writeInstallPermissions) { 16341 mSettings.writeLPr(); 16342 } 16343 } 16344 16345 /** 16346 * Remove entries from the keystore daemon. Will only remove it if the 16347 * {@code appId} is valid. 16348 */ 16349 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16350 if (appId < 0) { 16351 return; 16352 } 16353 16354 final KeyStore keyStore = KeyStore.getInstance(); 16355 if (keyStore != null) { 16356 if (userId == UserHandle.USER_ALL) { 16357 for (final int individual : sUserManager.getUserIds()) { 16358 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16359 } 16360 } else { 16361 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16362 } 16363 } else { 16364 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16365 } 16366 } 16367 16368 @Override 16369 public void deleteApplicationCacheFiles(final String packageName, 16370 final IPackageDataObserver observer) { 16371 final int userId = UserHandle.getCallingUserId(); 16372 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16373 } 16374 16375 @Override 16376 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16377 final IPackageDataObserver observer) { 16378 mContext.enforceCallingOrSelfPermission( 16379 android.Manifest.permission.DELETE_CACHE_FILES, null); 16380 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16381 /* requireFullPermission= */ true, /* checkShell= */ false, 16382 "delete application cache files"); 16383 16384 final PackageParser.Package pkg; 16385 synchronized (mPackages) { 16386 pkg = mPackages.get(packageName); 16387 } 16388 16389 // Queue up an async operation since the package deletion may take a little while. 16390 mHandler.post(new Runnable() { 16391 public void run() { 16392 synchronized (mInstallLock) { 16393 final int flags = StorageManager.FLAG_STORAGE_DE 16394 | StorageManager.FLAG_STORAGE_CE; 16395 // We're only clearing cache files, so we don't care if the 16396 // app is unfrozen and still able to run 16397 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16398 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16399 } 16400 clearExternalStorageDataSync(packageName, userId, false); 16401 if (observer != null) { 16402 try { 16403 observer.onRemoveCompleted(packageName, true); 16404 } catch (RemoteException e) { 16405 Log.i(TAG, "Observer no longer exists."); 16406 } 16407 } 16408 } 16409 }); 16410 } 16411 16412 @Override 16413 public void getPackageSizeInfo(final String packageName, int userHandle, 16414 final IPackageStatsObserver observer) { 16415 mContext.enforceCallingOrSelfPermission( 16416 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16417 if (packageName == null) { 16418 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16419 } 16420 16421 PackageStats stats = new PackageStats(packageName, userHandle); 16422 16423 /* 16424 * Queue up an async operation since the package measurement may take a 16425 * little while. 16426 */ 16427 Message msg = mHandler.obtainMessage(INIT_COPY); 16428 msg.obj = new MeasureParams(stats, observer); 16429 mHandler.sendMessage(msg); 16430 } 16431 16432 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16433 final PackageSetting ps; 16434 synchronized (mPackages) { 16435 ps = mSettings.mPackages.get(packageName); 16436 if (ps == null) { 16437 Slog.w(TAG, "Failed to find settings for " + packageName); 16438 return false; 16439 } 16440 } 16441 try { 16442 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16443 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16444 ps.getCeDataInode(userId), ps.codePathString, stats); 16445 } catch (InstallerException e) { 16446 Slog.w(TAG, String.valueOf(e)); 16447 return false; 16448 } 16449 16450 // For now, ignore code size of packages on system partition 16451 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16452 stats.codeSize = 0; 16453 } 16454 16455 return true; 16456 } 16457 16458 private int getUidTargetSdkVersionLockedLPr(int uid) { 16459 Object obj = mSettings.getUserIdLPr(uid); 16460 if (obj instanceof SharedUserSetting) { 16461 final SharedUserSetting sus = (SharedUserSetting) obj; 16462 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16463 final Iterator<PackageSetting> it = sus.packages.iterator(); 16464 while (it.hasNext()) { 16465 final PackageSetting ps = it.next(); 16466 if (ps.pkg != null) { 16467 int v = ps.pkg.applicationInfo.targetSdkVersion; 16468 if (v < vers) vers = v; 16469 } 16470 } 16471 return vers; 16472 } else if (obj instanceof PackageSetting) { 16473 final PackageSetting ps = (PackageSetting) obj; 16474 if (ps.pkg != null) { 16475 return ps.pkg.applicationInfo.targetSdkVersion; 16476 } 16477 } 16478 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16479 } 16480 16481 @Override 16482 public void addPreferredActivity(IntentFilter filter, int match, 16483 ComponentName[] set, ComponentName activity, int userId) { 16484 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16485 "Adding preferred"); 16486 } 16487 16488 private void addPreferredActivityInternal(IntentFilter filter, int match, 16489 ComponentName[] set, ComponentName activity, boolean always, int userId, 16490 String opname) { 16491 // writer 16492 int callingUid = Binder.getCallingUid(); 16493 enforceCrossUserPermission(callingUid, userId, 16494 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16495 if (filter.countActions() == 0) { 16496 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16497 return; 16498 } 16499 synchronized (mPackages) { 16500 if (mContext.checkCallingOrSelfPermission( 16501 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16502 != PackageManager.PERMISSION_GRANTED) { 16503 if (getUidTargetSdkVersionLockedLPr(callingUid) 16504 < Build.VERSION_CODES.FROYO) { 16505 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16506 + callingUid); 16507 return; 16508 } 16509 mContext.enforceCallingOrSelfPermission( 16510 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16511 } 16512 16513 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16514 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16515 + userId + ":"); 16516 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16517 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16518 scheduleWritePackageRestrictionsLocked(userId); 16519 } 16520 } 16521 16522 @Override 16523 public void replacePreferredActivity(IntentFilter filter, int match, 16524 ComponentName[] set, ComponentName activity, int userId) { 16525 if (filter.countActions() != 1) { 16526 throw new IllegalArgumentException( 16527 "replacePreferredActivity expects filter to have only 1 action."); 16528 } 16529 if (filter.countDataAuthorities() != 0 16530 || filter.countDataPaths() != 0 16531 || filter.countDataSchemes() > 1 16532 || filter.countDataTypes() != 0) { 16533 throw new IllegalArgumentException( 16534 "replacePreferredActivity expects filter to have no data authorities, " + 16535 "paths, or types; and at most one scheme."); 16536 } 16537 16538 final int callingUid = Binder.getCallingUid(); 16539 enforceCrossUserPermission(callingUid, userId, 16540 true /* requireFullPermission */, false /* checkShell */, 16541 "replace preferred activity"); 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 replacePreferredActivity() from uid " 16549 + Binder.getCallingUid()); 16550 return; 16551 } 16552 mContext.enforceCallingOrSelfPermission( 16553 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16554 } 16555 16556 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16557 if (pir != null) { 16558 // Get all of the existing entries that exactly match this filter. 16559 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16560 if (existing != null && existing.size() == 1) { 16561 PreferredActivity cur = existing.get(0); 16562 if (DEBUG_PREFERRED) { 16563 Slog.i(TAG, "Checking replace of preferred:"); 16564 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16565 if (!cur.mPref.mAlways) { 16566 Slog.i(TAG, " -- CUR; not mAlways!"); 16567 } else { 16568 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16569 Slog.i(TAG, " -- CUR: mSet=" 16570 + Arrays.toString(cur.mPref.mSetComponents)); 16571 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16572 Slog.i(TAG, " -- NEW: mMatch=" 16573 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16574 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16575 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16576 } 16577 } 16578 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16579 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16580 && cur.mPref.sameSet(set)) { 16581 // Setting the preferred activity to what it happens to be already 16582 if (DEBUG_PREFERRED) { 16583 Slog.i(TAG, "Replacing with same preferred activity " 16584 + cur.mPref.mShortComponent + " for user " 16585 + userId + ":"); 16586 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16587 } 16588 return; 16589 } 16590 } 16591 16592 if (existing != null) { 16593 if (DEBUG_PREFERRED) { 16594 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16595 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16596 } 16597 for (int i = 0; i < existing.size(); i++) { 16598 PreferredActivity pa = existing.get(i); 16599 if (DEBUG_PREFERRED) { 16600 Slog.i(TAG, "Removing existing preferred activity " 16601 + pa.mPref.mComponent + ":"); 16602 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16603 } 16604 pir.removeFilter(pa); 16605 } 16606 } 16607 } 16608 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16609 "Replacing preferred"); 16610 } 16611 } 16612 16613 @Override 16614 public void clearPackagePreferredActivities(String packageName) { 16615 final int uid = Binder.getCallingUid(); 16616 // writer 16617 synchronized (mPackages) { 16618 PackageParser.Package pkg = mPackages.get(packageName); 16619 if (pkg == null || pkg.applicationInfo.uid != uid) { 16620 if (mContext.checkCallingOrSelfPermission( 16621 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16622 != PackageManager.PERMISSION_GRANTED) { 16623 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16624 < Build.VERSION_CODES.FROYO) { 16625 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16626 + Binder.getCallingUid()); 16627 return; 16628 } 16629 mContext.enforceCallingOrSelfPermission( 16630 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16631 } 16632 } 16633 16634 int user = UserHandle.getCallingUserId(); 16635 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16636 scheduleWritePackageRestrictionsLocked(user); 16637 } 16638 } 16639 } 16640 16641 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16642 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16643 ArrayList<PreferredActivity> removed = null; 16644 boolean changed = false; 16645 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16646 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16647 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16648 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16649 continue; 16650 } 16651 Iterator<PreferredActivity> it = pir.filterIterator(); 16652 while (it.hasNext()) { 16653 PreferredActivity pa = it.next(); 16654 // Mark entry for removal only if it matches the package name 16655 // and the entry is of type "always". 16656 if (packageName == null || 16657 (pa.mPref.mComponent.getPackageName().equals(packageName) 16658 && pa.mPref.mAlways)) { 16659 if (removed == null) { 16660 removed = new ArrayList<PreferredActivity>(); 16661 } 16662 removed.add(pa); 16663 } 16664 } 16665 if (removed != null) { 16666 for (int j=0; j<removed.size(); j++) { 16667 PreferredActivity pa = removed.get(j); 16668 pir.removeFilter(pa); 16669 } 16670 changed = true; 16671 } 16672 } 16673 return changed; 16674 } 16675 16676 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16677 private void clearIntentFilterVerificationsLPw(int userId) { 16678 final int packageCount = mPackages.size(); 16679 for (int i = 0; i < packageCount; i++) { 16680 PackageParser.Package pkg = mPackages.valueAt(i); 16681 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16682 } 16683 } 16684 16685 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16686 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16687 if (userId == UserHandle.USER_ALL) { 16688 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16689 sUserManager.getUserIds())) { 16690 for (int oneUserId : sUserManager.getUserIds()) { 16691 scheduleWritePackageRestrictionsLocked(oneUserId); 16692 } 16693 } 16694 } else { 16695 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16696 scheduleWritePackageRestrictionsLocked(userId); 16697 } 16698 } 16699 } 16700 16701 void clearDefaultBrowserIfNeeded(String packageName) { 16702 for (int oneUserId : sUserManager.getUserIds()) { 16703 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16704 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16705 if (packageName.equals(defaultBrowserPackageName)) { 16706 setDefaultBrowserPackageName(null, oneUserId); 16707 } 16708 } 16709 } 16710 16711 @Override 16712 public void resetApplicationPreferences(int userId) { 16713 mContext.enforceCallingOrSelfPermission( 16714 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16715 final long identity = Binder.clearCallingIdentity(); 16716 // writer 16717 try { 16718 synchronized (mPackages) { 16719 clearPackagePreferredActivitiesLPw(null, userId); 16720 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16721 // TODO: We have to reset the default SMS and Phone. This requires 16722 // significant refactoring to keep all default apps in the package 16723 // manager (cleaner but more work) or have the services provide 16724 // callbacks to the package manager to request a default app reset. 16725 applyFactoryDefaultBrowserLPw(userId); 16726 clearIntentFilterVerificationsLPw(userId); 16727 primeDomainVerificationsLPw(userId); 16728 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16729 scheduleWritePackageRestrictionsLocked(userId); 16730 } 16731 resetNetworkPolicies(userId); 16732 } finally { 16733 Binder.restoreCallingIdentity(identity); 16734 } 16735 } 16736 16737 @Override 16738 public int getPreferredActivities(List<IntentFilter> outFilters, 16739 List<ComponentName> outActivities, String packageName) { 16740 16741 int num = 0; 16742 final int userId = UserHandle.getCallingUserId(); 16743 // reader 16744 synchronized (mPackages) { 16745 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16746 if (pir != null) { 16747 final Iterator<PreferredActivity> it = pir.filterIterator(); 16748 while (it.hasNext()) { 16749 final PreferredActivity pa = it.next(); 16750 if (packageName == null 16751 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16752 && pa.mPref.mAlways)) { 16753 if (outFilters != null) { 16754 outFilters.add(new IntentFilter(pa)); 16755 } 16756 if (outActivities != null) { 16757 outActivities.add(pa.mPref.mComponent); 16758 } 16759 } 16760 } 16761 } 16762 } 16763 16764 return num; 16765 } 16766 16767 @Override 16768 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16769 int userId) { 16770 int callingUid = Binder.getCallingUid(); 16771 if (callingUid != Process.SYSTEM_UID) { 16772 throw new SecurityException( 16773 "addPersistentPreferredActivity can only be run by the system"); 16774 } 16775 if (filter.countActions() == 0) { 16776 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16777 return; 16778 } 16779 synchronized (mPackages) { 16780 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16781 ":"); 16782 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16783 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16784 new PersistentPreferredActivity(filter, activity)); 16785 scheduleWritePackageRestrictionsLocked(userId); 16786 } 16787 } 16788 16789 @Override 16790 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16791 int callingUid = Binder.getCallingUid(); 16792 if (callingUid != Process.SYSTEM_UID) { 16793 throw new SecurityException( 16794 "clearPackagePersistentPreferredActivities can only be run by the system"); 16795 } 16796 ArrayList<PersistentPreferredActivity> removed = null; 16797 boolean changed = false; 16798 synchronized (mPackages) { 16799 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16800 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16801 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16802 .valueAt(i); 16803 if (userId != thisUserId) { 16804 continue; 16805 } 16806 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16807 while (it.hasNext()) { 16808 PersistentPreferredActivity ppa = it.next(); 16809 // Mark entry for removal only if it matches the package name. 16810 if (ppa.mComponent.getPackageName().equals(packageName)) { 16811 if (removed == null) { 16812 removed = new ArrayList<PersistentPreferredActivity>(); 16813 } 16814 removed.add(ppa); 16815 } 16816 } 16817 if (removed != null) { 16818 for (int j=0; j<removed.size(); j++) { 16819 PersistentPreferredActivity ppa = removed.get(j); 16820 ppir.removeFilter(ppa); 16821 } 16822 changed = true; 16823 } 16824 } 16825 16826 if (changed) { 16827 scheduleWritePackageRestrictionsLocked(userId); 16828 } 16829 } 16830 } 16831 16832 /** 16833 * Common machinery for picking apart a restored XML blob and passing 16834 * it to a caller-supplied functor to be applied to the running system. 16835 */ 16836 private void restoreFromXml(XmlPullParser parser, int userId, 16837 String expectedStartTag, BlobXmlRestorer functor) 16838 throws IOException, XmlPullParserException { 16839 int type; 16840 while ((type = parser.next()) != XmlPullParser.START_TAG 16841 && type != XmlPullParser.END_DOCUMENT) { 16842 } 16843 if (type != XmlPullParser.START_TAG) { 16844 // oops didn't find a start tag?! 16845 if (DEBUG_BACKUP) { 16846 Slog.e(TAG, "Didn't find start tag during restore"); 16847 } 16848 return; 16849 } 16850Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16851 // this is supposed to be TAG_PREFERRED_BACKUP 16852 if (!expectedStartTag.equals(parser.getName())) { 16853 if (DEBUG_BACKUP) { 16854 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16855 } 16856 return; 16857 } 16858 16859 // skip interfering stuff, then we're aligned with the backing implementation 16860 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16861Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16862 functor.apply(parser, userId); 16863 } 16864 16865 private interface BlobXmlRestorer { 16866 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16867 } 16868 16869 /** 16870 * Non-Binder method, support for the backup/restore mechanism: write the 16871 * full set of preferred activities in its canonical XML format. Returns the 16872 * XML output as a byte array, or null if there is none. 16873 */ 16874 @Override 16875 public byte[] getPreferredActivityBackup(int userId) { 16876 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16877 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16878 } 16879 16880 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16881 try { 16882 final XmlSerializer serializer = new FastXmlSerializer(); 16883 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16884 serializer.startDocument(null, true); 16885 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16886 16887 synchronized (mPackages) { 16888 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16889 } 16890 16891 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16892 serializer.endDocument(); 16893 serializer.flush(); 16894 } catch (Exception e) { 16895 if (DEBUG_BACKUP) { 16896 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16897 } 16898 return null; 16899 } 16900 16901 return dataStream.toByteArray(); 16902 } 16903 16904 @Override 16905 public void restorePreferredActivities(byte[] backup, int userId) { 16906 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16907 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16908 } 16909 16910 try { 16911 final XmlPullParser parser = Xml.newPullParser(); 16912 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16913 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16914 new BlobXmlRestorer() { 16915 @Override 16916 public void apply(XmlPullParser parser, int userId) 16917 throws XmlPullParserException, IOException { 16918 synchronized (mPackages) { 16919 mSettings.readPreferredActivitiesLPw(parser, userId); 16920 } 16921 } 16922 } ); 16923 } catch (Exception e) { 16924 if (DEBUG_BACKUP) { 16925 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16926 } 16927 } 16928 } 16929 16930 /** 16931 * Non-Binder method, support for the backup/restore mechanism: write the 16932 * default browser (etc) settings in its canonical XML format. Returns the default 16933 * browser XML representation as a byte array, or null if there is none. 16934 */ 16935 @Override 16936 public byte[] getDefaultAppsBackup(int userId) { 16937 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16938 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16939 } 16940 16941 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16942 try { 16943 final XmlSerializer serializer = new FastXmlSerializer(); 16944 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16945 serializer.startDocument(null, true); 16946 serializer.startTag(null, TAG_DEFAULT_APPS); 16947 16948 synchronized (mPackages) { 16949 mSettings.writeDefaultAppsLPr(serializer, userId); 16950 } 16951 16952 serializer.endTag(null, TAG_DEFAULT_APPS); 16953 serializer.endDocument(); 16954 serializer.flush(); 16955 } catch (Exception e) { 16956 if (DEBUG_BACKUP) { 16957 Slog.e(TAG, "Unable to write default apps for backup", e); 16958 } 16959 return null; 16960 } 16961 16962 return dataStream.toByteArray(); 16963 } 16964 16965 @Override 16966 public void restoreDefaultApps(byte[] backup, int userId) { 16967 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16968 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16969 } 16970 16971 try { 16972 final XmlPullParser parser = Xml.newPullParser(); 16973 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16974 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16975 new BlobXmlRestorer() { 16976 @Override 16977 public void apply(XmlPullParser parser, int userId) 16978 throws XmlPullParserException, IOException { 16979 synchronized (mPackages) { 16980 mSettings.readDefaultAppsLPw(parser, userId); 16981 } 16982 } 16983 } ); 16984 } catch (Exception e) { 16985 if (DEBUG_BACKUP) { 16986 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16987 } 16988 } 16989 } 16990 16991 @Override 16992 public byte[] getIntentFilterVerificationBackup(int userId) { 16993 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16994 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16995 } 16996 16997 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16998 try { 16999 final XmlSerializer serializer = new FastXmlSerializer(); 17000 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17001 serializer.startDocument(null, true); 17002 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17003 17004 synchronized (mPackages) { 17005 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17006 } 17007 17008 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17009 serializer.endDocument(); 17010 serializer.flush(); 17011 } catch (Exception e) { 17012 if (DEBUG_BACKUP) { 17013 Slog.e(TAG, "Unable to write default apps for backup", e); 17014 } 17015 return null; 17016 } 17017 17018 return dataStream.toByteArray(); 17019 } 17020 17021 @Override 17022 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17023 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17024 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17025 } 17026 17027 try { 17028 final XmlPullParser parser = Xml.newPullParser(); 17029 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17030 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17031 new BlobXmlRestorer() { 17032 @Override 17033 public void apply(XmlPullParser parser, int userId) 17034 throws XmlPullParserException, IOException { 17035 synchronized (mPackages) { 17036 mSettings.readAllDomainVerificationsLPr(parser, userId); 17037 mSettings.writeLPr(); 17038 } 17039 } 17040 } ); 17041 } catch (Exception e) { 17042 if (DEBUG_BACKUP) { 17043 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17044 } 17045 } 17046 } 17047 17048 @Override 17049 public byte[] getPermissionGrantBackup(int userId) { 17050 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17051 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17052 } 17053 17054 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17055 try { 17056 final XmlSerializer serializer = new FastXmlSerializer(); 17057 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17058 serializer.startDocument(null, true); 17059 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17060 17061 synchronized (mPackages) { 17062 serializeRuntimePermissionGrantsLPr(serializer, userId); 17063 } 17064 17065 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17066 serializer.endDocument(); 17067 serializer.flush(); 17068 } catch (Exception e) { 17069 if (DEBUG_BACKUP) { 17070 Slog.e(TAG, "Unable to write default apps for backup", e); 17071 } 17072 return null; 17073 } 17074 17075 return dataStream.toByteArray(); 17076 } 17077 17078 @Override 17079 public void restorePermissionGrants(byte[] backup, int userId) { 17080 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17081 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17082 } 17083 17084 try { 17085 final XmlPullParser parser = Xml.newPullParser(); 17086 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17087 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17088 new BlobXmlRestorer() { 17089 @Override 17090 public void apply(XmlPullParser parser, int userId) 17091 throws XmlPullParserException, IOException { 17092 synchronized (mPackages) { 17093 processRestoredPermissionGrantsLPr(parser, userId); 17094 } 17095 } 17096 } ); 17097 } catch (Exception e) { 17098 if (DEBUG_BACKUP) { 17099 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17100 } 17101 } 17102 } 17103 17104 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17105 throws IOException { 17106 serializer.startTag(null, TAG_ALL_GRANTS); 17107 17108 final int N = mSettings.mPackages.size(); 17109 for (int i = 0; i < N; i++) { 17110 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17111 boolean pkgGrantsKnown = false; 17112 17113 PermissionsState packagePerms = ps.getPermissionsState(); 17114 17115 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17116 final int grantFlags = state.getFlags(); 17117 // only look at grants that are not system/policy fixed 17118 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17119 final boolean isGranted = state.isGranted(); 17120 // And only back up the user-twiddled state bits 17121 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17122 final String packageName = mSettings.mPackages.keyAt(i); 17123 if (!pkgGrantsKnown) { 17124 serializer.startTag(null, TAG_GRANT); 17125 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17126 pkgGrantsKnown = true; 17127 } 17128 17129 final boolean userSet = 17130 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17131 final boolean userFixed = 17132 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17133 final boolean revoke = 17134 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17135 17136 serializer.startTag(null, TAG_PERMISSION); 17137 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17138 if (isGranted) { 17139 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17140 } 17141 if (userSet) { 17142 serializer.attribute(null, ATTR_USER_SET, "true"); 17143 } 17144 if (userFixed) { 17145 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17146 } 17147 if (revoke) { 17148 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17149 } 17150 serializer.endTag(null, TAG_PERMISSION); 17151 } 17152 } 17153 } 17154 17155 if (pkgGrantsKnown) { 17156 serializer.endTag(null, TAG_GRANT); 17157 } 17158 } 17159 17160 serializer.endTag(null, TAG_ALL_GRANTS); 17161 } 17162 17163 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17164 throws XmlPullParserException, IOException { 17165 String pkgName = null; 17166 int outerDepth = parser.getDepth(); 17167 int type; 17168 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17169 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17170 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17171 continue; 17172 } 17173 17174 final String tagName = parser.getName(); 17175 if (tagName.equals(TAG_GRANT)) { 17176 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17177 if (DEBUG_BACKUP) { 17178 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17179 } 17180 } else if (tagName.equals(TAG_PERMISSION)) { 17181 17182 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17183 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17184 17185 int newFlagSet = 0; 17186 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17187 newFlagSet |= FLAG_PERMISSION_USER_SET; 17188 } 17189 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17190 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17191 } 17192 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17193 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17194 } 17195 if (DEBUG_BACKUP) { 17196 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17197 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17198 } 17199 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17200 if (ps != null) { 17201 // Already installed so we apply the grant immediately 17202 if (DEBUG_BACKUP) { 17203 Slog.v(TAG, " + already installed; applying"); 17204 } 17205 PermissionsState perms = ps.getPermissionsState(); 17206 BasePermission bp = mSettings.mPermissions.get(permName); 17207 if (bp != null) { 17208 if (isGranted) { 17209 perms.grantRuntimePermission(bp, userId); 17210 } 17211 if (newFlagSet != 0) { 17212 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17213 } 17214 } 17215 } else { 17216 // Need to wait for post-restore install to apply the grant 17217 if (DEBUG_BACKUP) { 17218 Slog.v(TAG, " - not yet installed; saving for later"); 17219 } 17220 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17221 isGranted, newFlagSet, userId); 17222 } 17223 } else { 17224 PackageManagerService.reportSettingsProblem(Log.WARN, 17225 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17226 XmlUtils.skipCurrentTag(parser); 17227 } 17228 } 17229 17230 scheduleWriteSettingsLocked(); 17231 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17232 } 17233 17234 @Override 17235 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17236 int sourceUserId, int targetUserId, int flags) { 17237 mContext.enforceCallingOrSelfPermission( 17238 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17239 int callingUid = Binder.getCallingUid(); 17240 enforceOwnerRights(ownerPackage, callingUid); 17241 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17242 if (intentFilter.countActions() == 0) { 17243 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17244 return; 17245 } 17246 synchronized (mPackages) { 17247 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17248 ownerPackage, targetUserId, flags); 17249 CrossProfileIntentResolver resolver = 17250 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17251 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17252 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17253 if (existing != null) { 17254 int size = existing.size(); 17255 for (int i = 0; i < size; i++) { 17256 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17257 return; 17258 } 17259 } 17260 } 17261 resolver.addFilter(newFilter); 17262 scheduleWritePackageRestrictionsLocked(sourceUserId); 17263 } 17264 } 17265 17266 @Override 17267 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17268 mContext.enforceCallingOrSelfPermission( 17269 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17270 int callingUid = Binder.getCallingUid(); 17271 enforceOwnerRights(ownerPackage, callingUid); 17272 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17273 synchronized (mPackages) { 17274 CrossProfileIntentResolver resolver = 17275 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17276 ArraySet<CrossProfileIntentFilter> set = 17277 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17278 for (CrossProfileIntentFilter filter : set) { 17279 if (filter.getOwnerPackage().equals(ownerPackage)) { 17280 resolver.removeFilter(filter); 17281 } 17282 } 17283 scheduleWritePackageRestrictionsLocked(sourceUserId); 17284 } 17285 } 17286 17287 // Enforcing that callingUid is owning pkg on userId 17288 private void enforceOwnerRights(String pkg, int callingUid) { 17289 // The system owns everything. 17290 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17291 return; 17292 } 17293 int callingUserId = UserHandle.getUserId(callingUid); 17294 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17295 if (pi == null) { 17296 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17297 + callingUserId); 17298 } 17299 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17300 throw new SecurityException("Calling uid " + callingUid 17301 + " does not own package " + pkg); 17302 } 17303 } 17304 17305 @Override 17306 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17307 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17308 } 17309 17310 private Intent getHomeIntent() { 17311 Intent intent = new Intent(Intent.ACTION_MAIN); 17312 intent.addCategory(Intent.CATEGORY_HOME); 17313 return intent; 17314 } 17315 17316 private IntentFilter getHomeFilter() { 17317 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17318 filter.addCategory(Intent.CATEGORY_HOME); 17319 filter.addCategory(Intent.CATEGORY_DEFAULT); 17320 return filter; 17321 } 17322 17323 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17324 int userId) { 17325 Intent intent = getHomeIntent(); 17326 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17327 PackageManager.GET_META_DATA, userId); 17328 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17329 true, false, false, userId); 17330 17331 allHomeCandidates.clear(); 17332 if (list != null) { 17333 for (ResolveInfo ri : list) { 17334 allHomeCandidates.add(ri); 17335 } 17336 } 17337 return (preferred == null || preferred.activityInfo == null) 17338 ? null 17339 : new ComponentName(preferred.activityInfo.packageName, 17340 preferred.activityInfo.name); 17341 } 17342 17343 @Override 17344 public void setHomeActivity(ComponentName comp, int userId) { 17345 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17346 getHomeActivitiesAsUser(homeActivities, userId); 17347 17348 boolean found = false; 17349 17350 final int size = homeActivities.size(); 17351 final ComponentName[] set = new ComponentName[size]; 17352 for (int i = 0; i < size; i++) { 17353 final ResolveInfo candidate = homeActivities.get(i); 17354 final ActivityInfo info = candidate.activityInfo; 17355 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17356 set[i] = activityName; 17357 if (!found && activityName.equals(comp)) { 17358 found = true; 17359 } 17360 } 17361 if (!found) { 17362 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17363 + userId); 17364 } 17365 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17366 set, comp, userId); 17367 } 17368 17369 private @Nullable String getSetupWizardPackageName() { 17370 final Intent intent = new Intent(Intent.ACTION_MAIN); 17371 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17372 17373 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17374 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17375 | MATCH_DISABLED_COMPONENTS, 17376 UserHandle.myUserId()); 17377 if (matches.size() == 1) { 17378 return matches.get(0).getComponentInfo().packageName; 17379 } else { 17380 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17381 + ": matches=" + matches); 17382 return null; 17383 } 17384 } 17385 17386 @Override 17387 public void setApplicationEnabledSetting(String appPackageName, 17388 int newState, int flags, int userId, String callingPackage) { 17389 if (!sUserManager.exists(userId)) return; 17390 if (callingPackage == null) { 17391 callingPackage = Integer.toString(Binder.getCallingUid()); 17392 } 17393 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17394 } 17395 17396 @Override 17397 public void setComponentEnabledSetting(ComponentName componentName, 17398 int newState, int flags, int userId) { 17399 if (!sUserManager.exists(userId)) return; 17400 setEnabledSetting(componentName.getPackageName(), 17401 componentName.getClassName(), newState, flags, userId, null); 17402 } 17403 17404 private void setEnabledSetting(final String packageName, String className, int newState, 17405 final int flags, int userId, String callingPackage) { 17406 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17407 || newState == COMPONENT_ENABLED_STATE_ENABLED 17408 || newState == COMPONENT_ENABLED_STATE_DISABLED 17409 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17410 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17411 throw new IllegalArgumentException("Invalid new component state: " 17412 + newState); 17413 } 17414 PackageSetting pkgSetting; 17415 final int uid = Binder.getCallingUid(); 17416 final int permission; 17417 if (uid == Process.SYSTEM_UID) { 17418 permission = PackageManager.PERMISSION_GRANTED; 17419 } else { 17420 permission = mContext.checkCallingOrSelfPermission( 17421 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17422 } 17423 enforceCrossUserPermission(uid, userId, 17424 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17425 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17426 boolean sendNow = false; 17427 boolean isApp = (className == null); 17428 String componentName = isApp ? packageName : className; 17429 int packageUid = -1; 17430 ArrayList<String> components; 17431 17432 // writer 17433 synchronized (mPackages) { 17434 pkgSetting = mSettings.mPackages.get(packageName); 17435 if (pkgSetting == null) { 17436 if (className == null) { 17437 throw new IllegalArgumentException("Unknown package: " + packageName); 17438 } 17439 throw new IllegalArgumentException( 17440 "Unknown component: " + packageName + "/" + className); 17441 } 17442 // Allow root and verify that userId is not being specified by a different user 17443 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17444 throw new SecurityException( 17445 "Permission Denial: attempt to change component state from pid=" 17446 + Binder.getCallingPid() 17447 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17448 } 17449 if (className == null) { 17450 // We're dealing with an application/package level state change 17451 if (pkgSetting.getEnabled(userId) == newState) { 17452 // Nothing to do 17453 return; 17454 } 17455 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17456 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17457 // Don't care about who enables an app. 17458 callingPackage = null; 17459 } 17460 pkgSetting.setEnabled(newState, userId, callingPackage); 17461 // pkgSetting.pkg.mSetEnabled = newState; 17462 } else { 17463 // We're dealing with a component level state change 17464 // First, verify that this is a valid class name. 17465 PackageParser.Package pkg = pkgSetting.pkg; 17466 if (pkg == null || !pkg.hasComponentClassName(className)) { 17467 if (pkg != null && 17468 pkg.applicationInfo.targetSdkVersion >= 17469 Build.VERSION_CODES.JELLY_BEAN) { 17470 throw new IllegalArgumentException("Component class " + className 17471 + " does not exist in " + packageName); 17472 } else { 17473 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17474 + className + " does not exist in " + packageName); 17475 } 17476 } 17477 switch (newState) { 17478 case COMPONENT_ENABLED_STATE_ENABLED: 17479 if (!pkgSetting.enableComponentLPw(className, userId)) { 17480 return; 17481 } 17482 break; 17483 case COMPONENT_ENABLED_STATE_DISABLED: 17484 if (!pkgSetting.disableComponentLPw(className, userId)) { 17485 return; 17486 } 17487 break; 17488 case COMPONENT_ENABLED_STATE_DEFAULT: 17489 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17490 return; 17491 } 17492 break; 17493 default: 17494 Slog.e(TAG, "Invalid new component state: " + newState); 17495 return; 17496 } 17497 } 17498 scheduleWritePackageRestrictionsLocked(userId); 17499 components = mPendingBroadcasts.get(userId, packageName); 17500 final boolean newPackage = components == null; 17501 if (newPackage) { 17502 components = new ArrayList<String>(); 17503 } 17504 if (!components.contains(componentName)) { 17505 components.add(componentName); 17506 } 17507 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17508 sendNow = true; 17509 // Purge entry from pending broadcast list if another one exists already 17510 // since we are sending one right away. 17511 mPendingBroadcasts.remove(userId, packageName); 17512 } else { 17513 if (newPackage) { 17514 mPendingBroadcasts.put(userId, packageName, components); 17515 } 17516 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17517 // Schedule a message 17518 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17519 } 17520 } 17521 } 17522 17523 long callingId = Binder.clearCallingIdentity(); 17524 try { 17525 if (sendNow) { 17526 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17527 sendPackageChangedBroadcast(packageName, 17528 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17529 } 17530 } finally { 17531 Binder.restoreCallingIdentity(callingId); 17532 } 17533 } 17534 17535 @Override 17536 public void flushPackageRestrictionsAsUser(int userId) { 17537 if (!sUserManager.exists(userId)) { 17538 return; 17539 } 17540 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17541 false /* checkShell */, "flushPackageRestrictions"); 17542 synchronized (mPackages) { 17543 mSettings.writePackageRestrictionsLPr(userId); 17544 mDirtyUsers.remove(userId); 17545 if (mDirtyUsers.isEmpty()) { 17546 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17547 } 17548 } 17549 } 17550 17551 private void sendPackageChangedBroadcast(String packageName, 17552 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17553 if (DEBUG_INSTALL) 17554 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17555 + componentNames); 17556 Bundle extras = new Bundle(4); 17557 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17558 String nameList[] = new String[componentNames.size()]; 17559 componentNames.toArray(nameList); 17560 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17561 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17562 extras.putInt(Intent.EXTRA_UID, packageUid); 17563 // If this is not reporting a change of the overall package, then only send it 17564 // to registered receivers. We don't want to launch a swath of apps for every 17565 // little component state change. 17566 final int flags = !componentNames.contains(packageName) 17567 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17568 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17569 new int[] {UserHandle.getUserId(packageUid)}); 17570 } 17571 17572 @Override 17573 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17574 if (!sUserManager.exists(userId)) return; 17575 final int uid = Binder.getCallingUid(); 17576 final int permission = mContext.checkCallingOrSelfPermission( 17577 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17578 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17579 enforceCrossUserPermission(uid, userId, 17580 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17581 // writer 17582 synchronized (mPackages) { 17583 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17584 allowedByPermission, uid, userId)) { 17585 scheduleWritePackageRestrictionsLocked(userId); 17586 } 17587 } 17588 } 17589 17590 @Override 17591 public String getInstallerPackageName(String packageName) { 17592 // reader 17593 synchronized (mPackages) { 17594 return mSettings.getInstallerPackageNameLPr(packageName); 17595 } 17596 } 17597 17598 public boolean isOrphaned(String packageName) { 17599 // reader 17600 synchronized (mPackages) { 17601 return mSettings.isOrphaned(packageName); 17602 } 17603 } 17604 17605 @Override 17606 public int getApplicationEnabledSetting(String packageName, int userId) { 17607 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17608 int uid = Binder.getCallingUid(); 17609 enforceCrossUserPermission(uid, userId, 17610 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17611 // reader 17612 synchronized (mPackages) { 17613 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17614 } 17615 } 17616 17617 @Override 17618 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17619 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17620 int uid = Binder.getCallingUid(); 17621 enforceCrossUserPermission(uid, userId, 17622 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17623 // reader 17624 synchronized (mPackages) { 17625 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17626 } 17627 } 17628 17629 @Override 17630 public void enterSafeMode() { 17631 enforceSystemOrRoot("Only the system can request entering safe mode"); 17632 17633 if (!mSystemReady) { 17634 mSafeMode = true; 17635 } 17636 } 17637 17638 @Override 17639 public void systemReady() { 17640 mSystemReady = true; 17641 17642 // Read the compatibilty setting when the system is ready. 17643 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17644 mContext.getContentResolver(), 17645 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17646 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17647 if (DEBUG_SETTINGS) { 17648 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17649 } 17650 17651 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17652 17653 synchronized (mPackages) { 17654 // Verify that all of the preferred activity components actually 17655 // exist. It is possible for applications to be updated and at 17656 // that point remove a previously declared activity component that 17657 // had been set as a preferred activity. We try to clean this up 17658 // the next time we encounter that preferred activity, but it is 17659 // possible for the user flow to never be able to return to that 17660 // situation so here we do a sanity check to make sure we haven't 17661 // left any junk around. 17662 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17663 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17664 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17665 removed.clear(); 17666 for (PreferredActivity pa : pir.filterSet()) { 17667 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17668 removed.add(pa); 17669 } 17670 } 17671 if (removed.size() > 0) { 17672 for (int r=0; r<removed.size(); r++) { 17673 PreferredActivity pa = removed.get(r); 17674 Slog.w(TAG, "Removing dangling preferred activity: " 17675 + pa.mPref.mComponent); 17676 pir.removeFilter(pa); 17677 } 17678 mSettings.writePackageRestrictionsLPr( 17679 mSettings.mPreferredActivities.keyAt(i)); 17680 } 17681 } 17682 17683 for (int userId : UserManagerService.getInstance().getUserIds()) { 17684 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17685 grantPermissionsUserIds = ArrayUtils.appendInt( 17686 grantPermissionsUserIds, userId); 17687 } 17688 } 17689 } 17690 sUserManager.systemReady(); 17691 17692 // If we upgraded grant all default permissions before kicking off. 17693 for (int userId : grantPermissionsUserIds) { 17694 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17695 } 17696 17697 // Kick off any messages waiting for system ready 17698 if (mPostSystemReadyMessages != null) { 17699 for (Message msg : mPostSystemReadyMessages) { 17700 msg.sendToTarget(); 17701 } 17702 mPostSystemReadyMessages = null; 17703 } 17704 17705 // Watch for external volumes that come and go over time 17706 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17707 storage.registerListener(mStorageListener); 17708 17709 mInstallerService.systemReady(); 17710 mPackageDexOptimizer.systemReady(); 17711 17712 MountServiceInternal mountServiceInternal = LocalServices.getService( 17713 MountServiceInternal.class); 17714 mountServiceInternal.addExternalStoragePolicy( 17715 new MountServiceInternal.ExternalStorageMountPolicy() { 17716 @Override 17717 public int getMountMode(int uid, String packageName) { 17718 if (Process.isIsolated(uid)) { 17719 return Zygote.MOUNT_EXTERNAL_NONE; 17720 } 17721 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17722 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17723 } 17724 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17725 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17726 } 17727 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17728 return Zygote.MOUNT_EXTERNAL_READ; 17729 } 17730 return Zygote.MOUNT_EXTERNAL_WRITE; 17731 } 17732 17733 @Override 17734 public boolean hasExternalStorage(int uid, String packageName) { 17735 return true; 17736 } 17737 }); 17738 17739 // Now that we're mostly running, clean up stale users and apps 17740 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17741 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17742 } 17743 17744 @Override 17745 public boolean isSafeMode() { 17746 return mSafeMode; 17747 } 17748 17749 @Override 17750 public boolean hasSystemUidErrors() { 17751 return mHasSystemUidErrors; 17752 } 17753 17754 static String arrayToString(int[] array) { 17755 StringBuffer buf = new StringBuffer(128); 17756 buf.append('['); 17757 if (array != null) { 17758 for (int i=0; i<array.length; i++) { 17759 if (i > 0) buf.append(", "); 17760 buf.append(array[i]); 17761 } 17762 } 17763 buf.append(']'); 17764 return buf.toString(); 17765 } 17766 17767 static class DumpState { 17768 public static final int DUMP_LIBS = 1 << 0; 17769 public static final int DUMP_FEATURES = 1 << 1; 17770 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17771 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17772 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17773 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17774 public static final int DUMP_PERMISSIONS = 1 << 6; 17775 public static final int DUMP_PACKAGES = 1 << 7; 17776 public static final int DUMP_SHARED_USERS = 1 << 8; 17777 public static final int DUMP_MESSAGES = 1 << 9; 17778 public static final int DUMP_PROVIDERS = 1 << 10; 17779 public static final int DUMP_VERIFIERS = 1 << 11; 17780 public static final int DUMP_PREFERRED = 1 << 12; 17781 public static final int DUMP_PREFERRED_XML = 1 << 13; 17782 public static final int DUMP_KEYSETS = 1 << 14; 17783 public static final int DUMP_VERSION = 1 << 15; 17784 public static final int DUMP_INSTALLS = 1 << 16; 17785 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17786 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17787 public static final int DUMP_FROZEN = 1 << 19; 17788 public static final int DUMP_DEXOPT = 1 << 20; 17789 17790 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17791 17792 private int mTypes; 17793 17794 private int mOptions; 17795 17796 private boolean mTitlePrinted; 17797 17798 private SharedUserSetting mSharedUser; 17799 17800 public boolean isDumping(int type) { 17801 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17802 return true; 17803 } 17804 17805 return (mTypes & type) != 0; 17806 } 17807 17808 public void setDump(int type) { 17809 mTypes |= type; 17810 } 17811 17812 public boolean isOptionEnabled(int option) { 17813 return (mOptions & option) != 0; 17814 } 17815 17816 public void setOptionEnabled(int option) { 17817 mOptions |= option; 17818 } 17819 17820 public boolean onTitlePrinted() { 17821 final boolean printed = mTitlePrinted; 17822 mTitlePrinted = true; 17823 return printed; 17824 } 17825 17826 public boolean getTitlePrinted() { 17827 return mTitlePrinted; 17828 } 17829 17830 public void setTitlePrinted(boolean enabled) { 17831 mTitlePrinted = enabled; 17832 } 17833 17834 public SharedUserSetting getSharedUser() { 17835 return mSharedUser; 17836 } 17837 17838 public void setSharedUser(SharedUserSetting user) { 17839 mSharedUser = user; 17840 } 17841 } 17842 17843 @Override 17844 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17845 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17846 (new PackageManagerShellCommand(this)).exec( 17847 this, in, out, err, args, resultReceiver); 17848 } 17849 17850 @Override 17851 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17852 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17853 != PackageManager.PERMISSION_GRANTED) { 17854 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17855 + Binder.getCallingPid() 17856 + ", uid=" + Binder.getCallingUid() 17857 + " without permission " 17858 + android.Manifest.permission.DUMP); 17859 return; 17860 } 17861 17862 DumpState dumpState = new DumpState(); 17863 boolean fullPreferred = false; 17864 boolean checkin = false; 17865 17866 String packageName = null; 17867 ArraySet<String> permissionNames = null; 17868 17869 int opti = 0; 17870 while (opti < args.length) { 17871 String opt = args[opti]; 17872 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17873 break; 17874 } 17875 opti++; 17876 17877 if ("-a".equals(opt)) { 17878 // Right now we only know how to print all. 17879 } else if ("-h".equals(opt)) { 17880 pw.println("Package manager dump options:"); 17881 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17882 pw.println(" --checkin: dump for a checkin"); 17883 pw.println(" -f: print details of intent filters"); 17884 pw.println(" -h: print this help"); 17885 pw.println(" cmd may be one of:"); 17886 pw.println(" l[ibraries]: list known shared libraries"); 17887 pw.println(" f[eatures]: list device features"); 17888 pw.println(" k[eysets]: print known keysets"); 17889 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17890 pw.println(" perm[issions]: dump permissions"); 17891 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17892 pw.println(" pref[erred]: print preferred package settings"); 17893 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17894 pw.println(" prov[iders]: dump content providers"); 17895 pw.println(" p[ackages]: dump installed packages"); 17896 pw.println(" s[hared-users]: dump shared user IDs"); 17897 pw.println(" m[essages]: print collected runtime messages"); 17898 pw.println(" v[erifiers]: print package verifier info"); 17899 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17900 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17901 pw.println(" version: print database version info"); 17902 pw.println(" write: write current settings now"); 17903 pw.println(" installs: details about install sessions"); 17904 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17905 pw.println(" dexopt: dump dexopt state"); 17906 pw.println(" <package.name>: info about given package"); 17907 return; 17908 } else if ("--checkin".equals(opt)) { 17909 checkin = true; 17910 } else if ("-f".equals(opt)) { 17911 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17912 } else { 17913 pw.println("Unknown argument: " + opt + "; use -h for help"); 17914 } 17915 } 17916 17917 // Is the caller requesting to dump a particular piece of data? 17918 if (opti < args.length) { 17919 String cmd = args[opti]; 17920 opti++; 17921 // Is this a package name? 17922 if ("android".equals(cmd) || cmd.contains(".")) { 17923 packageName = cmd; 17924 // When dumping a single package, we always dump all of its 17925 // filter information since the amount of data will be reasonable. 17926 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17927 } else if ("check-permission".equals(cmd)) { 17928 if (opti >= args.length) { 17929 pw.println("Error: check-permission missing permission argument"); 17930 return; 17931 } 17932 String perm = args[opti]; 17933 opti++; 17934 if (opti >= args.length) { 17935 pw.println("Error: check-permission missing package argument"); 17936 return; 17937 } 17938 String pkg = args[opti]; 17939 opti++; 17940 int user = UserHandle.getUserId(Binder.getCallingUid()); 17941 if (opti < args.length) { 17942 try { 17943 user = Integer.parseInt(args[opti]); 17944 } catch (NumberFormatException e) { 17945 pw.println("Error: check-permission user argument is not a number: " 17946 + args[opti]); 17947 return; 17948 } 17949 } 17950 pw.println(checkPermission(perm, pkg, user)); 17951 return; 17952 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17953 dumpState.setDump(DumpState.DUMP_LIBS); 17954 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17955 dumpState.setDump(DumpState.DUMP_FEATURES); 17956 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17957 if (opti >= args.length) { 17958 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17959 | DumpState.DUMP_SERVICE_RESOLVERS 17960 | DumpState.DUMP_RECEIVER_RESOLVERS 17961 | DumpState.DUMP_CONTENT_RESOLVERS); 17962 } else { 17963 while (opti < args.length) { 17964 String name = args[opti]; 17965 if ("a".equals(name) || "activity".equals(name)) { 17966 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17967 } else if ("s".equals(name) || "service".equals(name)) { 17968 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17969 } else if ("r".equals(name) || "receiver".equals(name)) { 17970 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17971 } else if ("c".equals(name) || "content".equals(name)) { 17972 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17973 } else { 17974 pw.println("Error: unknown resolver table type: " + name); 17975 return; 17976 } 17977 opti++; 17978 } 17979 } 17980 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17981 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17982 } else if ("permission".equals(cmd)) { 17983 if (opti >= args.length) { 17984 pw.println("Error: permission requires permission name"); 17985 return; 17986 } 17987 permissionNames = new ArraySet<>(); 17988 while (opti < args.length) { 17989 permissionNames.add(args[opti]); 17990 opti++; 17991 } 17992 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17993 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17994 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17995 dumpState.setDump(DumpState.DUMP_PREFERRED); 17996 } else if ("preferred-xml".equals(cmd)) { 17997 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17998 if (opti < args.length && "--full".equals(args[opti])) { 17999 fullPreferred = true; 18000 opti++; 18001 } 18002 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18003 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18004 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18005 dumpState.setDump(DumpState.DUMP_PACKAGES); 18006 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18007 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18008 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18009 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18010 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18011 dumpState.setDump(DumpState.DUMP_MESSAGES); 18012 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18013 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18014 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18015 || "intent-filter-verifiers".equals(cmd)) { 18016 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18017 } else if ("version".equals(cmd)) { 18018 dumpState.setDump(DumpState.DUMP_VERSION); 18019 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18020 dumpState.setDump(DumpState.DUMP_KEYSETS); 18021 } else if ("installs".equals(cmd)) { 18022 dumpState.setDump(DumpState.DUMP_INSTALLS); 18023 } else if ("frozen".equals(cmd)) { 18024 dumpState.setDump(DumpState.DUMP_FROZEN); 18025 } else if ("dexopt".equals(cmd)) { 18026 dumpState.setDump(DumpState.DUMP_DEXOPT); 18027 } else if ("write".equals(cmd)) { 18028 synchronized (mPackages) { 18029 mSettings.writeLPr(); 18030 pw.println("Settings written."); 18031 return; 18032 } 18033 } 18034 } 18035 18036 if (checkin) { 18037 pw.println("vers,1"); 18038 } 18039 18040 // reader 18041 synchronized (mPackages) { 18042 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18043 if (!checkin) { 18044 if (dumpState.onTitlePrinted()) 18045 pw.println(); 18046 pw.println("Database versions:"); 18047 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18048 } 18049 } 18050 18051 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18052 if (!checkin) { 18053 if (dumpState.onTitlePrinted()) 18054 pw.println(); 18055 pw.println("Verifiers:"); 18056 pw.print(" Required: "); 18057 pw.print(mRequiredVerifierPackage); 18058 pw.print(" (uid="); 18059 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18060 UserHandle.USER_SYSTEM)); 18061 pw.println(")"); 18062 } else if (mRequiredVerifierPackage != null) { 18063 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18064 pw.print(","); 18065 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18066 UserHandle.USER_SYSTEM)); 18067 } 18068 } 18069 18070 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18071 packageName == null) { 18072 if (mIntentFilterVerifierComponent != null) { 18073 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18074 if (!checkin) { 18075 if (dumpState.onTitlePrinted()) 18076 pw.println(); 18077 pw.println("Intent Filter Verifier:"); 18078 pw.print(" Using: "); 18079 pw.print(verifierPackageName); 18080 pw.print(" (uid="); 18081 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18082 UserHandle.USER_SYSTEM)); 18083 pw.println(")"); 18084 } else if (verifierPackageName != null) { 18085 pw.print("ifv,"); pw.print(verifierPackageName); 18086 pw.print(","); 18087 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18088 UserHandle.USER_SYSTEM)); 18089 } 18090 } else { 18091 pw.println(); 18092 pw.println("No Intent Filter Verifier available!"); 18093 } 18094 } 18095 18096 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18097 boolean printedHeader = false; 18098 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18099 while (it.hasNext()) { 18100 String name = it.next(); 18101 SharedLibraryEntry ent = mSharedLibraries.get(name); 18102 if (!checkin) { 18103 if (!printedHeader) { 18104 if (dumpState.onTitlePrinted()) 18105 pw.println(); 18106 pw.println("Libraries:"); 18107 printedHeader = true; 18108 } 18109 pw.print(" "); 18110 } else { 18111 pw.print("lib,"); 18112 } 18113 pw.print(name); 18114 if (!checkin) { 18115 pw.print(" -> "); 18116 } 18117 if (ent.path != null) { 18118 if (!checkin) { 18119 pw.print("(jar) "); 18120 pw.print(ent.path); 18121 } else { 18122 pw.print(",jar,"); 18123 pw.print(ent.path); 18124 } 18125 } else { 18126 if (!checkin) { 18127 pw.print("(apk) "); 18128 pw.print(ent.apk); 18129 } else { 18130 pw.print(",apk,"); 18131 pw.print(ent.apk); 18132 } 18133 } 18134 pw.println(); 18135 } 18136 } 18137 18138 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18139 if (dumpState.onTitlePrinted()) 18140 pw.println(); 18141 if (!checkin) { 18142 pw.println("Features:"); 18143 } 18144 18145 for (FeatureInfo feat : mAvailableFeatures.values()) { 18146 if (checkin) { 18147 pw.print("feat,"); 18148 pw.print(feat.name); 18149 pw.print(","); 18150 pw.println(feat.version); 18151 } else { 18152 pw.print(" "); 18153 pw.print(feat.name); 18154 if (feat.version > 0) { 18155 pw.print(" version="); 18156 pw.print(feat.version); 18157 } 18158 pw.println(); 18159 } 18160 } 18161 } 18162 18163 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18164 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18165 : "Activity Resolver Table:", " ", packageName, 18166 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18167 dumpState.setTitlePrinted(true); 18168 } 18169 } 18170 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18171 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18172 : "Receiver Resolver Table:", " ", packageName, 18173 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18174 dumpState.setTitlePrinted(true); 18175 } 18176 } 18177 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18178 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18179 : "Service Resolver Table:", " ", packageName, 18180 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18181 dumpState.setTitlePrinted(true); 18182 } 18183 } 18184 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18185 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18186 : "Provider Resolver Table:", " ", packageName, 18187 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18188 dumpState.setTitlePrinted(true); 18189 } 18190 } 18191 18192 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18193 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18194 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18195 int user = mSettings.mPreferredActivities.keyAt(i); 18196 if (pir.dump(pw, 18197 dumpState.getTitlePrinted() 18198 ? "\nPreferred Activities User " + user + ":" 18199 : "Preferred Activities User " + user + ":", " ", 18200 packageName, true, false)) { 18201 dumpState.setTitlePrinted(true); 18202 } 18203 } 18204 } 18205 18206 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18207 pw.flush(); 18208 FileOutputStream fout = new FileOutputStream(fd); 18209 BufferedOutputStream str = new BufferedOutputStream(fout); 18210 XmlSerializer serializer = new FastXmlSerializer(); 18211 try { 18212 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18213 serializer.startDocument(null, true); 18214 serializer.setFeature( 18215 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18216 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18217 serializer.endDocument(); 18218 serializer.flush(); 18219 } catch (IllegalArgumentException e) { 18220 pw.println("Failed writing: " + e); 18221 } catch (IllegalStateException e) { 18222 pw.println("Failed writing: " + e); 18223 } catch (IOException e) { 18224 pw.println("Failed writing: " + e); 18225 } 18226 } 18227 18228 if (!checkin 18229 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18230 && packageName == null) { 18231 pw.println(); 18232 int count = mSettings.mPackages.size(); 18233 if (count == 0) { 18234 pw.println("No applications!"); 18235 pw.println(); 18236 } else { 18237 final String prefix = " "; 18238 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18239 if (allPackageSettings.size() == 0) { 18240 pw.println("No domain preferred apps!"); 18241 pw.println(); 18242 } else { 18243 pw.println("App verification status:"); 18244 pw.println(); 18245 count = 0; 18246 for (PackageSetting ps : allPackageSettings) { 18247 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18248 if (ivi == null || ivi.getPackageName() == null) continue; 18249 pw.println(prefix + "Package: " + ivi.getPackageName()); 18250 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18251 pw.println(prefix + "Status: " + ivi.getStatusString()); 18252 pw.println(); 18253 count++; 18254 } 18255 if (count == 0) { 18256 pw.println(prefix + "No app verification established."); 18257 pw.println(); 18258 } 18259 for (int userId : sUserManager.getUserIds()) { 18260 pw.println("App linkages for user " + userId + ":"); 18261 pw.println(); 18262 count = 0; 18263 for (PackageSetting ps : allPackageSettings) { 18264 final long status = ps.getDomainVerificationStatusForUser(userId); 18265 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18266 continue; 18267 } 18268 pw.println(prefix + "Package: " + ps.name); 18269 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18270 String statusStr = IntentFilterVerificationInfo. 18271 getStatusStringFromValue(status); 18272 pw.println(prefix + "Status: " + statusStr); 18273 pw.println(); 18274 count++; 18275 } 18276 if (count == 0) { 18277 pw.println(prefix + "No configured app linkages."); 18278 pw.println(); 18279 } 18280 } 18281 } 18282 } 18283 } 18284 18285 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18286 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18287 if (packageName == null && permissionNames == null) { 18288 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18289 if (iperm == 0) { 18290 if (dumpState.onTitlePrinted()) 18291 pw.println(); 18292 pw.println("AppOp Permissions:"); 18293 } 18294 pw.print(" AppOp Permission "); 18295 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18296 pw.println(":"); 18297 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18298 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18299 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18300 } 18301 } 18302 } 18303 } 18304 18305 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18306 boolean printedSomething = false; 18307 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18308 if (packageName != null && !packageName.equals(p.info.packageName)) { 18309 continue; 18310 } 18311 if (!printedSomething) { 18312 if (dumpState.onTitlePrinted()) 18313 pw.println(); 18314 pw.println("Registered ContentProviders:"); 18315 printedSomething = true; 18316 } 18317 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18318 pw.print(" "); pw.println(p.toString()); 18319 } 18320 printedSomething = false; 18321 for (Map.Entry<String, PackageParser.Provider> entry : 18322 mProvidersByAuthority.entrySet()) { 18323 PackageParser.Provider p = entry.getValue(); 18324 if (packageName != null && !packageName.equals(p.info.packageName)) { 18325 continue; 18326 } 18327 if (!printedSomething) { 18328 if (dumpState.onTitlePrinted()) 18329 pw.println(); 18330 pw.println("ContentProvider Authorities:"); 18331 printedSomething = true; 18332 } 18333 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18334 pw.print(" "); pw.println(p.toString()); 18335 if (p.info != null && p.info.applicationInfo != null) { 18336 final String appInfo = p.info.applicationInfo.toString(); 18337 pw.print(" applicationInfo="); pw.println(appInfo); 18338 } 18339 } 18340 } 18341 18342 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18343 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18344 } 18345 18346 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18347 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18348 } 18349 18350 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18351 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18352 } 18353 18354 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18355 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18356 } 18357 18358 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18359 // XXX should handle packageName != null by dumping only install data that 18360 // the given package is involved with. 18361 if (dumpState.onTitlePrinted()) pw.println(); 18362 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18363 } 18364 18365 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18366 // XXX should handle packageName != null by dumping only install data that 18367 // the given package is involved with. 18368 if (dumpState.onTitlePrinted()) pw.println(); 18369 18370 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18371 ipw.println(); 18372 ipw.println("Frozen packages:"); 18373 ipw.increaseIndent(); 18374 if (mFrozenPackages.size() == 0) { 18375 ipw.println("(none)"); 18376 } else { 18377 for (int i = 0; i < mFrozenPackages.size(); i++) { 18378 ipw.println(mFrozenPackages.valueAt(i)); 18379 } 18380 } 18381 ipw.decreaseIndent(); 18382 } 18383 18384 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18385 if (dumpState.onTitlePrinted()) pw.println(); 18386 dumpDexoptStateLPr(pw, packageName); 18387 } 18388 18389 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18390 if (dumpState.onTitlePrinted()) pw.println(); 18391 mSettings.dumpReadMessagesLPr(pw, dumpState); 18392 18393 pw.println(); 18394 pw.println("Package warning messages:"); 18395 BufferedReader in = null; 18396 String line = null; 18397 try { 18398 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18399 while ((line = in.readLine()) != null) { 18400 if (line.contains("ignored: updated version")) continue; 18401 pw.println(line); 18402 } 18403 } catch (IOException ignored) { 18404 } finally { 18405 IoUtils.closeQuietly(in); 18406 } 18407 } 18408 18409 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18410 BufferedReader in = null; 18411 String line = null; 18412 try { 18413 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18414 while ((line = in.readLine()) != null) { 18415 if (line.contains("ignored: updated version")) continue; 18416 pw.print("msg,"); 18417 pw.println(line); 18418 } 18419 } catch (IOException ignored) { 18420 } finally { 18421 IoUtils.closeQuietly(in); 18422 } 18423 } 18424 } 18425 } 18426 18427 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18428 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18429 ipw.println(); 18430 ipw.println("Dexopt state:"); 18431 ipw.increaseIndent(); 18432 Collection<PackageParser.Package> packages = null; 18433 if (packageName != null) { 18434 PackageParser.Package targetPackage = mPackages.get(packageName); 18435 if (targetPackage != null) { 18436 packages = Collections.singletonList(targetPackage); 18437 } else { 18438 ipw.println("Unable to find package: " + packageName); 18439 return; 18440 } 18441 } else { 18442 packages = mPackages.values(); 18443 } 18444 18445 for (PackageParser.Package pkg : packages) { 18446 ipw.println("[" + pkg.packageName + "]"); 18447 ipw.increaseIndent(); 18448 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18449 ipw.decreaseIndent(); 18450 } 18451 } 18452 18453 private String dumpDomainString(String packageName) { 18454 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18455 .getList(); 18456 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18457 18458 ArraySet<String> result = new ArraySet<>(); 18459 if (iviList.size() > 0) { 18460 for (IntentFilterVerificationInfo ivi : iviList) { 18461 for (String host : ivi.getDomains()) { 18462 result.add(host); 18463 } 18464 } 18465 } 18466 if (filters != null && filters.size() > 0) { 18467 for (IntentFilter filter : filters) { 18468 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18469 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18470 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18471 result.addAll(filter.getHostsList()); 18472 } 18473 } 18474 } 18475 18476 StringBuilder sb = new StringBuilder(result.size() * 16); 18477 for (String domain : result) { 18478 if (sb.length() > 0) sb.append(" "); 18479 sb.append(domain); 18480 } 18481 return sb.toString(); 18482 } 18483 18484 // ------- apps on sdcard specific code ------- 18485 static final boolean DEBUG_SD_INSTALL = false; 18486 18487 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18488 18489 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18490 18491 private boolean mMediaMounted = false; 18492 18493 static String getEncryptKey() { 18494 try { 18495 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18496 SD_ENCRYPTION_KEYSTORE_NAME); 18497 if (sdEncKey == null) { 18498 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18499 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18500 if (sdEncKey == null) { 18501 Slog.e(TAG, "Failed to create encryption keys"); 18502 return null; 18503 } 18504 } 18505 return sdEncKey; 18506 } catch (NoSuchAlgorithmException nsae) { 18507 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18508 return null; 18509 } catch (IOException ioe) { 18510 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18511 return null; 18512 } 18513 } 18514 18515 /* 18516 * Update media status on PackageManager. 18517 */ 18518 @Override 18519 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18520 int callingUid = Binder.getCallingUid(); 18521 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18522 throw new SecurityException("Media status can only be updated by the system"); 18523 } 18524 // reader; this apparently protects mMediaMounted, but should probably 18525 // be a different lock in that case. 18526 synchronized (mPackages) { 18527 Log.i(TAG, "Updating external media status from " 18528 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18529 + (mediaStatus ? "mounted" : "unmounted")); 18530 if (DEBUG_SD_INSTALL) 18531 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18532 + ", mMediaMounted=" + mMediaMounted); 18533 if (mediaStatus == mMediaMounted) { 18534 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18535 : 0, -1); 18536 mHandler.sendMessage(msg); 18537 return; 18538 } 18539 mMediaMounted = mediaStatus; 18540 } 18541 // Queue up an async operation since the package installation may take a 18542 // little while. 18543 mHandler.post(new Runnable() { 18544 public void run() { 18545 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18546 } 18547 }); 18548 } 18549 18550 /** 18551 * Called by MountService when the initial ASECs to scan are available. 18552 * Should block until all the ASEC containers are finished being scanned. 18553 */ 18554 public void scanAvailableAsecs() { 18555 updateExternalMediaStatusInner(true, false, false); 18556 } 18557 18558 /* 18559 * Collect information of applications on external media, map them against 18560 * existing containers and update information based on current mount status. 18561 * Please note that we always have to report status if reportStatus has been 18562 * set to true especially when unloading packages. 18563 */ 18564 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18565 boolean externalStorage) { 18566 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18567 int[] uidArr = EmptyArray.INT; 18568 18569 final String[] list = PackageHelper.getSecureContainerList(); 18570 if (ArrayUtils.isEmpty(list)) { 18571 Log.i(TAG, "No secure containers found"); 18572 } else { 18573 // Process list of secure containers and categorize them 18574 // as active or stale based on their package internal state. 18575 18576 // reader 18577 synchronized (mPackages) { 18578 for (String cid : list) { 18579 // Leave stages untouched for now; installer service owns them 18580 if (PackageInstallerService.isStageName(cid)) continue; 18581 18582 if (DEBUG_SD_INSTALL) 18583 Log.i(TAG, "Processing container " + cid); 18584 String pkgName = getAsecPackageName(cid); 18585 if (pkgName == null) { 18586 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18587 continue; 18588 } 18589 if (DEBUG_SD_INSTALL) 18590 Log.i(TAG, "Looking for pkg : " + pkgName); 18591 18592 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18593 if (ps == null) { 18594 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18595 continue; 18596 } 18597 18598 /* 18599 * Skip packages that are not external if we're unmounting 18600 * external storage. 18601 */ 18602 if (externalStorage && !isMounted && !isExternal(ps)) { 18603 continue; 18604 } 18605 18606 final AsecInstallArgs args = new AsecInstallArgs(cid, 18607 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18608 // The package status is changed only if the code path 18609 // matches between settings and the container id. 18610 if (ps.codePathString != null 18611 && ps.codePathString.startsWith(args.getCodePath())) { 18612 if (DEBUG_SD_INSTALL) { 18613 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18614 + " at code path: " + ps.codePathString); 18615 } 18616 18617 // We do have a valid package installed on sdcard 18618 processCids.put(args, ps.codePathString); 18619 final int uid = ps.appId; 18620 if (uid != -1) { 18621 uidArr = ArrayUtils.appendInt(uidArr, uid); 18622 } 18623 } else { 18624 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18625 + ps.codePathString); 18626 } 18627 } 18628 } 18629 18630 Arrays.sort(uidArr); 18631 } 18632 18633 // Process packages with valid entries. 18634 if (isMounted) { 18635 if (DEBUG_SD_INSTALL) 18636 Log.i(TAG, "Loading packages"); 18637 loadMediaPackages(processCids, uidArr, externalStorage); 18638 startCleaningPackages(); 18639 mInstallerService.onSecureContainersAvailable(); 18640 } else { 18641 if (DEBUG_SD_INSTALL) 18642 Log.i(TAG, "Unloading packages"); 18643 unloadMediaPackages(processCids, uidArr, reportStatus); 18644 } 18645 } 18646 18647 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18648 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18649 final int size = infos.size(); 18650 final String[] packageNames = new String[size]; 18651 final int[] packageUids = new int[size]; 18652 for (int i = 0; i < size; i++) { 18653 final ApplicationInfo info = infos.get(i); 18654 packageNames[i] = info.packageName; 18655 packageUids[i] = info.uid; 18656 } 18657 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18658 finishedReceiver); 18659 } 18660 18661 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18662 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18663 sendResourcesChangedBroadcast(mediaStatus, replacing, 18664 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18665 } 18666 18667 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18668 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18669 int size = pkgList.length; 18670 if (size > 0) { 18671 // Send broadcasts here 18672 Bundle extras = new Bundle(); 18673 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18674 if (uidArr != null) { 18675 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18676 } 18677 if (replacing) { 18678 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18679 } 18680 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18681 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18682 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18683 } 18684 } 18685 18686 /* 18687 * Look at potentially valid container ids from processCids If package 18688 * information doesn't match the one on record or package scanning fails, 18689 * the cid is added to list of removeCids. We currently don't delete stale 18690 * containers. 18691 */ 18692 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18693 boolean externalStorage) { 18694 ArrayList<String> pkgList = new ArrayList<String>(); 18695 Set<AsecInstallArgs> keys = processCids.keySet(); 18696 18697 for (AsecInstallArgs args : keys) { 18698 String codePath = processCids.get(args); 18699 if (DEBUG_SD_INSTALL) 18700 Log.i(TAG, "Loading container : " + args.cid); 18701 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18702 try { 18703 // Make sure there are no container errors first. 18704 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18705 Slog.e(TAG, "Failed to mount cid : " + args.cid 18706 + " when installing from sdcard"); 18707 continue; 18708 } 18709 // Check code path here. 18710 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18711 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18712 + " does not match one in settings " + codePath); 18713 continue; 18714 } 18715 // Parse package 18716 int parseFlags = mDefParseFlags; 18717 if (args.isExternalAsec()) { 18718 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18719 } 18720 if (args.isFwdLocked()) { 18721 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18722 } 18723 18724 synchronized (mInstallLock) { 18725 PackageParser.Package pkg = null; 18726 try { 18727 // Sadly we don't know the package name yet to freeze it 18728 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18729 SCAN_IGNORE_FROZEN, 0, null); 18730 } catch (PackageManagerException e) { 18731 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18732 } 18733 // Scan the package 18734 if (pkg != null) { 18735 /* 18736 * TODO why is the lock being held? doPostInstall is 18737 * called in other places without the lock. This needs 18738 * to be straightened out. 18739 */ 18740 // writer 18741 synchronized (mPackages) { 18742 retCode = PackageManager.INSTALL_SUCCEEDED; 18743 pkgList.add(pkg.packageName); 18744 // Post process args 18745 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18746 pkg.applicationInfo.uid); 18747 } 18748 } else { 18749 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18750 } 18751 } 18752 18753 } finally { 18754 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18755 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18756 } 18757 } 18758 } 18759 // writer 18760 synchronized (mPackages) { 18761 // If the platform SDK has changed since the last time we booted, 18762 // we need to re-grant app permission to catch any new ones that 18763 // appear. This is really a hack, and means that apps can in some 18764 // cases get permissions that the user didn't initially explicitly 18765 // allow... it would be nice to have some better way to handle 18766 // this situation. 18767 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18768 : mSettings.getInternalVersion(); 18769 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18770 : StorageManager.UUID_PRIVATE_INTERNAL; 18771 18772 int updateFlags = UPDATE_PERMISSIONS_ALL; 18773 if (ver.sdkVersion != mSdkVersion) { 18774 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18775 + mSdkVersion + "; regranting permissions for external"); 18776 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18777 } 18778 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18779 18780 // Yay, everything is now upgraded 18781 ver.forceCurrent(); 18782 18783 // can downgrade to reader 18784 // Persist settings 18785 mSettings.writeLPr(); 18786 } 18787 // Send a broadcast to let everyone know we are done processing 18788 if (pkgList.size() > 0) { 18789 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18790 } 18791 } 18792 18793 /* 18794 * Utility method to unload a list of specified containers 18795 */ 18796 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18797 // Just unmount all valid containers. 18798 for (AsecInstallArgs arg : cidArgs) { 18799 synchronized (mInstallLock) { 18800 arg.doPostDeleteLI(false); 18801 } 18802 } 18803 } 18804 18805 /* 18806 * Unload packages mounted on external media. This involves deleting package 18807 * data from internal structures, sending broadcasts about disabled packages, 18808 * gc'ing to free up references, unmounting all secure containers 18809 * corresponding to packages on external media, and posting a 18810 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18811 * that we always have to post this message if status has been requested no 18812 * matter what. 18813 */ 18814 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18815 final boolean reportStatus) { 18816 if (DEBUG_SD_INSTALL) 18817 Log.i(TAG, "unloading media packages"); 18818 ArrayList<String> pkgList = new ArrayList<String>(); 18819 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18820 final Set<AsecInstallArgs> keys = processCids.keySet(); 18821 for (AsecInstallArgs args : keys) { 18822 String pkgName = args.getPackageName(); 18823 if (DEBUG_SD_INSTALL) 18824 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18825 // Delete package internally 18826 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18827 synchronized (mInstallLock) { 18828 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18829 final boolean res; 18830 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18831 "unloadMediaPackages")) { 18832 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18833 null); 18834 } 18835 if (res) { 18836 pkgList.add(pkgName); 18837 } else { 18838 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18839 failedList.add(args); 18840 } 18841 } 18842 } 18843 18844 // reader 18845 synchronized (mPackages) { 18846 // We didn't update the settings after removing each package; 18847 // write them now for all packages. 18848 mSettings.writeLPr(); 18849 } 18850 18851 // We have to absolutely send UPDATED_MEDIA_STATUS only 18852 // after confirming that all the receivers processed the ordered 18853 // broadcast when packages get disabled, force a gc to clean things up. 18854 // and unload all the containers. 18855 if (pkgList.size() > 0) { 18856 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18857 new IIntentReceiver.Stub() { 18858 public void performReceive(Intent intent, int resultCode, String data, 18859 Bundle extras, boolean ordered, boolean sticky, 18860 int sendingUser) throws RemoteException { 18861 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18862 reportStatus ? 1 : 0, 1, keys); 18863 mHandler.sendMessage(msg); 18864 } 18865 }); 18866 } else { 18867 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18868 keys); 18869 mHandler.sendMessage(msg); 18870 } 18871 } 18872 18873 private void loadPrivatePackages(final VolumeInfo vol) { 18874 mHandler.post(new Runnable() { 18875 @Override 18876 public void run() { 18877 loadPrivatePackagesInner(vol); 18878 } 18879 }); 18880 } 18881 18882 private void loadPrivatePackagesInner(VolumeInfo vol) { 18883 final String volumeUuid = vol.fsUuid; 18884 if (TextUtils.isEmpty(volumeUuid)) { 18885 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18886 return; 18887 } 18888 18889 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18890 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18891 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18892 18893 final VersionInfo ver; 18894 final List<PackageSetting> packages; 18895 synchronized (mPackages) { 18896 ver = mSettings.findOrCreateVersion(volumeUuid); 18897 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18898 } 18899 18900 for (PackageSetting ps : packages) { 18901 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18902 synchronized (mInstallLock) { 18903 final PackageParser.Package pkg; 18904 try { 18905 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18906 loaded.add(pkg.applicationInfo); 18907 18908 } catch (PackageManagerException e) { 18909 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18910 } 18911 18912 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18913 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18914 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18915 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18916 } 18917 } 18918 } 18919 18920 // Reconcile app data for all started/unlocked users 18921 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18922 final UserManager um = mContext.getSystemService(UserManager.class); 18923 for (UserInfo user : um.getUsers()) { 18924 final int flags; 18925 if (um.isUserUnlockingOrUnlocked(user.id)) { 18926 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18927 } else if (um.isUserRunning(user.id)) { 18928 flags = StorageManager.FLAG_STORAGE_DE; 18929 } else { 18930 continue; 18931 } 18932 18933 try { 18934 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18935 synchronized (mInstallLock) { 18936 reconcileAppsDataLI(volumeUuid, user.id, flags); 18937 } 18938 } catch (IllegalStateException e) { 18939 // Device was probably ejected, and we'll process that event momentarily 18940 Slog.w(TAG, "Failed to prepare storage: " + e); 18941 } 18942 } 18943 18944 synchronized (mPackages) { 18945 int updateFlags = UPDATE_PERMISSIONS_ALL; 18946 if (ver.sdkVersion != mSdkVersion) { 18947 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18948 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18949 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18950 } 18951 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18952 18953 // Yay, everything is now upgraded 18954 ver.forceCurrent(); 18955 18956 mSettings.writeLPr(); 18957 } 18958 18959 for (PackageFreezer freezer : freezers) { 18960 freezer.close(); 18961 } 18962 18963 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18964 sendResourcesChangedBroadcast(true, false, loaded, null); 18965 } 18966 18967 private void unloadPrivatePackages(final VolumeInfo vol) { 18968 mHandler.post(new Runnable() { 18969 @Override 18970 public void run() { 18971 unloadPrivatePackagesInner(vol); 18972 } 18973 }); 18974 } 18975 18976 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18977 final String volumeUuid = vol.fsUuid; 18978 if (TextUtils.isEmpty(volumeUuid)) { 18979 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18980 return; 18981 } 18982 18983 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18984 synchronized (mInstallLock) { 18985 synchronized (mPackages) { 18986 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18987 for (PackageSetting ps : packages) { 18988 if (ps.pkg == null) continue; 18989 18990 final ApplicationInfo info = ps.pkg.applicationInfo; 18991 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18992 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18993 18994 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18995 "unloadPrivatePackagesInner")) { 18996 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18997 false, null)) { 18998 unloaded.add(info); 18999 } else { 19000 Slog.w(TAG, "Failed to unload " + ps.codePath); 19001 } 19002 } 19003 } 19004 19005 mSettings.writeLPr(); 19006 } 19007 } 19008 19009 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19010 sendResourcesChangedBroadcast(false, false, unloaded, null); 19011 } 19012 19013 /** 19014 * Prepare storage areas for given user on all mounted devices. 19015 */ 19016 void prepareUserData(int userId, int userSerial, int flags) { 19017 synchronized (mInstallLock) { 19018 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19019 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19020 final String volumeUuid = vol.getFsUuid(); 19021 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19022 } 19023 } 19024 } 19025 19026 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19027 boolean allowRecover) { 19028 // Prepare storage and verify that serial numbers are consistent; if 19029 // there's a mismatch we need to destroy to avoid leaking data 19030 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19031 try { 19032 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19033 19034 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19035 UserManagerService.enforceSerialNumber( 19036 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19037 } 19038 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19039 UserManagerService.enforceSerialNumber( 19040 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19041 } 19042 19043 synchronized (mInstallLock) { 19044 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19045 } 19046 } catch (Exception e) { 19047 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19048 + " because we failed to prepare: " + e); 19049 destroyUserDataLI(volumeUuid, userId, 19050 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19051 19052 if (allowRecover) { 19053 // Try one last time; if we fail again we're really in trouble 19054 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19055 } 19056 } 19057 } 19058 19059 /** 19060 * Destroy storage areas for given user on all mounted devices. 19061 */ 19062 void destroyUserData(int userId, int flags) { 19063 synchronized (mInstallLock) { 19064 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19065 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19066 final String volumeUuid = vol.getFsUuid(); 19067 destroyUserDataLI(volumeUuid, userId, flags); 19068 } 19069 } 19070 } 19071 19072 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19073 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19074 try { 19075 // Clean up app data, profile data, and media data 19076 mInstaller.destroyUserData(volumeUuid, userId, flags); 19077 19078 // Clean up system data 19079 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19080 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19081 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19082 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19083 } 19084 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19085 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19086 } 19087 } 19088 19089 // Data with special labels is now gone, so finish the job 19090 storage.destroyUserStorage(volumeUuid, userId, flags); 19091 19092 } catch (Exception e) { 19093 logCriticalInfo(Log.WARN, 19094 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19095 } 19096 } 19097 19098 /** 19099 * Examine all users present on given mounted volume, and destroy data 19100 * belonging to users that are no longer valid, or whose user ID has been 19101 * recycled. 19102 */ 19103 private void reconcileUsers(String volumeUuid) { 19104 final List<File> files = new ArrayList<>(); 19105 Collections.addAll(files, FileUtils 19106 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19107 Collections.addAll(files, FileUtils 19108 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19109 for (File file : files) { 19110 if (!file.isDirectory()) continue; 19111 19112 final int userId; 19113 final UserInfo info; 19114 try { 19115 userId = Integer.parseInt(file.getName()); 19116 info = sUserManager.getUserInfo(userId); 19117 } catch (NumberFormatException e) { 19118 Slog.w(TAG, "Invalid user directory " + file); 19119 continue; 19120 } 19121 19122 boolean destroyUser = false; 19123 if (info == null) { 19124 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19125 + " because no matching user was found"); 19126 destroyUser = true; 19127 } else if (!mOnlyCore) { 19128 try { 19129 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19130 } catch (IOException e) { 19131 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19132 + " because we failed to enforce serial number: " + e); 19133 destroyUser = true; 19134 } 19135 } 19136 19137 if (destroyUser) { 19138 synchronized (mInstallLock) { 19139 destroyUserDataLI(volumeUuid, userId, 19140 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19141 } 19142 } 19143 } 19144 } 19145 19146 private void assertPackageKnown(String volumeUuid, String packageName) 19147 throws PackageManagerException { 19148 synchronized (mPackages) { 19149 final PackageSetting ps = mSettings.mPackages.get(packageName); 19150 if (ps == null) { 19151 throw new PackageManagerException("Package " + packageName + " is unknown"); 19152 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19153 throw new PackageManagerException( 19154 "Package " + packageName + " found on unknown volume " + volumeUuid 19155 + "; expected volume " + ps.volumeUuid); 19156 } 19157 } 19158 } 19159 19160 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19161 throws PackageManagerException { 19162 synchronized (mPackages) { 19163 final PackageSetting ps = mSettings.mPackages.get(packageName); 19164 if (ps == null) { 19165 throw new PackageManagerException("Package " + packageName + " is unknown"); 19166 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19167 throw new PackageManagerException( 19168 "Package " + packageName + " found on unknown volume " + volumeUuid 19169 + "; expected volume " + ps.volumeUuid); 19170 } else if (!ps.getInstalled(userId)) { 19171 throw new PackageManagerException( 19172 "Package " + packageName + " not installed for user " + userId); 19173 } 19174 } 19175 } 19176 19177 /** 19178 * Examine all apps present on given mounted volume, and destroy apps that 19179 * aren't expected, either due to uninstallation or reinstallation on 19180 * another volume. 19181 */ 19182 private void reconcileApps(String volumeUuid) { 19183 final File[] files = FileUtils 19184 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19185 for (File file : files) { 19186 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19187 && !PackageInstallerService.isStageName(file.getName()); 19188 if (!isPackage) { 19189 // Ignore entries which are not packages 19190 continue; 19191 } 19192 19193 try { 19194 final PackageLite pkg = PackageParser.parsePackageLite(file, 19195 PackageParser.PARSE_MUST_BE_APK); 19196 assertPackageKnown(volumeUuid, pkg.packageName); 19197 19198 } catch (PackageParserException | PackageManagerException e) { 19199 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19200 synchronized (mInstallLock) { 19201 removeCodePathLI(file); 19202 } 19203 } 19204 } 19205 } 19206 19207 /** 19208 * Reconcile all app data for the given user. 19209 * <p> 19210 * Verifies that directories exist and that ownership and labeling is 19211 * correct for all installed apps on all mounted volumes. 19212 */ 19213 void reconcileAppsData(int userId, int flags) { 19214 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19215 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19216 final String volumeUuid = vol.getFsUuid(); 19217 synchronized (mInstallLock) { 19218 reconcileAppsDataLI(volumeUuid, userId, flags); 19219 } 19220 } 19221 } 19222 19223 /** 19224 * Reconcile all app data on given mounted volume. 19225 * <p> 19226 * Destroys app data that isn't expected, either due to uninstallation or 19227 * reinstallation on another volume. 19228 * <p> 19229 * Verifies that directories exist and that ownership and labeling is 19230 * correct for all installed apps. 19231 */ 19232 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19233 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19234 + Integer.toHexString(flags)); 19235 19236 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19237 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19238 19239 boolean restoreconNeeded = false; 19240 19241 // First look for stale data that doesn't belong, and check if things 19242 // have changed since we did our last restorecon 19243 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19244 if (StorageManager.isFileEncryptedNativeOrEmulated() 19245 && !StorageManager.isUserKeyUnlocked(userId)) { 19246 throw new RuntimeException( 19247 "Yikes, someone asked us to reconcile CE storage while " + userId 19248 + " was still locked; this would have caused massive data loss!"); 19249 } 19250 19251 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19252 19253 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19254 for (File file : files) { 19255 final String packageName = file.getName(); 19256 try { 19257 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19258 } catch (PackageManagerException e) { 19259 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19260 try { 19261 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19262 StorageManager.FLAG_STORAGE_CE, 0); 19263 } catch (InstallerException e2) { 19264 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19265 } 19266 } 19267 } 19268 } 19269 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19270 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19271 19272 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19273 for (File file : files) { 19274 final String packageName = file.getName(); 19275 try { 19276 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19277 } catch (PackageManagerException e) { 19278 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19279 try { 19280 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19281 StorageManager.FLAG_STORAGE_DE, 0); 19282 } catch (InstallerException e2) { 19283 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19284 } 19285 } 19286 } 19287 } 19288 19289 // Ensure that data directories are ready to roll for all packages 19290 // installed for this volume and user 19291 final List<PackageSetting> packages; 19292 synchronized (mPackages) { 19293 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19294 } 19295 int preparedCount = 0; 19296 for (PackageSetting ps : packages) { 19297 final String packageName = ps.name; 19298 if (ps.pkg == null) { 19299 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19300 // TODO: might be due to legacy ASEC apps; we should circle back 19301 // and reconcile again once they're scanned 19302 continue; 19303 } 19304 19305 if (ps.getInstalled(userId)) { 19306 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19307 19308 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19309 // We may have just shuffled around app data directories, so 19310 // prepare them one more time 19311 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19312 } 19313 19314 preparedCount++; 19315 } 19316 } 19317 19318 if (restoreconNeeded) { 19319 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19320 SELinuxMMAC.setRestoreconDone(ceDir); 19321 } 19322 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19323 SELinuxMMAC.setRestoreconDone(deDir); 19324 } 19325 } 19326 19327 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19328 + " packages; restoreconNeeded was " + restoreconNeeded); 19329 } 19330 19331 /** 19332 * Prepare app data for the given app just after it was installed or 19333 * upgraded. This method carefully only touches users that it's installed 19334 * for, and it forces a restorecon to handle any seinfo changes. 19335 * <p> 19336 * Verifies that directories exist and that ownership and labeling is 19337 * correct for all installed apps. If there is an ownership mismatch, it 19338 * will try recovering system apps by wiping data; third-party app data is 19339 * left intact. 19340 * <p> 19341 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19342 */ 19343 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19344 final PackageSetting ps; 19345 synchronized (mPackages) { 19346 ps = mSettings.mPackages.get(pkg.packageName); 19347 mSettings.writeKernelMappingLPr(ps); 19348 } 19349 19350 final UserManager um = mContext.getSystemService(UserManager.class); 19351 for (UserInfo user : um.getUsers()) { 19352 final int flags; 19353 if (um.isUserUnlockingOrUnlocked(user.id)) { 19354 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19355 } else if (um.isUserRunning(user.id)) { 19356 flags = StorageManager.FLAG_STORAGE_DE; 19357 } else { 19358 continue; 19359 } 19360 19361 if (ps.getInstalled(user.id)) { 19362 // Whenever an app changes, force a restorecon of its data 19363 // TODO: when user data is locked, mark that we're still dirty 19364 prepareAppDataLIF(pkg, user.id, flags, true); 19365 } 19366 } 19367 } 19368 19369 /** 19370 * Prepare app data for the given app. 19371 * <p> 19372 * Verifies that directories exist and that ownership and labeling is 19373 * correct for all installed apps. If there is an ownership mismatch, this 19374 * will try recovering system apps by wiping data; third-party app data is 19375 * left intact. 19376 */ 19377 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19378 boolean restoreconNeeded) { 19379 if (pkg == null) { 19380 Slog.wtf(TAG, "Package was null!", new Throwable()); 19381 return; 19382 } 19383 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19384 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19385 for (int i = 0; i < childCount; i++) { 19386 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19387 } 19388 } 19389 19390 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19391 boolean restoreconNeeded) { 19392 if (DEBUG_APP_DATA) { 19393 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19394 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19395 } 19396 19397 final String volumeUuid = pkg.volumeUuid; 19398 final String packageName = pkg.packageName; 19399 final ApplicationInfo app = pkg.applicationInfo; 19400 final int appId = UserHandle.getAppId(app.uid); 19401 19402 Preconditions.checkNotNull(app.seinfo); 19403 19404 try { 19405 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19406 appId, app.seinfo, app.targetSdkVersion); 19407 } catch (InstallerException e) { 19408 if (app.isSystemApp()) { 19409 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19410 + ", but trying to recover: " + e); 19411 destroyAppDataLeafLIF(pkg, userId, flags); 19412 try { 19413 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19414 appId, app.seinfo, app.targetSdkVersion); 19415 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19416 } catch (InstallerException e2) { 19417 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19418 } 19419 } else { 19420 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19421 } 19422 } 19423 19424 if (restoreconNeeded) { 19425 try { 19426 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19427 app.seinfo); 19428 } catch (InstallerException e) { 19429 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19430 } 19431 } 19432 19433 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19434 try { 19435 // CE storage is unlocked right now, so read out the inode and 19436 // remember for use later when it's locked 19437 // TODO: mark this structure as dirty so we persist it! 19438 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19439 StorageManager.FLAG_STORAGE_CE); 19440 synchronized (mPackages) { 19441 final PackageSetting ps = mSettings.mPackages.get(packageName); 19442 if (ps != null) { 19443 ps.setCeDataInode(ceDataInode, userId); 19444 } 19445 } 19446 } catch (InstallerException e) { 19447 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19448 } 19449 } 19450 19451 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19452 } 19453 19454 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19455 if (pkg == null) { 19456 Slog.wtf(TAG, "Package was null!", new Throwable()); 19457 return; 19458 } 19459 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19460 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19461 for (int i = 0; i < childCount; i++) { 19462 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19463 } 19464 } 19465 19466 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19467 final String volumeUuid = pkg.volumeUuid; 19468 final String packageName = pkg.packageName; 19469 final ApplicationInfo app = pkg.applicationInfo; 19470 19471 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19472 // Create a native library symlink only if we have native libraries 19473 // and if the native libraries are 32 bit libraries. We do not provide 19474 // this symlink for 64 bit libraries. 19475 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19476 final String nativeLibPath = app.nativeLibraryDir; 19477 try { 19478 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19479 nativeLibPath, userId); 19480 } catch (InstallerException e) { 19481 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19482 } 19483 } 19484 } 19485 } 19486 19487 /** 19488 * For system apps on non-FBE devices, this method migrates any existing 19489 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19490 * requested by the app. 19491 */ 19492 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19493 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19494 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19495 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19496 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19497 try { 19498 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19499 storageTarget); 19500 } catch (InstallerException e) { 19501 logCriticalInfo(Log.WARN, 19502 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19503 } 19504 return true; 19505 } else { 19506 return false; 19507 } 19508 } 19509 19510 public PackageFreezer freezePackage(String packageName, String killReason) { 19511 return new PackageFreezer(packageName, killReason); 19512 } 19513 19514 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19515 String killReason) { 19516 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19517 return new PackageFreezer(); 19518 } else { 19519 return freezePackage(packageName, killReason); 19520 } 19521 } 19522 19523 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19524 String killReason) { 19525 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19526 return new PackageFreezer(); 19527 } else { 19528 return freezePackage(packageName, killReason); 19529 } 19530 } 19531 19532 /** 19533 * Class that freezes and kills the given package upon creation, and 19534 * unfreezes it upon closing. This is typically used when doing surgery on 19535 * app code/data to prevent the app from running while you're working. 19536 */ 19537 private class PackageFreezer implements AutoCloseable { 19538 private final String mPackageName; 19539 private final PackageFreezer[] mChildren; 19540 19541 private final boolean mWeFroze; 19542 19543 private final AtomicBoolean mClosed = new AtomicBoolean(); 19544 private final CloseGuard mCloseGuard = CloseGuard.get(); 19545 19546 /** 19547 * Create and return a stub freezer that doesn't actually do anything, 19548 * typically used when someone requested 19549 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19550 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19551 */ 19552 public PackageFreezer() { 19553 mPackageName = null; 19554 mChildren = null; 19555 mWeFroze = false; 19556 mCloseGuard.open("close"); 19557 } 19558 19559 public PackageFreezer(String packageName, String killReason) { 19560 synchronized (mPackages) { 19561 mPackageName = packageName; 19562 mWeFroze = mFrozenPackages.add(mPackageName); 19563 19564 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19565 if (ps != null) { 19566 killApplication(ps.name, ps.appId, killReason); 19567 } 19568 19569 final PackageParser.Package p = mPackages.get(packageName); 19570 if (p != null && p.childPackages != null) { 19571 final int N = p.childPackages.size(); 19572 mChildren = new PackageFreezer[N]; 19573 for (int i = 0; i < N; i++) { 19574 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19575 killReason); 19576 } 19577 } else { 19578 mChildren = null; 19579 } 19580 } 19581 mCloseGuard.open("close"); 19582 } 19583 19584 @Override 19585 protected void finalize() throws Throwable { 19586 try { 19587 mCloseGuard.warnIfOpen(); 19588 close(); 19589 } finally { 19590 super.finalize(); 19591 } 19592 } 19593 19594 @Override 19595 public void close() { 19596 mCloseGuard.close(); 19597 if (mClosed.compareAndSet(false, true)) { 19598 synchronized (mPackages) { 19599 if (mWeFroze) { 19600 mFrozenPackages.remove(mPackageName); 19601 } 19602 19603 if (mChildren != null) { 19604 for (PackageFreezer freezer : mChildren) { 19605 freezer.close(); 19606 } 19607 } 19608 } 19609 } 19610 } 19611 } 19612 19613 /** 19614 * Verify that given package is currently frozen. 19615 */ 19616 private void checkPackageFrozen(String packageName) { 19617 synchronized (mPackages) { 19618 if (!mFrozenPackages.contains(packageName)) { 19619 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19620 } 19621 } 19622 } 19623 19624 @Override 19625 public int movePackage(final String packageName, final String volumeUuid) { 19626 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19627 19628 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19629 final int moveId = mNextMoveId.getAndIncrement(); 19630 mHandler.post(new Runnable() { 19631 @Override 19632 public void run() { 19633 try { 19634 movePackageInternal(packageName, volumeUuid, moveId, user); 19635 } catch (PackageManagerException e) { 19636 Slog.w(TAG, "Failed to move " + packageName, e); 19637 mMoveCallbacks.notifyStatusChanged(moveId, 19638 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19639 } 19640 } 19641 }); 19642 return moveId; 19643 } 19644 19645 private void movePackageInternal(final String packageName, final String volumeUuid, 19646 final int moveId, UserHandle user) throws PackageManagerException { 19647 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19648 final PackageManager pm = mContext.getPackageManager(); 19649 19650 final boolean currentAsec; 19651 final String currentVolumeUuid; 19652 final File codeFile; 19653 final String installerPackageName; 19654 final String packageAbiOverride; 19655 final int appId; 19656 final String seinfo; 19657 final String label; 19658 final int targetSdkVersion; 19659 final PackageFreezer freezer; 19660 final int[] installedUserIds; 19661 19662 // reader 19663 synchronized (mPackages) { 19664 final PackageParser.Package pkg = mPackages.get(packageName); 19665 final PackageSetting ps = mSettings.mPackages.get(packageName); 19666 if (pkg == null || ps == null) { 19667 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19668 } 19669 19670 if (pkg.applicationInfo.isSystemApp()) { 19671 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19672 "Cannot move system application"); 19673 } 19674 19675 if (pkg.applicationInfo.isExternalAsec()) { 19676 currentAsec = true; 19677 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19678 } else if (pkg.applicationInfo.isForwardLocked()) { 19679 currentAsec = true; 19680 currentVolumeUuid = "forward_locked"; 19681 } else { 19682 currentAsec = false; 19683 currentVolumeUuid = ps.volumeUuid; 19684 19685 final File probe = new File(pkg.codePath); 19686 final File probeOat = new File(probe, "oat"); 19687 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19688 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19689 "Move only supported for modern cluster style installs"); 19690 } 19691 } 19692 19693 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19694 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19695 "Package already moved to " + volumeUuid); 19696 } 19697 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19698 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19699 "Device admin cannot be moved"); 19700 } 19701 19702 if (mFrozenPackages.contains(packageName)) { 19703 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19704 "Failed to move already frozen package"); 19705 } 19706 19707 codeFile = new File(pkg.codePath); 19708 installerPackageName = ps.installerPackageName; 19709 packageAbiOverride = ps.cpuAbiOverrideString; 19710 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19711 seinfo = pkg.applicationInfo.seinfo; 19712 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19713 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19714 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19715 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19716 } 19717 19718 final Bundle extras = new Bundle(); 19719 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19720 extras.putString(Intent.EXTRA_TITLE, label); 19721 mMoveCallbacks.notifyCreated(moveId, extras); 19722 19723 int installFlags; 19724 final boolean moveCompleteApp; 19725 final File measurePath; 19726 19727 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19728 installFlags = INSTALL_INTERNAL; 19729 moveCompleteApp = !currentAsec; 19730 measurePath = Environment.getDataAppDirectory(volumeUuid); 19731 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19732 installFlags = INSTALL_EXTERNAL; 19733 moveCompleteApp = false; 19734 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19735 } else { 19736 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19737 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19738 || !volume.isMountedWritable()) { 19739 freezer.close(); 19740 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19741 "Move location not mounted private volume"); 19742 } 19743 19744 Preconditions.checkState(!currentAsec); 19745 19746 installFlags = INSTALL_INTERNAL; 19747 moveCompleteApp = true; 19748 measurePath = Environment.getDataAppDirectory(volumeUuid); 19749 } 19750 19751 final PackageStats stats = new PackageStats(null, -1); 19752 synchronized (mInstaller) { 19753 for (int userId : installedUserIds) { 19754 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19755 freezer.close(); 19756 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19757 "Failed to measure package size"); 19758 } 19759 } 19760 } 19761 19762 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19763 + stats.dataSize); 19764 19765 final long startFreeBytes = measurePath.getFreeSpace(); 19766 final long sizeBytes; 19767 if (moveCompleteApp) { 19768 sizeBytes = stats.codeSize + stats.dataSize; 19769 } else { 19770 sizeBytes = stats.codeSize; 19771 } 19772 19773 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19774 freezer.close(); 19775 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19776 "Not enough free space to move"); 19777 } 19778 19779 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19780 19781 final CountDownLatch installedLatch = new CountDownLatch(1); 19782 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19783 @Override 19784 public void onUserActionRequired(Intent intent) throws RemoteException { 19785 throw new IllegalStateException(); 19786 } 19787 19788 @Override 19789 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19790 Bundle extras) throws RemoteException { 19791 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19792 + PackageManager.installStatusToString(returnCode, msg)); 19793 19794 installedLatch.countDown(); 19795 freezer.close(); 19796 19797 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19798 switch (status) { 19799 case PackageInstaller.STATUS_SUCCESS: 19800 mMoveCallbacks.notifyStatusChanged(moveId, 19801 PackageManager.MOVE_SUCCEEDED); 19802 break; 19803 case PackageInstaller.STATUS_FAILURE_STORAGE: 19804 mMoveCallbacks.notifyStatusChanged(moveId, 19805 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19806 break; 19807 default: 19808 mMoveCallbacks.notifyStatusChanged(moveId, 19809 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19810 break; 19811 } 19812 } 19813 }; 19814 19815 final MoveInfo move; 19816 if (moveCompleteApp) { 19817 // Kick off a thread to report progress estimates 19818 new Thread() { 19819 @Override 19820 public void run() { 19821 while (true) { 19822 try { 19823 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19824 break; 19825 } 19826 } catch (InterruptedException ignored) { 19827 } 19828 19829 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19830 final int progress = 10 + (int) MathUtils.constrain( 19831 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19832 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19833 } 19834 } 19835 }.start(); 19836 19837 final String dataAppName = codeFile.getName(); 19838 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19839 dataAppName, appId, seinfo, targetSdkVersion); 19840 } else { 19841 move = null; 19842 } 19843 19844 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19845 19846 final Message msg = mHandler.obtainMessage(INIT_COPY); 19847 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19848 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19849 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19850 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19851 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19852 msg.obj = params; 19853 19854 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19855 System.identityHashCode(msg.obj)); 19856 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19857 System.identityHashCode(msg.obj)); 19858 19859 mHandler.sendMessage(msg); 19860 } 19861 19862 @Override 19863 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19864 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19865 19866 final int realMoveId = mNextMoveId.getAndIncrement(); 19867 final Bundle extras = new Bundle(); 19868 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19869 mMoveCallbacks.notifyCreated(realMoveId, extras); 19870 19871 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19872 @Override 19873 public void onCreated(int moveId, Bundle extras) { 19874 // Ignored 19875 } 19876 19877 @Override 19878 public void onStatusChanged(int moveId, int status, long estMillis) { 19879 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19880 } 19881 }; 19882 19883 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19884 storage.setPrimaryStorageUuid(volumeUuid, callback); 19885 return realMoveId; 19886 } 19887 19888 @Override 19889 public int getMoveStatus(int moveId) { 19890 mContext.enforceCallingOrSelfPermission( 19891 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19892 return mMoveCallbacks.mLastStatus.get(moveId); 19893 } 19894 19895 @Override 19896 public void registerMoveCallback(IPackageMoveObserver callback) { 19897 mContext.enforceCallingOrSelfPermission( 19898 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19899 mMoveCallbacks.register(callback); 19900 } 19901 19902 @Override 19903 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19904 mContext.enforceCallingOrSelfPermission( 19905 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19906 mMoveCallbacks.unregister(callback); 19907 } 19908 19909 @Override 19910 public boolean setInstallLocation(int loc) { 19911 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19912 null); 19913 if (getInstallLocation() == loc) { 19914 return true; 19915 } 19916 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19917 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19918 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19919 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19920 return true; 19921 } 19922 return false; 19923 } 19924 19925 @Override 19926 public int getInstallLocation() { 19927 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19928 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19929 PackageHelper.APP_INSTALL_AUTO); 19930 } 19931 19932 /** Called by UserManagerService */ 19933 void cleanUpUser(UserManagerService userManager, int userHandle) { 19934 synchronized (mPackages) { 19935 mDirtyUsers.remove(userHandle); 19936 mUserNeedsBadging.delete(userHandle); 19937 mSettings.removeUserLPw(userHandle); 19938 mPendingBroadcasts.remove(userHandle); 19939 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19940 removeUnusedPackagesLPw(userManager, userHandle); 19941 } 19942 } 19943 19944 /** 19945 * We're removing userHandle and would like to remove any downloaded packages 19946 * that are no longer in use by any other user. 19947 * @param userHandle the user being removed 19948 */ 19949 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19950 final boolean DEBUG_CLEAN_APKS = false; 19951 int [] users = userManager.getUserIds(); 19952 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19953 while (psit.hasNext()) { 19954 PackageSetting ps = psit.next(); 19955 if (ps.pkg == null) { 19956 continue; 19957 } 19958 final String packageName = ps.pkg.packageName; 19959 // Skip over if system app 19960 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19961 continue; 19962 } 19963 if (DEBUG_CLEAN_APKS) { 19964 Slog.i(TAG, "Checking package " + packageName); 19965 } 19966 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19967 if (keep) { 19968 if (DEBUG_CLEAN_APKS) { 19969 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19970 } 19971 } else { 19972 for (int i = 0; i < users.length; i++) { 19973 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19974 keep = true; 19975 if (DEBUG_CLEAN_APKS) { 19976 Slog.i(TAG, " Keeping package " + packageName + " for user " 19977 + users[i]); 19978 } 19979 break; 19980 } 19981 } 19982 } 19983 if (!keep) { 19984 if (DEBUG_CLEAN_APKS) { 19985 Slog.i(TAG, " Removing package " + packageName); 19986 } 19987 mHandler.post(new Runnable() { 19988 public void run() { 19989 deletePackageX(packageName, userHandle, 0); 19990 } //end run 19991 }); 19992 } 19993 } 19994 } 19995 19996 /** Called by UserManagerService */ 19997 void createNewUser(int userHandle) { 19998 synchronized (mInstallLock) { 19999 mSettings.createNewUserLI(this, mInstaller, userHandle); 20000 } 20001 synchronized (mPackages) { 20002 applyFactoryDefaultBrowserLPw(userHandle); 20003 primeDomainVerificationsLPw(userHandle); 20004 } 20005 } 20006 20007 void newUserCreated(final int userHandle) { 20008 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20009 // If permission review for legacy apps is required, we represent 20010 // dagerous permissions for such apps as always granted runtime 20011 // permissions to keep per user flag state whether review is needed. 20012 // Hence, if a new user is added we have to propagate dangerous 20013 // permission grants for these legacy apps. 20014 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20015 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20016 | UPDATE_PERMISSIONS_REPLACE_ALL); 20017 } 20018 } 20019 20020 @Override 20021 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20022 mContext.enforceCallingOrSelfPermission( 20023 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20024 "Only package verification agents can read the verifier device identity"); 20025 20026 synchronized (mPackages) { 20027 return mSettings.getVerifierDeviceIdentityLPw(); 20028 } 20029 } 20030 20031 @Override 20032 public void setPermissionEnforced(String permission, boolean enforced) { 20033 // TODO: Now that we no longer change GID for storage, this should to away. 20034 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20035 "setPermissionEnforced"); 20036 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20037 synchronized (mPackages) { 20038 if (mSettings.mReadExternalStorageEnforced == null 20039 || mSettings.mReadExternalStorageEnforced != enforced) { 20040 mSettings.mReadExternalStorageEnforced = enforced; 20041 mSettings.writeLPr(); 20042 } 20043 } 20044 // kill any non-foreground processes so we restart them and 20045 // grant/revoke the GID. 20046 final IActivityManager am = ActivityManagerNative.getDefault(); 20047 if (am != null) { 20048 final long token = Binder.clearCallingIdentity(); 20049 try { 20050 am.killProcessesBelowForeground("setPermissionEnforcement"); 20051 } catch (RemoteException e) { 20052 } finally { 20053 Binder.restoreCallingIdentity(token); 20054 } 20055 } 20056 } else { 20057 throw new IllegalArgumentException("No selective enforcement for " + permission); 20058 } 20059 } 20060 20061 @Override 20062 @Deprecated 20063 public boolean isPermissionEnforced(String permission) { 20064 return true; 20065 } 20066 20067 @Override 20068 public boolean isStorageLow() { 20069 final long token = Binder.clearCallingIdentity(); 20070 try { 20071 final DeviceStorageMonitorInternal 20072 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20073 if (dsm != null) { 20074 return dsm.isMemoryLow(); 20075 } else { 20076 return false; 20077 } 20078 } finally { 20079 Binder.restoreCallingIdentity(token); 20080 } 20081 } 20082 20083 @Override 20084 public IPackageInstaller getPackageInstaller() { 20085 return mInstallerService; 20086 } 20087 20088 private boolean userNeedsBadging(int userId) { 20089 int index = mUserNeedsBadging.indexOfKey(userId); 20090 if (index < 0) { 20091 final UserInfo userInfo; 20092 final long token = Binder.clearCallingIdentity(); 20093 try { 20094 userInfo = sUserManager.getUserInfo(userId); 20095 } finally { 20096 Binder.restoreCallingIdentity(token); 20097 } 20098 final boolean b; 20099 if (userInfo != null && userInfo.isManagedProfile()) { 20100 b = true; 20101 } else { 20102 b = false; 20103 } 20104 mUserNeedsBadging.put(userId, b); 20105 return b; 20106 } 20107 return mUserNeedsBadging.valueAt(index); 20108 } 20109 20110 @Override 20111 public KeySet getKeySetByAlias(String packageName, String alias) { 20112 if (packageName == null || alias == null) { 20113 return null; 20114 } 20115 synchronized(mPackages) { 20116 final PackageParser.Package pkg = mPackages.get(packageName); 20117 if (pkg == null) { 20118 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20119 throw new IllegalArgumentException("Unknown package: " + packageName); 20120 } 20121 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20122 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20123 } 20124 } 20125 20126 @Override 20127 public KeySet getSigningKeySet(String packageName) { 20128 if (packageName == null) { 20129 return null; 20130 } 20131 synchronized(mPackages) { 20132 final PackageParser.Package pkg = mPackages.get(packageName); 20133 if (pkg == null) { 20134 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20135 throw new IllegalArgumentException("Unknown package: " + packageName); 20136 } 20137 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20138 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20139 throw new SecurityException("May not access signing KeySet of other apps."); 20140 } 20141 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20142 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20143 } 20144 } 20145 20146 @Override 20147 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20148 if (packageName == null || ks == null) { 20149 return false; 20150 } 20151 synchronized(mPackages) { 20152 final PackageParser.Package pkg = mPackages.get(packageName); 20153 if (pkg == null) { 20154 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20155 throw new IllegalArgumentException("Unknown package: " + packageName); 20156 } 20157 IBinder ksh = ks.getToken(); 20158 if (ksh instanceof KeySetHandle) { 20159 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20160 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20161 } 20162 return false; 20163 } 20164 } 20165 20166 @Override 20167 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20168 if (packageName == null || ks == null) { 20169 return false; 20170 } 20171 synchronized(mPackages) { 20172 final PackageParser.Package pkg = mPackages.get(packageName); 20173 if (pkg == null) { 20174 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20175 throw new IllegalArgumentException("Unknown package: " + packageName); 20176 } 20177 IBinder ksh = ks.getToken(); 20178 if (ksh instanceof KeySetHandle) { 20179 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20180 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20181 } 20182 return false; 20183 } 20184 } 20185 20186 private void deletePackageIfUnusedLPr(final String packageName) { 20187 PackageSetting ps = mSettings.mPackages.get(packageName); 20188 if (ps == null) { 20189 return; 20190 } 20191 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20192 // TODO Implement atomic delete if package is unused 20193 // It is currently possible that the package will be deleted even if it is installed 20194 // after this method returns. 20195 mHandler.post(new Runnable() { 20196 public void run() { 20197 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20198 } 20199 }); 20200 } 20201 } 20202 20203 /** 20204 * Check and throw if the given before/after packages would be considered a 20205 * downgrade. 20206 */ 20207 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20208 throws PackageManagerException { 20209 if (after.versionCode < before.mVersionCode) { 20210 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20211 "Update version code " + after.versionCode + " is older than current " 20212 + before.mVersionCode); 20213 } else if (after.versionCode == before.mVersionCode) { 20214 if (after.baseRevisionCode < before.baseRevisionCode) { 20215 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20216 "Update base revision code " + after.baseRevisionCode 20217 + " is older than current " + before.baseRevisionCode); 20218 } 20219 20220 if (!ArrayUtils.isEmpty(after.splitNames)) { 20221 for (int i = 0; i < after.splitNames.length; i++) { 20222 final String splitName = after.splitNames[i]; 20223 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20224 if (j != -1) { 20225 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20226 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20227 "Update split " + splitName + " revision code " 20228 + after.splitRevisionCodes[i] + " is older than current " 20229 + before.splitRevisionCodes[j]); 20230 } 20231 } 20232 } 20233 } 20234 } 20235 } 20236 20237 private static class MoveCallbacks extends Handler { 20238 private static final int MSG_CREATED = 1; 20239 private static final int MSG_STATUS_CHANGED = 2; 20240 20241 private final RemoteCallbackList<IPackageMoveObserver> 20242 mCallbacks = new RemoteCallbackList<>(); 20243 20244 private final SparseIntArray mLastStatus = new SparseIntArray(); 20245 20246 public MoveCallbacks(Looper looper) { 20247 super(looper); 20248 } 20249 20250 public void register(IPackageMoveObserver callback) { 20251 mCallbacks.register(callback); 20252 } 20253 20254 public void unregister(IPackageMoveObserver callback) { 20255 mCallbacks.unregister(callback); 20256 } 20257 20258 @Override 20259 public void handleMessage(Message msg) { 20260 final SomeArgs args = (SomeArgs) msg.obj; 20261 final int n = mCallbacks.beginBroadcast(); 20262 for (int i = 0; i < n; i++) { 20263 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20264 try { 20265 invokeCallback(callback, msg.what, args); 20266 } catch (RemoteException ignored) { 20267 } 20268 } 20269 mCallbacks.finishBroadcast(); 20270 args.recycle(); 20271 } 20272 20273 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20274 throws RemoteException { 20275 switch (what) { 20276 case MSG_CREATED: { 20277 callback.onCreated(args.argi1, (Bundle) args.arg2); 20278 break; 20279 } 20280 case MSG_STATUS_CHANGED: { 20281 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20282 break; 20283 } 20284 } 20285 } 20286 20287 private void notifyCreated(int moveId, Bundle extras) { 20288 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20289 20290 final SomeArgs args = SomeArgs.obtain(); 20291 args.argi1 = moveId; 20292 args.arg2 = extras; 20293 obtainMessage(MSG_CREATED, args).sendToTarget(); 20294 } 20295 20296 private void notifyStatusChanged(int moveId, int status) { 20297 notifyStatusChanged(moveId, status, -1); 20298 } 20299 20300 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20301 Slog.v(TAG, "Move " + moveId + " status " + status); 20302 20303 final SomeArgs args = SomeArgs.obtain(); 20304 args.argi1 = moveId; 20305 args.argi2 = status; 20306 args.arg3 = estMillis; 20307 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20308 20309 synchronized (mLastStatus) { 20310 mLastStatus.put(moveId, status); 20311 } 20312 } 20313 } 20314 20315 private final static class OnPermissionChangeListeners extends Handler { 20316 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20317 20318 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20319 new RemoteCallbackList<>(); 20320 20321 public OnPermissionChangeListeners(Looper looper) { 20322 super(looper); 20323 } 20324 20325 @Override 20326 public void handleMessage(Message msg) { 20327 switch (msg.what) { 20328 case MSG_ON_PERMISSIONS_CHANGED: { 20329 final int uid = msg.arg1; 20330 handleOnPermissionsChanged(uid); 20331 } break; 20332 } 20333 } 20334 20335 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20336 mPermissionListeners.register(listener); 20337 20338 } 20339 20340 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20341 mPermissionListeners.unregister(listener); 20342 } 20343 20344 public void onPermissionsChanged(int uid) { 20345 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20346 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20347 } 20348 } 20349 20350 private void handleOnPermissionsChanged(int uid) { 20351 final int count = mPermissionListeners.beginBroadcast(); 20352 try { 20353 for (int i = 0; i < count; i++) { 20354 IOnPermissionsChangeListener callback = mPermissionListeners 20355 .getBroadcastItem(i); 20356 try { 20357 callback.onPermissionsChanged(uid); 20358 } catch (RemoteException e) { 20359 Log.e(TAG, "Permission listener is dead", e); 20360 } 20361 } 20362 } finally { 20363 mPermissionListeners.finishBroadcast(); 20364 } 20365 } 20366 } 20367 20368 private class PackageManagerInternalImpl extends PackageManagerInternal { 20369 @Override 20370 public void setLocationPackagesProvider(PackagesProvider provider) { 20371 synchronized (mPackages) { 20372 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20373 } 20374 } 20375 20376 @Override 20377 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20378 synchronized (mPackages) { 20379 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20380 } 20381 } 20382 20383 @Override 20384 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20385 synchronized (mPackages) { 20386 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20387 } 20388 } 20389 20390 @Override 20391 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20392 synchronized (mPackages) { 20393 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20394 } 20395 } 20396 20397 @Override 20398 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20399 synchronized (mPackages) { 20400 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20401 } 20402 } 20403 20404 @Override 20405 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20406 synchronized (mPackages) { 20407 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20408 } 20409 } 20410 20411 @Override 20412 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20413 synchronized (mPackages) { 20414 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20415 packageName, userId); 20416 } 20417 } 20418 20419 @Override 20420 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20421 synchronized (mPackages) { 20422 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20423 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20424 packageName, userId); 20425 } 20426 } 20427 20428 @Override 20429 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20430 synchronized (mPackages) { 20431 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20432 packageName, userId); 20433 } 20434 } 20435 20436 @Override 20437 public void setKeepUninstalledPackages(final List<String> packageList) { 20438 Preconditions.checkNotNull(packageList); 20439 List<String> removedFromList = null; 20440 synchronized (mPackages) { 20441 if (mKeepUninstalledPackages != null) { 20442 final int packagesCount = mKeepUninstalledPackages.size(); 20443 for (int i = 0; i < packagesCount; i++) { 20444 String oldPackage = mKeepUninstalledPackages.get(i); 20445 if (packageList != null && packageList.contains(oldPackage)) { 20446 continue; 20447 } 20448 if (removedFromList == null) { 20449 removedFromList = new ArrayList<>(); 20450 } 20451 removedFromList.add(oldPackage); 20452 } 20453 } 20454 mKeepUninstalledPackages = new ArrayList<>(packageList); 20455 if (removedFromList != null) { 20456 final int removedCount = removedFromList.size(); 20457 for (int i = 0; i < removedCount; i++) { 20458 deletePackageIfUnusedLPr(removedFromList.get(i)); 20459 } 20460 } 20461 } 20462 } 20463 20464 @Override 20465 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20466 synchronized (mPackages) { 20467 // If we do not support permission review, done. 20468 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20469 return false; 20470 } 20471 20472 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20473 if (packageSetting == null) { 20474 return false; 20475 } 20476 20477 // Permission review applies only to apps not supporting the new permission model. 20478 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20479 return false; 20480 } 20481 20482 // Legacy apps have the permission and get user consent on launch. 20483 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20484 return permissionsState.isPermissionReviewRequired(userId); 20485 } 20486 } 20487 20488 @Override 20489 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20490 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20491 } 20492 20493 @Override 20494 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20495 int userId) { 20496 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20497 } 20498 } 20499 20500 @Override 20501 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20502 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20503 synchronized (mPackages) { 20504 final long identity = Binder.clearCallingIdentity(); 20505 try { 20506 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20507 packageNames, userId); 20508 } finally { 20509 Binder.restoreCallingIdentity(identity); 20510 } 20511 } 20512 } 20513 20514 private static void enforceSystemOrPhoneCaller(String tag) { 20515 int callingUid = Binder.getCallingUid(); 20516 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20517 throw new SecurityException( 20518 "Cannot call " + tag + " from UID " + callingUid); 20519 } 20520 } 20521 20522 boolean isHistoricalPackageUsageAvailable() { 20523 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20524 } 20525 20526 /** 20527 * Return a <b>copy</b> of the collection of packages known to the package manager. 20528 * @return A copy of the values of mPackages. 20529 */ 20530 Collection<PackageParser.Package> getPackages() { 20531 synchronized (mPackages) { 20532 return new ArrayList<>(mPackages.values()); 20533 } 20534 } 20535 20536 /** 20537 * Logs process start information (including base APK hash) to the security log. 20538 * @hide 20539 */ 20540 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20541 String apkFile, int pid) { 20542 if (!SecurityLog.isLoggingEnabled()) { 20543 return; 20544 } 20545 Bundle data = new Bundle(); 20546 data.putLong("startTimestamp", System.currentTimeMillis()); 20547 data.putString("processName", processName); 20548 data.putInt("uid", uid); 20549 data.putString("seinfo", seinfo); 20550 data.putString("apkFile", apkFile); 20551 data.putInt("pid", pid); 20552 Message msg = mProcessLoggingHandler.obtainMessage( 20553 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20554 msg.setData(data); 20555 mProcessLoggingHandler.sendMessage(msg); 20556 } 20557} 20558