PackageManagerService.java revision e713efcac103f3d8083ec9d5b00c528af7266b21
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 return 0; 4269 } 4270 4271 final BasePermission bp = mSettings.mPermissions.get(name); 4272 if (bp == null) { 4273 return 0; 4274 } 4275 4276 SettingBase sb = (SettingBase) pkg.mExtras; 4277 if (sb == null) { 4278 return 0; 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 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8724 a.info.secondaryNativeLibraryDir = pkg.applicationInfo.secondaryNativeLibraryDir; 8725 mInstrumentation.put(a.getComponentName(), a); 8726 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8727 if (r == null) { 8728 r = new StringBuilder(256); 8729 } else { 8730 r.append(' '); 8731 } 8732 r.append(a.info.name); 8733 } 8734 } 8735 if (r != null) { 8736 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8737 } 8738 8739 if (pkg.protectedBroadcasts != null) { 8740 N = pkg.protectedBroadcasts.size(); 8741 for (i=0; i<N; i++) { 8742 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8743 } 8744 } 8745 8746 pkgSetting.setTimeStamp(scanFileTime); 8747 8748 // Create idmap files for pairs of (packages, overlay packages). 8749 // Note: "android", ie framework-res.apk, is handled by native layers. 8750 if (pkg.mOverlayTarget != null) { 8751 // This is an overlay package. 8752 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8753 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8754 mOverlays.put(pkg.mOverlayTarget, 8755 new ArrayMap<String, PackageParser.Package>()); 8756 } 8757 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8758 map.put(pkg.packageName, pkg); 8759 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8760 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8761 createIdmapFailed = true; 8762 } 8763 } 8764 } else if (mOverlays.containsKey(pkg.packageName) && 8765 !pkg.packageName.equals("android")) { 8766 // This is a regular package, with one or more known overlay packages. 8767 createIdmapsForPackageLI(pkg); 8768 } 8769 } 8770 8771 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8772 8773 if (createIdmapFailed) { 8774 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8775 "scanPackageLI failed to createIdmap"); 8776 } 8777 return pkg; 8778 } 8779 8780 /** 8781 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8782 * is derived purely on the basis of the contents of {@code scanFile} and 8783 * {@code cpuAbiOverride}. 8784 * 8785 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8786 */ 8787 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8788 String cpuAbiOverride, boolean extractLibs) 8789 throws PackageManagerException { 8790 // TODO: We can probably be smarter about this stuff. For installed apps, 8791 // we can calculate this information at install time once and for all. For 8792 // system apps, we can probably assume that this information doesn't change 8793 // after the first boot scan. As things stand, we do lots of unnecessary work. 8794 8795 // Give ourselves some initial paths; we'll come back for another 8796 // pass once we've determined ABI below. 8797 setNativeLibraryPaths(pkg); 8798 8799 // We would never need to extract libs for forward-locked and external packages, 8800 // since the container service will do it for us. We shouldn't attempt to 8801 // extract libs from system app when it was not updated. 8802 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8803 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8804 extractLibs = false; 8805 } 8806 8807 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8808 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8809 8810 NativeLibraryHelper.Handle handle = null; 8811 try { 8812 handle = NativeLibraryHelper.Handle.create(pkg); 8813 // TODO(multiArch): This can be null for apps that didn't go through the 8814 // usual installation process. We can calculate it again, like we 8815 // do during install time. 8816 // 8817 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8818 // unnecessary. 8819 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8820 8821 // Null out the abis so that they can be recalculated. 8822 pkg.applicationInfo.primaryCpuAbi = null; 8823 pkg.applicationInfo.secondaryCpuAbi = null; 8824 if (isMultiArch(pkg.applicationInfo)) { 8825 // Warn if we've set an abiOverride for multi-lib packages.. 8826 // By definition, we need to copy both 32 and 64 bit libraries for 8827 // such packages. 8828 if (pkg.cpuAbiOverride != null 8829 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8830 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8831 } 8832 8833 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8834 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8835 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8836 if (extractLibs) { 8837 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8838 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8839 useIsaSpecificSubdirs); 8840 } else { 8841 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8842 } 8843 } 8844 8845 maybeThrowExceptionForMultiArchCopy( 8846 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8847 8848 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8849 if (extractLibs) { 8850 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8851 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8852 useIsaSpecificSubdirs); 8853 } else { 8854 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8855 } 8856 } 8857 8858 maybeThrowExceptionForMultiArchCopy( 8859 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8860 8861 if (abi64 >= 0) { 8862 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8863 } 8864 8865 if (abi32 >= 0) { 8866 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8867 if (abi64 >= 0) { 8868 if (pkg.use32bitAbi) { 8869 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8870 pkg.applicationInfo.primaryCpuAbi = abi; 8871 } else { 8872 pkg.applicationInfo.secondaryCpuAbi = abi; 8873 } 8874 } else { 8875 pkg.applicationInfo.primaryCpuAbi = abi; 8876 } 8877 } 8878 8879 } else { 8880 String[] abiList = (cpuAbiOverride != null) ? 8881 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8882 8883 // Enable gross and lame hacks for apps that are built with old 8884 // SDK tools. We must scan their APKs for renderscript bitcode and 8885 // not launch them if it's present. Don't bother checking on devices 8886 // that don't have 64 bit support. 8887 boolean needsRenderScriptOverride = false; 8888 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8889 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8890 abiList = Build.SUPPORTED_32_BIT_ABIS; 8891 needsRenderScriptOverride = true; 8892 } 8893 8894 final int copyRet; 8895 if (extractLibs) { 8896 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8897 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8898 } else { 8899 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8900 } 8901 8902 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8903 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8904 "Error unpackaging native libs for app, errorCode=" + copyRet); 8905 } 8906 8907 if (copyRet >= 0) { 8908 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8909 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8910 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8911 } else if (needsRenderScriptOverride) { 8912 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8913 } 8914 } 8915 } catch (IOException ioe) { 8916 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8917 } finally { 8918 IoUtils.closeQuietly(handle); 8919 } 8920 8921 // Now that we've calculated the ABIs and determined if it's an internal app, 8922 // we will go ahead and populate the nativeLibraryPath. 8923 setNativeLibraryPaths(pkg); 8924 } 8925 8926 /** 8927 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8928 * i.e, so that all packages can be run inside a single process if required. 8929 * 8930 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8931 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8932 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8933 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8934 * updating a package that belongs to a shared user. 8935 * 8936 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8937 * adds unnecessary complexity. 8938 */ 8939 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8940 PackageParser.Package scannedPackage, boolean bootComplete) { 8941 String requiredInstructionSet = null; 8942 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8943 requiredInstructionSet = VMRuntime.getInstructionSet( 8944 scannedPackage.applicationInfo.primaryCpuAbi); 8945 } 8946 8947 PackageSetting requirer = null; 8948 for (PackageSetting ps : packagesForUser) { 8949 // If packagesForUser contains scannedPackage, we skip it. This will happen 8950 // when scannedPackage is an update of an existing package. Without this check, 8951 // we will never be able to change the ABI of any package belonging to a shared 8952 // user, even if it's compatible with other packages. 8953 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8954 if (ps.primaryCpuAbiString == null) { 8955 continue; 8956 } 8957 8958 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8959 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8960 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8961 // this but there's not much we can do. 8962 String errorMessage = "Instruction set mismatch, " 8963 + ((requirer == null) ? "[caller]" : requirer) 8964 + " requires " + requiredInstructionSet + " whereas " + ps 8965 + " requires " + instructionSet; 8966 Slog.w(TAG, errorMessage); 8967 } 8968 8969 if (requiredInstructionSet == null) { 8970 requiredInstructionSet = instructionSet; 8971 requirer = ps; 8972 } 8973 } 8974 } 8975 8976 if (requiredInstructionSet != null) { 8977 String adjustedAbi; 8978 if (requirer != null) { 8979 // requirer != null implies that either scannedPackage was null or that scannedPackage 8980 // did not require an ABI, in which case we have to adjust scannedPackage to match 8981 // the ABI of the set (which is the same as requirer's ABI) 8982 adjustedAbi = requirer.primaryCpuAbiString; 8983 if (scannedPackage != null) { 8984 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8985 } 8986 } else { 8987 // requirer == null implies that we're updating all ABIs in the set to 8988 // match scannedPackage. 8989 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8990 } 8991 8992 for (PackageSetting ps : packagesForUser) { 8993 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8994 if (ps.primaryCpuAbiString != null) { 8995 continue; 8996 } 8997 8998 ps.primaryCpuAbiString = adjustedAbi; 8999 if (ps.pkg != null && ps.pkg.applicationInfo != null && 9000 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 9001 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 9002 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 9003 + " (requirer=" 9004 + (requirer == null ? "null" : requirer.pkg.packageName) 9005 + ", scannedPackage=" 9006 + (scannedPackage != null ? scannedPackage.packageName : "null") 9007 + ")"); 9008 try { 9009 mInstaller.rmdex(ps.codePathString, 9010 getDexCodeInstructionSet(getPreferredInstructionSet())); 9011 } catch (InstallerException ignored) { 9012 } 9013 } 9014 } 9015 } 9016 } 9017 } 9018 9019 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 9020 synchronized (mPackages) { 9021 mResolverReplaced = true; 9022 // Set up information for custom user intent resolution activity. 9023 mResolveActivity.applicationInfo = pkg.applicationInfo; 9024 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 9025 mResolveActivity.packageName = pkg.applicationInfo.packageName; 9026 mResolveActivity.processName = pkg.applicationInfo.packageName; 9027 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9028 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9029 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9030 mResolveActivity.theme = 0; 9031 mResolveActivity.exported = true; 9032 mResolveActivity.enabled = true; 9033 mResolveInfo.activityInfo = mResolveActivity; 9034 mResolveInfo.priority = 0; 9035 mResolveInfo.preferredOrder = 0; 9036 mResolveInfo.match = 0; 9037 mResolveComponentName = mCustomResolverComponentName; 9038 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 9039 mResolveComponentName); 9040 } 9041 } 9042 9043 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9044 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9045 9046 // Set up information for ephemeral installer activity 9047 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9048 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9049 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9050 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9051 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9052 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9053 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9054 mEphemeralInstallerActivity.theme = 0; 9055 mEphemeralInstallerActivity.exported = true; 9056 mEphemeralInstallerActivity.enabled = true; 9057 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9058 mEphemeralInstallerInfo.priority = 0; 9059 mEphemeralInstallerInfo.preferredOrder = 0; 9060 mEphemeralInstallerInfo.match = 0; 9061 9062 if (DEBUG_EPHEMERAL) { 9063 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9064 } 9065 } 9066 9067 private static String calculateBundledApkRoot(final String codePathString) { 9068 final File codePath = new File(codePathString); 9069 final File codeRoot; 9070 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9071 codeRoot = Environment.getRootDirectory(); 9072 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9073 codeRoot = Environment.getOemDirectory(); 9074 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9075 codeRoot = Environment.getVendorDirectory(); 9076 } else { 9077 // Unrecognized code path; take its top real segment as the apk root: 9078 // e.g. /something/app/blah.apk => /something 9079 try { 9080 File f = codePath.getCanonicalFile(); 9081 File parent = f.getParentFile(); // non-null because codePath is a file 9082 File tmp; 9083 while ((tmp = parent.getParentFile()) != null) { 9084 f = parent; 9085 parent = tmp; 9086 } 9087 codeRoot = f; 9088 Slog.w(TAG, "Unrecognized code path " 9089 + codePath + " - using " + codeRoot); 9090 } catch (IOException e) { 9091 // Can't canonicalize the code path -- shenanigans? 9092 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9093 return Environment.getRootDirectory().getPath(); 9094 } 9095 } 9096 return codeRoot.getPath(); 9097 } 9098 9099 /** 9100 * Derive and set the location of native libraries for the given package, 9101 * which varies depending on where and how the package was installed. 9102 */ 9103 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9104 final ApplicationInfo info = pkg.applicationInfo; 9105 final String codePath = pkg.codePath; 9106 final File codeFile = new File(codePath); 9107 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9108 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9109 9110 info.nativeLibraryRootDir = null; 9111 info.nativeLibraryRootRequiresIsa = false; 9112 info.nativeLibraryDir = null; 9113 info.secondaryNativeLibraryDir = null; 9114 9115 if (isApkFile(codeFile)) { 9116 // Monolithic install 9117 if (bundledApp) { 9118 // If "/system/lib64/apkname" exists, assume that is the per-package 9119 // native library directory to use; otherwise use "/system/lib/apkname". 9120 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9121 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9122 getPrimaryInstructionSet(info)); 9123 9124 // This is a bundled system app so choose the path based on the ABI. 9125 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9126 // is just the default path. 9127 final String apkName = deriveCodePathName(codePath); 9128 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9129 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9130 apkName).getAbsolutePath(); 9131 9132 if (info.secondaryCpuAbi != null) { 9133 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9134 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9135 secondaryLibDir, apkName).getAbsolutePath(); 9136 } 9137 } else if (asecApp) { 9138 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9139 .getAbsolutePath(); 9140 } else { 9141 final String apkName = deriveCodePathName(codePath); 9142 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9143 .getAbsolutePath(); 9144 } 9145 9146 info.nativeLibraryRootRequiresIsa = false; 9147 info.nativeLibraryDir = info.nativeLibraryRootDir; 9148 } else { 9149 // Cluster install 9150 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9151 info.nativeLibraryRootRequiresIsa = true; 9152 9153 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9154 getPrimaryInstructionSet(info)).getAbsolutePath(); 9155 9156 if (info.secondaryCpuAbi != null) { 9157 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9158 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9159 } 9160 } 9161 } 9162 9163 /** 9164 * Calculate the abis and roots for a bundled app. These can uniquely 9165 * be determined from the contents of the system partition, i.e whether 9166 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9167 * of this information, and instead assume that the system was built 9168 * sensibly. 9169 */ 9170 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9171 PackageSetting pkgSetting) { 9172 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9173 9174 // If "/system/lib64/apkname" exists, assume that is the per-package 9175 // native library directory to use; otherwise use "/system/lib/apkname". 9176 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9177 setBundledAppAbi(pkg, apkRoot, apkName); 9178 // pkgSetting might be null during rescan following uninstall of updates 9179 // to a bundled app, so accommodate that possibility. The settings in 9180 // that case will be established later from the parsed package. 9181 // 9182 // If the settings aren't null, sync them up with what we've just derived. 9183 // note that apkRoot isn't stored in the package settings. 9184 if (pkgSetting != null) { 9185 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9186 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9187 } 9188 } 9189 9190 /** 9191 * Deduces the ABI of a bundled app and sets the relevant fields on the 9192 * parsed pkg object. 9193 * 9194 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9195 * under which system libraries are installed. 9196 * @param apkName the name of the installed package. 9197 */ 9198 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9199 final File codeFile = new File(pkg.codePath); 9200 9201 final boolean has64BitLibs; 9202 final boolean has32BitLibs; 9203 if (isApkFile(codeFile)) { 9204 // Monolithic install 9205 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9206 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9207 } else { 9208 // Cluster install 9209 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9210 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9211 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9212 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9213 has64BitLibs = (new File(rootDir, isa)).exists(); 9214 } else { 9215 has64BitLibs = false; 9216 } 9217 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9218 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9219 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9220 has32BitLibs = (new File(rootDir, isa)).exists(); 9221 } else { 9222 has32BitLibs = false; 9223 } 9224 } 9225 9226 if (has64BitLibs && !has32BitLibs) { 9227 // The package has 64 bit libs, but not 32 bit libs. Its primary 9228 // ABI should be 64 bit. We can safely assume here that the bundled 9229 // native libraries correspond to the most preferred ABI in the list. 9230 9231 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9232 pkg.applicationInfo.secondaryCpuAbi = null; 9233 } else if (has32BitLibs && !has64BitLibs) { 9234 // The package has 32 bit libs but not 64 bit libs. Its primary 9235 // ABI should be 32 bit. 9236 9237 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9238 pkg.applicationInfo.secondaryCpuAbi = null; 9239 } else if (has32BitLibs && has64BitLibs) { 9240 // The application has both 64 and 32 bit bundled libraries. We check 9241 // here that the app declares multiArch support, and warn if it doesn't. 9242 // 9243 // We will be lenient here and record both ABIs. The primary will be the 9244 // ABI that's higher on the list, i.e, a device that's configured to prefer 9245 // 64 bit apps will see a 64 bit primary ABI, 9246 9247 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9248 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9249 } 9250 9251 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9252 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9253 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9254 } else { 9255 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9256 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9257 } 9258 } else { 9259 pkg.applicationInfo.primaryCpuAbi = null; 9260 pkg.applicationInfo.secondaryCpuAbi = null; 9261 } 9262 } 9263 9264 private void killApplication(String pkgName, int appId, String reason) { 9265 // Request the ActivityManager to kill the process(only for existing packages) 9266 // so that we do not end up in a confused state while the user is still using the older 9267 // version of the application while the new one gets installed. 9268 final long token = Binder.clearCallingIdentity(); 9269 try { 9270 IActivityManager am = ActivityManagerNative.getDefault(); 9271 if (am != null) { 9272 try { 9273 am.killApplicationWithAppId(pkgName, appId, reason); 9274 } catch (RemoteException e) { 9275 } 9276 } 9277 } finally { 9278 Binder.restoreCallingIdentity(token); 9279 } 9280 } 9281 9282 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9283 // Remove the parent package setting 9284 PackageSetting ps = (PackageSetting) pkg.mExtras; 9285 if (ps != null) { 9286 removePackageLI(ps, chatty); 9287 } 9288 // Remove the child package setting 9289 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9290 for (int i = 0; i < childCount; i++) { 9291 PackageParser.Package childPkg = pkg.childPackages.get(i); 9292 ps = (PackageSetting) childPkg.mExtras; 9293 if (ps != null) { 9294 removePackageLI(ps, chatty); 9295 } 9296 } 9297 } 9298 9299 void removePackageLI(PackageSetting ps, boolean chatty) { 9300 if (DEBUG_INSTALL) { 9301 if (chatty) 9302 Log.d(TAG, "Removing package " + ps.name); 9303 } 9304 9305 // writer 9306 synchronized (mPackages) { 9307 mPackages.remove(ps.name); 9308 final PackageParser.Package pkg = ps.pkg; 9309 if (pkg != null) { 9310 cleanPackageDataStructuresLILPw(pkg, chatty); 9311 } 9312 } 9313 } 9314 9315 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9316 if (DEBUG_INSTALL) { 9317 if (chatty) 9318 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9319 } 9320 9321 // writer 9322 synchronized (mPackages) { 9323 // Remove the parent package 9324 mPackages.remove(pkg.applicationInfo.packageName); 9325 cleanPackageDataStructuresLILPw(pkg, chatty); 9326 9327 // Remove the child packages 9328 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9329 for (int i = 0; i < childCount; i++) { 9330 PackageParser.Package childPkg = pkg.childPackages.get(i); 9331 mPackages.remove(childPkg.applicationInfo.packageName); 9332 cleanPackageDataStructuresLILPw(childPkg, chatty); 9333 } 9334 } 9335 } 9336 9337 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9338 int N = pkg.providers.size(); 9339 StringBuilder r = null; 9340 int i; 9341 for (i=0; i<N; i++) { 9342 PackageParser.Provider p = pkg.providers.get(i); 9343 mProviders.removeProvider(p); 9344 if (p.info.authority == null) { 9345 9346 /* There was another ContentProvider with this authority when 9347 * this app was installed so this authority is null, 9348 * Ignore it as we don't have to unregister the provider. 9349 */ 9350 continue; 9351 } 9352 String names[] = p.info.authority.split(";"); 9353 for (int j = 0; j < names.length; j++) { 9354 if (mProvidersByAuthority.get(names[j]) == p) { 9355 mProvidersByAuthority.remove(names[j]); 9356 if (DEBUG_REMOVE) { 9357 if (chatty) 9358 Log.d(TAG, "Unregistered content provider: " + names[j] 9359 + ", className = " + p.info.name + ", isSyncable = " 9360 + p.info.isSyncable); 9361 } 9362 } 9363 } 9364 if (DEBUG_REMOVE && chatty) { 9365 if (r == null) { 9366 r = new StringBuilder(256); 9367 } else { 9368 r.append(' '); 9369 } 9370 r.append(p.info.name); 9371 } 9372 } 9373 if (r != null) { 9374 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9375 } 9376 9377 N = pkg.services.size(); 9378 r = null; 9379 for (i=0; i<N; i++) { 9380 PackageParser.Service s = pkg.services.get(i); 9381 mServices.removeService(s); 9382 if (chatty) { 9383 if (r == null) { 9384 r = new StringBuilder(256); 9385 } else { 9386 r.append(' '); 9387 } 9388 r.append(s.info.name); 9389 } 9390 } 9391 if (r != null) { 9392 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9393 } 9394 9395 N = pkg.receivers.size(); 9396 r = null; 9397 for (i=0; i<N; i++) { 9398 PackageParser.Activity a = pkg.receivers.get(i); 9399 mReceivers.removeActivity(a, "receiver"); 9400 if (DEBUG_REMOVE && chatty) { 9401 if (r == null) { 9402 r = new StringBuilder(256); 9403 } else { 9404 r.append(' '); 9405 } 9406 r.append(a.info.name); 9407 } 9408 } 9409 if (r != null) { 9410 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9411 } 9412 9413 N = pkg.activities.size(); 9414 r = null; 9415 for (i=0; i<N; i++) { 9416 PackageParser.Activity a = pkg.activities.get(i); 9417 mActivities.removeActivity(a, "activity"); 9418 if (DEBUG_REMOVE && chatty) { 9419 if (r == null) { 9420 r = new StringBuilder(256); 9421 } else { 9422 r.append(' '); 9423 } 9424 r.append(a.info.name); 9425 } 9426 } 9427 if (r != null) { 9428 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9429 } 9430 9431 N = pkg.permissions.size(); 9432 r = null; 9433 for (i=0; i<N; i++) { 9434 PackageParser.Permission p = pkg.permissions.get(i); 9435 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9436 if (bp == null) { 9437 bp = mSettings.mPermissionTrees.get(p.info.name); 9438 } 9439 if (bp != null && bp.perm == p) { 9440 bp.perm = null; 9441 if (DEBUG_REMOVE && chatty) { 9442 if (r == null) { 9443 r = new StringBuilder(256); 9444 } else { 9445 r.append(' '); 9446 } 9447 r.append(p.info.name); 9448 } 9449 } 9450 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9451 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9452 if (appOpPkgs != null) { 9453 appOpPkgs.remove(pkg.packageName); 9454 } 9455 } 9456 } 9457 if (r != null) { 9458 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9459 } 9460 9461 N = pkg.requestedPermissions.size(); 9462 r = null; 9463 for (i=0; i<N; i++) { 9464 String perm = pkg.requestedPermissions.get(i); 9465 BasePermission bp = mSettings.mPermissions.get(perm); 9466 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9467 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9468 if (appOpPkgs != null) { 9469 appOpPkgs.remove(pkg.packageName); 9470 if (appOpPkgs.isEmpty()) { 9471 mAppOpPermissionPackages.remove(perm); 9472 } 9473 } 9474 } 9475 } 9476 if (r != null) { 9477 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9478 } 9479 9480 N = pkg.instrumentation.size(); 9481 r = null; 9482 for (i=0; i<N; i++) { 9483 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9484 mInstrumentation.remove(a.getComponentName()); 9485 if (DEBUG_REMOVE && chatty) { 9486 if (r == null) { 9487 r = new StringBuilder(256); 9488 } else { 9489 r.append(' '); 9490 } 9491 r.append(a.info.name); 9492 } 9493 } 9494 if (r != null) { 9495 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9496 } 9497 9498 r = null; 9499 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9500 // Only system apps can hold shared libraries. 9501 if (pkg.libraryNames != null) { 9502 for (i=0; i<pkg.libraryNames.size(); i++) { 9503 String name = pkg.libraryNames.get(i); 9504 SharedLibraryEntry cur = mSharedLibraries.get(name); 9505 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9506 mSharedLibraries.remove(name); 9507 if (DEBUG_REMOVE && chatty) { 9508 if (r == null) { 9509 r = new StringBuilder(256); 9510 } else { 9511 r.append(' '); 9512 } 9513 r.append(name); 9514 } 9515 } 9516 } 9517 } 9518 } 9519 if (r != null) { 9520 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9521 } 9522 } 9523 9524 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9525 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9526 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9527 return true; 9528 } 9529 } 9530 return false; 9531 } 9532 9533 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9534 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9535 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9536 9537 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9538 // Update the parent permissions 9539 updatePermissionsLPw(pkg.packageName, pkg, flags); 9540 // Update the child permissions 9541 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9542 for (int i = 0; i < childCount; i++) { 9543 PackageParser.Package childPkg = pkg.childPackages.get(i); 9544 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9545 } 9546 } 9547 9548 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9549 int flags) { 9550 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9551 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9552 } 9553 9554 private void updatePermissionsLPw(String changingPkg, 9555 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9556 // Make sure there are no dangling permission trees. 9557 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9558 while (it.hasNext()) { 9559 final BasePermission bp = it.next(); 9560 if (bp.packageSetting == null) { 9561 // We may not yet have parsed the package, so just see if 9562 // we still know about its settings. 9563 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9564 } 9565 if (bp.packageSetting == null) { 9566 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9567 + " from package " + bp.sourcePackage); 9568 it.remove(); 9569 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9570 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9571 Slog.i(TAG, "Removing old permission tree: " + bp.name 9572 + " from package " + bp.sourcePackage); 9573 flags |= UPDATE_PERMISSIONS_ALL; 9574 it.remove(); 9575 } 9576 } 9577 } 9578 9579 // Make sure all dynamic permissions have been assigned to a package, 9580 // and make sure there are no dangling permissions. 9581 it = mSettings.mPermissions.values().iterator(); 9582 while (it.hasNext()) { 9583 final BasePermission bp = it.next(); 9584 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9585 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9586 + bp.name + " pkg=" + bp.sourcePackage 9587 + " info=" + bp.pendingInfo); 9588 if (bp.packageSetting == null && bp.pendingInfo != null) { 9589 final BasePermission tree = findPermissionTreeLP(bp.name); 9590 if (tree != null && tree.perm != null) { 9591 bp.packageSetting = tree.packageSetting; 9592 bp.perm = new PackageParser.Permission(tree.perm.owner, 9593 new PermissionInfo(bp.pendingInfo)); 9594 bp.perm.info.packageName = tree.perm.info.packageName; 9595 bp.perm.info.name = bp.name; 9596 bp.uid = tree.uid; 9597 } 9598 } 9599 } 9600 if (bp.packageSetting == null) { 9601 // We may not yet have parsed the package, so just see if 9602 // we still know about its settings. 9603 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9604 } 9605 if (bp.packageSetting == null) { 9606 Slog.w(TAG, "Removing dangling permission: " + bp.name 9607 + " from package " + bp.sourcePackage); 9608 it.remove(); 9609 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9610 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9611 Slog.i(TAG, "Removing old permission: " + bp.name 9612 + " from package " + bp.sourcePackage); 9613 flags |= UPDATE_PERMISSIONS_ALL; 9614 it.remove(); 9615 } 9616 } 9617 } 9618 9619 // Now update the permissions for all packages, in particular 9620 // replace the granted permissions of the system packages. 9621 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9622 for (PackageParser.Package pkg : mPackages.values()) { 9623 if (pkg != pkgInfo) { 9624 // Only replace for packages on requested volume 9625 final String volumeUuid = getVolumeUuidForPackage(pkg); 9626 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9627 && Objects.equals(replaceVolumeUuid, volumeUuid); 9628 grantPermissionsLPw(pkg, replace, changingPkg); 9629 } 9630 } 9631 } 9632 9633 if (pkgInfo != null) { 9634 // Only replace for packages on requested volume 9635 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9636 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9637 && Objects.equals(replaceVolumeUuid, volumeUuid); 9638 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9639 } 9640 } 9641 9642 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9643 String packageOfInterest) { 9644 // IMPORTANT: There are two types of permissions: install and runtime. 9645 // Install time permissions are granted when the app is installed to 9646 // all device users and users added in the future. Runtime permissions 9647 // are granted at runtime explicitly to specific users. Normal and signature 9648 // protected permissions are install time permissions. Dangerous permissions 9649 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9650 // otherwise they are runtime permissions. This function does not manage 9651 // runtime permissions except for the case an app targeting Lollipop MR1 9652 // being upgraded to target a newer SDK, in which case dangerous permissions 9653 // are transformed from install time to runtime ones. 9654 9655 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9656 if (ps == null) { 9657 return; 9658 } 9659 9660 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9661 9662 PermissionsState permissionsState = ps.getPermissionsState(); 9663 PermissionsState origPermissions = permissionsState; 9664 9665 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9666 9667 boolean runtimePermissionsRevoked = false; 9668 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9669 9670 boolean changedInstallPermission = false; 9671 9672 if (replace) { 9673 ps.installPermissionsFixed = false; 9674 if (!ps.isSharedUser()) { 9675 origPermissions = new PermissionsState(permissionsState); 9676 permissionsState.reset(); 9677 } else { 9678 // We need to know only about runtime permission changes since the 9679 // calling code always writes the install permissions state but 9680 // the runtime ones are written only if changed. The only cases of 9681 // changed runtime permissions here are promotion of an install to 9682 // runtime and revocation of a runtime from a shared user. 9683 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9684 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9685 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9686 runtimePermissionsRevoked = true; 9687 } 9688 } 9689 } 9690 9691 permissionsState.setGlobalGids(mGlobalGids); 9692 9693 final int N = pkg.requestedPermissions.size(); 9694 for (int i=0; i<N; i++) { 9695 final String name = pkg.requestedPermissions.get(i); 9696 final BasePermission bp = mSettings.mPermissions.get(name); 9697 9698 if (DEBUG_INSTALL) { 9699 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9700 } 9701 9702 if (bp == null || bp.packageSetting == null) { 9703 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9704 Slog.w(TAG, "Unknown permission " + name 9705 + " in package " + pkg.packageName); 9706 } 9707 continue; 9708 } 9709 9710 final String perm = bp.name; 9711 boolean allowedSig = false; 9712 int grant = GRANT_DENIED; 9713 9714 // Keep track of app op permissions. 9715 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9716 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9717 if (pkgs == null) { 9718 pkgs = new ArraySet<>(); 9719 mAppOpPermissionPackages.put(bp.name, pkgs); 9720 } 9721 pkgs.add(pkg.packageName); 9722 } 9723 9724 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9725 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9726 >= Build.VERSION_CODES.M; 9727 switch (level) { 9728 case PermissionInfo.PROTECTION_NORMAL: { 9729 // For all apps normal permissions are install time ones. 9730 grant = GRANT_INSTALL; 9731 } break; 9732 9733 case PermissionInfo.PROTECTION_DANGEROUS: { 9734 // If a permission review is required for legacy apps we represent 9735 // their permissions as always granted runtime ones since we need 9736 // to keep the review required permission flag per user while an 9737 // install permission's state is shared across all users. 9738 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9739 // For legacy apps dangerous permissions are install time ones. 9740 grant = GRANT_INSTALL; 9741 } else if (origPermissions.hasInstallPermission(bp.name)) { 9742 // For legacy apps that became modern, install becomes runtime. 9743 grant = GRANT_UPGRADE; 9744 } else if (mPromoteSystemApps 9745 && isSystemApp(ps) 9746 && mExistingSystemPackages.contains(ps.name)) { 9747 // For legacy system apps, install becomes runtime. 9748 // We cannot check hasInstallPermission() for system apps since those 9749 // permissions were granted implicitly and not persisted pre-M. 9750 grant = GRANT_UPGRADE; 9751 } else { 9752 // For modern apps keep runtime permissions unchanged. 9753 grant = GRANT_RUNTIME; 9754 } 9755 } break; 9756 9757 case PermissionInfo.PROTECTION_SIGNATURE: { 9758 // For all apps signature permissions are install time ones. 9759 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9760 if (allowedSig) { 9761 grant = GRANT_INSTALL; 9762 } 9763 } break; 9764 } 9765 9766 if (DEBUG_INSTALL) { 9767 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9768 } 9769 9770 if (grant != GRANT_DENIED) { 9771 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9772 // If this is an existing, non-system package, then 9773 // we can't add any new permissions to it. 9774 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9775 // Except... if this is a permission that was added 9776 // to the platform (note: need to only do this when 9777 // updating the platform). 9778 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9779 grant = GRANT_DENIED; 9780 } 9781 } 9782 } 9783 9784 switch (grant) { 9785 case GRANT_INSTALL: { 9786 // Revoke this as runtime permission to handle the case of 9787 // a runtime permission being downgraded to an install one. 9788 // Also in permission review mode we keep dangerous permissions 9789 // for legacy apps 9790 for (int userId : UserManagerService.getInstance().getUserIds()) { 9791 if (origPermissions.getRuntimePermissionState( 9792 bp.name, userId) != null) { 9793 // Revoke the runtime permission and clear the flags. 9794 origPermissions.revokeRuntimePermission(bp, userId); 9795 origPermissions.updatePermissionFlags(bp, userId, 9796 PackageManager.MASK_PERMISSION_FLAGS, 0); 9797 // If we revoked a permission permission, we have to write. 9798 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9799 changedRuntimePermissionUserIds, userId); 9800 } 9801 } 9802 // Grant an install permission. 9803 if (permissionsState.grantInstallPermission(bp) != 9804 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9805 changedInstallPermission = true; 9806 } 9807 } break; 9808 9809 case GRANT_RUNTIME: { 9810 // Grant previously granted runtime permissions. 9811 for (int userId : UserManagerService.getInstance().getUserIds()) { 9812 PermissionState permissionState = origPermissions 9813 .getRuntimePermissionState(bp.name, userId); 9814 int flags = permissionState != null 9815 ? permissionState.getFlags() : 0; 9816 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9817 if (permissionsState.grantRuntimePermission(bp, userId) == 9818 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9819 // If we cannot put the permission as it was, we have to write. 9820 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9821 changedRuntimePermissionUserIds, userId); 9822 } 9823 // If the app supports runtime permissions no need for a review. 9824 if (Build.PERMISSIONS_REVIEW_REQUIRED 9825 && appSupportsRuntimePermissions 9826 && (flags & PackageManager 9827 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9828 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9829 // Since we changed the flags, we have to write. 9830 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9831 changedRuntimePermissionUserIds, userId); 9832 } 9833 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9834 && !appSupportsRuntimePermissions) { 9835 // For legacy apps that need a permission review, every new 9836 // runtime permission is granted but it is pending a review. 9837 // We also need to review only platform defined runtime 9838 // permissions as these are the only ones the platform knows 9839 // how to disable the API to simulate revocation as legacy 9840 // apps don't expect to run with revoked permissions. 9841 if (PLATFORM_PACKAGE_NAME.equals(bp.sourcePackage)) { 9842 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9843 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9844 // We changed the flags, hence have to write. 9845 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9846 changedRuntimePermissionUserIds, userId); 9847 } 9848 } 9849 if (permissionsState.grantRuntimePermission(bp, userId) 9850 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9851 // We changed the permission, hence have to write. 9852 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9853 changedRuntimePermissionUserIds, userId); 9854 } 9855 } 9856 // Propagate the permission flags. 9857 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9858 } 9859 } break; 9860 9861 case GRANT_UPGRADE: { 9862 // Grant runtime permissions for a previously held install permission. 9863 PermissionState permissionState = origPermissions 9864 .getInstallPermissionState(bp.name); 9865 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9866 9867 if (origPermissions.revokeInstallPermission(bp) 9868 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9869 // We will be transferring the permission flags, so clear them. 9870 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9871 PackageManager.MASK_PERMISSION_FLAGS, 0); 9872 changedInstallPermission = true; 9873 } 9874 9875 // If the permission is not to be promoted to runtime we ignore it and 9876 // also its other flags as they are not applicable to install permissions. 9877 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9878 for (int userId : currentUserIds) { 9879 if (permissionsState.grantRuntimePermission(bp, userId) != 9880 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9881 // Transfer the permission flags. 9882 permissionsState.updatePermissionFlags(bp, userId, 9883 flags, flags); 9884 // If we granted the permission, we have to write. 9885 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9886 changedRuntimePermissionUserIds, userId); 9887 } 9888 } 9889 } 9890 } break; 9891 9892 default: { 9893 if (packageOfInterest == null 9894 || packageOfInterest.equals(pkg.packageName)) { 9895 Slog.w(TAG, "Not granting permission " + perm 9896 + " to package " + pkg.packageName 9897 + " because it was previously installed without"); 9898 } 9899 } break; 9900 } 9901 } else { 9902 if (permissionsState.revokeInstallPermission(bp) != 9903 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9904 // Also drop the permission flags. 9905 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9906 PackageManager.MASK_PERMISSION_FLAGS, 0); 9907 changedInstallPermission = true; 9908 Slog.i(TAG, "Un-granting permission " + perm 9909 + " from package " + pkg.packageName 9910 + " (protectionLevel=" + bp.protectionLevel 9911 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9912 + ")"); 9913 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9914 // Don't print warning for app op permissions, since it is fine for them 9915 // not to be granted, there is a UI for the user to decide. 9916 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9917 Slog.w(TAG, "Not granting permission " + perm 9918 + " to package " + pkg.packageName 9919 + " (protectionLevel=" + bp.protectionLevel 9920 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9921 + ")"); 9922 } 9923 } 9924 } 9925 } 9926 9927 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9928 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9929 // This is the first that we have heard about this package, so the 9930 // permissions we have now selected are fixed until explicitly 9931 // changed. 9932 ps.installPermissionsFixed = true; 9933 } 9934 9935 // Persist the runtime permissions state for users with changes. If permissions 9936 // were revoked because no app in the shared user declares them we have to 9937 // write synchronously to avoid losing runtime permissions state. 9938 for (int userId : changedRuntimePermissionUserIds) { 9939 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9940 } 9941 9942 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9943 } 9944 9945 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9946 boolean allowed = false; 9947 final int NP = PackageParser.NEW_PERMISSIONS.length; 9948 for (int ip=0; ip<NP; ip++) { 9949 final PackageParser.NewPermissionInfo npi 9950 = PackageParser.NEW_PERMISSIONS[ip]; 9951 if (npi.name.equals(perm) 9952 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9953 allowed = true; 9954 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9955 + pkg.packageName); 9956 break; 9957 } 9958 } 9959 return allowed; 9960 } 9961 9962 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9963 BasePermission bp, PermissionsState origPermissions) { 9964 boolean allowed; 9965 allowed = (compareSignatures( 9966 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9967 == PackageManager.SIGNATURE_MATCH) 9968 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9969 == PackageManager.SIGNATURE_MATCH); 9970 if (!allowed && (bp.protectionLevel 9971 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9972 if (isSystemApp(pkg)) { 9973 // For updated system applications, a system permission 9974 // is granted only if it had been defined by the original application. 9975 if (pkg.isUpdatedSystemApp()) { 9976 final PackageSetting sysPs = mSettings 9977 .getDisabledSystemPkgLPr(pkg.packageName); 9978 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9979 // If the original was granted this permission, we take 9980 // that grant decision as read and propagate it to the 9981 // update. 9982 if (sysPs.isPrivileged()) { 9983 allowed = true; 9984 } 9985 } else { 9986 // The system apk may have been updated with an older 9987 // version of the one on the data partition, but which 9988 // granted a new system permission that it didn't have 9989 // before. In this case we do want to allow the app to 9990 // now get the new permission if the ancestral apk is 9991 // privileged to get it. 9992 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9993 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9994 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9995 allowed = true; 9996 break; 9997 } 9998 } 9999 } 10000 // Also if a privileged parent package on the system image or any of 10001 // its children requested a privileged permission, the updated child 10002 // packages can also get the permission. 10003 if (pkg.parentPackage != null) { 10004 final PackageSetting disabledSysParentPs = mSettings 10005 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 10006 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 10007 && disabledSysParentPs.isPrivileged()) { 10008 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 10009 allowed = true; 10010 } else if (disabledSysParentPs.pkg.childPackages != null) { 10011 final int count = disabledSysParentPs.pkg.childPackages.size(); 10012 for (int i = 0; i < count; i++) { 10013 PackageParser.Package disabledSysChildPkg = 10014 disabledSysParentPs.pkg.childPackages.get(i); 10015 if (isPackageRequestingPermission(disabledSysChildPkg, 10016 perm)) { 10017 allowed = true; 10018 break; 10019 } 10020 } 10021 } 10022 } 10023 } 10024 } 10025 } else { 10026 allowed = isPrivilegedApp(pkg); 10027 } 10028 } 10029 } 10030 if (!allowed) { 10031 if (!allowed && (bp.protectionLevel 10032 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 10033 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 10034 // If this was a previously normal/dangerous permission that got moved 10035 // to a system permission as part of the runtime permission redesign, then 10036 // we still want to blindly grant it to old apps. 10037 allowed = true; 10038 } 10039 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 10040 && pkg.packageName.equals(mRequiredInstallerPackage)) { 10041 // If this permission is to be granted to the system installer and 10042 // this app is an installer, then it gets the permission. 10043 allowed = true; 10044 } 10045 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 10046 && pkg.packageName.equals(mRequiredVerifierPackage)) { 10047 // If this permission is to be granted to the system verifier and 10048 // this app is a verifier, then it gets the permission. 10049 allowed = true; 10050 } 10051 if (!allowed && (bp.protectionLevel 10052 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10053 && isSystemApp(pkg)) { 10054 // Any pre-installed system app is allowed to get this permission. 10055 allowed = true; 10056 } 10057 if (!allowed && (bp.protectionLevel 10058 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10059 // For development permissions, a development permission 10060 // is granted only if it was already granted. 10061 allowed = origPermissions.hasInstallPermission(perm); 10062 } 10063 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10064 && pkg.packageName.equals(mSetupWizardPackage)) { 10065 // If this permission is to be granted to the system setup wizard and 10066 // this app is a setup wizard, then it gets the permission. 10067 allowed = true; 10068 } 10069 } 10070 return allowed; 10071 } 10072 10073 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10074 final int permCount = pkg.requestedPermissions.size(); 10075 for (int j = 0; j < permCount; j++) { 10076 String requestedPermission = pkg.requestedPermissions.get(j); 10077 if (permission.equals(requestedPermission)) { 10078 return true; 10079 } 10080 } 10081 return false; 10082 } 10083 10084 final class ActivityIntentResolver 10085 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10086 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10087 boolean defaultOnly, int userId) { 10088 if (!sUserManager.exists(userId)) return null; 10089 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10090 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10091 } 10092 10093 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10094 int userId) { 10095 if (!sUserManager.exists(userId)) return null; 10096 mFlags = flags; 10097 return super.queryIntent(intent, resolvedType, 10098 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10099 } 10100 10101 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10102 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10103 if (!sUserManager.exists(userId)) return null; 10104 if (packageActivities == null) { 10105 return null; 10106 } 10107 mFlags = flags; 10108 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10109 final int N = packageActivities.size(); 10110 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10111 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10112 10113 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10114 for (int i = 0; i < N; ++i) { 10115 intentFilters = packageActivities.get(i).intents; 10116 if (intentFilters != null && intentFilters.size() > 0) { 10117 PackageParser.ActivityIntentInfo[] array = 10118 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10119 intentFilters.toArray(array); 10120 listCut.add(array); 10121 } 10122 } 10123 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10124 } 10125 10126 /** 10127 * Finds a privileged activity that matches the specified activity names. 10128 */ 10129 private PackageParser.Activity findMatchingActivity( 10130 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10131 for (PackageParser.Activity sysActivity : activityList) { 10132 if (sysActivity.info.name.equals(activityInfo.name)) { 10133 return sysActivity; 10134 } 10135 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10136 return sysActivity; 10137 } 10138 if (sysActivity.info.targetActivity != null) { 10139 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10140 return sysActivity; 10141 } 10142 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10143 return sysActivity; 10144 } 10145 } 10146 } 10147 return null; 10148 } 10149 10150 public class IterGenerator<E> { 10151 public Iterator<E> generate(ActivityIntentInfo info) { 10152 return null; 10153 } 10154 } 10155 10156 public class ActionIterGenerator extends IterGenerator<String> { 10157 @Override 10158 public Iterator<String> generate(ActivityIntentInfo info) { 10159 return info.actionsIterator(); 10160 } 10161 } 10162 10163 public class CategoriesIterGenerator extends IterGenerator<String> { 10164 @Override 10165 public Iterator<String> generate(ActivityIntentInfo info) { 10166 return info.categoriesIterator(); 10167 } 10168 } 10169 10170 public class SchemesIterGenerator extends IterGenerator<String> { 10171 @Override 10172 public Iterator<String> generate(ActivityIntentInfo info) { 10173 return info.schemesIterator(); 10174 } 10175 } 10176 10177 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10178 @Override 10179 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10180 return info.authoritiesIterator(); 10181 } 10182 } 10183 10184 /** 10185 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10186 * MODIFIED. Do not pass in a list that should not be changed. 10187 */ 10188 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10189 IterGenerator<T> generator, Iterator<T> searchIterator) { 10190 // loop through the set of actions; every one must be found in the intent filter 10191 while (searchIterator.hasNext()) { 10192 // we must have at least one filter in the list to consider a match 10193 if (intentList.size() == 0) { 10194 break; 10195 } 10196 10197 final T searchAction = searchIterator.next(); 10198 10199 // loop through the set of intent filters 10200 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10201 while (intentIter.hasNext()) { 10202 final ActivityIntentInfo intentInfo = intentIter.next(); 10203 boolean selectionFound = false; 10204 10205 // loop through the intent filter's selection criteria; at least one 10206 // of them must match the searched criteria 10207 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10208 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10209 final T intentSelection = intentSelectionIter.next(); 10210 if (intentSelection != null && intentSelection.equals(searchAction)) { 10211 selectionFound = true; 10212 break; 10213 } 10214 } 10215 10216 // the selection criteria wasn't found in this filter's set; this filter 10217 // is not a potential match 10218 if (!selectionFound) { 10219 intentIter.remove(); 10220 } 10221 } 10222 } 10223 } 10224 10225 private boolean isProtectedAction(ActivityIntentInfo filter) { 10226 final Iterator<String> actionsIter = filter.actionsIterator(); 10227 while (actionsIter != null && actionsIter.hasNext()) { 10228 final String filterAction = actionsIter.next(); 10229 if (PROTECTED_ACTIONS.contains(filterAction)) { 10230 return true; 10231 } 10232 } 10233 return false; 10234 } 10235 10236 /** 10237 * Adjusts the priority of the given intent filter according to policy. 10238 * <p> 10239 * <ul> 10240 * <li>The priority for non privileged applications is capped to '0'</li> 10241 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10242 * <li>The priority for unbundled updates to privileged applications is capped to the 10243 * priority defined on the system partition</li> 10244 * </ul> 10245 * <p> 10246 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10247 * allowed to obtain any priority on any action. 10248 */ 10249 private void adjustPriority( 10250 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10251 // nothing to do; priority is fine as-is 10252 if (intent.getPriority() <= 0) { 10253 return; 10254 } 10255 10256 final ActivityInfo activityInfo = intent.activity.info; 10257 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10258 10259 final boolean privilegedApp = 10260 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10261 if (!privilegedApp) { 10262 // non-privileged applications can never define a priority >0 10263 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10264 + " package: " + applicationInfo.packageName 10265 + " activity: " + intent.activity.className 10266 + " origPrio: " + intent.getPriority()); 10267 intent.setPriority(0); 10268 return; 10269 } 10270 10271 if (systemActivities == null) { 10272 // the system package is not disabled; we're parsing the system partition 10273 if (isProtectedAction(intent)) { 10274 if (mDeferProtectedFilters) { 10275 // We can't deal with these just yet. No component should ever obtain a 10276 // >0 priority for a protected actions, with ONE exception -- the setup 10277 // wizard. The setup wizard, however, cannot be known until we're able to 10278 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10279 // until all intent filters have been processed. Chicken, meet egg. 10280 // Let the filter temporarily have a high priority and rectify the 10281 // priorities after all system packages have been scanned. 10282 mProtectedFilters.add(intent); 10283 if (DEBUG_FILTERS) { 10284 Slog.i(TAG, "Protected action; save for later;" 10285 + " package: " + applicationInfo.packageName 10286 + " activity: " + intent.activity.className 10287 + " origPrio: " + intent.getPriority()); 10288 } 10289 return; 10290 } else { 10291 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10292 Slog.i(TAG, "No setup wizard;" 10293 + " All protected intents capped to priority 0"); 10294 } 10295 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10296 if (DEBUG_FILTERS) { 10297 Slog.i(TAG, "Found setup wizard;" 10298 + " allow priority " + intent.getPriority() + ";" 10299 + " package: " + intent.activity.info.packageName 10300 + " activity: " + intent.activity.className 10301 + " priority: " + intent.getPriority()); 10302 } 10303 // setup wizard gets whatever it wants 10304 return; 10305 } 10306 Slog.w(TAG, "Protected action; cap priority to 0;" 10307 + " package: " + intent.activity.info.packageName 10308 + " activity: " + intent.activity.className 10309 + " origPrio: " + intent.getPriority()); 10310 intent.setPriority(0); 10311 return; 10312 } 10313 } 10314 // privileged apps on the system image get whatever priority they request 10315 return; 10316 } 10317 10318 // privileged app unbundled update ... try to find the same activity 10319 final PackageParser.Activity foundActivity = 10320 findMatchingActivity(systemActivities, activityInfo); 10321 if (foundActivity == null) { 10322 // this is a new activity; it cannot obtain >0 priority 10323 if (DEBUG_FILTERS) { 10324 Slog.i(TAG, "New activity; cap priority to 0;" 10325 + " package: " + applicationInfo.packageName 10326 + " activity: " + intent.activity.className 10327 + " origPrio: " + intent.getPriority()); 10328 } 10329 intent.setPriority(0); 10330 return; 10331 } 10332 10333 // found activity, now check for filter equivalence 10334 10335 // a shallow copy is enough; we modify the list, not its contents 10336 final List<ActivityIntentInfo> intentListCopy = 10337 new ArrayList<>(foundActivity.intents); 10338 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10339 10340 // find matching action subsets 10341 final Iterator<String> actionsIterator = intent.actionsIterator(); 10342 if (actionsIterator != null) { 10343 getIntentListSubset( 10344 intentListCopy, new ActionIterGenerator(), actionsIterator); 10345 if (intentListCopy.size() == 0) { 10346 // no more intents to match; we're not equivalent 10347 if (DEBUG_FILTERS) { 10348 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10349 + " package: " + applicationInfo.packageName 10350 + " activity: " + intent.activity.className 10351 + " origPrio: " + intent.getPriority()); 10352 } 10353 intent.setPriority(0); 10354 return; 10355 } 10356 } 10357 10358 // find matching category subsets 10359 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10360 if (categoriesIterator != null) { 10361 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10362 categoriesIterator); 10363 if (intentListCopy.size() == 0) { 10364 // no more intents to match; we're not equivalent 10365 if (DEBUG_FILTERS) { 10366 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10367 + " package: " + applicationInfo.packageName 10368 + " activity: " + intent.activity.className 10369 + " origPrio: " + intent.getPriority()); 10370 } 10371 intent.setPriority(0); 10372 return; 10373 } 10374 } 10375 10376 // find matching schemes subsets 10377 final Iterator<String> schemesIterator = intent.schemesIterator(); 10378 if (schemesIterator != null) { 10379 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10380 schemesIterator); 10381 if (intentListCopy.size() == 0) { 10382 // no more intents to match; we're not equivalent 10383 if (DEBUG_FILTERS) { 10384 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10385 + " package: " + applicationInfo.packageName 10386 + " activity: " + intent.activity.className 10387 + " origPrio: " + intent.getPriority()); 10388 } 10389 intent.setPriority(0); 10390 return; 10391 } 10392 } 10393 10394 // find matching authorities subsets 10395 final Iterator<IntentFilter.AuthorityEntry> 10396 authoritiesIterator = intent.authoritiesIterator(); 10397 if (authoritiesIterator != null) { 10398 getIntentListSubset(intentListCopy, 10399 new AuthoritiesIterGenerator(), 10400 authoritiesIterator); 10401 if (intentListCopy.size() == 0) { 10402 // no more intents to match; we're not equivalent 10403 if (DEBUG_FILTERS) { 10404 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10405 + " package: " + applicationInfo.packageName 10406 + " activity: " + intent.activity.className 10407 + " origPrio: " + intent.getPriority()); 10408 } 10409 intent.setPriority(0); 10410 return; 10411 } 10412 } 10413 10414 // we found matching filter(s); app gets the max priority of all intents 10415 int cappedPriority = 0; 10416 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10417 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10418 } 10419 if (intent.getPriority() > cappedPriority) { 10420 if (DEBUG_FILTERS) { 10421 Slog.i(TAG, "Found matching filter(s);" 10422 + " cap priority to " + cappedPriority + ";" 10423 + " package: " + applicationInfo.packageName 10424 + " activity: " + intent.activity.className 10425 + " origPrio: " + intent.getPriority()); 10426 } 10427 intent.setPriority(cappedPriority); 10428 return; 10429 } 10430 // all this for nothing; the requested priority was <= what was on the system 10431 } 10432 10433 public final void addActivity(PackageParser.Activity a, String type) { 10434 mActivities.put(a.getComponentName(), a); 10435 if (DEBUG_SHOW_INFO) 10436 Log.v( 10437 TAG, " " + type + " " + 10438 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10439 if (DEBUG_SHOW_INFO) 10440 Log.v(TAG, " Class=" + a.info.name); 10441 final int NI = a.intents.size(); 10442 for (int j=0; j<NI; j++) { 10443 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10444 if ("activity".equals(type)) { 10445 final PackageSetting ps = 10446 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10447 final List<PackageParser.Activity> systemActivities = 10448 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10449 adjustPriority(systemActivities, intent); 10450 } 10451 if (DEBUG_SHOW_INFO) { 10452 Log.v(TAG, " IntentFilter:"); 10453 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10454 } 10455 if (!intent.debugCheck()) { 10456 Log.w(TAG, "==> For Activity " + a.info.name); 10457 } 10458 addFilter(intent); 10459 } 10460 } 10461 10462 public final void removeActivity(PackageParser.Activity a, String type) { 10463 mActivities.remove(a.getComponentName()); 10464 if (DEBUG_SHOW_INFO) { 10465 Log.v(TAG, " " + type + " " 10466 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10467 : a.info.name) + ":"); 10468 Log.v(TAG, " Class=" + a.info.name); 10469 } 10470 final int NI = a.intents.size(); 10471 for (int j=0; j<NI; j++) { 10472 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10473 if (DEBUG_SHOW_INFO) { 10474 Log.v(TAG, " IntentFilter:"); 10475 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10476 } 10477 removeFilter(intent); 10478 } 10479 } 10480 10481 @Override 10482 protected boolean allowFilterResult( 10483 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10484 ActivityInfo filterAi = filter.activity.info; 10485 for (int i=dest.size()-1; i>=0; i--) { 10486 ActivityInfo destAi = dest.get(i).activityInfo; 10487 if (destAi.name == filterAi.name 10488 && destAi.packageName == filterAi.packageName) { 10489 return false; 10490 } 10491 } 10492 return true; 10493 } 10494 10495 @Override 10496 protected ActivityIntentInfo[] newArray(int size) { 10497 return new ActivityIntentInfo[size]; 10498 } 10499 10500 @Override 10501 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10502 if (!sUserManager.exists(userId)) return true; 10503 PackageParser.Package p = filter.activity.owner; 10504 if (p != null) { 10505 PackageSetting ps = (PackageSetting)p.mExtras; 10506 if (ps != null) { 10507 // System apps are never considered stopped for purposes of 10508 // filtering, because there may be no way for the user to 10509 // actually re-launch them. 10510 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10511 && ps.getStopped(userId); 10512 } 10513 } 10514 return false; 10515 } 10516 10517 @Override 10518 protected boolean isPackageForFilter(String packageName, 10519 PackageParser.ActivityIntentInfo info) { 10520 return packageName.equals(info.activity.owner.packageName); 10521 } 10522 10523 @Override 10524 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10525 int match, int userId) { 10526 if (!sUserManager.exists(userId)) return null; 10527 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10528 return null; 10529 } 10530 final PackageParser.Activity activity = info.activity; 10531 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10532 if (ps == null) { 10533 return null; 10534 } 10535 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10536 ps.readUserState(userId), userId); 10537 if (ai == null) { 10538 return null; 10539 } 10540 final ResolveInfo res = new ResolveInfo(); 10541 res.activityInfo = ai; 10542 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10543 res.filter = info; 10544 } 10545 if (info != null) { 10546 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10547 } 10548 res.priority = info.getPriority(); 10549 res.preferredOrder = activity.owner.mPreferredOrder; 10550 //System.out.println("Result: " + res.activityInfo.className + 10551 // " = " + res.priority); 10552 res.match = match; 10553 res.isDefault = info.hasDefault; 10554 res.labelRes = info.labelRes; 10555 res.nonLocalizedLabel = info.nonLocalizedLabel; 10556 if (userNeedsBadging(userId)) { 10557 res.noResourceId = true; 10558 } else { 10559 res.icon = info.icon; 10560 } 10561 res.iconResourceId = info.icon; 10562 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10563 return res; 10564 } 10565 10566 @Override 10567 protected void sortResults(List<ResolveInfo> results) { 10568 Collections.sort(results, mResolvePrioritySorter); 10569 } 10570 10571 @Override 10572 protected void dumpFilter(PrintWriter out, String prefix, 10573 PackageParser.ActivityIntentInfo filter) { 10574 out.print(prefix); out.print( 10575 Integer.toHexString(System.identityHashCode(filter.activity))); 10576 out.print(' '); 10577 filter.activity.printComponentShortName(out); 10578 out.print(" filter "); 10579 out.println(Integer.toHexString(System.identityHashCode(filter))); 10580 } 10581 10582 @Override 10583 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10584 return filter.activity; 10585 } 10586 10587 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10588 PackageParser.Activity activity = (PackageParser.Activity)label; 10589 out.print(prefix); out.print( 10590 Integer.toHexString(System.identityHashCode(activity))); 10591 out.print(' '); 10592 activity.printComponentShortName(out); 10593 if (count > 1) { 10594 out.print(" ("); out.print(count); out.print(" filters)"); 10595 } 10596 out.println(); 10597 } 10598 10599 // Keys are String (activity class name), values are Activity. 10600 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10601 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10602 private int mFlags; 10603 } 10604 10605 private final class ServiceIntentResolver 10606 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10607 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10608 boolean defaultOnly, int userId) { 10609 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10610 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10611 } 10612 10613 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10614 int userId) { 10615 if (!sUserManager.exists(userId)) return null; 10616 mFlags = flags; 10617 return super.queryIntent(intent, resolvedType, 10618 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10619 } 10620 10621 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10622 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10623 if (!sUserManager.exists(userId)) return null; 10624 if (packageServices == null) { 10625 return null; 10626 } 10627 mFlags = flags; 10628 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10629 final int N = packageServices.size(); 10630 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10631 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10632 10633 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10634 for (int i = 0; i < N; ++i) { 10635 intentFilters = packageServices.get(i).intents; 10636 if (intentFilters != null && intentFilters.size() > 0) { 10637 PackageParser.ServiceIntentInfo[] array = 10638 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10639 intentFilters.toArray(array); 10640 listCut.add(array); 10641 } 10642 } 10643 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10644 } 10645 10646 public final void addService(PackageParser.Service s) { 10647 mServices.put(s.getComponentName(), s); 10648 if (DEBUG_SHOW_INFO) { 10649 Log.v(TAG, " " 10650 + (s.info.nonLocalizedLabel != null 10651 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10652 Log.v(TAG, " Class=" + s.info.name); 10653 } 10654 final int NI = s.intents.size(); 10655 int j; 10656 for (j=0; j<NI; j++) { 10657 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10658 if (DEBUG_SHOW_INFO) { 10659 Log.v(TAG, " IntentFilter:"); 10660 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10661 } 10662 if (!intent.debugCheck()) { 10663 Log.w(TAG, "==> For Service " + s.info.name); 10664 } 10665 addFilter(intent); 10666 } 10667 } 10668 10669 public final void removeService(PackageParser.Service s) { 10670 mServices.remove(s.getComponentName()); 10671 if (DEBUG_SHOW_INFO) { 10672 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10673 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10674 Log.v(TAG, " Class=" + s.info.name); 10675 } 10676 final int NI = s.intents.size(); 10677 int j; 10678 for (j=0; j<NI; j++) { 10679 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10680 if (DEBUG_SHOW_INFO) { 10681 Log.v(TAG, " IntentFilter:"); 10682 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10683 } 10684 removeFilter(intent); 10685 } 10686 } 10687 10688 @Override 10689 protected boolean allowFilterResult( 10690 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10691 ServiceInfo filterSi = filter.service.info; 10692 for (int i=dest.size()-1; i>=0; i--) { 10693 ServiceInfo destAi = dest.get(i).serviceInfo; 10694 if (destAi.name == filterSi.name 10695 && destAi.packageName == filterSi.packageName) { 10696 return false; 10697 } 10698 } 10699 return true; 10700 } 10701 10702 @Override 10703 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10704 return new PackageParser.ServiceIntentInfo[size]; 10705 } 10706 10707 @Override 10708 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10709 if (!sUserManager.exists(userId)) return true; 10710 PackageParser.Package p = filter.service.owner; 10711 if (p != null) { 10712 PackageSetting ps = (PackageSetting)p.mExtras; 10713 if (ps != null) { 10714 // System apps are never considered stopped for purposes of 10715 // filtering, because there may be no way for the user to 10716 // actually re-launch them. 10717 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10718 && ps.getStopped(userId); 10719 } 10720 } 10721 return false; 10722 } 10723 10724 @Override 10725 protected boolean isPackageForFilter(String packageName, 10726 PackageParser.ServiceIntentInfo info) { 10727 return packageName.equals(info.service.owner.packageName); 10728 } 10729 10730 @Override 10731 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10732 int match, int userId) { 10733 if (!sUserManager.exists(userId)) return null; 10734 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10735 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10736 return null; 10737 } 10738 final PackageParser.Service service = info.service; 10739 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10740 if (ps == null) { 10741 return null; 10742 } 10743 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10744 ps.readUserState(userId), userId); 10745 if (si == null) { 10746 return null; 10747 } 10748 final ResolveInfo res = new ResolveInfo(); 10749 res.serviceInfo = si; 10750 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10751 res.filter = filter; 10752 } 10753 res.priority = info.getPriority(); 10754 res.preferredOrder = service.owner.mPreferredOrder; 10755 res.match = match; 10756 res.isDefault = info.hasDefault; 10757 res.labelRes = info.labelRes; 10758 res.nonLocalizedLabel = info.nonLocalizedLabel; 10759 res.icon = info.icon; 10760 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10761 return res; 10762 } 10763 10764 @Override 10765 protected void sortResults(List<ResolveInfo> results) { 10766 Collections.sort(results, mResolvePrioritySorter); 10767 } 10768 10769 @Override 10770 protected void dumpFilter(PrintWriter out, String prefix, 10771 PackageParser.ServiceIntentInfo filter) { 10772 out.print(prefix); out.print( 10773 Integer.toHexString(System.identityHashCode(filter.service))); 10774 out.print(' '); 10775 filter.service.printComponentShortName(out); 10776 out.print(" filter "); 10777 out.println(Integer.toHexString(System.identityHashCode(filter))); 10778 } 10779 10780 @Override 10781 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10782 return filter.service; 10783 } 10784 10785 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10786 PackageParser.Service service = (PackageParser.Service)label; 10787 out.print(prefix); out.print( 10788 Integer.toHexString(System.identityHashCode(service))); 10789 out.print(' '); 10790 service.printComponentShortName(out); 10791 if (count > 1) { 10792 out.print(" ("); out.print(count); out.print(" filters)"); 10793 } 10794 out.println(); 10795 } 10796 10797// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10798// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10799// final List<ResolveInfo> retList = Lists.newArrayList(); 10800// while (i.hasNext()) { 10801// final ResolveInfo resolveInfo = (ResolveInfo) i; 10802// if (isEnabledLP(resolveInfo.serviceInfo)) { 10803// retList.add(resolveInfo); 10804// } 10805// } 10806// return retList; 10807// } 10808 10809 // Keys are String (activity class name), values are Activity. 10810 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10811 = new ArrayMap<ComponentName, PackageParser.Service>(); 10812 private int mFlags; 10813 }; 10814 10815 private final class ProviderIntentResolver 10816 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10817 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10818 boolean defaultOnly, int userId) { 10819 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10820 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10821 } 10822 10823 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10824 int userId) { 10825 if (!sUserManager.exists(userId)) 10826 return null; 10827 mFlags = flags; 10828 return super.queryIntent(intent, resolvedType, 10829 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10830 } 10831 10832 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10833 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10834 if (!sUserManager.exists(userId)) 10835 return null; 10836 if (packageProviders == null) { 10837 return null; 10838 } 10839 mFlags = flags; 10840 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10841 final int N = packageProviders.size(); 10842 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10843 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10844 10845 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10846 for (int i = 0; i < N; ++i) { 10847 intentFilters = packageProviders.get(i).intents; 10848 if (intentFilters != null && intentFilters.size() > 0) { 10849 PackageParser.ProviderIntentInfo[] array = 10850 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10851 intentFilters.toArray(array); 10852 listCut.add(array); 10853 } 10854 } 10855 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10856 } 10857 10858 public final void addProvider(PackageParser.Provider p) { 10859 if (mProviders.containsKey(p.getComponentName())) { 10860 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10861 return; 10862 } 10863 10864 mProviders.put(p.getComponentName(), p); 10865 if (DEBUG_SHOW_INFO) { 10866 Log.v(TAG, " " 10867 + (p.info.nonLocalizedLabel != null 10868 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10869 Log.v(TAG, " Class=" + p.info.name); 10870 } 10871 final int NI = p.intents.size(); 10872 int j; 10873 for (j = 0; j < NI; j++) { 10874 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10875 if (DEBUG_SHOW_INFO) { 10876 Log.v(TAG, " IntentFilter:"); 10877 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10878 } 10879 if (!intent.debugCheck()) { 10880 Log.w(TAG, "==> For Provider " + p.info.name); 10881 } 10882 addFilter(intent); 10883 } 10884 } 10885 10886 public final void removeProvider(PackageParser.Provider p) { 10887 mProviders.remove(p.getComponentName()); 10888 if (DEBUG_SHOW_INFO) { 10889 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10890 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10891 Log.v(TAG, " Class=" + p.info.name); 10892 } 10893 final int NI = p.intents.size(); 10894 int j; 10895 for (j = 0; j < NI; j++) { 10896 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10897 if (DEBUG_SHOW_INFO) { 10898 Log.v(TAG, " IntentFilter:"); 10899 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10900 } 10901 removeFilter(intent); 10902 } 10903 } 10904 10905 @Override 10906 protected boolean allowFilterResult( 10907 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10908 ProviderInfo filterPi = filter.provider.info; 10909 for (int i = dest.size() - 1; i >= 0; i--) { 10910 ProviderInfo destPi = dest.get(i).providerInfo; 10911 if (destPi.name == filterPi.name 10912 && destPi.packageName == filterPi.packageName) { 10913 return false; 10914 } 10915 } 10916 return true; 10917 } 10918 10919 @Override 10920 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10921 return new PackageParser.ProviderIntentInfo[size]; 10922 } 10923 10924 @Override 10925 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10926 if (!sUserManager.exists(userId)) 10927 return true; 10928 PackageParser.Package p = filter.provider.owner; 10929 if (p != null) { 10930 PackageSetting ps = (PackageSetting) p.mExtras; 10931 if (ps != null) { 10932 // System apps are never considered stopped for purposes of 10933 // filtering, because there may be no way for the user to 10934 // actually re-launch them. 10935 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10936 && ps.getStopped(userId); 10937 } 10938 } 10939 return false; 10940 } 10941 10942 @Override 10943 protected boolean isPackageForFilter(String packageName, 10944 PackageParser.ProviderIntentInfo info) { 10945 return packageName.equals(info.provider.owner.packageName); 10946 } 10947 10948 @Override 10949 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10950 int match, int userId) { 10951 if (!sUserManager.exists(userId)) 10952 return null; 10953 final PackageParser.ProviderIntentInfo info = filter; 10954 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10955 return null; 10956 } 10957 final PackageParser.Provider provider = info.provider; 10958 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10959 if (ps == null) { 10960 return null; 10961 } 10962 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10963 ps.readUserState(userId), userId); 10964 if (pi == null) { 10965 return null; 10966 } 10967 final ResolveInfo res = new ResolveInfo(); 10968 res.providerInfo = pi; 10969 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10970 res.filter = filter; 10971 } 10972 res.priority = info.getPriority(); 10973 res.preferredOrder = provider.owner.mPreferredOrder; 10974 res.match = match; 10975 res.isDefault = info.hasDefault; 10976 res.labelRes = info.labelRes; 10977 res.nonLocalizedLabel = info.nonLocalizedLabel; 10978 res.icon = info.icon; 10979 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10980 return res; 10981 } 10982 10983 @Override 10984 protected void sortResults(List<ResolveInfo> results) { 10985 Collections.sort(results, mResolvePrioritySorter); 10986 } 10987 10988 @Override 10989 protected void dumpFilter(PrintWriter out, String prefix, 10990 PackageParser.ProviderIntentInfo filter) { 10991 out.print(prefix); 10992 out.print( 10993 Integer.toHexString(System.identityHashCode(filter.provider))); 10994 out.print(' '); 10995 filter.provider.printComponentShortName(out); 10996 out.print(" filter "); 10997 out.println(Integer.toHexString(System.identityHashCode(filter))); 10998 } 10999 11000 @Override 11001 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 11002 return filter.provider; 11003 } 11004 11005 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 11006 PackageParser.Provider provider = (PackageParser.Provider)label; 11007 out.print(prefix); out.print( 11008 Integer.toHexString(System.identityHashCode(provider))); 11009 out.print(' '); 11010 provider.printComponentShortName(out); 11011 if (count > 1) { 11012 out.print(" ("); out.print(count); out.print(" filters)"); 11013 } 11014 out.println(); 11015 } 11016 11017 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 11018 = new ArrayMap<ComponentName, PackageParser.Provider>(); 11019 private int mFlags; 11020 } 11021 11022 private static final class EphemeralIntentResolver 11023 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 11024 @Override 11025 protected EphemeralResolveIntentInfo[] newArray(int size) { 11026 return new EphemeralResolveIntentInfo[size]; 11027 } 11028 11029 @Override 11030 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 11031 return true; 11032 } 11033 11034 @Override 11035 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 11036 int userId) { 11037 if (!sUserManager.exists(userId)) { 11038 return null; 11039 } 11040 return info.getEphemeralResolveInfo(); 11041 } 11042 } 11043 11044 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 11045 new Comparator<ResolveInfo>() { 11046 public int compare(ResolveInfo r1, ResolveInfo r2) { 11047 int v1 = r1.priority; 11048 int v2 = r2.priority; 11049 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 11050 if (v1 != v2) { 11051 return (v1 > v2) ? -1 : 1; 11052 } 11053 v1 = r1.preferredOrder; 11054 v2 = r2.preferredOrder; 11055 if (v1 != v2) { 11056 return (v1 > v2) ? -1 : 1; 11057 } 11058 if (r1.isDefault != r2.isDefault) { 11059 return r1.isDefault ? -1 : 1; 11060 } 11061 v1 = r1.match; 11062 v2 = r2.match; 11063 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11064 if (v1 != v2) { 11065 return (v1 > v2) ? -1 : 1; 11066 } 11067 if (r1.system != r2.system) { 11068 return r1.system ? -1 : 1; 11069 } 11070 if (r1.activityInfo != null) { 11071 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11072 } 11073 if (r1.serviceInfo != null) { 11074 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11075 } 11076 if (r1.providerInfo != null) { 11077 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11078 } 11079 return 0; 11080 } 11081 }; 11082 11083 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11084 new Comparator<ProviderInfo>() { 11085 public int compare(ProviderInfo p1, ProviderInfo p2) { 11086 final int v1 = p1.initOrder; 11087 final int v2 = p2.initOrder; 11088 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11089 } 11090 }; 11091 11092 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11093 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11094 final int[] userIds) { 11095 mHandler.post(new Runnable() { 11096 @Override 11097 public void run() { 11098 try { 11099 final IActivityManager am = ActivityManagerNative.getDefault(); 11100 if (am == null) return; 11101 final int[] resolvedUserIds; 11102 if (userIds == null) { 11103 resolvedUserIds = am.getRunningUserIds(); 11104 } else { 11105 resolvedUserIds = userIds; 11106 } 11107 for (int id : resolvedUserIds) { 11108 final Intent intent = new Intent(action, 11109 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11110 if (extras != null) { 11111 intent.putExtras(extras); 11112 } 11113 if (targetPkg != null) { 11114 intent.setPackage(targetPkg); 11115 } 11116 // Modify the UID when posting to other users 11117 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11118 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11119 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11120 intent.putExtra(Intent.EXTRA_UID, uid); 11121 } 11122 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11123 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11124 if (DEBUG_BROADCASTS) { 11125 RuntimeException here = new RuntimeException("here"); 11126 here.fillInStackTrace(); 11127 Slog.d(TAG, "Sending to user " + id + ": " 11128 + intent.toShortString(false, true, false, false) 11129 + " " + intent.getExtras(), here); 11130 } 11131 am.broadcastIntent(null, intent, null, finishedReceiver, 11132 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11133 null, finishedReceiver != null, false, id); 11134 } 11135 } catch (RemoteException ex) { 11136 } 11137 } 11138 }); 11139 } 11140 11141 /** 11142 * Check if the external storage media is available. This is true if there 11143 * is a mounted external storage medium or if the external storage is 11144 * emulated. 11145 */ 11146 private boolean isExternalMediaAvailable() { 11147 return mMediaMounted || Environment.isExternalStorageEmulated(); 11148 } 11149 11150 @Override 11151 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11152 // writer 11153 synchronized (mPackages) { 11154 if (!isExternalMediaAvailable()) { 11155 // If the external storage is no longer mounted at this point, 11156 // the caller may not have been able to delete all of this 11157 // packages files and can not delete any more. Bail. 11158 return null; 11159 } 11160 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11161 if (lastPackage != null) { 11162 pkgs.remove(lastPackage); 11163 } 11164 if (pkgs.size() > 0) { 11165 return pkgs.get(0); 11166 } 11167 } 11168 return null; 11169 } 11170 11171 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11172 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11173 userId, andCode ? 1 : 0, packageName); 11174 if (mSystemReady) { 11175 msg.sendToTarget(); 11176 } else { 11177 if (mPostSystemReadyMessages == null) { 11178 mPostSystemReadyMessages = new ArrayList<>(); 11179 } 11180 mPostSystemReadyMessages.add(msg); 11181 } 11182 } 11183 11184 void startCleaningPackages() { 11185 // reader 11186 if (!isExternalMediaAvailable()) { 11187 return; 11188 } 11189 synchronized (mPackages) { 11190 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11191 return; 11192 } 11193 } 11194 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11195 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11196 IActivityManager am = ActivityManagerNative.getDefault(); 11197 if (am != null) { 11198 try { 11199 am.startService(null, intent, null, mContext.getOpPackageName(), 11200 UserHandle.USER_SYSTEM); 11201 } catch (RemoteException e) { 11202 } 11203 } 11204 } 11205 11206 @Override 11207 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11208 int installFlags, String installerPackageName, int userId) { 11209 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11210 11211 final int callingUid = Binder.getCallingUid(); 11212 enforceCrossUserPermission(callingUid, userId, 11213 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11214 11215 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11216 try { 11217 if (observer != null) { 11218 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11219 } 11220 } catch (RemoteException re) { 11221 } 11222 return; 11223 } 11224 11225 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11226 installFlags |= PackageManager.INSTALL_FROM_ADB; 11227 11228 } else { 11229 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11230 // about installerPackageName. 11231 11232 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11233 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11234 } 11235 11236 UserHandle user; 11237 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11238 user = UserHandle.ALL; 11239 } else { 11240 user = new UserHandle(userId); 11241 } 11242 11243 // Only system components can circumvent runtime permissions when installing. 11244 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11245 && mContext.checkCallingOrSelfPermission(Manifest.permission 11246 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11247 throw new SecurityException("You need the " 11248 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11249 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11250 } 11251 11252 final File originFile = new File(originPath); 11253 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11254 11255 final Message msg = mHandler.obtainMessage(INIT_COPY); 11256 final VerificationInfo verificationInfo = new VerificationInfo( 11257 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11258 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11259 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11260 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11261 null /*certificates*/); 11262 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11263 msg.obj = params; 11264 11265 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11266 System.identityHashCode(msg.obj)); 11267 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11268 System.identityHashCode(msg.obj)); 11269 11270 mHandler.sendMessage(msg); 11271 } 11272 11273 void installStage(String packageName, File stagedDir, String stagedCid, 11274 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11275 String installerPackageName, int installerUid, UserHandle user, 11276 Certificate[][] certificates) { 11277 if (DEBUG_EPHEMERAL) { 11278 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11279 Slog.d(TAG, "Ephemeral install of " + packageName); 11280 } 11281 } 11282 final VerificationInfo verificationInfo = new VerificationInfo( 11283 sessionParams.originatingUri, sessionParams.referrerUri, 11284 sessionParams.originatingUid, installerUid); 11285 11286 final OriginInfo origin; 11287 if (stagedDir != null) { 11288 origin = OriginInfo.fromStagedFile(stagedDir); 11289 } else { 11290 origin = OriginInfo.fromStagedContainer(stagedCid); 11291 } 11292 11293 final Message msg = mHandler.obtainMessage(INIT_COPY); 11294 final InstallParams params = new InstallParams(origin, null, observer, 11295 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11296 verificationInfo, user, sessionParams.abiOverride, 11297 sessionParams.grantedRuntimePermissions, certificates); 11298 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11299 msg.obj = params; 11300 11301 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11302 System.identityHashCode(msg.obj)); 11303 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11304 System.identityHashCode(msg.obj)); 11305 11306 mHandler.sendMessage(msg); 11307 } 11308 11309 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11310 int userId) { 11311 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11312 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11313 } 11314 11315 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11316 int appId, int userId) { 11317 Bundle extras = new Bundle(1); 11318 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11319 11320 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11321 packageName, extras, 0, null, null, new int[] {userId}); 11322 try { 11323 IActivityManager am = ActivityManagerNative.getDefault(); 11324 if (isSystem && am.isUserRunning(userId, 0)) { 11325 // The just-installed/enabled app is bundled on the system, so presumed 11326 // to be able to run automatically without needing an explicit launch. 11327 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11328 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11329 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11330 .setPackage(packageName); 11331 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11332 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11333 } 11334 } catch (RemoteException e) { 11335 // shouldn't happen 11336 Slog.w(TAG, "Unable to bootstrap installed package", e); 11337 } 11338 } 11339 11340 @Override 11341 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11342 int userId) { 11343 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11344 PackageSetting pkgSetting; 11345 final int uid = Binder.getCallingUid(); 11346 enforceCrossUserPermission(uid, userId, 11347 true /* requireFullPermission */, true /* checkShell */, 11348 "setApplicationHiddenSetting for user " + userId); 11349 11350 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11351 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11352 return false; 11353 } 11354 11355 long callingId = Binder.clearCallingIdentity(); 11356 try { 11357 boolean sendAdded = false; 11358 boolean sendRemoved = false; 11359 // writer 11360 synchronized (mPackages) { 11361 pkgSetting = mSettings.mPackages.get(packageName); 11362 if (pkgSetting == null) { 11363 return false; 11364 } 11365 if (pkgSetting.getHidden(userId) != hidden) { 11366 pkgSetting.setHidden(hidden, userId); 11367 mSettings.writePackageRestrictionsLPr(userId); 11368 if (hidden) { 11369 sendRemoved = true; 11370 } else { 11371 sendAdded = true; 11372 } 11373 } 11374 } 11375 if (sendAdded) { 11376 sendPackageAddedForUser(packageName, pkgSetting, userId); 11377 return true; 11378 } 11379 if (sendRemoved) { 11380 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11381 "hiding pkg"); 11382 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11383 return true; 11384 } 11385 } finally { 11386 Binder.restoreCallingIdentity(callingId); 11387 } 11388 return false; 11389 } 11390 11391 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11392 int userId) { 11393 final PackageRemovedInfo info = new PackageRemovedInfo(); 11394 info.removedPackage = packageName; 11395 info.removedUsers = new int[] {userId}; 11396 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11397 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11398 } 11399 11400 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11401 if (pkgList.length > 0) { 11402 Bundle extras = new Bundle(1); 11403 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11404 11405 sendPackageBroadcast( 11406 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11407 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11408 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11409 new int[] {userId}); 11410 } 11411 } 11412 11413 /** 11414 * Returns true if application is not found or there was an error. Otherwise it returns 11415 * the hidden state of the package for the given user. 11416 */ 11417 @Override 11418 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11419 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11420 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11421 true /* requireFullPermission */, false /* checkShell */, 11422 "getApplicationHidden for user " + userId); 11423 PackageSetting pkgSetting; 11424 long callingId = Binder.clearCallingIdentity(); 11425 try { 11426 // writer 11427 synchronized (mPackages) { 11428 pkgSetting = mSettings.mPackages.get(packageName); 11429 if (pkgSetting == null) { 11430 return true; 11431 } 11432 return pkgSetting.getHidden(userId); 11433 } 11434 } finally { 11435 Binder.restoreCallingIdentity(callingId); 11436 } 11437 } 11438 11439 /** 11440 * @hide 11441 */ 11442 @Override 11443 public int installExistingPackageAsUser(String packageName, int userId) { 11444 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11445 null); 11446 PackageSetting pkgSetting; 11447 final int uid = Binder.getCallingUid(); 11448 enforceCrossUserPermission(uid, userId, 11449 true /* requireFullPermission */, true /* checkShell */, 11450 "installExistingPackage for user " + userId); 11451 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11452 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11453 } 11454 11455 long callingId = Binder.clearCallingIdentity(); 11456 try { 11457 boolean installed = false; 11458 11459 // writer 11460 synchronized (mPackages) { 11461 pkgSetting = mSettings.mPackages.get(packageName); 11462 if (pkgSetting == null) { 11463 return PackageManager.INSTALL_FAILED_INVALID_URI; 11464 } 11465 if (!pkgSetting.getInstalled(userId)) { 11466 pkgSetting.setInstalled(true, userId); 11467 pkgSetting.setHidden(false, userId); 11468 mSettings.writePackageRestrictionsLPr(userId); 11469 installed = true; 11470 } 11471 } 11472 11473 if (installed) { 11474 if (pkgSetting.pkg != null) { 11475 synchronized (mInstallLock) { 11476 // We don't need to freeze for a brand new install 11477 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11478 } 11479 } 11480 sendPackageAddedForUser(packageName, pkgSetting, userId); 11481 } 11482 } finally { 11483 Binder.restoreCallingIdentity(callingId); 11484 } 11485 11486 return PackageManager.INSTALL_SUCCEEDED; 11487 } 11488 11489 boolean isUserRestricted(int userId, String restrictionKey) { 11490 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11491 if (restrictions.getBoolean(restrictionKey, false)) { 11492 Log.w(TAG, "User is restricted: " + restrictionKey); 11493 return true; 11494 } 11495 return false; 11496 } 11497 11498 @Override 11499 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11500 int userId) { 11501 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11502 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11503 true /* requireFullPermission */, true /* checkShell */, 11504 "setPackagesSuspended for user " + userId); 11505 11506 if (ArrayUtils.isEmpty(packageNames)) { 11507 return packageNames; 11508 } 11509 11510 // List of package names for whom the suspended state has changed. 11511 List<String> changedPackages = new ArrayList<>(packageNames.length); 11512 // List of package names for whom the suspended state is not set as requested in this 11513 // method. 11514 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11515 long callingId = Binder.clearCallingIdentity(); 11516 try { 11517 for (int i = 0; i < packageNames.length; i++) { 11518 String packageName = packageNames[i]; 11519 boolean changed = false; 11520 final int appId; 11521 synchronized (mPackages) { 11522 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11523 if (pkgSetting == null) { 11524 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11525 + "\". Skipping suspending/un-suspending."); 11526 unactionedPackages.add(packageName); 11527 continue; 11528 } 11529 appId = pkgSetting.appId; 11530 if (pkgSetting.getSuspended(userId) != suspended) { 11531 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11532 unactionedPackages.add(packageName); 11533 continue; 11534 } 11535 pkgSetting.setSuspended(suspended, userId); 11536 mSettings.writePackageRestrictionsLPr(userId); 11537 changed = true; 11538 changedPackages.add(packageName); 11539 } 11540 } 11541 11542 if (changed && suspended) { 11543 killApplication(packageName, UserHandle.getUid(userId, appId), 11544 "suspending package"); 11545 } 11546 } 11547 } finally { 11548 Binder.restoreCallingIdentity(callingId); 11549 } 11550 11551 if (!changedPackages.isEmpty()) { 11552 sendPackagesSuspendedForUser(changedPackages.toArray( 11553 new String[changedPackages.size()]), userId, suspended); 11554 } 11555 11556 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11557 } 11558 11559 @Override 11560 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11561 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11562 true /* requireFullPermission */, false /* checkShell */, 11563 "isPackageSuspendedForUser for user " + userId); 11564 synchronized (mPackages) { 11565 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11566 if (pkgSetting == null) { 11567 throw new IllegalArgumentException("Unknown target package: " + packageName); 11568 } 11569 return pkgSetting.getSuspended(userId); 11570 } 11571 } 11572 11573 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11574 if (isPackageDeviceAdmin(packageName, userId)) { 11575 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11576 + "\": has an active device admin"); 11577 return false; 11578 } 11579 11580 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11581 if (packageName.equals(activeLauncherPackageName)) { 11582 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11583 + "\": contains the active launcher"); 11584 return false; 11585 } 11586 11587 if (packageName.equals(mRequiredInstallerPackage)) { 11588 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11589 + "\": required for package installation"); 11590 return false; 11591 } 11592 11593 if (packageName.equals(mRequiredVerifierPackage)) { 11594 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11595 + "\": required for package verification"); 11596 return false; 11597 } 11598 11599 if (packageName.equals(getDefaultDialerPackageName(userId))) { 11600 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11601 + "\": is the default dialer"); 11602 return false; 11603 } 11604 11605 return true; 11606 } 11607 11608 private String getActiveLauncherPackageName(int userId) { 11609 Intent intent = new Intent(Intent.ACTION_MAIN); 11610 intent.addCategory(Intent.CATEGORY_HOME); 11611 ResolveInfo resolveInfo = resolveIntent( 11612 intent, 11613 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11614 PackageManager.MATCH_DEFAULT_ONLY, 11615 userId); 11616 11617 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11618 } 11619 11620 private String getDefaultDialerPackageName(int userId) { 11621 synchronized (mPackages) { 11622 return mSettings.getDefaultDialerPackageNameLPw(userId); 11623 } 11624 } 11625 11626 @Override 11627 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11628 mContext.enforceCallingOrSelfPermission( 11629 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11630 "Only package verification agents can verify applications"); 11631 11632 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11633 final PackageVerificationResponse response = new PackageVerificationResponse( 11634 verificationCode, Binder.getCallingUid()); 11635 msg.arg1 = id; 11636 msg.obj = response; 11637 mHandler.sendMessage(msg); 11638 } 11639 11640 @Override 11641 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11642 long millisecondsToDelay) { 11643 mContext.enforceCallingOrSelfPermission( 11644 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11645 "Only package verification agents can extend verification timeouts"); 11646 11647 final PackageVerificationState state = mPendingVerification.get(id); 11648 final PackageVerificationResponse response = new PackageVerificationResponse( 11649 verificationCodeAtTimeout, Binder.getCallingUid()); 11650 11651 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11652 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11653 } 11654 if (millisecondsToDelay < 0) { 11655 millisecondsToDelay = 0; 11656 } 11657 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11658 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11659 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11660 } 11661 11662 if ((state != null) && !state.timeoutExtended()) { 11663 state.extendTimeout(); 11664 11665 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11666 msg.arg1 = id; 11667 msg.obj = response; 11668 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11669 } 11670 } 11671 11672 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11673 int verificationCode, UserHandle user) { 11674 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11675 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11676 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11677 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11678 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11679 11680 mContext.sendBroadcastAsUser(intent, user, 11681 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11682 } 11683 11684 private ComponentName matchComponentForVerifier(String packageName, 11685 List<ResolveInfo> receivers) { 11686 ActivityInfo targetReceiver = null; 11687 11688 final int NR = receivers.size(); 11689 for (int i = 0; i < NR; i++) { 11690 final ResolveInfo info = receivers.get(i); 11691 if (info.activityInfo == null) { 11692 continue; 11693 } 11694 11695 if (packageName.equals(info.activityInfo.packageName)) { 11696 targetReceiver = info.activityInfo; 11697 break; 11698 } 11699 } 11700 11701 if (targetReceiver == null) { 11702 return null; 11703 } 11704 11705 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11706 } 11707 11708 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11709 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11710 if (pkgInfo.verifiers.length == 0) { 11711 return null; 11712 } 11713 11714 final int N = pkgInfo.verifiers.length; 11715 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11716 for (int i = 0; i < N; i++) { 11717 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11718 11719 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11720 receivers); 11721 if (comp == null) { 11722 continue; 11723 } 11724 11725 final int verifierUid = getUidForVerifier(verifierInfo); 11726 if (verifierUid == -1) { 11727 continue; 11728 } 11729 11730 if (DEBUG_VERIFY) { 11731 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11732 + " with the correct signature"); 11733 } 11734 sufficientVerifiers.add(comp); 11735 verificationState.addSufficientVerifier(verifierUid); 11736 } 11737 11738 return sufficientVerifiers; 11739 } 11740 11741 private int getUidForVerifier(VerifierInfo verifierInfo) { 11742 synchronized (mPackages) { 11743 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11744 if (pkg == null) { 11745 return -1; 11746 } else if (pkg.mSignatures.length != 1) { 11747 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11748 + " has more than one signature; ignoring"); 11749 return -1; 11750 } 11751 11752 /* 11753 * If the public key of the package's signature does not match 11754 * our expected public key, then this is a different package and 11755 * we should skip. 11756 */ 11757 11758 final byte[] expectedPublicKey; 11759 try { 11760 final Signature verifierSig = pkg.mSignatures[0]; 11761 final PublicKey publicKey = verifierSig.getPublicKey(); 11762 expectedPublicKey = publicKey.getEncoded(); 11763 } catch (CertificateException e) { 11764 return -1; 11765 } 11766 11767 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11768 11769 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11770 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11771 + " does not have the expected public key; ignoring"); 11772 return -1; 11773 } 11774 11775 return pkg.applicationInfo.uid; 11776 } 11777 } 11778 11779 @Override 11780 public void finishPackageInstall(int token, boolean didLaunch) { 11781 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11782 11783 if (DEBUG_INSTALL) { 11784 Slog.v(TAG, "BM finishing package install for " + token); 11785 } 11786 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11787 11788 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, didLaunch ? 1 : 0); 11789 mHandler.sendMessage(msg); 11790 } 11791 11792 /** 11793 * Get the verification agent timeout. 11794 * 11795 * @return verification timeout in milliseconds 11796 */ 11797 private long getVerificationTimeout() { 11798 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11799 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11800 DEFAULT_VERIFICATION_TIMEOUT); 11801 } 11802 11803 /** 11804 * Get the default verification agent response code. 11805 * 11806 * @return default verification response code 11807 */ 11808 private int getDefaultVerificationResponse() { 11809 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11810 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11811 DEFAULT_VERIFICATION_RESPONSE); 11812 } 11813 11814 /** 11815 * Check whether or not package verification has been enabled. 11816 * 11817 * @return true if verification should be performed 11818 */ 11819 private boolean isVerificationEnabled(int userId, int installFlags) { 11820 if (!DEFAULT_VERIFY_ENABLE) { 11821 return false; 11822 } 11823 // Ephemeral apps don't get the full verification treatment 11824 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11825 if (DEBUG_EPHEMERAL) { 11826 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11827 } 11828 return false; 11829 } 11830 11831 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11832 11833 // Check if installing from ADB 11834 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11835 // Do not run verification in a test harness environment 11836 if (ActivityManager.isRunningInTestHarness()) { 11837 return false; 11838 } 11839 if (ensureVerifyAppsEnabled) { 11840 return true; 11841 } 11842 // Check if the developer does not want package verification for ADB installs 11843 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11844 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11845 return false; 11846 } 11847 } 11848 11849 if (ensureVerifyAppsEnabled) { 11850 return true; 11851 } 11852 11853 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11854 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11855 } 11856 11857 @Override 11858 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11859 throws RemoteException { 11860 mContext.enforceCallingOrSelfPermission( 11861 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11862 "Only intentfilter verification agents can verify applications"); 11863 11864 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11865 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11866 Binder.getCallingUid(), verificationCode, failedDomains); 11867 msg.arg1 = id; 11868 msg.obj = response; 11869 mHandler.sendMessage(msg); 11870 } 11871 11872 @Override 11873 public int getIntentVerificationStatus(String packageName, int userId) { 11874 synchronized (mPackages) { 11875 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11876 } 11877 } 11878 11879 @Override 11880 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11881 mContext.enforceCallingOrSelfPermission( 11882 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11883 11884 boolean result = false; 11885 synchronized (mPackages) { 11886 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11887 } 11888 if (result) { 11889 scheduleWritePackageRestrictionsLocked(userId); 11890 } 11891 return result; 11892 } 11893 11894 @Override 11895 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11896 String packageName) { 11897 synchronized (mPackages) { 11898 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11899 } 11900 } 11901 11902 @Override 11903 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11904 if (TextUtils.isEmpty(packageName)) { 11905 return ParceledListSlice.emptyList(); 11906 } 11907 synchronized (mPackages) { 11908 PackageParser.Package pkg = mPackages.get(packageName); 11909 if (pkg == null || pkg.activities == null) { 11910 return ParceledListSlice.emptyList(); 11911 } 11912 final int count = pkg.activities.size(); 11913 ArrayList<IntentFilter> result = new ArrayList<>(); 11914 for (int n=0; n<count; n++) { 11915 PackageParser.Activity activity = pkg.activities.get(n); 11916 if (activity.intents != null && activity.intents.size() > 0) { 11917 result.addAll(activity.intents); 11918 } 11919 } 11920 return new ParceledListSlice<>(result); 11921 } 11922 } 11923 11924 @Override 11925 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11926 mContext.enforceCallingOrSelfPermission( 11927 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11928 11929 synchronized (mPackages) { 11930 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11931 if (packageName != null) { 11932 result |= updateIntentVerificationStatus(packageName, 11933 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11934 userId); 11935 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11936 packageName, userId); 11937 } 11938 return result; 11939 } 11940 } 11941 11942 @Override 11943 public String getDefaultBrowserPackageName(int userId) { 11944 synchronized (mPackages) { 11945 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11946 } 11947 } 11948 11949 /** 11950 * Get the "allow unknown sources" setting. 11951 * 11952 * @return the current "allow unknown sources" setting 11953 */ 11954 private int getUnknownSourcesSettings() { 11955 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11956 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11957 -1); 11958 } 11959 11960 @Override 11961 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11962 final int uid = Binder.getCallingUid(); 11963 // writer 11964 synchronized (mPackages) { 11965 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11966 if (targetPackageSetting == null) { 11967 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11968 } 11969 11970 PackageSetting installerPackageSetting; 11971 if (installerPackageName != null) { 11972 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11973 if (installerPackageSetting == null) { 11974 throw new IllegalArgumentException("Unknown installer package: " 11975 + installerPackageName); 11976 } 11977 } else { 11978 installerPackageSetting = null; 11979 } 11980 11981 Signature[] callerSignature; 11982 Object obj = mSettings.getUserIdLPr(uid); 11983 if (obj != null) { 11984 if (obj instanceof SharedUserSetting) { 11985 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11986 } else if (obj instanceof PackageSetting) { 11987 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11988 } else { 11989 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11990 } 11991 } else { 11992 throw new SecurityException("Unknown calling UID: " + uid); 11993 } 11994 11995 // Verify: can't set installerPackageName to a package that is 11996 // not signed with the same cert as the caller. 11997 if (installerPackageSetting != null) { 11998 if (compareSignatures(callerSignature, 11999 installerPackageSetting.signatures.mSignatures) 12000 != PackageManager.SIGNATURE_MATCH) { 12001 throw new SecurityException( 12002 "Caller does not have same cert as new installer package " 12003 + installerPackageName); 12004 } 12005 } 12006 12007 // Verify: if target already has an installer package, it must 12008 // be signed with the same cert as the caller. 12009 if (targetPackageSetting.installerPackageName != null) { 12010 PackageSetting setting = mSettings.mPackages.get( 12011 targetPackageSetting.installerPackageName); 12012 // If the currently set package isn't valid, then it's always 12013 // okay to change it. 12014 if (setting != null) { 12015 if (compareSignatures(callerSignature, 12016 setting.signatures.mSignatures) 12017 != PackageManager.SIGNATURE_MATCH) { 12018 throw new SecurityException( 12019 "Caller does not have same cert as old installer package " 12020 + targetPackageSetting.installerPackageName); 12021 } 12022 } 12023 } 12024 12025 // Okay! 12026 targetPackageSetting.installerPackageName = installerPackageName; 12027 if (installerPackageName != null) { 12028 mSettings.mInstallerPackages.add(installerPackageName); 12029 } 12030 scheduleWriteSettingsLocked(); 12031 } 12032 } 12033 12034 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 12035 // Queue up an async operation since the package installation may take a little while. 12036 mHandler.post(new Runnable() { 12037 public void run() { 12038 mHandler.removeCallbacks(this); 12039 // Result object to be returned 12040 PackageInstalledInfo res = new PackageInstalledInfo(); 12041 res.setReturnCode(currentStatus); 12042 res.uid = -1; 12043 res.pkg = null; 12044 res.removedInfo = null; 12045 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 12046 args.doPreInstall(res.returnCode); 12047 synchronized (mInstallLock) { 12048 installPackageTracedLI(args, res); 12049 } 12050 args.doPostInstall(res.returnCode, res.uid); 12051 } 12052 12053 // A restore should be performed at this point if (a) the install 12054 // succeeded, (b) the operation is not an update, and (c) the new 12055 // package has not opted out of backup participation. 12056 final boolean update = res.removedInfo != null 12057 && res.removedInfo.removedPackage != null; 12058 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12059 boolean doRestore = !update 12060 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12061 12062 // Set up the post-install work request bookkeeping. This will be used 12063 // and cleaned up by the post-install event handling regardless of whether 12064 // there's a restore pass performed. Token values are >= 1. 12065 int token; 12066 if (mNextInstallToken < 0) mNextInstallToken = 1; 12067 token = mNextInstallToken++; 12068 12069 PostInstallData data = new PostInstallData(args, res); 12070 mRunningInstalls.put(token, data); 12071 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12072 12073 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12074 // Pass responsibility to the Backup Manager. It will perform a 12075 // restore if appropriate, then pass responsibility back to the 12076 // Package Manager to run the post-install observer callbacks 12077 // and broadcasts. 12078 IBackupManager bm = IBackupManager.Stub.asInterface( 12079 ServiceManager.getService(Context.BACKUP_SERVICE)); 12080 if (bm != null) { 12081 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12082 + " to BM for possible restore"); 12083 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12084 try { 12085 // TODO: http://b/22388012 12086 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12087 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12088 } else { 12089 doRestore = false; 12090 } 12091 } catch (RemoteException e) { 12092 // can't happen; the backup manager is local 12093 } catch (Exception e) { 12094 Slog.e(TAG, "Exception trying to enqueue restore", e); 12095 doRestore = false; 12096 } 12097 } else { 12098 Slog.e(TAG, "Backup Manager not found!"); 12099 doRestore = false; 12100 } 12101 } 12102 12103 if (!doRestore) { 12104 // No restore possible, or the Backup Manager was mysteriously not 12105 // available -- just fire the post-install work request directly. 12106 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12107 12108 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12109 12110 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12111 mHandler.sendMessage(msg); 12112 } 12113 } 12114 }); 12115 } 12116 12117 /** 12118 * Callback from PackageSettings whenever an app is first transitioned out of the 12119 * 'stopped' state. Normally we just issue the broadcast, but we can't do that if 12120 * the app was "launched" for a restoreAtInstall operation. Therefore we check 12121 * here whether the app is the target of an ongoing install, and only send the 12122 * broadcast immediately if it is not in that state. If it *is* undergoing a restore, 12123 * the first-launch broadcast will be sent implicitly on that basis in POST_INSTALL 12124 * handling. 12125 */ 12126 void notifyFirstLaunch(final String pkgName, final String installerPackage, final int userId) { 12127 // Serialize this with the rest of the install-process message chain. In the 12128 // restore-at-install case, this Runnable will necessarily run before the 12129 // POST_INSTALL message is processed, so the contents of mRunningInstalls 12130 // are coherent. In the non-restore case, the app has already completed install 12131 // and been launched through some other means, so it is not in a problematic 12132 // state for observers to see the FIRST_LAUNCH signal. 12133 mHandler.post(new Runnable() { 12134 @Override 12135 public void run() { 12136 for (int i = 0; i < mRunningInstalls.size(); i++) { 12137 final PostInstallData data = mRunningInstalls.valueAt(i); 12138 if (pkgName.equals(data.res.pkg.applicationInfo.packageName)) { 12139 // right package; but is it for the right user? 12140 for (int uIndex = 0; uIndex < data.res.newUsers.length; uIndex++) { 12141 if (userId == data.res.newUsers[uIndex]) { 12142 if (DEBUG_BACKUP) { 12143 Slog.i(TAG, "Package " + pkgName 12144 + " being restored so deferring FIRST_LAUNCH"); 12145 } 12146 return; 12147 } 12148 } 12149 } 12150 } 12151 // didn't find it, so not being restored 12152 if (DEBUG_BACKUP) { 12153 Slog.i(TAG, "Package " + pkgName + " sending normal FIRST_LAUNCH"); 12154 } 12155 sendFirstLaunchBroadcast(pkgName, installerPackage, new int[] {userId}); 12156 } 12157 }); 12158 } 12159 12160 private void sendFirstLaunchBroadcast(String pkgName, String installerPkg, int[] userIds) { 12161 sendPackageBroadcast(Intent.ACTION_PACKAGE_FIRST_LAUNCH, pkgName, null, 0, 12162 installerPkg, null, userIds); 12163 } 12164 12165 private abstract class HandlerParams { 12166 private static final int MAX_RETRIES = 4; 12167 12168 /** 12169 * Number of times startCopy() has been attempted and had a non-fatal 12170 * error. 12171 */ 12172 private int mRetries = 0; 12173 12174 /** User handle for the user requesting the information or installation. */ 12175 private final UserHandle mUser; 12176 String traceMethod; 12177 int traceCookie; 12178 12179 HandlerParams(UserHandle user) { 12180 mUser = user; 12181 } 12182 12183 UserHandle getUser() { 12184 return mUser; 12185 } 12186 12187 HandlerParams setTraceMethod(String traceMethod) { 12188 this.traceMethod = traceMethod; 12189 return this; 12190 } 12191 12192 HandlerParams setTraceCookie(int traceCookie) { 12193 this.traceCookie = traceCookie; 12194 return this; 12195 } 12196 12197 final boolean startCopy() { 12198 boolean res; 12199 try { 12200 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12201 12202 if (++mRetries > MAX_RETRIES) { 12203 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12204 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12205 handleServiceError(); 12206 return false; 12207 } else { 12208 handleStartCopy(); 12209 res = true; 12210 } 12211 } catch (RemoteException e) { 12212 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12213 mHandler.sendEmptyMessage(MCS_RECONNECT); 12214 res = false; 12215 } 12216 handleReturnCode(); 12217 return res; 12218 } 12219 12220 final void serviceError() { 12221 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12222 handleServiceError(); 12223 handleReturnCode(); 12224 } 12225 12226 abstract void handleStartCopy() throws RemoteException; 12227 abstract void handleServiceError(); 12228 abstract void handleReturnCode(); 12229 } 12230 12231 class MeasureParams extends HandlerParams { 12232 private final PackageStats mStats; 12233 private boolean mSuccess; 12234 12235 private final IPackageStatsObserver mObserver; 12236 12237 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12238 super(new UserHandle(stats.userHandle)); 12239 mObserver = observer; 12240 mStats = stats; 12241 } 12242 12243 @Override 12244 public String toString() { 12245 return "MeasureParams{" 12246 + Integer.toHexString(System.identityHashCode(this)) 12247 + " " + mStats.packageName + "}"; 12248 } 12249 12250 @Override 12251 void handleStartCopy() throws RemoteException { 12252 synchronized (mInstallLock) { 12253 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12254 } 12255 12256 if (mSuccess) { 12257 final boolean mounted; 12258 if (Environment.isExternalStorageEmulated()) { 12259 mounted = true; 12260 } else { 12261 final String status = Environment.getExternalStorageState(); 12262 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12263 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12264 } 12265 12266 if (mounted) { 12267 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12268 12269 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12270 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12271 12272 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12273 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12274 12275 // Always subtract cache size, since it's a subdirectory 12276 mStats.externalDataSize -= mStats.externalCacheSize; 12277 12278 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12279 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12280 12281 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12282 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12283 } 12284 } 12285 } 12286 12287 @Override 12288 void handleReturnCode() { 12289 if (mObserver != null) { 12290 try { 12291 mObserver.onGetStatsCompleted(mStats, mSuccess); 12292 } catch (RemoteException e) { 12293 Slog.i(TAG, "Observer no longer exists."); 12294 } 12295 } 12296 } 12297 12298 @Override 12299 void handleServiceError() { 12300 Slog.e(TAG, "Could not measure application " + mStats.packageName 12301 + " external storage"); 12302 } 12303 } 12304 12305 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12306 throws RemoteException { 12307 long result = 0; 12308 for (File path : paths) { 12309 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12310 } 12311 return result; 12312 } 12313 12314 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12315 for (File path : paths) { 12316 try { 12317 mcs.clearDirectory(path.getAbsolutePath()); 12318 } catch (RemoteException e) { 12319 } 12320 } 12321 } 12322 12323 static class OriginInfo { 12324 /** 12325 * Location where install is coming from, before it has been 12326 * copied/renamed into place. This could be a single monolithic APK 12327 * file, or a cluster directory. This location may be untrusted. 12328 */ 12329 final File file; 12330 final String cid; 12331 12332 /** 12333 * Flag indicating that {@link #file} or {@link #cid} has already been 12334 * staged, meaning downstream users don't need to defensively copy the 12335 * contents. 12336 */ 12337 final boolean staged; 12338 12339 /** 12340 * Flag indicating that {@link #file} or {@link #cid} is an already 12341 * installed app that is being moved. 12342 */ 12343 final boolean existing; 12344 12345 final String resolvedPath; 12346 final File resolvedFile; 12347 12348 static OriginInfo fromNothing() { 12349 return new OriginInfo(null, null, false, false); 12350 } 12351 12352 static OriginInfo fromUntrustedFile(File file) { 12353 return new OriginInfo(file, null, false, false); 12354 } 12355 12356 static OriginInfo fromExistingFile(File file) { 12357 return new OriginInfo(file, null, false, true); 12358 } 12359 12360 static OriginInfo fromStagedFile(File file) { 12361 return new OriginInfo(file, null, true, false); 12362 } 12363 12364 static OriginInfo fromStagedContainer(String cid) { 12365 return new OriginInfo(null, cid, true, false); 12366 } 12367 12368 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12369 this.file = file; 12370 this.cid = cid; 12371 this.staged = staged; 12372 this.existing = existing; 12373 12374 if (cid != null) { 12375 resolvedPath = PackageHelper.getSdDir(cid); 12376 resolvedFile = new File(resolvedPath); 12377 } else if (file != null) { 12378 resolvedPath = file.getAbsolutePath(); 12379 resolvedFile = file; 12380 } else { 12381 resolvedPath = null; 12382 resolvedFile = null; 12383 } 12384 } 12385 } 12386 12387 static class MoveInfo { 12388 final int moveId; 12389 final String fromUuid; 12390 final String toUuid; 12391 final String packageName; 12392 final String dataAppName; 12393 final int appId; 12394 final String seinfo; 12395 final int targetSdkVersion; 12396 12397 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12398 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12399 this.moveId = moveId; 12400 this.fromUuid = fromUuid; 12401 this.toUuid = toUuid; 12402 this.packageName = packageName; 12403 this.dataAppName = dataAppName; 12404 this.appId = appId; 12405 this.seinfo = seinfo; 12406 this.targetSdkVersion = targetSdkVersion; 12407 } 12408 } 12409 12410 static class VerificationInfo { 12411 /** A constant used to indicate that a uid value is not present. */ 12412 public static final int NO_UID = -1; 12413 12414 /** URI referencing where the package was downloaded from. */ 12415 final Uri originatingUri; 12416 12417 /** HTTP referrer URI associated with the originatingURI. */ 12418 final Uri referrer; 12419 12420 /** UID of the application that the install request originated from. */ 12421 final int originatingUid; 12422 12423 /** UID of application requesting the install */ 12424 final int installerUid; 12425 12426 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12427 this.originatingUri = originatingUri; 12428 this.referrer = referrer; 12429 this.originatingUid = originatingUid; 12430 this.installerUid = installerUid; 12431 } 12432 } 12433 12434 class InstallParams extends HandlerParams { 12435 final OriginInfo origin; 12436 final MoveInfo move; 12437 final IPackageInstallObserver2 observer; 12438 int installFlags; 12439 final String installerPackageName; 12440 final String volumeUuid; 12441 private InstallArgs mArgs; 12442 private int mRet; 12443 final String packageAbiOverride; 12444 final String[] grantedRuntimePermissions; 12445 final VerificationInfo verificationInfo; 12446 final Certificate[][] certificates; 12447 12448 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12449 int installFlags, String installerPackageName, String volumeUuid, 12450 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12451 String[] grantedPermissions, Certificate[][] certificates) { 12452 super(user); 12453 this.origin = origin; 12454 this.move = move; 12455 this.observer = observer; 12456 this.installFlags = installFlags; 12457 this.installerPackageName = installerPackageName; 12458 this.volumeUuid = volumeUuid; 12459 this.verificationInfo = verificationInfo; 12460 this.packageAbiOverride = packageAbiOverride; 12461 this.grantedRuntimePermissions = grantedPermissions; 12462 this.certificates = certificates; 12463 } 12464 12465 @Override 12466 public String toString() { 12467 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12468 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12469 } 12470 12471 private int installLocationPolicy(PackageInfoLite pkgLite) { 12472 String packageName = pkgLite.packageName; 12473 int installLocation = pkgLite.installLocation; 12474 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12475 // reader 12476 synchronized (mPackages) { 12477 // Currently installed package which the new package is attempting to replace or 12478 // null if no such package is installed. 12479 PackageParser.Package installedPkg = mPackages.get(packageName); 12480 // Package which currently owns the data which the new package will own if installed. 12481 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12482 // will be null whereas dataOwnerPkg will contain information about the package 12483 // which was uninstalled while keeping its data. 12484 PackageParser.Package dataOwnerPkg = installedPkg; 12485 if (dataOwnerPkg == null) { 12486 PackageSetting ps = mSettings.mPackages.get(packageName); 12487 if (ps != null) { 12488 dataOwnerPkg = ps.pkg; 12489 } 12490 } 12491 12492 if (dataOwnerPkg != null) { 12493 // If installed, the package will get access to data left on the device by its 12494 // predecessor. As a security measure, this is permited only if this is not a 12495 // version downgrade or if the predecessor package is marked as debuggable and 12496 // a downgrade is explicitly requested. 12497 // 12498 // On debuggable platform builds, downgrades are permitted even for 12499 // non-debuggable packages to make testing easier. Debuggable platform builds do 12500 // not offer security guarantees and thus it's OK to disable some security 12501 // mechanisms to make debugging/testing easier on those builds. However, even on 12502 // debuggable builds downgrades of packages are permitted only if requested via 12503 // installFlags. This is because we aim to keep the behavior of debuggable 12504 // platform builds as close as possible to the behavior of non-debuggable 12505 // platform builds. 12506 final boolean downgradeRequested = 12507 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12508 final boolean packageDebuggable = 12509 (dataOwnerPkg.applicationInfo.flags 12510 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12511 final boolean downgradePermitted = 12512 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12513 if (!downgradePermitted) { 12514 try { 12515 checkDowngrade(dataOwnerPkg, pkgLite); 12516 } catch (PackageManagerException e) { 12517 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12518 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12519 } 12520 } 12521 } 12522 12523 if (installedPkg != null) { 12524 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12525 // Check for updated system application. 12526 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12527 if (onSd) { 12528 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12529 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12530 } 12531 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12532 } else { 12533 if (onSd) { 12534 // Install flag overrides everything. 12535 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12536 } 12537 // If current upgrade specifies particular preference 12538 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12539 // Application explicitly specified internal. 12540 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12541 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12542 // App explictly prefers external. Let policy decide 12543 } else { 12544 // Prefer previous location 12545 if (isExternal(installedPkg)) { 12546 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12547 } 12548 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12549 } 12550 } 12551 } else { 12552 // Invalid install. Return error code 12553 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12554 } 12555 } 12556 } 12557 // All the special cases have been taken care of. 12558 // Return result based on recommended install location. 12559 if (onSd) { 12560 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12561 } 12562 return pkgLite.recommendedInstallLocation; 12563 } 12564 12565 /* 12566 * Invoke remote method to get package information and install 12567 * location values. Override install location based on default 12568 * policy if needed and then create install arguments based 12569 * on the install location. 12570 */ 12571 public void handleStartCopy() throws RemoteException { 12572 int ret = PackageManager.INSTALL_SUCCEEDED; 12573 12574 // If we're already staged, we've firmly committed to an install location 12575 if (origin.staged) { 12576 if (origin.file != null) { 12577 installFlags |= PackageManager.INSTALL_INTERNAL; 12578 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12579 } else if (origin.cid != null) { 12580 installFlags |= PackageManager.INSTALL_EXTERNAL; 12581 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12582 } else { 12583 throw new IllegalStateException("Invalid stage location"); 12584 } 12585 } 12586 12587 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12588 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12589 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12590 PackageInfoLite pkgLite = null; 12591 12592 if (onInt && onSd) { 12593 // Check if both bits are set. 12594 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12595 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12596 } else if (onSd && ephemeral) { 12597 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12598 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12599 } else { 12600 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12601 packageAbiOverride); 12602 12603 if (DEBUG_EPHEMERAL && ephemeral) { 12604 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12605 } 12606 12607 /* 12608 * If we have too little free space, try to free cache 12609 * before giving up. 12610 */ 12611 if (!origin.staged && pkgLite.recommendedInstallLocation 12612 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12613 // TODO: focus freeing disk space on the target device 12614 final StorageManager storage = StorageManager.from(mContext); 12615 final long lowThreshold = storage.getStorageLowBytes( 12616 Environment.getDataDirectory()); 12617 12618 final long sizeBytes = mContainerService.calculateInstalledSize( 12619 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12620 12621 try { 12622 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12623 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12624 installFlags, packageAbiOverride); 12625 } catch (InstallerException e) { 12626 Slog.w(TAG, "Failed to free cache", e); 12627 } 12628 12629 /* 12630 * The cache free must have deleted the file we 12631 * downloaded to install. 12632 * 12633 * TODO: fix the "freeCache" call to not delete 12634 * the file we care about. 12635 */ 12636 if (pkgLite.recommendedInstallLocation 12637 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12638 pkgLite.recommendedInstallLocation 12639 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12640 } 12641 } 12642 } 12643 12644 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12645 int loc = pkgLite.recommendedInstallLocation; 12646 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12647 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12648 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12649 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12650 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12651 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12652 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12653 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12654 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12655 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12656 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12657 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12658 } else { 12659 // Override with defaults if needed. 12660 loc = installLocationPolicy(pkgLite); 12661 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12662 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12663 } else if (!onSd && !onInt) { 12664 // Override install location with flags 12665 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12666 // Set the flag to install on external media. 12667 installFlags |= PackageManager.INSTALL_EXTERNAL; 12668 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12669 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12670 if (DEBUG_EPHEMERAL) { 12671 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12672 } 12673 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12674 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12675 |PackageManager.INSTALL_INTERNAL); 12676 } else { 12677 // Make sure the flag for installing on external 12678 // media is unset 12679 installFlags |= PackageManager.INSTALL_INTERNAL; 12680 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12681 } 12682 } 12683 } 12684 } 12685 12686 final InstallArgs args = createInstallArgs(this); 12687 mArgs = args; 12688 12689 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12690 // TODO: http://b/22976637 12691 // Apps installed for "all" users use the device owner to verify the app 12692 UserHandle verifierUser = getUser(); 12693 if (verifierUser == UserHandle.ALL) { 12694 verifierUser = UserHandle.SYSTEM; 12695 } 12696 12697 /* 12698 * Determine if we have any installed package verifiers. If we 12699 * do, then we'll defer to them to verify the packages. 12700 */ 12701 final int requiredUid = mRequiredVerifierPackage == null ? -1 12702 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12703 verifierUser.getIdentifier()); 12704 if (!origin.existing && requiredUid != -1 12705 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12706 final Intent verification = new Intent( 12707 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12708 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12709 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12710 PACKAGE_MIME_TYPE); 12711 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12712 12713 // Query all live verifiers based on current user state 12714 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12715 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12716 12717 if (DEBUG_VERIFY) { 12718 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12719 + verification.toString() + " with " + pkgLite.verifiers.length 12720 + " optional verifiers"); 12721 } 12722 12723 final int verificationId = mPendingVerificationToken++; 12724 12725 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12726 12727 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12728 installerPackageName); 12729 12730 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12731 installFlags); 12732 12733 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12734 pkgLite.packageName); 12735 12736 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12737 pkgLite.versionCode); 12738 12739 if (verificationInfo != null) { 12740 if (verificationInfo.originatingUri != null) { 12741 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12742 verificationInfo.originatingUri); 12743 } 12744 if (verificationInfo.referrer != null) { 12745 verification.putExtra(Intent.EXTRA_REFERRER, 12746 verificationInfo.referrer); 12747 } 12748 if (verificationInfo.originatingUid >= 0) { 12749 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12750 verificationInfo.originatingUid); 12751 } 12752 if (verificationInfo.installerUid >= 0) { 12753 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12754 verificationInfo.installerUid); 12755 } 12756 } 12757 12758 final PackageVerificationState verificationState = new PackageVerificationState( 12759 requiredUid, args); 12760 12761 mPendingVerification.append(verificationId, verificationState); 12762 12763 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12764 receivers, verificationState); 12765 12766 /* 12767 * If any sufficient verifiers were listed in the package 12768 * manifest, attempt to ask them. 12769 */ 12770 if (sufficientVerifiers != null) { 12771 final int N = sufficientVerifiers.size(); 12772 if (N == 0) { 12773 Slog.i(TAG, "Additional verifiers required, but none installed."); 12774 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12775 } else { 12776 for (int i = 0; i < N; i++) { 12777 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12778 12779 final Intent sufficientIntent = new Intent(verification); 12780 sufficientIntent.setComponent(verifierComponent); 12781 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12782 } 12783 } 12784 } 12785 12786 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12787 mRequiredVerifierPackage, receivers); 12788 if (ret == PackageManager.INSTALL_SUCCEEDED 12789 && mRequiredVerifierPackage != null) { 12790 Trace.asyncTraceBegin( 12791 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12792 /* 12793 * Send the intent to the required verification agent, 12794 * but only start the verification timeout after the 12795 * target BroadcastReceivers have run. 12796 */ 12797 verification.setComponent(requiredVerifierComponent); 12798 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12799 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12800 new BroadcastReceiver() { 12801 @Override 12802 public void onReceive(Context context, Intent intent) { 12803 final Message msg = mHandler 12804 .obtainMessage(CHECK_PENDING_VERIFICATION); 12805 msg.arg1 = verificationId; 12806 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12807 } 12808 }, null, 0, null, null); 12809 12810 /* 12811 * We don't want the copy to proceed until verification 12812 * succeeds, so null out this field. 12813 */ 12814 mArgs = null; 12815 } 12816 } else { 12817 /* 12818 * No package verification is enabled, so immediately start 12819 * the remote call to initiate copy using temporary file. 12820 */ 12821 ret = args.copyApk(mContainerService, true); 12822 } 12823 } 12824 12825 mRet = ret; 12826 } 12827 12828 @Override 12829 void handleReturnCode() { 12830 // If mArgs is null, then MCS couldn't be reached. When it 12831 // reconnects, it will try again to install. At that point, this 12832 // will succeed. 12833 if (mArgs != null) { 12834 processPendingInstall(mArgs, mRet); 12835 } 12836 } 12837 12838 @Override 12839 void handleServiceError() { 12840 mArgs = createInstallArgs(this); 12841 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12842 } 12843 12844 public boolean isForwardLocked() { 12845 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12846 } 12847 } 12848 12849 /** 12850 * Used during creation of InstallArgs 12851 * 12852 * @param installFlags package installation flags 12853 * @return true if should be installed on external storage 12854 */ 12855 private static boolean installOnExternalAsec(int installFlags) { 12856 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12857 return false; 12858 } 12859 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12860 return true; 12861 } 12862 return false; 12863 } 12864 12865 /** 12866 * Used during creation of InstallArgs 12867 * 12868 * @param installFlags package installation flags 12869 * @return true if should be installed as forward locked 12870 */ 12871 private static boolean installForwardLocked(int installFlags) { 12872 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12873 } 12874 12875 private InstallArgs createInstallArgs(InstallParams params) { 12876 if (params.move != null) { 12877 return new MoveInstallArgs(params); 12878 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12879 return new AsecInstallArgs(params); 12880 } else { 12881 return new FileInstallArgs(params); 12882 } 12883 } 12884 12885 /** 12886 * Create args that describe an existing installed package. Typically used 12887 * when cleaning up old installs, or used as a move source. 12888 */ 12889 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12890 String resourcePath, String[] instructionSets) { 12891 final boolean isInAsec; 12892 if (installOnExternalAsec(installFlags)) { 12893 /* Apps on SD card are always in ASEC containers. */ 12894 isInAsec = true; 12895 } else if (installForwardLocked(installFlags) 12896 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12897 /* 12898 * Forward-locked apps are only in ASEC containers if they're the 12899 * new style 12900 */ 12901 isInAsec = true; 12902 } else { 12903 isInAsec = false; 12904 } 12905 12906 if (isInAsec) { 12907 return new AsecInstallArgs(codePath, instructionSets, 12908 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12909 } else { 12910 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12911 } 12912 } 12913 12914 static abstract class InstallArgs { 12915 /** @see InstallParams#origin */ 12916 final OriginInfo origin; 12917 /** @see InstallParams#move */ 12918 final MoveInfo move; 12919 12920 final IPackageInstallObserver2 observer; 12921 // Always refers to PackageManager flags only 12922 final int installFlags; 12923 final String installerPackageName; 12924 final String volumeUuid; 12925 final UserHandle user; 12926 final String abiOverride; 12927 final String[] installGrantPermissions; 12928 /** If non-null, drop an async trace when the install completes */ 12929 final String traceMethod; 12930 final int traceCookie; 12931 final Certificate[][] certificates; 12932 12933 // The list of instruction sets supported by this app. This is currently 12934 // only used during the rmdex() phase to clean up resources. We can get rid of this 12935 // if we move dex files under the common app path. 12936 /* nullable */ String[] instructionSets; 12937 12938 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12939 int installFlags, String installerPackageName, String volumeUuid, 12940 UserHandle user, String[] instructionSets, 12941 String abiOverride, String[] installGrantPermissions, 12942 String traceMethod, int traceCookie, Certificate[][] certificates) { 12943 this.origin = origin; 12944 this.move = move; 12945 this.installFlags = installFlags; 12946 this.observer = observer; 12947 this.installerPackageName = installerPackageName; 12948 this.volumeUuid = volumeUuid; 12949 this.user = user; 12950 this.instructionSets = instructionSets; 12951 this.abiOverride = abiOverride; 12952 this.installGrantPermissions = installGrantPermissions; 12953 this.traceMethod = traceMethod; 12954 this.traceCookie = traceCookie; 12955 this.certificates = certificates; 12956 } 12957 12958 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12959 abstract int doPreInstall(int status); 12960 12961 /** 12962 * Rename package into final resting place. All paths on the given 12963 * scanned package should be updated to reflect the rename. 12964 */ 12965 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12966 abstract int doPostInstall(int status, int uid); 12967 12968 /** @see PackageSettingBase#codePathString */ 12969 abstract String getCodePath(); 12970 /** @see PackageSettingBase#resourcePathString */ 12971 abstract String getResourcePath(); 12972 12973 // Need installer lock especially for dex file removal. 12974 abstract void cleanUpResourcesLI(); 12975 abstract boolean doPostDeleteLI(boolean delete); 12976 12977 /** 12978 * Called before the source arguments are copied. This is used mostly 12979 * for MoveParams when it needs to read the source file to put it in the 12980 * destination. 12981 */ 12982 int doPreCopy() { 12983 return PackageManager.INSTALL_SUCCEEDED; 12984 } 12985 12986 /** 12987 * Called after the source arguments are copied. This is used mostly for 12988 * MoveParams when it needs to read the source file to put it in the 12989 * destination. 12990 */ 12991 int doPostCopy(int uid) { 12992 return PackageManager.INSTALL_SUCCEEDED; 12993 } 12994 12995 protected boolean isFwdLocked() { 12996 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12997 } 12998 12999 protected boolean isExternalAsec() { 13000 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 13001 } 13002 13003 protected boolean isEphemeral() { 13004 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13005 } 13006 13007 UserHandle getUser() { 13008 return user; 13009 } 13010 } 13011 13012 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 13013 if (!allCodePaths.isEmpty()) { 13014 if (instructionSets == null) { 13015 throw new IllegalStateException("instructionSet == null"); 13016 } 13017 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 13018 for (String codePath : allCodePaths) { 13019 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 13020 try { 13021 mInstaller.rmdex(codePath, dexCodeInstructionSet); 13022 } catch (InstallerException ignored) { 13023 } 13024 } 13025 } 13026 } 13027 } 13028 13029 /** 13030 * Logic to handle installation of non-ASEC applications, including copying 13031 * and renaming logic. 13032 */ 13033 class FileInstallArgs extends InstallArgs { 13034 private File codeFile; 13035 private File resourceFile; 13036 13037 // Example topology: 13038 // /data/app/com.example/base.apk 13039 // /data/app/com.example/split_foo.apk 13040 // /data/app/com.example/lib/arm/libfoo.so 13041 // /data/app/com.example/lib/arm64/libfoo.so 13042 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 13043 13044 /** New install */ 13045 FileInstallArgs(InstallParams params) { 13046 super(params.origin, params.move, params.observer, params.installFlags, 13047 params.installerPackageName, params.volumeUuid, 13048 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 13049 params.grantedRuntimePermissions, 13050 params.traceMethod, params.traceCookie, params.certificates); 13051 if (isFwdLocked()) { 13052 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 13053 } 13054 } 13055 13056 /** Existing install */ 13057 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 13058 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 13059 null, null, null, 0, null /*certificates*/); 13060 this.codeFile = (codePath != null) ? new File(codePath) : null; 13061 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 13062 } 13063 13064 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13065 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 13066 try { 13067 return doCopyApk(imcs, temp); 13068 } finally { 13069 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13070 } 13071 } 13072 13073 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13074 if (origin.staged) { 13075 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 13076 codeFile = origin.file; 13077 resourceFile = origin.file; 13078 return PackageManager.INSTALL_SUCCEEDED; 13079 } 13080 13081 try { 13082 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 13083 final File tempDir = 13084 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 13085 codeFile = tempDir; 13086 resourceFile = tempDir; 13087 } catch (IOException e) { 13088 Slog.w(TAG, "Failed to create copy file: " + e); 13089 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 13090 } 13091 13092 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 13093 @Override 13094 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 13095 if (!FileUtils.isValidExtFilename(name)) { 13096 throw new IllegalArgumentException("Invalid filename: " + name); 13097 } 13098 try { 13099 final File file = new File(codeFile, name); 13100 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13101 O_RDWR | O_CREAT, 0644); 13102 Os.chmod(file.getAbsolutePath(), 0644); 13103 return new ParcelFileDescriptor(fd); 13104 } catch (ErrnoException e) { 13105 throw new RemoteException("Failed to open: " + e.getMessage()); 13106 } 13107 } 13108 }; 13109 13110 int ret = PackageManager.INSTALL_SUCCEEDED; 13111 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13112 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13113 Slog.e(TAG, "Failed to copy package"); 13114 return ret; 13115 } 13116 13117 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13118 NativeLibraryHelper.Handle handle = null; 13119 try { 13120 handle = NativeLibraryHelper.Handle.create(codeFile); 13121 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13122 abiOverride); 13123 } catch (IOException e) { 13124 Slog.e(TAG, "Copying native libraries failed", e); 13125 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13126 } finally { 13127 IoUtils.closeQuietly(handle); 13128 } 13129 13130 return ret; 13131 } 13132 13133 int doPreInstall(int status) { 13134 if (status != PackageManager.INSTALL_SUCCEEDED) { 13135 cleanUp(); 13136 } 13137 return status; 13138 } 13139 13140 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13141 if (status != PackageManager.INSTALL_SUCCEEDED) { 13142 cleanUp(); 13143 return false; 13144 } 13145 13146 final File targetDir = codeFile.getParentFile(); 13147 final File beforeCodeFile = codeFile; 13148 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13149 13150 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13151 try { 13152 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13153 } catch (ErrnoException e) { 13154 Slog.w(TAG, "Failed to rename", e); 13155 return false; 13156 } 13157 13158 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13159 Slog.w(TAG, "Failed to restorecon"); 13160 return false; 13161 } 13162 13163 // Reflect the rename internally 13164 codeFile = afterCodeFile; 13165 resourceFile = afterCodeFile; 13166 13167 // Reflect the rename in scanned details 13168 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13169 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13170 afterCodeFile, pkg.baseCodePath)); 13171 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13172 afterCodeFile, pkg.splitCodePaths)); 13173 13174 // Reflect the rename in app info 13175 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13176 pkg.setApplicationInfoCodePath(pkg.codePath); 13177 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13178 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13179 pkg.setApplicationInfoResourcePath(pkg.codePath); 13180 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13181 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13182 13183 return true; 13184 } 13185 13186 int doPostInstall(int status, int uid) { 13187 if (status != PackageManager.INSTALL_SUCCEEDED) { 13188 cleanUp(); 13189 } 13190 return status; 13191 } 13192 13193 @Override 13194 String getCodePath() { 13195 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13196 } 13197 13198 @Override 13199 String getResourcePath() { 13200 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13201 } 13202 13203 private boolean cleanUp() { 13204 if (codeFile == null || !codeFile.exists()) { 13205 return false; 13206 } 13207 13208 removeCodePathLI(codeFile); 13209 13210 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13211 resourceFile.delete(); 13212 } 13213 13214 return true; 13215 } 13216 13217 void cleanUpResourcesLI() { 13218 // Try enumerating all code paths before deleting 13219 List<String> allCodePaths = Collections.EMPTY_LIST; 13220 if (codeFile != null && codeFile.exists()) { 13221 try { 13222 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13223 allCodePaths = pkg.getAllCodePaths(); 13224 } catch (PackageParserException e) { 13225 // Ignored; we tried our best 13226 } 13227 } 13228 13229 cleanUp(); 13230 removeDexFiles(allCodePaths, instructionSets); 13231 } 13232 13233 boolean doPostDeleteLI(boolean delete) { 13234 // XXX err, shouldn't we respect the delete flag? 13235 cleanUpResourcesLI(); 13236 return true; 13237 } 13238 } 13239 13240 private boolean isAsecExternal(String cid) { 13241 final String asecPath = PackageHelper.getSdFilesystem(cid); 13242 return !asecPath.startsWith(mAsecInternalPath); 13243 } 13244 13245 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13246 PackageManagerException { 13247 if (copyRet < 0) { 13248 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13249 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13250 throw new PackageManagerException(copyRet, message); 13251 } 13252 } 13253 } 13254 13255 /** 13256 * Extract the MountService "container ID" from the full code path of an 13257 * .apk. 13258 */ 13259 static String cidFromCodePath(String fullCodePath) { 13260 int eidx = fullCodePath.lastIndexOf("/"); 13261 String subStr1 = fullCodePath.substring(0, eidx); 13262 int sidx = subStr1.lastIndexOf("/"); 13263 return subStr1.substring(sidx+1, eidx); 13264 } 13265 13266 /** 13267 * Logic to handle installation of ASEC applications, including copying and 13268 * renaming logic. 13269 */ 13270 class AsecInstallArgs extends InstallArgs { 13271 static final String RES_FILE_NAME = "pkg.apk"; 13272 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13273 13274 String cid; 13275 String packagePath; 13276 String resourcePath; 13277 13278 /** New install */ 13279 AsecInstallArgs(InstallParams params) { 13280 super(params.origin, params.move, params.observer, params.installFlags, 13281 params.installerPackageName, params.volumeUuid, 13282 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13283 params.grantedRuntimePermissions, 13284 params.traceMethod, params.traceCookie, params.certificates); 13285 } 13286 13287 /** Existing install */ 13288 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13289 boolean isExternal, boolean isForwardLocked) { 13290 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13291 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13292 instructionSets, null, null, null, 0, null /*certificates*/); 13293 // Hackily pretend we're still looking at a full code path 13294 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13295 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13296 } 13297 13298 // Extract cid from fullCodePath 13299 int eidx = fullCodePath.lastIndexOf("/"); 13300 String subStr1 = fullCodePath.substring(0, eidx); 13301 int sidx = subStr1.lastIndexOf("/"); 13302 cid = subStr1.substring(sidx+1, eidx); 13303 setMountPath(subStr1); 13304 } 13305 13306 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13307 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13308 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13309 instructionSets, null, null, null, 0, null /*certificates*/); 13310 this.cid = cid; 13311 setMountPath(PackageHelper.getSdDir(cid)); 13312 } 13313 13314 void createCopyFile() { 13315 cid = mInstallerService.allocateExternalStageCidLegacy(); 13316 } 13317 13318 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13319 if (origin.staged && origin.cid != null) { 13320 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13321 cid = origin.cid; 13322 setMountPath(PackageHelper.getSdDir(cid)); 13323 return PackageManager.INSTALL_SUCCEEDED; 13324 } 13325 13326 if (temp) { 13327 createCopyFile(); 13328 } else { 13329 /* 13330 * Pre-emptively destroy the container since it's destroyed if 13331 * copying fails due to it existing anyway. 13332 */ 13333 PackageHelper.destroySdDir(cid); 13334 } 13335 13336 final String newMountPath = imcs.copyPackageToContainer( 13337 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13338 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13339 13340 if (newMountPath != null) { 13341 setMountPath(newMountPath); 13342 return PackageManager.INSTALL_SUCCEEDED; 13343 } else { 13344 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13345 } 13346 } 13347 13348 @Override 13349 String getCodePath() { 13350 return packagePath; 13351 } 13352 13353 @Override 13354 String getResourcePath() { 13355 return resourcePath; 13356 } 13357 13358 int doPreInstall(int status) { 13359 if (status != PackageManager.INSTALL_SUCCEEDED) { 13360 // Destroy container 13361 PackageHelper.destroySdDir(cid); 13362 } else { 13363 boolean mounted = PackageHelper.isContainerMounted(cid); 13364 if (!mounted) { 13365 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13366 Process.SYSTEM_UID); 13367 if (newMountPath != null) { 13368 setMountPath(newMountPath); 13369 } else { 13370 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13371 } 13372 } 13373 } 13374 return status; 13375 } 13376 13377 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13378 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13379 String newMountPath = null; 13380 if (PackageHelper.isContainerMounted(cid)) { 13381 // Unmount the container 13382 if (!PackageHelper.unMountSdDir(cid)) { 13383 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13384 return false; 13385 } 13386 } 13387 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13388 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13389 " which might be stale. Will try to clean up."); 13390 // Clean up the stale container and proceed to recreate. 13391 if (!PackageHelper.destroySdDir(newCacheId)) { 13392 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13393 return false; 13394 } 13395 // Successfully cleaned up stale container. Try to rename again. 13396 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13397 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13398 + " inspite of cleaning it up."); 13399 return false; 13400 } 13401 } 13402 if (!PackageHelper.isContainerMounted(newCacheId)) { 13403 Slog.w(TAG, "Mounting container " + newCacheId); 13404 newMountPath = PackageHelper.mountSdDir(newCacheId, 13405 getEncryptKey(), Process.SYSTEM_UID); 13406 } else { 13407 newMountPath = PackageHelper.getSdDir(newCacheId); 13408 } 13409 if (newMountPath == null) { 13410 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13411 return false; 13412 } 13413 Log.i(TAG, "Succesfully renamed " + cid + 13414 " to " + newCacheId + 13415 " at new path: " + newMountPath); 13416 cid = newCacheId; 13417 13418 final File beforeCodeFile = new File(packagePath); 13419 setMountPath(newMountPath); 13420 final File afterCodeFile = new File(packagePath); 13421 13422 // Reflect the rename in scanned details 13423 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13424 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13425 afterCodeFile, pkg.baseCodePath)); 13426 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13427 afterCodeFile, pkg.splitCodePaths)); 13428 13429 // Reflect the rename in app info 13430 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13431 pkg.setApplicationInfoCodePath(pkg.codePath); 13432 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13433 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13434 pkg.setApplicationInfoResourcePath(pkg.codePath); 13435 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13436 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13437 13438 return true; 13439 } 13440 13441 private void setMountPath(String mountPath) { 13442 final File mountFile = new File(mountPath); 13443 13444 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13445 if (monolithicFile.exists()) { 13446 packagePath = monolithicFile.getAbsolutePath(); 13447 if (isFwdLocked()) { 13448 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13449 } else { 13450 resourcePath = packagePath; 13451 } 13452 } else { 13453 packagePath = mountFile.getAbsolutePath(); 13454 resourcePath = packagePath; 13455 } 13456 } 13457 13458 int doPostInstall(int status, int uid) { 13459 if (status != PackageManager.INSTALL_SUCCEEDED) { 13460 cleanUp(); 13461 } else { 13462 final int groupOwner; 13463 final String protectedFile; 13464 if (isFwdLocked()) { 13465 groupOwner = UserHandle.getSharedAppGid(uid); 13466 protectedFile = RES_FILE_NAME; 13467 } else { 13468 groupOwner = -1; 13469 protectedFile = null; 13470 } 13471 13472 if (uid < Process.FIRST_APPLICATION_UID 13473 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13474 Slog.e(TAG, "Failed to finalize " + cid); 13475 PackageHelper.destroySdDir(cid); 13476 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13477 } 13478 13479 boolean mounted = PackageHelper.isContainerMounted(cid); 13480 if (!mounted) { 13481 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13482 } 13483 } 13484 return status; 13485 } 13486 13487 private void cleanUp() { 13488 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13489 13490 // Destroy secure container 13491 PackageHelper.destroySdDir(cid); 13492 } 13493 13494 private List<String> getAllCodePaths() { 13495 final File codeFile = new File(getCodePath()); 13496 if (codeFile != null && codeFile.exists()) { 13497 try { 13498 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13499 return pkg.getAllCodePaths(); 13500 } catch (PackageParserException e) { 13501 // Ignored; we tried our best 13502 } 13503 } 13504 return Collections.EMPTY_LIST; 13505 } 13506 13507 void cleanUpResourcesLI() { 13508 // Enumerate all code paths before deleting 13509 cleanUpResourcesLI(getAllCodePaths()); 13510 } 13511 13512 private void cleanUpResourcesLI(List<String> allCodePaths) { 13513 cleanUp(); 13514 removeDexFiles(allCodePaths, instructionSets); 13515 } 13516 13517 String getPackageName() { 13518 return getAsecPackageName(cid); 13519 } 13520 13521 boolean doPostDeleteLI(boolean delete) { 13522 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13523 final List<String> allCodePaths = getAllCodePaths(); 13524 boolean mounted = PackageHelper.isContainerMounted(cid); 13525 if (mounted) { 13526 // Unmount first 13527 if (PackageHelper.unMountSdDir(cid)) { 13528 mounted = false; 13529 } 13530 } 13531 if (!mounted && delete) { 13532 cleanUpResourcesLI(allCodePaths); 13533 } 13534 return !mounted; 13535 } 13536 13537 @Override 13538 int doPreCopy() { 13539 if (isFwdLocked()) { 13540 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13541 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13542 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13543 } 13544 } 13545 13546 return PackageManager.INSTALL_SUCCEEDED; 13547 } 13548 13549 @Override 13550 int doPostCopy(int uid) { 13551 if (isFwdLocked()) { 13552 if (uid < Process.FIRST_APPLICATION_UID 13553 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13554 RES_FILE_NAME)) { 13555 Slog.e(TAG, "Failed to finalize " + cid); 13556 PackageHelper.destroySdDir(cid); 13557 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13558 } 13559 } 13560 13561 return PackageManager.INSTALL_SUCCEEDED; 13562 } 13563 } 13564 13565 /** 13566 * Logic to handle movement of existing installed applications. 13567 */ 13568 class MoveInstallArgs extends InstallArgs { 13569 private File codeFile; 13570 private File resourceFile; 13571 13572 /** New install */ 13573 MoveInstallArgs(InstallParams params) { 13574 super(params.origin, params.move, params.observer, params.installFlags, 13575 params.installerPackageName, params.volumeUuid, 13576 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13577 params.grantedRuntimePermissions, 13578 params.traceMethod, params.traceCookie, params.certificates); 13579 } 13580 13581 int copyApk(IMediaContainerService imcs, boolean temp) { 13582 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13583 + move.fromUuid + " to " + move.toUuid); 13584 synchronized (mInstaller) { 13585 try { 13586 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13587 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13588 } catch (InstallerException e) { 13589 Slog.w(TAG, "Failed to move app", e); 13590 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13591 } 13592 } 13593 13594 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13595 resourceFile = codeFile; 13596 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13597 13598 return PackageManager.INSTALL_SUCCEEDED; 13599 } 13600 13601 int doPreInstall(int status) { 13602 if (status != PackageManager.INSTALL_SUCCEEDED) { 13603 cleanUp(move.toUuid); 13604 } 13605 return status; 13606 } 13607 13608 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13609 if (status != PackageManager.INSTALL_SUCCEEDED) { 13610 cleanUp(move.toUuid); 13611 return false; 13612 } 13613 13614 // Reflect the move in app info 13615 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13616 pkg.setApplicationInfoCodePath(pkg.codePath); 13617 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13618 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13619 pkg.setApplicationInfoResourcePath(pkg.codePath); 13620 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13621 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13622 13623 return true; 13624 } 13625 13626 int doPostInstall(int status, int uid) { 13627 if (status == PackageManager.INSTALL_SUCCEEDED) { 13628 cleanUp(move.fromUuid); 13629 } else { 13630 cleanUp(move.toUuid); 13631 } 13632 return status; 13633 } 13634 13635 @Override 13636 String getCodePath() { 13637 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13638 } 13639 13640 @Override 13641 String getResourcePath() { 13642 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13643 } 13644 13645 private boolean cleanUp(String volumeUuid) { 13646 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13647 move.dataAppName); 13648 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13649 final int[] userIds = sUserManager.getUserIds(); 13650 synchronized (mInstallLock) { 13651 // Clean up both app data and code 13652 // All package moves are frozen until finished 13653 for (int userId : userIds) { 13654 try { 13655 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13656 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13657 } catch (InstallerException e) { 13658 Slog.w(TAG, String.valueOf(e)); 13659 } 13660 } 13661 removeCodePathLI(codeFile); 13662 } 13663 return true; 13664 } 13665 13666 void cleanUpResourcesLI() { 13667 throw new UnsupportedOperationException(); 13668 } 13669 13670 boolean doPostDeleteLI(boolean delete) { 13671 throw new UnsupportedOperationException(); 13672 } 13673 } 13674 13675 static String getAsecPackageName(String packageCid) { 13676 int idx = packageCid.lastIndexOf("-"); 13677 if (idx == -1) { 13678 return packageCid; 13679 } 13680 return packageCid.substring(0, idx); 13681 } 13682 13683 // Utility method used to create code paths based on package name and available index. 13684 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13685 String idxStr = ""; 13686 int idx = 1; 13687 // Fall back to default value of idx=1 if prefix is not 13688 // part of oldCodePath 13689 if (oldCodePath != null) { 13690 String subStr = oldCodePath; 13691 // Drop the suffix right away 13692 if (suffix != null && subStr.endsWith(suffix)) { 13693 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13694 } 13695 // If oldCodePath already contains prefix find out the 13696 // ending index to either increment or decrement. 13697 int sidx = subStr.lastIndexOf(prefix); 13698 if (sidx != -1) { 13699 subStr = subStr.substring(sidx + prefix.length()); 13700 if (subStr != null) { 13701 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13702 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13703 } 13704 try { 13705 idx = Integer.parseInt(subStr); 13706 if (idx <= 1) { 13707 idx++; 13708 } else { 13709 idx--; 13710 } 13711 } catch(NumberFormatException e) { 13712 } 13713 } 13714 } 13715 } 13716 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13717 return prefix + idxStr; 13718 } 13719 13720 private File getNextCodePath(File targetDir, String packageName) { 13721 int suffix = 1; 13722 File result; 13723 do { 13724 result = new File(targetDir, packageName + "-" + suffix); 13725 suffix++; 13726 } while (result.exists()); 13727 return result; 13728 } 13729 13730 // Utility method that returns the relative package path with respect 13731 // to the installation directory. Like say for /data/data/com.test-1.apk 13732 // string com.test-1 is returned. 13733 static String deriveCodePathName(String codePath) { 13734 if (codePath == null) { 13735 return null; 13736 } 13737 final File codeFile = new File(codePath); 13738 final String name = codeFile.getName(); 13739 if (codeFile.isDirectory()) { 13740 return name; 13741 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13742 final int lastDot = name.lastIndexOf('.'); 13743 return name.substring(0, lastDot); 13744 } else { 13745 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13746 return null; 13747 } 13748 } 13749 13750 static class PackageInstalledInfo { 13751 String name; 13752 int uid; 13753 // The set of users that originally had this package installed. 13754 int[] origUsers; 13755 // The set of users that now have this package installed. 13756 int[] newUsers; 13757 PackageParser.Package pkg; 13758 int returnCode; 13759 String returnMsg; 13760 PackageRemovedInfo removedInfo; 13761 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13762 13763 public void setError(int code, String msg) { 13764 setReturnCode(code); 13765 setReturnMessage(msg); 13766 Slog.w(TAG, msg); 13767 } 13768 13769 public void setError(String msg, PackageParserException e) { 13770 setReturnCode(e.error); 13771 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13772 Slog.w(TAG, msg, e); 13773 } 13774 13775 public void setError(String msg, PackageManagerException e) { 13776 returnCode = e.error; 13777 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13778 Slog.w(TAG, msg, e); 13779 } 13780 13781 public void setReturnCode(int returnCode) { 13782 this.returnCode = returnCode; 13783 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13784 for (int i = 0; i < childCount; i++) { 13785 addedChildPackages.valueAt(i).returnCode = returnCode; 13786 } 13787 } 13788 13789 private void setReturnMessage(String returnMsg) { 13790 this.returnMsg = returnMsg; 13791 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13792 for (int i = 0; i < childCount; i++) { 13793 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13794 } 13795 } 13796 13797 // In some error cases we want to convey more info back to the observer 13798 String origPackage; 13799 String origPermission; 13800 } 13801 13802 /* 13803 * Install a non-existing package. 13804 */ 13805 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13806 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13807 PackageInstalledInfo res) { 13808 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13809 13810 // Remember this for later, in case we need to rollback this install 13811 String pkgName = pkg.packageName; 13812 13813 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13814 13815 synchronized(mPackages) { 13816 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13817 // A package with the same name is already installed, though 13818 // it has been renamed to an older name. The package we 13819 // are trying to install should be installed as an update to 13820 // the existing one, but that has not been requested, so bail. 13821 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13822 + " without first uninstalling package running as " 13823 + mSettings.mRenamedPackages.get(pkgName)); 13824 return; 13825 } 13826 if (mPackages.containsKey(pkgName)) { 13827 // Don't allow installation over an existing package with the same name. 13828 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13829 + " without first uninstalling."); 13830 return; 13831 } 13832 } 13833 13834 try { 13835 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13836 System.currentTimeMillis(), user); 13837 13838 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13839 13840 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13841 prepareAppDataAfterInstallLIF(newPackage); 13842 13843 } else { 13844 // Remove package from internal structures, but keep around any 13845 // data that might have already existed 13846 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13847 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13848 } 13849 } catch (PackageManagerException e) { 13850 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13851 } 13852 13853 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13854 } 13855 13856 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13857 // Can't rotate keys during boot or if sharedUser. 13858 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13859 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13860 return false; 13861 } 13862 // app is using upgradeKeySets; make sure all are valid 13863 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13864 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13865 for (int i = 0; i < upgradeKeySets.length; i++) { 13866 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13867 Slog.wtf(TAG, "Package " 13868 + (oldPs.name != null ? oldPs.name : "<null>") 13869 + " contains upgrade-key-set reference to unknown key-set: " 13870 + upgradeKeySets[i] 13871 + " reverting to signatures check."); 13872 return false; 13873 } 13874 } 13875 return true; 13876 } 13877 13878 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13879 // Upgrade keysets are being used. Determine if new package has a superset of the 13880 // required keys. 13881 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13882 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13883 for (int i = 0; i < upgradeKeySets.length; i++) { 13884 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13885 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13886 return true; 13887 } 13888 } 13889 return false; 13890 } 13891 13892 private static void updateDigest(MessageDigest digest, File file) throws IOException { 13893 try (DigestInputStream digestStream = 13894 new DigestInputStream(new FileInputStream(file), digest)) { 13895 while (digestStream.read() != -1) {} // nothing to do; just plow through the file 13896 } 13897 } 13898 13899 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13900 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13901 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13902 13903 final PackageParser.Package oldPackage; 13904 final String pkgName = pkg.packageName; 13905 final int[] allUsers; 13906 final int[] installedUsers; 13907 13908 synchronized(mPackages) { 13909 oldPackage = mPackages.get(pkgName); 13910 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13911 13912 // don't allow upgrade to target a release SDK from a pre-release SDK 13913 final boolean oldTargetsPreRelease = oldPackage.applicationInfo.targetSdkVersion 13914 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13915 final boolean newTargetsPreRelease = pkg.applicationInfo.targetSdkVersion 13916 == android.os.Build.VERSION_CODES.CUR_DEVELOPMENT; 13917 if (oldTargetsPreRelease 13918 && !newTargetsPreRelease 13919 && ((policyFlags & PackageParser.PARSE_FORCE_SDK) == 0)) { 13920 Slog.w(TAG, "Can't install package targeting released sdk"); 13921 res.setReturnCode(PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE); 13922 return; 13923 } 13924 13925 // don't allow an upgrade from full to ephemeral 13926 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13927 if (isEphemeral && !oldIsEphemeral) { 13928 // can't downgrade from full to ephemeral 13929 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13930 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13931 return; 13932 } 13933 13934 // verify signatures are valid 13935 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13936 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13937 if (!checkUpgradeKeySetLP(ps, pkg)) { 13938 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13939 "New package not signed by keys specified by upgrade-keysets: " 13940 + pkgName); 13941 return; 13942 } 13943 } else { 13944 // default to original signature matching 13945 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13946 != PackageManager.SIGNATURE_MATCH) { 13947 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13948 "New package has a different signature: " + pkgName); 13949 return; 13950 } 13951 } 13952 13953 // don't allow a system upgrade unless the upgrade hash matches 13954 if (oldPackage.restrictUpdateHash != null && oldPackage.isSystemApp()) { 13955 byte[] digestBytes = null; 13956 try { 13957 final MessageDigest digest = MessageDigest.getInstance("SHA-512"); 13958 updateDigest(digest, new File(pkg.baseCodePath)); 13959 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 13960 for (String path : pkg.splitCodePaths) { 13961 updateDigest(digest, new File(path)); 13962 } 13963 } 13964 digestBytes = digest.digest(); 13965 } catch (NoSuchAlgorithmException | IOException e) { 13966 res.setError(INSTALL_FAILED_INVALID_APK, 13967 "Could not compute hash: " + pkgName); 13968 return; 13969 } 13970 if (!Arrays.equals(oldPackage.restrictUpdateHash, digestBytes)) { 13971 res.setError(INSTALL_FAILED_INVALID_APK, 13972 "New package fails restrict-update check: " + pkgName); 13973 return; 13974 } 13975 // retain upgrade restriction 13976 pkg.restrictUpdateHash = oldPackage.restrictUpdateHash; 13977 } 13978 13979 // Check for shared user id changes 13980 String invalidPackageName = 13981 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13982 if (invalidPackageName != null) { 13983 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13984 "Package " + invalidPackageName + " tried to change user " 13985 + oldPackage.mSharedUserId); 13986 return; 13987 } 13988 13989 // In case of rollback, remember per-user/profile install state 13990 allUsers = sUserManager.getUserIds(); 13991 installedUsers = ps.queryInstalledUsers(allUsers, true); 13992 } 13993 13994 // Update what is removed 13995 res.removedInfo = new PackageRemovedInfo(); 13996 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13997 res.removedInfo.removedPackage = oldPackage.packageName; 13998 res.removedInfo.isUpdate = true; 13999 res.removedInfo.origUsers = installedUsers; 14000 final int childCount = (oldPackage.childPackages != null) 14001 ? oldPackage.childPackages.size() : 0; 14002 for (int i = 0; i < childCount; i++) { 14003 boolean childPackageUpdated = false; 14004 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 14005 if (res.addedChildPackages != null) { 14006 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14007 if (childRes != null) { 14008 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 14009 childRes.removedInfo.removedPackage = childPkg.packageName; 14010 childRes.removedInfo.isUpdate = true; 14011 childPackageUpdated = true; 14012 } 14013 } 14014 if (!childPackageUpdated) { 14015 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 14016 childRemovedRes.removedPackage = childPkg.packageName; 14017 childRemovedRes.isUpdate = false; 14018 childRemovedRes.dataRemoved = true; 14019 synchronized (mPackages) { 14020 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14021 if (childPs != null) { 14022 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 14023 } 14024 } 14025 if (res.removedInfo.removedChildPackages == null) { 14026 res.removedInfo.removedChildPackages = new ArrayMap<>(); 14027 } 14028 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 14029 } 14030 } 14031 14032 boolean sysPkg = (isSystemApp(oldPackage)); 14033 if (sysPkg) { 14034 // Set the system/privileged flags as needed 14035 final boolean privileged = 14036 (oldPackage.applicationInfo.privateFlags 14037 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14038 final int systemPolicyFlags = policyFlags 14039 | PackageParser.PARSE_IS_SYSTEM 14040 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 14041 14042 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 14043 user, allUsers, installerPackageName, res); 14044 } else { 14045 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 14046 user, allUsers, installerPackageName, res); 14047 } 14048 } 14049 14050 public List<String> getPreviousCodePaths(String packageName) { 14051 final PackageSetting ps = mSettings.mPackages.get(packageName); 14052 final List<String> result = new ArrayList<String>(); 14053 if (ps != null && ps.oldCodePaths != null) { 14054 result.addAll(ps.oldCodePaths); 14055 } 14056 return result; 14057 } 14058 14059 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 14060 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14061 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14062 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 14063 + deletedPackage); 14064 14065 String pkgName = deletedPackage.packageName; 14066 boolean deletedPkg = true; 14067 boolean addedPkg = false; 14068 boolean updatedSettings = false; 14069 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 14070 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 14071 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 14072 14073 final long origUpdateTime = (pkg.mExtras != null) 14074 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 14075 14076 // First delete the existing package while retaining the data directory 14077 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14078 res.removedInfo, true, pkg)) { 14079 // If the existing package wasn't successfully deleted 14080 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 14081 deletedPkg = false; 14082 } else { 14083 // Successfully deleted the old package; proceed with replace. 14084 14085 // If deleted package lived in a container, give users a chance to 14086 // relinquish resources before killing. 14087 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 14088 if (DEBUG_INSTALL) { 14089 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 14090 } 14091 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 14092 final ArrayList<String> pkgList = new ArrayList<String>(1); 14093 pkgList.add(deletedPackage.applicationInfo.packageName); 14094 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 14095 } 14096 14097 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14098 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14099 clearAppProfilesLIF(pkg); 14100 14101 try { 14102 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 14103 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 14104 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14105 14106 // Update the in-memory copy of the previous code paths. 14107 PackageSetting ps = mSettings.mPackages.get(pkgName); 14108 if (!killApp) { 14109 if (ps.oldCodePaths == null) { 14110 ps.oldCodePaths = new ArraySet<>(); 14111 } 14112 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 14113 if (deletedPackage.splitCodePaths != null) { 14114 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 14115 } 14116 } else { 14117 ps.oldCodePaths = null; 14118 } 14119 if (ps.childPackageNames != null) { 14120 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 14121 final String childPkgName = ps.childPackageNames.get(i); 14122 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 14123 childPs.oldCodePaths = ps.oldCodePaths; 14124 } 14125 } 14126 prepareAppDataAfterInstallLIF(newPackage); 14127 addedPkg = true; 14128 } catch (PackageManagerException e) { 14129 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14130 } 14131 } 14132 14133 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14134 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 14135 14136 // Revert all internal state mutations and added folders for the failed install 14137 if (addedPkg) { 14138 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 14139 res.removedInfo, true, null); 14140 } 14141 14142 // Restore the old package 14143 if (deletedPkg) { 14144 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 14145 File restoreFile = new File(deletedPackage.codePath); 14146 // Parse old package 14147 boolean oldExternal = isExternal(deletedPackage); 14148 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 14149 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 14150 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 14151 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 14152 try { 14153 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14154 null); 14155 } catch (PackageManagerException e) { 14156 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14157 + e.getMessage()); 14158 return; 14159 } 14160 14161 synchronized (mPackages) { 14162 // Ensure the installer package name up to date 14163 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14164 14165 // Update permissions for restored package 14166 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14167 14168 mSettings.writeLPr(); 14169 } 14170 14171 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14172 } 14173 } else { 14174 synchronized (mPackages) { 14175 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14176 if (ps != null) { 14177 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14178 if (res.removedInfo.removedChildPackages != null) { 14179 final int childCount = res.removedInfo.removedChildPackages.size(); 14180 // Iterate in reverse as we may modify the collection 14181 for (int i = childCount - 1; i >= 0; i--) { 14182 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14183 if (res.addedChildPackages.containsKey(childPackageName)) { 14184 res.removedInfo.removedChildPackages.removeAt(i); 14185 } else { 14186 PackageRemovedInfo childInfo = res.removedInfo 14187 .removedChildPackages.valueAt(i); 14188 childInfo.removedForAllUsers = mPackages.get( 14189 childInfo.removedPackage) == null; 14190 } 14191 } 14192 } 14193 } 14194 } 14195 } 14196 } 14197 14198 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14199 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14200 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14201 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14202 + ", old=" + deletedPackage); 14203 14204 final boolean disabledSystem; 14205 14206 // Remove existing system package 14207 removePackageLI(deletedPackage, true); 14208 14209 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14210 if (!disabledSystem) { 14211 // We didn't need to disable the .apk as a current system package, 14212 // which means we are replacing another update that is already 14213 // installed. We need to make sure to delete the older one's .apk. 14214 res.removedInfo.args = createInstallArgsForExisting(0, 14215 deletedPackage.applicationInfo.getCodePath(), 14216 deletedPackage.applicationInfo.getResourcePath(), 14217 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14218 } else { 14219 res.removedInfo.args = null; 14220 } 14221 14222 // Successfully disabled the old package. Now proceed with re-installation 14223 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14224 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14225 clearAppProfilesLIF(pkg); 14226 14227 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14228 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14229 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14230 14231 PackageParser.Package newPackage = null; 14232 try { 14233 // Add the package to the internal data structures 14234 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14235 14236 // Set the update and install times 14237 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14238 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14239 System.currentTimeMillis()); 14240 14241 // Update the package dynamic state if succeeded 14242 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14243 // Now that the install succeeded make sure we remove data 14244 // directories for any child package the update removed. 14245 final int deletedChildCount = (deletedPackage.childPackages != null) 14246 ? deletedPackage.childPackages.size() : 0; 14247 final int newChildCount = (newPackage.childPackages != null) 14248 ? newPackage.childPackages.size() : 0; 14249 for (int i = 0; i < deletedChildCount; i++) { 14250 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14251 boolean childPackageDeleted = true; 14252 for (int j = 0; j < newChildCount; j++) { 14253 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14254 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14255 childPackageDeleted = false; 14256 break; 14257 } 14258 } 14259 if (childPackageDeleted) { 14260 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14261 deletedChildPkg.packageName); 14262 if (ps != null && res.removedInfo.removedChildPackages != null) { 14263 PackageRemovedInfo removedChildRes = res.removedInfo 14264 .removedChildPackages.get(deletedChildPkg.packageName); 14265 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14266 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14267 } 14268 } 14269 } 14270 14271 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14272 prepareAppDataAfterInstallLIF(newPackage); 14273 } 14274 } catch (PackageManagerException e) { 14275 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14276 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14277 } 14278 14279 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14280 // Re installation failed. Restore old information 14281 // Remove new pkg information 14282 if (newPackage != null) { 14283 removeInstalledPackageLI(newPackage, true); 14284 } 14285 // Add back the old system package 14286 try { 14287 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14288 } catch (PackageManagerException e) { 14289 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14290 } 14291 14292 synchronized (mPackages) { 14293 if (disabledSystem) { 14294 enableSystemPackageLPw(deletedPackage); 14295 } 14296 14297 // Ensure the installer package name up to date 14298 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14299 14300 // Update permissions for restored package 14301 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14302 14303 mSettings.writeLPr(); 14304 } 14305 14306 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14307 + " after failed upgrade"); 14308 } 14309 } 14310 14311 /** 14312 * Checks whether the parent or any of the child packages have a change shared 14313 * user. For a package to be a valid update the shred users of the parent and 14314 * the children should match. We may later support changing child shared users. 14315 * @param oldPkg The updated package. 14316 * @param newPkg The update package. 14317 * @return The shared user that change between the versions. 14318 */ 14319 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14320 PackageParser.Package newPkg) { 14321 // Check parent shared user 14322 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14323 return newPkg.packageName; 14324 } 14325 // Check child shared users 14326 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14327 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14328 for (int i = 0; i < newChildCount; i++) { 14329 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14330 // If this child was present, did it have the same shared user? 14331 for (int j = 0; j < oldChildCount; j++) { 14332 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14333 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14334 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14335 return newChildPkg.packageName; 14336 } 14337 } 14338 } 14339 return null; 14340 } 14341 14342 private void removeNativeBinariesLI(PackageSetting ps) { 14343 // Remove the lib path for the parent package 14344 if (ps != null) { 14345 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14346 // Remove the lib path for the child packages 14347 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14348 for (int i = 0; i < childCount; i++) { 14349 PackageSetting childPs = null; 14350 synchronized (mPackages) { 14351 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14352 } 14353 if (childPs != null) { 14354 NativeLibraryHelper.removeNativeBinariesLI(childPs 14355 .legacyNativeLibraryPathString); 14356 } 14357 } 14358 } 14359 } 14360 14361 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14362 // Enable the parent package 14363 mSettings.enableSystemPackageLPw(pkg.packageName); 14364 // Enable the child packages 14365 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14366 for (int i = 0; i < childCount; i++) { 14367 PackageParser.Package childPkg = pkg.childPackages.get(i); 14368 mSettings.enableSystemPackageLPw(childPkg.packageName); 14369 } 14370 } 14371 14372 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14373 PackageParser.Package newPkg) { 14374 // Disable the parent package (parent always replaced) 14375 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14376 // Disable the child packages 14377 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14378 for (int i = 0; i < childCount; i++) { 14379 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14380 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14381 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14382 } 14383 return disabled; 14384 } 14385 14386 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14387 String installerPackageName) { 14388 // Enable the parent package 14389 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14390 // Enable the child packages 14391 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14392 for (int i = 0; i < childCount; i++) { 14393 PackageParser.Package childPkg = pkg.childPackages.get(i); 14394 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14395 } 14396 } 14397 14398 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14399 // Collect all used permissions in the UID 14400 ArraySet<String> usedPermissions = new ArraySet<>(); 14401 final int packageCount = su.packages.size(); 14402 for (int i = 0; i < packageCount; i++) { 14403 PackageSetting ps = su.packages.valueAt(i); 14404 if (ps.pkg == null) { 14405 continue; 14406 } 14407 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14408 for (int j = 0; j < requestedPermCount; j++) { 14409 String permission = ps.pkg.requestedPermissions.get(j); 14410 BasePermission bp = mSettings.mPermissions.get(permission); 14411 if (bp != null) { 14412 usedPermissions.add(permission); 14413 } 14414 } 14415 } 14416 14417 PermissionsState permissionsState = su.getPermissionsState(); 14418 // Prune install permissions 14419 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14420 final int installPermCount = installPermStates.size(); 14421 for (int i = installPermCount - 1; i >= 0; i--) { 14422 PermissionState permissionState = installPermStates.get(i); 14423 if (!usedPermissions.contains(permissionState.getName())) { 14424 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14425 if (bp != null) { 14426 permissionsState.revokeInstallPermission(bp); 14427 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14428 PackageManager.MASK_PERMISSION_FLAGS, 0); 14429 } 14430 } 14431 } 14432 14433 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14434 14435 // Prune runtime permissions 14436 for (int userId : allUserIds) { 14437 List<PermissionState> runtimePermStates = permissionsState 14438 .getRuntimePermissionStates(userId); 14439 final int runtimePermCount = runtimePermStates.size(); 14440 for (int i = runtimePermCount - 1; i >= 0; i--) { 14441 PermissionState permissionState = runtimePermStates.get(i); 14442 if (!usedPermissions.contains(permissionState.getName())) { 14443 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14444 if (bp != null) { 14445 permissionsState.revokeRuntimePermission(bp, userId); 14446 permissionsState.updatePermissionFlags(bp, userId, 14447 PackageManager.MASK_PERMISSION_FLAGS, 0); 14448 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14449 runtimePermissionChangedUserIds, userId); 14450 } 14451 } 14452 } 14453 } 14454 14455 return runtimePermissionChangedUserIds; 14456 } 14457 14458 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14459 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14460 // Update the parent package setting 14461 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14462 res, user); 14463 // Update the child packages setting 14464 final int childCount = (newPackage.childPackages != null) 14465 ? newPackage.childPackages.size() : 0; 14466 for (int i = 0; i < childCount; i++) { 14467 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14468 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14469 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14470 childRes.origUsers, childRes, user); 14471 } 14472 } 14473 14474 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14475 String installerPackageName, int[] allUsers, int[] installedForUsers, 14476 PackageInstalledInfo res, UserHandle user) { 14477 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14478 14479 String pkgName = newPackage.packageName; 14480 synchronized (mPackages) { 14481 //write settings. the installStatus will be incomplete at this stage. 14482 //note that the new package setting would have already been 14483 //added to mPackages. It hasn't been persisted yet. 14484 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14485 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14486 mSettings.writeLPr(); 14487 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14488 } 14489 14490 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14491 synchronized (mPackages) { 14492 updatePermissionsLPw(newPackage.packageName, newPackage, 14493 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14494 ? UPDATE_PERMISSIONS_ALL : 0)); 14495 // For system-bundled packages, we assume that installing an upgraded version 14496 // of the package implies that the user actually wants to run that new code, 14497 // so we enable the package. 14498 PackageSetting ps = mSettings.mPackages.get(pkgName); 14499 final int userId = user.getIdentifier(); 14500 if (ps != null) { 14501 if (isSystemApp(newPackage)) { 14502 if (DEBUG_INSTALL) { 14503 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14504 } 14505 // Enable system package for requested users 14506 if (res.origUsers != null) { 14507 for (int origUserId : res.origUsers) { 14508 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14509 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14510 origUserId, installerPackageName); 14511 } 14512 } 14513 } 14514 // Also convey the prior install/uninstall state 14515 if (allUsers != null && installedForUsers != null) { 14516 for (int currentUserId : allUsers) { 14517 final boolean installed = ArrayUtils.contains( 14518 installedForUsers, currentUserId); 14519 if (DEBUG_INSTALL) { 14520 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14521 } 14522 ps.setInstalled(installed, currentUserId); 14523 } 14524 // these install state changes will be persisted in the 14525 // upcoming call to mSettings.writeLPr(). 14526 } 14527 } 14528 // It's implied that when a user requests installation, they want the app to be 14529 // installed and enabled. 14530 if (userId != UserHandle.USER_ALL) { 14531 ps.setInstalled(true, userId); 14532 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14533 } 14534 } 14535 res.name = pkgName; 14536 res.uid = newPackage.applicationInfo.uid; 14537 res.pkg = newPackage; 14538 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14539 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14540 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14541 //to update install status 14542 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14543 mSettings.writeLPr(); 14544 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14545 } 14546 14547 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14548 } 14549 14550 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14551 try { 14552 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14553 installPackageLI(args, res); 14554 } finally { 14555 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14556 } 14557 } 14558 14559 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14560 final int installFlags = args.installFlags; 14561 final String installerPackageName = args.installerPackageName; 14562 final String volumeUuid = args.volumeUuid; 14563 final File tmpPackageFile = new File(args.getCodePath()); 14564 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14565 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14566 || (args.volumeUuid != null)); 14567 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14568 final boolean forceSdk = ((installFlags & PackageManager.INSTALL_FORCE_SDK) != 0); 14569 boolean replace = false; 14570 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14571 if (args.move != null) { 14572 // moving a complete application; perform an initial scan on the new install location 14573 scanFlags |= SCAN_INITIAL; 14574 } 14575 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14576 scanFlags |= SCAN_DONT_KILL_APP; 14577 } 14578 14579 // Result object to be returned 14580 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14581 14582 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14583 14584 // Sanity check 14585 if (ephemeral && (forwardLocked || onExternal)) { 14586 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14587 + " external=" + onExternal); 14588 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14589 return; 14590 } 14591 14592 // Retrieve PackageSettings and parse package 14593 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14594 | PackageParser.PARSE_ENFORCE_CODE 14595 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14596 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14597 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0) 14598 | (forceSdk ? PackageParser.PARSE_FORCE_SDK : 0); 14599 PackageParser pp = new PackageParser(); 14600 pp.setSeparateProcesses(mSeparateProcesses); 14601 pp.setDisplayMetrics(mMetrics); 14602 14603 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14604 final PackageParser.Package pkg; 14605 try { 14606 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14607 } catch (PackageParserException e) { 14608 res.setError("Failed parse during installPackageLI", e); 14609 return; 14610 } finally { 14611 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14612 } 14613 14614 // If we are installing a clustered package add results for the children 14615 if (pkg.childPackages != null) { 14616 synchronized (mPackages) { 14617 final int childCount = pkg.childPackages.size(); 14618 for (int i = 0; i < childCount; i++) { 14619 PackageParser.Package childPkg = pkg.childPackages.get(i); 14620 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14621 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14622 childRes.pkg = childPkg; 14623 childRes.name = childPkg.packageName; 14624 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14625 if (childPs != null) { 14626 childRes.origUsers = childPs.queryInstalledUsers( 14627 sUserManager.getUserIds(), true); 14628 } 14629 if ((mPackages.containsKey(childPkg.packageName))) { 14630 childRes.removedInfo = new PackageRemovedInfo(); 14631 childRes.removedInfo.removedPackage = childPkg.packageName; 14632 } 14633 if (res.addedChildPackages == null) { 14634 res.addedChildPackages = new ArrayMap<>(); 14635 } 14636 res.addedChildPackages.put(childPkg.packageName, childRes); 14637 } 14638 } 14639 } 14640 14641 // If package doesn't declare API override, mark that we have an install 14642 // time CPU ABI override. 14643 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14644 pkg.cpuAbiOverride = args.abiOverride; 14645 } 14646 14647 String pkgName = res.name = pkg.packageName; 14648 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14649 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14650 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14651 return; 14652 } 14653 } 14654 14655 try { 14656 // either use what we've been given or parse directly from the APK 14657 if (args.certificates != null) { 14658 try { 14659 PackageParser.populateCertificates(pkg, args.certificates); 14660 } catch (PackageParserException e) { 14661 // there was something wrong with the certificates we were given; 14662 // try to pull them from the APK 14663 PackageParser.collectCertificates(pkg, parseFlags); 14664 } 14665 } else { 14666 PackageParser.collectCertificates(pkg, parseFlags); 14667 } 14668 } catch (PackageParserException e) { 14669 res.setError("Failed collect during installPackageLI", e); 14670 return; 14671 } 14672 14673 // Get rid of all references to package scan path via parser. 14674 pp = null; 14675 String oldCodePath = null; 14676 boolean systemApp = false; 14677 synchronized (mPackages) { 14678 // Check if installing already existing package 14679 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14680 String oldName = mSettings.mRenamedPackages.get(pkgName); 14681 if (pkg.mOriginalPackages != null 14682 && pkg.mOriginalPackages.contains(oldName) 14683 && mPackages.containsKey(oldName)) { 14684 // This package is derived from an original package, 14685 // and this device has been updating from that original 14686 // name. We must continue using the original name, so 14687 // rename the new package here. 14688 pkg.setPackageName(oldName); 14689 pkgName = pkg.packageName; 14690 replace = true; 14691 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14692 + oldName + " pkgName=" + pkgName); 14693 } else if (mPackages.containsKey(pkgName)) { 14694 // This package, under its official name, already exists 14695 // on the device; we should replace it. 14696 replace = true; 14697 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14698 } 14699 14700 // Child packages are installed through the parent package 14701 if (pkg.parentPackage != null) { 14702 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14703 "Package " + pkg.packageName + " is child of package " 14704 + pkg.parentPackage.parentPackage + ". Child packages " 14705 + "can be updated only through the parent package."); 14706 return; 14707 } 14708 14709 if (replace) { 14710 // Prevent apps opting out from runtime permissions 14711 PackageParser.Package oldPackage = mPackages.get(pkgName); 14712 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14713 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14714 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14715 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14716 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14717 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14718 + " doesn't support runtime permissions but the old" 14719 + " target SDK " + oldTargetSdk + " does."); 14720 return; 14721 } 14722 14723 // Prevent installing of child packages 14724 if (oldPackage.parentPackage != null) { 14725 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14726 "Package " + pkg.packageName + " is child of package " 14727 + oldPackage.parentPackage + ". Child packages " 14728 + "can be updated only through the parent package."); 14729 return; 14730 } 14731 } 14732 } 14733 14734 PackageSetting ps = mSettings.mPackages.get(pkgName); 14735 if (ps != null) { 14736 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14737 14738 // Quick sanity check that we're signed correctly if updating; 14739 // we'll check this again later when scanning, but we want to 14740 // bail early here before tripping over redefined permissions. 14741 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14742 if (!checkUpgradeKeySetLP(ps, pkg)) { 14743 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14744 + pkg.packageName + " upgrade keys do not match the " 14745 + "previously installed version"); 14746 return; 14747 } 14748 } else { 14749 try { 14750 verifySignaturesLP(ps, pkg); 14751 } catch (PackageManagerException e) { 14752 res.setError(e.error, e.getMessage()); 14753 return; 14754 } 14755 } 14756 14757 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14758 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14759 systemApp = (ps.pkg.applicationInfo.flags & 14760 ApplicationInfo.FLAG_SYSTEM) != 0; 14761 } 14762 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14763 } 14764 14765 // Check whether the newly-scanned package wants to define an already-defined perm 14766 int N = pkg.permissions.size(); 14767 for (int i = N-1; i >= 0; i--) { 14768 PackageParser.Permission perm = pkg.permissions.get(i); 14769 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14770 if (bp != null) { 14771 // If the defining package is signed with our cert, it's okay. This 14772 // also includes the "updating the same package" case, of course. 14773 // "updating same package" could also involve key-rotation. 14774 final boolean sigsOk; 14775 if (bp.sourcePackage.equals(pkg.packageName) 14776 && (bp.packageSetting instanceof PackageSetting) 14777 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14778 scanFlags))) { 14779 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14780 } else { 14781 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14782 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14783 } 14784 if (!sigsOk) { 14785 // If the owning package is the system itself, we log but allow 14786 // install to proceed; we fail the install on all other permission 14787 // redefinitions. 14788 if (!bp.sourcePackage.equals("android")) { 14789 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14790 + pkg.packageName + " attempting to redeclare permission " 14791 + perm.info.name + " already owned by " + bp.sourcePackage); 14792 res.origPermission = perm.info.name; 14793 res.origPackage = bp.sourcePackage; 14794 return; 14795 } else { 14796 Slog.w(TAG, "Package " + pkg.packageName 14797 + " attempting to redeclare system permission " 14798 + perm.info.name + "; ignoring new declaration"); 14799 pkg.permissions.remove(i); 14800 } 14801 } 14802 } 14803 } 14804 } 14805 14806 if (systemApp) { 14807 if (onExternal) { 14808 // Abort update; system app can't be replaced with app on sdcard 14809 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14810 "Cannot install updates to system apps on sdcard"); 14811 return; 14812 } else if (ephemeral) { 14813 // Abort update; system app can't be replaced with an ephemeral app 14814 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14815 "Cannot update a system app with an ephemeral app"); 14816 return; 14817 } 14818 } 14819 14820 if (args.move != null) { 14821 // We did an in-place move, so dex is ready to roll 14822 scanFlags |= SCAN_NO_DEX; 14823 scanFlags |= SCAN_MOVE; 14824 14825 synchronized (mPackages) { 14826 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14827 if (ps == null) { 14828 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14829 "Missing settings for moved package " + pkgName); 14830 } 14831 14832 // We moved the entire application as-is, so bring over the 14833 // previously derived ABI information. 14834 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14835 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14836 } 14837 14838 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14839 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14840 scanFlags |= SCAN_NO_DEX; 14841 14842 try { 14843 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14844 args.abiOverride : pkg.cpuAbiOverride); 14845 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14846 true /* extract libs */); 14847 } catch (PackageManagerException pme) { 14848 Slog.e(TAG, "Error deriving application ABI", pme); 14849 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14850 return; 14851 } 14852 14853 // Shared libraries for the package need to be updated. 14854 synchronized (mPackages) { 14855 try { 14856 updateSharedLibrariesLPw(pkg, null); 14857 } catch (PackageManagerException e) { 14858 Slog.e(TAG, "updateSharedLibrariesLPw failed: " + e.getMessage()); 14859 } 14860 } 14861 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14862 // Do not run PackageDexOptimizer through the local performDexOpt 14863 // method because `pkg` is not in `mPackages` yet. 14864 int result = mPackageDexOptimizer.performDexOpt(pkg, pkg.usesLibraryFiles, 14865 null /* instructionSets */, false /* checkProfiles */, 14866 getCompilerFilterForReason(REASON_INSTALL)); 14867 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14868 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14869 String msg = "Extracting package failed for " + pkgName; 14870 res.setError(INSTALL_FAILED_DEXOPT, msg); 14871 return; 14872 } 14873 14874 // Notify BackgroundDexOptService that the package has been changed. 14875 // If this is an update of a package which used to fail to compile, 14876 // BDOS will remove it from its blacklist. 14877 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14878 } 14879 14880 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14881 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14882 return; 14883 } 14884 14885 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14886 14887 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14888 "installPackageLI")) { 14889 if (replace) { 14890 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14891 installerPackageName, res); 14892 } else { 14893 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14894 args.user, installerPackageName, volumeUuid, res); 14895 } 14896 } 14897 synchronized (mPackages) { 14898 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14899 if (ps != null) { 14900 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14901 } 14902 14903 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14904 for (int i = 0; i < childCount; i++) { 14905 PackageParser.Package childPkg = pkg.childPackages.get(i); 14906 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14907 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14908 if (childPs != null) { 14909 childRes.newUsers = childPs.queryInstalledUsers( 14910 sUserManager.getUserIds(), true); 14911 } 14912 } 14913 } 14914 } 14915 14916 private void startIntentFilterVerifications(int userId, boolean replacing, 14917 PackageParser.Package pkg) { 14918 if (mIntentFilterVerifierComponent == null) { 14919 Slog.w(TAG, "No IntentFilter verification will not be done as " 14920 + "there is no IntentFilterVerifier available!"); 14921 return; 14922 } 14923 14924 final int verifierUid = getPackageUid( 14925 mIntentFilterVerifierComponent.getPackageName(), 14926 MATCH_DEBUG_TRIAGED_MISSING, 14927 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14928 14929 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14930 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14931 mHandler.sendMessage(msg); 14932 14933 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14934 for (int i = 0; i < childCount; i++) { 14935 PackageParser.Package childPkg = pkg.childPackages.get(i); 14936 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14937 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14938 mHandler.sendMessage(msg); 14939 } 14940 } 14941 14942 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14943 PackageParser.Package pkg) { 14944 int size = pkg.activities.size(); 14945 if (size == 0) { 14946 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14947 "No activity, so no need to verify any IntentFilter!"); 14948 return; 14949 } 14950 14951 final boolean hasDomainURLs = hasDomainURLs(pkg); 14952 if (!hasDomainURLs) { 14953 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14954 "No domain URLs, so no need to verify any IntentFilter!"); 14955 return; 14956 } 14957 14958 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14959 + " if any IntentFilter from the " + size 14960 + " Activities needs verification ..."); 14961 14962 int count = 0; 14963 final String packageName = pkg.packageName; 14964 14965 synchronized (mPackages) { 14966 // If this is a new install and we see that we've already run verification for this 14967 // package, we have nothing to do: it means the state was restored from backup. 14968 if (!replacing) { 14969 IntentFilterVerificationInfo ivi = 14970 mSettings.getIntentFilterVerificationLPr(packageName); 14971 if (ivi != null) { 14972 if (DEBUG_DOMAIN_VERIFICATION) { 14973 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14974 + ivi.getStatusString()); 14975 } 14976 return; 14977 } 14978 } 14979 14980 // If any filters need to be verified, then all need to be. 14981 boolean needToVerify = false; 14982 for (PackageParser.Activity a : pkg.activities) { 14983 for (ActivityIntentInfo filter : a.intents) { 14984 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14985 if (DEBUG_DOMAIN_VERIFICATION) { 14986 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14987 } 14988 needToVerify = true; 14989 break; 14990 } 14991 } 14992 } 14993 14994 if (needToVerify) { 14995 final int verificationId = mIntentFilterVerificationToken++; 14996 for (PackageParser.Activity a : pkg.activities) { 14997 for (ActivityIntentInfo filter : a.intents) { 14998 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14999 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 15000 "Verification needed for IntentFilter:" + filter.toString()); 15001 mIntentFilterVerifier.addOneIntentFilterVerification( 15002 verifierUid, userId, verificationId, filter, packageName); 15003 count++; 15004 } 15005 } 15006 } 15007 } 15008 } 15009 15010 if (count > 0) { 15011 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 15012 + " IntentFilter verification" + (count > 1 ? "s" : "") 15013 + " for userId:" + userId); 15014 mIntentFilterVerifier.startVerifications(userId); 15015 } else { 15016 if (DEBUG_DOMAIN_VERIFICATION) { 15017 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 15018 } 15019 } 15020 } 15021 15022 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 15023 final ComponentName cn = filter.activity.getComponentName(); 15024 final String packageName = cn.getPackageName(); 15025 15026 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 15027 packageName); 15028 if (ivi == null) { 15029 return true; 15030 } 15031 int status = ivi.getStatus(); 15032 switch (status) { 15033 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 15034 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 15035 return true; 15036 15037 default: 15038 // Nothing to do 15039 return false; 15040 } 15041 } 15042 15043 private static boolean isMultiArch(ApplicationInfo info) { 15044 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 15045 } 15046 15047 private static boolean isExternal(PackageParser.Package pkg) { 15048 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15049 } 15050 15051 private static boolean isExternal(PackageSetting ps) { 15052 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 15053 } 15054 15055 private static boolean isEphemeral(PackageParser.Package pkg) { 15056 return pkg.applicationInfo.isEphemeralApp(); 15057 } 15058 15059 private static boolean isEphemeral(PackageSetting ps) { 15060 return ps.pkg != null && isEphemeral(ps.pkg); 15061 } 15062 15063 private static boolean isSystemApp(PackageParser.Package pkg) { 15064 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 15065 } 15066 15067 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 15068 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 15069 } 15070 15071 private static boolean hasDomainURLs(PackageParser.Package pkg) { 15072 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 15073 } 15074 15075 private static boolean isSystemApp(PackageSetting ps) { 15076 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 15077 } 15078 15079 private static boolean isUpdatedSystemApp(PackageSetting ps) { 15080 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 15081 } 15082 15083 private int packageFlagsToInstallFlags(PackageSetting ps) { 15084 int installFlags = 0; 15085 if (isEphemeral(ps)) { 15086 installFlags |= PackageManager.INSTALL_EPHEMERAL; 15087 } 15088 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 15089 // This existing package was an external ASEC install when we have 15090 // the external flag without a UUID 15091 installFlags |= PackageManager.INSTALL_EXTERNAL; 15092 } 15093 if (ps.isForwardLocked()) { 15094 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 15095 } 15096 return installFlags; 15097 } 15098 15099 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 15100 if (isExternal(pkg)) { 15101 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15102 return StorageManager.UUID_PRIMARY_PHYSICAL; 15103 } else { 15104 return pkg.volumeUuid; 15105 } 15106 } else { 15107 return StorageManager.UUID_PRIVATE_INTERNAL; 15108 } 15109 } 15110 15111 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 15112 if (isExternal(pkg)) { 15113 if (TextUtils.isEmpty(pkg.volumeUuid)) { 15114 return mSettings.getExternalVersion(); 15115 } else { 15116 return mSettings.findOrCreateVersion(pkg.volumeUuid); 15117 } 15118 } else { 15119 return mSettings.getInternalVersion(); 15120 } 15121 } 15122 15123 private void deleteTempPackageFiles() { 15124 final FilenameFilter filter = new FilenameFilter() { 15125 public boolean accept(File dir, String name) { 15126 return name.startsWith("vmdl") && name.endsWith(".tmp"); 15127 } 15128 }; 15129 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 15130 file.delete(); 15131 } 15132 } 15133 15134 @Override 15135 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 15136 int flags) { 15137 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 15138 flags); 15139 } 15140 15141 @Override 15142 public void deletePackage(final String packageName, 15143 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 15144 mContext.enforceCallingOrSelfPermission( 15145 android.Manifest.permission.DELETE_PACKAGES, null); 15146 Preconditions.checkNotNull(packageName); 15147 Preconditions.checkNotNull(observer); 15148 final int uid = Binder.getCallingUid(); 15149 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 15150 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 15151 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 15152 mContext.enforceCallingOrSelfPermission( 15153 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 15154 "deletePackage for user " + userId); 15155 } 15156 15157 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 15158 try { 15159 observer.onPackageDeleted(packageName, 15160 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 15161 } catch (RemoteException re) { 15162 } 15163 return; 15164 } 15165 15166 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15167 try { 15168 observer.onPackageDeleted(packageName, 15169 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15170 } catch (RemoteException re) { 15171 } 15172 return; 15173 } 15174 15175 if (DEBUG_REMOVE) { 15176 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15177 + " deleteAllUsers: " + deleteAllUsers ); 15178 } 15179 // Queue up an async operation since the package deletion may take a little while. 15180 mHandler.post(new Runnable() { 15181 public void run() { 15182 mHandler.removeCallbacks(this); 15183 int returnCode; 15184 if (!deleteAllUsers) { 15185 returnCode = deletePackageX(packageName, userId, deleteFlags); 15186 } else { 15187 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15188 // If nobody is blocking uninstall, proceed with delete for all users 15189 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15190 returnCode = deletePackageX(packageName, userId, deleteFlags); 15191 } else { 15192 // Otherwise uninstall individually for users with blockUninstalls=false 15193 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15194 for (int userId : users) { 15195 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15196 returnCode = deletePackageX(packageName, userId, userFlags); 15197 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15198 Slog.w(TAG, "Package delete failed for user " + userId 15199 + ", returnCode " + returnCode); 15200 } 15201 } 15202 } 15203 // The app has only been marked uninstalled for certain users. 15204 // We still need to report that delete was blocked 15205 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15206 } 15207 } 15208 try { 15209 observer.onPackageDeleted(packageName, returnCode, null); 15210 } catch (RemoteException e) { 15211 Log.i(TAG, "Observer no longer exists."); 15212 } //end catch 15213 } //end run 15214 }); 15215 } 15216 15217 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15218 int[] result = EMPTY_INT_ARRAY; 15219 for (int userId : userIds) { 15220 if (getBlockUninstallForUser(packageName, userId)) { 15221 result = ArrayUtils.appendInt(result, userId); 15222 } 15223 } 15224 return result; 15225 } 15226 15227 @Override 15228 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15229 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15230 } 15231 15232 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15233 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15234 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15235 try { 15236 if (dpm != null) { 15237 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15238 /* callingUserOnly =*/ false); 15239 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15240 : deviceOwnerComponentName.getPackageName(); 15241 // Does the package contains the device owner? 15242 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15243 // this check is probably not needed, since DO should be registered as a device 15244 // admin on some user too. (Original bug for this: b/17657954) 15245 if (packageName.equals(deviceOwnerPackageName)) { 15246 return true; 15247 } 15248 // Does it contain a device admin for any user? 15249 int[] users; 15250 if (userId == UserHandle.USER_ALL) { 15251 users = sUserManager.getUserIds(); 15252 } else { 15253 users = new int[]{userId}; 15254 } 15255 for (int i = 0; i < users.length; ++i) { 15256 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15257 return true; 15258 } 15259 } 15260 } 15261 } catch (RemoteException e) { 15262 } 15263 return false; 15264 } 15265 15266 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15267 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15268 } 15269 15270 /** 15271 * This method is an internal method that could be get invoked either 15272 * to delete an installed package or to clean up a failed installation. 15273 * After deleting an installed package, a broadcast is sent to notify any 15274 * listeners that the package has been removed. For cleaning up a failed 15275 * installation, the broadcast is not necessary since the package's 15276 * installation wouldn't have sent the initial broadcast either 15277 * The key steps in deleting a package are 15278 * deleting the package information in internal structures like mPackages, 15279 * deleting the packages base directories through installd 15280 * updating mSettings to reflect current status 15281 * persisting settings for later use 15282 * sending a broadcast if necessary 15283 */ 15284 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15285 final PackageRemovedInfo info = new PackageRemovedInfo(); 15286 final boolean res; 15287 15288 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15289 ? UserHandle.ALL : new UserHandle(userId); 15290 15291 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15292 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15293 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15294 } 15295 15296 PackageSetting uninstalledPs = null; 15297 15298 // for the uninstall-updates case and restricted profiles, remember the per- 15299 // user handle installed state 15300 int[] allUsers; 15301 synchronized (mPackages) { 15302 uninstalledPs = mSettings.mPackages.get(packageName); 15303 if (uninstalledPs == null) { 15304 Slog.w(TAG, "Not removing non-existent package " + packageName); 15305 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15306 } 15307 allUsers = sUserManager.getUserIds(); 15308 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15309 } 15310 15311 synchronized (mInstallLock) { 15312 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15313 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15314 "deletePackageX")) { 15315 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15316 deleteFlags | REMOVE_CHATTY, info, true, null); 15317 } 15318 synchronized (mPackages) { 15319 if (res) { 15320 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15321 } 15322 } 15323 } 15324 15325 if (res) { 15326 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15327 info.sendPackageRemovedBroadcasts(killApp); 15328 info.sendSystemPackageUpdatedBroadcasts(); 15329 info.sendSystemPackageAppearedBroadcasts(); 15330 } 15331 // Force a gc here. 15332 Runtime.getRuntime().gc(); 15333 // Delete the resources here after sending the broadcast to let 15334 // other processes clean up before deleting resources. 15335 if (info.args != null) { 15336 synchronized (mInstallLock) { 15337 info.args.doPostDeleteLI(true); 15338 } 15339 } 15340 15341 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15342 } 15343 15344 class PackageRemovedInfo { 15345 String removedPackage; 15346 int uid = -1; 15347 int removedAppId = -1; 15348 int[] origUsers; 15349 int[] removedUsers = null; 15350 boolean isRemovedPackageSystemUpdate = false; 15351 boolean isUpdate; 15352 boolean dataRemoved; 15353 boolean removedForAllUsers; 15354 // Clean up resources deleted packages. 15355 InstallArgs args = null; 15356 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15357 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15358 15359 void sendPackageRemovedBroadcasts(boolean killApp) { 15360 sendPackageRemovedBroadcastInternal(killApp); 15361 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15362 for (int i = 0; i < childCount; i++) { 15363 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15364 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15365 } 15366 } 15367 15368 void sendSystemPackageUpdatedBroadcasts() { 15369 if (isRemovedPackageSystemUpdate) { 15370 sendSystemPackageUpdatedBroadcastsInternal(); 15371 final int childCount = (removedChildPackages != null) 15372 ? removedChildPackages.size() : 0; 15373 for (int i = 0; i < childCount; i++) { 15374 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15375 if (childInfo.isRemovedPackageSystemUpdate) { 15376 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15377 } 15378 } 15379 } 15380 } 15381 15382 void sendSystemPackageAppearedBroadcasts() { 15383 final int packageCount = (appearedChildPackages != null) 15384 ? appearedChildPackages.size() : 0; 15385 for (int i = 0; i < packageCount; i++) { 15386 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15387 for (int userId : installedInfo.newUsers) { 15388 sendPackageAddedForUser(installedInfo.name, true, 15389 UserHandle.getAppId(installedInfo.uid), userId); 15390 } 15391 } 15392 } 15393 15394 private void sendSystemPackageUpdatedBroadcastsInternal() { 15395 Bundle extras = new Bundle(2); 15396 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15397 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15398 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15399 extras, 0, null, null, null); 15400 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15401 extras, 0, null, null, null); 15402 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15403 null, 0, removedPackage, null, null); 15404 } 15405 15406 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15407 Bundle extras = new Bundle(2); 15408 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15409 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15410 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15411 if (isUpdate || isRemovedPackageSystemUpdate) { 15412 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15413 } 15414 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15415 if (removedPackage != null) { 15416 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15417 extras, 0, null, null, removedUsers); 15418 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15419 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15420 removedPackage, extras, 0, null, null, removedUsers); 15421 } 15422 } 15423 if (removedAppId >= 0) { 15424 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15425 removedUsers); 15426 } 15427 } 15428 } 15429 15430 /* 15431 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15432 * flag is not set, the data directory is removed as well. 15433 * make sure this flag is set for partially installed apps. If not its meaningless to 15434 * delete a partially installed application. 15435 */ 15436 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15437 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15438 String packageName = ps.name; 15439 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15440 // Retrieve object to delete permissions for shared user later on 15441 final PackageParser.Package deletedPkg; 15442 final PackageSetting deletedPs; 15443 // reader 15444 synchronized (mPackages) { 15445 deletedPkg = mPackages.get(packageName); 15446 deletedPs = mSettings.mPackages.get(packageName); 15447 if (outInfo != null) { 15448 outInfo.removedPackage = packageName; 15449 outInfo.removedUsers = deletedPs != null 15450 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15451 : null; 15452 } 15453 } 15454 15455 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15456 15457 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15458 final PackageParser.Package resolvedPkg; 15459 if (deletedPkg != null) { 15460 resolvedPkg = deletedPkg; 15461 } else { 15462 // We don't have a parsed package when it lives on an ejected 15463 // adopted storage device, so fake something together 15464 resolvedPkg = new PackageParser.Package(ps.name); 15465 resolvedPkg.setVolumeUuid(ps.volumeUuid); 15466 } 15467 destroyAppDataLIF(resolvedPkg, UserHandle.USER_ALL, 15468 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15469 destroyAppProfilesLIF(resolvedPkg); 15470 if (outInfo != null) { 15471 outInfo.dataRemoved = true; 15472 } 15473 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15474 } 15475 15476 // writer 15477 synchronized (mPackages) { 15478 if (deletedPs != null) { 15479 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15480 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15481 clearDefaultBrowserIfNeeded(packageName); 15482 if (outInfo != null) { 15483 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15484 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15485 } 15486 updatePermissionsLPw(deletedPs.name, null, 0); 15487 if (deletedPs.sharedUser != null) { 15488 // Remove permissions associated with package. Since runtime 15489 // permissions are per user we have to kill the removed package 15490 // or packages running under the shared user of the removed 15491 // package if revoking the permissions requested only by the removed 15492 // package is successful and this causes a change in gids. 15493 for (int userId : UserManagerService.getInstance().getUserIds()) { 15494 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15495 userId); 15496 if (userIdToKill == UserHandle.USER_ALL 15497 || userIdToKill >= UserHandle.USER_SYSTEM) { 15498 // If gids changed for this user, kill all affected packages. 15499 mHandler.post(new Runnable() { 15500 @Override 15501 public void run() { 15502 // This has to happen with no lock held. 15503 killApplication(deletedPs.name, deletedPs.appId, 15504 KILL_APP_REASON_GIDS_CHANGED); 15505 } 15506 }); 15507 break; 15508 } 15509 } 15510 } 15511 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15512 } 15513 // make sure to preserve per-user disabled state if this removal was just 15514 // a downgrade of a system app to the factory package 15515 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15516 if (DEBUG_REMOVE) { 15517 Slog.d(TAG, "Propagating install state across downgrade"); 15518 } 15519 for (int userId : allUserHandles) { 15520 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15521 if (DEBUG_REMOVE) { 15522 Slog.d(TAG, " user " + userId + " => " + installed); 15523 } 15524 ps.setInstalled(installed, userId); 15525 } 15526 } 15527 } 15528 // can downgrade to reader 15529 if (writeSettings) { 15530 // Save settings now 15531 mSettings.writeLPr(); 15532 } 15533 } 15534 if (outInfo != null) { 15535 // A user ID was deleted here. Go through all users and remove it 15536 // from KeyStore. 15537 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15538 } 15539 } 15540 15541 static boolean locationIsPrivileged(File path) { 15542 try { 15543 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15544 .getCanonicalPath(); 15545 return path.getCanonicalPath().startsWith(privilegedAppDir); 15546 } catch (IOException e) { 15547 Slog.e(TAG, "Unable to access code path " + path); 15548 } 15549 return false; 15550 } 15551 15552 /* 15553 * Tries to delete system package. 15554 */ 15555 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15556 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15557 boolean writeSettings) { 15558 if (deletedPs.parentPackageName != null) { 15559 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15560 return false; 15561 } 15562 15563 final boolean applyUserRestrictions 15564 = (allUserHandles != null) && (outInfo.origUsers != null); 15565 final PackageSetting disabledPs; 15566 // Confirm if the system package has been updated 15567 // An updated system app can be deleted. This will also have to restore 15568 // the system pkg from system partition 15569 // reader 15570 synchronized (mPackages) { 15571 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15572 } 15573 15574 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15575 + " disabledPs=" + disabledPs); 15576 15577 if (disabledPs == null) { 15578 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15579 return false; 15580 } else if (DEBUG_REMOVE) { 15581 Slog.d(TAG, "Deleting system pkg from data partition"); 15582 } 15583 15584 if (DEBUG_REMOVE) { 15585 if (applyUserRestrictions) { 15586 Slog.d(TAG, "Remembering install states:"); 15587 for (int userId : allUserHandles) { 15588 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15589 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15590 } 15591 } 15592 } 15593 15594 // Delete the updated package 15595 outInfo.isRemovedPackageSystemUpdate = true; 15596 if (outInfo.removedChildPackages != null) { 15597 final int childCount = (deletedPs.childPackageNames != null) 15598 ? deletedPs.childPackageNames.size() : 0; 15599 for (int i = 0; i < childCount; i++) { 15600 String childPackageName = deletedPs.childPackageNames.get(i); 15601 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15602 .contains(childPackageName)) { 15603 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15604 childPackageName); 15605 if (childInfo != null) { 15606 childInfo.isRemovedPackageSystemUpdate = true; 15607 } 15608 } 15609 } 15610 } 15611 15612 if (disabledPs.versionCode < deletedPs.versionCode) { 15613 // Delete data for downgrades 15614 flags &= ~PackageManager.DELETE_KEEP_DATA; 15615 } else { 15616 // Preserve data by setting flag 15617 flags |= PackageManager.DELETE_KEEP_DATA; 15618 } 15619 15620 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15621 outInfo, writeSettings, disabledPs.pkg); 15622 if (!ret) { 15623 return false; 15624 } 15625 15626 // writer 15627 synchronized (mPackages) { 15628 // Reinstate the old system package 15629 enableSystemPackageLPw(disabledPs.pkg); 15630 // Remove any native libraries from the upgraded package. 15631 removeNativeBinariesLI(deletedPs); 15632 } 15633 15634 // Install the system package 15635 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15636 int parseFlags = mDefParseFlags 15637 | PackageParser.PARSE_MUST_BE_APK 15638 | PackageParser.PARSE_IS_SYSTEM 15639 | PackageParser.PARSE_IS_SYSTEM_DIR; 15640 if (locationIsPrivileged(disabledPs.codePath)) { 15641 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15642 } 15643 15644 final PackageParser.Package newPkg; 15645 try { 15646 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15647 } catch (PackageManagerException e) { 15648 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15649 + e.getMessage()); 15650 return false; 15651 } 15652 15653 prepareAppDataAfterInstallLIF(newPkg); 15654 15655 // writer 15656 synchronized (mPackages) { 15657 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15658 15659 // Propagate the permissions state as we do not want to drop on the floor 15660 // runtime permissions. The update permissions method below will take 15661 // care of removing obsolete permissions and grant install permissions. 15662 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15663 updatePermissionsLPw(newPkg.packageName, newPkg, 15664 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15665 15666 if (applyUserRestrictions) { 15667 if (DEBUG_REMOVE) { 15668 Slog.d(TAG, "Propagating install state across reinstall"); 15669 } 15670 for (int userId : allUserHandles) { 15671 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15672 if (DEBUG_REMOVE) { 15673 Slog.d(TAG, " user " + userId + " => " + installed); 15674 } 15675 ps.setInstalled(installed, userId); 15676 15677 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15678 } 15679 // Regardless of writeSettings we need to ensure that this restriction 15680 // state propagation is persisted 15681 mSettings.writeAllUsersPackageRestrictionsLPr(); 15682 } 15683 // can downgrade to reader here 15684 if (writeSettings) { 15685 mSettings.writeLPr(); 15686 } 15687 } 15688 return true; 15689 } 15690 15691 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15692 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15693 PackageRemovedInfo outInfo, boolean writeSettings, 15694 PackageParser.Package replacingPackage) { 15695 synchronized (mPackages) { 15696 if (outInfo != null) { 15697 outInfo.uid = ps.appId; 15698 } 15699 15700 if (outInfo != null && outInfo.removedChildPackages != null) { 15701 final int childCount = (ps.childPackageNames != null) 15702 ? ps.childPackageNames.size() : 0; 15703 for (int i = 0; i < childCount; i++) { 15704 String childPackageName = ps.childPackageNames.get(i); 15705 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15706 if (childPs == null) { 15707 return false; 15708 } 15709 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15710 childPackageName); 15711 if (childInfo != null) { 15712 childInfo.uid = childPs.appId; 15713 } 15714 } 15715 } 15716 } 15717 15718 // Delete package data from internal structures and also remove data if flag is set 15719 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15720 15721 // Delete the child packages data 15722 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15723 for (int i = 0; i < childCount; i++) { 15724 PackageSetting childPs; 15725 synchronized (mPackages) { 15726 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15727 } 15728 if (childPs != null) { 15729 PackageRemovedInfo childOutInfo = (outInfo != null 15730 && outInfo.removedChildPackages != null) 15731 ? outInfo.removedChildPackages.get(childPs.name) : null; 15732 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15733 && (replacingPackage != null 15734 && !replacingPackage.hasChildPackage(childPs.name)) 15735 ? flags & ~DELETE_KEEP_DATA : flags; 15736 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15737 deleteFlags, writeSettings); 15738 } 15739 } 15740 15741 // Delete application code and resources only for parent packages 15742 if (ps.parentPackageName == null) { 15743 if (deleteCodeAndResources && (outInfo != null)) { 15744 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15745 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15746 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15747 } 15748 } 15749 15750 return true; 15751 } 15752 15753 @Override 15754 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15755 int userId) { 15756 mContext.enforceCallingOrSelfPermission( 15757 android.Manifest.permission.DELETE_PACKAGES, null); 15758 synchronized (mPackages) { 15759 PackageSetting ps = mSettings.mPackages.get(packageName); 15760 if (ps == null) { 15761 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15762 return false; 15763 } 15764 if (!ps.getInstalled(userId)) { 15765 // Can't block uninstall for an app that is not installed or enabled. 15766 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15767 return false; 15768 } 15769 ps.setBlockUninstall(blockUninstall, userId); 15770 mSettings.writePackageRestrictionsLPr(userId); 15771 } 15772 return true; 15773 } 15774 15775 @Override 15776 public boolean getBlockUninstallForUser(String packageName, int userId) { 15777 synchronized (mPackages) { 15778 PackageSetting ps = mSettings.mPackages.get(packageName); 15779 if (ps == null) { 15780 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15781 return false; 15782 } 15783 return ps.getBlockUninstall(userId); 15784 } 15785 } 15786 15787 @Override 15788 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15789 int callingUid = Binder.getCallingUid(); 15790 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15791 throw new SecurityException( 15792 "setRequiredForSystemUser can only be run by the system or root"); 15793 } 15794 synchronized (mPackages) { 15795 PackageSetting ps = mSettings.mPackages.get(packageName); 15796 if (ps == null) { 15797 Log.w(TAG, "Package doesn't exist: " + packageName); 15798 return false; 15799 } 15800 if (systemUserApp) { 15801 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15802 } else { 15803 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15804 } 15805 mSettings.writeLPr(); 15806 } 15807 return true; 15808 } 15809 15810 /* 15811 * This method handles package deletion in general 15812 */ 15813 private boolean deletePackageLIF(String packageName, UserHandle user, 15814 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15815 PackageRemovedInfo outInfo, boolean writeSettings, 15816 PackageParser.Package replacingPackage) { 15817 if (packageName == null) { 15818 Slog.w(TAG, "Attempt to delete null packageName."); 15819 return false; 15820 } 15821 15822 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15823 15824 PackageSetting ps; 15825 15826 synchronized (mPackages) { 15827 ps = mSettings.mPackages.get(packageName); 15828 if (ps == null) { 15829 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15830 return false; 15831 } 15832 15833 if (ps.parentPackageName != null && (!isSystemApp(ps) 15834 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15835 if (DEBUG_REMOVE) { 15836 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15837 + ((user == null) ? UserHandle.USER_ALL : user)); 15838 } 15839 final int removedUserId = (user != null) ? user.getIdentifier() 15840 : UserHandle.USER_ALL; 15841 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15842 return false; 15843 } 15844 markPackageUninstalledForUserLPw(ps, user); 15845 scheduleWritePackageRestrictionsLocked(user); 15846 return true; 15847 } 15848 } 15849 15850 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15851 && user.getIdentifier() != UserHandle.USER_ALL)) { 15852 // The caller is asking that the package only be deleted for a single 15853 // user. To do this, we just mark its uninstalled state and delete 15854 // its data. If this is a system app, we only allow this to happen if 15855 // they have set the special DELETE_SYSTEM_APP which requests different 15856 // semantics than normal for uninstalling system apps. 15857 markPackageUninstalledForUserLPw(ps, user); 15858 15859 if (!isSystemApp(ps)) { 15860 // Do not uninstall the APK if an app should be cached 15861 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15862 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15863 // Other user still have this package installed, so all 15864 // we need to do is clear this user's data and save that 15865 // it is uninstalled. 15866 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15867 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15868 return false; 15869 } 15870 scheduleWritePackageRestrictionsLocked(user); 15871 return true; 15872 } else { 15873 // We need to set it back to 'installed' so the uninstall 15874 // broadcasts will be sent correctly. 15875 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15876 ps.setInstalled(true, user.getIdentifier()); 15877 } 15878 } else { 15879 // This is a system app, so we assume that the 15880 // other users still have this package installed, so all 15881 // we need to do is clear this user's data and save that 15882 // it is uninstalled. 15883 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15884 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15885 return false; 15886 } 15887 scheduleWritePackageRestrictionsLocked(user); 15888 return true; 15889 } 15890 } 15891 15892 // If we are deleting a composite package for all users, keep track 15893 // of result for each child. 15894 if (ps.childPackageNames != null && outInfo != null) { 15895 synchronized (mPackages) { 15896 final int childCount = ps.childPackageNames.size(); 15897 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15898 for (int i = 0; i < childCount; i++) { 15899 String childPackageName = ps.childPackageNames.get(i); 15900 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15901 childInfo.removedPackage = childPackageName; 15902 outInfo.removedChildPackages.put(childPackageName, childInfo); 15903 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15904 if (childPs != null) { 15905 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15906 } 15907 } 15908 } 15909 } 15910 15911 boolean ret = false; 15912 if (isSystemApp(ps)) { 15913 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15914 // When an updated system application is deleted we delete the existing resources 15915 // as well and fall back to existing code in system partition 15916 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15917 } else { 15918 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15919 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15920 outInfo, writeSettings, replacingPackage); 15921 } 15922 15923 // Take a note whether we deleted the package for all users 15924 if (outInfo != null) { 15925 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15926 if (outInfo.removedChildPackages != null) { 15927 synchronized (mPackages) { 15928 final int childCount = outInfo.removedChildPackages.size(); 15929 for (int i = 0; i < childCount; i++) { 15930 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15931 if (childInfo != null) { 15932 childInfo.removedForAllUsers = mPackages.get( 15933 childInfo.removedPackage) == null; 15934 } 15935 } 15936 } 15937 } 15938 // If we uninstalled an update to a system app there may be some 15939 // child packages that appeared as they are declared in the system 15940 // app but were not declared in the update. 15941 if (isSystemApp(ps)) { 15942 synchronized (mPackages) { 15943 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15944 final int childCount = (updatedPs.childPackageNames != null) 15945 ? updatedPs.childPackageNames.size() : 0; 15946 for (int i = 0; i < childCount; i++) { 15947 String childPackageName = updatedPs.childPackageNames.get(i); 15948 if (outInfo.removedChildPackages == null 15949 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15950 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15951 if (childPs == null) { 15952 continue; 15953 } 15954 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15955 installRes.name = childPackageName; 15956 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15957 installRes.pkg = mPackages.get(childPackageName); 15958 installRes.uid = childPs.pkg.applicationInfo.uid; 15959 if (outInfo.appearedChildPackages == null) { 15960 outInfo.appearedChildPackages = new ArrayMap<>(); 15961 } 15962 outInfo.appearedChildPackages.put(childPackageName, installRes); 15963 } 15964 } 15965 } 15966 } 15967 } 15968 15969 return ret; 15970 } 15971 15972 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15973 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15974 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15975 for (int nextUserId : userIds) { 15976 if (DEBUG_REMOVE) { 15977 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15978 } 15979 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15980 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15981 false /*hidden*/, false /*suspended*/, null, null, null, 15982 false /*blockUninstall*/, 15983 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15984 } 15985 } 15986 15987 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15988 PackageRemovedInfo outInfo) { 15989 final PackageParser.Package pkg; 15990 synchronized (mPackages) { 15991 pkg = mPackages.get(ps.name); 15992 } 15993 15994 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15995 : new int[] {userId}; 15996 for (int nextUserId : userIds) { 15997 if (DEBUG_REMOVE) { 15998 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15999 + nextUserId); 16000 } 16001 16002 destroyAppDataLIF(pkg, userId, 16003 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16004 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 16005 schedulePackageCleaning(ps.name, nextUserId, false); 16006 synchronized (mPackages) { 16007 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 16008 scheduleWritePackageRestrictionsLocked(nextUserId); 16009 } 16010 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 16011 } 16012 } 16013 16014 if (outInfo != null) { 16015 outInfo.removedPackage = ps.name; 16016 outInfo.removedAppId = ps.appId; 16017 outInfo.removedUsers = userIds; 16018 } 16019 16020 return true; 16021 } 16022 16023 private final class ClearStorageConnection implements ServiceConnection { 16024 IMediaContainerService mContainerService; 16025 16026 @Override 16027 public void onServiceConnected(ComponentName name, IBinder service) { 16028 synchronized (this) { 16029 mContainerService = IMediaContainerService.Stub.asInterface(service); 16030 notifyAll(); 16031 } 16032 } 16033 16034 @Override 16035 public void onServiceDisconnected(ComponentName name) { 16036 } 16037 } 16038 16039 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 16040 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 16041 16042 final boolean mounted; 16043 if (Environment.isExternalStorageEmulated()) { 16044 mounted = true; 16045 } else { 16046 final String status = Environment.getExternalStorageState(); 16047 16048 mounted = status.equals(Environment.MEDIA_MOUNTED) 16049 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 16050 } 16051 16052 if (!mounted) { 16053 return; 16054 } 16055 16056 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 16057 int[] users; 16058 if (userId == UserHandle.USER_ALL) { 16059 users = sUserManager.getUserIds(); 16060 } else { 16061 users = new int[] { userId }; 16062 } 16063 final ClearStorageConnection conn = new ClearStorageConnection(); 16064 if (mContext.bindServiceAsUser( 16065 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 16066 try { 16067 for (int curUser : users) { 16068 long timeout = SystemClock.uptimeMillis() + 5000; 16069 synchronized (conn) { 16070 long now = SystemClock.uptimeMillis(); 16071 while (conn.mContainerService == null && now < timeout) { 16072 try { 16073 conn.wait(timeout - now); 16074 } catch (InterruptedException e) { 16075 } 16076 } 16077 } 16078 if (conn.mContainerService == null) { 16079 return; 16080 } 16081 16082 final UserEnvironment userEnv = new UserEnvironment(curUser); 16083 clearDirectory(conn.mContainerService, 16084 userEnv.buildExternalStorageAppCacheDirs(packageName)); 16085 if (allData) { 16086 clearDirectory(conn.mContainerService, 16087 userEnv.buildExternalStorageAppDataDirs(packageName)); 16088 clearDirectory(conn.mContainerService, 16089 userEnv.buildExternalStorageAppMediaDirs(packageName)); 16090 } 16091 } 16092 } finally { 16093 mContext.unbindService(conn); 16094 } 16095 } 16096 } 16097 16098 @Override 16099 public void clearApplicationProfileData(String packageName) { 16100 enforceSystemOrRoot("Only the system can clear all profile data"); 16101 16102 final PackageParser.Package pkg; 16103 synchronized (mPackages) { 16104 pkg = mPackages.get(packageName); 16105 } 16106 16107 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 16108 synchronized (mInstallLock) { 16109 clearAppProfilesLIF(pkg); 16110 } 16111 } 16112 } 16113 16114 @Override 16115 public void clearApplicationUserData(final String packageName, 16116 final IPackageDataObserver observer, final int userId) { 16117 mContext.enforceCallingOrSelfPermission( 16118 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 16119 16120 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16121 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 16122 16123 final DevicePolicyManagerInternal dpmi = LocalServices 16124 .getService(DevicePolicyManagerInternal.class); 16125 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 16126 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 16127 } 16128 // Queue up an async operation since the package deletion may take a little while. 16129 mHandler.post(new Runnable() { 16130 public void run() { 16131 mHandler.removeCallbacks(this); 16132 final boolean succeeded; 16133 try (PackageFreezer freezer = freezePackage(packageName, 16134 "clearApplicationUserData")) { 16135 synchronized (mInstallLock) { 16136 succeeded = clearApplicationUserDataLIF(packageName, userId); 16137 } 16138 clearExternalStorageDataSync(packageName, userId, true); 16139 } 16140 if (succeeded) { 16141 // invoke DeviceStorageMonitor's update method to clear any notifications 16142 DeviceStorageMonitorInternal dsm = LocalServices 16143 .getService(DeviceStorageMonitorInternal.class); 16144 if (dsm != null) { 16145 dsm.checkMemory(); 16146 } 16147 } 16148 if(observer != null) { 16149 try { 16150 observer.onRemoveCompleted(packageName, succeeded); 16151 } catch (RemoteException e) { 16152 Log.i(TAG, "Observer no longer exists."); 16153 } 16154 } //end if observer 16155 } //end run 16156 }); 16157 } 16158 16159 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 16160 if (packageName == null) { 16161 Slog.w(TAG, "Attempt to delete null packageName."); 16162 return false; 16163 } 16164 16165 // Try finding details about the requested package 16166 PackageParser.Package pkg; 16167 synchronized (mPackages) { 16168 pkg = mPackages.get(packageName); 16169 if (pkg == null) { 16170 final PackageSetting ps = mSettings.mPackages.get(packageName); 16171 if (ps != null) { 16172 pkg = ps.pkg; 16173 } 16174 } 16175 16176 if (pkg == null) { 16177 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16178 return false; 16179 } 16180 16181 PackageSetting ps = (PackageSetting) pkg.mExtras; 16182 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16183 } 16184 16185 clearAppDataLIF(pkg, userId, 16186 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16187 16188 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16189 removeKeystoreDataIfNeeded(userId, appId); 16190 16191 final UserManager um = mContext.getSystemService(UserManager.class); 16192 final int flags; 16193 if (um.isUserUnlockingOrUnlocked(userId)) { 16194 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16195 } else if (um.isUserRunning(userId)) { 16196 flags = StorageManager.FLAG_STORAGE_DE; 16197 } else { 16198 flags = 0; 16199 } 16200 prepareAppDataContentsLIF(pkg, userId, flags); 16201 16202 return true; 16203 } 16204 16205 /** 16206 * Reverts user permission state changes (permissions and flags) in 16207 * all packages for a given user. 16208 * 16209 * @param userId The device user for which to do a reset. 16210 */ 16211 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16212 final int packageCount = mPackages.size(); 16213 for (int i = 0; i < packageCount; i++) { 16214 PackageParser.Package pkg = mPackages.valueAt(i); 16215 PackageSetting ps = (PackageSetting) pkg.mExtras; 16216 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16217 } 16218 } 16219 16220 private void resetNetworkPolicies(int userId) { 16221 LocalServices.getService(NetworkPolicyManagerInternal.class).resetUserState(userId); 16222 } 16223 16224 /** 16225 * Reverts user permission state changes (permissions and flags). 16226 * 16227 * @param ps The package for which to reset. 16228 * @param userId The device user for which to do a reset. 16229 */ 16230 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16231 final PackageSetting ps, final int userId) { 16232 if (ps.pkg == null) { 16233 return; 16234 } 16235 16236 // These are flags that can change base on user actions. 16237 final int userSettableMask = FLAG_PERMISSION_USER_SET 16238 | FLAG_PERMISSION_USER_FIXED 16239 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16240 | FLAG_PERMISSION_REVIEW_REQUIRED; 16241 16242 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16243 | FLAG_PERMISSION_POLICY_FIXED; 16244 16245 boolean writeInstallPermissions = false; 16246 boolean writeRuntimePermissions = false; 16247 16248 final int permissionCount = ps.pkg.requestedPermissions.size(); 16249 for (int i = 0; i < permissionCount; i++) { 16250 String permission = ps.pkg.requestedPermissions.get(i); 16251 16252 BasePermission bp = mSettings.mPermissions.get(permission); 16253 if (bp == null) { 16254 continue; 16255 } 16256 16257 // If shared user we just reset the state to which only this app contributed. 16258 if (ps.sharedUser != null) { 16259 boolean used = false; 16260 final int packageCount = ps.sharedUser.packages.size(); 16261 for (int j = 0; j < packageCount; j++) { 16262 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16263 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16264 && pkg.pkg.requestedPermissions.contains(permission)) { 16265 used = true; 16266 break; 16267 } 16268 } 16269 if (used) { 16270 continue; 16271 } 16272 } 16273 16274 PermissionsState permissionsState = ps.getPermissionsState(); 16275 16276 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16277 16278 // Always clear the user settable flags. 16279 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16280 bp.name) != null; 16281 // If permission review is enabled and this is a legacy app, mark the 16282 // permission as requiring a review as this is the initial state. 16283 int flags = 0; 16284 if (Build.PERMISSIONS_REVIEW_REQUIRED 16285 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16286 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16287 } 16288 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16289 if (hasInstallState) { 16290 writeInstallPermissions = true; 16291 } else { 16292 writeRuntimePermissions = true; 16293 } 16294 } 16295 16296 // Below is only runtime permission handling. 16297 if (!bp.isRuntime()) { 16298 continue; 16299 } 16300 16301 // Never clobber system or policy. 16302 if ((oldFlags & policyOrSystemFlags) != 0) { 16303 continue; 16304 } 16305 16306 // If this permission was granted by default, make sure it is. 16307 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16308 if (permissionsState.grantRuntimePermission(bp, userId) 16309 != PERMISSION_OPERATION_FAILURE) { 16310 writeRuntimePermissions = true; 16311 } 16312 // If permission review is enabled the permissions for a legacy apps 16313 // are represented as constantly granted runtime ones, so don't revoke. 16314 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16315 // Otherwise, reset the permission. 16316 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16317 switch (revokeResult) { 16318 case PERMISSION_OPERATION_SUCCESS: 16319 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16320 writeRuntimePermissions = true; 16321 final int appId = ps.appId; 16322 mHandler.post(new Runnable() { 16323 @Override 16324 public void run() { 16325 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16326 } 16327 }); 16328 } break; 16329 } 16330 } 16331 } 16332 16333 // Synchronously write as we are taking permissions away. 16334 if (writeRuntimePermissions) { 16335 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16336 } 16337 16338 // Synchronously write as we are taking permissions away. 16339 if (writeInstallPermissions) { 16340 mSettings.writeLPr(); 16341 } 16342 } 16343 16344 /** 16345 * Remove entries from the keystore daemon. Will only remove it if the 16346 * {@code appId} is valid. 16347 */ 16348 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16349 if (appId < 0) { 16350 return; 16351 } 16352 16353 final KeyStore keyStore = KeyStore.getInstance(); 16354 if (keyStore != null) { 16355 if (userId == UserHandle.USER_ALL) { 16356 for (final int individual : sUserManager.getUserIds()) { 16357 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16358 } 16359 } else { 16360 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16361 } 16362 } else { 16363 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16364 } 16365 } 16366 16367 @Override 16368 public void deleteApplicationCacheFiles(final String packageName, 16369 final IPackageDataObserver observer) { 16370 final int userId = UserHandle.getCallingUserId(); 16371 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16372 } 16373 16374 @Override 16375 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16376 final IPackageDataObserver observer) { 16377 mContext.enforceCallingOrSelfPermission( 16378 android.Manifest.permission.DELETE_CACHE_FILES, null); 16379 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16380 /* requireFullPermission= */ true, /* checkShell= */ false, 16381 "delete application cache files"); 16382 16383 final PackageParser.Package pkg; 16384 synchronized (mPackages) { 16385 pkg = mPackages.get(packageName); 16386 } 16387 16388 // Queue up an async operation since the package deletion may take a little while. 16389 mHandler.post(new Runnable() { 16390 public void run() { 16391 synchronized (mInstallLock) { 16392 final int flags = StorageManager.FLAG_STORAGE_DE 16393 | StorageManager.FLAG_STORAGE_CE; 16394 // We're only clearing cache files, so we don't care if the 16395 // app is unfrozen and still able to run 16396 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16397 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16398 } 16399 clearExternalStorageDataSync(packageName, userId, false); 16400 if (observer != null) { 16401 try { 16402 observer.onRemoveCompleted(packageName, true); 16403 } catch (RemoteException e) { 16404 Log.i(TAG, "Observer no longer exists."); 16405 } 16406 } 16407 } 16408 }); 16409 } 16410 16411 @Override 16412 public void getPackageSizeInfo(final String packageName, int userHandle, 16413 final IPackageStatsObserver observer) { 16414 mContext.enforceCallingOrSelfPermission( 16415 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16416 if (packageName == null) { 16417 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16418 } 16419 16420 PackageStats stats = new PackageStats(packageName, userHandle); 16421 16422 /* 16423 * Queue up an async operation since the package measurement may take a 16424 * little while. 16425 */ 16426 Message msg = mHandler.obtainMessage(INIT_COPY); 16427 msg.obj = new MeasureParams(stats, observer); 16428 mHandler.sendMessage(msg); 16429 } 16430 16431 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16432 final PackageSetting ps; 16433 synchronized (mPackages) { 16434 ps = mSettings.mPackages.get(packageName); 16435 if (ps == null) { 16436 Slog.w(TAG, "Failed to find settings for " + packageName); 16437 return false; 16438 } 16439 } 16440 try { 16441 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16442 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16443 ps.getCeDataInode(userId), ps.codePathString, stats); 16444 } catch (InstallerException e) { 16445 Slog.w(TAG, String.valueOf(e)); 16446 return false; 16447 } 16448 16449 // For now, ignore code size of packages on system partition 16450 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16451 stats.codeSize = 0; 16452 } 16453 16454 return true; 16455 } 16456 16457 private int getUidTargetSdkVersionLockedLPr(int uid) { 16458 Object obj = mSettings.getUserIdLPr(uid); 16459 if (obj instanceof SharedUserSetting) { 16460 final SharedUserSetting sus = (SharedUserSetting) obj; 16461 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16462 final Iterator<PackageSetting> it = sus.packages.iterator(); 16463 while (it.hasNext()) { 16464 final PackageSetting ps = it.next(); 16465 if (ps.pkg != null) { 16466 int v = ps.pkg.applicationInfo.targetSdkVersion; 16467 if (v < vers) vers = v; 16468 } 16469 } 16470 return vers; 16471 } else if (obj instanceof PackageSetting) { 16472 final PackageSetting ps = (PackageSetting) obj; 16473 if (ps.pkg != null) { 16474 return ps.pkg.applicationInfo.targetSdkVersion; 16475 } 16476 } 16477 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16478 } 16479 16480 @Override 16481 public void addPreferredActivity(IntentFilter filter, int match, 16482 ComponentName[] set, ComponentName activity, int userId) { 16483 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16484 "Adding preferred"); 16485 } 16486 16487 private void addPreferredActivityInternal(IntentFilter filter, int match, 16488 ComponentName[] set, ComponentName activity, boolean always, int userId, 16489 String opname) { 16490 // writer 16491 int callingUid = Binder.getCallingUid(); 16492 enforceCrossUserPermission(callingUid, userId, 16493 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16494 if (filter.countActions() == 0) { 16495 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16496 return; 16497 } 16498 synchronized (mPackages) { 16499 if (mContext.checkCallingOrSelfPermission( 16500 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16501 != PackageManager.PERMISSION_GRANTED) { 16502 if (getUidTargetSdkVersionLockedLPr(callingUid) 16503 < Build.VERSION_CODES.FROYO) { 16504 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16505 + callingUid); 16506 return; 16507 } 16508 mContext.enforceCallingOrSelfPermission( 16509 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16510 } 16511 16512 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16513 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16514 + userId + ":"); 16515 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16516 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16517 scheduleWritePackageRestrictionsLocked(userId); 16518 } 16519 } 16520 16521 @Override 16522 public void replacePreferredActivity(IntentFilter filter, int match, 16523 ComponentName[] set, ComponentName activity, int userId) { 16524 if (filter.countActions() != 1) { 16525 throw new IllegalArgumentException( 16526 "replacePreferredActivity expects filter to have only 1 action."); 16527 } 16528 if (filter.countDataAuthorities() != 0 16529 || filter.countDataPaths() != 0 16530 || filter.countDataSchemes() > 1 16531 || filter.countDataTypes() != 0) { 16532 throw new IllegalArgumentException( 16533 "replacePreferredActivity expects filter to have no data authorities, " + 16534 "paths, or types; and at most one scheme."); 16535 } 16536 16537 final int callingUid = Binder.getCallingUid(); 16538 enforceCrossUserPermission(callingUid, userId, 16539 true /* requireFullPermission */, false /* checkShell */, 16540 "replace preferred activity"); 16541 synchronized (mPackages) { 16542 if (mContext.checkCallingOrSelfPermission( 16543 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16544 != PackageManager.PERMISSION_GRANTED) { 16545 if (getUidTargetSdkVersionLockedLPr(callingUid) 16546 < Build.VERSION_CODES.FROYO) { 16547 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16548 + Binder.getCallingUid()); 16549 return; 16550 } 16551 mContext.enforceCallingOrSelfPermission( 16552 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16553 } 16554 16555 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16556 if (pir != null) { 16557 // Get all of the existing entries that exactly match this filter. 16558 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16559 if (existing != null && existing.size() == 1) { 16560 PreferredActivity cur = existing.get(0); 16561 if (DEBUG_PREFERRED) { 16562 Slog.i(TAG, "Checking replace of preferred:"); 16563 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16564 if (!cur.mPref.mAlways) { 16565 Slog.i(TAG, " -- CUR; not mAlways!"); 16566 } else { 16567 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16568 Slog.i(TAG, " -- CUR: mSet=" 16569 + Arrays.toString(cur.mPref.mSetComponents)); 16570 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16571 Slog.i(TAG, " -- NEW: mMatch=" 16572 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16573 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16574 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16575 } 16576 } 16577 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16578 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16579 && cur.mPref.sameSet(set)) { 16580 // Setting the preferred activity to what it happens to be already 16581 if (DEBUG_PREFERRED) { 16582 Slog.i(TAG, "Replacing with same preferred activity " 16583 + cur.mPref.mShortComponent + " for user " 16584 + userId + ":"); 16585 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16586 } 16587 return; 16588 } 16589 } 16590 16591 if (existing != null) { 16592 if (DEBUG_PREFERRED) { 16593 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16594 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16595 } 16596 for (int i = 0; i < existing.size(); i++) { 16597 PreferredActivity pa = existing.get(i); 16598 if (DEBUG_PREFERRED) { 16599 Slog.i(TAG, "Removing existing preferred activity " 16600 + pa.mPref.mComponent + ":"); 16601 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16602 } 16603 pir.removeFilter(pa); 16604 } 16605 } 16606 } 16607 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16608 "Replacing preferred"); 16609 } 16610 } 16611 16612 @Override 16613 public void clearPackagePreferredActivities(String packageName) { 16614 final int uid = Binder.getCallingUid(); 16615 // writer 16616 synchronized (mPackages) { 16617 PackageParser.Package pkg = mPackages.get(packageName); 16618 if (pkg == null || pkg.applicationInfo.uid != uid) { 16619 if (mContext.checkCallingOrSelfPermission( 16620 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16621 != PackageManager.PERMISSION_GRANTED) { 16622 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16623 < Build.VERSION_CODES.FROYO) { 16624 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16625 + Binder.getCallingUid()); 16626 return; 16627 } 16628 mContext.enforceCallingOrSelfPermission( 16629 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16630 } 16631 } 16632 16633 int user = UserHandle.getCallingUserId(); 16634 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16635 scheduleWritePackageRestrictionsLocked(user); 16636 } 16637 } 16638 } 16639 16640 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16641 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16642 ArrayList<PreferredActivity> removed = null; 16643 boolean changed = false; 16644 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16645 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16646 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16647 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16648 continue; 16649 } 16650 Iterator<PreferredActivity> it = pir.filterIterator(); 16651 while (it.hasNext()) { 16652 PreferredActivity pa = it.next(); 16653 // Mark entry for removal only if it matches the package name 16654 // and the entry is of type "always". 16655 if (packageName == null || 16656 (pa.mPref.mComponent.getPackageName().equals(packageName) 16657 && pa.mPref.mAlways)) { 16658 if (removed == null) { 16659 removed = new ArrayList<PreferredActivity>(); 16660 } 16661 removed.add(pa); 16662 } 16663 } 16664 if (removed != null) { 16665 for (int j=0; j<removed.size(); j++) { 16666 PreferredActivity pa = removed.get(j); 16667 pir.removeFilter(pa); 16668 } 16669 changed = true; 16670 } 16671 } 16672 return changed; 16673 } 16674 16675 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16676 private void clearIntentFilterVerificationsLPw(int userId) { 16677 final int packageCount = mPackages.size(); 16678 for (int i = 0; i < packageCount; i++) { 16679 PackageParser.Package pkg = mPackages.valueAt(i); 16680 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16681 } 16682 } 16683 16684 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16685 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16686 if (userId == UserHandle.USER_ALL) { 16687 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16688 sUserManager.getUserIds())) { 16689 for (int oneUserId : sUserManager.getUserIds()) { 16690 scheduleWritePackageRestrictionsLocked(oneUserId); 16691 } 16692 } 16693 } else { 16694 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16695 scheduleWritePackageRestrictionsLocked(userId); 16696 } 16697 } 16698 } 16699 16700 void clearDefaultBrowserIfNeeded(String packageName) { 16701 for (int oneUserId : sUserManager.getUserIds()) { 16702 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16703 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16704 if (packageName.equals(defaultBrowserPackageName)) { 16705 setDefaultBrowserPackageName(null, oneUserId); 16706 } 16707 } 16708 } 16709 16710 @Override 16711 public void resetApplicationPreferences(int userId) { 16712 mContext.enforceCallingOrSelfPermission( 16713 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16714 final long identity = Binder.clearCallingIdentity(); 16715 // writer 16716 try { 16717 synchronized (mPackages) { 16718 clearPackagePreferredActivitiesLPw(null, userId); 16719 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16720 // TODO: We have to reset the default SMS and Phone. This requires 16721 // significant refactoring to keep all default apps in the package 16722 // manager (cleaner but more work) or have the services provide 16723 // callbacks to the package manager to request a default app reset. 16724 applyFactoryDefaultBrowserLPw(userId); 16725 clearIntentFilterVerificationsLPw(userId); 16726 primeDomainVerificationsLPw(userId); 16727 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16728 scheduleWritePackageRestrictionsLocked(userId); 16729 } 16730 resetNetworkPolicies(userId); 16731 } finally { 16732 Binder.restoreCallingIdentity(identity); 16733 } 16734 } 16735 16736 @Override 16737 public int getPreferredActivities(List<IntentFilter> outFilters, 16738 List<ComponentName> outActivities, String packageName) { 16739 16740 int num = 0; 16741 final int userId = UserHandle.getCallingUserId(); 16742 // reader 16743 synchronized (mPackages) { 16744 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16745 if (pir != null) { 16746 final Iterator<PreferredActivity> it = pir.filterIterator(); 16747 while (it.hasNext()) { 16748 final PreferredActivity pa = it.next(); 16749 if (packageName == null 16750 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16751 && pa.mPref.mAlways)) { 16752 if (outFilters != null) { 16753 outFilters.add(new IntentFilter(pa)); 16754 } 16755 if (outActivities != null) { 16756 outActivities.add(pa.mPref.mComponent); 16757 } 16758 } 16759 } 16760 } 16761 } 16762 16763 return num; 16764 } 16765 16766 @Override 16767 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16768 int userId) { 16769 int callingUid = Binder.getCallingUid(); 16770 if (callingUid != Process.SYSTEM_UID) { 16771 throw new SecurityException( 16772 "addPersistentPreferredActivity can only be run by the system"); 16773 } 16774 if (filter.countActions() == 0) { 16775 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16776 return; 16777 } 16778 synchronized (mPackages) { 16779 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16780 ":"); 16781 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16782 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16783 new PersistentPreferredActivity(filter, activity)); 16784 scheduleWritePackageRestrictionsLocked(userId); 16785 } 16786 } 16787 16788 @Override 16789 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16790 int callingUid = Binder.getCallingUid(); 16791 if (callingUid != Process.SYSTEM_UID) { 16792 throw new SecurityException( 16793 "clearPackagePersistentPreferredActivities can only be run by the system"); 16794 } 16795 ArrayList<PersistentPreferredActivity> removed = null; 16796 boolean changed = false; 16797 synchronized (mPackages) { 16798 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16799 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16800 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16801 .valueAt(i); 16802 if (userId != thisUserId) { 16803 continue; 16804 } 16805 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16806 while (it.hasNext()) { 16807 PersistentPreferredActivity ppa = it.next(); 16808 // Mark entry for removal only if it matches the package name. 16809 if (ppa.mComponent.getPackageName().equals(packageName)) { 16810 if (removed == null) { 16811 removed = new ArrayList<PersistentPreferredActivity>(); 16812 } 16813 removed.add(ppa); 16814 } 16815 } 16816 if (removed != null) { 16817 for (int j=0; j<removed.size(); j++) { 16818 PersistentPreferredActivity ppa = removed.get(j); 16819 ppir.removeFilter(ppa); 16820 } 16821 changed = true; 16822 } 16823 } 16824 16825 if (changed) { 16826 scheduleWritePackageRestrictionsLocked(userId); 16827 } 16828 } 16829 } 16830 16831 /** 16832 * Common machinery for picking apart a restored XML blob and passing 16833 * it to a caller-supplied functor to be applied to the running system. 16834 */ 16835 private void restoreFromXml(XmlPullParser parser, int userId, 16836 String expectedStartTag, BlobXmlRestorer functor) 16837 throws IOException, XmlPullParserException { 16838 int type; 16839 while ((type = parser.next()) != XmlPullParser.START_TAG 16840 && type != XmlPullParser.END_DOCUMENT) { 16841 } 16842 if (type != XmlPullParser.START_TAG) { 16843 // oops didn't find a start tag?! 16844 if (DEBUG_BACKUP) { 16845 Slog.e(TAG, "Didn't find start tag during restore"); 16846 } 16847 return; 16848 } 16849Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16850 // this is supposed to be TAG_PREFERRED_BACKUP 16851 if (!expectedStartTag.equals(parser.getName())) { 16852 if (DEBUG_BACKUP) { 16853 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16854 } 16855 return; 16856 } 16857 16858 // skip interfering stuff, then we're aligned with the backing implementation 16859 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16860Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16861 functor.apply(parser, userId); 16862 } 16863 16864 private interface BlobXmlRestorer { 16865 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16866 } 16867 16868 /** 16869 * Non-Binder method, support for the backup/restore mechanism: write the 16870 * full set of preferred activities in its canonical XML format. Returns the 16871 * XML output as a byte array, or null if there is none. 16872 */ 16873 @Override 16874 public byte[] getPreferredActivityBackup(int userId) { 16875 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16876 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16877 } 16878 16879 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16880 try { 16881 final XmlSerializer serializer = new FastXmlSerializer(); 16882 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16883 serializer.startDocument(null, true); 16884 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16885 16886 synchronized (mPackages) { 16887 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16888 } 16889 16890 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16891 serializer.endDocument(); 16892 serializer.flush(); 16893 } catch (Exception e) { 16894 if (DEBUG_BACKUP) { 16895 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16896 } 16897 return null; 16898 } 16899 16900 return dataStream.toByteArray(); 16901 } 16902 16903 @Override 16904 public void restorePreferredActivities(byte[] backup, int userId) { 16905 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16906 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16907 } 16908 16909 try { 16910 final XmlPullParser parser = Xml.newPullParser(); 16911 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16912 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16913 new BlobXmlRestorer() { 16914 @Override 16915 public void apply(XmlPullParser parser, int userId) 16916 throws XmlPullParserException, IOException { 16917 synchronized (mPackages) { 16918 mSettings.readPreferredActivitiesLPw(parser, userId); 16919 } 16920 } 16921 } ); 16922 } catch (Exception e) { 16923 if (DEBUG_BACKUP) { 16924 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16925 } 16926 } 16927 } 16928 16929 /** 16930 * Non-Binder method, support for the backup/restore mechanism: write the 16931 * default browser (etc) settings in its canonical XML format. Returns the default 16932 * browser XML representation as a byte array, or null if there is none. 16933 */ 16934 @Override 16935 public byte[] getDefaultAppsBackup(int userId) { 16936 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16937 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16938 } 16939 16940 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16941 try { 16942 final XmlSerializer serializer = new FastXmlSerializer(); 16943 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16944 serializer.startDocument(null, true); 16945 serializer.startTag(null, TAG_DEFAULT_APPS); 16946 16947 synchronized (mPackages) { 16948 mSettings.writeDefaultAppsLPr(serializer, userId); 16949 } 16950 16951 serializer.endTag(null, TAG_DEFAULT_APPS); 16952 serializer.endDocument(); 16953 serializer.flush(); 16954 } catch (Exception e) { 16955 if (DEBUG_BACKUP) { 16956 Slog.e(TAG, "Unable to write default apps for backup", e); 16957 } 16958 return null; 16959 } 16960 16961 return dataStream.toByteArray(); 16962 } 16963 16964 @Override 16965 public void restoreDefaultApps(byte[] backup, int userId) { 16966 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16967 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16968 } 16969 16970 try { 16971 final XmlPullParser parser = Xml.newPullParser(); 16972 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16973 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16974 new BlobXmlRestorer() { 16975 @Override 16976 public void apply(XmlPullParser parser, int userId) 16977 throws XmlPullParserException, IOException { 16978 synchronized (mPackages) { 16979 mSettings.readDefaultAppsLPw(parser, userId); 16980 } 16981 } 16982 } ); 16983 } catch (Exception e) { 16984 if (DEBUG_BACKUP) { 16985 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16986 } 16987 } 16988 } 16989 16990 @Override 16991 public byte[] getIntentFilterVerificationBackup(int userId) { 16992 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16993 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16994 } 16995 16996 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16997 try { 16998 final XmlSerializer serializer = new FastXmlSerializer(); 16999 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17000 serializer.startDocument(null, true); 17001 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 17002 17003 synchronized (mPackages) { 17004 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 17005 } 17006 17007 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 17008 serializer.endDocument(); 17009 serializer.flush(); 17010 } catch (Exception e) { 17011 if (DEBUG_BACKUP) { 17012 Slog.e(TAG, "Unable to write default apps for backup", e); 17013 } 17014 return null; 17015 } 17016 17017 return dataStream.toByteArray(); 17018 } 17019 17020 @Override 17021 public void restoreIntentFilterVerification(byte[] backup, int userId) { 17022 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17023 throw new SecurityException("Only the system may call restorePreferredActivities()"); 17024 } 17025 17026 try { 17027 final XmlPullParser parser = Xml.newPullParser(); 17028 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17029 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 17030 new BlobXmlRestorer() { 17031 @Override 17032 public void apply(XmlPullParser parser, int userId) 17033 throws XmlPullParserException, IOException { 17034 synchronized (mPackages) { 17035 mSettings.readAllDomainVerificationsLPr(parser, userId); 17036 mSettings.writeLPr(); 17037 } 17038 } 17039 } ); 17040 } catch (Exception e) { 17041 if (DEBUG_BACKUP) { 17042 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17043 } 17044 } 17045 } 17046 17047 @Override 17048 public byte[] getPermissionGrantBackup(int userId) { 17049 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17050 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 17051 } 17052 17053 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 17054 try { 17055 final XmlSerializer serializer = new FastXmlSerializer(); 17056 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 17057 serializer.startDocument(null, true); 17058 serializer.startTag(null, TAG_PERMISSION_BACKUP); 17059 17060 synchronized (mPackages) { 17061 serializeRuntimePermissionGrantsLPr(serializer, userId); 17062 } 17063 17064 serializer.endTag(null, TAG_PERMISSION_BACKUP); 17065 serializer.endDocument(); 17066 serializer.flush(); 17067 } catch (Exception e) { 17068 if (DEBUG_BACKUP) { 17069 Slog.e(TAG, "Unable to write default apps for backup", e); 17070 } 17071 return null; 17072 } 17073 17074 return dataStream.toByteArray(); 17075 } 17076 17077 @Override 17078 public void restorePermissionGrants(byte[] backup, int userId) { 17079 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 17080 throw new SecurityException("Only the system may call restorePermissionGrants()"); 17081 } 17082 17083 try { 17084 final XmlPullParser parser = Xml.newPullParser(); 17085 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 17086 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 17087 new BlobXmlRestorer() { 17088 @Override 17089 public void apply(XmlPullParser parser, int userId) 17090 throws XmlPullParserException, IOException { 17091 synchronized (mPackages) { 17092 processRestoredPermissionGrantsLPr(parser, userId); 17093 } 17094 } 17095 } ); 17096 } catch (Exception e) { 17097 if (DEBUG_BACKUP) { 17098 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 17099 } 17100 } 17101 } 17102 17103 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 17104 throws IOException { 17105 serializer.startTag(null, TAG_ALL_GRANTS); 17106 17107 final int N = mSettings.mPackages.size(); 17108 for (int i = 0; i < N; i++) { 17109 final PackageSetting ps = mSettings.mPackages.valueAt(i); 17110 boolean pkgGrantsKnown = false; 17111 17112 PermissionsState packagePerms = ps.getPermissionsState(); 17113 17114 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 17115 final int grantFlags = state.getFlags(); 17116 // only look at grants that are not system/policy fixed 17117 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 17118 final boolean isGranted = state.isGranted(); 17119 // And only back up the user-twiddled state bits 17120 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 17121 final String packageName = mSettings.mPackages.keyAt(i); 17122 if (!pkgGrantsKnown) { 17123 serializer.startTag(null, TAG_GRANT); 17124 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 17125 pkgGrantsKnown = true; 17126 } 17127 17128 final boolean userSet = 17129 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 17130 final boolean userFixed = 17131 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 17132 final boolean revoke = 17133 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 17134 17135 serializer.startTag(null, TAG_PERMISSION); 17136 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 17137 if (isGranted) { 17138 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 17139 } 17140 if (userSet) { 17141 serializer.attribute(null, ATTR_USER_SET, "true"); 17142 } 17143 if (userFixed) { 17144 serializer.attribute(null, ATTR_USER_FIXED, "true"); 17145 } 17146 if (revoke) { 17147 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 17148 } 17149 serializer.endTag(null, TAG_PERMISSION); 17150 } 17151 } 17152 } 17153 17154 if (pkgGrantsKnown) { 17155 serializer.endTag(null, TAG_GRANT); 17156 } 17157 } 17158 17159 serializer.endTag(null, TAG_ALL_GRANTS); 17160 } 17161 17162 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 17163 throws XmlPullParserException, IOException { 17164 String pkgName = null; 17165 int outerDepth = parser.getDepth(); 17166 int type; 17167 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 17168 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 17169 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 17170 continue; 17171 } 17172 17173 final String tagName = parser.getName(); 17174 if (tagName.equals(TAG_GRANT)) { 17175 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 17176 if (DEBUG_BACKUP) { 17177 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17178 } 17179 } else if (tagName.equals(TAG_PERMISSION)) { 17180 17181 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17182 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17183 17184 int newFlagSet = 0; 17185 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17186 newFlagSet |= FLAG_PERMISSION_USER_SET; 17187 } 17188 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17189 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17190 } 17191 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17192 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17193 } 17194 if (DEBUG_BACKUP) { 17195 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17196 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17197 } 17198 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17199 if (ps != null) { 17200 // Already installed so we apply the grant immediately 17201 if (DEBUG_BACKUP) { 17202 Slog.v(TAG, " + already installed; applying"); 17203 } 17204 PermissionsState perms = ps.getPermissionsState(); 17205 BasePermission bp = mSettings.mPermissions.get(permName); 17206 if (bp != null) { 17207 if (isGranted) { 17208 perms.grantRuntimePermission(bp, userId); 17209 } 17210 if (newFlagSet != 0) { 17211 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17212 } 17213 } 17214 } else { 17215 // Need to wait for post-restore install to apply the grant 17216 if (DEBUG_BACKUP) { 17217 Slog.v(TAG, " - not yet installed; saving for later"); 17218 } 17219 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17220 isGranted, newFlagSet, userId); 17221 } 17222 } else { 17223 PackageManagerService.reportSettingsProblem(Log.WARN, 17224 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17225 XmlUtils.skipCurrentTag(parser); 17226 } 17227 } 17228 17229 scheduleWriteSettingsLocked(); 17230 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17231 } 17232 17233 @Override 17234 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17235 int sourceUserId, int targetUserId, int flags) { 17236 mContext.enforceCallingOrSelfPermission( 17237 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17238 int callingUid = Binder.getCallingUid(); 17239 enforceOwnerRights(ownerPackage, callingUid); 17240 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17241 if (intentFilter.countActions() == 0) { 17242 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17243 return; 17244 } 17245 synchronized (mPackages) { 17246 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17247 ownerPackage, targetUserId, flags); 17248 CrossProfileIntentResolver resolver = 17249 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17250 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17251 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17252 if (existing != null) { 17253 int size = existing.size(); 17254 for (int i = 0; i < size; i++) { 17255 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17256 return; 17257 } 17258 } 17259 } 17260 resolver.addFilter(newFilter); 17261 scheduleWritePackageRestrictionsLocked(sourceUserId); 17262 } 17263 } 17264 17265 @Override 17266 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17267 mContext.enforceCallingOrSelfPermission( 17268 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17269 int callingUid = Binder.getCallingUid(); 17270 enforceOwnerRights(ownerPackage, callingUid); 17271 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17272 synchronized (mPackages) { 17273 CrossProfileIntentResolver resolver = 17274 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17275 ArraySet<CrossProfileIntentFilter> set = 17276 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17277 for (CrossProfileIntentFilter filter : set) { 17278 if (filter.getOwnerPackage().equals(ownerPackage)) { 17279 resolver.removeFilter(filter); 17280 } 17281 } 17282 scheduleWritePackageRestrictionsLocked(sourceUserId); 17283 } 17284 } 17285 17286 // Enforcing that callingUid is owning pkg on userId 17287 private void enforceOwnerRights(String pkg, int callingUid) { 17288 // The system owns everything. 17289 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17290 return; 17291 } 17292 int callingUserId = UserHandle.getUserId(callingUid); 17293 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17294 if (pi == null) { 17295 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17296 + callingUserId); 17297 } 17298 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17299 throw new SecurityException("Calling uid " + callingUid 17300 + " does not own package " + pkg); 17301 } 17302 } 17303 17304 @Override 17305 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17306 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17307 } 17308 17309 private Intent getHomeIntent() { 17310 Intent intent = new Intent(Intent.ACTION_MAIN); 17311 intent.addCategory(Intent.CATEGORY_HOME); 17312 return intent; 17313 } 17314 17315 private IntentFilter getHomeFilter() { 17316 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17317 filter.addCategory(Intent.CATEGORY_HOME); 17318 filter.addCategory(Intent.CATEGORY_DEFAULT); 17319 return filter; 17320 } 17321 17322 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17323 int userId) { 17324 Intent intent = getHomeIntent(); 17325 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17326 PackageManager.GET_META_DATA, userId); 17327 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17328 true, false, false, userId); 17329 17330 allHomeCandidates.clear(); 17331 if (list != null) { 17332 for (ResolveInfo ri : list) { 17333 allHomeCandidates.add(ri); 17334 } 17335 } 17336 return (preferred == null || preferred.activityInfo == null) 17337 ? null 17338 : new ComponentName(preferred.activityInfo.packageName, 17339 preferred.activityInfo.name); 17340 } 17341 17342 @Override 17343 public void setHomeActivity(ComponentName comp, int userId) { 17344 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17345 getHomeActivitiesAsUser(homeActivities, userId); 17346 17347 boolean found = false; 17348 17349 final int size = homeActivities.size(); 17350 final ComponentName[] set = new ComponentName[size]; 17351 for (int i = 0; i < size; i++) { 17352 final ResolveInfo candidate = homeActivities.get(i); 17353 final ActivityInfo info = candidate.activityInfo; 17354 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17355 set[i] = activityName; 17356 if (!found && activityName.equals(comp)) { 17357 found = true; 17358 } 17359 } 17360 if (!found) { 17361 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17362 + userId); 17363 } 17364 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17365 set, comp, userId); 17366 } 17367 17368 private @Nullable String getSetupWizardPackageName() { 17369 final Intent intent = new Intent(Intent.ACTION_MAIN); 17370 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17371 17372 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17373 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17374 | MATCH_DISABLED_COMPONENTS, 17375 UserHandle.myUserId()); 17376 if (matches.size() == 1) { 17377 return matches.get(0).getComponentInfo().packageName; 17378 } else { 17379 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17380 + ": matches=" + matches); 17381 return null; 17382 } 17383 } 17384 17385 @Override 17386 public void setApplicationEnabledSetting(String appPackageName, 17387 int newState, int flags, int userId, String callingPackage) { 17388 if (!sUserManager.exists(userId)) return; 17389 if (callingPackage == null) { 17390 callingPackage = Integer.toString(Binder.getCallingUid()); 17391 } 17392 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17393 } 17394 17395 @Override 17396 public void setComponentEnabledSetting(ComponentName componentName, 17397 int newState, int flags, int userId) { 17398 if (!sUserManager.exists(userId)) return; 17399 setEnabledSetting(componentName.getPackageName(), 17400 componentName.getClassName(), newState, flags, userId, null); 17401 } 17402 17403 private void setEnabledSetting(final String packageName, String className, int newState, 17404 final int flags, int userId, String callingPackage) { 17405 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17406 || newState == COMPONENT_ENABLED_STATE_ENABLED 17407 || newState == COMPONENT_ENABLED_STATE_DISABLED 17408 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17409 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17410 throw new IllegalArgumentException("Invalid new component state: " 17411 + newState); 17412 } 17413 PackageSetting pkgSetting; 17414 final int uid = Binder.getCallingUid(); 17415 final int permission; 17416 if (uid == Process.SYSTEM_UID) { 17417 permission = PackageManager.PERMISSION_GRANTED; 17418 } else { 17419 permission = mContext.checkCallingOrSelfPermission( 17420 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17421 } 17422 enforceCrossUserPermission(uid, userId, 17423 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17424 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17425 boolean sendNow = false; 17426 boolean isApp = (className == null); 17427 String componentName = isApp ? packageName : className; 17428 int packageUid = -1; 17429 ArrayList<String> components; 17430 17431 // writer 17432 synchronized (mPackages) { 17433 pkgSetting = mSettings.mPackages.get(packageName); 17434 if (pkgSetting == null) { 17435 if (className == null) { 17436 throw new IllegalArgumentException("Unknown package: " + packageName); 17437 } 17438 throw new IllegalArgumentException( 17439 "Unknown component: " + packageName + "/" + className); 17440 } 17441 // Allow root and verify that userId is not being specified by a different user 17442 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17443 throw new SecurityException( 17444 "Permission Denial: attempt to change component state from pid=" 17445 + Binder.getCallingPid() 17446 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17447 } 17448 if (className == null) { 17449 // We're dealing with an application/package level state change 17450 if (pkgSetting.getEnabled(userId) == newState) { 17451 // Nothing to do 17452 return; 17453 } 17454 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17455 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17456 // Don't care about who enables an app. 17457 callingPackage = null; 17458 } 17459 pkgSetting.setEnabled(newState, userId, callingPackage); 17460 // pkgSetting.pkg.mSetEnabled = newState; 17461 } else { 17462 // We're dealing with a component level state change 17463 // First, verify that this is a valid class name. 17464 PackageParser.Package pkg = pkgSetting.pkg; 17465 if (pkg == null || !pkg.hasComponentClassName(className)) { 17466 if (pkg != null && 17467 pkg.applicationInfo.targetSdkVersion >= 17468 Build.VERSION_CODES.JELLY_BEAN) { 17469 throw new IllegalArgumentException("Component class " + className 17470 + " does not exist in " + packageName); 17471 } else { 17472 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17473 + className + " does not exist in " + packageName); 17474 } 17475 } 17476 switch (newState) { 17477 case COMPONENT_ENABLED_STATE_ENABLED: 17478 if (!pkgSetting.enableComponentLPw(className, userId)) { 17479 return; 17480 } 17481 break; 17482 case COMPONENT_ENABLED_STATE_DISABLED: 17483 if (!pkgSetting.disableComponentLPw(className, userId)) { 17484 return; 17485 } 17486 break; 17487 case COMPONENT_ENABLED_STATE_DEFAULT: 17488 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17489 return; 17490 } 17491 break; 17492 default: 17493 Slog.e(TAG, "Invalid new component state: " + newState); 17494 return; 17495 } 17496 } 17497 scheduleWritePackageRestrictionsLocked(userId); 17498 components = mPendingBroadcasts.get(userId, packageName); 17499 final boolean newPackage = components == null; 17500 if (newPackage) { 17501 components = new ArrayList<String>(); 17502 } 17503 if (!components.contains(componentName)) { 17504 components.add(componentName); 17505 } 17506 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17507 sendNow = true; 17508 // Purge entry from pending broadcast list if another one exists already 17509 // since we are sending one right away. 17510 mPendingBroadcasts.remove(userId, packageName); 17511 } else { 17512 if (newPackage) { 17513 mPendingBroadcasts.put(userId, packageName, components); 17514 } 17515 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17516 // Schedule a message 17517 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17518 } 17519 } 17520 } 17521 17522 long callingId = Binder.clearCallingIdentity(); 17523 try { 17524 if (sendNow) { 17525 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17526 sendPackageChangedBroadcast(packageName, 17527 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17528 } 17529 } finally { 17530 Binder.restoreCallingIdentity(callingId); 17531 } 17532 } 17533 17534 @Override 17535 public void flushPackageRestrictionsAsUser(int userId) { 17536 if (!sUserManager.exists(userId)) { 17537 return; 17538 } 17539 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17540 false /* checkShell */, "flushPackageRestrictions"); 17541 synchronized (mPackages) { 17542 mSettings.writePackageRestrictionsLPr(userId); 17543 mDirtyUsers.remove(userId); 17544 if (mDirtyUsers.isEmpty()) { 17545 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17546 } 17547 } 17548 } 17549 17550 private void sendPackageChangedBroadcast(String packageName, 17551 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17552 if (DEBUG_INSTALL) 17553 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17554 + componentNames); 17555 Bundle extras = new Bundle(4); 17556 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17557 String nameList[] = new String[componentNames.size()]; 17558 componentNames.toArray(nameList); 17559 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17560 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17561 extras.putInt(Intent.EXTRA_UID, packageUid); 17562 // If this is not reporting a change of the overall package, then only send it 17563 // to registered receivers. We don't want to launch a swath of apps for every 17564 // little component state change. 17565 final int flags = !componentNames.contains(packageName) 17566 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17567 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17568 new int[] {UserHandle.getUserId(packageUid)}); 17569 } 17570 17571 @Override 17572 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17573 if (!sUserManager.exists(userId)) return; 17574 final int uid = Binder.getCallingUid(); 17575 final int permission = mContext.checkCallingOrSelfPermission( 17576 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17577 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17578 enforceCrossUserPermission(uid, userId, 17579 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17580 // writer 17581 synchronized (mPackages) { 17582 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17583 allowedByPermission, uid, userId)) { 17584 scheduleWritePackageRestrictionsLocked(userId); 17585 } 17586 } 17587 } 17588 17589 @Override 17590 public String getInstallerPackageName(String packageName) { 17591 // reader 17592 synchronized (mPackages) { 17593 return mSettings.getInstallerPackageNameLPr(packageName); 17594 } 17595 } 17596 17597 public boolean isOrphaned(String packageName) { 17598 // reader 17599 synchronized (mPackages) { 17600 return mSettings.isOrphaned(packageName); 17601 } 17602 } 17603 17604 @Override 17605 public int getApplicationEnabledSetting(String packageName, int userId) { 17606 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17607 int uid = Binder.getCallingUid(); 17608 enforceCrossUserPermission(uid, userId, 17609 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17610 // reader 17611 synchronized (mPackages) { 17612 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17613 } 17614 } 17615 17616 @Override 17617 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17618 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17619 int uid = Binder.getCallingUid(); 17620 enforceCrossUserPermission(uid, userId, 17621 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17622 // reader 17623 synchronized (mPackages) { 17624 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17625 } 17626 } 17627 17628 @Override 17629 public void enterSafeMode() { 17630 enforceSystemOrRoot("Only the system can request entering safe mode"); 17631 17632 if (!mSystemReady) { 17633 mSafeMode = true; 17634 } 17635 } 17636 17637 @Override 17638 public void systemReady() { 17639 mSystemReady = true; 17640 17641 // Read the compatibilty setting when the system is ready. 17642 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17643 mContext.getContentResolver(), 17644 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17645 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17646 if (DEBUG_SETTINGS) { 17647 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17648 } 17649 17650 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17651 17652 synchronized (mPackages) { 17653 // Verify that all of the preferred activity components actually 17654 // exist. It is possible for applications to be updated and at 17655 // that point remove a previously declared activity component that 17656 // had been set as a preferred activity. We try to clean this up 17657 // the next time we encounter that preferred activity, but it is 17658 // possible for the user flow to never be able to return to that 17659 // situation so here we do a sanity check to make sure we haven't 17660 // left any junk around. 17661 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17662 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17663 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17664 removed.clear(); 17665 for (PreferredActivity pa : pir.filterSet()) { 17666 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17667 removed.add(pa); 17668 } 17669 } 17670 if (removed.size() > 0) { 17671 for (int r=0; r<removed.size(); r++) { 17672 PreferredActivity pa = removed.get(r); 17673 Slog.w(TAG, "Removing dangling preferred activity: " 17674 + pa.mPref.mComponent); 17675 pir.removeFilter(pa); 17676 } 17677 mSettings.writePackageRestrictionsLPr( 17678 mSettings.mPreferredActivities.keyAt(i)); 17679 } 17680 } 17681 17682 for (int userId : UserManagerService.getInstance().getUserIds()) { 17683 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17684 grantPermissionsUserIds = ArrayUtils.appendInt( 17685 grantPermissionsUserIds, userId); 17686 } 17687 } 17688 } 17689 sUserManager.systemReady(); 17690 17691 // If we upgraded grant all default permissions before kicking off. 17692 for (int userId : grantPermissionsUserIds) { 17693 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17694 } 17695 17696 // Kick off any messages waiting for system ready 17697 if (mPostSystemReadyMessages != null) { 17698 for (Message msg : mPostSystemReadyMessages) { 17699 msg.sendToTarget(); 17700 } 17701 mPostSystemReadyMessages = null; 17702 } 17703 17704 // Watch for external volumes that come and go over time 17705 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17706 storage.registerListener(mStorageListener); 17707 17708 mInstallerService.systemReady(); 17709 mPackageDexOptimizer.systemReady(); 17710 17711 MountServiceInternal mountServiceInternal = LocalServices.getService( 17712 MountServiceInternal.class); 17713 mountServiceInternal.addExternalStoragePolicy( 17714 new MountServiceInternal.ExternalStorageMountPolicy() { 17715 @Override 17716 public int getMountMode(int uid, String packageName) { 17717 if (Process.isIsolated(uid)) { 17718 return Zygote.MOUNT_EXTERNAL_NONE; 17719 } 17720 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17721 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17722 } 17723 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17724 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17725 } 17726 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17727 return Zygote.MOUNT_EXTERNAL_READ; 17728 } 17729 return Zygote.MOUNT_EXTERNAL_WRITE; 17730 } 17731 17732 @Override 17733 public boolean hasExternalStorage(int uid, String packageName) { 17734 return true; 17735 } 17736 }); 17737 17738 // Now that we're mostly running, clean up stale users and apps 17739 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17740 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17741 } 17742 17743 @Override 17744 public boolean isSafeMode() { 17745 return mSafeMode; 17746 } 17747 17748 @Override 17749 public boolean hasSystemUidErrors() { 17750 return mHasSystemUidErrors; 17751 } 17752 17753 static String arrayToString(int[] array) { 17754 StringBuffer buf = new StringBuffer(128); 17755 buf.append('['); 17756 if (array != null) { 17757 for (int i=0; i<array.length; i++) { 17758 if (i > 0) buf.append(", "); 17759 buf.append(array[i]); 17760 } 17761 } 17762 buf.append(']'); 17763 return buf.toString(); 17764 } 17765 17766 static class DumpState { 17767 public static final int DUMP_LIBS = 1 << 0; 17768 public static final int DUMP_FEATURES = 1 << 1; 17769 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17770 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17771 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17772 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17773 public static final int DUMP_PERMISSIONS = 1 << 6; 17774 public static final int DUMP_PACKAGES = 1 << 7; 17775 public static final int DUMP_SHARED_USERS = 1 << 8; 17776 public static final int DUMP_MESSAGES = 1 << 9; 17777 public static final int DUMP_PROVIDERS = 1 << 10; 17778 public static final int DUMP_VERIFIERS = 1 << 11; 17779 public static final int DUMP_PREFERRED = 1 << 12; 17780 public static final int DUMP_PREFERRED_XML = 1 << 13; 17781 public static final int DUMP_KEYSETS = 1 << 14; 17782 public static final int DUMP_VERSION = 1 << 15; 17783 public static final int DUMP_INSTALLS = 1 << 16; 17784 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17785 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17786 public static final int DUMP_FROZEN = 1 << 19; 17787 public static final int DUMP_DEXOPT = 1 << 20; 17788 17789 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17790 17791 private int mTypes; 17792 17793 private int mOptions; 17794 17795 private boolean mTitlePrinted; 17796 17797 private SharedUserSetting mSharedUser; 17798 17799 public boolean isDumping(int type) { 17800 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17801 return true; 17802 } 17803 17804 return (mTypes & type) != 0; 17805 } 17806 17807 public void setDump(int type) { 17808 mTypes |= type; 17809 } 17810 17811 public boolean isOptionEnabled(int option) { 17812 return (mOptions & option) != 0; 17813 } 17814 17815 public void setOptionEnabled(int option) { 17816 mOptions |= option; 17817 } 17818 17819 public boolean onTitlePrinted() { 17820 final boolean printed = mTitlePrinted; 17821 mTitlePrinted = true; 17822 return printed; 17823 } 17824 17825 public boolean getTitlePrinted() { 17826 return mTitlePrinted; 17827 } 17828 17829 public void setTitlePrinted(boolean enabled) { 17830 mTitlePrinted = enabled; 17831 } 17832 17833 public SharedUserSetting getSharedUser() { 17834 return mSharedUser; 17835 } 17836 17837 public void setSharedUser(SharedUserSetting user) { 17838 mSharedUser = user; 17839 } 17840 } 17841 17842 @Override 17843 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17844 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17845 (new PackageManagerShellCommand(this)).exec( 17846 this, in, out, err, args, resultReceiver); 17847 } 17848 17849 @Override 17850 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17851 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17852 != PackageManager.PERMISSION_GRANTED) { 17853 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17854 + Binder.getCallingPid() 17855 + ", uid=" + Binder.getCallingUid() 17856 + " without permission " 17857 + android.Manifest.permission.DUMP); 17858 return; 17859 } 17860 17861 DumpState dumpState = new DumpState(); 17862 boolean fullPreferred = false; 17863 boolean checkin = false; 17864 17865 String packageName = null; 17866 ArraySet<String> permissionNames = null; 17867 17868 int opti = 0; 17869 while (opti < args.length) { 17870 String opt = args[opti]; 17871 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17872 break; 17873 } 17874 opti++; 17875 17876 if ("-a".equals(opt)) { 17877 // Right now we only know how to print all. 17878 } else if ("-h".equals(opt)) { 17879 pw.println("Package manager dump options:"); 17880 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17881 pw.println(" --checkin: dump for a checkin"); 17882 pw.println(" -f: print details of intent filters"); 17883 pw.println(" -h: print this help"); 17884 pw.println(" cmd may be one of:"); 17885 pw.println(" l[ibraries]: list known shared libraries"); 17886 pw.println(" f[eatures]: list device features"); 17887 pw.println(" k[eysets]: print known keysets"); 17888 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17889 pw.println(" perm[issions]: dump permissions"); 17890 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17891 pw.println(" pref[erred]: print preferred package settings"); 17892 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17893 pw.println(" prov[iders]: dump content providers"); 17894 pw.println(" p[ackages]: dump installed packages"); 17895 pw.println(" s[hared-users]: dump shared user IDs"); 17896 pw.println(" m[essages]: print collected runtime messages"); 17897 pw.println(" v[erifiers]: print package verifier info"); 17898 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17899 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17900 pw.println(" version: print database version info"); 17901 pw.println(" write: write current settings now"); 17902 pw.println(" installs: details about install sessions"); 17903 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17904 pw.println(" dexopt: dump dexopt state"); 17905 pw.println(" <package.name>: info about given package"); 17906 return; 17907 } else if ("--checkin".equals(opt)) { 17908 checkin = true; 17909 } else if ("-f".equals(opt)) { 17910 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17911 } else { 17912 pw.println("Unknown argument: " + opt + "; use -h for help"); 17913 } 17914 } 17915 17916 // Is the caller requesting to dump a particular piece of data? 17917 if (opti < args.length) { 17918 String cmd = args[opti]; 17919 opti++; 17920 // Is this a package name? 17921 if ("android".equals(cmd) || cmd.contains(".")) { 17922 packageName = cmd; 17923 // When dumping a single package, we always dump all of its 17924 // filter information since the amount of data will be reasonable. 17925 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17926 } else if ("check-permission".equals(cmd)) { 17927 if (opti >= args.length) { 17928 pw.println("Error: check-permission missing permission argument"); 17929 return; 17930 } 17931 String perm = args[opti]; 17932 opti++; 17933 if (opti >= args.length) { 17934 pw.println("Error: check-permission missing package argument"); 17935 return; 17936 } 17937 String pkg = args[opti]; 17938 opti++; 17939 int user = UserHandle.getUserId(Binder.getCallingUid()); 17940 if (opti < args.length) { 17941 try { 17942 user = Integer.parseInt(args[opti]); 17943 } catch (NumberFormatException e) { 17944 pw.println("Error: check-permission user argument is not a number: " 17945 + args[opti]); 17946 return; 17947 } 17948 } 17949 pw.println(checkPermission(perm, pkg, user)); 17950 return; 17951 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17952 dumpState.setDump(DumpState.DUMP_LIBS); 17953 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17954 dumpState.setDump(DumpState.DUMP_FEATURES); 17955 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17956 if (opti >= args.length) { 17957 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17958 | DumpState.DUMP_SERVICE_RESOLVERS 17959 | DumpState.DUMP_RECEIVER_RESOLVERS 17960 | DumpState.DUMP_CONTENT_RESOLVERS); 17961 } else { 17962 while (opti < args.length) { 17963 String name = args[opti]; 17964 if ("a".equals(name) || "activity".equals(name)) { 17965 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17966 } else if ("s".equals(name) || "service".equals(name)) { 17967 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17968 } else if ("r".equals(name) || "receiver".equals(name)) { 17969 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17970 } else if ("c".equals(name) || "content".equals(name)) { 17971 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17972 } else { 17973 pw.println("Error: unknown resolver table type: " + name); 17974 return; 17975 } 17976 opti++; 17977 } 17978 } 17979 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17980 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17981 } else if ("permission".equals(cmd)) { 17982 if (opti >= args.length) { 17983 pw.println("Error: permission requires permission name"); 17984 return; 17985 } 17986 permissionNames = new ArraySet<>(); 17987 while (opti < args.length) { 17988 permissionNames.add(args[opti]); 17989 opti++; 17990 } 17991 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17992 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17993 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17994 dumpState.setDump(DumpState.DUMP_PREFERRED); 17995 } else if ("preferred-xml".equals(cmd)) { 17996 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17997 if (opti < args.length && "--full".equals(args[opti])) { 17998 fullPreferred = true; 17999 opti++; 18000 } 18001 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 18002 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 18003 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 18004 dumpState.setDump(DumpState.DUMP_PACKAGES); 18005 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 18006 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 18007 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 18008 dumpState.setDump(DumpState.DUMP_PROVIDERS); 18009 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 18010 dumpState.setDump(DumpState.DUMP_MESSAGES); 18011 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 18012 dumpState.setDump(DumpState.DUMP_VERIFIERS); 18013 } else if ("i".equals(cmd) || "ifv".equals(cmd) 18014 || "intent-filter-verifiers".equals(cmd)) { 18015 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 18016 } else if ("version".equals(cmd)) { 18017 dumpState.setDump(DumpState.DUMP_VERSION); 18018 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 18019 dumpState.setDump(DumpState.DUMP_KEYSETS); 18020 } else if ("installs".equals(cmd)) { 18021 dumpState.setDump(DumpState.DUMP_INSTALLS); 18022 } else if ("frozen".equals(cmd)) { 18023 dumpState.setDump(DumpState.DUMP_FROZEN); 18024 } else if ("dexopt".equals(cmd)) { 18025 dumpState.setDump(DumpState.DUMP_DEXOPT); 18026 } else if ("write".equals(cmd)) { 18027 synchronized (mPackages) { 18028 mSettings.writeLPr(); 18029 pw.println("Settings written."); 18030 return; 18031 } 18032 } 18033 } 18034 18035 if (checkin) { 18036 pw.println("vers,1"); 18037 } 18038 18039 // reader 18040 synchronized (mPackages) { 18041 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 18042 if (!checkin) { 18043 if (dumpState.onTitlePrinted()) 18044 pw.println(); 18045 pw.println("Database versions:"); 18046 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 18047 } 18048 } 18049 18050 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 18051 if (!checkin) { 18052 if (dumpState.onTitlePrinted()) 18053 pw.println(); 18054 pw.println("Verifiers:"); 18055 pw.print(" Required: "); 18056 pw.print(mRequiredVerifierPackage); 18057 pw.print(" (uid="); 18058 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18059 UserHandle.USER_SYSTEM)); 18060 pw.println(")"); 18061 } else if (mRequiredVerifierPackage != null) { 18062 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 18063 pw.print(","); 18064 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 18065 UserHandle.USER_SYSTEM)); 18066 } 18067 } 18068 18069 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 18070 packageName == null) { 18071 if (mIntentFilterVerifierComponent != null) { 18072 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 18073 if (!checkin) { 18074 if (dumpState.onTitlePrinted()) 18075 pw.println(); 18076 pw.println("Intent Filter Verifier:"); 18077 pw.print(" Using: "); 18078 pw.print(verifierPackageName); 18079 pw.print(" (uid="); 18080 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18081 UserHandle.USER_SYSTEM)); 18082 pw.println(")"); 18083 } else if (verifierPackageName != null) { 18084 pw.print("ifv,"); pw.print(verifierPackageName); 18085 pw.print(","); 18086 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 18087 UserHandle.USER_SYSTEM)); 18088 } 18089 } else { 18090 pw.println(); 18091 pw.println("No Intent Filter Verifier available!"); 18092 } 18093 } 18094 18095 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 18096 boolean printedHeader = false; 18097 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 18098 while (it.hasNext()) { 18099 String name = it.next(); 18100 SharedLibraryEntry ent = mSharedLibraries.get(name); 18101 if (!checkin) { 18102 if (!printedHeader) { 18103 if (dumpState.onTitlePrinted()) 18104 pw.println(); 18105 pw.println("Libraries:"); 18106 printedHeader = true; 18107 } 18108 pw.print(" "); 18109 } else { 18110 pw.print("lib,"); 18111 } 18112 pw.print(name); 18113 if (!checkin) { 18114 pw.print(" -> "); 18115 } 18116 if (ent.path != null) { 18117 if (!checkin) { 18118 pw.print("(jar) "); 18119 pw.print(ent.path); 18120 } else { 18121 pw.print(",jar,"); 18122 pw.print(ent.path); 18123 } 18124 } else { 18125 if (!checkin) { 18126 pw.print("(apk) "); 18127 pw.print(ent.apk); 18128 } else { 18129 pw.print(",apk,"); 18130 pw.print(ent.apk); 18131 } 18132 } 18133 pw.println(); 18134 } 18135 } 18136 18137 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 18138 if (dumpState.onTitlePrinted()) 18139 pw.println(); 18140 if (!checkin) { 18141 pw.println("Features:"); 18142 } 18143 18144 for (FeatureInfo feat : mAvailableFeatures.values()) { 18145 if (checkin) { 18146 pw.print("feat,"); 18147 pw.print(feat.name); 18148 pw.print(","); 18149 pw.println(feat.version); 18150 } else { 18151 pw.print(" "); 18152 pw.print(feat.name); 18153 if (feat.version > 0) { 18154 pw.print(" version="); 18155 pw.print(feat.version); 18156 } 18157 pw.println(); 18158 } 18159 } 18160 } 18161 18162 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 18163 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 18164 : "Activity Resolver Table:", " ", packageName, 18165 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18166 dumpState.setTitlePrinted(true); 18167 } 18168 } 18169 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 18170 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 18171 : "Receiver Resolver Table:", " ", packageName, 18172 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18173 dumpState.setTitlePrinted(true); 18174 } 18175 } 18176 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 18177 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 18178 : "Service Resolver Table:", " ", packageName, 18179 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18180 dumpState.setTitlePrinted(true); 18181 } 18182 } 18183 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 18184 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 18185 : "Provider Resolver Table:", " ", packageName, 18186 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 18187 dumpState.setTitlePrinted(true); 18188 } 18189 } 18190 18191 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18192 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18193 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18194 int user = mSettings.mPreferredActivities.keyAt(i); 18195 if (pir.dump(pw, 18196 dumpState.getTitlePrinted() 18197 ? "\nPreferred Activities User " + user + ":" 18198 : "Preferred Activities User " + user + ":", " ", 18199 packageName, true, false)) { 18200 dumpState.setTitlePrinted(true); 18201 } 18202 } 18203 } 18204 18205 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18206 pw.flush(); 18207 FileOutputStream fout = new FileOutputStream(fd); 18208 BufferedOutputStream str = new BufferedOutputStream(fout); 18209 XmlSerializer serializer = new FastXmlSerializer(); 18210 try { 18211 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18212 serializer.startDocument(null, true); 18213 serializer.setFeature( 18214 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18215 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18216 serializer.endDocument(); 18217 serializer.flush(); 18218 } catch (IllegalArgumentException e) { 18219 pw.println("Failed writing: " + e); 18220 } catch (IllegalStateException e) { 18221 pw.println("Failed writing: " + e); 18222 } catch (IOException e) { 18223 pw.println("Failed writing: " + e); 18224 } 18225 } 18226 18227 if (!checkin 18228 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18229 && packageName == null) { 18230 pw.println(); 18231 int count = mSettings.mPackages.size(); 18232 if (count == 0) { 18233 pw.println("No applications!"); 18234 pw.println(); 18235 } else { 18236 final String prefix = " "; 18237 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18238 if (allPackageSettings.size() == 0) { 18239 pw.println("No domain preferred apps!"); 18240 pw.println(); 18241 } else { 18242 pw.println("App verification status:"); 18243 pw.println(); 18244 count = 0; 18245 for (PackageSetting ps : allPackageSettings) { 18246 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18247 if (ivi == null || ivi.getPackageName() == null) continue; 18248 pw.println(prefix + "Package: " + ivi.getPackageName()); 18249 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18250 pw.println(prefix + "Status: " + ivi.getStatusString()); 18251 pw.println(); 18252 count++; 18253 } 18254 if (count == 0) { 18255 pw.println(prefix + "No app verification established."); 18256 pw.println(); 18257 } 18258 for (int userId : sUserManager.getUserIds()) { 18259 pw.println("App linkages for user " + userId + ":"); 18260 pw.println(); 18261 count = 0; 18262 for (PackageSetting ps : allPackageSettings) { 18263 final long status = ps.getDomainVerificationStatusForUser(userId); 18264 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18265 continue; 18266 } 18267 pw.println(prefix + "Package: " + ps.name); 18268 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18269 String statusStr = IntentFilterVerificationInfo. 18270 getStatusStringFromValue(status); 18271 pw.println(prefix + "Status: " + statusStr); 18272 pw.println(); 18273 count++; 18274 } 18275 if (count == 0) { 18276 pw.println(prefix + "No configured app linkages."); 18277 pw.println(); 18278 } 18279 } 18280 } 18281 } 18282 } 18283 18284 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18285 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18286 if (packageName == null && permissionNames == null) { 18287 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18288 if (iperm == 0) { 18289 if (dumpState.onTitlePrinted()) 18290 pw.println(); 18291 pw.println("AppOp Permissions:"); 18292 } 18293 pw.print(" AppOp Permission "); 18294 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18295 pw.println(":"); 18296 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18297 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18298 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18299 } 18300 } 18301 } 18302 } 18303 18304 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18305 boolean printedSomething = false; 18306 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18307 if (packageName != null && !packageName.equals(p.info.packageName)) { 18308 continue; 18309 } 18310 if (!printedSomething) { 18311 if (dumpState.onTitlePrinted()) 18312 pw.println(); 18313 pw.println("Registered ContentProviders:"); 18314 printedSomething = true; 18315 } 18316 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18317 pw.print(" "); pw.println(p.toString()); 18318 } 18319 printedSomething = false; 18320 for (Map.Entry<String, PackageParser.Provider> entry : 18321 mProvidersByAuthority.entrySet()) { 18322 PackageParser.Provider p = entry.getValue(); 18323 if (packageName != null && !packageName.equals(p.info.packageName)) { 18324 continue; 18325 } 18326 if (!printedSomething) { 18327 if (dumpState.onTitlePrinted()) 18328 pw.println(); 18329 pw.println("ContentProvider Authorities:"); 18330 printedSomething = true; 18331 } 18332 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18333 pw.print(" "); pw.println(p.toString()); 18334 if (p.info != null && p.info.applicationInfo != null) { 18335 final String appInfo = p.info.applicationInfo.toString(); 18336 pw.print(" applicationInfo="); pw.println(appInfo); 18337 } 18338 } 18339 } 18340 18341 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18342 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18343 } 18344 18345 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18346 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18347 } 18348 18349 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18350 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18351 } 18352 18353 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18354 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18355 } 18356 18357 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18358 // XXX should handle packageName != null by dumping only install data that 18359 // the given package is involved with. 18360 if (dumpState.onTitlePrinted()) pw.println(); 18361 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18362 } 18363 18364 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18365 // XXX should handle packageName != null by dumping only install data that 18366 // the given package is involved with. 18367 if (dumpState.onTitlePrinted()) pw.println(); 18368 18369 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18370 ipw.println(); 18371 ipw.println("Frozen packages:"); 18372 ipw.increaseIndent(); 18373 if (mFrozenPackages.size() == 0) { 18374 ipw.println("(none)"); 18375 } else { 18376 for (int i = 0; i < mFrozenPackages.size(); i++) { 18377 ipw.println(mFrozenPackages.valueAt(i)); 18378 } 18379 } 18380 ipw.decreaseIndent(); 18381 } 18382 18383 if (!checkin && dumpState.isDumping(DumpState.DUMP_DEXOPT)) { 18384 if (dumpState.onTitlePrinted()) pw.println(); 18385 dumpDexoptStateLPr(pw, packageName); 18386 } 18387 18388 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18389 if (dumpState.onTitlePrinted()) pw.println(); 18390 mSettings.dumpReadMessagesLPr(pw, dumpState); 18391 18392 pw.println(); 18393 pw.println("Package warning messages:"); 18394 BufferedReader in = null; 18395 String line = null; 18396 try { 18397 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18398 while ((line = in.readLine()) != null) { 18399 if (line.contains("ignored: updated version")) continue; 18400 pw.println(line); 18401 } 18402 } catch (IOException ignored) { 18403 } finally { 18404 IoUtils.closeQuietly(in); 18405 } 18406 } 18407 18408 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18409 BufferedReader in = null; 18410 String line = null; 18411 try { 18412 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18413 while ((line = in.readLine()) != null) { 18414 if (line.contains("ignored: updated version")) continue; 18415 pw.print("msg,"); 18416 pw.println(line); 18417 } 18418 } catch (IOException ignored) { 18419 } finally { 18420 IoUtils.closeQuietly(in); 18421 } 18422 } 18423 } 18424 } 18425 18426 private void dumpDexoptStateLPr(PrintWriter pw, String packageName) { 18427 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18428 ipw.println(); 18429 ipw.println("Dexopt state:"); 18430 ipw.increaseIndent(); 18431 Collection<PackageParser.Package> packages = null; 18432 if (packageName != null) { 18433 PackageParser.Package targetPackage = mPackages.get(packageName); 18434 if (targetPackage != null) { 18435 packages = Collections.singletonList(targetPackage); 18436 } else { 18437 ipw.println("Unable to find package: " + packageName); 18438 return; 18439 } 18440 } else { 18441 packages = mPackages.values(); 18442 } 18443 18444 for (PackageParser.Package pkg : packages) { 18445 ipw.println("[" + pkg.packageName + "]"); 18446 ipw.increaseIndent(); 18447 mPackageDexOptimizer.dumpDexoptState(ipw, pkg); 18448 ipw.decreaseIndent(); 18449 } 18450 } 18451 18452 private String dumpDomainString(String packageName) { 18453 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18454 .getList(); 18455 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18456 18457 ArraySet<String> result = new ArraySet<>(); 18458 if (iviList.size() > 0) { 18459 for (IntentFilterVerificationInfo ivi : iviList) { 18460 for (String host : ivi.getDomains()) { 18461 result.add(host); 18462 } 18463 } 18464 } 18465 if (filters != null && filters.size() > 0) { 18466 for (IntentFilter filter : filters) { 18467 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18468 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18469 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18470 result.addAll(filter.getHostsList()); 18471 } 18472 } 18473 } 18474 18475 StringBuilder sb = new StringBuilder(result.size() * 16); 18476 for (String domain : result) { 18477 if (sb.length() > 0) sb.append(" "); 18478 sb.append(domain); 18479 } 18480 return sb.toString(); 18481 } 18482 18483 // ------- apps on sdcard specific code ------- 18484 static final boolean DEBUG_SD_INSTALL = false; 18485 18486 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18487 18488 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18489 18490 private boolean mMediaMounted = false; 18491 18492 static String getEncryptKey() { 18493 try { 18494 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18495 SD_ENCRYPTION_KEYSTORE_NAME); 18496 if (sdEncKey == null) { 18497 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18498 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18499 if (sdEncKey == null) { 18500 Slog.e(TAG, "Failed to create encryption keys"); 18501 return null; 18502 } 18503 } 18504 return sdEncKey; 18505 } catch (NoSuchAlgorithmException nsae) { 18506 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18507 return null; 18508 } catch (IOException ioe) { 18509 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18510 return null; 18511 } 18512 } 18513 18514 /* 18515 * Update media status on PackageManager. 18516 */ 18517 @Override 18518 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18519 int callingUid = Binder.getCallingUid(); 18520 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18521 throw new SecurityException("Media status can only be updated by the system"); 18522 } 18523 // reader; this apparently protects mMediaMounted, but should probably 18524 // be a different lock in that case. 18525 synchronized (mPackages) { 18526 Log.i(TAG, "Updating external media status from " 18527 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18528 + (mediaStatus ? "mounted" : "unmounted")); 18529 if (DEBUG_SD_INSTALL) 18530 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18531 + ", mMediaMounted=" + mMediaMounted); 18532 if (mediaStatus == mMediaMounted) { 18533 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18534 : 0, -1); 18535 mHandler.sendMessage(msg); 18536 return; 18537 } 18538 mMediaMounted = mediaStatus; 18539 } 18540 // Queue up an async operation since the package installation may take a 18541 // little while. 18542 mHandler.post(new Runnable() { 18543 public void run() { 18544 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18545 } 18546 }); 18547 } 18548 18549 /** 18550 * Called by MountService when the initial ASECs to scan are available. 18551 * Should block until all the ASEC containers are finished being scanned. 18552 */ 18553 public void scanAvailableAsecs() { 18554 updateExternalMediaStatusInner(true, false, false); 18555 } 18556 18557 /* 18558 * Collect information of applications on external media, map them against 18559 * existing containers and update information based on current mount status. 18560 * Please note that we always have to report status if reportStatus has been 18561 * set to true especially when unloading packages. 18562 */ 18563 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18564 boolean externalStorage) { 18565 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18566 int[] uidArr = EmptyArray.INT; 18567 18568 final String[] list = PackageHelper.getSecureContainerList(); 18569 if (ArrayUtils.isEmpty(list)) { 18570 Log.i(TAG, "No secure containers found"); 18571 } else { 18572 // Process list of secure containers and categorize them 18573 // as active or stale based on their package internal state. 18574 18575 // reader 18576 synchronized (mPackages) { 18577 for (String cid : list) { 18578 // Leave stages untouched for now; installer service owns them 18579 if (PackageInstallerService.isStageName(cid)) continue; 18580 18581 if (DEBUG_SD_INSTALL) 18582 Log.i(TAG, "Processing container " + cid); 18583 String pkgName = getAsecPackageName(cid); 18584 if (pkgName == null) { 18585 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18586 continue; 18587 } 18588 if (DEBUG_SD_INSTALL) 18589 Log.i(TAG, "Looking for pkg : " + pkgName); 18590 18591 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18592 if (ps == null) { 18593 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18594 continue; 18595 } 18596 18597 /* 18598 * Skip packages that are not external if we're unmounting 18599 * external storage. 18600 */ 18601 if (externalStorage && !isMounted && !isExternal(ps)) { 18602 continue; 18603 } 18604 18605 final AsecInstallArgs args = new AsecInstallArgs(cid, 18606 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18607 // The package status is changed only if the code path 18608 // matches between settings and the container id. 18609 if (ps.codePathString != null 18610 && ps.codePathString.startsWith(args.getCodePath())) { 18611 if (DEBUG_SD_INSTALL) { 18612 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18613 + " at code path: " + ps.codePathString); 18614 } 18615 18616 // We do have a valid package installed on sdcard 18617 processCids.put(args, ps.codePathString); 18618 final int uid = ps.appId; 18619 if (uid != -1) { 18620 uidArr = ArrayUtils.appendInt(uidArr, uid); 18621 } 18622 } else { 18623 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18624 + ps.codePathString); 18625 } 18626 } 18627 } 18628 18629 Arrays.sort(uidArr); 18630 } 18631 18632 // Process packages with valid entries. 18633 if (isMounted) { 18634 if (DEBUG_SD_INSTALL) 18635 Log.i(TAG, "Loading packages"); 18636 loadMediaPackages(processCids, uidArr, externalStorage); 18637 startCleaningPackages(); 18638 mInstallerService.onSecureContainersAvailable(); 18639 } else { 18640 if (DEBUG_SD_INSTALL) 18641 Log.i(TAG, "Unloading packages"); 18642 unloadMediaPackages(processCids, uidArr, reportStatus); 18643 } 18644 } 18645 18646 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18647 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18648 final int size = infos.size(); 18649 final String[] packageNames = new String[size]; 18650 final int[] packageUids = new int[size]; 18651 for (int i = 0; i < size; i++) { 18652 final ApplicationInfo info = infos.get(i); 18653 packageNames[i] = info.packageName; 18654 packageUids[i] = info.uid; 18655 } 18656 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18657 finishedReceiver); 18658 } 18659 18660 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18661 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18662 sendResourcesChangedBroadcast(mediaStatus, replacing, 18663 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18664 } 18665 18666 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18667 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18668 int size = pkgList.length; 18669 if (size > 0) { 18670 // Send broadcasts here 18671 Bundle extras = new Bundle(); 18672 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18673 if (uidArr != null) { 18674 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18675 } 18676 if (replacing) { 18677 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18678 } 18679 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18680 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18681 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18682 } 18683 } 18684 18685 /* 18686 * Look at potentially valid container ids from processCids If package 18687 * information doesn't match the one on record or package scanning fails, 18688 * the cid is added to list of removeCids. We currently don't delete stale 18689 * containers. 18690 */ 18691 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18692 boolean externalStorage) { 18693 ArrayList<String> pkgList = new ArrayList<String>(); 18694 Set<AsecInstallArgs> keys = processCids.keySet(); 18695 18696 for (AsecInstallArgs args : keys) { 18697 String codePath = processCids.get(args); 18698 if (DEBUG_SD_INSTALL) 18699 Log.i(TAG, "Loading container : " + args.cid); 18700 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18701 try { 18702 // Make sure there are no container errors first. 18703 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18704 Slog.e(TAG, "Failed to mount cid : " + args.cid 18705 + " when installing from sdcard"); 18706 continue; 18707 } 18708 // Check code path here. 18709 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18710 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18711 + " does not match one in settings " + codePath); 18712 continue; 18713 } 18714 // Parse package 18715 int parseFlags = mDefParseFlags; 18716 if (args.isExternalAsec()) { 18717 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18718 } 18719 if (args.isFwdLocked()) { 18720 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18721 } 18722 18723 synchronized (mInstallLock) { 18724 PackageParser.Package pkg = null; 18725 try { 18726 // Sadly we don't know the package name yet to freeze it 18727 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18728 SCAN_IGNORE_FROZEN, 0, null); 18729 } catch (PackageManagerException e) { 18730 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18731 } 18732 // Scan the package 18733 if (pkg != null) { 18734 /* 18735 * TODO why is the lock being held? doPostInstall is 18736 * called in other places without the lock. This needs 18737 * to be straightened out. 18738 */ 18739 // writer 18740 synchronized (mPackages) { 18741 retCode = PackageManager.INSTALL_SUCCEEDED; 18742 pkgList.add(pkg.packageName); 18743 // Post process args 18744 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18745 pkg.applicationInfo.uid); 18746 } 18747 } else { 18748 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18749 } 18750 } 18751 18752 } finally { 18753 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18754 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18755 } 18756 } 18757 } 18758 // writer 18759 synchronized (mPackages) { 18760 // If the platform SDK has changed since the last time we booted, 18761 // we need to re-grant app permission to catch any new ones that 18762 // appear. This is really a hack, and means that apps can in some 18763 // cases get permissions that the user didn't initially explicitly 18764 // allow... it would be nice to have some better way to handle 18765 // this situation. 18766 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18767 : mSettings.getInternalVersion(); 18768 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18769 : StorageManager.UUID_PRIVATE_INTERNAL; 18770 18771 int updateFlags = UPDATE_PERMISSIONS_ALL; 18772 if (ver.sdkVersion != mSdkVersion) { 18773 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18774 + mSdkVersion + "; regranting permissions for external"); 18775 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18776 } 18777 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18778 18779 // Yay, everything is now upgraded 18780 ver.forceCurrent(); 18781 18782 // can downgrade to reader 18783 // Persist settings 18784 mSettings.writeLPr(); 18785 } 18786 // Send a broadcast to let everyone know we are done processing 18787 if (pkgList.size() > 0) { 18788 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18789 } 18790 } 18791 18792 /* 18793 * Utility method to unload a list of specified containers 18794 */ 18795 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18796 // Just unmount all valid containers. 18797 for (AsecInstallArgs arg : cidArgs) { 18798 synchronized (mInstallLock) { 18799 arg.doPostDeleteLI(false); 18800 } 18801 } 18802 } 18803 18804 /* 18805 * Unload packages mounted on external media. This involves deleting package 18806 * data from internal structures, sending broadcasts about disabled packages, 18807 * gc'ing to free up references, unmounting all secure containers 18808 * corresponding to packages on external media, and posting a 18809 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18810 * that we always have to post this message if status has been requested no 18811 * matter what. 18812 */ 18813 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18814 final boolean reportStatus) { 18815 if (DEBUG_SD_INSTALL) 18816 Log.i(TAG, "unloading media packages"); 18817 ArrayList<String> pkgList = new ArrayList<String>(); 18818 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18819 final Set<AsecInstallArgs> keys = processCids.keySet(); 18820 for (AsecInstallArgs args : keys) { 18821 String pkgName = args.getPackageName(); 18822 if (DEBUG_SD_INSTALL) 18823 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18824 // Delete package internally 18825 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18826 synchronized (mInstallLock) { 18827 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18828 final boolean res; 18829 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18830 "unloadMediaPackages")) { 18831 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18832 null); 18833 } 18834 if (res) { 18835 pkgList.add(pkgName); 18836 } else { 18837 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18838 failedList.add(args); 18839 } 18840 } 18841 } 18842 18843 // reader 18844 synchronized (mPackages) { 18845 // We didn't update the settings after removing each package; 18846 // write them now for all packages. 18847 mSettings.writeLPr(); 18848 } 18849 18850 // We have to absolutely send UPDATED_MEDIA_STATUS only 18851 // after confirming that all the receivers processed the ordered 18852 // broadcast when packages get disabled, force a gc to clean things up. 18853 // and unload all the containers. 18854 if (pkgList.size() > 0) { 18855 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18856 new IIntentReceiver.Stub() { 18857 public void performReceive(Intent intent, int resultCode, String data, 18858 Bundle extras, boolean ordered, boolean sticky, 18859 int sendingUser) throws RemoteException { 18860 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18861 reportStatus ? 1 : 0, 1, keys); 18862 mHandler.sendMessage(msg); 18863 } 18864 }); 18865 } else { 18866 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18867 keys); 18868 mHandler.sendMessage(msg); 18869 } 18870 } 18871 18872 private void loadPrivatePackages(final VolumeInfo vol) { 18873 mHandler.post(new Runnable() { 18874 @Override 18875 public void run() { 18876 loadPrivatePackagesInner(vol); 18877 } 18878 }); 18879 } 18880 18881 private void loadPrivatePackagesInner(VolumeInfo vol) { 18882 final String volumeUuid = vol.fsUuid; 18883 if (TextUtils.isEmpty(volumeUuid)) { 18884 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18885 return; 18886 } 18887 18888 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18889 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18890 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18891 18892 final VersionInfo ver; 18893 final List<PackageSetting> packages; 18894 synchronized (mPackages) { 18895 ver = mSettings.findOrCreateVersion(volumeUuid); 18896 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18897 } 18898 18899 for (PackageSetting ps : packages) { 18900 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18901 synchronized (mInstallLock) { 18902 final PackageParser.Package pkg; 18903 try { 18904 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18905 loaded.add(pkg.applicationInfo); 18906 18907 } catch (PackageManagerException e) { 18908 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18909 } 18910 18911 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18912 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18913 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18914 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18915 } 18916 } 18917 } 18918 18919 // Reconcile app data for all started/unlocked users 18920 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18921 final UserManager um = mContext.getSystemService(UserManager.class); 18922 for (UserInfo user : um.getUsers()) { 18923 final int flags; 18924 if (um.isUserUnlockingOrUnlocked(user.id)) { 18925 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18926 } else if (um.isUserRunning(user.id)) { 18927 flags = StorageManager.FLAG_STORAGE_DE; 18928 } else { 18929 continue; 18930 } 18931 18932 try { 18933 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18934 synchronized (mInstallLock) { 18935 reconcileAppsDataLI(volumeUuid, user.id, flags); 18936 } 18937 } catch (IllegalStateException e) { 18938 // Device was probably ejected, and we'll process that event momentarily 18939 Slog.w(TAG, "Failed to prepare storage: " + e); 18940 } 18941 } 18942 18943 synchronized (mPackages) { 18944 int updateFlags = UPDATE_PERMISSIONS_ALL; 18945 if (ver.sdkVersion != mSdkVersion) { 18946 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18947 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18948 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18949 } 18950 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18951 18952 // Yay, everything is now upgraded 18953 ver.forceCurrent(); 18954 18955 mSettings.writeLPr(); 18956 } 18957 18958 for (PackageFreezer freezer : freezers) { 18959 freezer.close(); 18960 } 18961 18962 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18963 sendResourcesChangedBroadcast(true, false, loaded, null); 18964 } 18965 18966 private void unloadPrivatePackages(final VolumeInfo vol) { 18967 mHandler.post(new Runnable() { 18968 @Override 18969 public void run() { 18970 unloadPrivatePackagesInner(vol); 18971 } 18972 }); 18973 } 18974 18975 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18976 final String volumeUuid = vol.fsUuid; 18977 if (TextUtils.isEmpty(volumeUuid)) { 18978 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18979 return; 18980 } 18981 18982 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18983 synchronized (mInstallLock) { 18984 synchronized (mPackages) { 18985 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18986 for (PackageSetting ps : packages) { 18987 if (ps.pkg == null) continue; 18988 18989 final ApplicationInfo info = ps.pkg.applicationInfo; 18990 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18991 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18992 18993 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18994 "unloadPrivatePackagesInner")) { 18995 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18996 false, null)) { 18997 unloaded.add(info); 18998 } else { 18999 Slog.w(TAG, "Failed to unload " + ps.codePath); 19000 } 19001 } 19002 } 19003 19004 mSettings.writeLPr(); 19005 } 19006 } 19007 19008 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 19009 sendResourcesChangedBroadcast(false, false, unloaded, null); 19010 } 19011 19012 /** 19013 * Prepare storage areas for given user on all mounted devices. 19014 */ 19015 void prepareUserData(int userId, int userSerial, int flags) { 19016 synchronized (mInstallLock) { 19017 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19018 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19019 final String volumeUuid = vol.getFsUuid(); 19020 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 19021 } 19022 } 19023 } 19024 19025 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 19026 boolean allowRecover) { 19027 // Prepare storage and verify that serial numbers are consistent; if 19028 // there's a mismatch we need to destroy to avoid leaking data 19029 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19030 try { 19031 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 19032 19033 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 19034 UserManagerService.enforceSerialNumber( 19035 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 19036 } 19037 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 19038 UserManagerService.enforceSerialNumber( 19039 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 19040 } 19041 19042 synchronized (mInstallLock) { 19043 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 19044 } 19045 } catch (Exception e) { 19046 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 19047 + " because we failed to prepare: " + e); 19048 destroyUserDataLI(volumeUuid, userId, 19049 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19050 19051 if (allowRecover) { 19052 // Try one last time; if we fail again we're really in trouble 19053 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 19054 } 19055 } 19056 } 19057 19058 /** 19059 * Destroy storage areas for given user on all mounted devices. 19060 */ 19061 void destroyUserData(int userId, int flags) { 19062 synchronized (mInstallLock) { 19063 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19064 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19065 final String volumeUuid = vol.getFsUuid(); 19066 destroyUserDataLI(volumeUuid, userId, flags); 19067 } 19068 } 19069 } 19070 19071 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 19072 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19073 try { 19074 // Clean up app data, profile data, and media data 19075 mInstaller.destroyUserData(volumeUuid, userId, flags); 19076 19077 // Clean up system data 19078 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 19079 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19080 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 19081 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 19082 } 19083 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19084 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 19085 } 19086 } 19087 19088 // Data with special labels is now gone, so finish the job 19089 storage.destroyUserStorage(volumeUuid, userId, flags); 19090 19091 } catch (Exception e) { 19092 logCriticalInfo(Log.WARN, 19093 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 19094 } 19095 } 19096 19097 /** 19098 * Examine all users present on given mounted volume, and destroy data 19099 * belonging to users that are no longer valid, or whose user ID has been 19100 * recycled. 19101 */ 19102 private void reconcileUsers(String volumeUuid) { 19103 final List<File> files = new ArrayList<>(); 19104 Collections.addAll(files, FileUtils 19105 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 19106 Collections.addAll(files, FileUtils 19107 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 19108 for (File file : files) { 19109 if (!file.isDirectory()) continue; 19110 19111 final int userId; 19112 final UserInfo info; 19113 try { 19114 userId = Integer.parseInt(file.getName()); 19115 info = sUserManager.getUserInfo(userId); 19116 } catch (NumberFormatException e) { 19117 Slog.w(TAG, "Invalid user directory " + file); 19118 continue; 19119 } 19120 19121 boolean destroyUser = false; 19122 if (info == null) { 19123 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19124 + " because no matching user was found"); 19125 destroyUser = true; 19126 } else if (!mOnlyCore) { 19127 try { 19128 UserManagerService.enforceSerialNumber(file, info.serialNumber); 19129 } catch (IOException e) { 19130 logCriticalInfo(Log.WARN, "Destroying user directory " + file 19131 + " because we failed to enforce serial number: " + e); 19132 destroyUser = true; 19133 } 19134 } 19135 19136 if (destroyUser) { 19137 synchronized (mInstallLock) { 19138 destroyUserDataLI(volumeUuid, userId, 19139 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 19140 } 19141 } 19142 } 19143 } 19144 19145 private void assertPackageKnown(String volumeUuid, String packageName) 19146 throws PackageManagerException { 19147 synchronized (mPackages) { 19148 final PackageSetting ps = mSettings.mPackages.get(packageName); 19149 if (ps == null) { 19150 throw new PackageManagerException("Package " + packageName + " is unknown"); 19151 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19152 throw new PackageManagerException( 19153 "Package " + packageName + " found on unknown volume " + volumeUuid 19154 + "; expected volume " + ps.volumeUuid); 19155 } 19156 } 19157 } 19158 19159 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 19160 throws PackageManagerException { 19161 synchronized (mPackages) { 19162 final PackageSetting ps = mSettings.mPackages.get(packageName); 19163 if (ps == null) { 19164 throw new PackageManagerException("Package " + packageName + " is unknown"); 19165 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 19166 throw new PackageManagerException( 19167 "Package " + packageName + " found on unknown volume " + volumeUuid 19168 + "; expected volume " + ps.volumeUuid); 19169 } else if (!ps.getInstalled(userId)) { 19170 throw new PackageManagerException( 19171 "Package " + packageName + " not installed for user " + userId); 19172 } 19173 } 19174 } 19175 19176 /** 19177 * Examine all apps present on given mounted volume, and destroy apps that 19178 * aren't expected, either due to uninstallation or reinstallation on 19179 * another volume. 19180 */ 19181 private void reconcileApps(String volumeUuid) { 19182 final File[] files = FileUtils 19183 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 19184 for (File file : files) { 19185 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 19186 && !PackageInstallerService.isStageName(file.getName()); 19187 if (!isPackage) { 19188 // Ignore entries which are not packages 19189 continue; 19190 } 19191 19192 try { 19193 final PackageLite pkg = PackageParser.parsePackageLite(file, 19194 PackageParser.PARSE_MUST_BE_APK); 19195 assertPackageKnown(volumeUuid, pkg.packageName); 19196 19197 } catch (PackageParserException | PackageManagerException e) { 19198 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19199 synchronized (mInstallLock) { 19200 removeCodePathLI(file); 19201 } 19202 } 19203 } 19204 } 19205 19206 /** 19207 * Reconcile all app data for the given user. 19208 * <p> 19209 * Verifies that directories exist and that ownership and labeling is 19210 * correct for all installed apps on all mounted volumes. 19211 */ 19212 void reconcileAppsData(int userId, int flags) { 19213 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19214 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19215 final String volumeUuid = vol.getFsUuid(); 19216 synchronized (mInstallLock) { 19217 reconcileAppsDataLI(volumeUuid, userId, flags); 19218 } 19219 } 19220 } 19221 19222 /** 19223 * Reconcile all app data on given mounted volume. 19224 * <p> 19225 * Destroys app data that isn't expected, either due to uninstallation or 19226 * reinstallation on another volume. 19227 * <p> 19228 * Verifies that directories exist and that ownership and labeling is 19229 * correct for all installed apps. 19230 */ 19231 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19232 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19233 + Integer.toHexString(flags)); 19234 19235 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19236 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19237 19238 boolean restoreconNeeded = false; 19239 19240 // First look for stale data that doesn't belong, and check if things 19241 // have changed since we did our last restorecon 19242 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19243 if (StorageManager.isFileEncryptedNativeOrEmulated() 19244 && !StorageManager.isUserKeyUnlocked(userId)) { 19245 throw new RuntimeException( 19246 "Yikes, someone asked us to reconcile CE storage while " + userId 19247 + " was still locked; this would have caused massive data loss!"); 19248 } 19249 19250 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19251 19252 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19253 for (File file : files) { 19254 final String packageName = file.getName(); 19255 try { 19256 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19257 } catch (PackageManagerException e) { 19258 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19259 try { 19260 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19261 StorageManager.FLAG_STORAGE_CE, 0); 19262 } catch (InstallerException e2) { 19263 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19264 } 19265 } 19266 } 19267 } 19268 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19269 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19270 19271 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19272 for (File file : files) { 19273 final String packageName = file.getName(); 19274 try { 19275 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19276 } catch (PackageManagerException e) { 19277 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19278 try { 19279 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19280 StorageManager.FLAG_STORAGE_DE, 0); 19281 } catch (InstallerException e2) { 19282 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19283 } 19284 } 19285 } 19286 } 19287 19288 // Ensure that data directories are ready to roll for all packages 19289 // installed for this volume and user 19290 final List<PackageSetting> packages; 19291 synchronized (mPackages) { 19292 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19293 } 19294 int preparedCount = 0; 19295 for (PackageSetting ps : packages) { 19296 final String packageName = ps.name; 19297 if (ps.pkg == null) { 19298 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19299 // TODO: might be due to legacy ASEC apps; we should circle back 19300 // and reconcile again once they're scanned 19301 continue; 19302 } 19303 19304 if (ps.getInstalled(userId)) { 19305 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19306 19307 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19308 // We may have just shuffled around app data directories, so 19309 // prepare them one more time 19310 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19311 } 19312 19313 preparedCount++; 19314 } 19315 } 19316 19317 if (restoreconNeeded) { 19318 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19319 SELinuxMMAC.setRestoreconDone(ceDir); 19320 } 19321 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19322 SELinuxMMAC.setRestoreconDone(deDir); 19323 } 19324 } 19325 19326 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19327 + " packages; restoreconNeeded was " + restoreconNeeded); 19328 } 19329 19330 /** 19331 * Prepare app data for the given app just after it was installed or 19332 * upgraded. This method carefully only touches users that it's installed 19333 * for, and it forces a restorecon to handle any seinfo changes. 19334 * <p> 19335 * Verifies that directories exist and that ownership and labeling is 19336 * correct for all installed apps. If there is an ownership mismatch, it 19337 * will try recovering system apps by wiping data; third-party app data is 19338 * left intact. 19339 * <p> 19340 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19341 */ 19342 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19343 final PackageSetting ps; 19344 synchronized (mPackages) { 19345 ps = mSettings.mPackages.get(pkg.packageName); 19346 mSettings.writeKernelMappingLPr(ps); 19347 } 19348 19349 final UserManager um = mContext.getSystemService(UserManager.class); 19350 for (UserInfo user : um.getUsers()) { 19351 final int flags; 19352 if (um.isUserUnlockingOrUnlocked(user.id)) { 19353 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19354 } else if (um.isUserRunning(user.id)) { 19355 flags = StorageManager.FLAG_STORAGE_DE; 19356 } else { 19357 continue; 19358 } 19359 19360 if (ps.getInstalled(user.id)) { 19361 // Whenever an app changes, force a restorecon of its data 19362 // TODO: when user data is locked, mark that we're still dirty 19363 prepareAppDataLIF(pkg, user.id, flags, true); 19364 } 19365 } 19366 } 19367 19368 /** 19369 * Prepare app data for the given app. 19370 * <p> 19371 * Verifies that directories exist and that ownership and labeling is 19372 * correct for all installed apps. If there is an ownership mismatch, this 19373 * will try recovering system apps by wiping data; third-party app data is 19374 * left intact. 19375 */ 19376 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19377 boolean restoreconNeeded) { 19378 if (pkg == null) { 19379 Slog.wtf(TAG, "Package was null!", new Throwable()); 19380 return; 19381 } 19382 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19383 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19384 for (int i = 0; i < childCount; i++) { 19385 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19386 } 19387 } 19388 19389 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19390 boolean restoreconNeeded) { 19391 if (DEBUG_APP_DATA) { 19392 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19393 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19394 } 19395 19396 final String volumeUuid = pkg.volumeUuid; 19397 final String packageName = pkg.packageName; 19398 final ApplicationInfo app = pkg.applicationInfo; 19399 final int appId = UserHandle.getAppId(app.uid); 19400 19401 Preconditions.checkNotNull(app.seinfo); 19402 19403 try { 19404 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19405 appId, app.seinfo, app.targetSdkVersion); 19406 } catch (InstallerException e) { 19407 if (app.isSystemApp()) { 19408 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19409 + ", but trying to recover: " + e); 19410 destroyAppDataLeafLIF(pkg, userId, flags); 19411 try { 19412 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19413 appId, app.seinfo, app.targetSdkVersion); 19414 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19415 } catch (InstallerException e2) { 19416 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19417 } 19418 } else { 19419 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19420 } 19421 } 19422 19423 if (restoreconNeeded) { 19424 try { 19425 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19426 app.seinfo); 19427 } catch (InstallerException e) { 19428 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19429 } 19430 } 19431 19432 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19433 try { 19434 // CE storage is unlocked right now, so read out the inode and 19435 // remember for use later when it's locked 19436 // TODO: mark this structure as dirty so we persist it! 19437 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19438 StorageManager.FLAG_STORAGE_CE); 19439 synchronized (mPackages) { 19440 final PackageSetting ps = mSettings.mPackages.get(packageName); 19441 if (ps != null) { 19442 ps.setCeDataInode(ceDataInode, userId); 19443 } 19444 } 19445 } catch (InstallerException e) { 19446 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19447 } 19448 } 19449 19450 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19451 } 19452 19453 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19454 if (pkg == null) { 19455 Slog.wtf(TAG, "Package was null!", new Throwable()); 19456 return; 19457 } 19458 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19459 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19460 for (int i = 0; i < childCount; i++) { 19461 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19462 } 19463 } 19464 19465 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19466 final String volumeUuid = pkg.volumeUuid; 19467 final String packageName = pkg.packageName; 19468 final ApplicationInfo app = pkg.applicationInfo; 19469 19470 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19471 // Create a native library symlink only if we have native libraries 19472 // and if the native libraries are 32 bit libraries. We do not provide 19473 // this symlink for 64 bit libraries. 19474 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19475 final String nativeLibPath = app.nativeLibraryDir; 19476 try { 19477 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19478 nativeLibPath, userId); 19479 } catch (InstallerException e) { 19480 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19481 } 19482 } 19483 } 19484 } 19485 19486 /** 19487 * For system apps on non-FBE devices, this method migrates any existing 19488 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19489 * requested by the app. 19490 */ 19491 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19492 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19493 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19494 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19495 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19496 try { 19497 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19498 storageTarget); 19499 } catch (InstallerException e) { 19500 logCriticalInfo(Log.WARN, 19501 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19502 } 19503 return true; 19504 } else { 19505 return false; 19506 } 19507 } 19508 19509 public PackageFreezer freezePackage(String packageName, String killReason) { 19510 return new PackageFreezer(packageName, killReason); 19511 } 19512 19513 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19514 String killReason) { 19515 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19516 return new PackageFreezer(); 19517 } else { 19518 return freezePackage(packageName, killReason); 19519 } 19520 } 19521 19522 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19523 String killReason) { 19524 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19525 return new PackageFreezer(); 19526 } else { 19527 return freezePackage(packageName, killReason); 19528 } 19529 } 19530 19531 /** 19532 * Class that freezes and kills the given package upon creation, and 19533 * unfreezes it upon closing. This is typically used when doing surgery on 19534 * app code/data to prevent the app from running while you're working. 19535 */ 19536 private class PackageFreezer implements AutoCloseable { 19537 private final String mPackageName; 19538 private final PackageFreezer[] mChildren; 19539 19540 private final boolean mWeFroze; 19541 19542 private final AtomicBoolean mClosed = new AtomicBoolean(); 19543 private final CloseGuard mCloseGuard = CloseGuard.get(); 19544 19545 /** 19546 * Create and return a stub freezer that doesn't actually do anything, 19547 * typically used when someone requested 19548 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19549 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19550 */ 19551 public PackageFreezer() { 19552 mPackageName = null; 19553 mChildren = null; 19554 mWeFroze = false; 19555 mCloseGuard.open("close"); 19556 } 19557 19558 public PackageFreezer(String packageName, String killReason) { 19559 synchronized (mPackages) { 19560 mPackageName = packageName; 19561 mWeFroze = mFrozenPackages.add(mPackageName); 19562 19563 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19564 if (ps != null) { 19565 killApplication(ps.name, ps.appId, killReason); 19566 } 19567 19568 final PackageParser.Package p = mPackages.get(packageName); 19569 if (p != null && p.childPackages != null) { 19570 final int N = p.childPackages.size(); 19571 mChildren = new PackageFreezer[N]; 19572 for (int i = 0; i < N; i++) { 19573 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19574 killReason); 19575 } 19576 } else { 19577 mChildren = null; 19578 } 19579 } 19580 mCloseGuard.open("close"); 19581 } 19582 19583 @Override 19584 protected void finalize() throws Throwable { 19585 try { 19586 mCloseGuard.warnIfOpen(); 19587 close(); 19588 } finally { 19589 super.finalize(); 19590 } 19591 } 19592 19593 @Override 19594 public void close() { 19595 mCloseGuard.close(); 19596 if (mClosed.compareAndSet(false, true)) { 19597 synchronized (mPackages) { 19598 if (mWeFroze) { 19599 mFrozenPackages.remove(mPackageName); 19600 } 19601 19602 if (mChildren != null) { 19603 for (PackageFreezer freezer : mChildren) { 19604 freezer.close(); 19605 } 19606 } 19607 } 19608 } 19609 } 19610 } 19611 19612 /** 19613 * Verify that given package is currently frozen. 19614 */ 19615 private void checkPackageFrozen(String packageName) { 19616 synchronized (mPackages) { 19617 if (!mFrozenPackages.contains(packageName)) { 19618 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19619 } 19620 } 19621 } 19622 19623 @Override 19624 public int movePackage(final String packageName, final String volumeUuid) { 19625 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19626 19627 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19628 final int moveId = mNextMoveId.getAndIncrement(); 19629 mHandler.post(new Runnable() { 19630 @Override 19631 public void run() { 19632 try { 19633 movePackageInternal(packageName, volumeUuid, moveId, user); 19634 } catch (PackageManagerException e) { 19635 Slog.w(TAG, "Failed to move " + packageName, e); 19636 mMoveCallbacks.notifyStatusChanged(moveId, 19637 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19638 } 19639 } 19640 }); 19641 return moveId; 19642 } 19643 19644 private void movePackageInternal(final String packageName, final String volumeUuid, 19645 final int moveId, UserHandle user) throws PackageManagerException { 19646 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19647 final PackageManager pm = mContext.getPackageManager(); 19648 19649 final boolean currentAsec; 19650 final String currentVolumeUuid; 19651 final File codeFile; 19652 final String installerPackageName; 19653 final String packageAbiOverride; 19654 final int appId; 19655 final String seinfo; 19656 final String label; 19657 final int targetSdkVersion; 19658 final PackageFreezer freezer; 19659 final int[] installedUserIds; 19660 19661 // reader 19662 synchronized (mPackages) { 19663 final PackageParser.Package pkg = mPackages.get(packageName); 19664 final PackageSetting ps = mSettings.mPackages.get(packageName); 19665 if (pkg == null || ps == null) { 19666 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19667 } 19668 19669 if (pkg.applicationInfo.isSystemApp()) { 19670 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19671 "Cannot move system application"); 19672 } 19673 19674 if (pkg.applicationInfo.isExternalAsec()) { 19675 currentAsec = true; 19676 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19677 } else if (pkg.applicationInfo.isForwardLocked()) { 19678 currentAsec = true; 19679 currentVolumeUuid = "forward_locked"; 19680 } else { 19681 currentAsec = false; 19682 currentVolumeUuid = ps.volumeUuid; 19683 19684 final File probe = new File(pkg.codePath); 19685 final File probeOat = new File(probe, "oat"); 19686 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19687 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19688 "Move only supported for modern cluster style installs"); 19689 } 19690 } 19691 19692 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19693 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19694 "Package already moved to " + volumeUuid); 19695 } 19696 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19697 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19698 "Device admin cannot be moved"); 19699 } 19700 19701 if (mFrozenPackages.contains(packageName)) { 19702 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19703 "Failed to move already frozen package"); 19704 } 19705 19706 codeFile = new File(pkg.codePath); 19707 installerPackageName = ps.installerPackageName; 19708 packageAbiOverride = ps.cpuAbiOverrideString; 19709 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19710 seinfo = pkg.applicationInfo.seinfo; 19711 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19712 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19713 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19714 installedUserIds = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 19715 } 19716 19717 final Bundle extras = new Bundle(); 19718 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19719 extras.putString(Intent.EXTRA_TITLE, label); 19720 mMoveCallbacks.notifyCreated(moveId, extras); 19721 19722 int installFlags; 19723 final boolean moveCompleteApp; 19724 final File measurePath; 19725 19726 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19727 installFlags = INSTALL_INTERNAL; 19728 moveCompleteApp = !currentAsec; 19729 measurePath = Environment.getDataAppDirectory(volumeUuid); 19730 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19731 installFlags = INSTALL_EXTERNAL; 19732 moveCompleteApp = false; 19733 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19734 } else { 19735 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19736 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19737 || !volume.isMountedWritable()) { 19738 freezer.close(); 19739 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19740 "Move location not mounted private volume"); 19741 } 19742 19743 Preconditions.checkState(!currentAsec); 19744 19745 installFlags = INSTALL_INTERNAL; 19746 moveCompleteApp = true; 19747 measurePath = Environment.getDataAppDirectory(volumeUuid); 19748 } 19749 19750 final PackageStats stats = new PackageStats(null, -1); 19751 synchronized (mInstaller) { 19752 for (int userId : installedUserIds) { 19753 if (!getPackageSizeInfoLI(packageName, userId, stats)) { 19754 freezer.close(); 19755 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19756 "Failed to measure package size"); 19757 } 19758 } 19759 } 19760 19761 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19762 + stats.dataSize); 19763 19764 final long startFreeBytes = measurePath.getFreeSpace(); 19765 final long sizeBytes; 19766 if (moveCompleteApp) { 19767 sizeBytes = stats.codeSize + stats.dataSize; 19768 } else { 19769 sizeBytes = stats.codeSize; 19770 } 19771 19772 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19773 freezer.close(); 19774 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19775 "Not enough free space to move"); 19776 } 19777 19778 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19779 19780 final CountDownLatch installedLatch = new CountDownLatch(1); 19781 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19782 @Override 19783 public void onUserActionRequired(Intent intent) throws RemoteException { 19784 throw new IllegalStateException(); 19785 } 19786 19787 @Override 19788 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19789 Bundle extras) throws RemoteException { 19790 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19791 + PackageManager.installStatusToString(returnCode, msg)); 19792 19793 installedLatch.countDown(); 19794 freezer.close(); 19795 19796 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19797 switch (status) { 19798 case PackageInstaller.STATUS_SUCCESS: 19799 mMoveCallbacks.notifyStatusChanged(moveId, 19800 PackageManager.MOVE_SUCCEEDED); 19801 break; 19802 case PackageInstaller.STATUS_FAILURE_STORAGE: 19803 mMoveCallbacks.notifyStatusChanged(moveId, 19804 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19805 break; 19806 default: 19807 mMoveCallbacks.notifyStatusChanged(moveId, 19808 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19809 break; 19810 } 19811 } 19812 }; 19813 19814 final MoveInfo move; 19815 if (moveCompleteApp) { 19816 // Kick off a thread to report progress estimates 19817 new Thread() { 19818 @Override 19819 public void run() { 19820 while (true) { 19821 try { 19822 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19823 break; 19824 } 19825 } catch (InterruptedException ignored) { 19826 } 19827 19828 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19829 final int progress = 10 + (int) MathUtils.constrain( 19830 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19831 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19832 } 19833 } 19834 }.start(); 19835 19836 final String dataAppName = codeFile.getName(); 19837 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19838 dataAppName, appId, seinfo, targetSdkVersion); 19839 } else { 19840 move = null; 19841 } 19842 19843 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19844 19845 final Message msg = mHandler.obtainMessage(INIT_COPY); 19846 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19847 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19848 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19849 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19850 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19851 msg.obj = params; 19852 19853 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19854 System.identityHashCode(msg.obj)); 19855 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19856 System.identityHashCode(msg.obj)); 19857 19858 mHandler.sendMessage(msg); 19859 } 19860 19861 @Override 19862 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19863 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19864 19865 final int realMoveId = mNextMoveId.getAndIncrement(); 19866 final Bundle extras = new Bundle(); 19867 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19868 mMoveCallbacks.notifyCreated(realMoveId, extras); 19869 19870 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19871 @Override 19872 public void onCreated(int moveId, Bundle extras) { 19873 // Ignored 19874 } 19875 19876 @Override 19877 public void onStatusChanged(int moveId, int status, long estMillis) { 19878 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19879 } 19880 }; 19881 19882 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19883 storage.setPrimaryStorageUuid(volumeUuid, callback); 19884 return realMoveId; 19885 } 19886 19887 @Override 19888 public int getMoveStatus(int moveId) { 19889 mContext.enforceCallingOrSelfPermission( 19890 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19891 return mMoveCallbacks.mLastStatus.get(moveId); 19892 } 19893 19894 @Override 19895 public void registerMoveCallback(IPackageMoveObserver callback) { 19896 mContext.enforceCallingOrSelfPermission( 19897 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19898 mMoveCallbacks.register(callback); 19899 } 19900 19901 @Override 19902 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19903 mContext.enforceCallingOrSelfPermission( 19904 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19905 mMoveCallbacks.unregister(callback); 19906 } 19907 19908 @Override 19909 public boolean setInstallLocation(int loc) { 19910 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19911 null); 19912 if (getInstallLocation() == loc) { 19913 return true; 19914 } 19915 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19916 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19917 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19918 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19919 return true; 19920 } 19921 return false; 19922 } 19923 19924 @Override 19925 public int getInstallLocation() { 19926 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19927 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19928 PackageHelper.APP_INSTALL_AUTO); 19929 } 19930 19931 /** Called by UserManagerService */ 19932 void cleanUpUser(UserManagerService userManager, int userHandle) { 19933 synchronized (mPackages) { 19934 mDirtyUsers.remove(userHandle); 19935 mUserNeedsBadging.delete(userHandle); 19936 mSettings.removeUserLPw(userHandle); 19937 mPendingBroadcasts.remove(userHandle); 19938 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19939 removeUnusedPackagesLPw(userManager, userHandle); 19940 } 19941 } 19942 19943 /** 19944 * We're removing userHandle and would like to remove any downloaded packages 19945 * that are no longer in use by any other user. 19946 * @param userHandle the user being removed 19947 */ 19948 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19949 final boolean DEBUG_CLEAN_APKS = false; 19950 int [] users = userManager.getUserIds(); 19951 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19952 while (psit.hasNext()) { 19953 PackageSetting ps = psit.next(); 19954 if (ps.pkg == null) { 19955 continue; 19956 } 19957 final String packageName = ps.pkg.packageName; 19958 // Skip over if system app 19959 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19960 continue; 19961 } 19962 if (DEBUG_CLEAN_APKS) { 19963 Slog.i(TAG, "Checking package " + packageName); 19964 } 19965 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19966 if (keep) { 19967 if (DEBUG_CLEAN_APKS) { 19968 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19969 } 19970 } else { 19971 for (int i = 0; i < users.length; i++) { 19972 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19973 keep = true; 19974 if (DEBUG_CLEAN_APKS) { 19975 Slog.i(TAG, " Keeping package " + packageName + " for user " 19976 + users[i]); 19977 } 19978 break; 19979 } 19980 } 19981 } 19982 if (!keep) { 19983 if (DEBUG_CLEAN_APKS) { 19984 Slog.i(TAG, " Removing package " + packageName); 19985 } 19986 mHandler.post(new Runnable() { 19987 public void run() { 19988 deletePackageX(packageName, userHandle, 0); 19989 } //end run 19990 }); 19991 } 19992 } 19993 } 19994 19995 /** Called by UserManagerService */ 19996 void createNewUser(int userHandle) { 19997 synchronized (mInstallLock) { 19998 mSettings.createNewUserLI(this, mInstaller, userHandle); 19999 } 20000 synchronized (mPackages) { 20001 applyFactoryDefaultBrowserLPw(userHandle); 20002 primeDomainVerificationsLPw(userHandle); 20003 } 20004 } 20005 20006 void newUserCreated(final int userHandle) { 20007 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 20008 // If permission review for legacy apps is required, we represent 20009 // dagerous permissions for such apps as always granted runtime 20010 // permissions to keep per user flag state whether review is needed. 20011 // Hence, if a new user is added we have to propagate dangerous 20012 // permission grants for these legacy apps. 20013 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 20014 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 20015 | UPDATE_PERMISSIONS_REPLACE_ALL); 20016 } 20017 } 20018 20019 @Override 20020 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 20021 mContext.enforceCallingOrSelfPermission( 20022 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 20023 "Only package verification agents can read the verifier device identity"); 20024 20025 synchronized (mPackages) { 20026 return mSettings.getVerifierDeviceIdentityLPw(); 20027 } 20028 } 20029 20030 @Override 20031 public void setPermissionEnforced(String permission, boolean enforced) { 20032 // TODO: Now that we no longer change GID for storage, this should to away. 20033 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 20034 "setPermissionEnforced"); 20035 if (READ_EXTERNAL_STORAGE.equals(permission)) { 20036 synchronized (mPackages) { 20037 if (mSettings.mReadExternalStorageEnforced == null 20038 || mSettings.mReadExternalStorageEnforced != enforced) { 20039 mSettings.mReadExternalStorageEnforced = enforced; 20040 mSettings.writeLPr(); 20041 } 20042 } 20043 // kill any non-foreground processes so we restart them and 20044 // grant/revoke the GID. 20045 final IActivityManager am = ActivityManagerNative.getDefault(); 20046 if (am != null) { 20047 final long token = Binder.clearCallingIdentity(); 20048 try { 20049 am.killProcessesBelowForeground("setPermissionEnforcement"); 20050 } catch (RemoteException e) { 20051 } finally { 20052 Binder.restoreCallingIdentity(token); 20053 } 20054 } 20055 } else { 20056 throw new IllegalArgumentException("No selective enforcement for " + permission); 20057 } 20058 } 20059 20060 @Override 20061 @Deprecated 20062 public boolean isPermissionEnforced(String permission) { 20063 return true; 20064 } 20065 20066 @Override 20067 public boolean isStorageLow() { 20068 final long token = Binder.clearCallingIdentity(); 20069 try { 20070 final DeviceStorageMonitorInternal 20071 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 20072 if (dsm != null) { 20073 return dsm.isMemoryLow(); 20074 } else { 20075 return false; 20076 } 20077 } finally { 20078 Binder.restoreCallingIdentity(token); 20079 } 20080 } 20081 20082 @Override 20083 public IPackageInstaller getPackageInstaller() { 20084 return mInstallerService; 20085 } 20086 20087 private boolean userNeedsBadging(int userId) { 20088 int index = mUserNeedsBadging.indexOfKey(userId); 20089 if (index < 0) { 20090 final UserInfo userInfo; 20091 final long token = Binder.clearCallingIdentity(); 20092 try { 20093 userInfo = sUserManager.getUserInfo(userId); 20094 } finally { 20095 Binder.restoreCallingIdentity(token); 20096 } 20097 final boolean b; 20098 if (userInfo != null && userInfo.isManagedProfile()) { 20099 b = true; 20100 } else { 20101 b = false; 20102 } 20103 mUserNeedsBadging.put(userId, b); 20104 return b; 20105 } 20106 return mUserNeedsBadging.valueAt(index); 20107 } 20108 20109 @Override 20110 public KeySet getKeySetByAlias(String packageName, String alias) { 20111 if (packageName == null || alias == null) { 20112 return null; 20113 } 20114 synchronized(mPackages) { 20115 final PackageParser.Package pkg = mPackages.get(packageName); 20116 if (pkg == null) { 20117 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20118 throw new IllegalArgumentException("Unknown package: " + packageName); 20119 } 20120 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20121 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 20122 } 20123 } 20124 20125 @Override 20126 public KeySet getSigningKeySet(String packageName) { 20127 if (packageName == null) { 20128 return null; 20129 } 20130 synchronized(mPackages) { 20131 final PackageParser.Package pkg = mPackages.get(packageName); 20132 if (pkg == null) { 20133 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20134 throw new IllegalArgumentException("Unknown package: " + packageName); 20135 } 20136 if (pkg.applicationInfo.uid != Binder.getCallingUid() 20137 && Process.SYSTEM_UID != Binder.getCallingUid()) { 20138 throw new SecurityException("May not access signing KeySet of other apps."); 20139 } 20140 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20141 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 20142 } 20143 } 20144 20145 @Override 20146 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 20147 if (packageName == null || ks == null) { 20148 return false; 20149 } 20150 synchronized(mPackages) { 20151 final PackageParser.Package pkg = mPackages.get(packageName); 20152 if (pkg == null) { 20153 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20154 throw new IllegalArgumentException("Unknown package: " + packageName); 20155 } 20156 IBinder ksh = ks.getToken(); 20157 if (ksh instanceof KeySetHandle) { 20158 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20159 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 20160 } 20161 return false; 20162 } 20163 } 20164 20165 @Override 20166 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 20167 if (packageName == null || ks == null) { 20168 return false; 20169 } 20170 synchronized(mPackages) { 20171 final PackageParser.Package pkg = mPackages.get(packageName); 20172 if (pkg == null) { 20173 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 20174 throw new IllegalArgumentException("Unknown package: " + packageName); 20175 } 20176 IBinder ksh = ks.getToken(); 20177 if (ksh instanceof KeySetHandle) { 20178 KeySetManagerService ksms = mSettings.mKeySetManagerService; 20179 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 20180 } 20181 return false; 20182 } 20183 } 20184 20185 private void deletePackageIfUnusedLPr(final String packageName) { 20186 PackageSetting ps = mSettings.mPackages.get(packageName); 20187 if (ps == null) { 20188 return; 20189 } 20190 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 20191 // TODO Implement atomic delete if package is unused 20192 // It is currently possible that the package will be deleted even if it is installed 20193 // after this method returns. 20194 mHandler.post(new Runnable() { 20195 public void run() { 20196 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 20197 } 20198 }); 20199 } 20200 } 20201 20202 /** 20203 * Check and throw if the given before/after packages would be considered a 20204 * downgrade. 20205 */ 20206 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 20207 throws PackageManagerException { 20208 if (after.versionCode < before.mVersionCode) { 20209 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20210 "Update version code " + after.versionCode + " is older than current " 20211 + before.mVersionCode); 20212 } else if (after.versionCode == before.mVersionCode) { 20213 if (after.baseRevisionCode < before.baseRevisionCode) { 20214 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20215 "Update base revision code " + after.baseRevisionCode 20216 + " is older than current " + before.baseRevisionCode); 20217 } 20218 20219 if (!ArrayUtils.isEmpty(after.splitNames)) { 20220 for (int i = 0; i < after.splitNames.length; i++) { 20221 final String splitName = after.splitNames[i]; 20222 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 20223 if (j != -1) { 20224 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 20225 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 20226 "Update split " + splitName + " revision code " 20227 + after.splitRevisionCodes[i] + " is older than current " 20228 + before.splitRevisionCodes[j]); 20229 } 20230 } 20231 } 20232 } 20233 } 20234 } 20235 20236 private static class MoveCallbacks extends Handler { 20237 private static final int MSG_CREATED = 1; 20238 private static final int MSG_STATUS_CHANGED = 2; 20239 20240 private final RemoteCallbackList<IPackageMoveObserver> 20241 mCallbacks = new RemoteCallbackList<>(); 20242 20243 private final SparseIntArray mLastStatus = new SparseIntArray(); 20244 20245 public MoveCallbacks(Looper looper) { 20246 super(looper); 20247 } 20248 20249 public void register(IPackageMoveObserver callback) { 20250 mCallbacks.register(callback); 20251 } 20252 20253 public void unregister(IPackageMoveObserver callback) { 20254 mCallbacks.unregister(callback); 20255 } 20256 20257 @Override 20258 public void handleMessage(Message msg) { 20259 final SomeArgs args = (SomeArgs) msg.obj; 20260 final int n = mCallbacks.beginBroadcast(); 20261 for (int i = 0; i < n; i++) { 20262 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20263 try { 20264 invokeCallback(callback, msg.what, args); 20265 } catch (RemoteException ignored) { 20266 } 20267 } 20268 mCallbacks.finishBroadcast(); 20269 args.recycle(); 20270 } 20271 20272 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20273 throws RemoteException { 20274 switch (what) { 20275 case MSG_CREATED: { 20276 callback.onCreated(args.argi1, (Bundle) args.arg2); 20277 break; 20278 } 20279 case MSG_STATUS_CHANGED: { 20280 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20281 break; 20282 } 20283 } 20284 } 20285 20286 private void notifyCreated(int moveId, Bundle extras) { 20287 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20288 20289 final SomeArgs args = SomeArgs.obtain(); 20290 args.argi1 = moveId; 20291 args.arg2 = extras; 20292 obtainMessage(MSG_CREATED, args).sendToTarget(); 20293 } 20294 20295 private void notifyStatusChanged(int moveId, int status) { 20296 notifyStatusChanged(moveId, status, -1); 20297 } 20298 20299 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20300 Slog.v(TAG, "Move " + moveId + " status " + status); 20301 20302 final SomeArgs args = SomeArgs.obtain(); 20303 args.argi1 = moveId; 20304 args.argi2 = status; 20305 args.arg3 = estMillis; 20306 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20307 20308 synchronized (mLastStatus) { 20309 mLastStatus.put(moveId, status); 20310 } 20311 } 20312 } 20313 20314 private final static class OnPermissionChangeListeners extends Handler { 20315 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20316 20317 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20318 new RemoteCallbackList<>(); 20319 20320 public OnPermissionChangeListeners(Looper looper) { 20321 super(looper); 20322 } 20323 20324 @Override 20325 public void handleMessage(Message msg) { 20326 switch (msg.what) { 20327 case MSG_ON_PERMISSIONS_CHANGED: { 20328 final int uid = msg.arg1; 20329 handleOnPermissionsChanged(uid); 20330 } break; 20331 } 20332 } 20333 20334 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20335 mPermissionListeners.register(listener); 20336 20337 } 20338 20339 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20340 mPermissionListeners.unregister(listener); 20341 } 20342 20343 public void onPermissionsChanged(int uid) { 20344 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20345 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20346 } 20347 } 20348 20349 private void handleOnPermissionsChanged(int uid) { 20350 final int count = mPermissionListeners.beginBroadcast(); 20351 try { 20352 for (int i = 0; i < count; i++) { 20353 IOnPermissionsChangeListener callback = mPermissionListeners 20354 .getBroadcastItem(i); 20355 try { 20356 callback.onPermissionsChanged(uid); 20357 } catch (RemoteException e) { 20358 Log.e(TAG, "Permission listener is dead", e); 20359 } 20360 } 20361 } finally { 20362 mPermissionListeners.finishBroadcast(); 20363 } 20364 } 20365 } 20366 20367 private class PackageManagerInternalImpl extends PackageManagerInternal { 20368 @Override 20369 public void setLocationPackagesProvider(PackagesProvider provider) { 20370 synchronized (mPackages) { 20371 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20372 } 20373 } 20374 20375 @Override 20376 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20377 synchronized (mPackages) { 20378 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20379 } 20380 } 20381 20382 @Override 20383 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20384 synchronized (mPackages) { 20385 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20386 } 20387 } 20388 20389 @Override 20390 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20391 synchronized (mPackages) { 20392 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20393 } 20394 } 20395 20396 @Override 20397 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20398 synchronized (mPackages) { 20399 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20400 } 20401 } 20402 20403 @Override 20404 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20405 synchronized (mPackages) { 20406 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20407 } 20408 } 20409 20410 @Override 20411 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20412 synchronized (mPackages) { 20413 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20414 packageName, userId); 20415 } 20416 } 20417 20418 @Override 20419 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20420 synchronized (mPackages) { 20421 mSettings.setDefaultDialerPackageNameLPw(packageName, userId); 20422 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20423 packageName, userId); 20424 } 20425 } 20426 20427 @Override 20428 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20429 synchronized (mPackages) { 20430 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20431 packageName, userId); 20432 } 20433 } 20434 20435 @Override 20436 public void setKeepUninstalledPackages(final List<String> packageList) { 20437 Preconditions.checkNotNull(packageList); 20438 List<String> removedFromList = null; 20439 synchronized (mPackages) { 20440 if (mKeepUninstalledPackages != null) { 20441 final int packagesCount = mKeepUninstalledPackages.size(); 20442 for (int i = 0; i < packagesCount; i++) { 20443 String oldPackage = mKeepUninstalledPackages.get(i); 20444 if (packageList != null && packageList.contains(oldPackage)) { 20445 continue; 20446 } 20447 if (removedFromList == null) { 20448 removedFromList = new ArrayList<>(); 20449 } 20450 removedFromList.add(oldPackage); 20451 } 20452 } 20453 mKeepUninstalledPackages = new ArrayList<>(packageList); 20454 if (removedFromList != null) { 20455 final int removedCount = removedFromList.size(); 20456 for (int i = 0; i < removedCount; i++) { 20457 deletePackageIfUnusedLPr(removedFromList.get(i)); 20458 } 20459 } 20460 } 20461 } 20462 20463 @Override 20464 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20465 synchronized (mPackages) { 20466 // If we do not support permission review, done. 20467 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20468 return false; 20469 } 20470 20471 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20472 if (packageSetting == null) { 20473 return false; 20474 } 20475 20476 // Permission review applies only to apps not supporting the new permission model. 20477 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20478 return false; 20479 } 20480 20481 // Legacy apps have the permission and get user consent on launch. 20482 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20483 return permissionsState.isPermissionReviewRequired(userId); 20484 } 20485 } 20486 20487 @Override 20488 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20489 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20490 } 20491 20492 @Override 20493 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20494 int userId) { 20495 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20496 } 20497 } 20498 20499 @Override 20500 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20501 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20502 synchronized (mPackages) { 20503 final long identity = Binder.clearCallingIdentity(); 20504 try { 20505 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20506 packageNames, userId); 20507 } finally { 20508 Binder.restoreCallingIdentity(identity); 20509 } 20510 } 20511 } 20512 20513 private static void enforceSystemOrPhoneCaller(String tag) { 20514 int callingUid = Binder.getCallingUid(); 20515 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20516 throw new SecurityException( 20517 "Cannot call " + tag + " from UID " + callingUid); 20518 } 20519 } 20520 20521 boolean isHistoricalPackageUsageAvailable() { 20522 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20523 } 20524 20525 /** 20526 * Return a <b>copy</b> of the collection of packages known to the package manager. 20527 * @return A copy of the values of mPackages. 20528 */ 20529 Collection<PackageParser.Package> getPackages() { 20530 synchronized (mPackages) { 20531 return new ArrayList<>(mPackages.values()); 20532 } 20533 } 20534 20535 /** 20536 * Logs process start information (including base APK hash) to the security log. 20537 * @hide 20538 */ 20539 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20540 String apkFile, int pid) { 20541 if (!SecurityLog.isLoggingEnabled()) { 20542 return; 20543 } 20544 Bundle data = new Bundle(); 20545 data.putLong("startTimestamp", System.currentTimeMillis()); 20546 data.putString("processName", processName); 20547 data.putInt("uid", uid); 20548 data.putString("seinfo", seinfo); 20549 data.putString("apkFile", apkFile); 20550 data.putInt("pid", pid); 20551 Message msg = mProcessLoggingHandler.obtainMessage( 20552 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20553 msg.setData(data); 20554 mProcessLoggingHandler.sendMessage(msg); 20555 } 20556} 20557