PackageManagerService.java revision fcf1e55821b694df3b8434f40aa3b6d3c3e7ea50
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.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.security.KeyStore; 199import android.security.SystemKeyStore; 200import android.system.ErrnoException; 201import android.system.Os; 202import android.text.TextUtils; 203import android.text.format.DateUtils; 204import android.util.ArrayMap; 205import android.util.ArraySet; 206import android.util.AtomicFile; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.view.Display; 220 221import com.android.internal.R; 222import com.android.internal.annotations.GuardedBy; 223import com.android.internal.app.IMediaContainerService; 224import com.android.internal.app.ResolverActivity; 225import com.android.internal.content.NativeLibraryHelper; 226import com.android.internal.content.PackageHelper; 227import com.android.internal.os.IParcelFileDescriptorFactory; 228import com.android.internal.os.InstallerConnection.InstallerException; 229import com.android.internal.os.SomeArgs; 230import com.android.internal.os.Zygote; 231import com.android.internal.telephony.CarrierAppUtils; 232import com.android.internal.util.ArrayUtils; 233import com.android.internal.util.FastPrintWriter; 234import com.android.internal.util.FastXmlSerializer; 235import com.android.internal.util.IndentingPrintWriter; 236import com.android.internal.util.Preconditions; 237import com.android.internal.util.XmlUtils; 238import com.android.server.EventLogTags; 239import com.android.server.FgThread; 240import com.android.server.IntentResolver; 241import com.android.server.LocalServices; 242import com.android.server.ServiceThread; 243import com.android.server.SystemConfig; 244import com.android.server.Watchdog; 245import com.android.server.pm.PermissionsState.PermissionState; 246import com.android.server.pm.Settings.DatabaseVersion; 247import com.android.server.pm.Settings.VersionInfo; 248import com.android.server.storage.DeviceStorageMonitorInternal; 249 250import dalvik.system.CloseGuard; 251import dalvik.system.DexFile; 252import dalvik.system.VMRuntime; 253 254import libcore.io.IoUtils; 255import libcore.util.EmptyArray; 256 257import org.xmlpull.v1.XmlPullParser; 258import org.xmlpull.v1.XmlPullParserException; 259import org.xmlpull.v1.XmlSerializer; 260 261import java.io.BufferedInputStream; 262import java.io.BufferedOutputStream; 263import java.io.BufferedReader; 264import java.io.ByteArrayInputStream; 265import java.io.ByteArrayOutputStream; 266import java.io.File; 267import java.io.FileDescriptor; 268import java.io.FileNotFoundException; 269import java.io.FileOutputStream; 270import java.io.FileReader; 271import java.io.FilenameFilter; 272import java.io.IOException; 273import java.io.InputStream; 274import java.io.PrintWriter; 275import java.nio.charset.StandardCharsets; 276import java.security.MessageDigest; 277import java.security.NoSuchAlgorithmException; 278import java.security.PublicKey; 279import java.security.cert.Certificate; 280import java.security.cert.CertificateEncodingException; 281import java.security.cert.CertificateException; 282import java.text.SimpleDateFormat; 283import java.util.ArrayList; 284import java.util.Arrays; 285import java.util.Collection; 286import java.util.Collections; 287import java.util.Comparator; 288import java.util.Date; 289import java.util.HashSet; 290import java.util.Iterator; 291import java.util.List; 292import java.util.Map; 293import java.util.Objects; 294import java.util.Set; 295import java.util.concurrent.CountDownLatch; 296import java.util.concurrent.TimeUnit; 297import java.util.concurrent.atomic.AtomicBoolean; 298import java.util.concurrent.atomic.AtomicInteger; 299import java.util.concurrent.atomic.AtomicLong; 300 301/** 302 * Keep track of all those APKs everywhere. 303 * <p> 304 * Internally there are two important locks: 305 * <ul> 306 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 307 * and other related state. It is a fine-grained lock that should only be held 308 * momentarily, as it's one of the most contended locks in the system. 309 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 310 * operations typically involve heavy lifting of application data on disk. Since 311 * {@code installd} is single-threaded, and it's operations can often be slow, 312 * this lock should never be acquired while already holding {@link #mPackages}. 313 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 314 * holding {@link #mInstallLock}. 315 * </ul> 316 * Many internal methods rely on the caller to hold the appropriate locks, and 317 * this contract is expressed through method name suffixes: 318 * <ul> 319 * <li>fooLI(): the caller must hold {@link #mInstallLock} 320 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 321 * being modified must be frozen 322 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 323 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 324 * </ul> 325 * <p> 326 * Because this class is very central to the platform's security; please run all 327 * CTS and unit tests whenever making modifications: 328 * 329 * <pre> 330 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 331 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 332 * </pre> 333 */ 334public class PackageManagerService extends IPackageManager.Stub { 335 static final String TAG = "PackageManager"; 336 static final boolean DEBUG_SETTINGS = false; 337 static final boolean DEBUG_PREFERRED = false; 338 static final boolean DEBUG_UPGRADE = false; 339 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 340 private static final boolean DEBUG_BACKUP = false; 341 private static final boolean DEBUG_INSTALL = false; 342 private static final boolean DEBUG_REMOVE = false; 343 private static final boolean DEBUG_BROADCASTS = false; 344 private static final boolean DEBUG_SHOW_INFO = false; 345 private static final boolean DEBUG_PACKAGE_INFO = false; 346 private static final boolean DEBUG_INTENT_MATCHING = false; 347 private static final boolean DEBUG_PACKAGE_SCANNING = false; 348 private static final boolean DEBUG_VERIFY = false; 349 private static final boolean DEBUG_FILTERS = false; 350 351 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 352 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 353 // user, but by default initialize to this. 354 static final boolean DEBUG_DEXOPT = false; 355 356 private static final boolean DEBUG_ABI_SELECTION = false; 357 private static final boolean DEBUG_EPHEMERAL = false; 358 private static final boolean DEBUG_TRIAGED_MISSING = false; 359 private static final boolean DEBUG_APP_DATA = false; 360 361 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 362 363 private static final boolean DISABLE_EPHEMERAL_APPS = true; 364 365 private static final int RADIO_UID = Process.PHONE_UID; 366 private static final int LOG_UID = Process.LOG_UID; 367 private static final int NFC_UID = Process.NFC_UID; 368 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 369 private static final int SHELL_UID = Process.SHELL_UID; 370 371 // Cap the size of permission trees that 3rd party apps can define 372 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 373 374 // Suffix used during package installation when copying/moving 375 // package apks to install directory. 376 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 377 378 static final int SCAN_NO_DEX = 1<<1; 379 static final int SCAN_FORCE_DEX = 1<<2; 380 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 381 static final int SCAN_NEW_INSTALL = 1<<4; 382 static final int SCAN_NO_PATHS = 1<<5; 383 static final int SCAN_UPDATE_TIME = 1<<6; 384 static final int SCAN_DEFER_DEX = 1<<7; 385 static final int SCAN_BOOTING = 1<<8; 386 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 387 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 388 static final int SCAN_REPLACING = 1<<11; 389 static final int SCAN_REQUIRE_KNOWN = 1<<12; 390 static final int SCAN_MOVE = 1<<13; 391 static final int SCAN_INITIAL = 1<<14; 392 static final int SCAN_CHECK_ONLY = 1<<15; 393 static final int SCAN_DONT_KILL_APP = 1<<17; 394 static final int SCAN_IGNORE_FROZEN = 1<<18; 395 396 static final int REMOVE_CHATTY = 1<<16; 397 398 private static final int[] EMPTY_INT_ARRAY = new int[0]; 399 400 /** 401 * Timeout (in milliseconds) after which the watchdog should declare that 402 * our handler thread is wedged. The usual default for such things is one 403 * minute but we sometimes do very lengthy I/O operations on this thread, 404 * such as installing multi-gigabyte applications, so ours needs to be longer. 405 */ 406 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 407 408 /** 409 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 410 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 411 * settings entry if available, otherwise we use the hardcoded default. If it's been 412 * more than this long since the last fstrim, we force one during the boot sequence. 413 * 414 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 415 * one gets run at the next available charging+idle time. This final mandatory 416 * no-fstrim check kicks in only of the other scheduling criteria is never met. 417 */ 418 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 419 420 /** 421 * Whether verification is enabled by default. 422 */ 423 private static final boolean DEFAULT_VERIFY_ENABLE = true; 424 425 /** 426 * The default maximum time to wait for the verification agent to return in 427 * milliseconds. 428 */ 429 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 430 431 /** 432 * The default response for package verification timeout. 433 * 434 * This can be either PackageManager.VERIFICATION_ALLOW or 435 * PackageManager.VERIFICATION_REJECT. 436 */ 437 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 438 439 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 440 441 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 442 DEFAULT_CONTAINER_PACKAGE, 443 "com.android.defcontainer.DefaultContainerService"); 444 445 private static final String KILL_APP_REASON_GIDS_CHANGED = 446 "permission grant or revoke changed gids"; 447 448 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 449 "permissions revoked"; 450 451 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 452 453 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 454 455 /** Permission grant: not grant the permission. */ 456 private static final int GRANT_DENIED = 1; 457 458 /** Permission grant: grant the permission as an install permission. */ 459 private static final int GRANT_INSTALL = 2; 460 461 /** Permission grant: grant the permission as a runtime one. */ 462 private static final int GRANT_RUNTIME = 3; 463 464 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 465 private static final int GRANT_UPGRADE = 4; 466 467 /** Canonical intent used to identify what counts as a "web browser" app */ 468 private static final Intent sBrowserIntent; 469 static { 470 sBrowserIntent = new Intent(); 471 sBrowserIntent.setAction(Intent.ACTION_VIEW); 472 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 473 sBrowserIntent.setData(Uri.parse("http:")); 474 } 475 476 /** 477 * The set of all protected actions [i.e. those actions for which a high priority 478 * intent filter is disallowed]. 479 */ 480 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 481 static { 482 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 483 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 485 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 486 } 487 488 // Compilation reasons. 489 public static final int REASON_FIRST_BOOT = 0; 490 public static final int REASON_BOOT = 1; 491 public static final int REASON_INSTALL = 2; 492 public static final int REASON_BACKGROUND_DEXOPT = 3; 493 public static final int REASON_AB_OTA = 4; 494 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 495 public static final int REASON_SHARED_APK = 6; 496 public static final int REASON_FORCED_DEXOPT = 7; 497 498 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 499 500 final ServiceThread mHandlerThread; 501 502 final PackageHandler mHandler; 503 504 private final ProcessLoggingHandler mProcessLoggingHandler; 505 506 /** 507 * Messages for {@link #mHandler} that need to wait for system ready before 508 * being dispatched. 509 */ 510 private ArrayList<Message> mPostSystemReadyMessages; 511 512 final int mSdkVersion = Build.VERSION.SDK_INT; 513 514 final Context mContext; 515 final boolean mFactoryTest; 516 final boolean mOnlyCore; 517 final DisplayMetrics mMetrics; 518 final int mDefParseFlags; 519 final String[] mSeparateProcesses; 520 final boolean mIsUpgrade; 521 final boolean mIsPreNUpgrade; 522 523 /** The location for ASEC container files on internal storage. */ 524 final String mAsecInternalPath; 525 526 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 527 // LOCK HELD. Can be called with mInstallLock held. 528 @GuardedBy("mInstallLock") 529 final Installer mInstaller; 530 531 /** Directory where installed third-party apps stored */ 532 final File mAppInstallDir; 533 final File mEphemeralInstallDir; 534 535 /** 536 * Directory to which applications installed internally have their 537 * 32 bit native libraries copied. 538 */ 539 private File mAppLib32InstallDir; 540 541 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 542 // apps. 543 final File mDrmAppPrivateInstallDir; 544 545 // ---------------------------------------------------------------- 546 547 // Lock for state used when installing and doing other long running 548 // operations. Methods that must be called with this lock held have 549 // the suffix "LI". 550 final Object mInstallLock = new Object(); 551 552 // ---------------------------------------------------------------- 553 554 // Keys are String (package name), values are Package. This also serves 555 // as the lock for the global state. Methods that must be called with 556 // this lock held have the prefix "LP". 557 @GuardedBy("mPackages") 558 final ArrayMap<String, PackageParser.Package> mPackages = 559 new ArrayMap<String, PackageParser.Package>(); 560 561 final ArrayMap<String, Set<String>> mKnownCodebase = 562 new ArrayMap<String, Set<String>>(); 563 564 // Tracks available target package names -> overlay package paths. 565 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 566 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 567 568 /** 569 * Tracks new system packages [received in an OTA] that we expect to 570 * find updated user-installed versions. Keys are package name, values 571 * are package location. 572 */ 573 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 574 /** 575 * Tracks high priority intent filters for protected actions. During boot, certain 576 * filter actions are protected and should never be allowed to have a high priority 577 * intent filter for them. However, there is one, and only one exception -- the 578 * setup wizard. It must be able to define a high priority intent filter for these 579 * actions to ensure there are no escapes from the wizard. We need to delay processing 580 * of these during boot as we need to look at all of the system packages in order 581 * to know which component is the setup wizard. 582 */ 583 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 584 /** 585 * Whether or not processing protected filters should be deferred. 586 */ 587 private boolean mDeferProtectedFilters = true; 588 589 /** 590 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 591 */ 592 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 593 /** 594 * Whether or not system app permissions should be promoted from install to runtime. 595 */ 596 boolean mPromoteSystemApps; 597 598 @GuardedBy("mPackages") 599 final Settings mSettings; 600 601 /** 602 * Set of package names that are currently "frozen", which means active 603 * surgery is being done on the code/data for that package. The platform 604 * will refuse to launch frozen packages to avoid race conditions. 605 * 606 * @see PackageFreezer 607 */ 608 @GuardedBy("mPackages") 609 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 610 611 boolean mRestoredSettings; 612 613 // System configuration read by SystemConfig. 614 final int[] mGlobalGids; 615 final SparseArray<ArraySet<String>> mSystemPermissions; 616 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 617 618 // If mac_permissions.xml was found for seinfo labeling. 619 boolean mFoundPolicyFile; 620 621 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 622 623 public static final class SharedLibraryEntry { 624 public final String path; 625 public final String apk; 626 627 SharedLibraryEntry(String _path, String _apk) { 628 path = _path; 629 apk = _apk; 630 } 631 } 632 633 // Currently known shared libraries. 634 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 635 new ArrayMap<String, SharedLibraryEntry>(); 636 637 // All available activities, for your resolving pleasure. 638 final ActivityIntentResolver mActivities = 639 new ActivityIntentResolver(); 640 641 // All available receivers, for your resolving pleasure. 642 final ActivityIntentResolver mReceivers = 643 new ActivityIntentResolver(); 644 645 // All available services, for your resolving pleasure. 646 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 647 648 // All available providers, for your resolving pleasure. 649 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 650 651 // Mapping from provider base names (first directory in content URI codePath) 652 // to the provider information. 653 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 654 new ArrayMap<String, PackageParser.Provider>(); 655 656 // Mapping from instrumentation class names to info about them. 657 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 658 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 659 660 // Mapping from permission names to info about them. 661 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 662 new ArrayMap<String, PackageParser.PermissionGroup>(); 663 664 // Packages whose data we have transfered into another package, thus 665 // should no longer exist. 666 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 667 668 // Broadcast actions that are only available to the system. 669 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 670 671 /** List of packages waiting for verification. */ 672 final SparseArray<PackageVerificationState> mPendingVerification 673 = new SparseArray<PackageVerificationState>(); 674 675 /** Set of packages associated with each app op permission. */ 676 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 677 678 final PackageInstallerService mInstallerService; 679 680 private final PackageDexOptimizer mPackageDexOptimizer; 681 682 private AtomicInteger mNextMoveId = new AtomicInteger(); 683 private final MoveCallbacks mMoveCallbacks; 684 685 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 686 687 // Cache of users who need badging. 688 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 689 690 /** Token for keys in mPendingVerification. */ 691 private int mPendingVerificationToken = 0; 692 693 volatile boolean mSystemReady; 694 volatile boolean mSafeMode; 695 volatile boolean mHasSystemUidErrors; 696 697 ApplicationInfo mAndroidApplication; 698 final ActivityInfo mResolveActivity = new ActivityInfo(); 699 final ResolveInfo mResolveInfo = new ResolveInfo(); 700 ComponentName mResolveComponentName; 701 PackageParser.Package mPlatformPackage; 702 ComponentName mCustomResolverComponentName; 703 704 boolean mResolverReplaced = false; 705 706 private final @Nullable ComponentName mIntentFilterVerifierComponent; 707 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 708 709 private int mIntentFilterVerificationToken = 0; 710 711 /** Component that knows whether or not an ephemeral application exists */ 712 final ComponentName mEphemeralResolverComponent; 713 /** The service connection to the ephemeral resolver */ 714 final EphemeralResolverConnection mEphemeralResolverConnection; 715 716 /** Component used to install ephemeral applications */ 717 final ComponentName mEphemeralInstallerComponent; 718 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 719 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 720 721 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 722 = new SparseArray<IntentFilterVerificationState>(); 723 724 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 725 new DefaultPermissionGrantPolicy(this); 726 727 // List of packages names to keep cached, even if they are uninstalled for all users 728 private List<String> mKeepUninstalledPackages; 729 730 private static class IFVerificationParams { 731 PackageParser.Package pkg; 732 boolean replacing; 733 int userId; 734 int verifierUid; 735 736 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 737 int _userId, int _verifierUid) { 738 pkg = _pkg; 739 replacing = _replacing; 740 userId = _userId; 741 replacing = _replacing; 742 verifierUid = _verifierUid; 743 } 744 } 745 746 private interface IntentFilterVerifier<T extends IntentFilter> { 747 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 748 T filter, String packageName); 749 void startVerifications(int userId); 750 void receiveVerificationResponse(int verificationId); 751 } 752 753 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 754 private Context mContext; 755 private ComponentName mIntentFilterVerifierComponent; 756 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 757 758 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 759 mContext = context; 760 mIntentFilterVerifierComponent = verifierComponent; 761 } 762 763 private String getDefaultScheme() { 764 return IntentFilter.SCHEME_HTTPS; 765 } 766 767 @Override 768 public void startVerifications(int userId) { 769 // Launch verifications requests 770 int count = mCurrentIntentFilterVerifications.size(); 771 for (int n=0; n<count; n++) { 772 int verificationId = mCurrentIntentFilterVerifications.get(n); 773 final IntentFilterVerificationState ivs = 774 mIntentFilterVerificationStates.get(verificationId); 775 776 String packageName = ivs.getPackageName(); 777 778 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 779 final int filterCount = filters.size(); 780 ArraySet<String> domainsSet = new ArraySet<>(); 781 for (int m=0; m<filterCount; m++) { 782 PackageParser.ActivityIntentInfo filter = filters.get(m); 783 domainsSet.addAll(filter.getHostsList()); 784 } 785 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 786 synchronized (mPackages) { 787 if (mSettings.createIntentFilterVerificationIfNeededLPw( 788 packageName, domainsList) != null) { 789 scheduleWriteSettingsLocked(); 790 } 791 } 792 sendVerificationRequest(userId, verificationId, ivs); 793 } 794 mCurrentIntentFilterVerifications.clear(); 795 } 796 797 private void sendVerificationRequest(int userId, int verificationId, 798 IntentFilterVerificationState ivs) { 799 800 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 801 verificationIntent.putExtra( 802 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 803 verificationId); 804 verificationIntent.putExtra( 805 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 806 getDefaultScheme()); 807 verificationIntent.putExtra( 808 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 809 ivs.getHostsString()); 810 verificationIntent.putExtra( 811 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 812 ivs.getPackageName()); 813 verificationIntent.setComponent(mIntentFilterVerifierComponent); 814 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 815 816 UserHandle user = new UserHandle(userId); 817 mContext.sendBroadcastAsUser(verificationIntent, user); 818 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 819 "Sending IntentFilter verification broadcast"); 820 } 821 822 public void receiveVerificationResponse(int verificationId) { 823 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 824 825 final boolean verified = ivs.isVerified(); 826 827 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 828 final int count = filters.size(); 829 if (DEBUG_DOMAIN_VERIFICATION) { 830 Slog.i(TAG, "Received verification response " + verificationId 831 + " for " + count + " filters, verified=" + verified); 832 } 833 for (int n=0; n<count; n++) { 834 PackageParser.ActivityIntentInfo filter = filters.get(n); 835 filter.setVerified(verified); 836 837 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 838 + " verified with result:" + verified + " and hosts:" 839 + ivs.getHostsString()); 840 } 841 842 mIntentFilterVerificationStates.remove(verificationId); 843 844 final String packageName = ivs.getPackageName(); 845 IntentFilterVerificationInfo ivi = null; 846 847 synchronized (mPackages) { 848 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 849 } 850 if (ivi == null) { 851 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 852 + verificationId + " packageName:" + packageName); 853 return; 854 } 855 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 856 "Updating IntentFilterVerificationInfo for package " + packageName 857 +" verificationId:" + verificationId); 858 859 synchronized (mPackages) { 860 if (verified) { 861 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 862 } else { 863 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 864 } 865 scheduleWriteSettingsLocked(); 866 867 final int userId = ivs.getUserId(); 868 if (userId != UserHandle.USER_ALL) { 869 final int userStatus = 870 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 871 872 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 873 boolean needUpdate = false; 874 875 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 876 // already been set by the User thru the Disambiguation dialog 877 switch (userStatus) { 878 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 879 if (verified) { 880 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 881 } else { 882 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 883 } 884 needUpdate = true; 885 break; 886 887 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 888 if (verified) { 889 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 890 needUpdate = true; 891 } 892 break; 893 894 default: 895 // Nothing to do 896 } 897 898 if (needUpdate) { 899 mSettings.updateIntentFilterVerificationStatusLPw( 900 packageName, updatedStatus, userId); 901 scheduleWritePackageRestrictionsLocked(userId); 902 } 903 } 904 } 905 } 906 907 @Override 908 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 909 ActivityIntentInfo filter, String packageName) { 910 if (!hasValidDomains(filter)) { 911 return false; 912 } 913 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 914 if (ivs == null) { 915 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 916 packageName); 917 } 918 if (DEBUG_DOMAIN_VERIFICATION) { 919 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 920 } 921 ivs.addFilter(filter); 922 return true; 923 } 924 925 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 926 int userId, int verificationId, String packageName) { 927 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 928 verifierUid, userId, packageName); 929 ivs.setPendingState(); 930 synchronized (mPackages) { 931 mIntentFilterVerificationStates.append(verificationId, ivs); 932 mCurrentIntentFilterVerifications.add(verificationId); 933 } 934 return ivs; 935 } 936 } 937 938 private static boolean hasValidDomains(ActivityIntentInfo filter) { 939 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 940 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 941 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 942 } 943 944 // Set of pending broadcasts for aggregating enable/disable of components. 945 static class PendingPackageBroadcasts { 946 // for each user id, a map of <package name -> components within that package> 947 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 948 949 public PendingPackageBroadcasts() { 950 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 951 } 952 953 public ArrayList<String> get(int userId, String packageName) { 954 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 955 return packages.get(packageName); 956 } 957 958 public void put(int userId, String packageName, ArrayList<String> components) { 959 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 960 packages.put(packageName, components); 961 } 962 963 public void remove(int userId, String packageName) { 964 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 965 if (packages != null) { 966 packages.remove(packageName); 967 } 968 } 969 970 public void remove(int userId) { 971 mUidMap.remove(userId); 972 } 973 974 public int userIdCount() { 975 return mUidMap.size(); 976 } 977 978 public int userIdAt(int n) { 979 return mUidMap.keyAt(n); 980 } 981 982 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 983 return mUidMap.get(userId); 984 } 985 986 public int size() { 987 // total number of pending broadcast entries across all userIds 988 int num = 0; 989 for (int i = 0; i< mUidMap.size(); i++) { 990 num += mUidMap.valueAt(i).size(); 991 } 992 return num; 993 } 994 995 public void clear() { 996 mUidMap.clear(); 997 } 998 999 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1000 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1001 if (map == null) { 1002 map = new ArrayMap<String, ArrayList<String>>(); 1003 mUidMap.put(userId, map); 1004 } 1005 return map; 1006 } 1007 } 1008 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1009 1010 // Service Connection to remote media container service to copy 1011 // package uri's from external media onto secure containers 1012 // or internal storage. 1013 private IMediaContainerService mContainerService = null; 1014 1015 static final int SEND_PENDING_BROADCAST = 1; 1016 static final int MCS_BOUND = 3; 1017 static final int END_COPY = 4; 1018 static final int INIT_COPY = 5; 1019 static final int MCS_UNBIND = 6; 1020 static final int START_CLEANING_PACKAGE = 7; 1021 static final int FIND_INSTALL_LOC = 8; 1022 static final int POST_INSTALL = 9; 1023 static final int MCS_RECONNECT = 10; 1024 static final int MCS_GIVE_UP = 11; 1025 static final int UPDATED_MEDIA_STATUS = 12; 1026 static final int WRITE_SETTINGS = 13; 1027 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1028 static final int PACKAGE_VERIFIED = 15; 1029 static final int CHECK_PENDING_VERIFICATION = 16; 1030 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1031 static final int INTENT_FILTER_VERIFIED = 18; 1032 1033 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1034 1035 // Delay time in millisecs 1036 static final int BROADCAST_DELAY = 10 * 1000; 1037 1038 static UserManagerService sUserManager; 1039 1040 // Stores a list of users whose package restrictions file needs to be updated 1041 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1042 1043 final private DefaultContainerConnection mDefContainerConn = 1044 new DefaultContainerConnection(); 1045 class DefaultContainerConnection implements ServiceConnection { 1046 public void onServiceConnected(ComponentName name, IBinder service) { 1047 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1048 IMediaContainerService imcs = 1049 IMediaContainerService.Stub.asInterface(service); 1050 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1051 } 1052 1053 public void onServiceDisconnected(ComponentName name) { 1054 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1055 } 1056 } 1057 1058 // Recordkeeping of restore-after-install operations that are currently in flight 1059 // between the Package Manager and the Backup Manager 1060 static class PostInstallData { 1061 public InstallArgs args; 1062 public PackageInstalledInfo res; 1063 1064 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1065 args = _a; 1066 res = _r; 1067 } 1068 } 1069 1070 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1071 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1072 1073 // XML tags for backup/restore of various bits of state 1074 private static final String TAG_PREFERRED_BACKUP = "pa"; 1075 private static final String TAG_DEFAULT_APPS = "da"; 1076 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1077 1078 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1079 private static final String TAG_ALL_GRANTS = "rt-grants"; 1080 private static final String TAG_GRANT = "grant"; 1081 private static final String ATTR_PACKAGE_NAME = "pkg"; 1082 1083 private static final String TAG_PERMISSION = "perm"; 1084 private static final String ATTR_PERMISSION_NAME = "name"; 1085 private static final String ATTR_IS_GRANTED = "g"; 1086 private static final String ATTR_USER_SET = "set"; 1087 private static final String ATTR_USER_FIXED = "fixed"; 1088 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1089 1090 // System/policy permission grants are not backed up 1091 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1092 FLAG_PERMISSION_POLICY_FIXED 1093 | FLAG_PERMISSION_SYSTEM_FIXED 1094 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1095 1096 // And we back up these user-adjusted states 1097 private static final int USER_RUNTIME_GRANT_MASK = 1098 FLAG_PERMISSION_USER_SET 1099 | FLAG_PERMISSION_USER_FIXED 1100 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1101 1102 final @Nullable String mRequiredVerifierPackage; 1103 final @NonNull String mRequiredInstallerPackage; 1104 final @Nullable String mSetupWizardPackage; 1105 final @NonNull String mServicesSystemSharedLibraryPackageName; 1106 1107 private final PackageUsage mPackageUsage = new PackageUsage(); 1108 1109 private class PackageUsage { 1110 private static final int WRITE_INTERVAL 1111 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1112 1113 private final Object mFileLock = new Object(); 1114 private final AtomicLong mLastWritten = new AtomicLong(0); 1115 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1116 1117 private boolean mIsHistoricalPackageUsageAvailable = true; 1118 1119 boolean isHistoricalPackageUsageAvailable() { 1120 return mIsHistoricalPackageUsageAvailable; 1121 } 1122 1123 void write(boolean force) { 1124 if (force) { 1125 writeInternal(); 1126 return; 1127 } 1128 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1129 && !DEBUG_DEXOPT) { 1130 return; 1131 } 1132 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1133 new Thread("PackageUsage_DiskWriter") { 1134 @Override 1135 public void run() { 1136 try { 1137 writeInternal(); 1138 } finally { 1139 mBackgroundWriteRunning.set(false); 1140 } 1141 } 1142 }.start(); 1143 } 1144 } 1145 1146 private void writeInternal() { 1147 synchronized (mPackages) { 1148 synchronized (mFileLock) { 1149 AtomicFile file = getFile(); 1150 FileOutputStream f = null; 1151 try { 1152 f = file.startWrite(); 1153 BufferedOutputStream out = new BufferedOutputStream(f); 1154 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1155 StringBuilder sb = new StringBuilder(); 1156 for (PackageParser.Package pkg : mPackages.values()) { 1157 if (pkg.mLastPackageUsageTimeInMills == 0) { 1158 continue; 1159 } 1160 sb.setLength(0); 1161 sb.append(pkg.packageName); 1162 sb.append(' '); 1163 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1164 sb.append('\n'); 1165 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1166 } 1167 out.flush(); 1168 file.finishWrite(f); 1169 } catch (IOException e) { 1170 if (f != null) { 1171 file.failWrite(f); 1172 } 1173 Log.e(TAG, "Failed to write package usage times", e); 1174 } 1175 } 1176 } 1177 mLastWritten.set(SystemClock.elapsedRealtime()); 1178 } 1179 1180 void readLP() { 1181 synchronized (mFileLock) { 1182 AtomicFile file = getFile(); 1183 BufferedInputStream in = null; 1184 try { 1185 in = new BufferedInputStream(file.openRead()); 1186 StringBuffer sb = new StringBuffer(); 1187 while (true) { 1188 String packageName = readToken(in, sb, ' '); 1189 if (packageName == null) { 1190 break; 1191 } 1192 String timeInMillisString = readToken(in, sb, '\n'); 1193 if (timeInMillisString == null) { 1194 throw new IOException("Failed to find last usage time for package " 1195 + packageName); 1196 } 1197 PackageParser.Package pkg = mPackages.get(packageName); 1198 if (pkg == null) { 1199 continue; 1200 } 1201 long timeInMillis; 1202 try { 1203 timeInMillis = Long.parseLong(timeInMillisString); 1204 } catch (NumberFormatException e) { 1205 throw new IOException("Failed to parse " + timeInMillisString 1206 + " as a long.", e); 1207 } 1208 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1209 } 1210 } catch (FileNotFoundException expected) { 1211 mIsHistoricalPackageUsageAvailable = false; 1212 } catch (IOException e) { 1213 Log.w(TAG, "Failed to read package usage times", e); 1214 } finally { 1215 IoUtils.closeQuietly(in); 1216 } 1217 } 1218 mLastWritten.set(SystemClock.elapsedRealtime()); 1219 } 1220 1221 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1222 throws IOException { 1223 sb.setLength(0); 1224 while (true) { 1225 int ch = in.read(); 1226 if (ch == -1) { 1227 if (sb.length() == 0) { 1228 return null; 1229 } 1230 throw new IOException("Unexpected EOF"); 1231 } 1232 if (ch == endOfToken) { 1233 return sb.toString(); 1234 } 1235 sb.append((char)ch); 1236 } 1237 } 1238 1239 private AtomicFile getFile() { 1240 File dataDir = Environment.getDataDirectory(); 1241 File systemDir = new File(dataDir, "system"); 1242 File fname = new File(systemDir, "package-usage.list"); 1243 return new AtomicFile(fname); 1244 } 1245 } 1246 1247 class PackageHandler extends Handler { 1248 private boolean mBound = false; 1249 final ArrayList<HandlerParams> mPendingInstalls = 1250 new ArrayList<HandlerParams>(); 1251 1252 private boolean connectToService() { 1253 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1254 " DefaultContainerService"); 1255 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1256 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1257 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1258 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1259 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1260 mBound = true; 1261 return true; 1262 } 1263 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1264 return false; 1265 } 1266 1267 private void disconnectService() { 1268 mContainerService = null; 1269 mBound = false; 1270 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1271 mContext.unbindService(mDefContainerConn); 1272 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1273 } 1274 1275 PackageHandler(Looper looper) { 1276 super(looper); 1277 } 1278 1279 public void handleMessage(Message msg) { 1280 try { 1281 doHandleMessage(msg); 1282 } finally { 1283 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1284 } 1285 } 1286 1287 void doHandleMessage(Message msg) { 1288 switch (msg.what) { 1289 case INIT_COPY: { 1290 HandlerParams params = (HandlerParams) msg.obj; 1291 int idx = mPendingInstalls.size(); 1292 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1293 // If a bind was already initiated we dont really 1294 // need to do anything. The pending install 1295 // will be processed later on. 1296 if (!mBound) { 1297 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1298 System.identityHashCode(mHandler)); 1299 // If this is the only one pending we might 1300 // have to bind to the service again. 1301 if (!connectToService()) { 1302 Slog.e(TAG, "Failed to bind to media container service"); 1303 params.serviceError(); 1304 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1305 System.identityHashCode(mHandler)); 1306 if (params.traceMethod != null) { 1307 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1308 params.traceCookie); 1309 } 1310 return; 1311 } else { 1312 // Once we bind to the service, the first 1313 // pending request will be processed. 1314 mPendingInstalls.add(idx, params); 1315 } 1316 } else { 1317 mPendingInstalls.add(idx, params); 1318 // Already bound to the service. Just make 1319 // sure we trigger off processing the first request. 1320 if (idx == 0) { 1321 mHandler.sendEmptyMessage(MCS_BOUND); 1322 } 1323 } 1324 break; 1325 } 1326 case MCS_BOUND: { 1327 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1328 if (msg.obj != null) { 1329 mContainerService = (IMediaContainerService) msg.obj; 1330 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1331 System.identityHashCode(mHandler)); 1332 } 1333 if (mContainerService == null) { 1334 if (!mBound) { 1335 // Something seriously wrong since we are not bound and we are not 1336 // waiting for connection. Bail out. 1337 Slog.e(TAG, "Cannot bind to media container service"); 1338 for (HandlerParams params : mPendingInstalls) { 1339 // Indicate service bind error 1340 params.serviceError(); 1341 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1342 System.identityHashCode(params)); 1343 if (params.traceMethod != null) { 1344 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1345 params.traceMethod, params.traceCookie); 1346 } 1347 return; 1348 } 1349 mPendingInstalls.clear(); 1350 } else { 1351 Slog.w(TAG, "Waiting to connect to media container service"); 1352 } 1353 } else if (mPendingInstalls.size() > 0) { 1354 HandlerParams params = mPendingInstalls.get(0); 1355 if (params != null) { 1356 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1357 System.identityHashCode(params)); 1358 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1359 if (params.startCopy()) { 1360 // We are done... look for more work or to 1361 // go idle. 1362 if (DEBUG_SD_INSTALL) Log.i(TAG, 1363 "Checking for more work or unbind..."); 1364 // Delete pending install 1365 if (mPendingInstalls.size() > 0) { 1366 mPendingInstalls.remove(0); 1367 } 1368 if (mPendingInstalls.size() == 0) { 1369 if (mBound) { 1370 if (DEBUG_SD_INSTALL) Log.i(TAG, 1371 "Posting delayed MCS_UNBIND"); 1372 removeMessages(MCS_UNBIND); 1373 Message ubmsg = obtainMessage(MCS_UNBIND); 1374 // Unbind after a little delay, to avoid 1375 // continual thrashing. 1376 sendMessageDelayed(ubmsg, 10000); 1377 } 1378 } else { 1379 // There are more pending requests in queue. 1380 // Just post MCS_BOUND message to trigger processing 1381 // of next pending install. 1382 if (DEBUG_SD_INSTALL) Log.i(TAG, 1383 "Posting MCS_BOUND for next work"); 1384 mHandler.sendEmptyMessage(MCS_BOUND); 1385 } 1386 } 1387 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1388 } 1389 } else { 1390 // Should never happen ideally. 1391 Slog.w(TAG, "Empty queue"); 1392 } 1393 break; 1394 } 1395 case MCS_RECONNECT: { 1396 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1397 if (mPendingInstalls.size() > 0) { 1398 if (mBound) { 1399 disconnectService(); 1400 } 1401 if (!connectToService()) { 1402 Slog.e(TAG, "Failed to bind to media container service"); 1403 for (HandlerParams params : mPendingInstalls) { 1404 // Indicate service bind error 1405 params.serviceError(); 1406 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1407 System.identityHashCode(params)); 1408 } 1409 mPendingInstalls.clear(); 1410 } 1411 } 1412 break; 1413 } 1414 case MCS_UNBIND: { 1415 // If there is no actual work left, then time to unbind. 1416 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1417 1418 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1419 if (mBound) { 1420 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1421 1422 disconnectService(); 1423 } 1424 } else if (mPendingInstalls.size() > 0) { 1425 // There are more pending requests in queue. 1426 // Just post MCS_BOUND message to trigger processing 1427 // of next pending install. 1428 mHandler.sendEmptyMessage(MCS_BOUND); 1429 } 1430 1431 break; 1432 } 1433 case MCS_GIVE_UP: { 1434 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1435 HandlerParams params = mPendingInstalls.remove(0); 1436 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1437 System.identityHashCode(params)); 1438 break; 1439 } 1440 case SEND_PENDING_BROADCAST: { 1441 String packages[]; 1442 ArrayList<String> components[]; 1443 int size = 0; 1444 int uids[]; 1445 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1446 synchronized (mPackages) { 1447 if (mPendingBroadcasts == null) { 1448 return; 1449 } 1450 size = mPendingBroadcasts.size(); 1451 if (size <= 0) { 1452 // Nothing to be done. Just return 1453 return; 1454 } 1455 packages = new String[size]; 1456 components = new ArrayList[size]; 1457 uids = new int[size]; 1458 int i = 0; // filling out the above arrays 1459 1460 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1461 int packageUserId = mPendingBroadcasts.userIdAt(n); 1462 Iterator<Map.Entry<String, ArrayList<String>>> it 1463 = mPendingBroadcasts.packagesForUserId(packageUserId) 1464 .entrySet().iterator(); 1465 while (it.hasNext() && i < size) { 1466 Map.Entry<String, ArrayList<String>> ent = it.next(); 1467 packages[i] = ent.getKey(); 1468 components[i] = ent.getValue(); 1469 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1470 uids[i] = (ps != null) 1471 ? UserHandle.getUid(packageUserId, ps.appId) 1472 : -1; 1473 i++; 1474 } 1475 } 1476 size = i; 1477 mPendingBroadcasts.clear(); 1478 } 1479 // Send broadcasts 1480 for (int i = 0; i < size; i++) { 1481 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1482 } 1483 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1484 break; 1485 } 1486 case START_CLEANING_PACKAGE: { 1487 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1488 final String packageName = (String)msg.obj; 1489 final int userId = msg.arg1; 1490 final boolean andCode = msg.arg2 != 0; 1491 synchronized (mPackages) { 1492 if (userId == UserHandle.USER_ALL) { 1493 int[] users = sUserManager.getUserIds(); 1494 for (int user : users) { 1495 mSettings.addPackageToCleanLPw( 1496 new PackageCleanItem(user, packageName, andCode)); 1497 } 1498 } else { 1499 mSettings.addPackageToCleanLPw( 1500 new PackageCleanItem(userId, packageName, andCode)); 1501 } 1502 } 1503 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1504 startCleaningPackages(); 1505 } break; 1506 case POST_INSTALL: { 1507 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1508 1509 PostInstallData data = mRunningInstalls.get(msg.arg1); 1510 mRunningInstalls.delete(msg.arg1); 1511 1512 if (data != null) { 1513 InstallArgs args = data.args; 1514 PackageInstalledInfo parentRes = data.res; 1515 1516 final boolean grantPermissions = (args.installFlags 1517 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1518 final boolean killApp = (args.installFlags 1519 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1520 final String[] grantedPermissions = args.installGrantPermissions; 1521 1522 // Handle the parent package 1523 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1524 grantedPermissions, args.observer); 1525 1526 // Handle the child packages 1527 final int childCount = (parentRes.addedChildPackages != null) 1528 ? parentRes.addedChildPackages.size() : 0; 1529 for (int i = 0; i < childCount; i++) { 1530 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1531 handlePackagePostInstall(childRes, grantPermissions, killApp, 1532 grantedPermissions, args.observer); 1533 } 1534 1535 // Log tracing if needed 1536 if (args.traceMethod != null) { 1537 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1538 args.traceCookie); 1539 } 1540 } else { 1541 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1542 } 1543 1544 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1545 } break; 1546 case UPDATED_MEDIA_STATUS: { 1547 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1548 boolean reportStatus = msg.arg1 == 1; 1549 boolean doGc = msg.arg2 == 1; 1550 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1551 if (doGc) { 1552 // Force a gc to clear up stale containers. 1553 Runtime.getRuntime().gc(); 1554 } 1555 if (msg.obj != null) { 1556 @SuppressWarnings("unchecked") 1557 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1558 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1559 // Unload containers 1560 unloadAllContainers(args); 1561 } 1562 if (reportStatus) { 1563 try { 1564 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1565 PackageHelper.getMountService().finishMediaUpdate(); 1566 } catch (RemoteException e) { 1567 Log.e(TAG, "MountService not running?"); 1568 } 1569 } 1570 } break; 1571 case WRITE_SETTINGS: { 1572 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1573 synchronized (mPackages) { 1574 removeMessages(WRITE_SETTINGS); 1575 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1576 mSettings.writeLPr(); 1577 mDirtyUsers.clear(); 1578 } 1579 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1580 } break; 1581 case WRITE_PACKAGE_RESTRICTIONS: { 1582 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1583 synchronized (mPackages) { 1584 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1585 for (int userId : mDirtyUsers) { 1586 mSettings.writePackageRestrictionsLPr(userId); 1587 } 1588 mDirtyUsers.clear(); 1589 } 1590 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1591 } break; 1592 case CHECK_PENDING_VERIFICATION: { 1593 final int verificationId = msg.arg1; 1594 final PackageVerificationState state = mPendingVerification.get(verificationId); 1595 1596 if ((state != null) && !state.timeoutExtended()) { 1597 final InstallArgs args = state.getInstallArgs(); 1598 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1599 1600 Slog.i(TAG, "Verification timed out for " + originUri); 1601 mPendingVerification.remove(verificationId); 1602 1603 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1604 1605 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1606 Slog.i(TAG, "Continuing with installation of " + originUri); 1607 state.setVerifierResponse(Binder.getCallingUid(), 1608 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1609 broadcastPackageVerified(verificationId, originUri, 1610 PackageManager.VERIFICATION_ALLOW, 1611 state.getInstallArgs().getUser()); 1612 try { 1613 ret = args.copyApk(mContainerService, true); 1614 } catch (RemoteException e) { 1615 Slog.e(TAG, "Could not contact the ContainerService"); 1616 } 1617 } else { 1618 broadcastPackageVerified(verificationId, originUri, 1619 PackageManager.VERIFICATION_REJECT, 1620 state.getInstallArgs().getUser()); 1621 } 1622 1623 Trace.asyncTraceEnd( 1624 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1625 1626 processPendingInstall(args, ret); 1627 mHandler.sendEmptyMessage(MCS_UNBIND); 1628 } 1629 break; 1630 } 1631 case PACKAGE_VERIFIED: { 1632 final int verificationId = msg.arg1; 1633 1634 final PackageVerificationState state = mPendingVerification.get(verificationId); 1635 if (state == null) { 1636 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1637 break; 1638 } 1639 1640 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1641 1642 state.setVerifierResponse(response.callerUid, response.code); 1643 1644 if (state.isVerificationComplete()) { 1645 mPendingVerification.remove(verificationId); 1646 1647 final InstallArgs args = state.getInstallArgs(); 1648 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1649 1650 int ret; 1651 if (state.isInstallAllowed()) { 1652 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1653 broadcastPackageVerified(verificationId, originUri, 1654 response.code, state.getInstallArgs().getUser()); 1655 try { 1656 ret = args.copyApk(mContainerService, true); 1657 } catch (RemoteException e) { 1658 Slog.e(TAG, "Could not contact the ContainerService"); 1659 } 1660 } else { 1661 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1662 } 1663 1664 Trace.asyncTraceEnd( 1665 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1666 1667 processPendingInstall(args, ret); 1668 mHandler.sendEmptyMessage(MCS_UNBIND); 1669 } 1670 1671 break; 1672 } 1673 case START_INTENT_FILTER_VERIFICATIONS: { 1674 IFVerificationParams params = (IFVerificationParams) msg.obj; 1675 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1676 params.replacing, params.pkg); 1677 break; 1678 } 1679 case INTENT_FILTER_VERIFIED: { 1680 final int verificationId = msg.arg1; 1681 1682 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1683 verificationId); 1684 if (state == null) { 1685 Slog.w(TAG, "Invalid IntentFilter verification token " 1686 + verificationId + " received"); 1687 break; 1688 } 1689 1690 final int userId = state.getUserId(); 1691 1692 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1693 "Processing IntentFilter verification with token:" 1694 + verificationId + " and userId:" + userId); 1695 1696 final IntentFilterVerificationResponse response = 1697 (IntentFilterVerificationResponse) msg.obj; 1698 1699 state.setVerifierResponse(response.callerUid, response.code); 1700 1701 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1702 "IntentFilter verification with token:" + verificationId 1703 + " and userId:" + userId 1704 + " is settings verifier response with response code:" 1705 + response.code); 1706 1707 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1708 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1709 + response.getFailedDomainsString()); 1710 } 1711 1712 if (state.isVerificationComplete()) { 1713 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1714 } else { 1715 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1716 "IntentFilter verification with token:" + verificationId 1717 + " was not said to be complete"); 1718 } 1719 1720 break; 1721 } 1722 } 1723 } 1724 } 1725 1726 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1727 boolean killApp, String[] grantedPermissions, 1728 IPackageInstallObserver2 installObserver) { 1729 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1730 // Send the removed broadcasts 1731 if (res.removedInfo != null) { 1732 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1733 } 1734 1735 // Now that we successfully installed the package, grant runtime 1736 // permissions if requested before broadcasting the install. 1737 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1738 >= Build.VERSION_CODES.M) { 1739 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1740 } 1741 1742 final boolean update = res.removedInfo != null 1743 && res.removedInfo.removedPackage != null; 1744 1745 // If this is the first time we have child packages for a disabled privileged 1746 // app that had no children, we grant requested runtime permissions to the new 1747 // children if the parent on the system image had them already granted. 1748 if (res.pkg.parentPackage != null) { 1749 synchronized (mPackages) { 1750 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1751 } 1752 } 1753 1754 synchronized (mPackages) { 1755 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1756 } 1757 1758 final String packageName = res.pkg.applicationInfo.packageName; 1759 Bundle extras = new Bundle(1); 1760 extras.putInt(Intent.EXTRA_UID, res.uid); 1761 1762 // Determine the set of users who are adding this package for 1763 // the first time vs. those who are seeing an update. 1764 int[] firstUsers = EMPTY_INT_ARRAY; 1765 int[] updateUsers = EMPTY_INT_ARRAY; 1766 if (res.origUsers == null || res.origUsers.length == 0) { 1767 firstUsers = res.newUsers; 1768 } else { 1769 for (int newUser : res.newUsers) { 1770 boolean isNew = true; 1771 for (int origUser : res.origUsers) { 1772 if (origUser == newUser) { 1773 isNew = false; 1774 break; 1775 } 1776 } 1777 if (isNew) { 1778 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1779 } else { 1780 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1781 } 1782 } 1783 } 1784 1785 // Send installed broadcasts if the install/update is not ephemeral 1786 if (!isEphemeral(res.pkg)) { 1787 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1788 1789 // Send added for users that see the package for the first time 1790 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1791 extras, 0 /*flags*/, null /*targetPackage*/, 1792 null /*finishedReceiver*/, firstUsers); 1793 1794 // Send added for users that don't see the package for the first time 1795 if (update) { 1796 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1797 } 1798 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1799 extras, 0 /*flags*/, null /*targetPackage*/, 1800 null /*finishedReceiver*/, updateUsers); 1801 1802 // Send replaced for users that don't see the package for the first time 1803 if (update) { 1804 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1805 packageName, extras, 0 /*flags*/, 1806 null /*targetPackage*/, null /*finishedReceiver*/, 1807 updateUsers); 1808 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1809 null /*package*/, null /*extras*/, 0 /*flags*/, 1810 packageName /*targetPackage*/, 1811 null /*finishedReceiver*/, updateUsers); 1812 } 1813 1814 // Send broadcast package appeared if forward locked/external for all users 1815 // treat asec-hosted packages like removable media on upgrade 1816 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1817 if (DEBUG_INSTALL) { 1818 Slog.i(TAG, "upgrading pkg " + res.pkg 1819 + " is ASEC-hosted -> AVAILABLE"); 1820 } 1821 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1822 ArrayList<String> pkgList = new ArrayList<>(1); 1823 pkgList.add(packageName); 1824 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1825 } 1826 } 1827 1828 // Work that needs to happen on first install within each user 1829 if (firstUsers != null && firstUsers.length > 0) { 1830 synchronized (mPackages) { 1831 for (int userId : firstUsers) { 1832 // If this app is a browser and it's newly-installed for some 1833 // users, clear any default-browser state in those users. The 1834 // app's nature doesn't depend on the user, so we can just check 1835 // its browser nature in any user and generalize. 1836 if (packageIsBrowser(packageName, userId)) { 1837 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1838 } 1839 1840 // We may also need to apply pending (restored) runtime 1841 // permission grants within these users. 1842 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1843 } 1844 } 1845 } 1846 1847 // Log current value of "unknown sources" setting 1848 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1849 getUnknownSourcesSettings()); 1850 1851 // Force a gc to clear up things 1852 Runtime.getRuntime().gc(); 1853 1854 // Remove the replaced package's older resources safely now 1855 // We delete after a gc for applications on sdcard. 1856 if (res.removedInfo != null && res.removedInfo.args != null) { 1857 synchronized (mInstallLock) { 1858 res.removedInfo.args.doPostDeleteLI(true); 1859 } 1860 } 1861 } 1862 1863 // If someone is watching installs - notify them 1864 if (installObserver != null) { 1865 try { 1866 Bundle extras = extrasForInstallResult(res); 1867 installObserver.onPackageInstalled(res.name, res.returnCode, 1868 res.returnMsg, extras); 1869 } catch (RemoteException e) { 1870 Slog.i(TAG, "Observer no longer exists."); 1871 } 1872 } 1873 } 1874 1875 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1876 PackageParser.Package pkg) { 1877 if (pkg.parentPackage == null) { 1878 return; 1879 } 1880 if (pkg.requestedPermissions == null) { 1881 return; 1882 } 1883 final PackageSetting disabledSysParentPs = mSettings 1884 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1885 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1886 || !disabledSysParentPs.isPrivileged() 1887 || (disabledSysParentPs.childPackageNames != null 1888 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1889 return; 1890 } 1891 final int[] allUserIds = sUserManager.getUserIds(); 1892 final int permCount = pkg.requestedPermissions.size(); 1893 for (int i = 0; i < permCount; i++) { 1894 String permission = pkg.requestedPermissions.get(i); 1895 BasePermission bp = mSettings.mPermissions.get(permission); 1896 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1897 continue; 1898 } 1899 for (int userId : allUserIds) { 1900 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1901 permission, userId)) { 1902 grantRuntimePermission(pkg.packageName, permission, userId); 1903 } 1904 } 1905 } 1906 } 1907 1908 private StorageEventListener mStorageListener = new StorageEventListener() { 1909 @Override 1910 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1911 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1912 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1913 final String volumeUuid = vol.getFsUuid(); 1914 1915 // Clean up any users or apps that were removed or recreated 1916 // while this volume was missing 1917 reconcileUsers(volumeUuid); 1918 reconcileApps(volumeUuid); 1919 1920 // Clean up any install sessions that expired or were 1921 // cancelled while this volume was missing 1922 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1923 1924 loadPrivatePackages(vol); 1925 1926 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1927 unloadPrivatePackages(vol); 1928 } 1929 } 1930 1931 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1932 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1933 updateExternalMediaStatus(true, false); 1934 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1935 updateExternalMediaStatus(false, false); 1936 } 1937 } 1938 } 1939 1940 @Override 1941 public void onVolumeForgotten(String fsUuid) { 1942 if (TextUtils.isEmpty(fsUuid)) { 1943 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1944 return; 1945 } 1946 1947 // Remove any apps installed on the forgotten volume 1948 synchronized (mPackages) { 1949 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1950 for (PackageSetting ps : packages) { 1951 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1952 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1953 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1954 } 1955 1956 mSettings.onVolumeForgotten(fsUuid); 1957 mSettings.writeLPr(); 1958 } 1959 } 1960 }; 1961 1962 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1963 String[] grantedPermissions) { 1964 for (int userId : userIds) { 1965 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1966 } 1967 1968 // We could have touched GID membership, so flush out packages.list 1969 synchronized (mPackages) { 1970 mSettings.writePackageListLPr(); 1971 } 1972 } 1973 1974 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1975 String[] grantedPermissions) { 1976 SettingBase sb = (SettingBase) pkg.mExtras; 1977 if (sb == null) { 1978 return; 1979 } 1980 1981 PermissionsState permissionsState = sb.getPermissionsState(); 1982 1983 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1984 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1985 1986 synchronized (mPackages) { 1987 for (String permission : pkg.requestedPermissions) { 1988 BasePermission bp = mSettings.mPermissions.get(permission); 1989 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1990 && (grantedPermissions == null 1991 || ArrayUtils.contains(grantedPermissions, permission))) { 1992 final int flags = permissionsState.getPermissionFlags(permission, userId); 1993 // Installer cannot change immutable permissions. 1994 if ((flags & immutableFlags) == 0) { 1995 grantRuntimePermission(pkg.packageName, permission, userId); 1996 } 1997 } 1998 } 1999 } 2000 } 2001 2002 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2003 Bundle extras = null; 2004 switch (res.returnCode) { 2005 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2006 extras = new Bundle(); 2007 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2008 res.origPermission); 2009 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2010 res.origPackage); 2011 break; 2012 } 2013 case PackageManager.INSTALL_SUCCEEDED: { 2014 extras = new Bundle(); 2015 extras.putBoolean(Intent.EXTRA_REPLACING, 2016 res.removedInfo != null && res.removedInfo.removedPackage != null); 2017 break; 2018 } 2019 } 2020 return extras; 2021 } 2022 2023 void scheduleWriteSettingsLocked() { 2024 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2025 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2026 } 2027 } 2028 2029 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2030 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2031 scheduleWritePackageRestrictionsLocked(userId); 2032 } 2033 2034 void scheduleWritePackageRestrictionsLocked(int userId) { 2035 final int[] userIds = (userId == UserHandle.USER_ALL) 2036 ? sUserManager.getUserIds() : new int[]{userId}; 2037 for (int nextUserId : userIds) { 2038 if (!sUserManager.exists(nextUserId)) return; 2039 mDirtyUsers.add(nextUserId); 2040 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2041 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2042 } 2043 } 2044 } 2045 2046 public static PackageManagerService main(Context context, Installer installer, 2047 boolean factoryTest, boolean onlyCore) { 2048 // Self-check for initial settings. 2049 PackageManagerServiceCompilerMapping.checkProperties(); 2050 2051 PackageManagerService m = new PackageManagerService(context, installer, 2052 factoryTest, onlyCore); 2053 m.enableSystemUserPackages(); 2054 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2055 // disabled after already being started. 2056 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2057 UserHandle.USER_SYSTEM); 2058 ServiceManager.addService("package", m); 2059 return m; 2060 } 2061 2062 private void enableSystemUserPackages() { 2063 if (!UserManager.isSplitSystemUser()) { 2064 return; 2065 } 2066 // For system user, enable apps based on the following conditions: 2067 // - app is whitelisted or belong to one of these groups: 2068 // -- system app which has no launcher icons 2069 // -- system app which has INTERACT_ACROSS_USERS permission 2070 // -- system IME app 2071 // - app is not in the blacklist 2072 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2073 Set<String> enableApps = new ArraySet<>(); 2074 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2075 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2076 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2077 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2078 enableApps.addAll(wlApps); 2079 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2080 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2081 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2082 enableApps.removeAll(blApps); 2083 Log.i(TAG, "Applications installed for system user: " + enableApps); 2084 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2085 UserHandle.SYSTEM); 2086 final int allAppsSize = allAps.size(); 2087 synchronized (mPackages) { 2088 for (int i = 0; i < allAppsSize; i++) { 2089 String pName = allAps.get(i); 2090 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2091 // Should not happen, but we shouldn't be failing if it does 2092 if (pkgSetting == null) { 2093 continue; 2094 } 2095 boolean install = enableApps.contains(pName); 2096 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2097 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2098 + " for system user"); 2099 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2100 } 2101 } 2102 } 2103 } 2104 2105 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2106 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2107 Context.DISPLAY_SERVICE); 2108 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2109 } 2110 2111 public PackageManagerService(Context context, Installer installer, 2112 boolean factoryTest, boolean onlyCore) { 2113 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2114 SystemClock.uptimeMillis()); 2115 2116 if (mSdkVersion <= 0) { 2117 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2118 } 2119 2120 mContext = context; 2121 mFactoryTest = factoryTest; 2122 mOnlyCore = onlyCore; 2123 mMetrics = new DisplayMetrics(); 2124 mSettings = new Settings(mPackages); 2125 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2126 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2127 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2128 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2129 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2130 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2131 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2132 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2133 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2134 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2135 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2136 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2137 2138 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2139 if (separateProcesses != null && separateProcesses.length() > 0) { 2140 if ("*".equals(separateProcesses)) { 2141 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2142 mSeparateProcesses = null; 2143 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2144 } else { 2145 mDefParseFlags = 0; 2146 mSeparateProcesses = separateProcesses.split(","); 2147 Slog.w(TAG, "Running with debug.separate_processes: " 2148 + separateProcesses); 2149 } 2150 } else { 2151 mDefParseFlags = 0; 2152 mSeparateProcesses = null; 2153 } 2154 2155 mInstaller = installer; 2156 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2157 "*dexopt*"); 2158 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2159 2160 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2161 FgThread.get().getLooper()); 2162 2163 getDefaultDisplayMetrics(context, mMetrics); 2164 2165 SystemConfig systemConfig = SystemConfig.getInstance(); 2166 mGlobalGids = systemConfig.getGlobalGids(); 2167 mSystemPermissions = systemConfig.getSystemPermissions(); 2168 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2169 2170 synchronized (mInstallLock) { 2171 // writer 2172 synchronized (mPackages) { 2173 mHandlerThread = new ServiceThread(TAG, 2174 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2175 mHandlerThread.start(); 2176 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2177 mProcessLoggingHandler = new ProcessLoggingHandler(); 2178 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2179 2180 File dataDir = Environment.getDataDirectory(); 2181 mAppInstallDir = new File(dataDir, "app"); 2182 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2183 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2184 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2185 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2186 2187 sUserManager = new UserManagerService(context, this, mPackages); 2188 2189 // Propagate permission configuration in to package manager. 2190 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2191 = systemConfig.getPermissions(); 2192 for (int i=0; i<permConfig.size(); i++) { 2193 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2194 BasePermission bp = mSettings.mPermissions.get(perm.name); 2195 if (bp == null) { 2196 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2197 mSettings.mPermissions.put(perm.name, bp); 2198 } 2199 if (perm.gids != null) { 2200 bp.setGids(perm.gids, perm.perUser); 2201 } 2202 } 2203 2204 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2205 for (int i=0; i<libConfig.size(); i++) { 2206 mSharedLibraries.put(libConfig.keyAt(i), 2207 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2208 } 2209 2210 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2211 2212 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2213 2214 String customResolverActivity = Resources.getSystem().getString( 2215 R.string.config_customResolverActivity); 2216 if (TextUtils.isEmpty(customResolverActivity)) { 2217 customResolverActivity = null; 2218 } else { 2219 mCustomResolverComponentName = ComponentName.unflattenFromString( 2220 customResolverActivity); 2221 } 2222 2223 long startTime = SystemClock.uptimeMillis(); 2224 2225 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2226 startTime); 2227 2228 // Set flag to monitor and not change apk file paths when 2229 // scanning install directories. 2230 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2231 2232 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2233 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2234 2235 if (bootClassPath == null) { 2236 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2237 } 2238 2239 if (systemServerClassPath == null) { 2240 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2241 } 2242 2243 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2244 final String[] dexCodeInstructionSets = 2245 getDexCodeInstructionSets( 2246 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2247 2248 /** 2249 * Ensure all external libraries have had dexopt run on them. 2250 */ 2251 if (mSharedLibraries.size() > 0) { 2252 // NOTE: For now, we're compiling these system "shared libraries" 2253 // (and framework jars) into all available architectures. It's possible 2254 // to compile them only when we come across an app that uses them (there's 2255 // already logic for that in scanPackageLI) but that adds some complexity. 2256 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2257 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2258 final String lib = libEntry.path; 2259 if (lib == null) { 2260 continue; 2261 } 2262 2263 try { 2264 // Shared libraries do not have profiles so we perform a full 2265 // AOT compilation (if needed). 2266 int dexoptNeeded = DexFile.getDexOptNeeded( 2267 lib, dexCodeInstructionSet, 2268 getCompilerFilterForReason(REASON_SHARED_APK), 2269 false /* newProfile */); 2270 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2271 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2272 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2273 getCompilerFilterForReason(REASON_SHARED_APK), 2274 StorageManager.UUID_PRIVATE_INTERNAL); 2275 } 2276 } catch (FileNotFoundException e) { 2277 Slog.w(TAG, "Library not found: " + lib); 2278 } catch (IOException | InstallerException e) { 2279 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2280 + e.getMessage()); 2281 } 2282 } 2283 } 2284 } 2285 2286 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2287 2288 final VersionInfo ver = mSettings.getInternalVersion(); 2289 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2290 2291 // when upgrading from pre-M, promote system app permissions from install to runtime 2292 mPromoteSystemApps = 2293 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2294 2295 // save off the names of pre-existing system packages prior to scanning; we don't 2296 // want to automatically grant runtime permissions for new system apps 2297 if (mPromoteSystemApps) { 2298 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2299 while (pkgSettingIter.hasNext()) { 2300 PackageSetting ps = pkgSettingIter.next(); 2301 if (isSystemApp(ps)) { 2302 mExistingSystemPackages.add(ps.name); 2303 } 2304 } 2305 } 2306 2307 // When upgrading from pre-N, we need to handle package extraction like first boot, 2308 // as there is no profiling data available. 2309 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2310 mSettings.setNWorkDone(); 2311 2312 // Collect vendor overlay packages. 2313 // (Do this before scanning any apps.) 2314 // For security and version matching reason, only consider 2315 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2316 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2317 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2318 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2319 2320 // Find base frameworks (resource packages without code). 2321 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2322 | PackageParser.PARSE_IS_SYSTEM_DIR 2323 | PackageParser.PARSE_IS_PRIVILEGED, 2324 scanFlags | SCAN_NO_DEX, 0); 2325 2326 // Collected privileged system packages. 2327 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2328 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2329 | PackageParser.PARSE_IS_SYSTEM_DIR 2330 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2331 2332 // Collect ordinary system packages. 2333 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2334 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2335 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2336 2337 // Collect all vendor packages. 2338 File vendorAppDir = new File("/vendor/app"); 2339 try { 2340 vendorAppDir = vendorAppDir.getCanonicalFile(); 2341 } catch (IOException e) { 2342 // failed to look up canonical path, continue with original one 2343 } 2344 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2345 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2346 2347 // Collect all OEM packages. 2348 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2349 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2350 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2351 2352 // Prune any system packages that no longer exist. 2353 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2354 if (!mOnlyCore) { 2355 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2356 while (psit.hasNext()) { 2357 PackageSetting ps = psit.next(); 2358 2359 /* 2360 * If this is not a system app, it can't be a 2361 * disable system app. 2362 */ 2363 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2364 continue; 2365 } 2366 2367 /* 2368 * If the package is scanned, it's not erased. 2369 */ 2370 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2371 if (scannedPkg != null) { 2372 /* 2373 * If the system app is both scanned and in the 2374 * disabled packages list, then it must have been 2375 * added via OTA. Remove it from the currently 2376 * scanned package so the previously user-installed 2377 * application can be scanned. 2378 */ 2379 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2380 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2381 + ps.name + "; removing system app. Last known codePath=" 2382 + ps.codePathString + ", installStatus=" + ps.installStatus 2383 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2384 + scannedPkg.mVersionCode); 2385 removePackageLI(scannedPkg, true); 2386 mExpectingBetter.put(ps.name, ps.codePath); 2387 } 2388 2389 continue; 2390 } 2391 2392 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2393 psit.remove(); 2394 logCriticalInfo(Log.WARN, "System package " + ps.name 2395 + " no longer exists; it's data will be wiped"); 2396 // Actual deletion of code and data will be handled by later 2397 // reconciliation step 2398 } else { 2399 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2400 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2401 possiblyDeletedUpdatedSystemApps.add(ps.name); 2402 } 2403 } 2404 } 2405 } 2406 2407 //look for any incomplete package installations 2408 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2409 for (int i = 0; i < deletePkgsList.size(); i++) { 2410 // Actual deletion of code and data will be handled by later 2411 // reconciliation step 2412 final String packageName = deletePkgsList.get(i).name; 2413 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2414 synchronized (mPackages) { 2415 mSettings.removePackageLPw(packageName); 2416 } 2417 } 2418 2419 //delete tmp files 2420 deleteTempPackageFiles(); 2421 2422 // Remove any shared userIDs that have no associated packages 2423 mSettings.pruneSharedUsersLPw(); 2424 2425 if (!mOnlyCore) { 2426 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2427 SystemClock.uptimeMillis()); 2428 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2429 2430 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2431 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2432 2433 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2434 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2435 2436 /** 2437 * Remove disable package settings for any updated system 2438 * apps that were removed via an OTA. If they're not a 2439 * previously-updated app, remove them completely. 2440 * Otherwise, just revoke their system-level permissions. 2441 */ 2442 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2443 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2444 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2445 2446 String msg; 2447 if (deletedPkg == null) { 2448 msg = "Updated system package " + deletedAppName 2449 + " no longer exists; it's data will be wiped"; 2450 // Actual deletion of code and data will be handled by later 2451 // reconciliation step 2452 } else { 2453 msg = "Updated system app + " + deletedAppName 2454 + " no longer present; removing system privileges for " 2455 + deletedAppName; 2456 2457 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2458 2459 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2460 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2461 } 2462 logCriticalInfo(Log.WARN, msg); 2463 } 2464 2465 /** 2466 * Make sure all system apps that we expected to appear on 2467 * the userdata partition actually showed up. If they never 2468 * appeared, crawl back and revive the system version. 2469 */ 2470 for (int i = 0; i < mExpectingBetter.size(); i++) { 2471 final String packageName = mExpectingBetter.keyAt(i); 2472 if (!mPackages.containsKey(packageName)) { 2473 final File scanFile = mExpectingBetter.valueAt(i); 2474 2475 logCriticalInfo(Log.WARN, "Expected better " + packageName 2476 + " but never showed up; reverting to system"); 2477 2478 final int reparseFlags; 2479 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2480 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2481 | PackageParser.PARSE_IS_SYSTEM_DIR 2482 | PackageParser.PARSE_IS_PRIVILEGED; 2483 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2484 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2485 | PackageParser.PARSE_IS_SYSTEM_DIR; 2486 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2487 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2488 | PackageParser.PARSE_IS_SYSTEM_DIR; 2489 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2490 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2491 | PackageParser.PARSE_IS_SYSTEM_DIR; 2492 } else { 2493 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2494 continue; 2495 } 2496 2497 mSettings.enableSystemPackageLPw(packageName); 2498 2499 try { 2500 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2501 } catch (PackageManagerException e) { 2502 Slog.e(TAG, "Failed to parse original system package: " 2503 + e.getMessage()); 2504 } 2505 } 2506 } 2507 } 2508 mExpectingBetter.clear(); 2509 2510 // Resolve protected action filters. Only the setup wizard is allowed to 2511 // have a high priority filter for these actions. 2512 mSetupWizardPackage = getSetupWizardPackageName(); 2513 if (mProtectedFilters.size() > 0) { 2514 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2515 Slog.i(TAG, "No setup wizard;" 2516 + " All protected intents capped to priority 0"); 2517 } 2518 for (ActivityIntentInfo filter : mProtectedFilters) { 2519 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2520 if (DEBUG_FILTERS) { 2521 Slog.i(TAG, "Found setup wizard;" 2522 + " allow priority " + filter.getPriority() + ";" 2523 + " package: " + filter.activity.info.packageName 2524 + " activity: " + filter.activity.className 2525 + " priority: " + filter.getPriority()); 2526 } 2527 // skip setup wizard; allow it to keep the high priority filter 2528 continue; 2529 } 2530 Slog.w(TAG, "Protected action; cap priority to 0;" 2531 + " package: " + filter.activity.info.packageName 2532 + " activity: " + filter.activity.className 2533 + " origPrio: " + filter.getPriority()); 2534 filter.setPriority(0); 2535 } 2536 } 2537 mDeferProtectedFilters = false; 2538 mProtectedFilters.clear(); 2539 2540 // Now that we know all of the shared libraries, update all clients to have 2541 // the correct library paths. 2542 updateAllSharedLibrariesLPw(); 2543 2544 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2545 // NOTE: We ignore potential failures here during a system scan (like 2546 // the rest of the commands above) because there's precious little we 2547 // can do about it. A settings error is reported, though. 2548 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2549 false /* boot complete */); 2550 } 2551 2552 // Now that we know all the packages we are keeping, 2553 // read and update their last usage times. 2554 mPackageUsage.readLP(); 2555 2556 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2557 SystemClock.uptimeMillis()); 2558 Slog.i(TAG, "Time to scan packages: " 2559 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2560 + " seconds"); 2561 2562 // If the platform SDK has changed since the last time we booted, 2563 // we need to re-grant app permission to catch any new ones that 2564 // appear. This is really a hack, and means that apps can in some 2565 // cases get permissions that the user didn't initially explicitly 2566 // allow... it would be nice to have some better way to handle 2567 // this situation. 2568 int updateFlags = UPDATE_PERMISSIONS_ALL; 2569 if (ver.sdkVersion != mSdkVersion) { 2570 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2571 + mSdkVersion + "; regranting permissions for internal storage"); 2572 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2573 } 2574 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2575 ver.sdkVersion = mSdkVersion; 2576 2577 // If this is the first boot or an update from pre-M, and it is a normal 2578 // boot, then we need to initialize the default preferred apps across 2579 // all defined users. 2580 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2581 for (UserInfo user : sUserManager.getUsers(true)) { 2582 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2583 applyFactoryDefaultBrowserLPw(user.id); 2584 primeDomainVerificationsLPw(user.id); 2585 } 2586 } 2587 2588 // Prepare storage for system user really early during boot, 2589 // since core system apps like SettingsProvider and SystemUI 2590 // can't wait for user to start 2591 final int storageFlags; 2592 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2593 storageFlags = StorageManager.FLAG_STORAGE_DE; 2594 } else { 2595 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2596 } 2597 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2598 storageFlags); 2599 2600 // If this is first boot after an OTA, and a normal boot, then 2601 // we need to clear code cache directories. 2602 if (mIsUpgrade && !onlyCore) { 2603 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2604 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2605 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2606 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2607 // No apps are running this early, so no need to freeze 2608 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2609 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2610 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2611 } 2612 clearAppProfilesLIF(ps.pkg); 2613 } 2614 ver.fingerprint = Build.FINGERPRINT; 2615 } 2616 2617 checkDefaultBrowser(); 2618 2619 // clear only after permissions and other defaults have been updated 2620 mExistingSystemPackages.clear(); 2621 mPromoteSystemApps = false; 2622 2623 // All the changes are done during package scanning. 2624 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2625 2626 // can downgrade to reader 2627 mSettings.writeLPr(); 2628 2629 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2630 SystemClock.uptimeMillis()); 2631 2632 if (!mOnlyCore) { 2633 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2634 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2635 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2636 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2637 mIntentFilterVerifierComponent); 2638 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2639 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2640 getRequiredSharedLibraryLPr( 2641 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2642 } else { 2643 mRequiredVerifierPackage = null; 2644 mRequiredInstallerPackage = null; 2645 mIntentFilterVerifierComponent = null; 2646 mIntentFilterVerifier = null; 2647 mServicesSystemSharedLibraryPackageName = null; 2648 } 2649 2650 mInstallerService = new PackageInstallerService(context, this); 2651 2652 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2653 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2654 // both the installer and resolver must be present to enable ephemeral 2655 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2656 if (DEBUG_EPHEMERAL) { 2657 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2658 + " installer:" + ephemeralInstallerComponent); 2659 } 2660 mEphemeralResolverComponent = ephemeralResolverComponent; 2661 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2662 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2663 mEphemeralResolverConnection = 2664 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2665 } else { 2666 if (DEBUG_EPHEMERAL) { 2667 final String missingComponent = 2668 (ephemeralResolverComponent == null) 2669 ? (ephemeralInstallerComponent == null) 2670 ? "resolver and installer" 2671 : "resolver" 2672 : "installer"; 2673 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2674 } 2675 mEphemeralResolverComponent = null; 2676 mEphemeralInstallerComponent = null; 2677 mEphemeralResolverConnection = null; 2678 } 2679 2680 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2681 } // synchronized (mPackages) 2682 } // synchronized (mInstallLock) 2683 2684 // Now after opening every single application zip, make sure they 2685 // are all flushed. Not really needed, but keeps things nice and 2686 // tidy. 2687 Runtime.getRuntime().gc(); 2688 2689 // The initial scanning above does many calls into installd while 2690 // holding the mPackages lock, but we're mostly interested in yelling 2691 // once we have a booted system. 2692 mInstaller.setWarnIfHeld(mPackages); 2693 2694 // Expose private service for system components to use. 2695 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2696 } 2697 2698 @Override 2699 public boolean isFirstBoot() { 2700 return !mRestoredSettings; 2701 } 2702 2703 @Override 2704 public boolean isOnlyCoreApps() { 2705 return mOnlyCore; 2706 } 2707 2708 @Override 2709 public boolean isUpgrade() { 2710 return mIsUpgrade; 2711 } 2712 2713 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2714 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2715 2716 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2717 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2718 UserHandle.USER_SYSTEM); 2719 if (matches.size() == 1) { 2720 return matches.get(0).getComponentInfo().packageName; 2721 } else { 2722 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2723 return null; 2724 } 2725 } 2726 2727 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2728 synchronized (mPackages) { 2729 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2730 if (libraryEntry == null) { 2731 throw new IllegalStateException("Missing required shared library:" + libraryName); 2732 } 2733 return libraryEntry.apk; 2734 } 2735 } 2736 2737 private @NonNull String getRequiredInstallerLPr() { 2738 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2739 intent.addCategory(Intent.CATEGORY_DEFAULT); 2740 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2741 2742 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2743 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2744 UserHandle.USER_SYSTEM); 2745 if (matches.size() == 1) { 2746 ResolveInfo resolveInfo = matches.get(0); 2747 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2748 throw new RuntimeException("The installer must be a privileged app"); 2749 } 2750 return matches.get(0).getComponentInfo().packageName; 2751 } else { 2752 throw new RuntimeException("There must be exactly one installer; found " + matches); 2753 } 2754 } 2755 2756 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2757 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2758 2759 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2760 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2761 UserHandle.USER_SYSTEM); 2762 ResolveInfo best = null; 2763 final int N = matches.size(); 2764 for (int i = 0; i < N; i++) { 2765 final ResolveInfo cur = matches.get(i); 2766 final String packageName = cur.getComponentInfo().packageName; 2767 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2768 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2769 continue; 2770 } 2771 2772 if (best == null || cur.priority > best.priority) { 2773 best = cur; 2774 } 2775 } 2776 2777 if (best != null) { 2778 return best.getComponentInfo().getComponentName(); 2779 } else { 2780 throw new RuntimeException("There must be at least one intent filter verifier"); 2781 } 2782 } 2783 2784 private @Nullable ComponentName getEphemeralResolverLPr() { 2785 final String[] packageArray = 2786 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2787 if (packageArray.length == 0) { 2788 if (DEBUG_EPHEMERAL) { 2789 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2790 } 2791 return null; 2792 } 2793 2794 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2795 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2796 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2797 UserHandle.USER_SYSTEM); 2798 2799 final int N = resolvers.size(); 2800 if (N == 0) { 2801 if (DEBUG_EPHEMERAL) { 2802 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2803 } 2804 return null; 2805 } 2806 2807 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2808 for (int i = 0; i < N; i++) { 2809 final ResolveInfo info = resolvers.get(i); 2810 2811 if (info.serviceInfo == null) { 2812 continue; 2813 } 2814 2815 final String packageName = info.serviceInfo.packageName; 2816 if (!possiblePackages.contains(packageName)) { 2817 if (DEBUG_EPHEMERAL) { 2818 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2819 + " pkg: " + packageName + ", info:" + info); 2820 } 2821 continue; 2822 } 2823 2824 if (DEBUG_EPHEMERAL) { 2825 Slog.v(TAG, "Ephemeral resolver found;" 2826 + " pkg: " + packageName + ", info:" + info); 2827 } 2828 return new ComponentName(packageName, info.serviceInfo.name); 2829 } 2830 if (DEBUG_EPHEMERAL) { 2831 Slog.v(TAG, "Ephemeral resolver NOT found"); 2832 } 2833 return null; 2834 } 2835 2836 private @Nullable ComponentName getEphemeralInstallerLPr() { 2837 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2838 intent.addCategory(Intent.CATEGORY_DEFAULT); 2839 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2840 2841 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2842 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2843 UserHandle.USER_SYSTEM); 2844 if (matches.size() == 0) { 2845 return null; 2846 } else if (matches.size() == 1) { 2847 return matches.get(0).getComponentInfo().getComponentName(); 2848 } else { 2849 throw new RuntimeException( 2850 "There must be at most one ephemeral installer; found " + matches); 2851 } 2852 } 2853 2854 private void primeDomainVerificationsLPw(int userId) { 2855 if (DEBUG_DOMAIN_VERIFICATION) { 2856 Slog.d(TAG, "Priming domain verifications in user " + userId); 2857 } 2858 2859 SystemConfig systemConfig = SystemConfig.getInstance(); 2860 ArraySet<String> packages = systemConfig.getLinkedApps(); 2861 ArraySet<String> domains = new ArraySet<String>(); 2862 2863 for (String packageName : packages) { 2864 PackageParser.Package pkg = mPackages.get(packageName); 2865 if (pkg != null) { 2866 if (!pkg.isSystemApp()) { 2867 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2868 continue; 2869 } 2870 2871 domains.clear(); 2872 for (PackageParser.Activity a : pkg.activities) { 2873 for (ActivityIntentInfo filter : a.intents) { 2874 if (hasValidDomains(filter)) { 2875 domains.addAll(filter.getHostsList()); 2876 } 2877 } 2878 } 2879 2880 if (domains.size() > 0) { 2881 if (DEBUG_DOMAIN_VERIFICATION) { 2882 Slog.v(TAG, " + " + packageName); 2883 } 2884 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2885 // state w.r.t. the formal app-linkage "no verification attempted" state; 2886 // and then 'always' in the per-user state actually used for intent resolution. 2887 final IntentFilterVerificationInfo ivi; 2888 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2889 new ArrayList<String>(domains)); 2890 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2891 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2892 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2893 } else { 2894 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2895 + "' does not handle web links"); 2896 } 2897 } else { 2898 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2899 } 2900 } 2901 2902 scheduleWritePackageRestrictionsLocked(userId); 2903 scheduleWriteSettingsLocked(); 2904 } 2905 2906 private void applyFactoryDefaultBrowserLPw(int userId) { 2907 // The default browser app's package name is stored in a string resource, 2908 // with a product-specific overlay used for vendor customization. 2909 String browserPkg = mContext.getResources().getString( 2910 com.android.internal.R.string.default_browser); 2911 if (!TextUtils.isEmpty(browserPkg)) { 2912 // non-empty string => required to be a known package 2913 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2914 if (ps == null) { 2915 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2916 browserPkg = null; 2917 } else { 2918 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2919 } 2920 } 2921 2922 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2923 // default. If there's more than one, just leave everything alone. 2924 if (browserPkg == null) { 2925 calculateDefaultBrowserLPw(userId); 2926 } 2927 } 2928 2929 private void calculateDefaultBrowserLPw(int userId) { 2930 List<String> allBrowsers = resolveAllBrowserApps(userId); 2931 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2932 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2933 } 2934 2935 private List<String> resolveAllBrowserApps(int userId) { 2936 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2937 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2938 PackageManager.MATCH_ALL, userId); 2939 2940 final int count = list.size(); 2941 List<String> result = new ArrayList<String>(count); 2942 for (int i=0; i<count; i++) { 2943 ResolveInfo info = list.get(i); 2944 if (info.activityInfo == null 2945 || !info.handleAllWebDataURI 2946 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2947 || result.contains(info.activityInfo.packageName)) { 2948 continue; 2949 } 2950 result.add(info.activityInfo.packageName); 2951 } 2952 2953 return result; 2954 } 2955 2956 private boolean packageIsBrowser(String packageName, int userId) { 2957 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2958 PackageManager.MATCH_ALL, userId); 2959 final int N = list.size(); 2960 for (int i = 0; i < N; i++) { 2961 ResolveInfo info = list.get(i); 2962 if (packageName.equals(info.activityInfo.packageName)) { 2963 return true; 2964 } 2965 } 2966 return false; 2967 } 2968 2969 private void checkDefaultBrowser() { 2970 final int myUserId = UserHandle.myUserId(); 2971 final String packageName = getDefaultBrowserPackageName(myUserId); 2972 if (packageName != null) { 2973 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2974 if (info == null) { 2975 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2976 synchronized (mPackages) { 2977 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2978 } 2979 } 2980 } 2981 } 2982 2983 @Override 2984 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2985 throws RemoteException { 2986 try { 2987 return super.onTransact(code, data, reply, flags); 2988 } catch (RuntimeException e) { 2989 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2990 Slog.wtf(TAG, "Package Manager Crash", e); 2991 } 2992 throw e; 2993 } 2994 } 2995 2996 static int[] appendInts(int[] cur, int[] add) { 2997 if (add == null) return cur; 2998 if (cur == null) return add; 2999 final int N = add.length; 3000 for (int i=0; i<N; i++) { 3001 cur = appendInt(cur, add[i]); 3002 } 3003 return cur; 3004 } 3005 3006 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3007 if (!sUserManager.exists(userId)) return null; 3008 if (ps == null) { 3009 return null; 3010 } 3011 final PackageParser.Package p = ps.pkg; 3012 if (p == null) { 3013 return null; 3014 } 3015 3016 final PermissionsState permissionsState = ps.getPermissionsState(); 3017 3018 final int[] gids = permissionsState.computeGids(userId); 3019 final Set<String> permissions = permissionsState.getPermissions(userId); 3020 final PackageUserState state = ps.readUserState(userId); 3021 3022 return PackageParser.generatePackageInfo(p, gids, flags, 3023 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3024 } 3025 3026 @Override 3027 public void checkPackageStartable(String packageName, int userId) { 3028 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3029 3030 synchronized (mPackages) { 3031 final PackageSetting ps = mSettings.mPackages.get(packageName); 3032 if (ps == null) { 3033 throw new SecurityException("Package " + packageName + " was not found!"); 3034 } 3035 3036 if (!ps.getInstalled(userId)) { 3037 throw new SecurityException( 3038 "Package " + packageName + " was not installed for user " + userId + "!"); 3039 } 3040 3041 if (mSafeMode && !ps.isSystem()) { 3042 throw new SecurityException("Package " + packageName + " not a system app!"); 3043 } 3044 3045 if (mFrozenPackages.contains(packageName)) { 3046 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3047 } 3048 3049 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3050 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3051 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3052 } 3053 } 3054 } 3055 3056 @Override 3057 public boolean isPackageAvailable(String packageName, int userId) { 3058 if (!sUserManager.exists(userId)) return false; 3059 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3060 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3061 synchronized (mPackages) { 3062 PackageParser.Package p = mPackages.get(packageName); 3063 if (p != null) { 3064 final PackageSetting ps = (PackageSetting) p.mExtras; 3065 if (ps != null) { 3066 final PackageUserState state = ps.readUserState(userId); 3067 if (state != null) { 3068 return PackageParser.isAvailable(state); 3069 } 3070 } 3071 } 3072 } 3073 return false; 3074 } 3075 3076 @Override 3077 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3078 if (!sUserManager.exists(userId)) return null; 3079 flags = updateFlagsForPackage(flags, userId, packageName); 3080 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3081 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3082 // reader 3083 synchronized (mPackages) { 3084 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3085 PackageParser.Package p = null; 3086 if (matchFactoryOnly) { 3087 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3088 if (ps != null) { 3089 return generatePackageInfo(ps, flags, userId); 3090 } 3091 } 3092 if (p == null) { 3093 p = mPackages.get(packageName); 3094 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3095 return null; 3096 } 3097 } 3098 if (DEBUG_PACKAGE_INFO) 3099 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3100 if (p != null) { 3101 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3102 } 3103 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3104 final PackageSetting ps = mSettings.mPackages.get(packageName); 3105 return generatePackageInfo(ps, flags, userId); 3106 } 3107 } 3108 return null; 3109 } 3110 3111 @Override 3112 public String[] currentToCanonicalPackageNames(String[] names) { 3113 String[] out = new String[names.length]; 3114 // reader 3115 synchronized (mPackages) { 3116 for (int i=names.length-1; i>=0; i--) { 3117 PackageSetting ps = mSettings.mPackages.get(names[i]); 3118 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3119 } 3120 } 3121 return out; 3122 } 3123 3124 @Override 3125 public String[] canonicalToCurrentPackageNames(String[] names) { 3126 String[] out = new String[names.length]; 3127 // reader 3128 synchronized (mPackages) { 3129 for (int i=names.length-1; i>=0; i--) { 3130 String cur = mSettings.mRenamedPackages.get(names[i]); 3131 out[i] = cur != null ? cur : names[i]; 3132 } 3133 } 3134 return out; 3135 } 3136 3137 @Override 3138 public int getPackageUid(String packageName, int flags, int userId) { 3139 if (!sUserManager.exists(userId)) return -1; 3140 flags = updateFlagsForPackage(flags, userId, packageName); 3141 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3142 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3143 3144 // reader 3145 synchronized (mPackages) { 3146 final PackageParser.Package p = mPackages.get(packageName); 3147 if (p != null && p.isMatch(flags)) { 3148 return UserHandle.getUid(userId, p.applicationInfo.uid); 3149 } 3150 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3151 final PackageSetting ps = mSettings.mPackages.get(packageName); 3152 if (ps != null && ps.isMatch(flags)) { 3153 return UserHandle.getUid(userId, ps.appId); 3154 } 3155 } 3156 } 3157 3158 return -1; 3159 } 3160 3161 @Override 3162 public int[] getPackageGids(String packageName, int flags, int userId) { 3163 if (!sUserManager.exists(userId)) return null; 3164 flags = updateFlagsForPackage(flags, userId, packageName); 3165 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3166 false /* requireFullPermission */, false /* checkShell */, 3167 "getPackageGids"); 3168 3169 // reader 3170 synchronized (mPackages) { 3171 final PackageParser.Package p = mPackages.get(packageName); 3172 if (p != null && p.isMatch(flags)) { 3173 PackageSetting ps = (PackageSetting) p.mExtras; 3174 return ps.getPermissionsState().computeGids(userId); 3175 } 3176 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3177 final PackageSetting ps = mSettings.mPackages.get(packageName); 3178 if (ps != null && ps.isMatch(flags)) { 3179 return ps.getPermissionsState().computeGids(userId); 3180 } 3181 } 3182 } 3183 3184 return null; 3185 } 3186 3187 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3188 if (bp.perm != null) { 3189 return PackageParser.generatePermissionInfo(bp.perm, flags); 3190 } 3191 PermissionInfo pi = new PermissionInfo(); 3192 pi.name = bp.name; 3193 pi.packageName = bp.sourcePackage; 3194 pi.nonLocalizedLabel = bp.name; 3195 pi.protectionLevel = bp.protectionLevel; 3196 return pi; 3197 } 3198 3199 @Override 3200 public PermissionInfo getPermissionInfo(String name, int flags) { 3201 // reader 3202 synchronized (mPackages) { 3203 final BasePermission p = mSettings.mPermissions.get(name); 3204 if (p != null) { 3205 return generatePermissionInfo(p, flags); 3206 } 3207 return null; 3208 } 3209 } 3210 3211 @Override 3212 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3213 int flags) { 3214 // reader 3215 synchronized (mPackages) { 3216 if (group != null && !mPermissionGroups.containsKey(group)) { 3217 // This is thrown as NameNotFoundException 3218 return null; 3219 } 3220 3221 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3222 for (BasePermission p : mSettings.mPermissions.values()) { 3223 if (group == null) { 3224 if (p.perm == null || p.perm.info.group == null) { 3225 out.add(generatePermissionInfo(p, flags)); 3226 } 3227 } else { 3228 if (p.perm != null && group.equals(p.perm.info.group)) { 3229 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3230 } 3231 } 3232 } 3233 return new ParceledListSlice<>(out); 3234 } 3235 } 3236 3237 @Override 3238 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3239 // reader 3240 synchronized (mPackages) { 3241 return PackageParser.generatePermissionGroupInfo( 3242 mPermissionGroups.get(name), flags); 3243 } 3244 } 3245 3246 @Override 3247 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3248 // reader 3249 synchronized (mPackages) { 3250 final int N = mPermissionGroups.size(); 3251 ArrayList<PermissionGroupInfo> out 3252 = new ArrayList<PermissionGroupInfo>(N); 3253 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3254 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3255 } 3256 return new ParceledListSlice<>(out); 3257 } 3258 } 3259 3260 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3261 int userId) { 3262 if (!sUserManager.exists(userId)) return null; 3263 PackageSetting ps = mSettings.mPackages.get(packageName); 3264 if (ps != null) { 3265 if (ps.pkg == null) { 3266 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3267 if (pInfo != null) { 3268 return pInfo.applicationInfo; 3269 } 3270 return null; 3271 } 3272 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3273 ps.readUserState(userId), userId); 3274 } 3275 return null; 3276 } 3277 3278 @Override 3279 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3280 if (!sUserManager.exists(userId)) return null; 3281 flags = updateFlagsForApplication(flags, userId, packageName); 3282 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3283 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3284 // writer 3285 synchronized (mPackages) { 3286 PackageParser.Package p = mPackages.get(packageName); 3287 if (DEBUG_PACKAGE_INFO) Log.v( 3288 TAG, "getApplicationInfo " + packageName 3289 + ": " + p); 3290 if (p != null) { 3291 PackageSetting ps = mSettings.mPackages.get(packageName); 3292 if (ps == null) return null; 3293 // Note: isEnabledLP() does not apply here - always return info 3294 return PackageParser.generateApplicationInfo( 3295 p, flags, ps.readUserState(userId), userId); 3296 } 3297 if ("android".equals(packageName)||"system".equals(packageName)) { 3298 return mAndroidApplication; 3299 } 3300 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3301 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3302 } 3303 } 3304 return null; 3305 } 3306 3307 @Override 3308 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3309 final IPackageDataObserver observer) { 3310 mContext.enforceCallingOrSelfPermission( 3311 android.Manifest.permission.CLEAR_APP_CACHE, null); 3312 // Queue up an async operation since clearing cache may take a little while. 3313 mHandler.post(new Runnable() { 3314 public void run() { 3315 mHandler.removeCallbacks(this); 3316 boolean success = true; 3317 synchronized (mInstallLock) { 3318 try { 3319 mInstaller.freeCache(volumeUuid, freeStorageSize); 3320 } catch (InstallerException e) { 3321 Slog.w(TAG, "Couldn't clear application caches: " + e); 3322 success = false; 3323 } 3324 } 3325 if (observer != null) { 3326 try { 3327 observer.onRemoveCompleted(null, success); 3328 } catch (RemoteException e) { 3329 Slog.w(TAG, "RemoveException when invoking call back"); 3330 } 3331 } 3332 } 3333 }); 3334 } 3335 3336 @Override 3337 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3338 final IntentSender pi) { 3339 mContext.enforceCallingOrSelfPermission( 3340 android.Manifest.permission.CLEAR_APP_CACHE, null); 3341 // Queue up an async operation since clearing cache may take a little while. 3342 mHandler.post(new Runnable() { 3343 public void run() { 3344 mHandler.removeCallbacks(this); 3345 boolean success = true; 3346 synchronized (mInstallLock) { 3347 try { 3348 mInstaller.freeCache(volumeUuid, freeStorageSize); 3349 } catch (InstallerException e) { 3350 Slog.w(TAG, "Couldn't clear application caches: " + e); 3351 success = false; 3352 } 3353 } 3354 if(pi != null) { 3355 try { 3356 // Callback via pending intent 3357 int code = success ? 1 : 0; 3358 pi.sendIntent(null, code, null, 3359 null, null); 3360 } catch (SendIntentException e1) { 3361 Slog.i(TAG, "Failed to send pending intent"); 3362 } 3363 } 3364 } 3365 }); 3366 } 3367 3368 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3369 synchronized (mInstallLock) { 3370 try { 3371 mInstaller.freeCache(volumeUuid, freeStorageSize); 3372 } catch (InstallerException e) { 3373 throw new IOException("Failed to free enough space", e); 3374 } 3375 } 3376 } 3377 3378 /** 3379 * Return if the user key is currently unlocked. 3380 */ 3381 private boolean isUserKeyUnlocked(int userId) { 3382 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3383 final IMountService mount = IMountService.Stub 3384 .asInterface(ServiceManager.getService("mount")); 3385 if (mount == null) { 3386 Slog.w(TAG, "Early during boot, assuming locked"); 3387 return false; 3388 } 3389 final long token = Binder.clearCallingIdentity(); 3390 try { 3391 return mount.isUserKeyUnlocked(userId); 3392 } catch (RemoteException e) { 3393 throw e.rethrowAsRuntimeException(); 3394 } finally { 3395 Binder.restoreCallingIdentity(token); 3396 } 3397 } else { 3398 return true; 3399 } 3400 } 3401 3402 /** 3403 * Update given flags based on encryption status of current user. 3404 */ 3405 private int updateFlags(int flags, int userId) { 3406 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3407 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3408 // Caller expressed an explicit opinion about what encryption 3409 // aware/unaware components they want to see, so fall through and 3410 // give them what they want 3411 } else { 3412 // Caller expressed no opinion, so match based on user state 3413 if (isUserKeyUnlocked(userId)) { 3414 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3415 } else { 3416 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3417 } 3418 } 3419 return flags; 3420 } 3421 3422 /** 3423 * Update given flags when being used to request {@link PackageInfo}. 3424 */ 3425 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3426 boolean triaged = true; 3427 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3428 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3429 // Caller is asking for component details, so they'd better be 3430 // asking for specific encryption matching behavior, or be triaged 3431 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3432 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3433 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3434 triaged = false; 3435 } 3436 } 3437 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3438 | PackageManager.MATCH_SYSTEM_ONLY 3439 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3440 triaged = false; 3441 } 3442 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3443 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3444 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3445 } 3446 return updateFlags(flags, userId); 3447 } 3448 3449 /** 3450 * Update given flags when being used to request {@link ApplicationInfo}. 3451 */ 3452 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3453 return updateFlagsForPackage(flags, userId, cookie); 3454 } 3455 3456 /** 3457 * Update given flags when being used to request {@link ComponentInfo}. 3458 */ 3459 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3460 if (cookie instanceof Intent) { 3461 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3462 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3463 } 3464 } 3465 3466 boolean triaged = true; 3467 // Caller is asking for component details, so they'd better be 3468 // asking for specific encryption matching behavior, or be triaged 3469 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3470 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3471 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3472 triaged = false; 3473 } 3474 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3475 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3476 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3477 } 3478 3479 return updateFlags(flags, userId); 3480 } 3481 3482 /** 3483 * Update given flags when being used to request {@link ResolveInfo}. 3484 */ 3485 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3486 // Safe mode means we shouldn't match any third-party components 3487 if (mSafeMode) { 3488 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3489 } 3490 3491 return updateFlagsForComponent(flags, userId, cookie); 3492 } 3493 3494 @Override 3495 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3496 if (!sUserManager.exists(userId)) return null; 3497 flags = updateFlagsForComponent(flags, userId, component); 3498 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3499 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3500 synchronized (mPackages) { 3501 PackageParser.Activity a = mActivities.mActivities.get(component); 3502 3503 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3504 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3505 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3506 if (ps == null) return null; 3507 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3508 userId); 3509 } 3510 if (mResolveComponentName.equals(component)) { 3511 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3512 new PackageUserState(), userId); 3513 } 3514 } 3515 return null; 3516 } 3517 3518 @Override 3519 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3520 String resolvedType) { 3521 synchronized (mPackages) { 3522 if (component.equals(mResolveComponentName)) { 3523 // The resolver supports EVERYTHING! 3524 return true; 3525 } 3526 PackageParser.Activity a = mActivities.mActivities.get(component); 3527 if (a == null) { 3528 return false; 3529 } 3530 for (int i=0; i<a.intents.size(); i++) { 3531 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3532 intent.getData(), intent.getCategories(), TAG) >= 0) { 3533 return true; 3534 } 3535 } 3536 return false; 3537 } 3538 } 3539 3540 @Override 3541 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3542 if (!sUserManager.exists(userId)) return null; 3543 flags = updateFlagsForComponent(flags, userId, component); 3544 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3545 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3546 synchronized (mPackages) { 3547 PackageParser.Activity a = mReceivers.mActivities.get(component); 3548 if (DEBUG_PACKAGE_INFO) Log.v( 3549 TAG, "getReceiverInfo " + component + ": " + a); 3550 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3551 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3552 if (ps == null) return null; 3553 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3554 userId); 3555 } 3556 } 3557 return null; 3558 } 3559 3560 @Override 3561 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3562 if (!sUserManager.exists(userId)) return null; 3563 flags = updateFlagsForComponent(flags, userId, component); 3564 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3565 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3566 synchronized (mPackages) { 3567 PackageParser.Service s = mServices.mServices.get(component); 3568 if (DEBUG_PACKAGE_INFO) Log.v( 3569 TAG, "getServiceInfo " + component + ": " + s); 3570 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3571 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3572 if (ps == null) return null; 3573 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3574 userId); 3575 } 3576 } 3577 return null; 3578 } 3579 3580 @Override 3581 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3582 if (!sUserManager.exists(userId)) return null; 3583 flags = updateFlagsForComponent(flags, userId, component); 3584 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3585 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3586 synchronized (mPackages) { 3587 PackageParser.Provider p = mProviders.mProviders.get(component); 3588 if (DEBUG_PACKAGE_INFO) Log.v( 3589 TAG, "getProviderInfo " + component + ": " + p); 3590 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3591 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3592 if (ps == null) return null; 3593 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3594 userId); 3595 } 3596 } 3597 return null; 3598 } 3599 3600 @Override 3601 public String[] getSystemSharedLibraryNames() { 3602 Set<String> libSet; 3603 synchronized (mPackages) { 3604 libSet = mSharedLibraries.keySet(); 3605 int size = libSet.size(); 3606 if (size > 0) { 3607 String[] libs = new String[size]; 3608 libSet.toArray(libs); 3609 return libs; 3610 } 3611 } 3612 return null; 3613 } 3614 3615 @Override 3616 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3617 synchronized (mPackages) { 3618 return mServicesSystemSharedLibraryPackageName; 3619 } 3620 } 3621 3622 @Override 3623 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3624 synchronized (mPackages) { 3625 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3626 3627 final FeatureInfo fi = new FeatureInfo(); 3628 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3629 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3630 res.add(fi); 3631 3632 return new ParceledListSlice<>(res); 3633 } 3634 } 3635 3636 @Override 3637 public boolean hasSystemFeature(String name, int version) { 3638 synchronized (mPackages) { 3639 final FeatureInfo feat = mAvailableFeatures.get(name); 3640 if (feat == null) { 3641 return false; 3642 } else { 3643 return feat.version >= version; 3644 } 3645 } 3646 } 3647 3648 @Override 3649 public int checkPermission(String permName, String pkgName, int userId) { 3650 if (!sUserManager.exists(userId)) { 3651 return PackageManager.PERMISSION_DENIED; 3652 } 3653 3654 synchronized (mPackages) { 3655 final PackageParser.Package p = mPackages.get(pkgName); 3656 if (p != null && p.mExtras != null) { 3657 final PackageSetting ps = (PackageSetting) p.mExtras; 3658 final PermissionsState permissionsState = ps.getPermissionsState(); 3659 if (permissionsState.hasPermission(permName, userId)) { 3660 return PackageManager.PERMISSION_GRANTED; 3661 } 3662 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3663 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3664 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3665 return PackageManager.PERMISSION_GRANTED; 3666 } 3667 } 3668 } 3669 3670 return PackageManager.PERMISSION_DENIED; 3671 } 3672 3673 @Override 3674 public int checkUidPermission(String permName, int uid) { 3675 final int userId = UserHandle.getUserId(uid); 3676 3677 if (!sUserManager.exists(userId)) { 3678 return PackageManager.PERMISSION_DENIED; 3679 } 3680 3681 synchronized (mPackages) { 3682 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3683 if (obj != null) { 3684 final SettingBase ps = (SettingBase) obj; 3685 final PermissionsState permissionsState = ps.getPermissionsState(); 3686 if (permissionsState.hasPermission(permName, userId)) { 3687 return PackageManager.PERMISSION_GRANTED; 3688 } 3689 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3690 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3691 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3692 return PackageManager.PERMISSION_GRANTED; 3693 } 3694 } else { 3695 ArraySet<String> perms = mSystemPermissions.get(uid); 3696 if (perms != null) { 3697 if (perms.contains(permName)) { 3698 return PackageManager.PERMISSION_GRANTED; 3699 } 3700 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3701 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3702 return PackageManager.PERMISSION_GRANTED; 3703 } 3704 } 3705 } 3706 } 3707 3708 return PackageManager.PERMISSION_DENIED; 3709 } 3710 3711 @Override 3712 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3713 if (UserHandle.getCallingUserId() != userId) { 3714 mContext.enforceCallingPermission( 3715 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3716 "isPermissionRevokedByPolicy for user " + userId); 3717 } 3718 3719 if (checkPermission(permission, packageName, userId) 3720 == PackageManager.PERMISSION_GRANTED) { 3721 return false; 3722 } 3723 3724 final long identity = Binder.clearCallingIdentity(); 3725 try { 3726 final int flags = getPermissionFlags(permission, packageName, userId); 3727 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3728 } finally { 3729 Binder.restoreCallingIdentity(identity); 3730 } 3731 } 3732 3733 @Override 3734 public String getPermissionControllerPackageName() { 3735 synchronized (mPackages) { 3736 return mRequiredInstallerPackage; 3737 } 3738 } 3739 3740 /** 3741 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3742 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3743 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3744 * @param message the message to log on security exception 3745 */ 3746 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3747 boolean checkShell, String message) { 3748 if (userId < 0) { 3749 throw new IllegalArgumentException("Invalid userId " + userId); 3750 } 3751 if (checkShell) { 3752 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3753 } 3754 if (userId == UserHandle.getUserId(callingUid)) return; 3755 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3756 if (requireFullPermission) { 3757 mContext.enforceCallingOrSelfPermission( 3758 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3759 } else { 3760 try { 3761 mContext.enforceCallingOrSelfPermission( 3762 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3763 } catch (SecurityException se) { 3764 mContext.enforceCallingOrSelfPermission( 3765 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3766 } 3767 } 3768 } 3769 } 3770 3771 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3772 if (callingUid == Process.SHELL_UID) { 3773 if (userHandle >= 0 3774 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3775 throw new SecurityException("Shell does not have permission to access user " 3776 + userHandle); 3777 } else if (userHandle < 0) { 3778 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3779 + Debug.getCallers(3)); 3780 } 3781 } 3782 } 3783 3784 private BasePermission findPermissionTreeLP(String permName) { 3785 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3786 if (permName.startsWith(bp.name) && 3787 permName.length() > bp.name.length() && 3788 permName.charAt(bp.name.length()) == '.') { 3789 return bp; 3790 } 3791 } 3792 return null; 3793 } 3794 3795 private BasePermission checkPermissionTreeLP(String permName) { 3796 if (permName != null) { 3797 BasePermission bp = findPermissionTreeLP(permName); 3798 if (bp != null) { 3799 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3800 return bp; 3801 } 3802 throw new SecurityException("Calling uid " 3803 + Binder.getCallingUid() 3804 + " is not allowed to add to permission tree " 3805 + bp.name + " owned by uid " + bp.uid); 3806 } 3807 } 3808 throw new SecurityException("No permission tree found for " + permName); 3809 } 3810 3811 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3812 if (s1 == null) { 3813 return s2 == null; 3814 } 3815 if (s2 == null) { 3816 return false; 3817 } 3818 if (s1.getClass() != s2.getClass()) { 3819 return false; 3820 } 3821 return s1.equals(s2); 3822 } 3823 3824 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3825 if (pi1.icon != pi2.icon) return false; 3826 if (pi1.logo != pi2.logo) return false; 3827 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3828 if (!compareStrings(pi1.name, pi2.name)) return false; 3829 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3830 // We'll take care of setting this one. 3831 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3832 // These are not currently stored in settings. 3833 //if (!compareStrings(pi1.group, pi2.group)) return false; 3834 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3835 //if (pi1.labelRes != pi2.labelRes) return false; 3836 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3837 return true; 3838 } 3839 3840 int permissionInfoFootprint(PermissionInfo info) { 3841 int size = info.name.length(); 3842 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3843 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3844 return size; 3845 } 3846 3847 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3848 int size = 0; 3849 for (BasePermission perm : mSettings.mPermissions.values()) { 3850 if (perm.uid == tree.uid) { 3851 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3852 } 3853 } 3854 return size; 3855 } 3856 3857 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3858 // We calculate the max size of permissions defined by this uid and throw 3859 // if that plus the size of 'info' would exceed our stated maximum. 3860 if (tree.uid != Process.SYSTEM_UID) { 3861 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3862 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3863 throw new SecurityException("Permission tree size cap exceeded"); 3864 } 3865 } 3866 } 3867 3868 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3869 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3870 throw new SecurityException("Label must be specified in permission"); 3871 } 3872 BasePermission tree = checkPermissionTreeLP(info.name); 3873 BasePermission bp = mSettings.mPermissions.get(info.name); 3874 boolean added = bp == null; 3875 boolean changed = true; 3876 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3877 if (added) { 3878 enforcePermissionCapLocked(info, tree); 3879 bp = new BasePermission(info.name, tree.sourcePackage, 3880 BasePermission.TYPE_DYNAMIC); 3881 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3882 throw new SecurityException( 3883 "Not allowed to modify non-dynamic permission " 3884 + info.name); 3885 } else { 3886 if (bp.protectionLevel == fixedLevel 3887 && bp.perm.owner.equals(tree.perm.owner) 3888 && bp.uid == tree.uid 3889 && comparePermissionInfos(bp.perm.info, info)) { 3890 changed = false; 3891 } 3892 } 3893 bp.protectionLevel = fixedLevel; 3894 info = new PermissionInfo(info); 3895 info.protectionLevel = fixedLevel; 3896 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3897 bp.perm.info.packageName = tree.perm.info.packageName; 3898 bp.uid = tree.uid; 3899 if (added) { 3900 mSettings.mPermissions.put(info.name, bp); 3901 } 3902 if (changed) { 3903 if (!async) { 3904 mSettings.writeLPr(); 3905 } else { 3906 scheduleWriteSettingsLocked(); 3907 } 3908 } 3909 return added; 3910 } 3911 3912 @Override 3913 public boolean addPermission(PermissionInfo info) { 3914 synchronized (mPackages) { 3915 return addPermissionLocked(info, false); 3916 } 3917 } 3918 3919 @Override 3920 public boolean addPermissionAsync(PermissionInfo info) { 3921 synchronized (mPackages) { 3922 return addPermissionLocked(info, true); 3923 } 3924 } 3925 3926 @Override 3927 public void removePermission(String name) { 3928 synchronized (mPackages) { 3929 checkPermissionTreeLP(name); 3930 BasePermission bp = mSettings.mPermissions.get(name); 3931 if (bp != null) { 3932 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3933 throw new SecurityException( 3934 "Not allowed to modify non-dynamic permission " 3935 + name); 3936 } 3937 mSettings.mPermissions.remove(name); 3938 mSettings.writeLPr(); 3939 } 3940 } 3941 } 3942 3943 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3944 BasePermission bp) { 3945 int index = pkg.requestedPermissions.indexOf(bp.name); 3946 if (index == -1) { 3947 throw new SecurityException("Package " + pkg.packageName 3948 + " has not requested permission " + bp.name); 3949 } 3950 if (!bp.isRuntime() && !bp.isDevelopment()) { 3951 throw new SecurityException("Permission " + bp.name 3952 + " is not a changeable permission type"); 3953 } 3954 } 3955 3956 @Override 3957 public void grantRuntimePermission(String packageName, String name, final int userId) { 3958 if (!sUserManager.exists(userId)) { 3959 Log.e(TAG, "No such user:" + userId); 3960 return; 3961 } 3962 3963 mContext.enforceCallingOrSelfPermission( 3964 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3965 "grantRuntimePermission"); 3966 3967 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3968 true /* requireFullPermission */, true /* checkShell */, 3969 "grantRuntimePermission"); 3970 3971 final int uid; 3972 final SettingBase sb; 3973 3974 synchronized (mPackages) { 3975 final PackageParser.Package pkg = mPackages.get(packageName); 3976 if (pkg == null) { 3977 throw new IllegalArgumentException("Unknown package: " + packageName); 3978 } 3979 3980 final BasePermission bp = mSettings.mPermissions.get(name); 3981 if (bp == null) { 3982 throw new IllegalArgumentException("Unknown permission: " + name); 3983 } 3984 3985 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3986 3987 // If a permission review is required for legacy apps we represent 3988 // their permissions as always granted runtime ones since we need 3989 // to keep the review required permission flag per user while an 3990 // install permission's state is shared across all users. 3991 if (Build.PERMISSIONS_REVIEW_REQUIRED 3992 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3993 && bp.isRuntime()) { 3994 return; 3995 } 3996 3997 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3998 sb = (SettingBase) pkg.mExtras; 3999 if (sb == null) { 4000 throw new IllegalArgumentException("Unknown package: " + packageName); 4001 } 4002 4003 final PermissionsState permissionsState = sb.getPermissionsState(); 4004 4005 final int flags = permissionsState.getPermissionFlags(name, userId); 4006 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4007 throw new SecurityException("Cannot grant system fixed permission " 4008 + name + " for package " + packageName); 4009 } 4010 4011 if (bp.isDevelopment()) { 4012 // Development permissions must be handled specially, since they are not 4013 // normal runtime permissions. For now they apply to all users. 4014 if (permissionsState.grantInstallPermission(bp) != 4015 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4016 scheduleWriteSettingsLocked(); 4017 } 4018 return; 4019 } 4020 4021 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4022 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4023 return; 4024 } 4025 4026 final int result = permissionsState.grantRuntimePermission(bp, userId); 4027 switch (result) { 4028 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4029 return; 4030 } 4031 4032 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4033 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4034 mHandler.post(new Runnable() { 4035 @Override 4036 public void run() { 4037 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4038 } 4039 }); 4040 } 4041 break; 4042 } 4043 4044 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4045 4046 // Not critical if that is lost - app has to request again. 4047 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4048 } 4049 4050 // Only need to do this if user is initialized. Otherwise it's a new user 4051 // and there are no processes running as the user yet and there's no need 4052 // to make an expensive call to remount processes for the changed permissions. 4053 if (READ_EXTERNAL_STORAGE.equals(name) 4054 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4055 final long token = Binder.clearCallingIdentity(); 4056 try { 4057 if (sUserManager.isInitialized(userId)) { 4058 MountServiceInternal mountServiceInternal = LocalServices.getService( 4059 MountServiceInternal.class); 4060 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4061 } 4062 } finally { 4063 Binder.restoreCallingIdentity(token); 4064 } 4065 } 4066 } 4067 4068 @Override 4069 public void revokeRuntimePermission(String packageName, String name, int userId) { 4070 if (!sUserManager.exists(userId)) { 4071 Log.e(TAG, "No such user:" + userId); 4072 return; 4073 } 4074 4075 mContext.enforceCallingOrSelfPermission( 4076 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4077 "revokeRuntimePermission"); 4078 4079 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4080 true /* requireFullPermission */, true /* checkShell */, 4081 "revokeRuntimePermission"); 4082 4083 final int appId; 4084 4085 synchronized (mPackages) { 4086 final PackageParser.Package pkg = mPackages.get(packageName); 4087 if (pkg == null) { 4088 throw new IllegalArgumentException("Unknown package: " + packageName); 4089 } 4090 4091 final BasePermission bp = mSettings.mPermissions.get(name); 4092 if (bp == null) { 4093 throw new IllegalArgumentException("Unknown permission: " + name); 4094 } 4095 4096 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4097 4098 // If a permission review is required for legacy apps we represent 4099 // their permissions as always granted runtime ones since we need 4100 // to keep the review required permission flag per user while an 4101 // install permission's state is shared across all users. 4102 if (Build.PERMISSIONS_REVIEW_REQUIRED 4103 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4104 && bp.isRuntime()) { 4105 return; 4106 } 4107 4108 SettingBase sb = (SettingBase) pkg.mExtras; 4109 if (sb == null) { 4110 throw new IllegalArgumentException("Unknown package: " + packageName); 4111 } 4112 4113 final PermissionsState permissionsState = sb.getPermissionsState(); 4114 4115 final int flags = permissionsState.getPermissionFlags(name, userId); 4116 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4117 throw new SecurityException("Cannot revoke system fixed permission " 4118 + name + " for package " + packageName); 4119 } 4120 4121 if (bp.isDevelopment()) { 4122 // Development permissions must be handled specially, since they are not 4123 // normal runtime permissions. For now they apply to all users. 4124 if (permissionsState.revokeInstallPermission(bp) != 4125 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4126 scheduleWriteSettingsLocked(); 4127 } 4128 return; 4129 } 4130 4131 if (permissionsState.revokeRuntimePermission(bp, userId) == 4132 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4133 return; 4134 } 4135 4136 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4137 4138 // Critical, after this call app should never have the permission. 4139 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4140 4141 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4142 } 4143 4144 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4145 } 4146 4147 @Override 4148 public void resetRuntimePermissions() { 4149 mContext.enforceCallingOrSelfPermission( 4150 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4151 "revokeRuntimePermission"); 4152 4153 int callingUid = Binder.getCallingUid(); 4154 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4155 mContext.enforceCallingOrSelfPermission( 4156 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4157 "resetRuntimePermissions"); 4158 } 4159 4160 synchronized (mPackages) { 4161 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4162 for (int userId : UserManagerService.getInstance().getUserIds()) { 4163 final int packageCount = mPackages.size(); 4164 for (int i = 0; i < packageCount; i++) { 4165 PackageParser.Package pkg = mPackages.valueAt(i); 4166 if (!(pkg.mExtras instanceof PackageSetting)) { 4167 continue; 4168 } 4169 PackageSetting ps = (PackageSetting) pkg.mExtras; 4170 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4171 } 4172 } 4173 } 4174 } 4175 4176 @Override 4177 public int getPermissionFlags(String name, String packageName, int userId) { 4178 if (!sUserManager.exists(userId)) { 4179 return 0; 4180 } 4181 4182 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4183 4184 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4185 true /* requireFullPermission */, false /* checkShell */, 4186 "getPermissionFlags"); 4187 4188 synchronized (mPackages) { 4189 final PackageParser.Package pkg = mPackages.get(packageName); 4190 if (pkg == null) { 4191 throw new IllegalArgumentException("Unknown package: " + packageName); 4192 } 4193 4194 final BasePermission bp = mSettings.mPermissions.get(name); 4195 if (bp == null) { 4196 throw new IllegalArgumentException("Unknown permission: " + name); 4197 } 4198 4199 SettingBase sb = (SettingBase) pkg.mExtras; 4200 if (sb == null) { 4201 throw new IllegalArgumentException("Unknown package: " + packageName); 4202 } 4203 4204 PermissionsState permissionsState = sb.getPermissionsState(); 4205 return permissionsState.getPermissionFlags(name, userId); 4206 } 4207 } 4208 4209 @Override 4210 public void updatePermissionFlags(String name, String packageName, int flagMask, 4211 int flagValues, int userId) { 4212 if (!sUserManager.exists(userId)) { 4213 return; 4214 } 4215 4216 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4217 4218 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4219 true /* requireFullPermission */, true /* checkShell */, 4220 "updatePermissionFlags"); 4221 4222 // Only the system can change these flags and nothing else. 4223 if (getCallingUid() != Process.SYSTEM_UID) { 4224 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4225 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4226 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4227 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4228 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4229 } 4230 4231 synchronized (mPackages) { 4232 final PackageParser.Package pkg = mPackages.get(packageName); 4233 if (pkg == null) { 4234 throw new IllegalArgumentException("Unknown package: " + packageName); 4235 } 4236 4237 final BasePermission bp = mSettings.mPermissions.get(name); 4238 if (bp == null) { 4239 throw new IllegalArgumentException("Unknown permission: " + name); 4240 } 4241 4242 SettingBase sb = (SettingBase) pkg.mExtras; 4243 if (sb == null) { 4244 throw new IllegalArgumentException("Unknown package: " + packageName); 4245 } 4246 4247 PermissionsState permissionsState = sb.getPermissionsState(); 4248 4249 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4250 4251 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4252 // Install and runtime permissions are stored in different places, 4253 // so figure out what permission changed and persist the change. 4254 if (permissionsState.getInstallPermissionState(name) != null) { 4255 scheduleWriteSettingsLocked(); 4256 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4257 || hadState) { 4258 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4259 } 4260 } 4261 } 4262 } 4263 4264 /** 4265 * Update the permission flags for all packages and runtime permissions of a user in order 4266 * to allow device or profile owner to remove POLICY_FIXED. 4267 */ 4268 @Override 4269 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4270 if (!sUserManager.exists(userId)) { 4271 return; 4272 } 4273 4274 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4275 4276 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4277 true /* requireFullPermission */, true /* checkShell */, 4278 "updatePermissionFlagsForAllApps"); 4279 4280 // Only the system can change system fixed flags. 4281 if (getCallingUid() != Process.SYSTEM_UID) { 4282 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4283 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4284 } 4285 4286 synchronized (mPackages) { 4287 boolean changed = false; 4288 final int packageCount = mPackages.size(); 4289 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4290 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4291 SettingBase sb = (SettingBase) pkg.mExtras; 4292 if (sb == null) { 4293 continue; 4294 } 4295 PermissionsState permissionsState = sb.getPermissionsState(); 4296 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4297 userId, flagMask, flagValues); 4298 } 4299 if (changed) { 4300 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4301 } 4302 } 4303 } 4304 4305 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4306 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4307 != PackageManager.PERMISSION_GRANTED 4308 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4309 != PackageManager.PERMISSION_GRANTED) { 4310 throw new SecurityException(message + " requires " 4311 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4312 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4313 } 4314 } 4315 4316 @Override 4317 public boolean shouldShowRequestPermissionRationale(String permissionName, 4318 String packageName, int userId) { 4319 if (UserHandle.getCallingUserId() != userId) { 4320 mContext.enforceCallingPermission( 4321 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4322 "canShowRequestPermissionRationale for user " + userId); 4323 } 4324 4325 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4326 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4327 return false; 4328 } 4329 4330 if (checkPermission(permissionName, packageName, userId) 4331 == PackageManager.PERMISSION_GRANTED) { 4332 return false; 4333 } 4334 4335 final int flags; 4336 4337 final long identity = Binder.clearCallingIdentity(); 4338 try { 4339 flags = getPermissionFlags(permissionName, 4340 packageName, userId); 4341 } finally { 4342 Binder.restoreCallingIdentity(identity); 4343 } 4344 4345 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4346 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4347 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4348 4349 if ((flags & fixedFlags) != 0) { 4350 return false; 4351 } 4352 4353 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4354 } 4355 4356 @Override 4357 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4358 mContext.enforceCallingOrSelfPermission( 4359 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4360 "addOnPermissionsChangeListener"); 4361 4362 synchronized (mPackages) { 4363 mOnPermissionChangeListeners.addListenerLocked(listener); 4364 } 4365 } 4366 4367 @Override 4368 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4369 synchronized (mPackages) { 4370 mOnPermissionChangeListeners.removeListenerLocked(listener); 4371 } 4372 } 4373 4374 @Override 4375 public boolean isProtectedBroadcast(String actionName) { 4376 synchronized (mPackages) { 4377 if (mProtectedBroadcasts.contains(actionName)) { 4378 return true; 4379 } else if (actionName != null) { 4380 // TODO: remove these terrible hacks 4381 if (actionName.startsWith("android.net.netmon.lingerExpired") 4382 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4383 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4384 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4385 return true; 4386 } 4387 } 4388 } 4389 return false; 4390 } 4391 4392 @Override 4393 public int checkSignatures(String pkg1, String pkg2) { 4394 synchronized (mPackages) { 4395 final PackageParser.Package p1 = mPackages.get(pkg1); 4396 final PackageParser.Package p2 = mPackages.get(pkg2); 4397 if (p1 == null || p1.mExtras == null 4398 || p2 == null || p2.mExtras == null) { 4399 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4400 } 4401 return compareSignatures(p1.mSignatures, p2.mSignatures); 4402 } 4403 } 4404 4405 @Override 4406 public int checkUidSignatures(int uid1, int uid2) { 4407 // Map to base uids. 4408 uid1 = UserHandle.getAppId(uid1); 4409 uid2 = UserHandle.getAppId(uid2); 4410 // reader 4411 synchronized (mPackages) { 4412 Signature[] s1; 4413 Signature[] s2; 4414 Object obj = mSettings.getUserIdLPr(uid1); 4415 if (obj != null) { 4416 if (obj instanceof SharedUserSetting) { 4417 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4418 } else if (obj instanceof PackageSetting) { 4419 s1 = ((PackageSetting)obj).signatures.mSignatures; 4420 } else { 4421 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4422 } 4423 } else { 4424 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4425 } 4426 obj = mSettings.getUserIdLPr(uid2); 4427 if (obj != null) { 4428 if (obj instanceof SharedUserSetting) { 4429 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4430 } else if (obj instanceof PackageSetting) { 4431 s2 = ((PackageSetting)obj).signatures.mSignatures; 4432 } else { 4433 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4434 } 4435 } else { 4436 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4437 } 4438 return compareSignatures(s1, s2); 4439 } 4440 } 4441 4442 /** 4443 * This method should typically only be used when granting or revoking 4444 * permissions, since the app may immediately restart after this call. 4445 * <p> 4446 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4447 * guard your work against the app being relaunched. 4448 */ 4449 private void killUid(int appId, int userId, String reason) { 4450 final long identity = Binder.clearCallingIdentity(); 4451 try { 4452 IActivityManager am = ActivityManagerNative.getDefault(); 4453 if (am != null) { 4454 try { 4455 am.killUid(appId, userId, reason); 4456 } catch (RemoteException e) { 4457 /* ignore - same process */ 4458 } 4459 } 4460 } finally { 4461 Binder.restoreCallingIdentity(identity); 4462 } 4463 } 4464 4465 /** 4466 * Compares two sets of signatures. Returns: 4467 * <br /> 4468 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4469 * <br /> 4470 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4471 * <br /> 4472 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4473 * <br /> 4474 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4475 * <br /> 4476 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4477 */ 4478 static int compareSignatures(Signature[] s1, Signature[] s2) { 4479 if (s1 == null) { 4480 return s2 == null 4481 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4482 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4483 } 4484 4485 if (s2 == null) { 4486 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4487 } 4488 4489 if (s1.length != s2.length) { 4490 return PackageManager.SIGNATURE_NO_MATCH; 4491 } 4492 4493 // Since both signature sets are of size 1, we can compare without HashSets. 4494 if (s1.length == 1) { 4495 return s1[0].equals(s2[0]) ? 4496 PackageManager.SIGNATURE_MATCH : 4497 PackageManager.SIGNATURE_NO_MATCH; 4498 } 4499 4500 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4501 for (Signature sig : s1) { 4502 set1.add(sig); 4503 } 4504 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4505 for (Signature sig : s2) { 4506 set2.add(sig); 4507 } 4508 // Make sure s2 contains all signatures in s1. 4509 if (set1.equals(set2)) { 4510 return PackageManager.SIGNATURE_MATCH; 4511 } 4512 return PackageManager.SIGNATURE_NO_MATCH; 4513 } 4514 4515 /** 4516 * If the database version for this type of package (internal storage or 4517 * external storage) is less than the version where package signatures 4518 * were updated, return true. 4519 */ 4520 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4521 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4522 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4523 } 4524 4525 /** 4526 * Used for backward compatibility to make sure any packages with 4527 * certificate chains get upgraded to the new style. {@code existingSigs} 4528 * will be in the old format (since they were stored on disk from before the 4529 * system upgrade) and {@code scannedSigs} will be in the newer format. 4530 */ 4531 private int compareSignaturesCompat(PackageSignatures existingSigs, 4532 PackageParser.Package scannedPkg) { 4533 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4534 return PackageManager.SIGNATURE_NO_MATCH; 4535 } 4536 4537 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4538 for (Signature sig : existingSigs.mSignatures) { 4539 existingSet.add(sig); 4540 } 4541 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4542 for (Signature sig : scannedPkg.mSignatures) { 4543 try { 4544 Signature[] chainSignatures = sig.getChainSignatures(); 4545 for (Signature chainSig : chainSignatures) { 4546 scannedCompatSet.add(chainSig); 4547 } 4548 } catch (CertificateEncodingException e) { 4549 scannedCompatSet.add(sig); 4550 } 4551 } 4552 /* 4553 * Make sure the expanded scanned set contains all signatures in the 4554 * existing one. 4555 */ 4556 if (scannedCompatSet.equals(existingSet)) { 4557 // Migrate the old signatures to the new scheme. 4558 existingSigs.assignSignatures(scannedPkg.mSignatures); 4559 // The new KeySets will be re-added later in the scanning process. 4560 synchronized (mPackages) { 4561 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4562 } 4563 return PackageManager.SIGNATURE_MATCH; 4564 } 4565 return PackageManager.SIGNATURE_NO_MATCH; 4566 } 4567 4568 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4569 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4570 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4571 } 4572 4573 private int compareSignaturesRecover(PackageSignatures existingSigs, 4574 PackageParser.Package scannedPkg) { 4575 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4576 return PackageManager.SIGNATURE_NO_MATCH; 4577 } 4578 4579 String msg = null; 4580 try { 4581 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4582 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4583 + scannedPkg.packageName); 4584 return PackageManager.SIGNATURE_MATCH; 4585 } 4586 } catch (CertificateException e) { 4587 msg = e.getMessage(); 4588 } 4589 4590 logCriticalInfo(Log.INFO, 4591 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4592 return PackageManager.SIGNATURE_NO_MATCH; 4593 } 4594 4595 @Override 4596 public List<String> getAllPackages() { 4597 synchronized (mPackages) { 4598 return new ArrayList<String>(mPackages.keySet()); 4599 } 4600 } 4601 4602 @Override 4603 public String[] getPackagesForUid(int uid) { 4604 uid = UserHandle.getAppId(uid); 4605 // reader 4606 synchronized (mPackages) { 4607 Object obj = mSettings.getUserIdLPr(uid); 4608 if (obj instanceof SharedUserSetting) { 4609 final SharedUserSetting sus = (SharedUserSetting) obj; 4610 final int N = sus.packages.size(); 4611 final String[] res = new String[N]; 4612 final Iterator<PackageSetting> it = sus.packages.iterator(); 4613 int i = 0; 4614 while (it.hasNext()) { 4615 res[i++] = it.next().name; 4616 } 4617 return res; 4618 } else if (obj instanceof PackageSetting) { 4619 final PackageSetting ps = (PackageSetting) obj; 4620 return new String[] { ps.name }; 4621 } 4622 } 4623 return null; 4624 } 4625 4626 @Override 4627 public String getNameForUid(int uid) { 4628 // reader 4629 synchronized (mPackages) { 4630 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4631 if (obj instanceof SharedUserSetting) { 4632 final SharedUserSetting sus = (SharedUserSetting) obj; 4633 return sus.name + ":" + sus.userId; 4634 } else if (obj instanceof PackageSetting) { 4635 final PackageSetting ps = (PackageSetting) obj; 4636 return ps.name; 4637 } 4638 } 4639 return null; 4640 } 4641 4642 @Override 4643 public int getUidForSharedUser(String sharedUserName) { 4644 if(sharedUserName == null) { 4645 return -1; 4646 } 4647 // reader 4648 synchronized (mPackages) { 4649 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4650 if (suid == null) { 4651 return -1; 4652 } 4653 return suid.userId; 4654 } 4655 } 4656 4657 @Override 4658 public int getFlagsForUid(int uid) { 4659 synchronized (mPackages) { 4660 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4661 if (obj instanceof SharedUserSetting) { 4662 final SharedUserSetting sus = (SharedUserSetting) obj; 4663 return sus.pkgFlags; 4664 } else if (obj instanceof PackageSetting) { 4665 final PackageSetting ps = (PackageSetting) obj; 4666 return ps.pkgFlags; 4667 } 4668 } 4669 return 0; 4670 } 4671 4672 @Override 4673 public int getPrivateFlagsForUid(int uid) { 4674 synchronized (mPackages) { 4675 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4676 if (obj instanceof SharedUserSetting) { 4677 final SharedUserSetting sus = (SharedUserSetting) obj; 4678 return sus.pkgPrivateFlags; 4679 } else if (obj instanceof PackageSetting) { 4680 final PackageSetting ps = (PackageSetting) obj; 4681 return ps.pkgPrivateFlags; 4682 } 4683 } 4684 return 0; 4685 } 4686 4687 @Override 4688 public boolean isUidPrivileged(int uid) { 4689 uid = UserHandle.getAppId(uid); 4690 // reader 4691 synchronized (mPackages) { 4692 Object obj = mSettings.getUserIdLPr(uid); 4693 if (obj instanceof SharedUserSetting) { 4694 final SharedUserSetting sus = (SharedUserSetting) obj; 4695 final Iterator<PackageSetting> it = sus.packages.iterator(); 4696 while (it.hasNext()) { 4697 if (it.next().isPrivileged()) { 4698 return true; 4699 } 4700 } 4701 } else if (obj instanceof PackageSetting) { 4702 final PackageSetting ps = (PackageSetting) obj; 4703 return ps.isPrivileged(); 4704 } 4705 } 4706 return false; 4707 } 4708 4709 @Override 4710 public String[] getAppOpPermissionPackages(String permissionName) { 4711 synchronized (mPackages) { 4712 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4713 if (pkgs == null) { 4714 return null; 4715 } 4716 return pkgs.toArray(new String[pkgs.size()]); 4717 } 4718 } 4719 4720 @Override 4721 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4722 int flags, int userId) { 4723 try { 4724 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4725 4726 if (!sUserManager.exists(userId)) return null; 4727 flags = updateFlagsForResolve(flags, userId, intent); 4728 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4729 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4730 4731 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4732 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4733 flags, userId); 4734 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4735 4736 final ResolveInfo bestChoice = 4737 chooseBestActivity(intent, resolvedType, flags, query, userId); 4738 4739 if (isEphemeralAllowed(intent, query, userId)) { 4740 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4741 final EphemeralResolveInfo ai = 4742 getEphemeralResolveInfo(intent, resolvedType, userId); 4743 if (ai != null) { 4744 if (DEBUG_EPHEMERAL) { 4745 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4746 } 4747 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4748 bestChoice.ephemeralResolveInfo = ai; 4749 } 4750 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4751 } 4752 return bestChoice; 4753 } finally { 4754 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4755 } 4756 } 4757 4758 @Override 4759 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4760 IntentFilter filter, int match, ComponentName activity) { 4761 final int userId = UserHandle.getCallingUserId(); 4762 if (DEBUG_PREFERRED) { 4763 Log.v(TAG, "setLastChosenActivity intent=" + intent 4764 + " resolvedType=" + resolvedType 4765 + " flags=" + flags 4766 + " filter=" + filter 4767 + " match=" + match 4768 + " activity=" + activity); 4769 filter.dump(new PrintStreamPrinter(System.out), " "); 4770 } 4771 intent.setComponent(null); 4772 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4773 userId); 4774 // Find any earlier preferred or last chosen entries and nuke them 4775 findPreferredActivity(intent, resolvedType, 4776 flags, query, 0, false, true, false, userId); 4777 // Add the new activity as the last chosen for this filter 4778 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4779 "Setting last chosen"); 4780 } 4781 4782 @Override 4783 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4784 final int userId = UserHandle.getCallingUserId(); 4785 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4786 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4787 userId); 4788 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4789 false, false, false, userId); 4790 } 4791 4792 4793 private boolean isEphemeralAllowed( 4794 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4795 // Short circuit and return early if possible. 4796 if (DISABLE_EPHEMERAL_APPS) { 4797 return false; 4798 } 4799 final int callingUser = UserHandle.getCallingUserId(); 4800 if (callingUser != UserHandle.USER_SYSTEM) { 4801 return false; 4802 } 4803 if (mEphemeralResolverConnection == null) { 4804 return false; 4805 } 4806 if (intent.getComponent() != null) { 4807 return false; 4808 } 4809 if (intent.getPackage() != null) { 4810 return false; 4811 } 4812 final boolean isWebUri = hasWebURI(intent); 4813 if (!isWebUri) { 4814 return false; 4815 } 4816 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4817 synchronized (mPackages) { 4818 final int count = resolvedActivites.size(); 4819 for (int n = 0; n < count; n++) { 4820 ResolveInfo info = resolvedActivites.get(n); 4821 String packageName = info.activityInfo.packageName; 4822 PackageSetting ps = mSettings.mPackages.get(packageName); 4823 if (ps != null) { 4824 // Try to get the status from User settings first 4825 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4826 int status = (int) (packedStatus >> 32); 4827 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4828 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4829 if (DEBUG_EPHEMERAL) { 4830 Slog.v(TAG, "DENY ephemeral apps;" 4831 + " pkg: " + packageName + ", status: " + status); 4832 } 4833 return false; 4834 } 4835 } 4836 } 4837 } 4838 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4839 return true; 4840 } 4841 4842 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4843 int userId) { 4844 MessageDigest digest = null; 4845 try { 4846 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4847 } catch (NoSuchAlgorithmException e) { 4848 // If we can't create a digest, ignore ephemeral apps. 4849 return null; 4850 } 4851 4852 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4853 final byte[] digestBytes = digest.digest(hostBytes); 4854 int shaPrefix = 4855 digestBytes[0] << 24 4856 | digestBytes[1] << 16 4857 | digestBytes[2] << 8 4858 | digestBytes[3] << 0; 4859 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4860 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4861 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4862 // No hash prefix match; there are no ephemeral apps for this domain. 4863 return null; 4864 } 4865 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4866 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4867 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4868 continue; 4869 } 4870 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4871 // No filters; this should never happen. 4872 if (filters.isEmpty()) { 4873 continue; 4874 } 4875 // We have a domain match; resolve the filters to see if anything matches. 4876 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4877 for (int j = filters.size() - 1; j >= 0; --j) { 4878 final EphemeralResolveIntentInfo intentInfo = 4879 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4880 ephemeralResolver.addFilter(intentInfo); 4881 } 4882 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4883 intent, resolvedType, false /*defaultOnly*/, userId); 4884 if (!matchedResolveInfoList.isEmpty()) { 4885 return matchedResolveInfoList.get(0); 4886 } 4887 } 4888 // Hash or filter mis-match; no ephemeral apps for this domain. 4889 return null; 4890 } 4891 4892 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4893 int flags, List<ResolveInfo> query, int userId) { 4894 if (query != null) { 4895 final int N = query.size(); 4896 if (N == 1) { 4897 return query.get(0); 4898 } else if (N > 1) { 4899 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4900 // If there is more than one activity with the same priority, 4901 // then let the user decide between them. 4902 ResolveInfo r0 = query.get(0); 4903 ResolveInfo r1 = query.get(1); 4904 if (DEBUG_INTENT_MATCHING || debug) { 4905 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4906 + r1.activityInfo.name + "=" + r1.priority); 4907 } 4908 // If the first activity has a higher priority, or a different 4909 // default, then it is always desirable to pick it. 4910 if (r0.priority != r1.priority 4911 || r0.preferredOrder != r1.preferredOrder 4912 || r0.isDefault != r1.isDefault) { 4913 return query.get(0); 4914 } 4915 // If we have saved a preference for a preferred activity for 4916 // this Intent, use that. 4917 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4918 flags, query, r0.priority, true, false, debug, userId); 4919 if (ri != null) { 4920 return ri; 4921 } 4922 ri = new ResolveInfo(mResolveInfo); 4923 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4924 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4925 ri.activityInfo.applicationInfo = new ApplicationInfo( 4926 ri.activityInfo.applicationInfo); 4927 if (userId != 0) { 4928 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4929 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4930 } 4931 // Make sure that the resolver is displayable in car mode 4932 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4933 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4934 return ri; 4935 } 4936 } 4937 return null; 4938 } 4939 4940 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4941 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4942 final int N = query.size(); 4943 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4944 .get(userId); 4945 // Get the list of persistent preferred activities that handle the intent 4946 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4947 List<PersistentPreferredActivity> pprefs = ppir != null 4948 ? ppir.queryIntent(intent, resolvedType, 4949 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4950 : null; 4951 if (pprefs != null && pprefs.size() > 0) { 4952 final int M = pprefs.size(); 4953 for (int i=0; i<M; i++) { 4954 final PersistentPreferredActivity ppa = pprefs.get(i); 4955 if (DEBUG_PREFERRED || debug) { 4956 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4957 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4958 + "\n component=" + ppa.mComponent); 4959 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4960 } 4961 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4962 flags | MATCH_DISABLED_COMPONENTS, userId); 4963 if (DEBUG_PREFERRED || debug) { 4964 Slog.v(TAG, "Found persistent preferred activity:"); 4965 if (ai != null) { 4966 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4967 } else { 4968 Slog.v(TAG, " null"); 4969 } 4970 } 4971 if (ai == null) { 4972 // This previously registered persistent preferred activity 4973 // component is no longer known. Ignore it and do NOT remove it. 4974 continue; 4975 } 4976 for (int j=0; j<N; j++) { 4977 final ResolveInfo ri = query.get(j); 4978 if (!ri.activityInfo.applicationInfo.packageName 4979 .equals(ai.applicationInfo.packageName)) { 4980 continue; 4981 } 4982 if (!ri.activityInfo.name.equals(ai.name)) { 4983 continue; 4984 } 4985 // Found a persistent preference that can handle the intent. 4986 if (DEBUG_PREFERRED || debug) { 4987 Slog.v(TAG, "Returning persistent preferred activity: " + 4988 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4989 } 4990 return ri; 4991 } 4992 } 4993 } 4994 return null; 4995 } 4996 4997 // TODO: handle preferred activities missing while user has amnesia 4998 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 4999 List<ResolveInfo> query, int priority, boolean always, 5000 boolean removeMatches, boolean debug, int userId) { 5001 if (!sUserManager.exists(userId)) return null; 5002 flags = updateFlagsForResolve(flags, userId, intent); 5003 // writer 5004 synchronized (mPackages) { 5005 if (intent.getSelector() != null) { 5006 intent = intent.getSelector(); 5007 } 5008 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5009 5010 // Try to find a matching persistent preferred activity. 5011 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5012 debug, userId); 5013 5014 // If a persistent preferred activity matched, use it. 5015 if (pri != null) { 5016 return pri; 5017 } 5018 5019 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5020 // Get the list of preferred activities that handle the intent 5021 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5022 List<PreferredActivity> prefs = pir != null 5023 ? pir.queryIntent(intent, resolvedType, 5024 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5025 : null; 5026 if (prefs != null && prefs.size() > 0) { 5027 boolean changed = false; 5028 try { 5029 // First figure out how good the original match set is. 5030 // We will only allow preferred activities that came 5031 // from the same match quality. 5032 int match = 0; 5033 5034 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5035 5036 final int N = query.size(); 5037 for (int j=0; j<N; j++) { 5038 final ResolveInfo ri = query.get(j); 5039 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5040 + ": 0x" + Integer.toHexString(match)); 5041 if (ri.match > match) { 5042 match = ri.match; 5043 } 5044 } 5045 5046 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5047 + Integer.toHexString(match)); 5048 5049 match &= IntentFilter.MATCH_CATEGORY_MASK; 5050 final int M = prefs.size(); 5051 for (int i=0; i<M; i++) { 5052 final PreferredActivity pa = prefs.get(i); 5053 if (DEBUG_PREFERRED || debug) { 5054 Slog.v(TAG, "Checking PreferredActivity ds=" 5055 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5056 + "\n component=" + pa.mPref.mComponent); 5057 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5058 } 5059 if (pa.mPref.mMatch != match) { 5060 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5061 + Integer.toHexString(pa.mPref.mMatch)); 5062 continue; 5063 } 5064 // If it's not an "always" type preferred activity and that's what we're 5065 // looking for, skip it. 5066 if (always && !pa.mPref.mAlways) { 5067 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5068 continue; 5069 } 5070 final ActivityInfo ai = getActivityInfo( 5071 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5072 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5073 userId); 5074 if (DEBUG_PREFERRED || debug) { 5075 Slog.v(TAG, "Found preferred activity:"); 5076 if (ai != null) { 5077 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5078 } else { 5079 Slog.v(TAG, " null"); 5080 } 5081 } 5082 if (ai == null) { 5083 // This previously registered preferred activity 5084 // component is no longer known. Most likely an update 5085 // to the app was installed and in the new version this 5086 // component no longer exists. Clean it up by removing 5087 // it from the preferred activities list, and skip it. 5088 Slog.w(TAG, "Removing dangling preferred activity: " 5089 + pa.mPref.mComponent); 5090 pir.removeFilter(pa); 5091 changed = true; 5092 continue; 5093 } 5094 for (int j=0; j<N; j++) { 5095 final ResolveInfo ri = query.get(j); 5096 if (!ri.activityInfo.applicationInfo.packageName 5097 .equals(ai.applicationInfo.packageName)) { 5098 continue; 5099 } 5100 if (!ri.activityInfo.name.equals(ai.name)) { 5101 continue; 5102 } 5103 5104 if (removeMatches) { 5105 pir.removeFilter(pa); 5106 changed = true; 5107 if (DEBUG_PREFERRED) { 5108 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5109 } 5110 break; 5111 } 5112 5113 // Okay we found a previously set preferred or last chosen app. 5114 // If the result set is different from when this 5115 // was created, we need to clear it and re-ask the 5116 // user their preference, if we're looking for an "always" type entry. 5117 if (always && !pa.mPref.sameSet(query)) { 5118 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5119 + intent + " type " + resolvedType); 5120 if (DEBUG_PREFERRED) { 5121 Slog.v(TAG, "Removing preferred activity since set changed " 5122 + pa.mPref.mComponent); 5123 } 5124 pir.removeFilter(pa); 5125 // Re-add the filter as a "last chosen" entry (!always) 5126 PreferredActivity lastChosen = new PreferredActivity( 5127 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5128 pir.addFilter(lastChosen); 5129 changed = true; 5130 return null; 5131 } 5132 5133 // Yay! Either the set matched or we're looking for the last chosen 5134 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5135 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5136 return ri; 5137 } 5138 } 5139 } finally { 5140 if (changed) { 5141 if (DEBUG_PREFERRED) { 5142 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5143 } 5144 scheduleWritePackageRestrictionsLocked(userId); 5145 } 5146 } 5147 } 5148 } 5149 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5150 return null; 5151 } 5152 5153 /* 5154 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5155 */ 5156 @Override 5157 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5158 int targetUserId) { 5159 mContext.enforceCallingOrSelfPermission( 5160 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5161 List<CrossProfileIntentFilter> matches = 5162 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5163 if (matches != null) { 5164 int size = matches.size(); 5165 for (int i = 0; i < size; i++) { 5166 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5167 } 5168 } 5169 if (hasWebURI(intent)) { 5170 // cross-profile app linking works only towards the parent. 5171 final UserInfo parent = getProfileParent(sourceUserId); 5172 synchronized(mPackages) { 5173 int flags = updateFlagsForResolve(0, parent.id, intent); 5174 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5175 intent, resolvedType, flags, sourceUserId, parent.id); 5176 return xpDomainInfo != null; 5177 } 5178 } 5179 return false; 5180 } 5181 5182 private UserInfo getProfileParent(int userId) { 5183 final long identity = Binder.clearCallingIdentity(); 5184 try { 5185 return sUserManager.getProfileParent(userId); 5186 } finally { 5187 Binder.restoreCallingIdentity(identity); 5188 } 5189 } 5190 5191 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5192 String resolvedType, int userId) { 5193 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5194 if (resolver != null) { 5195 return resolver.queryIntent(intent, resolvedType, false, userId); 5196 } 5197 return null; 5198 } 5199 5200 @Override 5201 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5202 String resolvedType, int flags, int userId) { 5203 try { 5204 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5205 5206 return new ParceledListSlice<>( 5207 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5208 } finally { 5209 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5210 } 5211 } 5212 5213 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5214 String resolvedType, int flags, int userId) { 5215 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5216 flags = updateFlagsForResolve(flags, userId, intent); 5217 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5218 false /* requireFullPermission */, false /* checkShell */, 5219 "query intent activities"); 5220 ComponentName comp = intent.getComponent(); 5221 if (comp == null) { 5222 if (intent.getSelector() != null) { 5223 intent = intent.getSelector(); 5224 comp = intent.getComponent(); 5225 } 5226 } 5227 5228 if (comp != null) { 5229 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5230 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5231 if (ai != null) { 5232 final ResolveInfo ri = new ResolveInfo(); 5233 ri.activityInfo = ai; 5234 list.add(ri); 5235 } 5236 return list; 5237 } 5238 5239 // reader 5240 synchronized (mPackages) { 5241 final String pkgName = intent.getPackage(); 5242 if (pkgName == null) { 5243 List<CrossProfileIntentFilter> matchingFilters = 5244 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5245 // Check for results that need to skip the current profile. 5246 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5247 resolvedType, flags, userId); 5248 if (xpResolveInfo != null) { 5249 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5250 result.add(xpResolveInfo); 5251 return filterIfNotSystemUser(result, userId); 5252 } 5253 5254 // Check for results in the current profile. 5255 List<ResolveInfo> result = mActivities.queryIntent( 5256 intent, resolvedType, flags, userId); 5257 result = filterIfNotSystemUser(result, userId); 5258 5259 // Check for cross profile results. 5260 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5261 xpResolveInfo = queryCrossProfileIntents( 5262 matchingFilters, intent, resolvedType, flags, userId, 5263 hasNonNegativePriorityResult); 5264 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5265 boolean isVisibleToUser = filterIfNotSystemUser( 5266 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5267 if (isVisibleToUser) { 5268 result.add(xpResolveInfo); 5269 Collections.sort(result, mResolvePrioritySorter); 5270 } 5271 } 5272 if (hasWebURI(intent)) { 5273 CrossProfileDomainInfo xpDomainInfo = null; 5274 final UserInfo parent = getProfileParent(userId); 5275 if (parent != null) { 5276 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5277 flags, userId, parent.id); 5278 } 5279 if (xpDomainInfo != null) { 5280 if (xpResolveInfo != null) { 5281 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5282 // in the result. 5283 result.remove(xpResolveInfo); 5284 } 5285 if (result.size() == 0) { 5286 result.add(xpDomainInfo.resolveInfo); 5287 return result; 5288 } 5289 } else if (result.size() <= 1) { 5290 return result; 5291 } 5292 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5293 xpDomainInfo, userId); 5294 Collections.sort(result, mResolvePrioritySorter); 5295 } 5296 return result; 5297 } 5298 final PackageParser.Package pkg = mPackages.get(pkgName); 5299 if (pkg != null) { 5300 return filterIfNotSystemUser( 5301 mActivities.queryIntentForPackage( 5302 intent, resolvedType, flags, pkg.activities, userId), 5303 userId); 5304 } 5305 return new ArrayList<ResolveInfo>(); 5306 } 5307 } 5308 5309 private static class CrossProfileDomainInfo { 5310 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5311 ResolveInfo resolveInfo; 5312 /* Best domain verification status of the activities found in the other profile */ 5313 int bestDomainVerificationStatus; 5314 } 5315 5316 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5317 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5318 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5319 sourceUserId)) { 5320 return null; 5321 } 5322 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5323 resolvedType, flags, parentUserId); 5324 5325 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5326 return null; 5327 } 5328 CrossProfileDomainInfo result = null; 5329 int size = resultTargetUser.size(); 5330 for (int i = 0; i < size; i++) { 5331 ResolveInfo riTargetUser = resultTargetUser.get(i); 5332 // Intent filter verification is only for filters that specify a host. So don't return 5333 // those that handle all web uris. 5334 if (riTargetUser.handleAllWebDataURI) { 5335 continue; 5336 } 5337 String packageName = riTargetUser.activityInfo.packageName; 5338 PackageSetting ps = mSettings.mPackages.get(packageName); 5339 if (ps == null) { 5340 continue; 5341 } 5342 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5343 int status = (int)(verificationState >> 32); 5344 if (result == null) { 5345 result = new CrossProfileDomainInfo(); 5346 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5347 sourceUserId, parentUserId); 5348 result.bestDomainVerificationStatus = status; 5349 } else { 5350 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5351 result.bestDomainVerificationStatus); 5352 } 5353 } 5354 // Don't consider matches with status NEVER across profiles. 5355 if (result != null && result.bestDomainVerificationStatus 5356 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5357 return null; 5358 } 5359 return result; 5360 } 5361 5362 /** 5363 * Verification statuses are ordered from the worse to the best, except for 5364 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5365 */ 5366 private int bestDomainVerificationStatus(int status1, int status2) { 5367 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5368 return status2; 5369 } 5370 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5371 return status1; 5372 } 5373 return (int) MathUtils.max(status1, status2); 5374 } 5375 5376 private boolean isUserEnabled(int userId) { 5377 long callingId = Binder.clearCallingIdentity(); 5378 try { 5379 UserInfo userInfo = sUserManager.getUserInfo(userId); 5380 return userInfo != null && userInfo.isEnabled(); 5381 } finally { 5382 Binder.restoreCallingIdentity(callingId); 5383 } 5384 } 5385 5386 /** 5387 * Filter out activities with systemUserOnly flag set, when current user is not System. 5388 * 5389 * @return filtered list 5390 */ 5391 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5392 if (userId == UserHandle.USER_SYSTEM) { 5393 return resolveInfos; 5394 } 5395 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5396 ResolveInfo info = resolveInfos.get(i); 5397 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5398 resolveInfos.remove(i); 5399 } 5400 } 5401 return resolveInfos; 5402 } 5403 5404 /** 5405 * @param resolveInfos list of resolve infos in descending priority order 5406 * @return if the list contains a resolve info with non-negative priority 5407 */ 5408 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5409 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5410 } 5411 5412 private static boolean hasWebURI(Intent intent) { 5413 if (intent.getData() == null) { 5414 return false; 5415 } 5416 final String scheme = intent.getScheme(); 5417 if (TextUtils.isEmpty(scheme)) { 5418 return false; 5419 } 5420 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5421 } 5422 5423 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5424 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5425 int userId) { 5426 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5427 5428 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5429 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5430 candidates.size()); 5431 } 5432 5433 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5434 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5435 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5436 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5437 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5438 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5439 5440 synchronized (mPackages) { 5441 final int count = candidates.size(); 5442 // First, try to use linked apps. Partition the candidates into four lists: 5443 // one for the final results, one for the "do not use ever", one for "undefined status" 5444 // and finally one for "browser app type". 5445 for (int n=0; n<count; n++) { 5446 ResolveInfo info = candidates.get(n); 5447 String packageName = info.activityInfo.packageName; 5448 PackageSetting ps = mSettings.mPackages.get(packageName); 5449 if (ps != null) { 5450 // Add to the special match all list (Browser use case) 5451 if (info.handleAllWebDataURI) { 5452 matchAllList.add(info); 5453 continue; 5454 } 5455 // Try to get the status from User settings first 5456 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5457 int status = (int)(packedStatus >> 32); 5458 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5459 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5460 if (DEBUG_DOMAIN_VERIFICATION) { 5461 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5462 + " : linkgen=" + linkGeneration); 5463 } 5464 // Use link-enabled generation as preferredOrder, i.e. 5465 // prefer newly-enabled over earlier-enabled. 5466 info.preferredOrder = linkGeneration; 5467 alwaysList.add(info); 5468 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5469 if (DEBUG_DOMAIN_VERIFICATION) { 5470 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5471 } 5472 neverList.add(info); 5473 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5474 if (DEBUG_DOMAIN_VERIFICATION) { 5475 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5476 } 5477 alwaysAskList.add(info); 5478 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5479 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5480 if (DEBUG_DOMAIN_VERIFICATION) { 5481 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5482 } 5483 undefinedList.add(info); 5484 } 5485 } 5486 } 5487 5488 // We'll want to include browser possibilities in a few cases 5489 boolean includeBrowser = false; 5490 5491 // First try to add the "always" resolution(s) for the current user, if any 5492 if (alwaysList.size() > 0) { 5493 result.addAll(alwaysList); 5494 } else { 5495 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5496 result.addAll(undefinedList); 5497 // Maybe add one for the other profile. 5498 if (xpDomainInfo != null && ( 5499 xpDomainInfo.bestDomainVerificationStatus 5500 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5501 result.add(xpDomainInfo.resolveInfo); 5502 } 5503 includeBrowser = true; 5504 } 5505 5506 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5507 // If there were 'always' entries their preferred order has been set, so we also 5508 // back that off to make the alternatives equivalent 5509 if (alwaysAskList.size() > 0) { 5510 for (ResolveInfo i : result) { 5511 i.preferredOrder = 0; 5512 } 5513 result.addAll(alwaysAskList); 5514 includeBrowser = true; 5515 } 5516 5517 if (includeBrowser) { 5518 // Also add browsers (all of them or only the default one) 5519 if (DEBUG_DOMAIN_VERIFICATION) { 5520 Slog.v(TAG, " ...including browsers in candidate set"); 5521 } 5522 if ((matchFlags & MATCH_ALL) != 0) { 5523 result.addAll(matchAllList); 5524 } else { 5525 // Browser/generic handling case. If there's a default browser, go straight 5526 // to that (but only if there is no other higher-priority match). 5527 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5528 int maxMatchPrio = 0; 5529 ResolveInfo defaultBrowserMatch = null; 5530 final int numCandidates = matchAllList.size(); 5531 for (int n = 0; n < numCandidates; n++) { 5532 ResolveInfo info = matchAllList.get(n); 5533 // track the highest overall match priority... 5534 if (info.priority > maxMatchPrio) { 5535 maxMatchPrio = info.priority; 5536 } 5537 // ...and the highest-priority default browser match 5538 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5539 if (defaultBrowserMatch == null 5540 || (defaultBrowserMatch.priority < info.priority)) { 5541 if (debug) { 5542 Slog.v(TAG, "Considering default browser match " + info); 5543 } 5544 defaultBrowserMatch = info; 5545 } 5546 } 5547 } 5548 if (defaultBrowserMatch != null 5549 && defaultBrowserMatch.priority >= maxMatchPrio 5550 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5551 { 5552 if (debug) { 5553 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5554 } 5555 result.add(defaultBrowserMatch); 5556 } else { 5557 result.addAll(matchAllList); 5558 } 5559 } 5560 5561 // If there is nothing selected, add all candidates and remove the ones that the user 5562 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5563 if (result.size() == 0) { 5564 result.addAll(candidates); 5565 result.removeAll(neverList); 5566 } 5567 } 5568 } 5569 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5570 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5571 result.size()); 5572 for (ResolveInfo info : result) { 5573 Slog.v(TAG, " + " + info.activityInfo); 5574 } 5575 } 5576 return result; 5577 } 5578 5579 // Returns a packed value as a long: 5580 // 5581 // high 'int'-sized word: link status: undefined/ask/never/always. 5582 // low 'int'-sized word: relative priority among 'always' results. 5583 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5584 long result = ps.getDomainVerificationStatusForUser(userId); 5585 // if none available, get the master status 5586 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5587 if (ps.getIntentFilterVerificationInfo() != null) { 5588 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5589 } 5590 } 5591 return result; 5592 } 5593 5594 private ResolveInfo querySkipCurrentProfileIntents( 5595 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5596 int flags, int sourceUserId) { 5597 if (matchingFilters != null) { 5598 int size = matchingFilters.size(); 5599 for (int i = 0; i < size; i ++) { 5600 CrossProfileIntentFilter filter = matchingFilters.get(i); 5601 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5602 // Checking if there are activities in the target user that can handle the 5603 // intent. 5604 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5605 resolvedType, flags, sourceUserId); 5606 if (resolveInfo != null) { 5607 return resolveInfo; 5608 } 5609 } 5610 } 5611 } 5612 return null; 5613 } 5614 5615 // Return matching ResolveInfo in target user if any. 5616 private ResolveInfo queryCrossProfileIntents( 5617 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5618 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5619 if (matchingFilters != null) { 5620 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5621 // match the same intent. For performance reasons, it is better not to 5622 // run queryIntent twice for the same userId 5623 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5624 int size = matchingFilters.size(); 5625 for (int i = 0; i < size; i++) { 5626 CrossProfileIntentFilter filter = matchingFilters.get(i); 5627 int targetUserId = filter.getTargetUserId(); 5628 boolean skipCurrentProfile = 5629 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5630 boolean skipCurrentProfileIfNoMatchFound = 5631 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5632 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5633 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5634 // Checking if there are activities in the target user that can handle the 5635 // intent. 5636 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5637 resolvedType, flags, sourceUserId); 5638 if (resolveInfo != null) return resolveInfo; 5639 alreadyTriedUserIds.put(targetUserId, true); 5640 } 5641 } 5642 } 5643 return null; 5644 } 5645 5646 /** 5647 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5648 * will forward the intent to the filter's target user. 5649 * Otherwise, returns null. 5650 */ 5651 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5652 String resolvedType, int flags, int sourceUserId) { 5653 int targetUserId = filter.getTargetUserId(); 5654 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5655 resolvedType, flags, targetUserId); 5656 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5657 // If all the matches in the target profile are suspended, return null. 5658 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5659 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5660 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5661 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5662 targetUserId); 5663 } 5664 } 5665 } 5666 return null; 5667 } 5668 5669 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5670 int sourceUserId, int targetUserId) { 5671 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5672 long ident = Binder.clearCallingIdentity(); 5673 boolean targetIsProfile; 5674 try { 5675 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5676 } finally { 5677 Binder.restoreCallingIdentity(ident); 5678 } 5679 String className; 5680 if (targetIsProfile) { 5681 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5682 } else { 5683 className = FORWARD_INTENT_TO_PARENT; 5684 } 5685 ComponentName forwardingActivityComponentName = new ComponentName( 5686 mAndroidApplication.packageName, className); 5687 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5688 sourceUserId); 5689 if (!targetIsProfile) { 5690 forwardingActivityInfo.showUserIcon = targetUserId; 5691 forwardingResolveInfo.noResourceId = true; 5692 } 5693 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5694 forwardingResolveInfo.priority = 0; 5695 forwardingResolveInfo.preferredOrder = 0; 5696 forwardingResolveInfo.match = 0; 5697 forwardingResolveInfo.isDefault = true; 5698 forwardingResolveInfo.filter = filter; 5699 forwardingResolveInfo.targetUserId = targetUserId; 5700 return forwardingResolveInfo; 5701 } 5702 5703 @Override 5704 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5705 Intent[] specifics, String[] specificTypes, Intent intent, 5706 String resolvedType, int flags, int userId) { 5707 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5708 specificTypes, intent, resolvedType, flags, userId)); 5709 } 5710 5711 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5712 Intent[] specifics, String[] specificTypes, Intent intent, 5713 String resolvedType, int flags, int userId) { 5714 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5715 flags = updateFlagsForResolve(flags, userId, intent); 5716 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5717 false /* requireFullPermission */, false /* checkShell */, 5718 "query intent activity options"); 5719 final String resultsAction = intent.getAction(); 5720 5721 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5722 | PackageManager.GET_RESOLVED_FILTER, userId); 5723 5724 if (DEBUG_INTENT_MATCHING) { 5725 Log.v(TAG, "Query " + intent + ": " + results); 5726 } 5727 5728 int specificsPos = 0; 5729 int N; 5730 5731 // todo: note that the algorithm used here is O(N^2). This 5732 // isn't a problem in our current environment, but if we start running 5733 // into situations where we have more than 5 or 10 matches then this 5734 // should probably be changed to something smarter... 5735 5736 // First we go through and resolve each of the specific items 5737 // that were supplied, taking care of removing any corresponding 5738 // duplicate items in the generic resolve list. 5739 if (specifics != null) { 5740 for (int i=0; i<specifics.length; i++) { 5741 final Intent sintent = specifics[i]; 5742 if (sintent == null) { 5743 continue; 5744 } 5745 5746 if (DEBUG_INTENT_MATCHING) { 5747 Log.v(TAG, "Specific #" + i + ": " + sintent); 5748 } 5749 5750 String action = sintent.getAction(); 5751 if (resultsAction != null && resultsAction.equals(action)) { 5752 // If this action was explicitly requested, then don't 5753 // remove things that have it. 5754 action = null; 5755 } 5756 5757 ResolveInfo ri = null; 5758 ActivityInfo ai = null; 5759 5760 ComponentName comp = sintent.getComponent(); 5761 if (comp == null) { 5762 ri = resolveIntent( 5763 sintent, 5764 specificTypes != null ? specificTypes[i] : null, 5765 flags, userId); 5766 if (ri == null) { 5767 continue; 5768 } 5769 if (ri == mResolveInfo) { 5770 // ACK! Must do something better with this. 5771 } 5772 ai = ri.activityInfo; 5773 comp = new ComponentName(ai.applicationInfo.packageName, 5774 ai.name); 5775 } else { 5776 ai = getActivityInfo(comp, flags, userId); 5777 if (ai == null) { 5778 continue; 5779 } 5780 } 5781 5782 // Look for any generic query activities that are duplicates 5783 // of this specific one, and remove them from the results. 5784 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5785 N = results.size(); 5786 int j; 5787 for (j=specificsPos; j<N; j++) { 5788 ResolveInfo sri = results.get(j); 5789 if ((sri.activityInfo.name.equals(comp.getClassName()) 5790 && sri.activityInfo.applicationInfo.packageName.equals( 5791 comp.getPackageName())) 5792 || (action != null && sri.filter.matchAction(action))) { 5793 results.remove(j); 5794 if (DEBUG_INTENT_MATCHING) Log.v( 5795 TAG, "Removing duplicate item from " + j 5796 + " due to specific " + specificsPos); 5797 if (ri == null) { 5798 ri = sri; 5799 } 5800 j--; 5801 N--; 5802 } 5803 } 5804 5805 // Add this specific item to its proper place. 5806 if (ri == null) { 5807 ri = new ResolveInfo(); 5808 ri.activityInfo = ai; 5809 } 5810 results.add(specificsPos, ri); 5811 ri.specificIndex = i; 5812 specificsPos++; 5813 } 5814 } 5815 5816 // Now we go through the remaining generic results and remove any 5817 // duplicate actions that are found here. 5818 N = results.size(); 5819 for (int i=specificsPos; i<N-1; i++) { 5820 final ResolveInfo rii = results.get(i); 5821 if (rii.filter == null) { 5822 continue; 5823 } 5824 5825 // Iterate over all of the actions of this result's intent 5826 // filter... typically this should be just one. 5827 final Iterator<String> it = rii.filter.actionsIterator(); 5828 if (it == null) { 5829 continue; 5830 } 5831 while (it.hasNext()) { 5832 final String action = it.next(); 5833 if (resultsAction != null && resultsAction.equals(action)) { 5834 // If this action was explicitly requested, then don't 5835 // remove things that have it. 5836 continue; 5837 } 5838 for (int j=i+1; j<N; j++) { 5839 final ResolveInfo rij = results.get(j); 5840 if (rij.filter != null && rij.filter.hasAction(action)) { 5841 results.remove(j); 5842 if (DEBUG_INTENT_MATCHING) Log.v( 5843 TAG, "Removing duplicate item from " + j 5844 + " due to action " + action + " at " + i); 5845 j--; 5846 N--; 5847 } 5848 } 5849 } 5850 5851 // If the caller didn't request filter information, drop it now 5852 // so we don't have to marshall/unmarshall it. 5853 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5854 rii.filter = null; 5855 } 5856 } 5857 5858 // Filter out the caller activity if so requested. 5859 if (caller != null) { 5860 N = results.size(); 5861 for (int i=0; i<N; i++) { 5862 ActivityInfo ainfo = results.get(i).activityInfo; 5863 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5864 && caller.getClassName().equals(ainfo.name)) { 5865 results.remove(i); 5866 break; 5867 } 5868 } 5869 } 5870 5871 // If the caller didn't request filter information, 5872 // drop them now so we don't have to 5873 // marshall/unmarshall it. 5874 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5875 N = results.size(); 5876 for (int i=0; i<N; i++) { 5877 results.get(i).filter = null; 5878 } 5879 } 5880 5881 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5882 return results; 5883 } 5884 5885 @Override 5886 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5887 String resolvedType, int flags, int userId) { 5888 return new ParceledListSlice<>( 5889 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5890 } 5891 5892 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5893 String resolvedType, int flags, int userId) { 5894 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5895 flags = updateFlagsForResolve(flags, userId, intent); 5896 ComponentName comp = intent.getComponent(); 5897 if (comp == null) { 5898 if (intent.getSelector() != null) { 5899 intent = intent.getSelector(); 5900 comp = intent.getComponent(); 5901 } 5902 } 5903 if (comp != null) { 5904 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5905 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5906 if (ai != null) { 5907 ResolveInfo ri = new ResolveInfo(); 5908 ri.activityInfo = ai; 5909 list.add(ri); 5910 } 5911 return list; 5912 } 5913 5914 // reader 5915 synchronized (mPackages) { 5916 String pkgName = intent.getPackage(); 5917 if (pkgName == null) { 5918 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5919 } 5920 final PackageParser.Package pkg = mPackages.get(pkgName); 5921 if (pkg != null) { 5922 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5923 userId); 5924 } 5925 return Collections.emptyList(); 5926 } 5927 } 5928 5929 @Override 5930 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5931 if (!sUserManager.exists(userId)) return null; 5932 flags = updateFlagsForResolve(flags, userId, intent); 5933 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5934 if (query != null) { 5935 if (query.size() >= 1) { 5936 // If there is more than one service with the same priority, 5937 // just arbitrarily pick the first one. 5938 return query.get(0); 5939 } 5940 } 5941 return null; 5942 } 5943 5944 @Override 5945 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5946 String resolvedType, int flags, int userId) { 5947 return new ParceledListSlice<>( 5948 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5949 } 5950 5951 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5952 String resolvedType, int flags, int userId) { 5953 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5954 flags = updateFlagsForResolve(flags, userId, intent); 5955 ComponentName comp = intent.getComponent(); 5956 if (comp == null) { 5957 if (intent.getSelector() != null) { 5958 intent = intent.getSelector(); 5959 comp = intent.getComponent(); 5960 } 5961 } 5962 if (comp != null) { 5963 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5964 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5965 if (si != null) { 5966 final ResolveInfo ri = new ResolveInfo(); 5967 ri.serviceInfo = si; 5968 list.add(ri); 5969 } 5970 return list; 5971 } 5972 5973 // reader 5974 synchronized (mPackages) { 5975 String pkgName = intent.getPackage(); 5976 if (pkgName == null) { 5977 return mServices.queryIntent(intent, resolvedType, flags, userId); 5978 } 5979 final PackageParser.Package pkg = mPackages.get(pkgName); 5980 if (pkg != null) { 5981 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5982 userId); 5983 } 5984 return Collections.emptyList(); 5985 } 5986 } 5987 5988 @Override 5989 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5990 String resolvedType, int flags, int userId) { 5991 return new ParceledListSlice<>( 5992 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5993 } 5994 5995 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5996 Intent intent, String resolvedType, int flags, int userId) { 5997 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5998 flags = updateFlagsForResolve(flags, userId, intent); 5999 ComponentName comp = intent.getComponent(); 6000 if (comp == null) { 6001 if (intent.getSelector() != null) { 6002 intent = intent.getSelector(); 6003 comp = intent.getComponent(); 6004 } 6005 } 6006 if (comp != null) { 6007 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6008 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6009 if (pi != null) { 6010 final ResolveInfo ri = new ResolveInfo(); 6011 ri.providerInfo = pi; 6012 list.add(ri); 6013 } 6014 return list; 6015 } 6016 6017 // reader 6018 synchronized (mPackages) { 6019 String pkgName = intent.getPackage(); 6020 if (pkgName == null) { 6021 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6022 } 6023 final PackageParser.Package pkg = mPackages.get(pkgName); 6024 if (pkg != null) { 6025 return mProviders.queryIntentForPackage( 6026 intent, resolvedType, flags, pkg.providers, userId); 6027 } 6028 return Collections.emptyList(); 6029 } 6030 } 6031 6032 @Override 6033 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6034 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6035 flags = updateFlagsForPackage(flags, userId, null); 6036 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6037 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6038 true /* requireFullPermission */, false /* checkShell */, 6039 "get installed packages"); 6040 6041 // writer 6042 synchronized (mPackages) { 6043 ArrayList<PackageInfo> list; 6044 if (listUninstalled) { 6045 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6046 for (PackageSetting ps : mSettings.mPackages.values()) { 6047 final PackageInfo pi; 6048 if (ps.pkg != null) { 6049 pi = generatePackageInfo(ps, flags, userId); 6050 } else { 6051 pi = generatePackageInfo(ps, flags, userId); 6052 } 6053 if (pi != null) { 6054 list.add(pi); 6055 } 6056 } 6057 } else { 6058 list = new ArrayList<PackageInfo>(mPackages.size()); 6059 for (PackageParser.Package p : mPackages.values()) { 6060 final PackageInfo pi = 6061 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6062 if (pi != null) { 6063 list.add(pi); 6064 } 6065 } 6066 } 6067 6068 return new ParceledListSlice<PackageInfo>(list); 6069 } 6070 } 6071 6072 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6073 String[] permissions, boolean[] tmp, int flags, int userId) { 6074 int numMatch = 0; 6075 final PermissionsState permissionsState = ps.getPermissionsState(); 6076 for (int i=0; i<permissions.length; i++) { 6077 final String permission = permissions[i]; 6078 if (permissionsState.hasPermission(permission, userId)) { 6079 tmp[i] = true; 6080 numMatch++; 6081 } else { 6082 tmp[i] = false; 6083 } 6084 } 6085 if (numMatch == 0) { 6086 return; 6087 } 6088 final PackageInfo pi; 6089 if (ps.pkg != null) { 6090 pi = generatePackageInfo(ps, flags, userId); 6091 } else { 6092 pi = generatePackageInfo(ps, flags, userId); 6093 } 6094 // The above might return null in cases of uninstalled apps or install-state 6095 // skew across users/profiles. 6096 if (pi != null) { 6097 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6098 if (numMatch == permissions.length) { 6099 pi.requestedPermissions = permissions; 6100 } else { 6101 pi.requestedPermissions = new String[numMatch]; 6102 numMatch = 0; 6103 for (int i=0; i<permissions.length; i++) { 6104 if (tmp[i]) { 6105 pi.requestedPermissions[numMatch] = permissions[i]; 6106 numMatch++; 6107 } 6108 } 6109 } 6110 } 6111 list.add(pi); 6112 } 6113 } 6114 6115 @Override 6116 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6117 String[] permissions, int flags, int userId) { 6118 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6119 flags = updateFlagsForPackage(flags, userId, permissions); 6120 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6121 6122 // writer 6123 synchronized (mPackages) { 6124 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6125 boolean[] tmpBools = new boolean[permissions.length]; 6126 if (listUninstalled) { 6127 for (PackageSetting ps : mSettings.mPackages.values()) { 6128 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6129 } 6130 } else { 6131 for (PackageParser.Package pkg : mPackages.values()) { 6132 PackageSetting ps = (PackageSetting)pkg.mExtras; 6133 if (ps != null) { 6134 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6135 userId); 6136 } 6137 } 6138 } 6139 6140 return new ParceledListSlice<PackageInfo>(list); 6141 } 6142 } 6143 6144 @Override 6145 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6146 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6147 flags = updateFlagsForApplication(flags, userId, null); 6148 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6149 6150 // writer 6151 synchronized (mPackages) { 6152 ArrayList<ApplicationInfo> list; 6153 if (listUninstalled) { 6154 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6155 for (PackageSetting ps : mSettings.mPackages.values()) { 6156 ApplicationInfo ai; 6157 if (ps.pkg != null) { 6158 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6159 ps.readUserState(userId), userId); 6160 } else { 6161 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6162 } 6163 if (ai != null) { 6164 list.add(ai); 6165 } 6166 } 6167 } else { 6168 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6169 for (PackageParser.Package p : mPackages.values()) { 6170 if (p.mExtras != null) { 6171 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6172 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6173 if (ai != null) { 6174 list.add(ai); 6175 } 6176 } 6177 } 6178 } 6179 6180 return new ParceledListSlice<ApplicationInfo>(list); 6181 } 6182 } 6183 6184 @Override 6185 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6186 if (DISABLE_EPHEMERAL_APPS) { 6187 return null; 6188 } 6189 6190 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6191 "getEphemeralApplications"); 6192 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6193 true /* requireFullPermission */, false /* checkShell */, 6194 "getEphemeralApplications"); 6195 synchronized (mPackages) { 6196 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6197 .getEphemeralApplicationsLPw(userId); 6198 if (ephemeralApps != null) { 6199 return new ParceledListSlice<>(ephemeralApps); 6200 } 6201 } 6202 return null; 6203 } 6204 6205 @Override 6206 public boolean isEphemeralApplication(String packageName, int userId) { 6207 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6208 true /* requireFullPermission */, false /* checkShell */, 6209 "isEphemeral"); 6210 if (DISABLE_EPHEMERAL_APPS) { 6211 return false; 6212 } 6213 6214 if (!isCallerSameApp(packageName)) { 6215 return false; 6216 } 6217 synchronized (mPackages) { 6218 PackageParser.Package pkg = mPackages.get(packageName); 6219 if (pkg != null) { 6220 return pkg.applicationInfo.isEphemeralApp(); 6221 } 6222 } 6223 return false; 6224 } 6225 6226 @Override 6227 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6228 if (DISABLE_EPHEMERAL_APPS) { 6229 return null; 6230 } 6231 6232 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6233 true /* requireFullPermission */, false /* checkShell */, 6234 "getCookie"); 6235 if (!isCallerSameApp(packageName)) { 6236 return null; 6237 } 6238 synchronized (mPackages) { 6239 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6240 packageName, userId); 6241 } 6242 } 6243 6244 @Override 6245 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6246 if (DISABLE_EPHEMERAL_APPS) { 6247 return true; 6248 } 6249 6250 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6251 true /* requireFullPermission */, true /* checkShell */, 6252 "setCookie"); 6253 if (!isCallerSameApp(packageName)) { 6254 return false; 6255 } 6256 synchronized (mPackages) { 6257 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6258 packageName, cookie, userId); 6259 } 6260 } 6261 6262 @Override 6263 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6264 if (DISABLE_EPHEMERAL_APPS) { 6265 return null; 6266 } 6267 6268 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6269 "getEphemeralApplicationIcon"); 6270 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6271 true /* requireFullPermission */, false /* checkShell */, 6272 "getEphemeralApplicationIcon"); 6273 synchronized (mPackages) { 6274 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6275 packageName, userId); 6276 } 6277 } 6278 6279 private boolean isCallerSameApp(String packageName) { 6280 PackageParser.Package pkg = mPackages.get(packageName); 6281 return pkg != null 6282 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6283 } 6284 6285 @Override 6286 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6287 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6288 } 6289 6290 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6291 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6292 6293 // reader 6294 synchronized (mPackages) { 6295 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6296 final int userId = UserHandle.getCallingUserId(); 6297 while (i.hasNext()) { 6298 final PackageParser.Package p = i.next(); 6299 if (p.applicationInfo == null) continue; 6300 6301 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6302 && !p.applicationInfo.isDirectBootAware(); 6303 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6304 && p.applicationInfo.isDirectBootAware(); 6305 6306 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6307 && (!mSafeMode || isSystemApp(p)) 6308 && (matchesUnaware || matchesAware)) { 6309 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6310 if (ps != null) { 6311 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6312 ps.readUserState(userId), userId); 6313 if (ai != null) { 6314 finalList.add(ai); 6315 } 6316 } 6317 } 6318 } 6319 } 6320 6321 return finalList; 6322 } 6323 6324 @Override 6325 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6326 if (!sUserManager.exists(userId)) return null; 6327 flags = updateFlagsForComponent(flags, userId, name); 6328 // reader 6329 synchronized (mPackages) { 6330 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6331 PackageSetting ps = provider != null 6332 ? mSettings.mPackages.get(provider.owner.packageName) 6333 : null; 6334 return ps != null 6335 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6336 ? PackageParser.generateProviderInfo(provider, flags, 6337 ps.readUserState(userId), userId) 6338 : null; 6339 } 6340 } 6341 6342 /** 6343 * @deprecated 6344 */ 6345 @Deprecated 6346 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6347 // reader 6348 synchronized (mPackages) { 6349 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6350 .entrySet().iterator(); 6351 final int userId = UserHandle.getCallingUserId(); 6352 while (i.hasNext()) { 6353 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6354 PackageParser.Provider p = entry.getValue(); 6355 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6356 6357 if (ps != null && p.syncable 6358 && (!mSafeMode || (p.info.applicationInfo.flags 6359 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6360 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6361 ps.readUserState(userId), userId); 6362 if (info != null) { 6363 outNames.add(entry.getKey()); 6364 outInfo.add(info); 6365 } 6366 } 6367 } 6368 } 6369 } 6370 6371 @Override 6372 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6373 int uid, int flags) { 6374 final int userId = processName != null ? UserHandle.getUserId(uid) 6375 : UserHandle.getCallingUserId(); 6376 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6377 flags = updateFlagsForComponent(flags, userId, processName); 6378 6379 ArrayList<ProviderInfo> finalList = null; 6380 // reader 6381 synchronized (mPackages) { 6382 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6383 while (i.hasNext()) { 6384 final PackageParser.Provider p = i.next(); 6385 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6386 if (ps != null && p.info.authority != null 6387 && (processName == null 6388 || (p.info.processName.equals(processName) 6389 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6390 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6391 if (finalList == null) { 6392 finalList = new ArrayList<ProviderInfo>(3); 6393 } 6394 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6395 ps.readUserState(userId), userId); 6396 if (info != null) { 6397 finalList.add(info); 6398 } 6399 } 6400 } 6401 } 6402 6403 if (finalList != null) { 6404 Collections.sort(finalList, mProviderInitOrderSorter); 6405 return new ParceledListSlice<ProviderInfo>(finalList); 6406 } 6407 6408 return ParceledListSlice.emptyList(); 6409 } 6410 6411 @Override 6412 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6413 // reader 6414 synchronized (mPackages) { 6415 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6416 return PackageParser.generateInstrumentationInfo(i, flags); 6417 } 6418 } 6419 6420 @Override 6421 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6422 String targetPackage, int flags) { 6423 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6424 } 6425 6426 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6427 int flags) { 6428 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6429 6430 // reader 6431 synchronized (mPackages) { 6432 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6433 while (i.hasNext()) { 6434 final PackageParser.Instrumentation p = i.next(); 6435 if (targetPackage == null 6436 || targetPackage.equals(p.info.targetPackage)) { 6437 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6438 flags); 6439 if (ii != null) { 6440 finalList.add(ii); 6441 } 6442 } 6443 } 6444 } 6445 6446 return finalList; 6447 } 6448 6449 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6450 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6451 if (overlays == null) { 6452 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6453 return; 6454 } 6455 for (PackageParser.Package opkg : overlays.values()) { 6456 // Not much to do if idmap fails: we already logged the error 6457 // and we certainly don't want to abort installation of pkg simply 6458 // because an overlay didn't fit properly. For these reasons, 6459 // ignore the return value of createIdmapForPackagePairLI. 6460 createIdmapForPackagePairLI(pkg, opkg); 6461 } 6462 } 6463 6464 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6465 PackageParser.Package opkg) { 6466 if (!opkg.mTrustedOverlay) { 6467 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6468 opkg.baseCodePath + ": overlay not trusted"); 6469 return false; 6470 } 6471 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6472 if (overlaySet == null) { 6473 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6474 opkg.baseCodePath + " but target package has no known overlays"); 6475 return false; 6476 } 6477 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6478 // TODO: generate idmap for split APKs 6479 try { 6480 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6481 } catch (InstallerException e) { 6482 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6483 + opkg.baseCodePath); 6484 return false; 6485 } 6486 PackageParser.Package[] overlayArray = 6487 overlaySet.values().toArray(new PackageParser.Package[0]); 6488 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6489 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6490 return p1.mOverlayPriority - p2.mOverlayPriority; 6491 } 6492 }; 6493 Arrays.sort(overlayArray, cmp); 6494 6495 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6496 int i = 0; 6497 for (PackageParser.Package p : overlayArray) { 6498 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6499 } 6500 return true; 6501 } 6502 6503 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6504 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6505 try { 6506 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6507 } finally { 6508 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6509 } 6510 } 6511 6512 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6513 final File[] files = dir.listFiles(); 6514 if (ArrayUtils.isEmpty(files)) { 6515 Log.d(TAG, "No files in app dir " + dir); 6516 return; 6517 } 6518 6519 if (DEBUG_PACKAGE_SCANNING) { 6520 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6521 + " flags=0x" + Integer.toHexString(parseFlags)); 6522 } 6523 6524 for (File file : files) { 6525 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6526 && !PackageInstallerService.isStageName(file.getName()); 6527 if (!isPackage) { 6528 // Ignore entries which are not packages 6529 continue; 6530 } 6531 try { 6532 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6533 scanFlags, currentTime, null); 6534 } catch (PackageManagerException e) { 6535 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6536 6537 // Delete invalid userdata apps 6538 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6539 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6540 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6541 removeCodePathLI(file); 6542 } 6543 } 6544 } 6545 } 6546 6547 private static File getSettingsProblemFile() { 6548 File dataDir = Environment.getDataDirectory(); 6549 File systemDir = new File(dataDir, "system"); 6550 File fname = new File(systemDir, "uiderrors.txt"); 6551 return fname; 6552 } 6553 6554 static void reportSettingsProblem(int priority, String msg) { 6555 logCriticalInfo(priority, msg); 6556 } 6557 6558 static void logCriticalInfo(int priority, String msg) { 6559 Slog.println(priority, TAG, msg); 6560 EventLogTags.writePmCriticalInfo(msg); 6561 try { 6562 File fname = getSettingsProblemFile(); 6563 FileOutputStream out = new FileOutputStream(fname, true); 6564 PrintWriter pw = new FastPrintWriter(out); 6565 SimpleDateFormat formatter = new SimpleDateFormat(); 6566 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6567 pw.println(dateString + ": " + msg); 6568 pw.close(); 6569 FileUtils.setPermissions( 6570 fname.toString(), 6571 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6572 -1, -1); 6573 } catch (java.io.IOException e) { 6574 } 6575 } 6576 6577 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6578 int parseFlags) throws PackageManagerException { 6579 if (ps != null 6580 && ps.codePath.equals(srcFile) 6581 && ps.timeStamp == srcFile.lastModified() 6582 && !isCompatSignatureUpdateNeeded(pkg) 6583 && !isRecoverSignatureUpdateNeeded(pkg)) { 6584 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6585 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6586 ArraySet<PublicKey> signingKs; 6587 synchronized (mPackages) { 6588 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6589 } 6590 if (ps.signatures.mSignatures != null 6591 && ps.signatures.mSignatures.length != 0 6592 && signingKs != null) { 6593 // Optimization: reuse the existing cached certificates 6594 // if the package appears to be unchanged. 6595 pkg.mSignatures = ps.signatures.mSignatures; 6596 pkg.mSigningKeys = signingKs; 6597 return; 6598 } 6599 6600 Slog.w(TAG, "PackageSetting for " + ps.name 6601 + " is missing signatures. Collecting certs again to recover them."); 6602 } else { 6603 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6604 } 6605 6606 try { 6607 PackageParser.collectCertificates(pkg, parseFlags); 6608 } catch (PackageParserException e) { 6609 throw PackageManagerException.from(e); 6610 } 6611 } 6612 6613 /** 6614 * Traces a package scan. 6615 * @see #scanPackageLI(File, int, int, long, UserHandle) 6616 */ 6617 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6618 long currentTime, UserHandle user) throws PackageManagerException { 6619 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6620 try { 6621 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6622 } finally { 6623 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6624 } 6625 } 6626 6627 /** 6628 * Scans a package and returns the newly parsed package. 6629 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6630 */ 6631 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6632 long currentTime, UserHandle user) throws PackageManagerException { 6633 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6634 parseFlags |= mDefParseFlags; 6635 PackageParser pp = new PackageParser(); 6636 pp.setSeparateProcesses(mSeparateProcesses); 6637 pp.setOnlyCoreApps(mOnlyCore); 6638 pp.setDisplayMetrics(mMetrics); 6639 6640 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6641 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6642 } 6643 6644 final PackageParser.Package pkg; 6645 try { 6646 pkg = pp.parsePackage(scanFile, parseFlags); 6647 } catch (PackageParserException e) { 6648 throw PackageManagerException.from(e); 6649 } 6650 6651 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6652 } 6653 6654 /** 6655 * Scans a package and returns the newly parsed package. 6656 * @throws PackageManagerException on a parse error. 6657 */ 6658 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6659 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6660 throws PackageManagerException { 6661 // If the package has children and this is the first dive in the function 6662 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6663 // packages (parent and children) would be successfully scanned before the 6664 // actual scan since scanning mutates internal state and we want to atomically 6665 // install the package and its children. 6666 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6667 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6668 scanFlags |= SCAN_CHECK_ONLY; 6669 } 6670 } else { 6671 scanFlags &= ~SCAN_CHECK_ONLY; 6672 } 6673 6674 // Scan the parent 6675 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6676 scanFlags, currentTime, user); 6677 6678 // Scan the children 6679 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6680 for (int i = 0; i < childCount; i++) { 6681 PackageParser.Package childPackage = pkg.childPackages.get(i); 6682 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6683 currentTime, user); 6684 } 6685 6686 6687 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6688 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6689 } 6690 6691 return scannedPkg; 6692 } 6693 6694 /** 6695 * Scans a package and returns the newly parsed package. 6696 * @throws PackageManagerException on a parse error. 6697 */ 6698 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6699 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6700 throws PackageManagerException { 6701 PackageSetting ps = null; 6702 PackageSetting updatedPkg; 6703 // reader 6704 synchronized (mPackages) { 6705 // Look to see if we already know about this package. 6706 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6707 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6708 // This package has been renamed to its original name. Let's 6709 // use that. 6710 ps = mSettings.peekPackageLPr(oldName); 6711 } 6712 // If there was no original package, see one for the real package name. 6713 if (ps == null) { 6714 ps = mSettings.peekPackageLPr(pkg.packageName); 6715 } 6716 // Check to see if this package could be hiding/updating a system 6717 // package. Must look for it either under the original or real 6718 // package name depending on our state. 6719 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6720 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6721 6722 // If this is a package we don't know about on the system partition, we 6723 // may need to remove disabled child packages on the system partition 6724 // or may need to not add child packages if the parent apk is updated 6725 // on the data partition and no longer defines this child package. 6726 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6727 // If this is a parent package for an updated system app and this system 6728 // app got an OTA update which no longer defines some of the child packages 6729 // we have to prune them from the disabled system packages. 6730 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6731 if (disabledPs != null) { 6732 final int scannedChildCount = (pkg.childPackages != null) 6733 ? pkg.childPackages.size() : 0; 6734 final int disabledChildCount = disabledPs.childPackageNames != null 6735 ? disabledPs.childPackageNames.size() : 0; 6736 for (int i = 0; i < disabledChildCount; i++) { 6737 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6738 boolean disabledPackageAvailable = false; 6739 for (int j = 0; j < scannedChildCount; j++) { 6740 PackageParser.Package childPkg = pkg.childPackages.get(j); 6741 if (childPkg.packageName.equals(disabledChildPackageName)) { 6742 disabledPackageAvailable = true; 6743 break; 6744 } 6745 } 6746 if (!disabledPackageAvailable) { 6747 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6748 } 6749 } 6750 } 6751 } 6752 } 6753 6754 boolean updatedPkgBetter = false; 6755 // First check if this is a system package that may involve an update 6756 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6757 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6758 // it needs to drop FLAG_PRIVILEGED. 6759 if (locationIsPrivileged(scanFile)) { 6760 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6761 } else { 6762 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6763 } 6764 6765 if (ps != null && !ps.codePath.equals(scanFile)) { 6766 // The path has changed from what was last scanned... check the 6767 // version of the new path against what we have stored to determine 6768 // what to do. 6769 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6770 if (pkg.mVersionCode <= ps.versionCode) { 6771 // The system package has been updated and the code path does not match 6772 // Ignore entry. Skip it. 6773 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6774 + " ignored: updated version " + ps.versionCode 6775 + " better than this " + pkg.mVersionCode); 6776 if (!updatedPkg.codePath.equals(scanFile)) { 6777 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6778 + ps.name + " changing from " + updatedPkg.codePathString 6779 + " to " + scanFile); 6780 updatedPkg.codePath = scanFile; 6781 updatedPkg.codePathString = scanFile.toString(); 6782 updatedPkg.resourcePath = scanFile; 6783 updatedPkg.resourcePathString = scanFile.toString(); 6784 } 6785 updatedPkg.pkg = pkg; 6786 updatedPkg.versionCode = pkg.mVersionCode; 6787 6788 // Update the disabled system child packages to point to the package too. 6789 final int childCount = updatedPkg.childPackageNames != null 6790 ? updatedPkg.childPackageNames.size() : 0; 6791 for (int i = 0; i < childCount; i++) { 6792 String childPackageName = updatedPkg.childPackageNames.get(i); 6793 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6794 childPackageName); 6795 if (updatedChildPkg != null) { 6796 updatedChildPkg.pkg = pkg; 6797 updatedChildPkg.versionCode = pkg.mVersionCode; 6798 } 6799 } 6800 6801 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6802 + scanFile + " ignored: updated version " + ps.versionCode 6803 + " better than this " + pkg.mVersionCode); 6804 } else { 6805 // The current app on the system partition is better than 6806 // what we have updated to on the data partition; switch 6807 // back to the system partition version. 6808 // At this point, its safely assumed that package installation for 6809 // apps in system partition will go through. If not there won't be a working 6810 // version of the app 6811 // writer 6812 synchronized (mPackages) { 6813 // Just remove the loaded entries from package lists. 6814 mPackages.remove(ps.name); 6815 } 6816 6817 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6818 + " reverting from " + ps.codePathString 6819 + ": new version " + pkg.mVersionCode 6820 + " better than installed " + ps.versionCode); 6821 6822 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6823 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6824 synchronized (mInstallLock) { 6825 args.cleanUpResourcesLI(); 6826 } 6827 synchronized (mPackages) { 6828 mSettings.enableSystemPackageLPw(ps.name); 6829 } 6830 updatedPkgBetter = true; 6831 } 6832 } 6833 } 6834 6835 if (updatedPkg != null) { 6836 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6837 // initially 6838 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6839 6840 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6841 // flag set initially 6842 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6843 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6844 } 6845 } 6846 6847 // Verify certificates against what was last scanned 6848 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6849 6850 /* 6851 * A new system app appeared, but we already had a non-system one of the 6852 * same name installed earlier. 6853 */ 6854 boolean shouldHideSystemApp = false; 6855 if (updatedPkg == null && ps != null 6856 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6857 /* 6858 * Check to make sure the signatures match first. If they don't, 6859 * wipe the installed application and its data. 6860 */ 6861 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6862 != PackageManager.SIGNATURE_MATCH) { 6863 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6864 + " signatures don't match existing userdata copy; removing"); 6865 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6866 "scanPackageInternalLI")) { 6867 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6868 } 6869 ps = null; 6870 } else { 6871 /* 6872 * If the newly-added system app is an older version than the 6873 * already installed version, hide it. It will be scanned later 6874 * and re-added like an update. 6875 */ 6876 if (pkg.mVersionCode <= ps.versionCode) { 6877 shouldHideSystemApp = true; 6878 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6879 + " but new version " + pkg.mVersionCode + " better than installed " 6880 + ps.versionCode + "; hiding system"); 6881 } else { 6882 /* 6883 * The newly found system app is a newer version that the 6884 * one previously installed. Simply remove the 6885 * already-installed application and replace it with our own 6886 * while keeping the application data. 6887 */ 6888 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6889 + " reverting from " + ps.codePathString + ": new version " 6890 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6891 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6892 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6893 synchronized (mInstallLock) { 6894 args.cleanUpResourcesLI(); 6895 } 6896 } 6897 } 6898 } 6899 6900 // The apk is forward locked (not public) if its code and resources 6901 // are kept in different files. (except for app in either system or 6902 // vendor path). 6903 // TODO grab this value from PackageSettings 6904 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6905 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6906 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6907 } 6908 } 6909 6910 // TODO: extend to support forward-locked splits 6911 String resourcePath = null; 6912 String baseResourcePath = null; 6913 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6914 if (ps != null && ps.resourcePathString != null) { 6915 resourcePath = ps.resourcePathString; 6916 baseResourcePath = ps.resourcePathString; 6917 } else { 6918 // Should not happen at all. Just log an error. 6919 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6920 } 6921 } else { 6922 resourcePath = pkg.codePath; 6923 baseResourcePath = pkg.baseCodePath; 6924 } 6925 6926 // Set application objects path explicitly. 6927 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6928 pkg.setApplicationInfoCodePath(pkg.codePath); 6929 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6930 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6931 pkg.setApplicationInfoResourcePath(resourcePath); 6932 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6933 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6934 6935 // Note that we invoke the following method only if we are about to unpack an application 6936 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6937 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6938 6939 /* 6940 * If the system app should be overridden by a previously installed 6941 * data, hide the system app now and let the /data/app scan pick it up 6942 * again. 6943 */ 6944 if (shouldHideSystemApp) { 6945 synchronized (mPackages) { 6946 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6947 } 6948 } 6949 6950 return scannedPkg; 6951 } 6952 6953 private static String fixProcessName(String defProcessName, 6954 String processName, int uid) { 6955 if (processName == null) { 6956 return defProcessName; 6957 } 6958 return processName; 6959 } 6960 6961 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6962 throws PackageManagerException { 6963 if (pkgSetting.signatures.mSignatures != null) { 6964 // Already existing package. Make sure signatures match 6965 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6966 == PackageManager.SIGNATURE_MATCH; 6967 if (!match) { 6968 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6969 == PackageManager.SIGNATURE_MATCH; 6970 } 6971 if (!match) { 6972 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6973 == PackageManager.SIGNATURE_MATCH; 6974 } 6975 if (!match) { 6976 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6977 + pkg.packageName + " signatures do not match the " 6978 + "previously installed version; ignoring!"); 6979 } 6980 } 6981 6982 // Check for shared user signatures 6983 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6984 // Already existing package. Make sure signatures match 6985 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6986 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6987 if (!match) { 6988 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6989 == PackageManager.SIGNATURE_MATCH; 6990 } 6991 if (!match) { 6992 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6993 == PackageManager.SIGNATURE_MATCH; 6994 } 6995 if (!match) { 6996 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6997 "Package " + pkg.packageName 6998 + " has no signatures that match those in shared user " 6999 + pkgSetting.sharedUser.name + "; ignoring!"); 7000 } 7001 } 7002 } 7003 7004 /** 7005 * Enforces that only the system UID or root's UID can call a method exposed 7006 * via Binder. 7007 * 7008 * @param message used as message if SecurityException is thrown 7009 * @throws SecurityException if the caller is not system or root 7010 */ 7011 private static final void enforceSystemOrRoot(String message) { 7012 final int uid = Binder.getCallingUid(); 7013 if (uid != Process.SYSTEM_UID && uid != 0) { 7014 throw new SecurityException(message); 7015 } 7016 } 7017 7018 @Override 7019 public void performFstrimIfNeeded() { 7020 enforceSystemOrRoot("Only the system can request fstrim"); 7021 7022 // Before everything else, see whether we need to fstrim. 7023 try { 7024 IMountService ms = PackageHelper.getMountService(); 7025 if (ms != null) { 7026 final boolean isUpgrade = isUpgrade(); 7027 boolean doTrim = isUpgrade; 7028 if (doTrim) { 7029 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7030 } else { 7031 final long interval = android.provider.Settings.Global.getLong( 7032 mContext.getContentResolver(), 7033 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7034 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7035 if (interval > 0) { 7036 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7037 if (timeSinceLast > interval) { 7038 doTrim = true; 7039 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7040 + "; running immediately"); 7041 } 7042 } 7043 } 7044 if (doTrim) { 7045 if (!isFirstBoot()) { 7046 try { 7047 ActivityManagerNative.getDefault().showBootMessage( 7048 mContext.getResources().getString( 7049 R.string.android_upgrading_fstrim), true); 7050 } catch (RemoteException e) { 7051 } 7052 } 7053 ms.runMaintenance(); 7054 } 7055 } else { 7056 Slog.e(TAG, "Mount service unavailable!"); 7057 } 7058 } catch (RemoteException e) { 7059 // Can't happen; MountService is local 7060 } 7061 } 7062 7063 @Override 7064 public void updatePackagesIfNeeded() { 7065 enforceSystemOrRoot("Only the system can request package update"); 7066 7067 // We need to re-extract after an OTA. 7068 boolean causeUpgrade = isUpgrade(); 7069 7070 // First boot or factory reset. 7071 // Note: we also handle devices that are upgrading to N right now as if it is their 7072 // first boot, as they do not have profile data. 7073 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7074 7075 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7076 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7077 7078 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7079 return; 7080 } 7081 7082 List<PackageParser.Package> pkgs; 7083 synchronized (mPackages) { 7084 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7085 } 7086 7087 int curr = 0; 7088 int total = pkgs.size(); 7089 for (PackageParser.Package pkg : pkgs) { 7090 curr++; 7091 7092 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7093 if (DEBUG_DEXOPT) { 7094 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7095 } 7096 continue; 7097 } 7098 7099 if (DEBUG_DEXOPT) { 7100 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7101 } 7102 7103 if (!isFirstBoot()) { 7104 try { 7105 ActivityManagerNative.getDefault().showBootMessage( 7106 mContext.getResources().getString(R.string.android_upgrading_apk, 7107 curr, total), true); 7108 } catch (RemoteException e) { 7109 } 7110 } 7111 7112 performDexOpt(pkg.packageName, 7113 null /* instructionSet */, 7114 false /* checkProfiles */, 7115 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7116 false /* force */); 7117 } 7118 } 7119 7120 @Override 7121 public void notifyPackageUse(String packageName) { 7122 synchronized (mPackages) { 7123 PackageParser.Package p = mPackages.get(packageName); 7124 if (p == null) { 7125 return; 7126 } 7127 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7128 } 7129 } 7130 7131 // TODO: this is not used nor needed. Delete it. 7132 @Override 7133 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7134 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7135 getFullCompilerFilter(), false /* force */); 7136 } 7137 7138 @Override 7139 public boolean performDexOpt(String packageName, String instructionSet, 7140 boolean checkProfiles, int compileReason, boolean force) { 7141 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7142 getCompilerFilterForReason(compileReason), force); 7143 } 7144 7145 @Override 7146 public boolean performDexOptMode(String packageName, String instructionSet, 7147 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7148 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7149 targetCompilerFilter, force); 7150 } 7151 7152 private boolean performDexOptTraced(String packageName, String instructionSet, 7153 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7154 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7155 try { 7156 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7157 targetCompilerFilter, force); 7158 } finally { 7159 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7160 } 7161 } 7162 7163 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7164 // if the package can now be considered up to date for the given filter. 7165 private boolean performDexOptInternal(String packageName, String instructionSet, 7166 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7167 PackageParser.Package p; 7168 final String targetInstructionSet; 7169 synchronized (mPackages) { 7170 p = mPackages.get(packageName); 7171 if (p == null) { 7172 return false; 7173 } 7174 mPackageUsage.write(false); 7175 7176 targetInstructionSet = instructionSet != null ? instructionSet : 7177 getPrimaryInstructionSet(p.applicationInfo); 7178 } 7179 long callingId = Binder.clearCallingIdentity(); 7180 try { 7181 synchronized (mInstallLock) { 7182 final String[] instructionSets = new String[] { targetInstructionSet }; 7183 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7184 checkProfiles, targetCompilerFilter, force); 7185 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7186 } 7187 } finally { 7188 Binder.restoreCallingIdentity(callingId); 7189 } 7190 } 7191 7192 public ArraySet<String> getOptimizablePackages() { 7193 ArraySet<String> pkgs = new ArraySet<String>(); 7194 synchronized (mPackages) { 7195 for (PackageParser.Package p : mPackages.values()) { 7196 if (PackageDexOptimizer.canOptimizePackage(p)) { 7197 pkgs.add(p.packageName); 7198 } 7199 } 7200 } 7201 return pkgs; 7202 } 7203 7204 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7205 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7206 boolean force) { 7207 // Select the dex optimizer based on the force parameter. 7208 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7209 // allocate an object here. 7210 PackageDexOptimizer pdo = force 7211 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7212 : mPackageDexOptimizer; 7213 7214 // Optimize all dependencies first. Note: we ignore the return value and march on 7215 // on errors. 7216 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7217 if (!deps.isEmpty()) { 7218 for (PackageParser.Package depPackage : deps) { 7219 // TODO: Analyze and investigate if we (should) profile libraries. 7220 // Currently this will do a full compilation of the library by default. 7221 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7222 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7223 } 7224 } 7225 7226 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7227 } 7228 7229 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7230 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7231 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7232 Set<String> collectedNames = new HashSet<>(); 7233 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7234 7235 retValue.remove(p); 7236 7237 return retValue; 7238 } else { 7239 return Collections.emptyList(); 7240 } 7241 } 7242 7243 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7244 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7245 if (!collectedNames.contains(p.packageName)) { 7246 collectedNames.add(p.packageName); 7247 collected.add(p); 7248 7249 if (p.usesLibraries != null) { 7250 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7251 } 7252 if (p.usesOptionalLibraries != null) { 7253 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7254 collectedNames); 7255 } 7256 } 7257 } 7258 7259 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7260 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7261 for (String libName : libs) { 7262 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7263 if (libPkg != null) { 7264 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7265 } 7266 } 7267 } 7268 7269 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7270 synchronized (mPackages) { 7271 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7272 if (lib != null && lib.apk != null) { 7273 return mPackages.get(lib.apk); 7274 } 7275 } 7276 return null; 7277 } 7278 7279 public void shutdown() { 7280 mPackageUsage.write(true); 7281 } 7282 7283 @Override 7284 public void forceDexOpt(String packageName) { 7285 enforceSystemOrRoot("forceDexOpt"); 7286 7287 PackageParser.Package pkg; 7288 synchronized (mPackages) { 7289 pkg = mPackages.get(packageName); 7290 if (pkg == null) { 7291 throw new IllegalArgumentException("Unknown package: " + packageName); 7292 } 7293 } 7294 7295 synchronized (mInstallLock) { 7296 final String[] instructionSets = new String[] { 7297 getPrimaryInstructionSet(pkg.applicationInfo) }; 7298 7299 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7300 7301 // Whoever is calling forceDexOpt wants a fully compiled package. 7302 // Don't use profiles since that may cause compilation to be skipped. 7303 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7304 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7305 true /* force */); 7306 7307 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7308 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7309 throw new IllegalStateException("Failed to dexopt: " + res); 7310 } 7311 } 7312 } 7313 7314 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7315 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7316 Slog.w(TAG, "Unable to update from " + oldPkg.name 7317 + " to " + newPkg.packageName 7318 + ": old package not in system partition"); 7319 return false; 7320 } else if (mPackages.get(oldPkg.name) != null) { 7321 Slog.w(TAG, "Unable to update from " + oldPkg.name 7322 + " to " + newPkg.packageName 7323 + ": old package still exists"); 7324 return false; 7325 } 7326 return true; 7327 } 7328 7329 void removeCodePathLI(File codePath) { 7330 if (codePath.isDirectory()) { 7331 try { 7332 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7333 } catch (InstallerException e) { 7334 Slog.w(TAG, "Failed to remove code path", e); 7335 } 7336 } else { 7337 codePath.delete(); 7338 } 7339 } 7340 7341 private int[] resolveUserIds(int userId) { 7342 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7343 } 7344 7345 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7346 if (pkg == null) { 7347 Slog.wtf(TAG, "Package was null!", new Throwable()); 7348 return; 7349 } 7350 clearAppDataLeafLIF(pkg, userId, flags); 7351 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7352 for (int i = 0; i < childCount; i++) { 7353 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7354 } 7355 } 7356 7357 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7358 final PackageSetting ps; 7359 synchronized (mPackages) { 7360 ps = mSettings.mPackages.get(pkg.packageName); 7361 } 7362 for (int realUserId : resolveUserIds(userId)) { 7363 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7364 try { 7365 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7366 ceDataInode); 7367 } catch (InstallerException e) { 7368 Slog.w(TAG, String.valueOf(e)); 7369 } 7370 } 7371 } 7372 7373 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7374 if (pkg == null) { 7375 Slog.wtf(TAG, "Package was null!", new Throwable()); 7376 return; 7377 } 7378 destroyAppDataLeafLIF(pkg, userId, flags); 7379 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7380 for (int i = 0; i < childCount; i++) { 7381 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7382 } 7383 } 7384 7385 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7386 final PackageSetting ps; 7387 synchronized (mPackages) { 7388 ps = mSettings.mPackages.get(pkg.packageName); 7389 } 7390 for (int realUserId : resolveUserIds(userId)) { 7391 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7392 try { 7393 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7394 ceDataInode); 7395 } catch (InstallerException e) { 7396 Slog.w(TAG, String.valueOf(e)); 7397 } 7398 } 7399 } 7400 7401 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7402 if (pkg == null) { 7403 Slog.wtf(TAG, "Package was null!", new Throwable()); 7404 return; 7405 } 7406 destroyAppProfilesLeafLIF(pkg); 7407 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7408 for (int i = 0; i < childCount; i++) { 7409 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7410 } 7411 } 7412 7413 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7414 try { 7415 mInstaller.destroyAppProfiles(pkg.packageName); 7416 } catch (InstallerException e) { 7417 Slog.w(TAG, String.valueOf(e)); 7418 } 7419 } 7420 7421 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7422 if (pkg == null) { 7423 Slog.wtf(TAG, "Package was null!", new Throwable()); 7424 return; 7425 } 7426 clearAppProfilesLeafLIF(pkg); 7427 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7428 for (int i = 0; i < childCount; i++) { 7429 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7430 } 7431 } 7432 7433 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7434 try { 7435 mInstaller.clearAppProfiles(pkg.packageName); 7436 } catch (InstallerException e) { 7437 Slog.w(TAG, String.valueOf(e)); 7438 } 7439 } 7440 7441 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7442 long lastUpdateTime) { 7443 // Set parent install/update time 7444 PackageSetting ps = (PackageSetting) pkg.mExtras; 7445 if (ps != null) { 7446 ps.firstInstallTime = firstInstallTime; 7447 ps.lastUpdateTime = lastUpdateTime; 7448 } 7449 // Set children install/update time 7450 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7451 for (int i = 0; i < childCount; i++) { 7452 PackageParser.Package childPkg = pkg.childPackages.get(i); 7453 ps = (PackageSetting) childPkg.mExtras; 7454 if (ps != null) { 7455 ps.firstInstallTime = firstInstallTime; 7456 ps.lastUpdateTime = lastUpdateTime; 7457 } 7458 } 7459 } 7460 7461 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7462 PackageParser.Package changingLib) { 7463 if (file.path != null) { 7464 usesLibraryFiles.add(file.path); 7465 return; 7466 } 7467 PackageParser.Package p = mPackages.get(file.apk); 7468 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7469 // If we are doing this while in the middle of updating a library apk, 7470 // then we need to make sure to use that new apk for determining the 7471 // dependencies here. (We haven't yet finished committing the new apk 7472 // to the package manager state.) 7473 if (p == null || p.packageName.equals(changingLib.packageName)) { 7474 p = changingLib; 7475 } 7476 } 7477 if (p != null) { 7478 usesLibraryFiles.addAll(p.getAllCodePaths()); 7479 } 7480 } 7481 7482 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7483 PackageParser.Package changingLib) throws PackageManagerException { 7484 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7485 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7486 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7487 for (int i=0; i<N; i++) { 7488 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7489 if (file == null) { 7490 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7491 "Package " + pkg.packageName + " requires unavailable shared library " 7492 + pkg.usesLibraries.get(i) + "; failing!"); 7493 } 7494 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7495 } 7496 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7497 for (int i=0; i<N; i++) { 7498 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7499 if (file == null) { 7500 Slog.w(TAG, "Package " + pkg.packageName 7501 + " desires unavailable shared library " 7502 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7503 } else { 7504 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7505 } 7506 } 7507 N = usesLibraryFiles.size(); 7508 if (N > 0) { 7509 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7510 } else { 7511 pkg.usesLibraryFiles = null; 7512 } 7513 } 7514 } 7515 7516 private static boolean hasString(List<String> list, List<String> which) { 7517 if (list == null) { 7518 return false; 7519 } 7520 for (int i=list.size()-1; i>=0; i--) { 7521 for (int j=which.size()-1; j>=0; j--) { 7522 if (which.get(j).equals(list.get(i))) { 7523 return true; 7524 } 7525 } 7526 } 7527 return false; 7528 } 7529 7530 private void updateAllSharedLibrariesLPw() { 7531 for (PackageParser.Package pkg : mPackages.values()) { 7532 try { 7533 updateSharedLibrariesLPw(pkg, null); 7534 } catch (PackageManagerException e) { 7535 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7536 } 7537 } 7538 } 7539 7540 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7541 PackageParser.Package changingPkg) { 7542 ArrayList<PackageParser.Package> res = null; 7543 for (PackageParser.Package pkg : mPackages.values()) { 7544 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7545 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7546 if (res == null) { 7547 res = new ArrayList<PackageParser.Package>(); 7548 } 7549 res.add(pkg); 7550 try { 7551 updateSharedLibrariesLPw(pkg, changingPkg); 7552 } catch (PackageManagerException e) { 7553 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7554 } 7555 } 7556 } 7557 return res; 7558 } 7559 7560 /** 7561 * Derive the value of the {@code cpuAbiOverride} based on the provided 7562 * value and an optional stored value from the package settings. 7563 */ 7564 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7565 String cpuAbiOverride = null; 7566 7567 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7568 cpuAbiOverride = null; 7569 } else if (abiOverride != null) { 7570 cpuAbiOverride = abiOverride; 7571 } else if (settings != null) { 7572 cpuAbiOverride = settings.cpuAbiOverrideString; 7573 } 7574 7575 return cpuAbiOverride; 7576 } 7577 7578 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7579 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7580 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7581 // If the package has children and this is the first dive in the function 7582 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7583 // whether all packages (parent and children) would be successfully scanned 7584 // before the actual scan since scanning mutates internal state and we want 7585 // to atomically install the package and its children. 7586 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7587 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7588 scanFlags |= SCAN_CHECK_ONLY; 7589 } 7590 } else { 7591 scanFlags &= ~SCAN_CHECK_ONLY; 7592 } 7593 7594 final PackageParser.Package scannedPkg; 7595 try { 7596 // Scan the parent 7597 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7598 // Scan the children 7599 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7600 for (int i = 0; i < childCount; i++) { 7601 PackageParser.Package childPkg = pkg.childPackages.get(i); 7602 scanPackageLI(childPkg, parseFlags, 7603 scanFlags, currentTime, user); 7604 } 7605 } finally { 7606 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7607 } 7608 7609 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7610 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7611 } 7612 7613 return scannedPkg; 7614 } 7615 7616 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7617 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7618 boolean success = false; 7619 try { 7620 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7621 currentTime, user); 7622 success = true; 7623 return res; 7624 } finally { 7625 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7626 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7627 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7628 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7629 destroyAppProfilesLIF(pkg); 7630 } 7631 } 7632 } 7633 7634 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7635 int scanFlags, long currentTime, UserHandle user) 7636 throws PackageManagerException { 7637 final File scanFile = new File(pkg.codePath); 7638 if (pkg.applicationInfo.getCodePath() == null || 7639 pkg.applicationInfo.getResourcePath() == null) { 7640 // Bail out. The resource and code paths haven't been set. 7641 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7642 "Code and resource paths haven't been set correctly"); 7643 } 7644 7645 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7646 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7647 } else { 7648 // Only allow system apps to be flagged as core apps. 7649 pkg.coreApp = false; 7650 } 7651 7652 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7653 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7654 } 7655 7656 if (mCustomResolverComponentName != null && 7657 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7658 setUpCustomResolverActivity(pkg); 7659 } 7660 7661 if (pkg.packageName.equals("android")) { 7662 synchronized (mPackages) { 7663 if (mAndroidApplication != null) { 7664 Slog.w(TAG, "*************************************************"); 7665 Slog.w(TAG, "Core android package being redefined. Skipping."); 7666 Slog.w(TAG, " file=" + scanFile); 7667 Slog.w(TAG, "*************************************************"); 7668 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7669 "Core android package being redefined. Skipping."); 7670 } 7671 7672 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7673 // Set up information for our fall-back user intent resolution activity. 7674 mPlatformPackage = pkg; 7675 pkg.mVersionCode = mSdkVersion; 7676 mAndroidApplication = pkg.applicationInfo; 7677 7678 if (!mResolverReplaced) { 7679 mResolveActivity.applicationInfo = mAndroidApplication; 7680 mResolveActivity.name = ResolverActivity.class.getName(); 7681 mResolveActivity.packageName = mAndroidApplication.packageName; 7682 mResolveActivity.processName = "system:ui"; 7683 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7684 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7685 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7686 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7687 mResolveActivity.exported = true; 7688 mResolveActivity.enabled = true; 7689 mResolveInfo.activityInfo = mResolveActivity; 7690 mResolveInfo.priority = 0; 7691 mResolveInfo.preferredOrder = 0; 7692 mResolveInfo.match = 0; 7693 mResolveComponentName = new ComponentName( 7694 mAndroidApplication.packageName, mResolveActivity.name); 7695 } 7696 } 7697 } 7698 } 7699 7700 if (DEBUG_PACKAGE_SCANNING) { 7701 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7702 Log.d(TAG, "Scanning package " + pkg.packageName); 7703 } 7704 7705 synchronized (mPackages) { 7706 if (mPackages.containsKey(pkg.packageName) 7707 || mSharedLibraries.containsKey(pkg.packageName)) { 7708 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7709 "Application package " + pkg.packageName 7710 + " already installed. Skipping duplicate."); 7711 } 7712 7713 // If we're only installing presumed-existing packages, require that the 7714 // scanned APK is both already known and at the path previously established 7715 // for it. Previously unknown packages we pick up normally, but if we have an 7716 // a priori expectation about this package's install presence, enforce it. 7717 // With a singular exception for new system packages. When an OTA contains 7718 // a new system package, we allow the codepath to change from a system location 7719 // to the user-installed location. If we don't allow this change, any newer, 7720 // user-installed version of the application will be ignored. 7721 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7722 if (mExpectingBetter.containsKey(pkg.packageName)) { 7723 logCriticalInfo(Log.WARN, 7724 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7725 } else { 7726 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7727 if (known != null) { 7728 if (DEBUG_PACKAGE_SCANNING) { 7729 Log.d(TAG, "Examining " + pkg.codePath 7730 + " and requiring known paths " + known.codePathString 7731 + " & " + known.resourcePathString); 7732 } 7733 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7734 || !pkg.applicationInfo.getResourcePath().equals( 7735 known.resourcePathString)) { 7736 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7737 "Application package " + pkg.packageName 7738 + " found at " + pkg.applicationInfo.getCodePath() 7739 + " but expected at " + known.codePathString 7740 + "; ignoring."); 7741 } 7742 } 7743 } 7744 } 7745 } 7746 7747 // Initialize package source and resource directories 7748 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7749 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7750 7751 SharedUserSetting suid = null; 7752 PackageSetting pkgSetting = null; 7753 7754 if (!isSystemApp(pkg)) { 7755 // Only system apps can use these features. 7756 pkg.mOriginalPackages = null; 7757 pkg.mRealPackage = null; 7758 pkg.mAdoptPermissions = null; 7759 } 7760 7761 // Getting the package setting may have a side-effect, so if we 7762 // are only checking if scan would succeed, stash a copy of the 7763 // old setting to restore at the end. 7764 PackageSetting nonMutatedPs = null; 7765 7766 // writer 7767 synchronized (mPackages) { 7768 if (pkg.mSharedUserId != null) { 7769 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7770 if (suid == null) { 7771 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7772 "Creating application package " + pkg.packageName 7773 + " for shared user failed"); 7774 } 7775 if (DEBUG_PACKAGE_SCANNING) { 7776 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7777 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7778 + "): packages=" + suid.packages); 7779 } 7780 } 7781 7782 // Check if we are renaming from an original package name. 7783 PackageSetting origPackage = null; 7784 String realName = null; 7785 if (pkg.mOriginalPackages != null) { 7786 // This package may need to be renamed to a previously 7787 // installed name. Let's check on that... 7788 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7789 if (pkg.mOriginalPackages.contains(renamed)) { 7790 // This package had originally been installed as the 7791 // original name, and we have already taken care of 7792 // transitioning to the new one. Just update the new 7793 // one to continue using the old name. 7794 realName = pkg.mRealPackage; 7795 if (!pkg.packageName.equals(renamed)) { 7796 // Callers into this function may have already taken 7797 // care of renaming the package; only do it here if 7798 // it is not already done. 7799 pkg.setPackageName(renamed); 7800 } 7801 7802 } else { 7803 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7804 if ((origPackage = mSettings.peekPackageLPr( 7805 pkg.mOriginalPackages.get(i))) != null) { 7806 // We do have the package already installed under its 7807 // original name... should we use it? 7808 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7809 // New package is not compatible with original. 7810 origPackage = null; 7811 continue; 7812 } else if (origPackage.sharedUser != null) { 7813 // Make sure uid is compatible between packages. 7814 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7815 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7816 + " to " + pkg.packageName + ": old uid " 7817 + origPackage.sharedUser.name 7818 + " differs from " + pkg.mSharedUserId); 7819 origPackage = null; 7820 continue; 7821 } 7822 } else { 7823 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7824 + pkg.packageName + " to old name " + origPackage.name); 7825 } 7826 break; 7827 } 7828 } 7829 } 7830 } 7831 7832 if (mTransferedPackages.contains(pkg.packageName)) { 7833 Slog.w(TAG, "Package " + pkg.packageName 7834 + " was transferred to another, but its .apk remains"); 7835 } 7836 7837 // See comments in nonMutatedPs declaration 7838 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7839 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7840 if (foundPs != null) { 7841 nonMutatedPs = new PackageSetting(foundPs); 7842 } 7843 } 7844 7845 // Just create the setting, don't add it yet. For already existing packages 7846 // the PkgSetting exists already and doesn't have to be created. 7847 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7848 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7849 pkg.applicationInfo.primaryCpuAbi, 7850 pkg.applicationInfo.secondaryCpuAbi, 7851 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7852 user, false); 7853 if (pkgSetting == null) { 7854 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7855 "Creating application package " + pkg.packageName + " failed"); 7856 } 7857 7858 if (pkgSetting.origPackage != null) { 7859 // If we are first transitioning from an original package, 7860 // fix up the new package's name now. We need to do this after 7861 // looking up the package under its new name, so getPackageLP 7862 // can take care of fiddling things correctly. 7863 pkg.setPackageName(origPackage.name); 7864 7865 // File a report about this. 7866 String msg = "New package " + pkgSetting.realName 7867 + " renamed to replace old package " + pkgSetting.name; 7868 reportSettingsProblem(Log.WARN, msg); 7869 7870 // Make a note of it. 7871 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7872 mTransferedPackages.add(origPackage.name); 7873 } 7874 7875 // No longer need to retain this. 7876 pkgSetting.origPackage = null; 7877 } 7878 7879 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7880 // Make a note of it. 7881 mTransferedPackages.add(pkg.packageName); 7882 } 7883 7884 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7885 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7886 } 7887 7888 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7889 // Check all shared libraries and map to their actual file path. 7890 // We only do this here for apps not on a system dir, because those 7891 // are the only ones that can fail an install due to this. We 7892 // will take care of the system apps by updating all of their 7893 // library paths after the scan is done. 7894 updateSharedLibrariesLPw(pkg, null); 7895 } 7896 7897 if (mFoundPolicyFile) { 7898 SELinuxMMAC.assignSeinfoValue(pkg); 7899 } 7900 7901 pkg.applicationInfo.uid = pkgSetting.appId; 7902 pkg.mExtras = pkgSetting; 7903 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7904 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7905 // We just determined the app is signed correctly, so bring 7906 // over the latest parsed certs. 7907 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7908 } else { 7909 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7910 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7911 "Package " + pkg.packageName + " upgrade keys do not match the " 7912 + "previously installed version"); 7913 } else { 7914 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7915 String msg = "System package " + pkg.packageName 7916 + " signature changed; retaining data."; 7917 reportSettingsProblem(Log.WARN, msg); 7918 } 7919 } 7920 } else { 7921 try { 7922 verifySignaturesLP(pkgSetting, pkg); 7923 // We just determined the app is signed correctly, so bring 7924 // over the latest parsed certs. 7925 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7926 } catch (PackageManagerException e) { 7927 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7928 throw e; 7929 } 7930 // The signature has changed, but this package is in the system 7931 // image... let's recover! 7932 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7933 // However... if this package is part of a shared user, but it 7934 // doesn't match the signature of the shared user, let's fail. 7935 // What this means is that you can't change the signatures 7936 // associated with an overall shared user, which doesn't seem all 7937 // that unreasonable. 7938 if (pkgSetting.sharedUser != null) { 7939 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7940 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7941 throw new PackageManagerException( 7942 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7943 "Signature mismatch for shared user: " 7944 + pkgSetting.sharedUser); 7945 } 7946 } 7947 // File a report about this. 7948 String msg = "System package " + pkg.packageName 7949 + " signature changed; retaining data."; 7950 reportSettingsProblem(Log.WARN, msg); 7951 } 7952 } 7953 // Verify that this new package doesn't have any content providers 7954 // that conflict with existing packages. Only do this if the 7955 // package isn't already installed, since we don't want to break 7956 // things that are installed. 7957 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7958 final int N = pkg.providers.size(); 7959 int i; 7960 for (i=0; i<N; i++) { 7961 PackageParser.Provider p = pkg.providers.get(i); 7962 if (p.info.authority != null) { 7963 String names[] = p.info.authority.split(";"); 7964 for (int j = 0; j < names.length; j++) { 7965 if (mProvidersByAuthority.containsKey(names[j])) { 7966 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7967 final String otherPackageName = 7968 ((other != null && other.getComponentName() != null) ? 7969 other.getComponentName().getPackageName() : "?"); 7970 throw new PackageManagerException( 7971 INSTALL_FAILED_CONFLICTING_PROVIDER, 7972 "Can't install because provider name " + names[j] 7973 + " (in package " + pkg.applicationInfo.packageName 7974 + ") is already used by " + otherPackageName); 7975 } 7976 } 7977 } 7978 } 7979 } 7980 7981 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7982 // This package wants to adopt ownership of permissions from 7983 // another package. 7984 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7985 final String origName = pkg.mAdoptPermissions.get(i); 7986 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7987 if (orig != null) { 7988 if (verifyPackageUpdateLPr(orig, pkg)) { 7989 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7990 + pkg.packageName); 7991 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7992 } 7993 } 7994 } 7995 } 7996 } 7997 7998 final String pkgName = pkg.packageName; 7999 8000 final long scanFileTime = scanFile.lastModified(); 8001 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8002 pkg.applicationInfo.processName = fixProcessName( 8003 pkg.applicationInfo.packageName, 8004 pkg.applicationInfo.processName, 8005 pkg.applicationInfo.uid); 8006 8007 if (pkg != mPlatformPackage) { 8008 // Get all of our default paths setup 8009 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8010 } 8011 8012 final String path = scanFile.getPath(); 8013 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8014 8015 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8016 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8017 8018 // Some system apps still use directory structure for native libraries 8019 // in which case we might end up not detecting abi solely based on apk 8020 // structure. Try to detect abi based on directory structure. 8021 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8022 pkg.applicationInfo.primaryCpuAbi == null) { 8023 setBundledAppAbisAndRoots(pkg, pkgSetting); 8024 setNativeLibraryPaths(pkg); 8025 } 8026 8027 } else { 8028 if ((scanFlags & SCAN_MOVE) != 0) { 8029 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8030 // but we already have this packages package info in the PackageSetting. We just 8031 // use that and derive the native library path based on the new codepath. 8032 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8033 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8034 } 8035 8036 // Set native library paths again. For moves, the path will be updated based on the 8037 // ABIs we've determined above. For non-moves, the path will be updated based on the 8038 // ABIs we determined during compilation, but the path will depend on the final 8039 // package path (after the rename away from the stage path). 8040 setNativeLibraryPaths(pkg); 8041 } 8042 8043 // This is a special case for the "system" package, where the ABI is 8044 // dictated by the zygote configuration (and init.rc). We should keep track 8045 // of this ABI so that we can deal with "normal" applications that run under 8046 // the same UID correctly. 8047 if (mPlatformPackage == pkg) { 8048 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8049 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8050 } 8051 8052 // If there's a mismatch between the abi-override in the package setting 8053 // and the abiOverride specified for the install. Warn about this because we 8054 // would've already compiled the app without taking the package setting into 8055 // account. 8056 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8057 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8058 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8059 " for package " + pkg.packageName); 8060 } 8061 } 8062 8063 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8064 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8065 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8066 8067 // Copy the derived override back to the parsed package, so that we can 8068 // update the package settings accordingly. 8069 pkg.cpuAbiOverride = cpuAbiOverride; 8070 8071 if (DEBUG_ABI_SELECTION) { 8072 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8073 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8074 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8075 } 8076 8077 // Push the derived path down into PackageSettings so we know what to 8078 // clean up at uninstall time. 8079 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8080 8081 if (DEBUG_ABI_SELECTION) { 8082 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8083 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8084 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8085 } 8086 8087 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8088 // We don't do this here during boot because we can do it all 8089 // at once after scanning all existing packages. 8090 // 8091 // We also do this *before* we perform dexopt on this package, so that 8092 // we can avoid redundant dexopts, and also to make sure we've got the 8093 // code and package path correct. 8094 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8095 pkg, true /* boot complete */); 8096 } 8097 8098 if (mFactoryTest && pkg.requestedPermissions.contains( 8099 android.Manifest.permission.FACTORY_TEST)) { 8100 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8101 } 8102 8103 ArrayList<PackageParser.Package> clientLibPkgs = null; 8104 8105 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8106 if (nonMutatedPs != null) { 8107 synchronized (mPackages) { 8108 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8109 } 8110 } 8111 return pkg; 8112 } 8113 8114 // Only privileged apps and updated privileged apps can add child packages. 8115 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8116 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8117 throw new PackageManagerException("Only privileged apps and updated " 8118 + "privileged apps can add child packages. Ignoring package " 8119 + pkg.packageName); 8120 } 8121 final int childCount = pkg.childPackages.size(); 8122 for (int i = 0; i < childCount; i++) { 8123 PackageParser.Package childPkg = pkg.childPackages.get(i); 8124 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8125 childPkg.packageName)) { 8126 throw new PackageManagerException("Cannot override a child package of " 8127 + "another disabled system app. Ignoring package " + pkg.packageName); 8128 } 8129 } 8130 } 8131 8132 // writer 8133 synchronized (mPackages) { 8134 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8135 // Only system apps can add new shared libraries. 8136 if (pkg.libraryNames != null) { 8137 for (int i=0; i<pkg.libraryNames.size(); i++) { 8138 String name = pkg.libraryNames.get(i); 8139 boolean allowed = false; 8140 if (pkg.isUpdatedSystemApp()) { 8141 // New library entries can only be added through the 8142 // system image. This is important to get rid of a lot 8143 // of nasty edge cases: for example if we allowed a non- 8144 // system update of the app to add a library, then uninstalling 8145 // the update would make the library go away, and assumptions 8146 // we made such as through app install filtering would now 8147 // have allowed apps on the device which aren't compatible 8148 // with it. Better to just have the restriction here, be 8149 // conservative, and create many fewer cases that can negatively 8150 // impact the user experience. 8151 final PackageSetting sysPs = mSettings 8152 .getDisabledSystemPkgLPr(pkg.packageName); 8153 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8154 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8155 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8156 allowed = true; 8157 break; 8158 } 8159 } 8160 } 8161 } else { 8162 allowed = true; 8163 } 8164 if (allowed) { 8165 if (!mSharedLibraries.containsKey(name)) { 8166 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8167 } else if (!name.equals(pkg.packageName)) { 8168 Slog.w(TAG, "Package " + pkg.packageName + " library " 8169 + name + " already exists; skipping"); 8170 } 8171 } else { 8172 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8173 + name + " that is not declared on system image; skipping"); 8174 } 8175 } 8176 if ((scanFlags & SCAN_BOOTING) == 0) { 8177 // If we are not booting, we need to update any applications 8178 // that are clients of our shared library. If we are booting, 8179 // this will all be done once the scan is complete. 8180 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8181 } 8182 } 8183 } 8184 } 8185 8186 if ((scanFlags & SCAN_BOOTING) != 0) { 8187 // No apps can run during boot scan, so they don't need to be frozen 8188 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8189 // Caller asked to not kill app, so it's probably not frozen 8190 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8191 // Caller asked us to ignore frozen check for some reason; they 8192 // probably didn't know the package name 8193 } else { 8194 // We're doing major surgery on this package, so it better be frozen 8195 // right now to keep it from launching 8196 checkPackageFrozen(pkgName); 8197 } 8198 8199 // Also need to kill any apps that are dependent on the library. 8200 if (clientLibPkgs != null) { 8201 for (int i=0; i<clientLibPkgs.size(); i++) { 8202 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8203 killApplication(clientPkg.applicationInfo.packageName, 8204 clientPkg.applicationInfo.uid, "update lib"); 8205 } 8206 } 8207 8208 // Make sure we're not adding any bogus keyset info 8209 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8210 ksms.assertScannedPackageValid(pkg); 8211 8212 // writer 8213 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8214 8215 boolean createIdmapFailed = false; 8216 synchronized (mPackages) { 8217 // We don't expect installation to fail beyond this point 8218 8219 // Add the new setting to mSettings 8220 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8221 // Add the new setting to mPackages 8222 mPackages.put(pkg.applicationInfo.packageName, pkg); 8223 // Make sure we don't accidentally delete its data. 8224 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8225 while (iter.hasNext()) { 8226 PackageCleanItem item = iter.next(); 8227 if (pkgName.equals(item.packageName)) { 8228 iter.remove(); 8229 } 8230 } 8231 8232 // Take care of first install / last update times. 8233 if (currentTime != 0) { 8234 if (pkgSetting.firstInstallTime == 0) { 8235 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8236 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8237 pkgSetting.lastUpdateTime = currentTime; 8238 } 8239 } else if (pkgSetting.firstInstallTime == 0) { 8240 // We need *something*. Take time time stamp of the file. 8241 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8242 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8243 if (scanFileTime != pkgSetting.timeStamp) { 8244 // A package on the system image has changed; consider this 8245 // to be an update. 8246 pkgSetting.lastUpdateTime = scanFileTime; 8247 } 8248 } 8249 8250 // Add the package's KeySets to the global KeySetManagerService 8251 ksms.addScannedPackageLPw(pkg); 8252 8253 int N = pkg.providers.size(); 8254 StringBuilder r = null; 8255 int i; 8256 for (i=0; i<N; i++) { 8257 PackageParser.Provider p = pkg.providers.get(i); 8258 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8259 p.info.processName, pkg.applicationInfo.uid); 8260 mProviders.addProvider(p); 8261 p.syncable = p.info.isSyncable; 8262 if (p.info.authority != null) { 8263 String names[] = p.info.authority.split(";"); 8264 p.info.authority = null; 8265 for (int j = 0; j < names.length; j++) { 8266 if (j == 1 && p.syncable) { 8267 // We only want the first authority for a provider to possibly be 8268 // syncable, so if we already added this provider using a different 8269 // authority clear the syncable flag. We copy the provider before 8270 // changing it because the mProviders object contains a reference 8271 // to a provider that we don't want to change. 8272 // Only do this for the second authority since the resulting provider 8273 // object can be the same for all future authorities for this provider. 8274 p = new PackageParser.Provider(p); 8275 p.syncable = false; 8276 } 8277 if (!mProvidersByAuthority.containsKey(names[j])) { 8278 mProvidersByAuthority.put(names[j], p); 8279 if (p.info.authority == null) { 8280 p.info.authority = names[j]; 8281 } else { 8282 p.info.authority = p.info.authority + ";" + names[j]; 8283 } 8284 if (DEBUG_PACKAGE_SCANNING) { 8285 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8286 Log.d(TAG, "Registered content provider: " + names[j] 8287 + ", className = " + p.info.name + ", isSyncable = " 8288 + p.info.isSyncable); 8289 } 8290 } else { 8291 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8292 Slog.w(TAG, "Skipping provider name " + names[j] + 8293 " (in package " + pkg.applicationInfo.packageName + 8294 "): name already used by " 8295 + ((other != null && other.getComponentName() != null) 8296 ? other.getComponentName().getPackageName() : "?")); 8297 } 8298 } 8299 } 8300 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8301 if (r == null) { 8302 r = new StringBuilder(256); 8303 } else { 8304 r.append(' '); 8305 } 8306 r.append(p.info.name); 8307 } 8308 } 8309 if (r != null) { 8310 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8311 } 8312 8313 N = pkg.services.size(); 8314 r = null; 8315 for (i=0; i<N; i++) { 8316 PackageParser.Service s = pkg.services.get(i); 8317 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8318 s.info.processName, pkg.applicationInfo.uid); 8319 mServices.addService(s); 8320 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8321 if (r == null) { 8322 r = new StringBuilder(256); 8323 } else { 8324 r.append(' '); 8325 } 8326 r.append(s.info.name); 8327 } 8328 } 8329 if (r != null) { 8330 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8331 } 8332 8333 N = pkg.receivers.size(); 8334 r = null; 8335 for (i=0; i<N; i++) { 8336 PackageParser.Activity a = pkg.receivers.get(i); 8337 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8338 a.info.processName, pkg.applicationInfo.uid); 8339 mReceivers.addActivity(a, "receiver"); 8340 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8341 if (r == null) { 8342 r = new StringBuilder(256); 8343 } else { 8344 r.append(' '); 8345 } 8346 r.append(a.info.name); 8347 } 8348 } 8349 if (r != null) { 8350 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8351 } 8352 8353 N = pkg.activities.size(); 8354 r = null; 8355 for (i=0; i<N; i++) { 8356 PackageParser.Activity a = pkg.activities.get(i); 8357 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8358 a.info.processName, pkg.applicationInfo.uid); 8359 mActivities.addActivity(a, "activity"); 8360 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8361 if (r == null) { 8362 r = new StringBuilder(256); 8363 } else { 8364 r.append(' '); 8365 } 8366 r.append(a.info.name); 8367 } 8368 } 8369 if (r != null) { 8370 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8371 } 8372 8373 N = pkg.permissionGroups.size(); 8374 r = null; 8375 for (i=0; i<N; i++) { 8376 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8377 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8378 if (cur == null) { 8379 mPermissionGroups.put(pg.info.name, pg); 8380 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8381 if (r == null) { 8382 r = new StringBuilder(256); 8383 } else { 8384 r.append(' '); 8385 } 8386 r.append(pg.info.name); 8387 } 8388 } else { 8389 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8390 + pg.info.packageName + " ignored: original from " 8391 + cur.info.packageName); 8392 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8393 if (r == null) { 8394 r = new StringBuilder(256); 8395 } else { 8396 r.append(' '); 8397 } 8398 r.append("DUP:"); 8399 r.append(pg.info.name); 8400 } 8401 } 8402 } 8403 if (r != null) { 8404 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8405 } 8406 8407 N = pkg.permissions.size(); 8408 r = null; 8409 for (i=0; i<N; i++) { 8410 PackageParser.Permission p = pkg.permissions.get(i); 8411 8412 // Assume by default that we did not install this permission into the system. 8413 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8414 8415 // Now that permission groups have a special meaning, we ignore permission 8416 // groups for legacy apps to prevent unexpected behavior. In particular, 8417 // permissions for one app being granted to someone just becase they happen 8418 // to be in a group defined by another app (before this had no implications). 8419 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8420 p.group = mPermissionGroups.get(p.info.group); 8421 // Warn for a permission in an unknown group. 8422 if (p.info.group != null && p.group == null) { 8423 Slog.w(TAG, "Permission " + p.info.name + " from package " 8424 + p.info.packageName + " in an unknown group " + p.info.group); 8425 } 8426 } 8427 8428 ArrayMap<String, BasePermission> permissionMap = 8429 p.tree ? mSettings.mPermissionTrees 8430 : mSettings.mPermissions; 8431 BasePermission bp = permissionMap.get(p.info.name); 8432 8433 // Allow system apps to redefine non-system permissions 8434 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8435 final boolean currentOwnerIsSystem = (bp.perm != null 8436 && isSystemApp(bp.perm.owner)); 8437 if (isSystemApp(p.owner)) { 8438 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8439 // It's a built-in permission and no owner, take ownership now 8440 bp.packageSetting = pkgSetting; 8441 bp.perm = p; 8442 bp.uid = pkg.applicationInfo.uid; 8443 bp.sourcePackage = p.info.packageName; 8444 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8445 } else if (!currentOwnerIsSystem) { 8446 String msg = "New decl " + p.owner + " of permission " 8447 + p.info.name + " is system; overriding " + bp.sourcePackage; 8448 reportSettingsProblem(Log.WARN, msg); 8449 bp = null; 8450 } 8451 } 8452 } 8453 8454 if (bp == null) { 8455 bp = new BasePermission(p.info.name, p.info.packageName, 8456 BasePermission.TYPE_NORMAL); 8457 permissionMap.put(p.info.name, bp); 8458 } 8459 8460 if (bp.perm == null) { 8461 if (bp.sourcePackage == null 8462 || bp.sourcePackage.equals(p.info.packageName)) { 8463 BasePermission tree = findPermissionTreeLP(p.info.name); 8464 if (tree == null 8465 || tree.sourcePackage.equals(p.info.packageName)) { 8466 bp.packageSetting = pkgSetting; 8467 bp.perm = p; 8468 bp.uid = pkg.applicationInfo.uid; 8469 bp.sourcePackage = p.info.packageName; 8470 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8471 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8472 if (r == null) { 8473 r = new StringBuilder(256); 8474 } else { 8475 r.append(' '); 8476 } 8477 r.append(p.info.name); 8478 } 8479 } else { 8480 Slog.w(TAG, "Permission " + p.info.name + " from package " 8481 + p.info.packageName + " ignored: base tree " 8482 + tree.name + " is from package " 8483 + tree.sourcePackage); 8484 } 8485 } else { 8486 Slog.w(TAG, "Permission " + p.info.name + " from package " 8487 + p.info.packageName + " ignored: original from " 8488 + bp.sourcePackage); 8489 } 8490 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8491 if (r == null) { 8492 r = new StringBuilder(256); 8493 } else { 8494 r.append(' '); 8495 } 8496 r.append("DUP:"); 8497 r.append(p.info.name); 8498 } 8499 if (bp.perm == p) { 8500 bp.protectionLevel = p.info.protectionLevel; 8501 } 8502 } 8503 8504 if (r != null) { 8505 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8506 } 8507 8508 N = pkg.instrumentation.size(); 8509 r = null; 8510 for (i=0; i<N; i++) { 8511 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8512 a.info.packageName = pkg.applicationInfo.packageName; 8513 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8514 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8515 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8516 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8517 a.info.dataDir = pkg.applicationInfo.dataDir; 8518 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8519 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8520 8521 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8522 // need other information about the application, like the ABI and what not ? 8523 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8524 mInstrumentation.put(a.getComponentName(), a); 8525 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8526 if (r == null) { 8527 r = new StringBuilder(256); 8528 } else { 8529 r.append(' '); 8530 } 8531 r.append(a.info.name); 8532 } 8533 } 8534 if (r != null) { 8535 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8536 } 8537 8538 if (pkg.protectedBroadcasts != null) { 8539 N = pkg.protectedBroadcasts.size(); 8540 for (i=0; i<N; i++) { 8541 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8542 } 8543 } 8544 8545 pkgSetting.setTimeStamp(scanFileTime); 8546 8547 // Create idmap files for pairs of (packages, overlay packages). 8548 // Note: "android", ie framework-res.apk, is handled by native layers. 8549 if (pkg.mOverlayTarget != null) { 8550 // This is an overlay package. 8551 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8552 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8553 mOverlays.put(pkg.mOverlayTarget, 8554 new ArrayMap<String, PackageParser.Package>()); 8555 } 8556 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8557 map.put(pkg.packageName, pkg); 8558 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8559 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8560 createIdmapFailed = true; 8561 } 8562 } 8563 } else if (mOverlays.containsKey(pkg.packageName) && 8564 !pkg.packageName.equals("android")) { 8565 // This is a regular package, with one or more known overlay packages. 8566 createIdmapsForPackageLI(pkg); 8567 } 8568 } 8569 8570 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8571 8572 if (createIdmapFailed) { 8573 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8574 "scanPackageLI failed to createIdmap"); 8575 } 8576 return pkg; 8577 } 8578 8579 /** 8580 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8581 * is derived purely on the basis of the contents of {@code scanFile} and 8582 * {@code cpuAbiOverride}. 8583 * 8584 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8585 */ 8586 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8587 String cpuAbiOverride, boolean extractLibs) 8588 throws PackageManagerException { 8589 // TODO: We can probably be smarter about this stuff. For installed apps, 8590 // we can calculate this information at install time once and for all. For 8591 // system apps, we can probably assume that this information doesn't change 8592 // after the first boot scan. As things stand, we do lots of unnecessary work. 8593 8594 // Give ourselves some initial paths; we'll come back for another 8595 // pass once we've determined ABI below. 8596 setNativeLibraryPaths(pkg); 8597 8598 // We would never need to extract libs for forward-locked and external packages, 8599 // since the container service will do it for us. We shouldn't attempt to 8600 // extract libs from system app when it was not updated. 8601 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8602 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8603 extractLibs = false; 8604 } 8605 8606 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8607 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8608 8609 NativeLibraryHelper.Handle handle = null; 8610 try { 8611 handle = NativeLibraryHelper.Handle.create(pkg); 8612 // TODO(multiArch): This can be null for apps that didn't go through the 8613 // usual installation process. We can calculate it again, like we 8614 // do during install time. 8615 // 8616 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8617 // unnecessary. 8618 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8619 8620 // Null out the abis so that they can be recalculated. 8621 pkg.applicationInfo.primaryCpuAbi = null; 8622 pkg.applicationInfo.secondaryCpuAbi = null; 8623 if (isMultiArch(pkg.applicationInfo)) { 8624 // Warn if we've set an abiOverride for multi-lib packages.. 8625 // By definition, we need to copy both 32 and 64 bit libraries for 8626 // such packages. 8627 if (pkg.cpuAbiOverride != null 8628 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8629 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8630 } 8631 8632 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8633 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8634 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8635 if (extractLibs) { 8636 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8637 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8638 useIsaSpecificSubdirs); 8639 } else { 8640 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8641 } 8642 } 8643 8644 maybeThrowExceptionForMultiArchCopy( 8645 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8646 8647 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8648 if (extractLibs) { 8649 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8650 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8651 useIsaSpecificSubdirs); 8652 } else { 8653 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8654 } 8655 } 8656 8657 maybeThrowExceptionForMultiArchCopy( 8658 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8659 8660 if (abi64 >= 0) { 8661 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8662 } 8663 8664 if (abi32 >= 0) { 8665 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8666 if (abi64 >= 0) { 8667 if (pkg.use32bitAbi) { 8668 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8669 pkg.applicationInfo.primaryCpuAbi = abi; 8670 } else { 8671 pkg.applicationInfo.secondaryCpuAbi = abi; 8672 } 8673 } else { 8674 pkg.applicationInfo.primaryCpuAbi = abi; 8675 } 8676 } 8677 8678 } else { 8679 String[] abiList = (cpuAbiOverride != null) ? 8680 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8681 8682 // Enable gross and lame hacks for apps that are built with old 8683 // SDK tools. We must scan their APKs for renderscript bitcode and 8684 // not launch them if it's present. Don't bother checking on devices 8685 // that don't have 64 bit support. 8686 boolean needsRenderScriptOverride = false; 8687 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8688 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8689 abiList = Build.SUPPORTED_32_BIT_ABIS; 8690 needsRenderScriptOverride = true; 8691 } 8692 8693 final int copyRet; 8694 if (extractLibs) { 8695 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8696 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8697 } else { 8698 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8699 } 8700 8701 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8702 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8703 "Error unpackaging native libs for app, errorCode=" + copyRet); 8704 } 8705 8706 if (copyRet >= 0) { 8707 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8708 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8709 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8710 } else if (needsRenderScriptOverride) { 8711 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8712 } 8713 } 8714 } catch (IOException ioe) { 8715 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8716 } finally { 8717 IoUtils.closeQuietly(handle); 8718 } 8719 8720 // Now that we've calculated the ABIs and determined if it's an internal app, 8721 // we will go ahead and populate the nativeLibraryPath. 8722 setNativeLibraryPaths(pkg); 8723 } 8724 8725 /** 8726 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8727 * i.e, so that all packages can be run inside a single process if required. 8728 * 8729 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8730 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8731 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8732 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8733 * updating a package that belongs to a shared user. 8734 * 8735 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8736 * adds unnecessary complexity. 8737 */ 8738 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8739 PackageParser.Package scannedPackage, boolean bootComplete) { 8740 String requiredInstructionSet = null; 8741 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8742 requiredInstructionSet = VMRuntime.getInstructionSet( 8743 scannedPackage.applicationInfo.primaryCpuAbi); 8744 } 8745 8746 PackageSetting requirer = null; 8747 for (PackageSetting ps : packagesForUser) { 8748 // If packagesForUser contains scannedPackage, we skip it. This will happen 8749 // when scannedPackage is an update of an existing package. Without this check, 8750 // we will never be able to change the ABI of any package belonging to a shared 8751 // user, even if it's compatible with other packages. 8752 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8753 if (ps.primaryCpuAbiString == null) { 8754 continue; 8755 } 8756 8757 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8758 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8759 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8760 // this but there's not much we can do. 8761 String errorMessage = "Instruction set mismatch, " 8762 + ((requirer == null) ? "[caller]" : requirer) 8763 + " requires " + requiredInstructionSet + " whereas " + ps 8764 + " requires " + instructionSet; 8765 Slog.w(TAG, errorMessage); 8766 } 8767 8768 if (requiredInstructionSet == null) { 8769 requiredInstructionSet = instructionSet; 8770 requirer = ps; 8771 } 8772 } 8773 } 8774 8775 if (requiredInstructionSet != null) { 8776 String adjustedAbi; 8777 if (requirer != null) { 8778 // requirer != null implies that either scannedPackage was null or that scannedPackage 8779 // did not require an ABI, in which case we have to adjust scannedPackage to match 8780 // the ABI of the set (which is the same as requirer's ABI) 8781 adjustedAbi = requirer.primaryCpuAbiString; 8782 if (scannedPackage != null) { 8783 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8784 } 8785 } else { 8786 // requirer == null implies that we're updating all ABIs in the set to 8787 // match scannedPackage. 8788 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8789 } 8790 8791 for (PackageSetting ps : packagesForUser) { 8792 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8793 if (ps.primaryCpuAbiString != null) { 8794 continue; 8795 } 8796 8797 ps.primaryCpuAbiString = adjustedAbi; 8798 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8799 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8800 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8801 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8802 + " (requirer=" 8803 + (requirer == null ? "null" : requirer.pkg.packageName) 8804 + ", scannedPackage=" 8805 + (scannedPackage != null ? scannedPackage.packageName : "null") 8806 + ")"); 8807 try { 8808 mInstaller.rmdex(ps.codePathString, 8809 getDexCodeInstructionSet(getPreferredInstructionSet())); 8810 } catch (InstallerException ignored) { 8811 } 8812 } 8813 } 8814 } 8815 } 8816 } 8817 8818 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8819 synchronized (mPackages) { 8820 mResolverReplaced = true; 8821 // Set up information for custom user intent resolution activity. 8822 mResolveActivity.applicationInfo = pkg.applicationInfo; 8823 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8824 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8825 mResolveActivity.processName = pkg.applicationInfo.packageName; 8826 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8827 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8828 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8829 mResolveActivity.theme = 0; 8830 mResolveActivity.exported = true; 8831 mResolveActivity.enabled = true; 8832 mResolveInfo.activityInfo = mResolveActivity; 8833 mResolveInfo.priority = 0; 8834 mResolveInfo.preferredOrder = 0; 8835 mResolveInfo.match = 0; 8836 mResolveComponentName = mCustomResolverComponentName; 8837 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8838 mResolveComponentName); 8839 } 8840 } 8841 8842 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8843 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8844 8845 // Set up information for ephemeral installer activity 8846 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8847 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8848 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8849 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8850 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8851 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8852 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8853 mEphemeralInstallerActivity.theme = 0; 8854 mEphemeralInstallerActivity.exported = true; 8855 mEphemeralInstallerActivity.enabled = true; 8856 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8857 mEphemeralInstallerInfo.priority = 0; 8858 mEphemeralInstallerInfo.preferredOrder = 0; 8859 mEphemeralInstallerInfo.match = 0; 8860 8861 if (DEBUG_EPHEMERAL) { 8862 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8863 } 8864 } 8865 8866 private static String calculateBundledApkRoot(final String codePathString) { 8867 final File codePath = new File(codePathString); 8868 final File codeRoot; 8869 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8870 codeRoot = Environment.getRootDirectory(); 8871 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8872 codeRoot = Environment.getOemDirectory(); 8873 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8874 codeRoot = Environment.getVendorDirectory(); 8875 } else { 8876 // Unrecognized code path; take its top real segment as the apk root: 8877 // e.g. /something/app/blah.apk => /something 8878 try { 8879 File f = codePath.getCanonicalFile(); 8880 File parent = f.getParentFile(); // non-null because codePath is a file 8881 File tmp; 8882 while ((tmp = parent.getParentFile()) != null) { 8883 f = parent; 8884 parent = tmp; 8885 } 8886 codeRoot = f; 8887 Slog.w(TAG, "Unrecognized code path " 8888 + codePath + " - using " + codeRoot); 8889 } catch (IOException e) { 8890 // Can't canonicalize the code path -- shenanigans? 8891 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8892 return Environment.getRootDirectory().getPath(); 8893 } 8894 } 8895 return codeRoot.getPath(); 8896 } 8897 8898 /** 8899 * Derive and set the location of native libraries for the given package, 8900 * which varies depending on where and how the package was installed. 8901 */ 8902 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8903 final ApplicationInfo info = pkg.applicationInfo; 8904 final String codePath = pkg.codePath; 8905 final File codeFile = new File(codePath); 8906 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8907 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8908 8909 info.nativeLibraryRootDir = null; 8910 info.nativeLibraryRootRequiresIsa = false; 8911 info.nativeLibraryDir = null; 8912 info.secondaryNativeLibraryDir = null; 8913 8914 if (isApkFile(codeFile)) { 8915 // Monolithic install 8916 if (bundledApp) { 8917 // If "/system/lib64/apkname" exists, assume that is the per-package 8918 // native library directory to use; otherwise use "/system/lib/apkname". 8919 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8920 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8921 getPrimaryInstructionSet(info)); 8922 8923 // This is a bundled system app so choose the path based on the ABI. 8924 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8925 // is just the default path. 8926 final String apkName = deriveCodePathName(codePath); 8927 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8928 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8929 apkName).getAbsolutePath(); 8930 8931 if (info.secondaryCpuAbi != null) { 8932 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8933 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8934 secondaryLibDir, apkName).getAbsolutePath(); 8935 } 8936 } else if (asecApp) { 8937 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8938 .getAbsolutePath(); 8939 } else { 8940 final String apkName = deriveCodePathName(codePath); 8941 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8942 .getAbsolutePath(); 8943 } 8944 8945 info.nativeLibraryRootRequiresIsa = false; 8946 info.nativeLibraryDir = info.nativeLibraryRootDir; 8947 } else { 8948 // Cluster install 8949 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8950 info.nativeLibraryRootRequiresIsa = true; 8951 8952 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8953 getPrimaryInstructionSet(info)).getAbsolutePath(); 8954 8955 if (info.secondaryCpuAbi != null) { 8956 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8957 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8958 } 8959 } 8960 } 8961 8962 /** 8963 * Calculate the abis and roots for a bundled app. These can uniquely 8964 * be determined from the contents of the system partition, i.e whether 8965 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8966 * of this information, and instead assume that the system was built 8967 * sensibly. 8968 */ 8969 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8970 PackageSetting pkgSetting) { 8971 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8972 8973 // If "/system/lib64/apkname" exists, assume that is the per-package 8974 // native library directory to use; otherwise use "/system/lib/apkname". 8975 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8976 setBundledAppAbi(pkg, apkRoot, apkName); 8977 // pkgSetting might be null during rescan following uninstall of updates 8978 // to a bundled app, so accommodate that possibility. The settings in 8979 // that case will be established later from the parsed package. 8980 // 8981 // If the settings aren't null, sync them up with what we've just derived. 8982 // note that apkRoot isn't stored in the package settings. 8983 if (pkgSetting != null) { 8984 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8985 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8986 } 8987 } 8988 8989 /** 8990 * Deduces the ABI of a bundled app and sets the relevant fields on the 8991 * parsed pkg object. 8992 * 8993 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8994 * under which system libraries are installed. 8995 * @param apkName the name of the installed package. 8996 */ 8997 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8998 final File codeFile = new File(pkg.codePath); 8999 9000 final boolean has64BitLibs; 9001 final boolean has32BitLibs; 9002 if (isApkFile(codeFile)) { 9003 // Monolithic install 9004 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9005 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9006 } else { 9007 // Cluster install 9008 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9009 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9010 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9011 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9012 has64BitLibs = (new File(rootDir, isa)).exists(); 9013 } else { 9014 has64BitLibs = false; 9015 } 9016 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9017 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9018 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9019 has32BitLibs = (new File(rootDir, isa)).exists(); 9020 } else { 9021 has32BitLibs = false; 9022 } 9023 } 9024 9025 if (has64BitLibs && !has32BitLibs) { 9026 // The package has 64 bit libs, but not 32 bit libs. Its primary 9027 // ABI should be 64 bit. We can safely assume here that the bundled 9028 // native libraries correspond to the most preferred ABI in the list. 9029 9030 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9031 pkg.applicationInfo.secondaryCpuAbi = null; 9032 } else if (has32BitLibs && !has64BitLibs) { 9033 // The package has 32 bit libs but not 64 bit libs. Its primary 9034 // ABI should be 32 bit. 9035 9036 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9037 pkg.applicationInfo.secondaryCpuAbi = null; 9038 } else if (has32BitLibs && has64BitLibs) { 9039 // The application has both 64 and 32 bit bundled libraries. We check 9040 // here that the app declares multiArch support, and warn if it doesn't. 9041 // 9042 // We will be lenient here and record both ABIs. The primary will be the 9043 // ABI that's higher on the list, i.e, a device that's configured to prefer 9044 // 64 bit apps will see a 64 bit primary ABI, 9045 9046 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9047 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9048 } 9049 9050 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9051 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9052 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9053 } else { 9054 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9055 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9056 } 9057 } else { 9058 pkg.applicationInfo.primaryCpuAbi = null; 9059 pkg.applicationInfo.secondaryCpuAbi = null; 9060 } 9061 } 9062 9063 private void killApplication(String pkgName, int appId, String reason) { 9064 // Request the ActivityManager to kill the process(only for existing packages) 9065 // so that we do not end up in a confused state while the user is still using the older 9066 // version of the application while the new one gets installed. 9067 final long token = Binder.clearCallingIdentity(); 9068 try { 9069 IActivityManager am = ActivityManagerNative.getDefault(); 9070 if (am != null) { 9071 try { 9072 am.killApplicationWithAppId(pkgName, appId, reason); 9073 } catch (RemoteException e) { 9074 } 9075 } 9076 } finally { 9077 Binder.restoreCallingIdentity(token); 9078 } 9079 } 9080 9081 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9082 // Remove the parent package setting 9083 PackageSetting ps = (PackageSetting) pkg.mExtras; 9084 if (ps != null) { 9085 removePackageLI(ps, chatty); 9086 } 9087 // Remove the child package setting 9088 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9089 for (int i = 0; i < childCount; i++) { 9090 PackageParser.Package childPkg = pkg.childPackages.get(i); 9091 ps = (PackageSetting) childPkg.mExtras; 9092 if (ps != null) { 9093 removePackageLI(ps, chatty); 9094 } 9095 } 9096 } 9097 9098 void removePackageLI(PackageSetting ps, boolean chatty) { 9099 if (DEBUG_INSTALL) { 9100 if (chatty) 9101 Log.d(TAG, "Removing package " + ps.name); 9102 } 9103 9104 // writer 9105 synchronized (mPackages) { 9106 mPackages.remove(ps.name); 9107 final PackageParser.Package pkg = ps.pkg; 9108 if (pkg != null) { 9109 cleanPackageDataStructuresLILPw(pkg, chatty); 9110 } 9111 } 9112 } 9113 9114 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9115 if (DEBUG_INSTALL) { 9116 if (chatty) 9117 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9118 } 9119 9120 // writer 9121 synchronized (mPackages) { 9122 // Remove the parent package 9123 mPackages.remove(pkg.applicationInfo.packageName); 9124 cleanPackageDataStructuresLILPw(pkg, chatty); 9125 9126 // Remove the child packages 9127 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9128 for (int i = 0; i < childCount; i++) { 9129 PackageParser.Package childPkg = pkg.childPackages.get(i); 9130 mPackages.remove(childPkg.applicationInfo.packageName); 9131 cleanPackageDataStructuresLILPw(childPkg, chatty); 9132 } 9133 } 9134 } 9135 9136 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9137 int N = pkg.providers.size(); 9138 StringBuilder r = null; 9139 int i; 9140 for (i=0; i<N; i++) { 9141 PackageParser.Provider p = pkg.providers.get(i); 9142 mProviders.removeProvider(p); 9143 if (p.info.authority == null) { 9144 9145 /* There was another ContentProvider with this authority when 9146 * this app was installed so this authority is null, 9147 * Ignore it as we don't have to unregister the provider. 9148 */ 9149 continue; 9150 } 9151 String names[] = p.info.authority.split(";"); 9152 for (int j = 0; j < names.length; j++) { 9153 if (mProvidersByAuthority.get(names[j]) == p) { 9154 mProvidersByAuthority.remove(names[j]); 9155 if (DEBUG_REMOVE) { 9156 if (chatty) 9157 Log.d(TAG, "Unregistered content provider: " + names[j] 9158 + ", className = " + p.info.name + ", isSyncable = " 9159 + p.info.isSyncable); 9160 } 9161 } 9162 } 9163 if (DEBUG_REMOVE && chatty) { 9164 if (r == null) { 9165 r = new StringBuilder(256); 9166 } else { 9167 r.append(' '); 9168 } 9169 r.append(p.info.name); 9170 } 9171 } 9172 if (r != null) { 9173 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9174 } 9175 9176 N = pkg.services.size(); 9177 r = null; 9178 for (i=0; i<N; i++) { 9179 PackageParser.Service s = pkg.services.get(i); 9180 mServices.removeService(s); 9181 if (chatty) { 9182 if (r == null) { 9183 r = new StringBuilder(256); 9184 } else { 9185 r.append(' '); 9186 } 9187 r.append(s.info.name); 9188 } 9189 } 9190 if (r != null) { 9191 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9192 } 9193 9194 N = pkg.receivers.size(); 9195 r = null; 9196 for (i=0; i<N; i++) { 9197 PackageParser.Activity a = pkg.receivers.get(i); 9198 mReceivers.removeActivity(a, "receiver"); 9199 if (DEBUG_REMOVE && chatty) { 9200 if (r == null) { 9201 r = new StringBuilder(256); 9202 } else { 9203 r.append(' '); 9204 } 9205 r.append(a.info.name); 9206 } 9207 } 9208 if (r != null) { 9209 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9210 } 9211 9212 N = pkg.activities.size(); 9213 r = null; 9214 for (i=0; i<N; i++) { 9215 PackageParser.Activity a = pkg.activities.get(i); 9216 mActivities.removeActivity(a, "activity"); 9217 if (DEBUG_REMOVE && chatty) { 9218 if (r == null) { 9219 r = new StringBuilder(256); 9220 } else { 9221 r.append(' '); 9222 } 9223 r.append(a.info.name); 9224 } 9225 } 9226 if (r != null) { 9227 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9228 } 9229 9230 N = pkg.permissions.size(); 9231 r = null; 9232 for (i=0; i<N; i++) { 9233 PackageParser.Permission p = pkg.permissions.get(i); 9234 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9235 if (bp == null) { 9236 bp = mSettings.mPermissionTrees.get(p.info.name); 9237 } 9238 if (bp != null && bp.perm == p) { 9239 bp.perm = null; 9240 if (DEBUG_REMOVE && chatty) { 9241 if (r == null) { 9242 r = new StringBuilder(256); 9243 } else { 9244 r.append(' '); 9245 } 9246 r.append(p.info.name); 9247 } 9248 } 9249 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9250 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9251 if (appOpPkgs != null) { 9252 appOpPkgs.remove(pkg.packageName); 9253 } 9254 } 9255 } 9256 if (r != null) { 9257 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9258 } 9259 9260 N = pkg.requestedPermissions.size(); 9261 r = null; 9262 for (i=0; i<N; i++) { 9263 String perm = pkg.requestedPermissions.get(i); 9264 BasePermission bp = mSettings.mPermissions.get(perm); 9265 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9266 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9267 if (appOpPkgs != null) { 9268 appOpPkgs.remove(pkg.packageName); 9269 if (appOpPkgs.isEmpty()) { 9270 mAppOpPermissionPackages.remove(perm); 9271 } 9272 } 9273 } 9274 } 9275 if (r != null) { 9276 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9277 } 9278 9279 N = pkg.instrumentation.size(); 9280 r = null; 9281 for (i=0; i<N; i++) { 9282 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9283 mInstrumentation.remove(a.getComponentName()); 9284 if (DEBUG_REMOVE && chatty) { 9285 if (r == null) { 9286 r = new StringBuilder(256); 9287 } else { 9288 r.append(' '); 9289 } 9290 r.append(a.info.name); 9291 } 9292 } 9293 if (r != null) { 9294 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9295 } 9296 9297 r = null; 9298 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9299 // Only system apps can hold shared libraries. 9300 if (pkg.libraryNames != null) { 9301 for (i=0; i<pkg.libraryNames.size(); i++) { 9302 String name = pkg.libraryNames.get(i); 9303 SharedLibraryEntry cur = mSharedLibraries.get(name); 9304 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9305 mSharedLibraries.remove(name); 9306 if (DEBUG_REMOVE && chatty) { 9307 if (r == null) { 9308 r = new StringBuilder(256); 9309 } else { 9310 r.append(' '); 9311 } 9312 r.append(name); 9313 } 9314 } 9315 } 9316 } 9317 } 9318 if (r != null) { 9319 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9320 } 9321 } 9322 9323 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9324 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9325 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9326 return true; 9327 } 9328 } 9329 return false; 9330 } 9331 9332 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9333 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9334 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9335 9336 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9337 // Update the parent permissions 9338 updatePermissionsLPw(pkg.packageName, pkg, flags); 9339 // Update the child permissions 9340 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9341 for (int i = 0; i < childCount; i++) { 9342 PackageParser.Package childPkg = pkg.childPackages.get(i); 9343 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9344 } 9345 } 9346 9347 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9348 int flags) { 9349 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9350 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9351 } 9352 9353 private void updatePermissionsLPw(String changingPkg, 9354 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9355 // Make sure there are no dangling permission trees. 9356 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9357 while (it.hasNext()) { 9358 final BasePermission bp = it.next(); 9359 if (bp.packageSetting == null) { 9360 // We may not yet have parsed the package, so just see if 9361 // we still know about its settings. 9362 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9363 } 9364 if (bp.packageSetting == null) { 9365 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9366 + " from package " + bp.sourcePackage); 9367 it.remove(); 9368 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9369 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9370 Slog.i(TAG, "Removing old permission tree: " + bp.name 9371 + " from package " + bp.sourcePackage); 9372 flags |= UPDATE_PERMISSIONS_ALL; 9373 it.remove(); 9374 } 9375 } 9376 } 9377 9378 // Make sure all dynamic permissions have been assigned to a package, 9379 // and make sure there are no dangling permissions. 9380 it = mSettings.mPermissions.values().iterator(); 9381 while (it.hasNext()) { 9382 final BasePermission bp = it.next(); 9383 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9384 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9385 + bp.name + " pkg=" + bp.sourcePackage 9386 + " info=" + bp.pendingInfo); 9387 if (bp.packageSetting == null && bp.pendingInfo != null) { 9388 final BasePermission tree = findPermissionTreeLP(bp.name); 9389 if (tree != null && tree.perm != null) { 9390 bp.packageSetting = tree.packageSetting; 9391 bp.perm = new PackageParser.Permission(tree.perm.owner, 9392 new PermissionInfo(bp.pendingInfo)); 9393 bp.perm.info.packageName = tree.perm.info.packageName; 9394 bp.perm.info.name = bp.name; 9395 bp.uid = tree.uid; 9396 } 9397 } 9398 } 9399 if (bp.packageSetting == null) { 9400 // We may not yet have parsed the package, so just see if 9401 // we still know about its settings. 9402 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9403 } 9404 if (bp.packageSetting == null) { 9405 Slog.w(TAG, "Removing dangling permission: " + bp.name 9406 + " from package " + bp.sourcePackage); 9407 it.remove(); 9408 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9409 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9410 Slog.i(TAG, "Removing old permission: " + bp.name 9411 + " from package " + bp.sourcePackage); 9412 flags |= UPDATE_PERMISSIONS_ALL; 9413 it.remove(); 9414 } 9415 } 9416 } 9417 9418 // Now update the permissions for all packages, in particular 9419 // replace the granted permissions of the system packages. 9420 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9421 for (PackageParser.Package pkg : mPackages.values()) { 9422 if (pkg != pkgInfo) { 9423 // Only replace for packages on requested volume 9424 final String volumeUuid = getVolumeUuidForPackage(pkg); 9425 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9426 && Objects.equals(replaceVolumeUuid, volumeUuid); 9427 grantPermissionsLPw(pkg, replace, changingPkg); 9428 } 9429 } 9430 } 9431 9432 if (pkgInfo != null) { 9433 // Only replace for packages on requested volume 9434 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9435 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9436 && Objects.equals(replaceVolumeUuid, volumeUuid); 9437 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9438 } 9439 } 9440 9441 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9442 String packageOfInterest) { 9443 // IMPORTANT: There are two types of permissions: install and runtime. 9444 // Install time permissions are granted when the app is installed to 9445 // all device users and users added in the future. Runtime permissions 9446 // are granted at runtime explicitly to specific users. Normal and signature 9447 // protected permissions are install time permissions. Dangerous permissions 9448 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9449 // otherwise they are runtime permissions. This function does not manage 9450 // runtime permissions except for the case an app targeting Lollipop MR1 9451 // being upgraded to target a newer SDK, in which case dangerous permissions 9452 // are transformed from install time to runtime ones. 9453 9454 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9455 if (ps == null) { 9456 return; 9457 } 9458 9459 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9460 9461 PermissionsState permissionsState = ps.getPermissionsState(); 9462 PermissionsState origPermissions = permissionsState; 9463 9464 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9465 9466 boolean runtimePermissionsRevoked = false; 9467 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9468 9469 boolean changedInstallPermission = false; 9470 9471 if (replace) { 9472 ps.installPermissionsFixed = false; 9473 if (!ps.isSharedUser()) { 9474 origPermissions = new PermissionsState(permissionsState); 9475 permissionsState.reset(); 9476 } else { 9477 // We need to know only about runtime permission changes since the 9478 // calling code always writes the install permissions state but 9479 // the runtime ones are written only if changed. The only cases of 9480 // changed runtime permissions here are promotion of an install to 9481 // runtime and revocation of a runtime from a shared user. 9482 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9483 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9484 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9485 runtimePermissionsRevoked = true; 9486 } 9487 } 9488 } 9489 9490 permissionsState.setGlobalGids(mGlobalGids); 9491 9492 final int N = pkg.requestedPermissions.size(); 9493 for (int i=0; i<N; i++) { 9494 final String name = pkg.requestedPermissions.get(i); 9495 final BasePermission bp = mSettings.mPermissions.get(name); 9496 9497 if (DEBUG_INSTALL) { 9498 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9499 } 9500 9501 if (bp == null || bp.packageSetting == null) { 9502 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9503 Slog.w(TAG, "Unknown permission " + name 9504 + " in package " + pkg.packageName); 9505 } 9506 continue; 9507 } 9508 9509 final String perm = bp.name; 9510 boolean allowedSig = false; 9511 int grant = GRANT_DENIED; 9512 9513 // Keep track of app op permissions. 9514 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9515 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9516 if (pkgs == null) { 9517 pkgs = new ArraySet<>(); 9518 mAppOpPermissionPackages.put(bp.name, pkgs); 9519 } 9520 pkgs.add(pkg.packageName); 9521 } 9522 9523 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9524 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9525 >= Build.VERSION_CODES.M; 9526 switch (level) { 9527 case PermissionInfo.PROTECTION_NORMAL: { 9528 // For all apps normal permissions are install time ones. 9529 grant = GRANT_INSTALL; 9530 } break; 9531 9532 case PermissionInfo.PROTECTION_DANGEROUS: { 9533 // If a permission review is required for legacy apps we represent 9534 // their permissions as always granted runtime ones since we need 9535 // to keep the review required permission flag per user while an 9536 // install permission's state is shared across all users. 9537 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9538 // For legacy apps dangerous permissions are install time ones. 9539 grant = GRANT_INSTALL; 9540 } else if (origPermissions.hasInstallPermission(bp.name)) { 9541 // For legacy apps that became modern, install becomes runtime. 9542 grant = GRANT_UPGRADE; 9543 } else if (mPromoteSystemApps 9544 && isSystemApp(ps) 9545 && mExistingSystemPackages.contains(ps.name)) { 9546 // For legacy system apps, install becomes runtime. 9547 // We cannot check hasInstallPermission() for system apps since those 9548 // permissions were granted implicitly and not persisted pre-M. 9549 grant = GRANT_UPGRADE; 9550 } else { 9551 // For modern apps keep runtime permissions unchanged. 9552 grant = GRANT_RUNTIME; 9553 } 9554 } break; 9555 9556 case PermissionInfo.PROTECTION_SIGNATURE: { 9557 // For all apps signature permissions are install time ones. 9558 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9559 if (allowedSig) { 9560 grant = GRANT_INSTALL; 9561 } 9562 } break; 9563 } 9564 9565 if (DEBUG_INSTALL) { 9566 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9567 } 9568 9569 if (grant != GRANT_DENIED) { 9570 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9571 // If this is an existing, non-system package, then 9572 // we can't add any new permissions to it. 9573 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9574 // Except... if this is a permission that was added 9575 // to the platform (note: need to only do this when 9576 // updating the platform). 9577 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9578 grant = GRANT_DENIED; 9579 } 9580 } 9581 } 9582 9583 switch (grant) { 9584 case GRANT_INSTALL: { 9585 // Revoke this as runtime permission to handle the case of 9586 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9587 for (int userId : UserManagerService.getInstance().getUserIds()) { 9588 if (origPermissions.getRuntimePermissionState( 9589 bp.name, userId) != null) { 9590 // Revoke the runtime permission and clear the flags. 9591 origPermissions.revokeRuntimePermission(bp, userId); 9592 origPermissions.updatePermissionFlags(bp, userId, 9593 PackageManager.MASK_PERMISSION_FLAGS, 0); 9594 // If we revoked a permission permission, we have to write. 9595 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9596 changedRuntimePermissionUserIds, userId); 9597 } 9598 } 9599 // Grant an install permission. 9600 if (permissionsState.grantInstallPermission(bp) != 9601 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9602 changedInstallPermission = true; 9603 } 9604 } break; 9605 9606 case GRANT_RUNTIME: { 9607 // Grant previously granted runtime permissions. 9608 for (int userId : UserManagerService.getInstance().getUserIds()) { 9609 PermissionState permissionState = origPermissions 9610 .getRuntimePermissionState(bp.name, userId); 9611 int flags = permissionState != null 9612 ? permissionState.getFlags() : 0; 9613 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9614 if (permissionsState.grantRuntimePermission(bp, userId) == 9615 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9616 // If we cannot put the permission as it was, we have to write. 9617 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9618 changedRuntimePermissionUserIds, userId); 9619 } 9620 // If the app supports runtime permissions no need for a review. 9621 if (Build.PERMISSIONS_REVIEW_REQUIRED 9622 && appSupportsRuntimePermissions 9623 && (flags & PackageManager 9624 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9625 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9626 // Since we changed the flags, we have to write. 9627 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9628 changedRuntimePermissionUserIds, userId); 9629 } 9630 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9631 && !appSupportsRuntimePermissions) { 9632 // For legacy apps that need a permission review, every new 9633 // runtime permission is granted but it is pending a review. 9634 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9635 permissionsState.grantRuntimePermission(bp, userId); 9636 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9637 // We changed the permission and flags, hence have to write. 9638 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9639 changedRuntimePermissionUserIds, userId); 9640 } 9641 } 9642 // Propagate the permission flags. 9643 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9644 } 9645 } break; 9646 9647 case GRANT_UPGRADE: { 9648 // Grant runtime permissions for a previously held install permission. 9649 PermissionState permissionState = origPermissions 9650 .getInstallPermissionState(bp.name); 9651 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9652 9653 if (origPermissions.revokeInstallPermission(bp) 9654 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9655 // We will be transferring the permission flags, so clear them. 9656 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9657 PackageManager.MASK_PERMISSION_FLAGS, 0); 9658 changedInstallPermission = true; 9659 } 9660 9661 // If the permission is not to be promoted to runtime we ignore it and 9662 // also its other flags as they are not applicable to install permissions. 9663 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9664 for (int userId : currentUserIds) { 9665 if (permissionsState.grantRuntimePermission(bp, userId) != 9666 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9667 // Transfer the permission flags. 9668 permissionsState.updatePermissionFlags(bp, userId, 9669 flags, flags); 9670 // If we granted the permission, we have to write. 9671 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9672 changedRuntimePermissionUserIds, userId); 9673 } 9674 } 9675 } 9676 } break; 9677 9678 default: { 9679 if (packageOfInterest == null 9680 || packageOfInterest.equals(pkg.packageName)) { 9681 Slog.w(TAG, "Not granting permission " + perm 9682 + " to package " + pkg.packageName 9683 + " because it was previously installed without"); 9684 } 9685 } break; 9686 } 9687 } else { 9688 if (permissionsState.revokeInstallPermission(bp) != 9689 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9690 // Also drop the permission flags. 9691 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9692 PackageManager.MASK_PERMISSION_FLAGS, 0); 9693 changedInstallPermission = true; 9694 Slog.i(TAG, "Un-granting permission " + perm 9695 + " from package " + pkg.packageName 9696 + " (protectionLevel=" + bp.protectionLevel 9697 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9698 + ")"); 9699 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9700 // Don't print warning for app op permissions, since it is fine for them 9701 // not to be granted, there is a UI for the user to decide. 9702 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9703 Slog.w(TAG, "Not granting permission " + perm 9704 + " to package " + pkg.packageName 9705 + " (protectionLevel=" + bp.protectionLevel 9706 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9707 + ")"); 9708 } 9709 } 9710 } 9711 } 9712 9713 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9714 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9715 // This is the first that we have heard about this package, so the 9716 // permissions we have now selected are fixed until explicitly 9717 // changed. 9718 ps.installPermissionsFixed = true; 9719 } 9720 9721 // Persist the runtime permissions state for users with changes. If permissions 9722 // were revoked because no app in the shared user declares them we have to 9723 // write synchronously to avoid losing runtime permissions state. 9724 for (int userId : changedRuntimePermissionUserIds) { 9725 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9726 } 9727 9728 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9729 } 9730 9731 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9732 boolean allowed = false; 9733 final int NP = PackageParser.NEW_PERMISSIONS.length; 9734 for (int ip=0; ip<NP; ip++) { 9735 final PackageParser.NewPermissionInfo npi 9736 = PackageParser.NEW_PERMISSIONS[ip]; 9737 if (npi.name.equals(perm) 9738 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9739 allowed = true; 9740 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9741 + pkg.packageName); 9742 break; 9743 } 9744 } 9745 return allowed; 9746 } 9747 9748 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9749 BasePermission bp, PermissionsState origPermissions) { 9750 boolean allowed; 9751 allowed = (compareSignatures( 9752 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9753 == PackageManager.SIGNATURE_MATCH) 9754 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9755 == PackageManager.SIGNATURE_MATCH); 9756 if (!allowed && (bp.protectionLevel 9757 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9758 if (isSystemApp(pkg)) { 9759 // For updated system applications, a system permission 9760 // is granted only if it had been defined by the original application. 9761 if (pkg.isUpdatedSystemApp()) { 9762 final PackageSetting sysPs = mSettings 9763 .getDisabledSystemPkgLPr(pkg.packageName); 9764 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9765 // If the original was granted this permission, we take 9766 // that grant decision as read and propagate it to the 9767 // update. 9768 if (sysPs.isPrivileged()) { 9769 allowed = true; 9770 } 9771 } else { 9772 // The system apk may have been updated with an older 9773 // version of the one on the data partition, but which 9774 // granted a new system permission that it didn't have 9775 // before. In this case we do want to allow the app to 9776 // now get the new permission if the ancestral apk is 9777 // privileged to get it. 9778 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9779 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9780 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9781 allowed = true; 9782 break; 9783 } 9784 } 9785 } 9786 // Also if a privileged parent package on the system image or any of 9787 // its children requested a privileged permission, the updated child 9788 // packages can also get the permission. 9789 if (pkg.parentPackage != null) { 9790 final PackageSetting disabledSysParentPs = mSettings 9791 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9792 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9793 && disabledSysParentPs.isPrivileged()) { 9794 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9795 allowed = true; 9796 } else if (disabledSysParentPs.pkg.childPackages != null) { 9797 final int count = disabledSysParentPs.pkg.childPackages.size(); 9798 for (int i = 0; i < count; i++) { 9799 PackageParser.Package disabledSysChildPkg = 9800 disabledSysParentPs.pkg.childPackages.get(i); 9801 if (isPackageRequestingPermission(disabledSysChildPkg, 9802 perm)) { 9803 allowed = true; 9804 break; 9805 } 9806 } 9807 } 9808 } 9809 } 9810 } 9811 } else { 9812 allowed = isPrivilegedApp(pkg); 9813 } 9814 } 9815 } 9816 if (!allowed) { 9817 if (!allowed && (bp.protectionLevel 9818 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9819 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9820 // If this was a previously normal/dangerous permission that got moved 9821 // to a system permission as part of the runtime permission redesign, then 9822 // we still want to blindly grant it to old apps. 9823 allowed = true; 9824 } 9825 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9826 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9827 // If this permission is to be granted to the system installer and 9828 // this app is an installer, then it gets the permission. 9829 allowed = true; 9830 } 9831 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9832 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9833 // If this permission is to be granted to the system verifier and 9834 // this app is a verifier, then it gets the permission. 9835 allowed = true; 9836 } 9837 if (!allowed && (bp.protectionLevel 9838 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9839 && isSystemApp(pkg)) { 9840 // Any pre-installed system app is allowed to get this permission. 9841 allowed = true; 9842 } 9843 if (!allowed && (bp.protectionLevel 9844 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9845 // For development permissions, a development permission 9846 // is granted only if it was already granted. 9847 allowed = origPermissions.hasInstallPermission(perm); 9848 } 9849 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9850 && pkg.packageName.equals(mSetupWizardPackage)) { 9851 // If this permission is to be granted to the system setup wizard and 9852 // this app is a setup wizard, then it gets the permission. 9853 allowed = true; 9854 } 9855 } 9856 return allowed; 9857 } 9858 9859 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9860 final int permCount = pkg.requestedPermissions.size(); 9861 for (int j = 0; j < permCount; j++) { 9862 String requestedPermission = pkg.requestedPermissions.get(j); 9863 if (permission.equals(requestedPermission)) { 9864 return true; 9865 } 9866 } 9867 return false; 9868 } 9869 9870 final class ActivityIntentResolver 9871 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9872 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9873 boolean defaultOnly, int userId) { 9874 if (!sUserManager.exists(userId)) return null; 9875 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9876 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9877 } 9878 9879 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9880 int userId) { 9881 if (!sUserManager.exists(userId)) return null; 9882 mFlags = flags; 9883 return super.queryIntent(intent, resolvedType, 9884 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9885 } 9886 9887 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9888 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9889 if (!sUserManager.exists(userId)) return null; 9890 if (packageActivities == null) { 9891 return null; 9892 } 9893 mFlags = flags; 9894 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9895 final int N = packageActivities.size(); 9896 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9897 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9898 9899 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9900 for (int i = 0; i < N; ++i) { 9901 intentFilters = packageActivities.get(i).intents; 9902 if (intentFilters != null && intentFilters.size() > 0) { 9903 PackageParser.ActivityIntentInfo[] array = 9904 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9905 intentFilters.toArray(array); 9906 listCut.add(array); 9907 } 9908 } 9909 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9910 } 9911 9912 /** 9913 * Finds a privileged activity that matches the specified activity names. 9914 */ 9915 private PackageParser.Activity findMatchingActivity( 9916 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9917 for (PackageParser.Activity sysActivity : activityList) { 9918 if (sysActivity.info.name.equals(activityInfo.name)) { 9919 return sysActivity; 9920 } 9921 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9922 return sysActivity; 9923 } 9924 if (sysActivity.info.targetActivity != null) { 9925 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9926 return sysActivity; 9927 } 9928 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9929 return sysActivity; 9930 } 9931 } 9932 } 9933 return null; 9934 } 9935 9936 public class IterGenerator<E> { 9937 public Iterator<E> generate(ActivityIntentInfo info) { 9938 return null; 9939 } 9940 } 9941 9942 public class ActionIterGenerator extends IterGenerator<String> { 9943 @Override 9944 public Iterator<String> generate(ActivityIntentInfo info) { 9945 return info.actionsIterator(); 9946 } 9947 } 9948 9949 public class CategoriesIterGenerator extends IterGenerator<String> { 9950 @Override 9951 public Iterator<String> generate(ActivityIntentInfo info) { 9952 return info.categoriesIterator(); 9953 } 9954 } 9955 9956 public class SchemesIterGenerator extends IterGenerator<String> { 9957 @Override 9958 public Iterator<String> generate(ActivityIntentInfo info) { 9959 return info.schemesIterator(); 9960 } 9961 } 9962 9963 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9964 @Override 9965 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9966 return info.authoritiesIterator(); 9967 } 9968 } 9969 9970 /** 9971 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9972 * MODIFIED. Do not pass in a list that should not be changed. 9973 */ 9974 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9975 IterGenerator<T> generator, Iterator<T> searchIterator) { 9976 // loop through the set of actions; every one must be found in the intent filter 9977 while (searchIterator.hasNext()) { 9978 // we must have at least one filter in the list to consider a match 9979 if (intentList.size() == 0) { 9980 break; 9981 } 9982 9983 final T searchAction = searchIterator.next(); 9984 9985 // loop through the set of intent filters 9986 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9987 while (intentIter.hasNext()) { 9988 final ActivityIntentInfo intentInfo = intentIter.next(); 9989 boolean selectionFound = false; 9990 9991 // loop through the intent filter's selection criteria; at least one 9992 // of them must match the searched criteria 9993 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9994 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9995 final T intentSelection = intentSelectionIter.next(); 9996 if (intentSelection != null && intentSelection.equals(searchAction)) { 9997 selectionFound = true; 9998 break; 9999 } 10000 } 10001 10002 // the selection criteria wasn't found in this filter's set; this filter 10003 // is not a potential match 10004 if (!selectionFound) { 10005 intentIter.remove(); 10006 } 10007 } 10008 } 10009 } 10010 10011 private boolean isProtectedAction(ActivityIntentInfo filter) { 10012 final Iterator<String> actionsIter = filter.actionsIterator(); 10013 while (actionsIter != null && actionsIter.hasNext()) { 10014 final String filterAction = actionsIter.next(); 10015 if (PROTECTED_ACTIONS.contains(filterAction)) { 10016 return true; 10017 } 10018 } 10019 return false; 10020 } 10021 10022 /** 10023 * Adjusts the priority of the given intent filter according to policy. 10024 * <p> 10025 * <ul> 10026 * <li>The priority for non privileged applications is capped to '0'</li> 10027 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10028 * <li>The priority for unbundled updates to privileged applications is capped to the 10029 * priority defined on the system partition</li> 10030 * </ul> 10031 * <p> 10032 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10033 * allowed to obtain any priority on any action. 10034 */ 10035 private void adjustPriority( 10036 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10037 // nothing to do; priority is fine as-is 10038 if (intent.getPriority() <= 0) { 10039 return; 10040 } 10041 10042 final ActivityInfo activityInfo = intent.activity.info; 10043 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10044 10045 final boolean privilegedApp = 10046 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10047 if (!privilegedApp) { 10048 // non-privileged applications can never define a priority >0 10049 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10050 + " package: " + applicationInfo.packageName 10051 + " activity: " + intent.activity.className 10052 + " origPrio: " + intent.getPriority()); 10053 intent.setPriority(0); 10054 return; 10055 } 10056 10057 if (systemActivities == null) { 10058 // the system package is not disabled; we're parsing the system partition 10059 if (isProtectedAction(intent)) { 10060 if (mDeferProtectedFilters) { 10061 // We can't deal with these just yet. No component should ever obtain a 10062 // >0 priority for a protected actions, with ONE exception -- the setup 10063 // wizard. The setup wizard, however, cannot be known until we're able to 10064 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10065 // until all intent filters have been processed. Chicken, meet egg. 10066 // Let the filter temporarily have a high priority and rectify the 10067 // priorities after all system packages have been scanned. 10068 mProtectedFilters.add(intent); 10069 if (DEBUG_FILTERS) { 10070 Slog.i(TAG, "Protected action; save for later;" 10071 + " package: " + applicationInfo.packageName 10072 + " activity: " + intent.activity.className 10073 + " origPrio: " + intent.getPriority()); 10074 } 10075 return; 10076 } else { 10077 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10078 Slog.i(TAG, "No setup wizard;" 10079 + " All protected intents capped to priority 0"); 10080 } 10081 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10082 if (DEBUG_FILTERS) { 10083 Slog.i(TAG, "Found setup wizard;" 10084 + " allow priority " + intent.getPriority() + ";" 10085 + " package: " + intent.activity.info.packageName 10086 + " activity: " + intent.activity.className 10087 + " priority: " + intent.getPriority()); 10088 } 10089 // setup wizard gets whatever it wants 10090 return; 10091 } 10092 Slog.w(TAG, "Protected action; cap priority to 0;" 10093 + " package: " + intent.activity.info.packageName 10094 + " activity: " + intent.activity.className 10095 + " origPrio: " + intent.getPriority()); 10096 intent.setPriority(0); 10097 return; 10098 } 10099 } 10100 // privileged apps on the system image get whatever priority they request 10101 return; 10102 } 10103 10104 // privileged app unbundled update ... try to find the same activity 10105 final PackageParser.Activity foundActivity = 10106 findMatchingActivity(systemActivities, activityInfo); 10107 if (foundActivity == null) { 10108 // this is a new activity; it cannot obtain >0 priority 10109 if (DEBUG_FILTERS) { 10110 Slog.i(TAG, "New activity; cap priority to 0;" 10111 + " package: " + applicationInfo.packageName 10112 + " activity: " + intent.activity.className 10113 + " origPrio: " + intent.getPriority()); 10114 } 10115 intent.setPriority(0); 10116 return; 10117 } 10118 10119 // found activity, now check for filter equivalence 10120 10121 // a shallow copy is enough; we modify the list, not its contents 10122 final List<ActivityIntentInfo> intentListCopy = 10123 new ArrayList<>(foundActivity.intents); 10124 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10125 10126 // find matching action subsets 10127 final Iterator<String> actionsIterator = intent.actionsIterator(); 10128 if (actionsIterator != null) { 10129 getIntentListSubset( 10130 intentListCopy, new ActionIterGenerator(), actionsIterator); 10131 if (intentListCopy.size() == 0) { 10132 // no more intents to match; we're not equivalent 10133 if (DEBUG_FILTERS) { 10134 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10135 + " package: " + applicationInfo.packageName 10136 + " activity: " + intent.activity.className 10137 + " origPrio: " + intent.getPriority()); 10138 } 10139 intent.setPriority(0); 10140 return; 10141 } 10142 } 10143 10144 // find matching category subsets 10145 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10146 if (categoriesIterator != null) { 10147 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10148 categoriesIterator); 10149 if (intentListCopy.size() == 0) { 10150 // no more intents to match; we're not equivalent 10151 if (DEBUG_FILTERS) { 10152 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10153 + " package: " + applicationInfo.packageName 10154 + " activity: " + intent.activity.className 10155 + " origPrio: " + intent.getPriority()); 10156 } 10157 intent.setPriority(0); 10158 return; 10159 } 10160 } 10161 10162 // find matching schemes subsets 10163 final Iterator<String> schemesIterator = intent.schemesIterator(); 10164 if (schemesIterator != null) { 10165 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10166 schemesIterator); 10167 if (intentListCopy.size() == 0) { 10168 // no more intents to match; we're not equivalent 10169 if (DEBUG_FILTERS) { 10170 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10171 + " package: " + applicationInfo.packageName 10172 + " activity: " + intent.activity.className 10173 + " origPrio: " + intent.getPriority()); 10174 } 10175 intent.setPriority(0); 10176 return; 10177 } 10178 } 10179 10180 // find matching authorities subsets 10181 final Iterator<IntentFilter.AuthorityEntry> 10182 authoritiesIterator = intent.authoritiesIterator(); 10183 if (authoritiesIterator != null) { 10184 getIntentListSubset(intentListCopy, 10185 new AuthoritiesIterGenerator(), 10186 authoritiesIterator); 10187 if (intentListCopy.size() == 0) { 10188 // no more intents to match; we're not equivalent 10189 if (DEBUG_FILTERS) { 10190 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10191 + " package: " + applicationInfo.packageName 10192 + " activity: " + intent.activity.className 10193 + " origPrio: " + intent.getPriority()); 10194 } 10195 intent.setPriority(0); 10196 return; 10197 } 10198 } 10199 10200 // we found matching filter(s); app gets the max priority of all intents 10201 int cappedPriority = 0; 10202 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10203 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10204 } 10205 if (intent.getPriority() > cappedPriority) { 10206 if (DEBUG_FILTERS) { 10207 Slog.i(TAG, "Found matching filter(s);" 10208 + " cap priority to " + cappedPriority + ";" 10209 + " package: " + applicationInfo.packageName 10210 + " activity: " + intent.activity.className 10211 + " origPrio: " + intent.getPriority()); 10212 } 10213 intent.setPriority(cappedPriority); 10214 return; 10215 } 10216 // all this for nothing; the requested priority was <= what was on the system 10217 } 10218 10219 public final void addActivity(PackageParser.Activity a, String type) { 10220 mActivities.put(a.getComponentName(), a); 10221 if (DEBUG_SHOW_INFO) 10222 Log.v( 10223 TAG, " " + type + " " + 10224 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10225 if (DEBUG_SHOW_INFO) 10226 Log.v(TAG, " Class=" + a.info.name); 10227 final int NI = a.intents.size(); 10228 for (int j=0; j<NI; j++) { 10229 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10230 if ("activity".equals(type)) { 10231 final PackageSetting ps = 10232 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10233 final List<PackageParser.Activity> systemActivities = 10234 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10235 adjustPriority(systemActivities, intent); 10236 } 10237 if (DEBUG_SHOW_INFO) { 10238 Log.v(TAG, " IntentFilter:"); 10239 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10240 } 10241 if (!intent.debugCheck()) { 10242 Log.w(TAG, "==> For Activity " + a.info.name); 10243 } 10244 addFilter(intent); 10245 } 10246 } 10247 10248 public final void removeActivity(PackageParser.Activity a, String type) { 10249 mActivities.remove(a.getComponentName()); 10250 if (DEBUG_SHOW_INFO) { 10251 Log.v(TAG, " " + type + " " 10252 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10253 : a.info.name) + ":"); 10254 Log.v(TAG, " Class=" + a.info.name); 10255 } 10256 final int NI = a.intents.size(); 10257 for (int j=0; j<NI; j++) { 10258 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10259 if (DEBUG_SHOW_INFO) { 10260 Log.v(TAG, " IntentFilter:"); 10261 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10262 } 10263 removeFilter(intent); 10264 } 10265 } 10266 10267 @Override 10268 protected boolean allowFilterResult( 10269 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10270 ActivityInfo filterAi = filter.activity.info; 10271 for (int i=dest.size()-1; i>=0; i--) { 10272 ActivityInfo destAi = dest.get(i).activityInfo; 10273 if (destAi.name == filterAi.name 10274 && destAi.packageName == filterAi.packageName) { 10275 return false; 10276 } 10277 } 10278 return true; 10279 } 10280 10281 @Override 10282 protected ActivityIntentInfo[] newArray(int size) { 10283 return new ActivityIntentInfo[size]; 10284 } 10285 10286 @Override 10287 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10288 if (!sUserManager.exists(userId)) return true; 10289 PackageParser.Package p = filter.activity.owner; 10290 if (p != null) { 10291 PackageSetting ps = (PackageSetting)p.mExtras; 10292 if (ps != null) { 10293 // System apps are never considered stopped for purposes of 10294 // filtering, because there may be no way for the user to 10295 // actually re-launch them. 10296 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10297 && ps.getStopped(userId); 10298 } 10299 } 10300 return false; 10301 } 10302 10303 @Override 10304 protected boolean isPackageForFilter(String packageName, 10305 PackageParser.ActivityIntentInfo info) { 10306 return packageName.equals(info.activity.owner.packageName); 10307 } 10308 10309 @Override 10310 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10311 int match, int userId) { 10312 if (!sUserManager.exists(userId)) return null; 10313 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10314 return null; 10315 } 10316 final PackageParser.Activity activity = info.activity; 10317 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10318 if (ps == null) { 10319 return null; 10320 } 10321 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10322 ps.readUserState(userId), userId); 10323 if (ai == null) { 10324 return null; 10325 } 10326 final ResolveInfo res = new ResolveInfo(); 10327 res.activityInfo = ai; 10328 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10329 res.filter = info; 10330 } 10331 if (info != null) { 10332 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10333 } 10334 res.priority = info.getPriority(); 10335 res.preferredOrder = activity.owner.mPreferredOrder; 10336 //System.out.println("Result: " + res.activityInfo.className + 10337 // " = " + res.priority); 10338 res.match = match; 10339 res.isDefault = info.hasDefault; 10340 res.labelRes = info.labelRes; 10341 res.nonLocalizedLabel = info.nonLocalizedLabel; 10342 if (userNeedsBadging(userId)) { 10343 res.noResourceId = true; 10344 } else { 10345 res.icon = info.icon; 10346 } 10347 res.iconResourceId = info.icon; 10348 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10349 return res; 10350 } 10351 10352 @Override 10353 protected void sortResults(List<ResolveInfo> results) { 10354 Collections.sort(results, mResolvePrioritySorter); 10355 } 10356 10357 @Override 10358 protected void dumpFilter(PrintWriter out, String prefix, 10359 PackageParser.ActivityIntentInfo filter) { 10360 out.print(prefix); out.print( 10361 Integer.toHexString(System.identityHashCode(filter.activity))); 10362 out.print(' '); 10363 filter.activity.printComponentShortName(out); 10364 out.print(" filter "); 10365 out.println(Integer.toHexString(System.identityHashCode(filter))); 10366 } 10367 10368 @Override 10369 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10370 return filter.activity; 10371 } 10372 10373 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10374 PackageParser.Activity activity = (PackageParser.Activity)label; 10375 out.print(prefix); out.print( 10376 Integer.toHexString(System.identityHashCode(activity))); 10377 out.print(' '); 10378 activity.printComponentShortName(out); 10379 if (count > 1) { 10380 out.print(" ("); out.print(count); out.print(" filters)"); 10381 } 10382 out.println(); 10383 } 10384 10385 // Keys are String (activity class name), values are Activity. 10386 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10387 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10388 private int mFlags; 10389 } 10390 10391 private final class ServiceIntentResolver 10392 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10393 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10394 boolean defaultOnly, int userId) { 10395 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10396 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10397 } 10398 10399 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10400 int userId) { 10401 if (!sUserManager.exists(userId)) return null; 10402 mFlags = flags; 10403 return super.queryIntent(intent, resolvedType, 10404 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10405 } 10406 10407 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10408 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10409 if (!sUserManager.exists(userId)) return null; 10410 if (packageServices == null) { 10411 return null; 10412 } 10413 mFlags = flags; 10414 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10415 final int N = packageServices.size(); 10416 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10417 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10418 10419 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10420 for (int i = 0; i < N; ++i) { 10421 intentFilters = packageServices.get(i).intents; 10422 if (intentFilters != null && intentFilters.size() > 0) { 10423 PackageParser.ServiceIntentInfo[] array = 10424 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10425 intentFilters.toArray(array); 10426 listCut.add(array); 10427 } 10428 } 10429 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10430 } 10431 10432 public final void addService(PackageParser.Service s) { 10433 mServices.put(s.getComponentName(), s); 10434 if (DEBUG_SHOW_INFO) { 10435 Log.v(TAG, " " 10436 + (s.info.nonLocalizedLabel != null 10437 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10438 Log.v(TAG, " Class=" + s.info.name); 10439 } 10440 final int NI = s.intents.size(); 10441 int j; 10442 for (j=0; j<NI; j++) { 10443 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10444 if (DEBUG_SHOW_INFO) { 10445 Log.v(TAG, " IntentFilter:"); 10446 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10447 } 10448 if (!intent.debugCheck()) { 10449 Log.w(TAG, "==> For Service " + s.info.name); 10450 } 10451 addFilter(intent); 10452 } 10453 } 10454 10455 public final void removeService(PackageParser.Service s) { 10456 mServices.remove(s.getComponentName()); 10457 if (DEBUG_SHOW_INFO) { 10458 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10459 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10460 Log.v(TAG, " Class=" + s.info.name); 10461 } 10462 final int NI = s.intents.size(); 10463 int j; 10464 for (j=0; j<NI; j++) { 10465 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10466 if (DEBUG_SHOW_INFO) { 10467 Log.v(TAG, " IntentFilter:"); 10468 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10469 } 10470 removeFilter(intent); 10471 } 10472 } 10473 10474 @Override 10475 protected boolean allowFilterResult( 10476 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10477 ServiceInfo filterSi = filter.service.info; 10478 for (int i=dest.size()-1; i>=0; i--) { 10479 ServiceInfo destAi = dest.get(i).serviceInfo; 10480 if (destAi.name == filterSi.name 10481 && destAi.packageName == filterSi.packageName) { 10482 return false; 10483 } 10484 } 10485 return true; 10486 } 10487 10488 @Override 10489 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10490 return new PackageParser.ServiceIntentInfo[size]; 10491 } 10492 10493 @Override 10494 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10495 if (!sUserManager.exists(userId)) return true; 10496 PackageParser.Package p = filter.service.owner; 10497 if (p != null) { 10498 PackageSetting ps = (PackageSetting)p.mExtras; 10499 if (ps != null) { 10500 // System apps are never considered stopped for purposes of 10501 // filtering, because there may be no way for the user to 10502 // actually re-launch them. 10503 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10504 && ps.getStopped(userId); 10505 } 10506 } 10507 return false; 10508 } 10509 10510 @Override 10511 protected boolean isPackageForFilter(String packageName, 10512 PackageParser.ServiceIntentInfo info) { 10513 return packageName.equals(info.service.owner.packageName); 10514 } 10515 10516 @Override 10517 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10518 int match, int userId) { 10519 if (!sUserManager.exists(userId)) return null; 10520 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10521 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10522 return null; 10523 } 10524 final PackageParser.Service service = info.service; 10525 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10526 if (ps == null) { 10527 return null; 10528 } 10529 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10530 ps.readUserState(userId), userId); 10531 if (si == null) { 10532 return null; 10533 } 10534 final ResolveInfo res = new ResolveInfo(); 10535 res.serviceInfo = si; 10536 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10537 res.filter = filter; 10538 } 10539 res.priority = info.getPriority(); 10540 res.preferredOrder = service.owner.mPreferredOrder; 10541 res.match = match; 10542 res.isDefault = info.hasDefault; 10543 res.labelRes = info.labelRes; 10544 res.nonLocalizedLabel = info.nonLocalizedLabel; 10545 res.icon = info.icon; 10546 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10547 return res; 10548 } 10549 10550 @Override 10551 protected void sortResults(List<ResolveInfo> results) { 10552 Collections.sort(results, mResolvePrioritySorter); 10553 } 10554 10555 @Override 10556 protected void dumpFilter(PrintWriter out, String prefix, 10557 PackageParser.ServiceIntentInfo filter) { 10558 out.print(prefix); out.print( 10559 Integer.toHexString(System.identityHashCode(filter.service))); 10560 out.print(' '); 10561 filter.service.printComponentShortName(out); 10562 out.print(" filter "); 10563 out.println(Integer.toHexString(System.identityHashCode(filter))); 10564 } 10565 10566 @Override 10567 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10568 return filter.service; 10569 } 10570 10571 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10572 PackageParser.Service service = (PackageParser.Service)label; 10573 out.print(prefix); out.print( 10574 Integer.toHexString(System.identityHashCode(service))); 10575 out.print(' '); 10576 service.printComponentShortName(out); 10577 if (count > 1) { 10578 out.print(" ("); out.print(count); out.print(" filters)"); 10579 } 10580 out.println(); 10581 } 10582 10583// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10584// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10585// final List<ResolveInfo> retList = Lists.newArrayList(); 10586// while (i.hasNext()) { 10587// final ResolveInfo resolveInfo = (ResolveInfo) i; 10588// if (isEnabledLP(resolveInfo.serviceInfo)) { 10589// retList.add(resolveInfo); 10590// } 10591// } 10592// return retList; 10593// } 10594 10595 // Keys are String (activity class name), values are Activity. 10596 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10597 = new ArrayMap<ComponentName, PackageParser.Service>(); 10598 private int mFlags; 10599 }; 10600 10601 private final class ProviderIntentResolver 10602 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10603 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10604 boolean defaultOnly, int userId) { 10605 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10606 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10607 } 10608 10609 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10610 int userId) { 10611 if (!sUserManager.exists(userId)) 10612 return null; 10613 mFlags = flags; 10614 return super.queryIntent(intent, resolvedType, 10615 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10616 } 10617 10618 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10619 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10620 if (!sUserManager.exists(userId)) 10621 return null; 10622 if (packageProviders == null) { 10623 return null; 10624 } 10625 mFlags = flags; 10626 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10627 final int N = packageProviders.size(); 10628 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10629 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10630 10631 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10632 for (int i = 0; i < N; ++i) { 10633 intentFilters = packageProviders.get(i).intents; 10634 if (intentFilters != null && intentFilters.size() > 0) { 10635 PackageParser.ProviderIntentInfo[] array = 10636 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10637 intentFilters.toArray(array); 10638 listCut.add(array); 10639 } 10640 } 10641 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10642 } 10643 10644 public final void addProvider(PackageParser.Provider p) { 10645 if (mProviders.containsKey(p.getComponentName())) { 10646 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10647 return; 10648 } 10649 10650 mProviders.put(p.getComponentName(), p); 10651 if (DEBUG_SHOW_INFO) { 10652 Log.v(TAG, " " 10653 + (p.info.nonLocalizedLabel != null 10654 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10655 Log.v(TAG, " Class=" + p.info.name); 10656 } 10657 final int NI = p.intents.size(); 10658 int j; 10659 for (j = 0; j < NI; j++) { 10660 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10661 if (DEBUG_SHOW_INFO) { 10662 Log.v(TAG, " IntentFilter:"); 10663 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10664 } 10665 if (!intent.debugCheck()) { 10666 Log.w(TAG, "==> For Provider " + p.info.name); 10667 } 10668 addFilter(intent); 10669 } 10670 } 10671 10672 public final void removeProvider(PackageParser.Provider p) { 10673 mProviders.remove(p.getComponentName()); 10674 if (DEBUG_SHOW_INFO) { 10675 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10676 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10677 Log.v(TAG, " Class=" + p.info.name); 10678 } 10679 final int NI = p.intents.size(); 10680 int j; 10681 for (j = 0; j < NI; j++) { 10682 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10683 if (DEBUG_SHOW_INFO) { 10684 Log.v(TAG, " IntentFilter:"); 10685 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10686 } 10687 removeFilter(intent); 10688 } 10689 } 10690 10691 @Override 10692 protected boolean allowFilterResult( 10693 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10694 ProviderInfo filterPi = filter.provider.info; 10695 for (int i = dest.size() - 1; i >= 0; i--) { 10696 ProviderInfo destPi = dest.get(i).providerInfo; 10697 if (destPi.name == filterPi.name 10698 && destPi.packageName == filterPi.packageName) { 10699 return false; 10700 } 10701 } 10702 return true; 10703 } 10704 10705 @Override 10706 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10707 return new PackageParser.ProviderIntentInfo[size]; 10708 } 10709 10710 @Override 10711 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10712 if (!sUserManager.exists(userId)) 10713 return true; 10714 PackageParser.Package p = filter.provider.owner; 10715 if (p != null) { 10716 PackageSetting ps = (PackageSetting) p.mExtras; 10717 if (ps != null) { 10718 // System apps are never considered stopped for purposes of 10719 // filtering, because there may be no way for the user to 10720 // actually re-launch them. 10721 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10722 && ps.getStopped(userId); 10723 } 10724 } 10725 return false; 10726 } 10727 10728 @Override 10729 protected boolean isPackageForFilter(String packageName, 10730 PackageParser.ProviderIntentInfo info) { 10731 return packageName.equals(info.provider.owner.packageName); 10732 } 10733 10734 @Override 10735 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10736 int match, int userId) { 10737 if (!sUserManager.exists(userId)) 10738 return null; 10739 final PackageParser.ProviderIntentInfo info = filter; 10740 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10741 return null; 10742 } 10743 final PackageParser.Provider provider = info.provider; 10744 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10745 if (ps == null) { 10746 return null; 10747 } 10748 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10749 ps.readUserState(userId), userId); 10750 if (pi == null) { 10751 return null; 10752 } 10753 final ResolveInfo res = new ResolveInfo(); 10754 res.providerInfo = pi; 10755 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10756 res.filter = filter; 10757 } 10758 res.priority = info.getPriority(); 10759 res.preferredOrder = provider.owner.mPreferredOrder; 10760 res.match = match; 10761 res.isDefault = info.hasDefault; 10762 res.labelRes = info.labelRes; 10763 res.nonLocalizedLabel = info.nonLocalizedLabel; 10764 res.icon = info.icon; 10765 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10766 return res; 10767 } 10768 10769 @Override 10770 protected void sortResults(List<ResolveInfo> results) { 10771 Collections.sort(results, mResolvePrioritySorter); 10772 } 10773 10774 @Override 10775 protected void dumpFilter(PrintWriter out, String prefix, 10776 PackageParser.ProviderIntentInfo filter) { 10777 out.print(prefix); 10778 out.print( 10779 Integer.toHexString(System.identityHashCode(filter.provider))); 10780 out.print(' '); 10781 filter.provider.printComponentShortName(out); 10782 out.print(" filter "); 10783 out.println(Integer.toHexString(System.identityHashCode(filter))); 10784 } 10785 10786 @Override 10787 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10788 return filter.provider; 10789 } 10790 10791 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10792 PackageParser.Provider provider = (PackageParser.Provider)label; 10793 out.print(prefix); out.print( 10794 Integer.toHexString(System.identityHashCode(provider))); 10795 out.print(' '); 10796 provider.printComponentShortName(out); 10797 if (count > 1) { 10798 out.print(" ("); out.print(count); out.print(" filters)"); 10799 } 10800 out.println(); 10801 } 10802 10803 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10804 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10805 private int mFlags; 10806 } 10807 10808 private static final class EphemeralIntentResolver 10809 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10810 @Override 10811 protected EphemeralResolveIntentInfo[] newArray(int size) { 10812 return new EphemeralResolveIntentInfo[size]; 10813 } 10814 10815 @Override 10816 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10817 return true; 10818 } 10819 10820 @Override 10821 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10822 int userId) { 10823 if (!sUserManager.exists(userId)) { 10824 return null; 10825 } 10826 return info.getEphemeralResolveInfo(); 10827 } 10828 } 10829 10830 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10831 new Comparator<ResolveInfo>() { 10832 public int compare(ResolveInfo r1, ResolveInfo r2) { 10833 int v1 = r1.priority; 10834 int v2 = r2.priority; 10835 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10836 if (v1 != v2) { 10837 return (v1 > v2) ? -1 : 1; 10838 } 10839 v1 = r1.preferredOrder; 10840 v2 = r2.preferredOrder; 10841 if (v1 != v2) { 10842 return (v1 > v2) ? -1 : 1; 10843 } 10844 if (r1.isDefault != r2.isDefault) { 10845 return r1.isDefault ? -1 : 1; 10846 } 10847 v1 = r1.match; 10848 v2 = r2.match; 10849 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10850 if (v1 != v2) { 10851 return (v1 > v2) ? -1 : 1; 10852 } 10853 if (r1.system != r2.system) { 10854 return r1.system ? -1 : 1; 10855 } 10856 if (r1.activityInfo != null) { 10857 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10858 } 10859 if (r1.serviceInfo != null) { 10860 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10861 } 10862 if (r1.providerInfo != null) { 10863 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10864 } 10865 return 0; 10866 } 10867 }; 10868 10869 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10870 new Comparator<ProviderInfo>() { 10871 public int compare(ProviderInfo p1, ProviderInfo p2) { 10872 final int v1 = p1.initOrder; 10873 final int v2 = p2.initOrder; 10874 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10875 } 10876 }; 10877 10878 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10879 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10880 final int[] userIds) { 10881 mHandler.post(new Runnable() { 10882 @Override 10883 public void run() { 10884 try { 10885 final IActivityManager am = ActivityManagerNative.getDefault(); 10886 if (am == null) return; 10887 final int[] resolvedUserIds; 10888 if (userIds == null) { 10889 resolvedUserIds = am.getRunningUserIds(); 10890 } else { 10891 resolvedUserIds = userIds; 10892 } 10893 for (int id : resolvedUserIds) { 10894 final Intent intent = new Intent(action, 10895 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10896 if (extras != null) { 10897 intent.putExtras(extras); 10898 } 10899 if (targetPkg != null) { 10900 intent.setPackage(targetPkg); 10901 } 10902 // Modify the UID when posting to other users 10903 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10904 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10905 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10906 intent.putExtra(Intent.EXTRA_UID, uid); 10907 } 10908 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10909 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10910 if (DEBUG_BROADCASTS) { 10911 RuntimeException here = new RuntimeException("here"); 10912 here.fillInStackTrace(); 10913 Slog.d(TAG, "Sending to user " + id + ": " 10914 + intent.toShortString(false, true, false, false) 10915 + " " + intent.getExtras(), here); 10916 } 10917 am.broadcastIntent(null, intent, null, finishedReceiver, 10918 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10919 null, finishedReceiver != null, false, id); 10920 } 10921 } catch (RemoteException ex) { 10922 } 10923 } 10924 }); 10925 } 10926 10927 /** 10928 * Check if the external storage media is available. This is true if there 10929 * is a mounted external storage medium or if the external storage is 10930 * emulated. 10931 */ 10932 private boolean isExternalMediaAvailable() { 10933 return mMediaMounted || Environment.isExternalStorageEmulated(); 10934 } 10935 10936 @Override 10937 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10938 // writer 10939 synchronized (mPackages) { 10940 if (!isExternalMediaAvailable()) { 10941 // If the external storage is no longer mounted at this point, 10942 // the caller may not have been able to delete all of this 10943 // packages files and can not delete any more. Bail. 10944 return null; 10945 } 10946 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10947 if (lastPackage != null) { 10948 pkgs.remove(lastPackage); 10949 } 10950 if (pkgs.size() > 0) { 10951 return pkgs.get(0); 10952 } 10953 } 10954 return null; 10955 } 10956 10957 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10958 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10959 userId, andCode ? 1 : 0, packageName); 10960 if (mSystemReady) { 10961 msg.sendToTarget(); 10962 } else { 10963 if (mPostSystemReadyMessages == null) { 10964 mPostSystemReadyMessages = new ArrayList<>(); 10965 } 10966 mPostSystemReadyMessages.add(msg); 10967 } 10968 } 10969 10970 void startCleaningPackages() { 10971 // reader 10972 if (!isExternalMediaAvailable()) { 10973 return; 10974 } 10975 synchronized (mPackages) { 10976 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10977 return; 10978 } 10979 } 10980 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10981 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10982 IActivityManager am = ActivityManagerNative.getDefault(); 10983 if (am != null) { 10984 try { 10985 am.startService(null, intent, null, mContext.getOpPackageName(), 10986 UserHandle.USER_SYSTEM); 10987 } catch (RemoteException e) { 10988 } 10989 } 10990 } 10991 10992 @Override 10993 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10994 int installFlags, String installerPackageName, int userId) { 10995 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10996 10997 final int callingUid = Binder.getCallingUid(); 10998 enforceCrossUserPermission(callingUid, userId, 10999 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11000 11001 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11002 try { 11003 if (observer != null) { 11004 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11005 } 11006 } catch (RemoteException re) { 11007 } 11008 return; 11009 } 11010 11011 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11012 installFlags |= PackageManager.INSTALL_FROM_ADB; 11013 11014 } else { 11015 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11016 // about installerPackageName. 11017 11018 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11019 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11020 } 11021 11022 UserHandle user; 11023 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11024 user = UserHandle.ALL; 11025 } else { 11026 user = new UserHandle(userId); 11027 } 11028 11029 // Only system components can circumvent runtime permissions when installing. 11030 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11031 && mContext.checkCallingOrSelfPermission(Manifest.permission 11032 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11033 throw new SecurityException("You need the " 11034 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11035 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11036 } 11037 11038 final File originFile = new File(originPath); 11039 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11040 11041 final Message msg = mHandler.obtainMessage(INIT_COPY); 11042 final VerificationInfo verificationInfo = new VerificationInfo( 11043 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11044 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11045 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11046 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11047 null /*certificates*/); 11048 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11049 msg.obj = params; 11050 11051 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11052 System.identityHashCode(msg.obj)); 11053 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11054 System.identityHashCode(msg.obj)); 11055 11056 mHandler.sendMessage(msg); 11057 } 11058 11059 void installStage(String packageName, File stagedDir, String stagedCid, 11060 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11061 String installerPackageName, int installerUid, UserHandle user, 11062 Certificate[][] certificates) { 11063 if (DEBUG_EPHEMERAL) { 11064 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11065 Slog.d(TAG, "Ephemeral install of " + packageName); 11066 } 11067 } 11068 final VerificationInfo verificationInfo = new VerificationInfo( 11069 sessionParams.originatingUri, sessionParams.referrerUri, 11070 sessionParams.originatingUid, installerUid); 11071 11072 final OriginInfo origin; 11073 if (stagedDir != null) { 11074 origin = OriginInfo.fromStagedFile(stagedDir); 11075 } else { 11076 origin = OriginInfo.fromStagedContainer(stagedCid); 11077 } 11078 11079 final Message msg = mHandler.obtainMessage(INIT_COPY); 11080 final InstallParams params = new InstallParams(origin, null, observer, 11081 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11082 verificationInfo, user, sessionParams.abiOverride, 11083 sessionParams.grantedRuntimePermissions, certificates); 11084 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11085 msg.obj = params; 11086 11087 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11088 System.identityHashCode(msg.obj)); 11089 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11090 System.identityHashCode(msg.obj)); 11091 11092 mHandler.sendMessage(msg); 11093 } 11094 11095 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11096 int userId) { 11097 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11098 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11099 } 11100 11101 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11102 int appId, int userId) { 11103 Bundle extras = new Bundle(1); 11104 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11105 11106 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11107 packageName, extras, 0, null, null, new int[] {userId}); 11108 try { 11109 IActivityManager am = ActivityManagerNative.getDefault(); 11110 if (isSystem && am.isUserRunning(userId, 0)) { 11111 // The just-installed/enabled app is bundled on the system, so presumed 11112 // to be able to run automatically without needing an explicit launch. 11113 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11114 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11115 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11116 .setPackage(packageName); 11117 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11118 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11119 } 11120 } catch (RemoteException e) { 11121 // shouldn't happen 11122 Slog.w(TAG, "Unable to bootstrap installed package", e); 11123 } 11124 } 11125 11126 @Override 11127 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11128 int userId) { 11129 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11130 PackageSetting pkgSetting; 11131 final int uid = Binder.getCallingUid(); 11132 enforceCrossUserPermission(uid, userId, 11133 true /* requireFullPermission */, true /* checkShell */, 11134 "setApplicationHiddenSetting for user " + userId); 11135 11136 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11137 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11138 return false; 11139 } 11140 11141 long callingId = Binder.clearCallingIdentity(); 11142 try { 11143 boolean sendAdded = false; 11144 boolean sendRemoved = false; 11145 // writer 11146 synchronized (mPackages) { 11147 pkgSetting = mSettings.mPackages.get(packageName); 11148 if (pkgSetting == null) { 11149 return false; 11150 } 11151 if (pkgSetting.getHidden(userId) != hidden) { 11152 pkgSetting.setHidden(hidden, userId); 11153 mSettings.writePackageRestrictionsLPr(userId); 11154 if (hidden) { 11155 sendRemoved = true; 11156 } else { 11157 sendAdded = true; 11158 } 11159 } 11160 } 11161 if (sendAdded) { 11162 sendPackageAddedForUser(packageName, pkgSetting, userId); 11163 return true; 11164 } 11165 if (sendRemoved) { 11166 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11167 "hiding pkg"); 11168 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11169 return true; 11170 } 11171 } finally { 11172 Binder.restoreCallingIdentity(callingId); 11173 } 11174 return false; 11175 } 11176 11177 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11178 int userId) { 11179 final PackageRemovedInfo info = new PackageRemovedInfo(); 11180 info.removedPackage = packageName; 11181 info.removedUsers = new int[] {userId}; 11182 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11183 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11184 } 11185 11186 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11187 if (pkgList.length > 0) { 11188 Bundle extras = new Bundle(1); 11189 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11190 11191 sendPackageBroadcast( 11192 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11193 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11194 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11195 new int[] {userId}); 11196 } 11197 } 11198 11199 /** 11200 * Returns true if application is not found or there was an error. Otherwise it returns 11201 * the hidden state of the package for the given user. 11202 */ 11203 @Override 11204 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11205 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11206 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11207 true /* requireFullPermission */, false /* checkShell */, 11208 "getApplicationHidden for user " + userId); 11209 PackageSetting pkgSetting; 11210 long callingId = Binder.clearCallingIdentity(); 11211 try { 11212 // writer 11213 synchronized (mPackages) { 11214 pkgSetting = mSettings.mPackages.get(packageName); 11215 if (pkgSetting == null) { 11216 return true; 11217 } 11218 return pkgSetting.getHidden(userId); 11219 } 11220 } finally { 11221 Binder.restoreCallingIdentity(callingId); 11222 } 11223 } 11224 11225 /** 11226 * @hide 11227 */ 11228 @Override 11229 public int installExistingPackageAsUser(String packageName, int userId) { 11230 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11231 null); 11232 PackageSetting pkgSetting; 11233 final int uid = Binder.getCallingUid(); 11234 enforceCrossUserPermission(uid, userId, 11235 true /* requireFullPermission */, true /* checkShell */, 11236 "installExistingPackage for user " + userId); 11237 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11238 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11239 } 11240 11241 long callingId = Binder.clearCallingIdentity(); 11242 try { 11243 boolean installed = false; 11244 11245 // writer 11246 synchronized (mPackages) { 11247 pkgSetting = mSettings.mPackages.get(packageName); 11248 if (pkgSetting == null) { 11249 return PackageManager.INSTALL_FAILED_INVALID_URI; 11250 } 11251 if (!pkgSetting.getInstalled(userId)) { 11252 pkgSetting.setInstalled(true, userId); 11253 pkgSetting.setHidden(false, userId); 11254 mSettings.writePackageRestrictionsLPr(userId); 11255 installed = true; 11256 } 11257 } 11258 11259 if (installed) { 11260 if (pkgSetting.pkg != null) { 11261 synchronized (mInstallLock) { 11262 // We don't need to freeze for a brand new install 11263 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11264 } 11265 } 11266 sendPackageAddedForUser(packageName, pkgSetting, userId); 11267 } 11268 } finally { 11269 Binder.restoreCallingIdentity(callingId); 11270 } 11271 11272 return PackageManager.INSTALL_SUCCEEDED; 11273 } 11274 11275 boolean isUserRestricted(int userId, String restrictionKey) { 11276 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11277 if (restrictions.getBoolean(restrictionKey, false)) { 11278 Log.w(TAG, "User is restricted: " + restrictionKey); 11279 return true; 11280 } 11281 return false; 11282 } 11283 11284 @Override 11285 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11286 int userId) { 11287 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11288 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11289 true /* requireFullPermission */, true /* checkShell */, 11290 "setPackagesSuspended for user " + userId); 11291 11292 if (ArrayUtils.isEmpty(packageNames)) { 11293 return packageNames; 11294 } 11295 11296 // List of package names for whom the suspended state has changed. 11297 List<String> changedPackages = new ArrayList<>(packageNames.length); 11298 // List of package names for whom the suspended state is not set as requested in this 11299 // method. 11300 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11301 for (int i = 0; i < packageNames.length; i++) { 11302 String packageName = packageNames[i]; 11303 long callingId = Binder.clearCallingIdentity(); 11304 try { 11305 boolean changed = false; 11306 final int appId; 11307 synchronized (mPackages) { 11308 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11309 if (pkgSetting == null) { 11310 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11311 + "\". Skipping suspending/un-suspending."); 11312 unactionedPackages.add(packageName); 11313 continue; 11314 } 11315 appId = pkgSetting.appId; 11316 if (pkgSetting.getSuspended(userId) != suspended) { 11317 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11318 unactionedPackages.add(packageName); 11319 continue; 11320 } 11321 pkgSetting.setSuspended(suspended, userId); 11322 mSettings.writePackageRestrictionsLPr(userId); 11323 changed = true; 11324 changedPackages.add(packageName); 11325 } 11326 } 11327 11328 if (changed && suspended) { 11329 killApplication(packageName, UserHandle.getUid(userId, appId), 11330 "suspending package"); 11331 } 11332 } finally { 11333 Binder.restoreCallingIdentity(callingId); 11334 } 11335 } 11336 11337 if (!changedPackages.isEmpty()) { 11338 sendPackagesSuspendedForUser(changedPackages.toArray( 11339 new String[changedPackages.size()]), userId, suspended); 11340 } 11341 11342 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11343 } 11344 11345 @Override 11346 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11347 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11348 true /* requireFullPermission */, false /* checkShell */, 11349 "isPackageSuspendedForUser for user " + userId); 11350 synchronized (mPackages) { 11351 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11352 if (pkgSetting == null) { 11353 throw new IllegalArgumentException("Unknown target package: " + packageName); 11354 } 11355 return pkgSetting.getSuspended(userId); 11356 } 11357 } 11358 11359 /** 11360 * TODO: cache and disallow blocking the active dialer. 11361 * 11362 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11363 */ 11364 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11365 if (isPackageDeviceAdmin(packageName, userId)) { 11366 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11367 + "\": has an active device admin"); 11368 return false; 11369 } 11370 11371 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11372 if (packageName.equals(activeLauncherPackageName)) { 11373 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11374 + "\": contains the active launcher"); 11375 return false; 11376 } 11377 11378 if (packageName.equals(mRequiredInstallerPackage)) { 11379 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11380 + "\": required for package installation"); 11381 return false; 11382 } 11383 11384 if (packageName.equals(mRequiredVerifierPackage)) { 11385 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11386 + "\": required for package verification"); 11387 return false; 11388 } 11389 11390 final PackageParser.Package pkg = mPackages.get(packageName); 11391 if (pkg != null && isPrivilegedApp(pkg)) { 11392 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11393 + "\": is a privileged app"); 11394 return false; 11395 } 11396 11397 return true; 11398 } 11399 11400 private String getActiveLauncherPackageName(int userId) { 11401 Intent intent = new Intent(Intent.ACTION_MAIN); 11402 intent.addCategory(Intent.CATEGORY_HOME); 11403 ResolveInfo resolveInfo = resolveIntent( 11404 intent, 11405 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11406 PackageManager.MATCH_DEFAULT_ONLY, 11407 userId); 11408 11409 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11410 } 11411 11412 @Override 11413 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11414 mContext.enforceCallingOrSelfPermission( 11415 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11416 "Only package verification agents can verify applications"); 11417 11418 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11419 final PackageVerificationResponse response = new PackageVerificationResponse( 11420 verificationCode, Binder.getCallingUid()); 11421 msg.arg1 = id; 11422 msg.obj = response; 11423 mHandler.sendMessage(msg); 11424 } 11425 11426 @Override 11427 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11428 long millisecondsToDelay) { 11429 mContext.enforceCallingOrSelfPermission( 11430 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11431 "Only package verification agents can extend verification timeouts"); 11432 11433 final PackageVerificationState state = mPendingVerification.get(id); 11434 final PackageVerificationResponse response = new PackageVerificationResponse( 11435 verificationCodeAtTimeout, Binder.getCallingUid()); 11436 11437 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11438 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11439 } 11440 if (millisecondsToDelay < 0) { 11441 millisecondsToDelay = 0; 11442 } 11443 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11444 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11445 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11446 } 11447 11448 if ((state != null) && !state.timeoutExtended()) { 11449 state.extendTimeout(); 11450 11451 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11452 msg.arg1 = id; 11453 msg.obj = response; 11454 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11455 } 11456 } 11457 11458 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11459 int verificationCode, UserHandle user) { 11460 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11461 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11462 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11463 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11464 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11465 11466 mContext.sendBroadcastAsUser(intent, user, 11467 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11468 } 11469 11470 private ComponentName matchComponentForVerifier(String packageName, 11471 List<ResolveInfo> receivers) { 11472 ActivityInfo targetReceiver = null; 11473 11474 final int NR = receivers.size(); 11475 for (int i = 0; i < NR; i++) { 11476 final ResolveInfo info = receivers.get(i); 11477 if (info.activityInfo == null) { 11478 continue; 11479 } 11480 11481 if (packageName.equals(info.activityInfo.packageName)) { 11482 targetReceiver = info.activityInfo; 11483 break; 11484 } 11485 } 11486 11487 if (targetReceiver == null) { 11488 return null; 11489 } 11490 11491 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11492 } 11493 11494 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11495 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11496 if (pkgInfo.verifiers.length == 0) { 11497 return null; 11498 } 11499 11500 final int N = pkgInfo.verifiers.length; 11501 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11502 for (int i = 0; i < N; i++) { 11503 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11504 11505 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11506 receivers); 11507 if (comp == null) { 11508 continue; 11509 } 11510 11511 final int verifierUid = getUidForVerifier(verifierInfo); 11512 if (verifierUid == -1) { 11513 continue; 11514 } 11515 11516 if (DEBUG_VERIFY) { 11517 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11518 + " with the correct signature"); 11519 } 11520 sufficientVerifiers.add(comp); 11521 verificationState.addSufficientVerifier(verifierUid); 11522 } 11523 11524 return sufficientVerifiers; 11525 } 11526 11527 private int getUidForVerifier(VerifierInfo verifierInfo) { 11528 synchronized (mPackages) { 11529 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11530 if (pkg == null) { 11531 return -1; 11532 } else if (pkg.mSignatures.length != 1) { 11533 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11534 + " has more than one signature; ignoring"); 11535 return -1; 11536 } 11537 11538 /* 11539 * If the public key of the package's signature does not match 11540 * our expected public key, then this is a different package and 11541 * we should skip. 11542 */ 11543 11544 final byte[] expectedPublicKey; 11545 try { 11546 final Signature verifierSig = pkg.mSignatures[0]; 11547 final PublicKey publicKey = verifierSig.getPublicKey(); 11548 expectedPublicKey = publicKey.getEncoded(); 11549 } catch (CertificateException e) { 11550 return -1; 11551 } 11552 11553 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11554 11555 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11556 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11557 + " does not have the expected public key; ignoring"); 11558 return -1; 11559 } 11560 11561 return pkg.applicationInfo.uid; 11562 } 11563 } 11564 11565 @Override 11566 public void finishPackageInstall(int token) { 11567 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11568 11569 if (DEBUG_INSTALL) { 11570 Slog.v(TAG, "BM finishing package install for " + token); 11571 } 11572 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11573 11574 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11575 mHandler.sendMessage(msg); 11576 } 11577 11578 /** 11579 * Get the verification agent timeout. 11580 * 11581 * @return verification timeout in milliseconds 11582 */ 11583 private long getVerificationTimeout() { 11584 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11585 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11586 DEFAULT_VERIFICATION_TIMEOUT); 11587 } 11588 11589 /** 11590 * Get the default verification agent response code. 11591 * 11592 * @return default verification response code 11593 */ 11594 private int getDefaultVerificationResponse() { 11595 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11596 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11597 DEFAULT_VERIFICATION_RESPONSE); 11598 } 11599 11600 /** 11601 * Check whether or not package verification has been enabled. 11602 * 11603 * @return true if verification should be performed 11604 */ 11605 private boolean isVerificationEnabled(int userId, int installFlags) { 11606 if (!DEFAULT_VERIFY_ENABLE) { 11607 return false; 11608 } 11609 // Ephemeral apps don't get the full verification treatment 11610 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11611 if (DEBUG_EPHEMERAL) { 11612 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11613 } 11614 return false; 11615 } 11616 11617 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11618 11619 // Check if installing from ADB 11620 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11621 // Do not run verification in a test harness environment 11622 if (ActivityManager.isRunningInTestHarness()) { 11623 return false; 11624 } 11625 if (ensureVerifyAppsEnabled) { 11626 return true; 11627 } 11628 // Check if the developer does not want package verification for ADB installs 11629 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11630 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11631 return false; 11632 } 11633 } 11634 11635 if (ensureVerifyAppsEnabled) { 11636 return true; 11637 } 11638 11639 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11640 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11641 } 11642 11643 @Override 11644 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11645 throws RemoteException { 11646 mContext.enforceCallingOrSelfPermission( 11647 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11648 "Only intentfilter verification agents can verify applications"); 11649 11650 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11651 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11652 Binder.getCallingUid(), verificationCode, failedDomains); 11653 msg.arg1 = id; 11654 msg.obj = response; 11655 mHandler.sendMessage(msg); 11656 } 11657 11658 @Override 11659 public int getIntentVerificationStatus(String packageName, int userId) { 11660 synchronized (mPackages) { 11661 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11662 } 11663 } 11664 11665 @Override 11666 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11667 mContext.enforceCallingOrSelfPermission( 11668 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11669 11670 boolean result = false; 11671 synchronized (mPackages) { 11672 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11673 } 11674 if (result) { 11675 scheduleWritePackageRestrictionsLocked(userId); 11676 } 11677 return result; 11678 } 11679 11680 @Override 11681 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11682 String packageName) { 11683 synchronized (mPackages) { 11684 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11685 } 11686 } 11687 11688 @Override 11689 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11690 if (TextUtils.isEmpty(packageName)) { 11691 return ParceledListSlice.emptyList(); 11692 } 11693 synchronized (mPackages) { 11694 PackageParser.Package pkg = mPackages.get(packageName); 11695 if (pkg == null || pkg.activities == null) { 11696 return ParceledListSlice.emptyList(); 11697 } 11698 final int count = pkg.activities.size(); 11699 ArrayList<IntentFilter> result = new ArrayList<>(); 11700 for (int n=0; n<count; n++) { 11701 PackageParser.Activity activity = pkg.activities.get(n); 11702 if (activity.intents != null && activity.intents.size() > 0) { 11703 result.addAll(activity.intents); 11704 } 11705 } 11706 return new ParceledListSlice<>(result); 11707 } 11708 } 11709 11710 @Override 11711 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11712 mContext.enforceCallingOrSelfPermission( 11713 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11714 11715 synchronized (mPackages) { 11716 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11717 if (packageName != null) { 11718 result |= updateIntentVerificationStatus(packageName, 11719 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11720 userId); 11721 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11722 packageName, userId); 11723 } 11724 return result; 11725 } 11726 } 11727 11728 @Override 11729 public String getDefaultBrowserPackageName(int userId) { 11730 synchronized (mPackages) { 11731 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11732 } 11733 } 11734 11735 /** 11736 * Get the "allow unknown sources" setting. 11737 * 11738 * @return the current "allow unknown sources" setting 11739 */ 11740 private int getUnknownSourcesSettings() { 11741 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11742 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11743 -1); 11744 } 11745 11746 @Override 11747 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11748 final int uid = Binder.getCallingUid(); 11749 // writer 11750 synchronized (mPackages) { 11751 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11752 if (targetPackageSetting == null) { 11753 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11754 } 11755 11756 PackageSetting installerPackageSetting; 11757 if (installerPackageName != null) { 11758 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11759 if (installerPackageSetting == null) { 11760 throw new IllegalArgumentException("Unknown installer package: " 11761 + installerPackageName); 11762 } 11763 } else { 11764 installerPackageSetting = null; 11765 } 11766 11767 Signature[] callerSignature; 11768 Object obj = mSettings.getUserIdLPr(uid); 11769 if (obj != null) { 11770 if (obj instanceof SharedUserSetting) { 11771 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11772 } else if (obj instanceof PackageSetting) { 11773 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11774 } else { 11775 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11776 } 11777 } else { 11778 throw new SecurityException("Unknown calling UID: " + uid); 11779 } 11780 11781 // Verify: can't set installerPackageName to a package that is 11782 // not signed with the same cert as the caller. 11783 if (installerPackageSetting != null) { 11784 if (compareSignatures(callerSignature, 11785 installerPackageSetting.signatures.mSignatures) 11786 != PackageManager.SIGNATURE_MATCH) { 11787 throw new SecurityException( 11788 "Caller does not have same cert as new installer package " 11789 + installerPackageName); 11790 } 11791 } 11792 11793 // Verify: if target already has an installer package, it must 11794 // be signed with the same cert as the caller. 11795 if (targetPackageSetting.installerPackageName != null) { 11796 PackageSetting setting = mSettings.mPackages.get( 11797 targetPackageSetting.installerPackageName); 11798 // If the currently set package isn't valid, then it's always 11799 // okay to change it. 11800 if (setting != null) { 11801 if (compareSignatures(callerSignature, 11802 setting.signatures.mSignatures) 11803 != PackageManager.SIGNATURE_MATCH) { 11804 throw new SecurityException( 11805 "Caller does not have same cert as old installer package " 11806 + targetPackageSetting.installerPackageName); 11807 } 11808 } 11809 } 11810 11811 // Okay! 11812 targetPackageSetting.installerPackageName = installerPackageName; 11813 if (installerPackageName != null) { 11814 mSettings.mInstallerPackages.add(installerPackageName); 11815 } 11816 scheduleWriteSettingsLocked(); 11817 } 11818 } 11819 11820 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11821 // Queue up an async operation since the package installation may take a little while. 11822 mHandler.post(new Runnable() { 11823 public void run() { 11824 mHandler.removeCallbacks(this); 11825 // Result object to be returned 11826 PackageInstalledInfo res = new PackageInstalledInfo(); 11827 res.setReturnCode(currentStatus); 11828 res.uid = -1; 11829 res.pkg = null; 11830 res.removedInfo = null; 11831 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11832 args.doPreInstall(res.returnCode); 11833 synchronized (mInstallLock) { 11834 installPackageTracedLI(args, res); 11835 } 11836 args.doPostInstall(res.returnCode, res.uid); 11837 } 11838 11839 // A restore should be performed at this point if (a) the install 11840 // succeeded, (b) the operation is not an update, and (c) the new 11841 // package has not opted out of backup participation. 11842 final boolean update = res.removedInfo != null 11843 && res.removedInfo.removedPackage != null; 11844 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11845 boolean doRestore = !update 11846 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11847 11848 // Set up the post-install work request bookkeeping. This will be used 11849 // and cleaned up by the post-install event handling regardless of whether 11850 // there's a restore pass performed. Token values are >= 1. 11851 int token; 11852 if (mNextInstallToken < 0) mNextInstallToken = 1; 11853 token = mNextInstallToken++; 11854 11855 PostInstallData data = new PostInstallData(args, res); 11856 mRunningInstalls.put(token, data); 11857 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11858 11859 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11860 // Pass responsibility to the Backup Manager. It will perform a 11861 // restore if appropriate, then pass responsibility back to the 11862 // Package Manager to run the post-install observer callbacks 11863 // and broadcasts. 11864 IBackupManager bm = IBackupManager.Stub.asInterface( 11865 ServiceManager.getService(Context.BACKUP_SERVICE)); 11866 if (bm != null) { 11867 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11868 + " to BM for possible restore"); 11869 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11870 try { 11871 // TODO: http://b/22388012 11872 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11873 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11874 } else { 11875 doRestore = false; 11876 } 11877 } catch (RemoteException e) { 11878 // can't happen; the backup manager is local 11879 } catch (Exception e) { 11880 Slog.e(TAG, "Exception trying to enqueue restore", e); 11881 doRestore = false; 11882 } 11883 } else { 11884 Slog.e(TAG, "Backup Manager not found!"); 11885 doRestore = false; 11886 } 11887 } 11888 11889 if (!doRestore) { 11890 // No restore possible, or the Backup Manager was mysteriously not 11891 // available -- just fire the post-install work request directly. 11892 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11893 11894 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11895 11896 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11897 mHandler.sendMessage(msg); 11898 } 11899 } 11900 }); 11901 } 11902 11903 private abstract class HandlerParams { 11904 private static final int MAX_RETRIES = 4; 11905 11906 /** 11907 * Number of times startCopy() has been attempted and had a non-fatal 11908 * error. 11909 */ 11910 private int mRetries = 0; 11911 11912 /** User handle for the user requesting the information or installation. */ 11913 private final UserHandle mUser; 11914 String traceMethod; 11915 int traceCookie; 11916 11917 HandlerParams(UserHandle user) { 11918 mUser = user; 11919 } 11920 11921 UserHandle getUser() { 11922 return mUser; 11923 } 11924 11925 HandlerParams setTraceMethod(String traceMethod) { 11926 this.traceMethod = traceMethod; 11927 return this; 11928 } 11929 11930 HandlerParams setTraceCookie(int traceCookie) { 11931 this.traceCookie = traceCookie; 11932 return this; 11933 } 11934 11935 final boolean startCopy() { 11936 boolean res; 11937 try { 11938 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11939 11940 if (++mRetries > MAX_RETRIES) { 11941 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11942 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11943 handleServiceError(); 11944 return false; 11945 } else { 11946 handleStartCopy(); 11947 res = true; 11948 } 11949 } catch (RemoteException e) { 11950 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11951 mHandler.sendEmptyMessage(MCS_RECONNECT); 11952 res = false; 11953 } 11954 handleReturnCode(); 11955 return res; 11956 } 11957 11958 final void serviceError() { 11959 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11960 handleServiceError(); 11961 handleReturnCode(); 11962 } 11963 11964 abstract void handleStartCopy() throws RemoteException; 11965 abstract void handleServiceError(); 11966 abstract void handleReturnCode(); 11967 } 11968 11969 class MeasureParams extends HandlerParams { 11970 private final PackageStats mStats; 11971 private boolean mSuccess; 11972 11973 private final IPackageStatsObserver mObserver; 11974 11975 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11976 super(new UserHandle(stats.userHandle)); 11977 mObserver = observer; 11978 mStats = stats; 11979 } 11980 11981 @Override 11982 public String toString() { 11983 return "MeasureParams{" 11984 + Integer.toHexString(System.identityHashCode(this)) 11985 + " " + mStats.packageName + "}"; 11986 } 11987 11988 @Override 11989 void handleStartCopy() throws RemoteException { 11990 synchronized (mInstallLock) { 11991 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11992 } 11993 11994 if (mSuccess) { 11995 final boolean mounted; 11996 if (Environment.isExternalStorageEmulated()) { 11997 mounted = true; 11998 } else { 11999 final String status = Environment.getExternalStorageState(); 12000 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12001 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12002 } 12003 12004 if (mounted) { 12005 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12006 12007 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12008 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12009 12010 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12011 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12012 12013 // Always subtract cache size, since it's a subdirectory 12014 mStats.externalDataSize -= mStats.externalCacheSize; 12015 12016 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12017 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12018 12019 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12020 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12021 } 12022 } 12023 } 12024 12025 @Override 12026 void handleReturnCode() { 12027 if (mObserver != null) { 12028 try { 12029 mObserver.onGetStatsCompleted(mStats, mSuccess); 12030 } catch (RemoteException e) { 12031 Slog.i(TAG, "Observer no longer exists."); 12032 } 12033 } 12034 } 12035 12036 @Override 12037 void handleServiceError() { 12038 Slog.e(TAG, "Could not measure application " + mStats.packageName 12039 + " external storage"); 12040 } 12041 } 12042 12043 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12044 throws RemoteException { 12045 long result = 0; 12046 for (File path : paths) { 12047 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12048 } 12049 return result; 12050 } 12051 12052 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12053 for (File path : paths) { 12054 try { 12055 mcs.clearDirectory(path.getAbsolutePath()); 12056 } catch (RemoteException e) { 12057 } 12058 } 12059 } 12060 12061 static class OriginInfo { 12062 /** 12063 * Location where install is coming from, before it has been 12064 * copied/renamed into place. This could be a single monolithic APK 12065 * file, or a cluster directory. This location may be untrusted. 12066 */ 12067 final File file; 12068 final String cid; 12069 12070 /** 12071 * Flag indicating that {@link #file} or {@link #cid} has already been 12072 * staged, meaning downstream users don't need to defensively copy the 12073 * contents. 12074 */ 12075 final boolean staged; 12076 12077 /** 12078 * Flag indicating that {@link #file} or {@link #cid} is an already 12079 * installed app that is being moved. 12080 */ 12081 final boolean existing; 12082 12083 final String resolvedPath; 12084 final File resolvedFile; 12085 12086 static OriginInfo fromNothing() { 12087 return new OriginInfo(null, null, false, false); 12088 } 12089 12090 static OriginInfo fromUntrustedFile(File file) { 12091 return new OriginInfo(file, null, false, false); 12092 } 12093 12094 static OriginInfo fromExistingFile(File file) { 12095 return new OriginInfo(file, null, false, true); 12096 } 12097 12098 static OriginInfo fromStagedFile(File file) { 12099 return new OriginInfo(file, null, true, false); 12100 } 12101 12102 static OriginInfo fromStagedContainer(String cid) { 12103 return new OriginInfo(null, cid, true, false); 12104 } 12105 12106 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12107 this.file = file; 12108 this.cid = cid; 12109 this.staged = staged; 12110 this.existing = existing; 12111 12112 if (cid != null) { 12113 resolvedPath = PackageHelper.getSdDir(cid); 12114 resolvedFile = new File(resolvedPath); 12115 } else if (file != null) { 12116 resolvedPath = file.getAbsolutePath(); 12117 resolvedFile = file; 12118 } else { 12119 resolvedPath = null; 12120 resolvedFile = null; 12121 } 12122 } 12123 } 12124 12125 static class MoveInfo { 12126 final int moveId; 12127 final String fromUuid; 12128 final String toUuid; 12129 final String packageName; 12130 final String dataAppName; 12131 final int appId; 12132 final String seinfo; 12133 final int targetSdkVersion; 12134 12135 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12136 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12137 this.moveId = moveId; 12138 this.fromUuid = fromUuid; 12139 this.toUuid = toUuid; 12140 this.packageName = packageName; 12141 this.dataAppName = dataAppName; 12142 this.appId = appId; 12143 this.seinfo = seinfo; 12144 this.targetSdkVersion = targetSdkVersion; 12145 } 12146 } 12147 12148 static class VerificationInfo { 12149 /** A constant used to indicate that a uid value is not present. */ 12150 public static final int NO_UID = -1; 12151 12152 /** URI referencing where the package was downloaded from. */ 12153 final Uri originatingUri; 12154 12155 /** HTTP referrer URI associated with the originatingURI. */ 12156 final Uri referrer; 12157 12158 /** UID of the application that the install request originated from. */ 12159 final int originatingUid; 12160 12161 /** UID of application requesting the install */ 12162 final int installerUid; 12163 12164 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12165 this.originatingUri = originatingUri; 12166 this.referrer = referrer; 12167 this.originatingUid = originatingUid; 12168 this.installerUid = installerUid; 12169 } 12170 } 12171 12172 class InstallParams extends HandlerParams { 12173 final OriginInfo origin; 12174 final MoveInfo move; 12175 final IPackageInstallObserver2 observer; 12176 int installFlags; 12177 final String installerPackageName; 12178 final String volumeUuid; 12179 private InstallArgs mArgs; 12180 private int mRet; 12181 final String packageAbiOverride; 12182 final String[] grantedRuntimePermissions; 12183 final VerificationInfo verificationInfo; 12184 final Certificate[][] certificates; 12185 12186 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12187 int installFlags, String installerPackageName, String volumeUuid, 12188 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12189 String[] grantedPermissions, Certificate[][] certificates) { 12190 super(user); 12191 this.origin = origin; 12192 this.move = move; 12193 this.observer = observer; 12194 this.installFlags = installFlags; 12195 this.installerPackageName = installerPackageName; 12196 this.volumeUuid = volumeUuid; 12197 this.verificationInfo = verificationInfo; 12198 this.packageAbiOverride = packageAbiOverride; 12199 this.grantedRuntimePermissions = grantedPermissions; 12200 this.certificates = certificates; 12201 } 12202 12203 @Override 12204 public String toString() { 12205 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12206 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12207 } 12208 12209 private int installLocationPolicy(PackageInfoLite pkgLite) { 12210 String packageName = pkgLite.packageName; 12211 int installLocation = pkgLite.installLocation; 12212 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12213 // reader 12214 synchronized (mPackages) { 12215 // Currently installed package which the new package is attempting to replace or 12216 // null if no such package is installed. 12217 PackageParser.Package installedPkg = mPackages.get(packageName); 12218 // Package which currently owns the data which the new package will own if installed. 12219 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12220 // will be null whereas dataOwnerPkg will contain information about the package 12221 // which was uninstalled while keeping its data. 12222 PackageParser.Package dataOwnerPkg = installedPkg; 12223 if (dataOwnerPkg == null) { 12224 PackageSetting ps = mSettings.mPackages.get(packageName); 12225 if (ps != null) { 12226 dataOwnerPkg = ps.pkg; 12227 } 12228 } 12229 12230 if (dataOwnerPkg != null) { 12231 // If installed, the package will get access to data left on the device by its 12232 // predecessor. As a security measure, this is permited only if this is not a 12233 // version downgrade or if the predecessor package is marked as debuggable and 12234 // a downgrade is explicitly requested. 12235 // 12236 // On debuggable platform builds, downgrades are permitted even for 12237 // non-debuggable packages to make testing easier. Debuggable platform builds do 12238 // not offer security guarantees and thus it's OK to disable some security 12239 // mechanisms to make debugging/testing easier on those builds. However, even on 12240 // debuggable builds downgrades of packages are permitted only if requested via 12241 // installFlags. This is because we aim to keep the behavior of debuggable 12242 // platform builds as close as possible to the behavior of non-debuggable 12243 // platform builds. 12244 final boolean downgradeRequested = 12245 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12246 final boolean packageDebuggable = 12247 (dataOwnerPkg.applicationInfo.flags 12248 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12249 final boolean downgradePermitted = 12250 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12251 if (!downgradePermitted) { 12252 try { 12253 checkDowngrade(dataOwnerPkg, pkgLite); 12254 } catch (PackageManagerException e) { 12255 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12256 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12257 } 12258 } 12259 } 12260 12261 if (installedPkg != null) { 12262 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12263 // Check for updated system application. 12264 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12265 if (onSd) { 12266 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12267 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12268 } 12269 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12270 } else { 12271 if (onSd) { 12272 // Install flag overrides everything. 12273 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12274 } 12275 // If current upgrade specifies particular preference 12276 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12277 // Application explicitly specified internal. 12278 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12279 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12280 // App explictly prefers external. Let policy decide 12281 } else { 12282 // Prefer previous location 12283 if (isExternal(installedPkg)) { 12284 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12285 } 12286 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12287 } 12288 } 12289 } else { 12290 // Invalid install. Return error code 12291 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12292 } 12293 } 12294 } 12295 // All the special cases have been taken care of. 12296 // Return result based on recommended install location. 12297 if (onSd) { 12298 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12299 } 12300 return pkgLite.recommendedInstallLocation; 12301 } 12302 12303 /* 12304 * Invoke remote method to get package information and install 12305 * location values. Override install location based on default 12306 * policy if needed and then create install arguments based 12307 * on the install location. 12308 */ 12309 public void handleStartCopy() throws RemoteException { 12310 int ret = PackageManager.INSTALL_SUCCEEDED; 12311 12312 // If we're already staged, we've firmly committed to an install location 12313 if (origin.staged) { 12314 if (origin.file != null) { 12315 installFlags |= PackageManager.INSTALL_INTERNAL; 12316 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12317 } else if (origin.cid != null) { 12318 installFlags |= PackageManager.INSTALL_EXTERNAL; 12319 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12320 } else { 12321 throw new IllegalStateException("Invalid stage location"); 12322 } 12323 } 12324 12325 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12326 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12327 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12328 PackageInfoLite pkgLite = null; 12329 12330 if (onInt && onSd) { 12331 // Check if both bits are set. 12332 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12333 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12334 } else if (onSd && ephemeral) { 12335 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12336 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12337 } else { 12338 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12339 packageAbiOverride); 12340 12341 if (DEBUG_EPHEMERAL && ephemeral) { 12342 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12343 } 12344 12345 /* 12346 * If we have too little free space, try to free cache 12347 * before giving up. 12348 */ 12349 if (!origin.staged && pkgLite.recommendedInstallLocation 12350 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12351 // TODO: focus freeing disk space on the target device 12352 final StorageManager storage = StorageManager.from(mContext); 12353 final long lowThreshold = storage.getStorageLowBytes( 12354 Environment.getDataDirectory()); 12355 12356 final long sizeBytes = mContainerService.calculateInstalledSize( 12357 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12358 12359 try { 12360 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12361 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12362 installFlags, packageAbiOverride); 12363 } catch (InstallerException e) { 12364 Slog.w(TAG, "Failed to free cache", e); 12365 } 12366 12367 /* 12368 * The cache free must have deleted the file we 12369 * downloaded to install. 12370 * 12371 * TODO: fix the "freeCache" call to not delete 12372 * the file we care about. 12373 */ 12374 if (pkgLite.recommendedInstallLocation 12375 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12376 pkgLite.recommendedInstallLocation 12377 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12378 } 12379 } 12380 } 12381 12382 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12383 int loc = pkgLite.recommendedInstallLocation; 12384 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12385 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12386 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12387 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12388 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12389 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12390 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12391 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12392 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12393 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12394 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12395 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12396 } else { 12397 // Override with defaults if needed. 12398 loc = installLocationPolicy(pkgLite); 12399 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12400 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12401 } else if (!onSd && !onInt) { 12402 // Override install location with flags 12403 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12404 // Set the flag to install on external media. 12405 installFlags |= PackageManager.INSTALL_EXTERNAL; 12406 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12407 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12408 if (DEBUG_EPHEMERAL) { 12409 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12410 } 12411 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12412 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12413 |PackageManager.INSTALL_INTERNAL); 12414 } else { 12415 // Make sure the flag for installing on external 12416 // media is unset 12417 installFlags |= PackageManager.INSTALL_INTERNAL; 12418 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12419 } 12420 } 12421 } 12422 } 12423 12424 final InstallArgs args = createInstallArgs(this); 12425 mArgs = args; 12426 12427 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12428 // TODO: http://b/22976637 12429 // Apps installed for "all" users use the device owner to verify the app 12430 UserHandle verifierUser = getUser(); 12431 if (verifierUser == UserHandle.ALL) { 12432 verifierUser = UserHandle.SYSTEM; 12433 } 12434 12435 /* 12436 * Determine if we have any installed package verifiers. If we 12437 * do, then we'll defer to them to verify the packages. 12438 */ 12439 final int requiredUid = mRequiredVerifierPackage == null ? -1 12440 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12441 verifierUser.getIdentifier()); 12442 if (!origin.existing && requiredUid != -1 12443 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12444 final Intent verification = new Intent( 12445 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12446 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12447 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12448 PACKAGE_MIME_TYPE); 12449 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12450 12451 // Query all live verifiers based on current user state 12452 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12453 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12454 12455 if (DEBUG_VERIFY) { 12456 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12457 + verification.toString() + " with " + pkgLite.verifiers.length 12458 + " optional verifiers"); 12459 } 12460 12461 final int verificationId = mPendingVerificationToken++; 12462 12463 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12464 12465 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12466 installerPackageName); 12467 12468 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12469 installFlags); 12470 12471 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12472 pkgLite.packageName); 12473 12474 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12475 pkgLite.versionCode); 12476 12477 if (verificationInfo != null) { 12478 if (verificationInfo.originatingUri != null) { 12479 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12480 verificationInfo.originatingUri); 12481 } 12482 if (verificationInfo.referrer != null) { 12483 verification.putExtra(Intent.EXTRA_REFERRER, 12484 verificationInfo.referrer); 12485 } 12486 if (verificationInfo.originatingUid >= 0) { 12487 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12488 verificationInfo.originatingUid); 12489 } 12490 if (verificationInfo.installerUid >= 0) { 12491 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12492 verificationInfo.installerUid); 12493 } 12494 } 12495 12496 final PackageVerificationState verificationState = new PackageVerificationState( 12497 requiredUid, args); 12498 12499 mPendingVerification.append(verificationId, verificationState); 12500 12501 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12502 receivers, verificationState); 12503 12504 /* 12505 * If any sufficient verifiers were listed in the package 12506 * manifest, attempt to ask them. 12507 */ 12508 if (sufficientVerifiers != null) { 12509 final int N = sufficientVerifiers.size(); 12510 if (N == 0) { 12511 Slog.i(TAG, "Additional verifiers required, but none installed."); 12512 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12513 } else { 12514 for (int i = 0; i < N; i++) { 12515 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12516 12517 final Intent sufficientIntent = new Intent(verification); 12518 sufficientIntent.setComponent(verifierComponent); 12519 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12520 } 12521 } 12522 } 12523 12524 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12525 mRequiredVerifierPackage, receivers); 12526 if (ret == PackageManager.INSTALL_SUCCEEDED 12527 && mRequiredVerifierPackage != null) { 12528 Trace.asyncTraceBegin( 12529 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12530 /* 12531 * Send the intent to the required verification agent, 12532 * but only start the verification timeout after the 12533 * target BroadcastReceivers have run. 12534 */ 12535 verification.setComponent(requiredVerifierComponent); 12536 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12537 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12538 new BroadcastReceiver() { 12539 @Override 12540 public void onReceive(Context context, Intent intent) { 12541 final Message msg = mHandler 12542 .obtainMessage(CHECK_PENDING_VERIFICATION); 12543 msg.arg1 = verificationId; 12544 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12545 } 12546 }, null, 0, null, null); 12547 12548 /* 12549 * We don't want the copy to proceed until verification 12550 * succeeds, so null out this field. 12551 */ 12552 mArgs = null; 12553 } 12554 } else { 12555 /* 12556 * No package verification is enabled, so immediately start 12557 * the remote call to initiate copy using temporary file. 12558 */ 12559 ret = args.copyApk(mContainerService, true); 12560 } 12561 } 12562 12563 mRet = ret; 12564 } 12565 12566 @Override 12567 void handleReturnCode() { 12568 // If mArgs is null, then MCS couldn't be reached. When it 12569 // reconnects, it will try again to install. At that point, this 12570 // will succeed. 12571 if (mArgs != null) { 12572 processPendingInstall(mArgs, mRet); 12573 } 12574 } 12575 12576 @Override 12577 void handleServiceError() { 12578 mArgs = createInstallArgs(this); 12579 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12580 } 12581 12582 public boolean isForwardLocked() { 12583 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12584 } 12585 } 12586 12587 /** 12588 * Used during creation of InstallArgs 12589 * 12590 * @param installFlags package installation flags 12591 * @return true if should be installed on external storage 12592 */ 12593 private static boolean installOnExternalAsec(int installFlags) { 12594 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12595 return false; 12596 } 12597 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12598 return true; 12599 } 12600 return false; 12601 } 12602 12603 /** 12604 * Used during creation of InstallArgs 12605 * 12606 * @param installFlags package installation flags 12607 * @return true if should be installed as forward locked 12608 */ 12609 private static boolean installForwardLocked(int installFlags) { 12610 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12611 } 12612 12613 private InstallArgs createInstallArgs(InstallParams params) { 12614 if (params.move != null) { 12615 return new MoveInstallArgs(params); 12616 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12617 return new AsecInstallArgs(params); 12618 } else { 12619 return new FileInstallArgs(params); 12620 } 12621 } 12622 12623 /** 12624 * Create args that describe an existing installed package. Typically used 12625 * when cleaning up old installs, or used as a move source. 12626 */ 12627 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12628 String resourcePath, String[] instructionSets) { 12629 final boolean isInAsec; 12630 if (installOnExternalAsec(installFlags)) { 12631 /* Apps on SD card are always in ASEC containers. */ 12632 isInAsec = true; 12633 } else if (installForwardLocked(installFlags) 12634 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12635 /* 12636 * Forward-locked apps are only in ASEC containers if they're the 12637 * new style 12638 */ 12639 isInAsec = true; 12640 } else { 12641 isInAsec = false; 12642 } 12643 12644 if (isInAsec) { 12645 return new AsecInstallArgs(codePath, instructionSets, 12646 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12647 } else { 12648 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12649 } 12650 } 12651 12652 static abstract class InstallArgs { 12653 /** @see InstallParams#origin */ 12654 final OriginInfo origin; 12655 /** @see InstallParams#move */ 12656 final MoveInfo move; 12657 12658 final IPackageInstallObserver2 observer; 12659 // Always refers to PackageManager flags only 12660 final int installFlags; 12661 final String installerPackageName; 12662 final String volumeUuid; 12663 final UserHandle user; 12664 final String abiOverride; 12665 final String[] installGrantPermissions; 12666 /** If non-null, drop an async trace when the install completes */ 12667 final String traceMethod; 12668 final int traceCookie; 12669 final Certificate[][] certificates; 12670 12671 // The list of instruction sets supported by this app. This is currently 12672 // only used during the rmdex() phase to clean up resources. We can get rid of this 12673 // if we move dex files under the common app path. 12674 /* nullable */ String[] instructionSets; 12675 12676 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12677 int installFlags, String installerPackageName, String volumeUuid, 12678 UserHandle user, String[] instructionSets, 12679 String abiOverride, String[] installGrantPermissions, 12680 String traceMethod, int traceCookie, Certificate[][] certificates) { 12681 this.origin = origin; 12682 this.move = move; 12683 this.installFlags = installFlags; 12684 this.observer = observer; 12685 this.installerPackageName = installerPackageName; 12686 this.volumeUuid = volumeUuid; 12687 this.user = user; 12688 this.instructionSets = instructionSets; 12689 this.abiOverride = abiOverride; 12690 this.installGrantPermissions = installGrantPermissions; 12691 this.traceMethod = traceMethod; 12692 this.traceCookie = traceCookie; 12693 this.certificates = certificates; 12694 } 12695 12696 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12697 abstract int doPreInstall(int status); 12698 12699 /** 12700 * Rename package into final resting place. All paths on the given 12701 * scanned package should be updated to reflect the rename. 12702 */ 12703 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12704 abstract int doPostInstall(int status, int uid); 12705 12706 /** @see PackageSettingBase#codePathString */ 12707 abstract String getCodePath(); 12708 /** @see PackageSettingBase#resourcePathString */ 12709 abstract String getResourcePath(); 12710 12711 // Need installer lock especially for dex file removal. 12712 abstract void cleanUpResourcesLI(); 12713 abstract boolean doPostDeleteLI(boolean delete); 12714 12715 /** 12716 * Called before the source arguments are copied. This is used mostly 12717 * for MoveParams when it needs to read the source file to put it in the 12718 * destination. 12719 */ 12720 int doPreCopy() { 12721 return PackageManager.INSTALL_SUCCEEDED; 12722 } 12723 12724 /** 12725 * Called after the source arguments are copied. This is used mostly for 12726 * MoveParams when it needs to read the source file to put it in the 12727 * destination. 12728 */ 12729 int doPostCopy(int uid) { 12730 return PackageManager.INSTALL_SUCCEEDED; 12731 } 12732 12733 protected boolean isFwdLocked() { 12734 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12735 } 12736 12737 protected boolean isExternalAsec() { 12738 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12739 } 12740 12741 protected boolean isEphemeral() { 12742 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12743 } 12744 12745 UserHandle getUser() { 12746 return user; 12747 } 12748 } 12749 12750 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12751 if (!allCodePaths.isEmpty()) { 12752 if (instructionSets == null) { 12753 throw new IllegalStateException("instructionSet == null"); 12754 } 12755 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12756 for (String codePath : allCodePaths) { 12757 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12758 try { 12759 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12760 } catch (InstallerException ignored) { 12761 } 12762 } 12763 } 12764 } 12765 } 12766 12767 /** 12768 * Logic to handle installation of non-ASEC applications, including copying 12769 * and renaming logic. 12770 */ 12771 class FileInstallArgs extends InstallArgs { 12772 private File codeFile; 12773 private File resourceFile; 12774 12775 // Example topology: 12776 // /data/app/com.example/base.apk 12777 // /data/app/com.example/split_foo.apk 12778 // /data/app/com.example/lib/arm/libfoo.so 12779 // /data/app/com.example/lib/arm64/libfoo.so 12780 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12781 12782 /** New install */ 12783 FileInstallArgs(InstallParams params) { 12784 super(params.origin, params.move, params.observer, params.installFlags, 12785 params.installerPackageName, params.volumeUuid, 12786 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12787 params.grantedRuntimePermissions, 12788 params.traceMethod, params.traceCookie, params.certificates); 12789 if (isFwdLocked()) { 12790 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12791 } 12792 } 12793 12794 /** Existing install */ 12795 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12796 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12797 null, null, null, 0, null /*certificates*/); 12798 this.codeFile = (codePath != null) ? new File(codePath) : null; 12799 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12800 } 12801 12802 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12803 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12804 try { 12805 return doCopyApk(imcs, temp); 12806 } finally { 12807 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12808 } 12809 } 12810 12811 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12812 if (origin.staged) { 12813 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12814 codeFile = origin.file; 12815 resourceFile = origin.file; 12816 return PackageManager.INSTALL_SUCCEEDED; 12817 } 12818 12819 try { 12820 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12821 final File tempDir = 12822 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12823 codeFile = tempDir; 12824 resourceFile = tempDir; 12825 } catch (IOException e) { 12826 Slog.w(TAG, "Failed to create copy file: " + e); 12827 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12828 } 12829 12830 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12831 @Override 12832 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12833 if (!FileUtils.isValidExtFilename(name)) { 12834 throw new IllegalArgumentException("Invalid filename: " + name); 12835 } 12836 try { 12837 final File file = new File(codeFile, name); 12838 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12839 O_RDWR | O_CREAT, 0644); 12840 Os.chmod(file.getAbsolutePath(), 0644); 12841 return new ParcelFileDescriptor(fd); 12842 } catch (ErrnoException e) { 12843 throw new RemoteException("Failed to open: " + e.getMessage()); 12844 } 12845 } 12846 }; 12847 12848 int ret = PackageManager.INSTALL_SUCCEEDED; 12849 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12850 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12851 Slog.e(TAG, "Failed to copy package"); 12852 return ret; 12853 } 12854 12855 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12856 NativeLibraryHelper.Handle handle = null; 12857 try { 12858 handle = NativeLibraryHelper.Handle.create(codeFile); 12859 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12860 abiOverride); 12861 } catch (IOException e) { 12862 Slog.e(TAG, "Copying native libraries failed", e); 12863 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12864 } finally { 12865 IoUtils.closeQuietly(handle); 12866 } 12867 12868 return ret; 12869 } 12870 12871 int doPreInstall(int status) { 12872 if (status != PackageManager.INSTALL_SUCCEEDED) { 12873 cleanUp(); 12874 } 12875 return status; 12876 } 12877 12878 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12879 if (status != PackageManager.INSTALL_SUCCEEDED) { 12880 cleanUp(); 12881 return false; 12882 } 12883 12884 final File targetDir = codeFile.getParentFile(); 12885 final File beforeCodeFile = codeFile; 12886 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12887 12888 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12889 try { 12890 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12891 } catch (ErrnoException e) { 12892 Slog.w(TAG, "Failed to rename", e); 12893 return false; 12894 } 12895 12896 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12897 Slog.w(TAG, "Failed to restorecon"); 12898 return false; 12899 } 12900 12901 // Reflect the rename internally 12902 codeFile = afterCodeFile; 12903 resourceFile = afterCodeFile; 12904 12905 // Reflect the rename in scanned details 12906 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12907 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12908 afterCodeFile, pkg.baseCodePath)); 12909 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12910 afterCodeFile, pkg.splitCodePaths)); 12911 12912 // Reflect the rename in app info 12913 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12914 pkg.setApplicationInfoCodePath(pkg.codePath); 12915 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12916 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12917 pkg.setApplicationInfoResourcePath(pkg.codePath); 12918 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12919 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12920 12921 return true; 12922 } 12923 12924 int doPostInstall(int status, int uid) { 12925 if (status != PackageManager.INSTALL_SUCCEEDED) { 12926 cleanUp(); 12927 } 12928 return status; 12929 } 12930 12931 @Override 12932 String getCodePath() { 12933 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12934 } 12935 12936 @Override 12937 String getResourcePath() { 12938 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12939 } 12940 12941 private boolean cleanUp() { 12942 if (codeFile == null || !codeFile.exists()) { 12943 return false; 12944 } 12945 12946 removeCodePathLI(codeFile); 12947 12948 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12949 resourceFile.delete(); 12950 } 12951 12952 return true; 12953 } 12954 12955 void cleanUpResourcesLI() { 12956 // Try enumerating all code paths before deleting 12957 List<String> allCodePaths = Collections.EMPTY_LIST; 12958 if (codeFile != null && codeFile.exists()) { 12959 try { 12960 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12961 allCodePaths = pkg.getAllCodePaths(); 12962 } catch (PackageParserException e) { 12963 // Ignored; we tried our best 12964 } 12965 } 12966 12967 cleanUp(); 12968 removeDexFiles(allCodePaths, instructionSets); 12969 } 12970 12971 boolean doPostDeleteLI(boolean delete) { 12972 // XXX err, shouldn't we respect the delete flag? 12973 cleanUpResourcesLI(); 12974 return true; 12975 } 12976 } 12977 12978 private boolean isAsecExternal(String cid) { 12979 final String asecPath = PackageHelper.getSdFilesystem(cid); 12980 return !asecPath.startsWith(mAsecInternalPath); 12981 } 12982 12983 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12984 PackageManagerException { 12985 if (copyRet < 0) { 12986 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12987 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12988 throw new PackageManagerException(copyRet, message); 12989 } 12990 } 12991 } 12992 12993 /** 12994 * Extract the MountService "container ID" from the full code path of an 12995 * .apk. 12996 */ 12997 static String cidFromCodePath(String fullCodePath) { 12998 int eidx = fullCodePath.lastIndexOf("/"); 12999 String subStr1 = fullCodePath.substring(0, eidx); 13000 int sidx = subStr1.lastIndexOf("/"); 13001 return subStr1.substring(sidx+1, eidx); 13002 } 13003 13004 /** 13005 * Logic to handle installation of ASEC applications, including copying and 13006 * renaming logic. 13007 */ 13008 class AsecInstallArgs extends InstallArgs { 13009 static final String RES_FILE_NAME = "pkg.apk"; 13010 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13011 13012 String cid; 13013 String packagePath; 13014 String resourcePath; 13015 13016 /** New install */ 13017 AsecInstallArgs(InstallParams params) { 13018 super(params.origin, params.move, params.observer, params.installFlags, 13019 params.installerPackageName, params.volumeUuid, 13020 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13021 params.grantedRuntimePermissions, 13022 params.traceMethod, params.traceCookie, params.certificates); 13023 } 13024 13025 /** Existing install */ 13026 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13027 boolean isExternal, boolean isForwardLocked) { 13028 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13029 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13030 instructionSets, null, null, null, 0, null /*certificates*/); 13031 // Hackily pretend we're still looking at a full code path 13032 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13033 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13034 } 13035 13036 // Extract cid from fullCodePath 13037 int eidx = fullCodePath.lastIndexOf("/"); 13038 String subStr1 = fullCodePath.substring(0, eidx); 13039 int sidx = subStr1.lastIndexOf("/"); 13040 cid = subStr1.substring(sidx+1, eidx); 13041 setMountPath(subStr1); 13042 } 13043 13044 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13045 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13046 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13047 instructionSets, null, null, null, 0, null /*certificates*/); 13048 this.cid = cid; 13049 setMountPath(PackageHelper.getSdDir(cid)); 13050 } 13051 13052 void createCopyFile() { 13053 cid = mInstallerService.allocateExternalStageCidLegacy(); 13054 } 13055 13056 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13057 if (origin.staged && origin.cid != null) { 13058 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13059 cid = origin.cid; 13060 setMountPath(PackageHelper.getSdDir(cid)); 13061 return PackageManager.INSTALL_SUCCEEDED; 13062 } 13063 13064 if (temp) { 13065 createCopyFile(); 13066 } else { 13067 /* 13068 * Pre-emptively destroy the container since it's destroyed if 13069 * copying fails due to it existing anyway. 13070 */ 13071 PackageHelper.destroySdDir(cid); 13072 } 13073 13074 final String newMountPath = imcs.copyPackageToContainer( 13075 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13076 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13077 13078 if (newMountPath != null) { 13079 setMountPath(newMountPath); 13080 return PackageManager.INSTALL_SUCCEEDED; 13081 } else { 13082 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13083 } 13084 } 13085 13086 @Override 13087 String getCodePath() { 13088 return packagePath; 13089 } 13090 13091 @Override 13092 String getResourcePath() { 13093 return resourcePath; 13094 } 13095 13096 int doPreInstall(int status) { 13097 if (status != PackageManager.INSTALL_SUCCEEDED) { 13098 // Destroy container 13099 PackageHelper.destroySdDir(cid); 13100 } else { 13101 boolean mounted = PackageHelper.isContainerMounted(cid); 13102 if (!mounted) { 13103 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13104 Process.SYSTEM_UID); 13105 if (newMountPath != null) { 13106 setMountPath(newMountPath); 13107 } else { 13108 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13109 } 13110 } 13111 } 13112 return status; 13113 } 13114 13115 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13116 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13117 String newMountPath = null; 13118 if (PackageHelper.isContainerMounted(cid)) { 13119 // Unmount the container 13120 if (!PackageHelper.unMountSdDir(cid)) { 13121 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13122 return false; 13123 } 13124 } 13125 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13126 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13127 " which might be stale. Will try to clean up."); 13128 // Clean up the stale container and proceed to recreate. 13129 if (!PackageHelper.destroySdDir(newCacheId)) { 13130 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13131 return false; 13132 } 13133 // Successfully cleaned up stale container. Try to rename again. 13134 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13135 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13136 + " inspite of cleaning it up."); 13137 return false; 13138 } 13139 } 13140 if (!PackageHelper.isContainerMounted(newCacheId)) { 13141 Slog.w(TAG, "Mounting container " + newCacheId); 13142 newMountPath = PackageHelper.mountSdDir(newCacheId, 13143 getEncryptKey(), Process.SYSTEM_UID); 13144 } else { 13145 newMountPath = PackageHelper.getSdDir(newCacheId); 13146 } 13147 if (newMountPath == null) { 13148 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13149 return false; 13150 } 13151 Log.i(TAG, "Succesfully renamed " + cid + 13152 " to " + newCacheId + 13153 " at new path: " + newMountPath); 13154 cid = newCacheId; 13155 13156 final File beforeCodeFile = new File(packagePath); 13157 setMountPath(newMountPath); 13158 final File afterCodeFile = new File(packagePath); 13159 13160 // Reflect the rename in scanned details 13161 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13162 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13163 afterCodeFile, pkg.baseCodePath)); 13164 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13165 afterCodeFile, pkg.splitCodePaths)); 13166 13167 // Reflect the rename in app info 13168 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13169 pkg.setApplicationInfoCodePath(pkg.codePath); 13170 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13171 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13172 pkg.setApplicationInfoResourcePath(pkg.codePath); 13173 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13174 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13175 13176 return true; 13177 } 13178 13179 private void setMountPath(String mountPath) { 13180 final File mountFile = new File(mountPath); 13181 13182 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13183 if (monolithicFile.exists()) { 13184 packagePath = monolithicFile.getAbsolutePath(); 13185 if (isFwdLocked()) { 13186 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13187 } else { 13188 resourcePath = packagePath; 13189 } 13190 } else { 13191 packagePath = mountFile.getAbsolutePath(); 13192 resourcePath = packagePath; 13193 } 13194 } 13195 13196 int doPostInstall(int status, int uid) { 13197 if (status != PackageManager.INSTALL_SUCCEEDED) { 13198 cleanUp(); 13199 } else { 13200 final int groupOwner; 13201 final String protectedFile; 13202 if (isFwdLocked()) { 13203 groupOwner = UserHandle.getSharedAppGid(uid); 13204 protectedFile = RES_FILE_NAME; 13205 } else { 13206 groupOwner = -1; 13207 protectedFile = null; 13208 } 13209 13210 if (uid < Process.FIRST_APPLICATION_UID 13211 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13212 Slog.e(TAG, "Failed to finalize " + cid); 13213 PackageHelper.destroySdDir(cid); 13214 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13215 } 13216 13217 boolean mounted = PackageHelper.isContainerMounted(cid); 13218 if (!mounted) { 13219 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13220 } 13221 } 13222 return status; 13223 } 13224 13225 private void cleanUp() { 13226 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13227 13228 // Destroy secure container 13229 PackageHelper.destroySdDir(cid); 13230 } 13231 13232 private List<String> getAllCodePaths() { 13233 final File codeFile = new File(getCodePath()); 13234 if (codeFile != null && codeFile.exists()) { 13235 try { 13236 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13237 return pkg.getAllCodePaths(); 13238 } catch (PackageParserException e) { 13239 // Ignored; we tried our best 13240 } 13241 } 13242 return Collections.EMPTY_LIST; 13243 } 13244 13245 void cleanUpResourcesLI() { 13246 // Enumerate all code paths before deleting 13247 cleanUpResourcesLI(getAllCodePaths()); 13248 } 13249 13250 private void cleanUpResourcesLI(List<String> allCodePaths) { 13251 cleanUp(); 13252 removeDexFiles(allCodePaths, instructionSets); 13253 } 13254 13255 String getPackageName() { 13256 return getAsecPackageName(cid); 13257 } 13258 13259 boolean doPostDeleteLI(boolean delete) { 13260 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13261 final List<String> allCodePaths = getAllCodePaths(); 13262 boolean mounted = PackageHelper.isContainerMounted(cid); 13263 if (mounted) { 13264 // Unmount first 13265 if (PackageHelper.unMountSdDir(cid)) { 13266 mounted = false; 13267 } 13268 } 13269 if (!mounted && delete) { 13270 cleanUpResourcesLI(allCodePaths); 13271 } 13272 return !mounted; 13273 } 13274 13275 @Override 13276 int doPreCopy() { 13277 if (isFwdLocked()) { 13278 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13279 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13280 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13281 } 13282 } 13283 13284 return PackageManager.INSTALL_SUCCEEDED; 13285 } 13286 13287 @Override 13288 int doPostCopy(int uid) { 13289 if (isFwdLocked()) { 13290 if (uid < Process.FIRST_APPLICATION_UID 13291 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13292 RES_FILE_NAME)) { 13293 Slog.e(TAG, "Failed to finalize " + cid); 13294 PackageHelper.destroySdDir(cid); 13295 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13296 } 13297 } 13298 13299 return PackageManager.INSTALL_SUCCEEDED; 13300 } 13301 } 13302 13303 /** 13304 * Logic to handle movement of existing installed applications. 13305 */ 13306 class MoveInstallArgs extends InstallArgs { 13307 private File codeFile; 13308 private File resourceFile; 13309 13310 /** New install */ 13311 MoveInstallArgs(InstallParams params) { 13312 super(params.origin, params.move, params.observer, params.installFlags, 13313 params.installerPackageName, params.volumeUuid, 13314 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13315 params.grantedRuntimePermissions, 13316 params.traceMethod, params.traceCookie, params.certificates); 13317 } 13318 13319 int copyApk(IMediaContainerService imcs, boolean temp) { 13320 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13321 + move.fromUuid + " to " + move.toUuid); 13322 synchronized (mInstaller) { 13323 try { 13324 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13325 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13326 } catch (InstallerException e) { 13327 Slog.w(TAG, "Failed to move app", e); 13328 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13329 } 13330 } 13331 13332 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13333 resourceFile = codeFile; 13334 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13335 13336 return PackageManager.INSTALL_SUCCEEDED; 13337 } 13338 13339 int doPreInstall(int status) { 13340 if (status != PackageManager.INSTALL_SUCCEEDED) { 13341 cleanUp(move.toUuid); 13342 } 13343 return status; 13344 } 13345 13346 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13347 if (status != PackageManager.INSTALL_SUCCEEDED) { 13348 cleanUp(move.toUuid); 13349 return false; 13350 } 13351 13352 // Reflect the move in app info 13353 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13354 pkg.setApplicationInfoCodePath(pkg.codePath); 13355 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13356 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13357 pkg.setApplicationInfoResourcePath(pkg.codePath); 13358 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13359 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13360 13361 return true; 13362 } 13363 13364 int doPostInstall(int status, int uid) { 13365 if (status == PackageManager.INSTALL_SUCCEEDED) { 13366 cleanUp(move.fromUuid); 13367 } else { 13368 cleanUp(move.toUuid); 13369 } 13370 return status; 13371 } 13372 13373 @Override 13374 String getCodePath() { 13375 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13376 } 13377 13378 @Override 13379 String getResourcePath() { 13380 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13381 } 13382 13383 private boolean cleanUp(String volumeUuid) { 13384 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13385 move.dataAppName); 13386 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13387 synchronized (mInstallLock) { 13388 // Clean up both app data and code 13389 // All package moves are frozen until finished 13390 try { 13391 mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL, 13392 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13393 } catch (InstallerException e) { 13394 Slog.w(TAG, String.valueOf(e)); 13395 } 13396 removeCodePathLI(codeFile); 13397 } 13398 return true; 13399 } 13400 13401 void cleanUpResourcesLI() { 13402 throw new UnsupportedOperationException(); 13403 } 13404 13405 boolean doPostDeleteLI(boolean delete) { 13406 throw new UnsupportedOperationException(); 13407 } 13408 } 13409 13410 static String getAsecPackageName(String packageCid) { 13411 int idx = packageCid.lastIndexOf("-"); 13412 if (idx == -1) { 13413 return packageCid; 13414 } 13415 return packageCid.substring(0, idx); 13416 } 13417 13418 // Utility method used to create code paths based on package name and available index. 13419 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13420 String idxStr = ""; 13421 int idx = 1; 13422 // Fall back to default value of idx=1 if prefix is not 13423 // part of oldCodePath 13424 if (oldCodePath != null) { 13425 String subStr = oldCodePath; 13426 // Drop the suffix right away 13427 if (suffix != null && subStr.endsWith(suffix)) { 13428 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13429 } 13430 // If oldCodePath already contains prefix find out the 13431 // ending index to either increment or decrement. 13432 int sidx = subStr.lastIndexOf(prefix); 13433 if (sidx != -1) { 13434 subStr = subStr.substring(sidx + prefix.length()); 13435 if (subStr != null) { 13436 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13437 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13438 } 13439 try { 13440 idx = Integer.parseInt(subStr); 13441 if (idx <= 1) { 13442 idx++; 13443 } else { 13444 idx--; 13445 } 13446 } catch(NumberFormatException e) { 13447 } 13448 } 13449 } 13450 } 13451 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13452 return prefix + idxStr; 13453 } 13454 13455 private File getNextCodePath(File targetDir, String packageName) { 13456 int suffix = 1; 13457 File result; 13458 do { 13459 result = new File(targetDir, packageName + "-" + suffix); 13460 suffix++; 13461 } while (result.exists()); 13462 return result; 13463 } 13464 13465 // Utility method that returns the relative package path with respect 13466 // to the installation directory. Like say for /data/data/com.test-1.apk 13467 // string com.test-1 is returned. 13468 static String deriveCodePathName(String codePath) { 13469 if (codePath == null) { 13470 return null; 13471 } 13472 final File codeFile = new File(codePath); 13473 final String name = codeFile.getName(); 13474 if (codeFile.isDirectory()) { 13475 return name; 13476 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13477 final int lastDot = name.lastIndexOf('.'); 13478 return name.substring(0, lastDot); 13479 } else { 13480 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13481 return null; 13482 } 13483 } 13484 13485 static class PackageInstalledInfo { 13486 String name; 13487 int uid; 13488 // The set of users that originally had this package installed. 13489 int[] origUsers; 13490 // The set of users that now have this package installed. 13491 int[] newUsers; 13492 PackageParser.Package pkg; 13493 int returnCode; 13494 String returnMsg; 13495 PackageRemovedInfo removedInfo; 13496 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13497 13498 public void setError(int code, String msg) { 13499 setReturnCode(code); 13500 setReturnMessage(msg); 13501 Slog.w(TAG, msg); 13502 } 13503 13504 public void setError(String msg, PackageParserException e) { 13505 setReturnCode(e.error); 13506 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13507 Slog.w(TAG, msg, e); 13508 } 13509 13510 public void setError(String msg, PackageManagerException e) { 13511 returnCode = e.error; 13512 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13513 Slog.w(TAG, msg, e); 13514 } 13515 13516 public void setReturnCode(int returnCode) { 13517 this.returnCode = returnCode; 13518 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13519 for (int i = 0; i < childCount; i++) { 13520 addedChildPackages.valueAt(i).returnCode = returnCode; 13521 } 13522 } 13523 13524 private void setReturnMessage(String returnMsg) { 13525 this.returnMsg = returnMsg; 13526 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13527 for (int i = 0; i < childCount; i++) { 13528 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13529 } 13530 } 13531 13532 // In some error cases we want to convey more info back to the observer 13533 String origPackage; 13534 String origPermission; 13535 } 13536 13537 /* 13538 * Install a non-existing package. 13539 */ 13540 private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13541 UserHandle user, String installerPackageName, String volumeUuid, 13542 PackageInstalledInfo res) { 13543 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13544 13545 // Remember this for later, in case we need to rollback this install 13546 String pkgName = pkg.packageName; 13547 13548 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13549 13550 synchronized(mPackages) { 13551 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13552 // A package with the same name is already installed, though 13553 // it has been renamed to an older name. The package we 13554 // are trying to install should be installed as an update to 13555 // the existing one, but that has not been requested, so bail. 13556 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13557 + " without first uninstalling package running as " 13558 + mSettings.mRenamedPackages.get(pkgName)); 13559 return; 13560 } 13561 if (mPackages.containsKey(pkgName)) { 13562 // Don't allow installation over an existing package with the same name. 13563 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13564 + " without first uninstalling."); 13565 return; 13566 } 13567 } 13568 13569 try { 13570 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13571 System.currentTimeMillis(), user); 13572 13573 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13574 13575 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13576 prepareAppDataAfterInstallLIF(newPackage); 13577 13578 } else { 13579 // Remove package from internal structures, but keep around any 13580 // data that might have already existed 13581 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13582 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13583 } 13584 } catch (PackageManagerException e) { 13585 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13586 } 13587 13588 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13589 } 13590 13591 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13592 // Can't rotate keys during boot or if sharedUser. 13593 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13594 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13595 return false; 13596 } 13597 // app is using upgradeKeySets; make sure all are valid 13598 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13599 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13600 for (int i = 0; i < upgradeKeySets.length; i++) { 13601 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13602 Slog.wtf(TAG, "Package " 13603 + (oldPs.name != null ? oldPs.name : "<null>") 13604 + " contains upgrade-key-set reference to unknown key-set: " 13605 + upgradeKeySets[i] 13606 + " reverting to signatures check."); 13607 return false; 13608 } 13609 } 13610 return true; 13611 } 13612 13613 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13614 // Upgrade keysets are being used. Determine if new package has a superset of the 13615 // required keys. 13616 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13617 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13618 for (int i = 0; i < upgradeKeySets.length; i++) { 13619 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13620 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13621 return true; 13622 } 13623 } 13624 return false; 13625 } 13626 13627 private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13628 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13629 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13630 13631 final PackageParser.Package oldPackage; 13632 final String pkgName = pkg.packageName; 13633 final int[] allUsers; 13634 13635 // First find the old package info and check signatures 13636 synchronized(mPackages) { 13637 oldPackage = mPackages.get(pkgName); 13638 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13639 if (isEphemeral && !oldIsEphemeral) { 13640 // can't downgrade from full to ephemeral 13641 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13642 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13643 return; 13644 } 13645 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13646 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13647 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13648 if (!checkUpgradeKeySetLP(ps, pkg)) { 13649 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13650 "New package not signed by keys specified by upgrade-keysets: " 13651 + pkgName); 13652 return; 13653 } 13654 } else { 13655 // default to original signature matching 13656 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13657 != PackageManager.SIGNATURE_MATCH) { 13658 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13659 "New package has a different signature: " + pkgName); 13660 return; 13661 } 13662 } 13663 13664 // Check for shared user id changes 13665 String invalidPackageName = 13666 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13667 if (invalidPackageName != null) { 13668 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13669 "Package " + invalidPackageName + " tried to change user " 13670 + oldPackage.mSharedUserId); 13671 return; 13672 } 13673 13674 // In case of rollback, remember per-user/profile install state 13675 allUsers = sUserManager.getUserIds(); 13676 } 13677 13678 // Update what is removed 13679 res.removedInfo = new PackageRemovedInfo(); 13680 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13681 res.removedInfo.removedPackage = oldPackage.packageName; 13682 res.removedInfo.isUpdate = true; 13683 final int childCount = (oldPackage.childPackages != null) 13684 ? oldPackage.childPackages.size() : 0; 13685 for (int i = 0; i < childCount; i++) { 13686 boolean childPackageUpdated = false; 13687 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13688 if (res.addedChildPackages != null) { 13689 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13690 if (childRes != null) { 13691 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13692 childRes.removedInfo.removedPackage = childPkg.packageName; 13693 childRes.removedInfo.isUpdate = true; 13694 childPackageUpdated = true; 13695 } 13696 } 13697 if (!childPackageUpdated) { 13698 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13699 childRemovedRes.removedPackage = childPkg.packageName; 13700 childRemovedRes.isUpdate = false; 13701 childRemovedRes.dataRemoved = true; 13702 synchronized (mPackages) { 13703 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13704 if (childPs != null) { 13705 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13706 } 13707 } 13708 if (res.removedInfo.removedChildPackages == null) { 13709 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13710 } 13711 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13712 } 13713 } 13714 13715 boolean sysPkg = (isSystemApp(oldPackage)); 13716 if (sysPkg) { 13717 replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13718 user, allUsers, installerPackageName, res); 13719 } else { 13720 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13721 user, allUsers, installerPackageName, res); 13722 } 13723 } 13724 13725 public List<String> getPreviousCodePaths(String packageName) { 13726 final PackageSetting ps = mSettings.mPackages.get(packageName); 13727 final List<String> result = new ArrayList<String>(); 13728 if (ps != null && ps.oldCodePaths != null) { 13729 result.addAll(ps.oldCodePaths); 13730 } 13731 return result; 13732 } 13733 13734 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13735 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13736 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13737 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13738 + deletedPackage); 13739 13740 String pkgName = deletedPackage.packageName; 13741 boolean deletedPkg = true; 13742 boolean addedPkg = false; 13743 boolean updatedSettings = false; 13744 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13745 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13746 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13747 13748 final long origUpdateTime = (pkg.mExtras != null) 13749 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13750 13751 // First delete the existing package while retaining the data directory 13752 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13753 res.removedInfo, true, pkg)) { 13754 // If the existing package wasn't successfully deleted 13755 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13756 deletedPkg = false; 13757 } else { 13758 // Successfully deleted the old package; proceed with replace. 13759 13760 // If deleted package lived in a container, give users a chance to 13761 // relinquish resources before killing. 13762 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13763 if (DEBUG_INSTALL) { 13764 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13765 } 13766 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13767 final ArrayList<String> pkgList = new ArrayList<String>(1); 13768 pkgList.add(deletedPackage.applicationInfo.packageName); 13769 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13770 } 13771 13772 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13773 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13774 clearAppProfilesLIF(pkg); 13775 13776 try { 13777 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13778 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13779 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13780 13781 // Update the in-memory copy of the previous code paths. 13782 PackageSetting ps = mSettings.mPackages.get(pkgName); 13783 if (!killApp) { 13784 if (ps.oldCodePaths == null) { 13785 ps.oldCodePaths = new ArraySet<>(); 13786 } 13787 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13788 if (deletedPackage.splitCodePaths != null) { 13789 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13790 } 13791 } else { 13792 ps.oldCodePaths = null; 13793 } 13794 if (ps.childPackageNames != null) { 13795 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13796 final String childPkgName = ps.childPackageNames.get(i); 13797 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13798 childPs.oldCodePaths = ps.oldCodePaths; 13799 } 13800 } 13801 prepareAppDataAfterInstallLIF(newPackage); 13802 addedPkg = true; 13803 } catch (PackageManagerException e) { 13804 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13805 } 13806 } 13807 13808 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13809 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13810 13811 // Revert all internal state mutations and added folders for the failed install 13812 if (addedPkg) { 13813 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13814 res.removedInfo, true, null); 13815 } 13816 13817 // Restore the old package 13818 if (deletedPkg) { 13819 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13820 File restoreFile = new File(deletedPackage.codePath); 13821 // Parse old package 13822 boolean oldExternal = isExternal(deletedPackage); 13823 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13824 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13825 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13826 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13827 try { 13828 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13829 null); 13830 } catch (PackageManagerException e) { 13831 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13832 + e.getMessage()); 13833 return; 13834 } 13835 13836 synchronized (mPackages) { 13837 // Ensure the installer package name up to date 13838 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13839 13840 // Update permissions for restored package 13841 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13842 13843 mSettings.writeLPr(); 13844 } 13845 13846 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13847 } 13848 } else { 13849 synchronized (mPackages) { 13850 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13851 if (ps != null) { 13852 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13853 if (res.removedInfo.removedChildPackages != null) { 13854 final int childCount = res.removedInfo.removedChildPackages.size(); 13855 // Iterate in reverse as we may modify the collection 13856 for (int i = childCount - 1; i >= 0; i--) { 13857 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13858 if (res.addedChildPackages.containsKey(childPackageName)) { 13859 res.removedInfo.removedChildPackages.removeAt(i); 13860 } else { 13861 PackageRemovedInfo childInfo = res.removedInfo 13862 .removedChildPackages.valueAt(i); 13863 childInfo.removedForAllUsers = mPackages.get( 13864 childInfo.removedPackage) == null; 13865 } 13866 } 13867 } 13868 } 13869 } 13870 } 13871 } 13872 13873 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13874 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13875 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13876 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13877 + ", old=" + deletedPackage); 13878 13879 final boolean disabledSystem; 13880 13881 // Set the system/privileged flags as needed 13882 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13883 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13884 != 0) { 13885 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13886 } 13887 13888 // Remove existing system package 13889 removePackageLI(deletedPackage, true); 13890 13891 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13892 if (!disabledSystem) { 13893 // We didn't need to disable the .apk as a current system package, 13894 // which means we are replacing another update that is already 13895 // installed. We need to make sure to delete the older one's .apk. 13896 res.removedInfo.args = createInstallArgsForExisting(0, 13897 deletedPackage.applicationInfo.getCodePath(), 13898 deletedPackage.applicationInfo.getResourcePath(), 13899 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13900 } else { 13901 res.removedInfo.args = null; 13902 } 13903 13904 // Successfully disabled the old package. Now proceed with re-installation 13905 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13906 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13907 clearAppProfilesLIF(pkg); 13908 13909 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13910 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13911 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13912 13913 PackageParser.Package newPackage = null; 13914 try { 13915 // Add the package to the internal data structures 13916 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13917 13918 // Set the update and install times 13919 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13920 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13921 System.currentTimeMillis()); 13922 13923 // Update the package dynamic state if succeeded 13924 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13925 // Now that the install succeeded make sure we remove data 13926 // directories for any child package the update removed. 13927 final int deletedChildCount = (deletedPackage.childPackages != null) 13928 ? deletedPackage.childPackages.size() : 0; 13929 final int newChildCount = (newPackage.childPackages != null) 13930 ? newPackage.childPackages.size() : 0; 13931 for (int i = 0; i < deletedChildCount; i++) { 13932 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13933 boolean childPackageDeleted = true; 13934 for (int j = 0; j < newChildCount; j++) { 13935 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13936 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13937 childPackageDeleted = false; 13938 break; 13939 } 13940 } 13941 if (childPackageDeleted) { 13942 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13943 deletedChildPkg.packageName); 13944 if (ps != null && res.removedInfo.removedChildPackages != null) { 13945 PackageRemovedInfo removedChildRes = res.removedInfo 13946 .removedChildPackages.get(deletedChildPkg.packageName); 13947 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13948 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13949 } 13950 } 13951 } 13952 13953 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13954 prepareAppDataAfterInstallLIF(newPackage); 13955 } 13956 } catch (PackageManagerException e) { 13957 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13958 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13959 } 13960 13961 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13962 // Re installation failed. Restore old information 13963 // Remove new pkg information 13964 if (newPackage != null) { 13965 removeInstalledPackageLI(newPackage, true); 13966 } 13967 // Add back the old system package 13968 try { 13969 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13970 } catch (PackageManagerException e) { 13971 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13972 } 13973 13974 synchronized (mPackages) { 13975 if (disabledSystem) { 13976 enableSystemPackageLPw(deletedPackage); 13977 } 13978 13979 // Ensure the installer package name up to date 13980 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13981 13982 // Update permissions for restored package 13983 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13984 13985 mSettings.writeLPr(); 13986 } 13987 13988 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13989 + " after failed upgrade"); 13990 } 13991 } 13992 13993 /** 13994 * Checks whether the parent or any of the child packages have a change shared 13995 * user. For a package to be a valid update the shred users of the parent and 13996 * the children should match. We may later support changing child shared users. 13997 * @param oldPkg The updated package. 13998 * @param newPkg The update package. 13999 * @return The shared user that change between the versions. 14000 */ 14001 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14002 PackageParser.Package newPkg) { 14003 // Check parent shared user 14004 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14005 return newPkg.packageName; 14006 } 14007 // Check child shared users 14008 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14009 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14010 for (int i = 0; i < newChildCount; i++) { 14011 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14012 // If this child was present, did it have the same shared user? 14013 for (int j = 0; j < oldChildCount; j++) { 14014 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14015 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14016 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14017 return newChildPkg.packageName; 14018 } 14019 } 14020 } 14021 return null; 14022 } 14023 14024 private void removeNativeBinariesLI(PackageSetting ps) { 14025 // Remove the lib path for the parent package 14026 if (ps != null) { 14027 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14028 // Remove the lib path for the child packages 14029 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14030 for (int i = 0; i < childCount; i++) { 14031 PackageSetting childPs = null; 14032 synchronized (mPackages) { 14033 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14034 } 14035 if (childPs != null) { 14036 NativeLibraryHelper.removeNativeBinariesLI(childPs 14037 .legacyNativeLibraryPathString); 14038 } 14039 } 14040 } 14041 } 14042 14043 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14044 // Enable the parent package 14045 mSettings.enableSystemPackageLPw(pkg.packageName); 14046 // Enable the child packages 14047 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14048 for (int i = 0; i < childCount; i++) { 14049 PackageParser.Package childPkg = pkg.childPackages.get(i); 14050 mSettings.enableSystemPackageLPw(childPkg.packageName); 14051 } 14052 } 14053 14054 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14055 PackageParser.Package newPkg) { 14056 // Disable the parent package (parent always replaced) 14057 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14058 // Disable the child packages 14059 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14060 for (int i = 0; i < childCount; i++) { 14061 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14062 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14063 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14064 } 14065 return disabled; 14066 } 14067 14068 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14069 String installerPackageName) { 14070 // Enable the parent package 14071 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14072 // Enable the child packages 14073 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14074 for (int i = 0; i < childCount; i++) { 14075 PackageParser.Package childPkg = pkg.childPackages.get(i); 14076 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14077 } 14078 } 14079 14080 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14081 // Collect all used permissions in the UID 14082 ArraySet<String> usedPermissions = new ArraySet<>(); 14083 final int packageCount = su.packages.size(); 14084 for (int i = 0; i < packageCount; i++) { 14085 PackageSetting ps = su.packages.valueAt(i); 14086 if (ps.pkg == null) { 14087 continue; 14088 } 14089 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14090 for (int j = 0; j < requestedPermCount; j++) { 14091 String permission = ps.pkg.requestedPermissions.get(j); 14092 BasePermission bp = mSettings.mPermissions.get(permission); 14093 if (bp != null) { 14094 usedPermissions.add(permission); 14095 } 14096 } 14097 } 14098 14099 PermissionsState permissionsState = su.getPermissionsState(); 14100 // Prune install permissions 14101 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14102 final int installPermCount = installPermStates.size(); 14103 for (int i = installPermCount - 1; i >= 0; i--) { 14104 PermissionState permissionState = installPermStates.get(i); 14105 if (!usedPermissions.contains(permissionState.getName())) { 14106 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14107 if (bp != null) { 14108 permissionsState.revokeInstallPermission(bp); 14109 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14110 PackageManager.MASK_PERMISSION_FLAGS, 0); 14111 } 14112 } 14113 } 14114 14115 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14116 14117 // Prune runtime permissions 14118 for (int userId : allUserIds) { 14119 List<PermissionState> runtimePermStates = permissionsState 14120 .getRuntimePermissionStates(userId); 14121 final int runtimePermCount = runtimePermStates.size(); 14122 for (int i = runtimePermCount - 1; i >= 0; i--) { 14123 PermissionState permissionState = runtimePermStates.get(i); 14124 if (!usedPermissions.contains(permissionState.getName())) { 14125 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14126 if (bp != null) { 14127 permissionsState.revokeRuntimePermission(bp, userId); 14128 permissionsState.updatePermissionFlags(bp, userId, 14129 PackageManager.MASK_PERMISSION_FLAGS, 0); 14130 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14131 runtimePermissionChangedUserIds, userId); 14132 } 14133 } 14134 } 14135 } 14136 14137 return runtimePermissionChangedUserIds; 14138 } 14139 14140 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14141 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14142 // Update the parent package setting 14143 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14144 res, user); 14145 // Update the child packages setting 14146 final int childCount = (newPackage.childPackages != null) 14147 ? newPackage.childPackages.size() : 0; 14148 for (int i = 0; i < childCount; i++) { 14149 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14150 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14151 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14152 childRes.origUsers, childRes, user); 14153 } 14154 } 14155 14156 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14157 String installerPackageName, int[] allUsers, int[] installedForUsers, 14158 PackageInstalledInfo res, UserHandle user) { 14159 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14160 14161 String pkgName = newPackage.packageName; 14162 synchronized (mPackages) { 14163 //write settings. the installStatus will be incomplete at this stage. 14164 //note that the new package setting would have already been 14165 //added to mPackages. It hasn't been persisted yet. 14166 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14167 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14168 mSettings.writeLPr(); 14169 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14170 } 14171 14172 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14173 synchronized (mPackages) { 14174 updatePermissionsLPw(newPackage.packageName, newPackage, 14175 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14176 ? UPDATE_PERMISSIONS_ALL : 0)); 14177 // For system-bundled packages, we assume that installing an upgraded version 14178 // of the package implies that the user actually wants to run that new code, 14179 // so we enable the package. 14180 PackageSetting ps = mSettings.mPackages.get(pkgName); 14181 final int userId = user.getIdentifier(); 14182 if (ps != null) { 14183 if (isSystemApp(newPackage)) { 14184 if (DEBUG_INSTALL) { 14185 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14186 } 14187 // Enable system package for requested users 14188 if (res.origUsers != null) { 14189 for (int origUserId : res.origUsers) { 14190 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14191 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14192 origUserId, installerPackageName); 14193 } 14194 } 14195 } 14196 // Also convey the prior install/uninstall state 14197 if (allUsers != null && installedForUsers != null) { 14198 for (int currentUserId : allUsers) { 14199 final boolean installed = ArrayUtils.contains( 14200 installedForUsers, currentUserId); 14201 if (DEBUG_INSTALL) { 14202 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14203 } 14204 ps.setInstalled(installed, currentUserId); 14205 } 14206 // these install state changes will be persisted in the 14207 // upcoming call to mSettings.writeLPr(). 14208 } 14209 } 14210 // It's implied that when a user requests installation, they want the app to be 14211 // installed and enabled. 14212 if (userId != UserHandle.USER_ALL) { 14213 ps.setInstalled(true, userId); 14214 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14215 } 14216 } 14217 res.name = pkgName; 14218 res.uid = newPackage.applicationInfo.uid; 14219 res.pkg = newPackage; 14220 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14221 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14222 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14223 //to update install status 14224 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14225 mSettings.writeLPr(); 14226 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14227 } 14228 14229 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14230 } 14231 14232 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14233 try { 14234 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14235 installPackageLI(args, res); 14236 } finally { 14237 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14238 } 14239 } 14240 14241 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14242 final int installFlags = args.installFlags; 14243 final String installerPackageName = args.installerPackageName; 14244 final String volumeUuid = args.volumeUuid; 14245 final File tmpPackageFile = new File(args.getCodePath()); 14246 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14247 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14248 || (args.volumeUuid != null)); 14249 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14250 boolean replace = false; 14251 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14252 if (args.move != null) { 14253 // moving a complete application; perform an initial scan on the new install location 14254 scanFlags |= SCAN_INITIAL; 14255 } 14256 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14257 scanFlags |= SCAN_DONT_KILL_APP; 14258 } 14259 14260 // Result object to be returned 14261 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14262 14263 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14264 14265 // Sanity check 14266 if (ephemeral && (forwardLocked || onExternal)) { 14267 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14268 + " external=" + onExternal); 14269 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14270 return; 14271 } 14272 14273 // Retrieve PackageSettings and parse package 14274 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14275 | PackageParser.PARSE_ENFORCE_CODE 14276 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14277 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14278 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14279 PackageParser pp = new PackageParser(); 14280 pp.setSeparateProcesses(mSeparateProcesses); 14281 pp.setDisplayMetrics(mMetrics); 14282 14283 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14284 final PackageParser.Package pkg; 14285 try { 14286 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14287 } catch (PackageParserException e) { 14288 res.setError("Failed parse during installPackageLI", e); 14289 return; 14290 } finally { 14291 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14292 } 14293 14294 // If we are installing a clustered package add results for the children 14295 if (pkg.childPackages != null) { 14296 synchronized (mPackages) { 14297 final int childCount = pkg.childPackages.size(); 14298 for (int i = 0; i < childCount; i++) { 14299 PackageParser.Package childPkg = pkg.childPackages.get(i); 14300 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14301 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14302 childRes.pkg = childPkg; 14303 childRes.name = childPkg.packageName; 14304 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14305 if (childPs != null) { 14306 childRes.origUsers = childPs.queryInstalledUsers( 14307 sUserManager.getUserIds(), true); 14308 } 14309 if ((mPackages.containsKey(childPkg.packageName))) { 14310 childRes.removedInfo = new PackageRemovedInfo(); 14311 childRes.removedInfo.removedPackage = childPkg.packageName; 14312 } 14313 if (res.addedChildPackages == null) { 14314 res.addedChildPackages = new ArrayMap<>(); 14315 } 14316 res.addedChildPackages.put(childPkg.packageName, childRes); 14317 } 14318 } 14319 } 14320 14321 // If package doesn't declare API override, mark that we have an install 14322 // time CPU ABI override. 14323 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14324 pkg.cpuAbiOverride = args.abiOverride; 14325 } 14326 14327 String pkgName = res.name = pkg.packageName; 14328 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14329 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14330 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14331 return; 14332 } 14333 } 14334 14335 try { 14336 // either use what we've been given or parse directly from the APK 14337 if (args.certificates != null) { 14338 try { 14339 PackageParser.populateCertificates(pkg, args.certificates); 14340 } catch (PackageParserException e) { 14341 // there was something wrong with the certificates we were given; 14342 // try to pull them from the APK 14343 PackageParser.collectCertificates(pkg, parseFlags); 14344 } 14345 } else { 14346 PackageParser.collectCertificates(pkg, parseFlags); 14347 } 14348 } catch (PackageParserException e) { 14349 res.setError("Failed collect during installPackageLI", e); 14350 return; 14351 } 14352 14353 // Get rid of all references to package scan path via parser. 14354 pp = null; 14355 String oldCodePath = null; 14356 boolean systemApp = false; 14357 synchronized (mPackages) { 14358 // Check if installing already existing package 14359 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14360 String oldName = mSettings.mRenamedPackages.get(pkgName); 14361 if (pkg.mOriginalPackages != null 14362 && pkg.mOriginalPackages.contains(oldName) 14363 && mPackages.containsKey(oldName)) { 14364 // This package is derived from an original package, 14365 // and this device has been updating from that original 14366 // name. We must continue using the original name, so 14367 // rename the new package here. 14368 pkg.setPackageName(oldName); 14369 pkgName = pkg.packageName; 14370 replace = true; 14371 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14372 + oldName + " pkgName=" + pkgName); 14373 } else if (mPackages.containsKey(pkgName)) { 14374 // This package, under its official name, already exists 14375 // on the device; we should replace it. 14376 replace = true; 14377 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14378 } 14379 14380 // Child packages are installed through the parent package 14381 if (pkg.parentPackage != null) { 14382 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14383 "Package " + pkg.packageName + " is child of package " 14384 + pkg.parentPackage.parentPackage + ". Child packages " 14385 + "can be updated only through the parent package."); 14386 return; 14387 } 14388 14389 if (replace) { 14390 // Prevent apps opting out from runtime permissions 14391 PackageParser.Package oldPackage = mPackages.get(pkgName); 14392 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14393 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14394 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14395 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14396 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14397 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14398 + " doesn't support runtime permissions but the old" 14399 + " target SDK " + oldTargetSdk + " does."); 14400 return; 14401 } 14402 14403 // Prevent installing of child packages 14404 if (oldPackage.parentPackage != null) { 14405 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14406 "Package " + pkg.packageName + " is child of package " 14407 + oldPackage.parentPackage + ". Child packages " 14408 + "can be updated only through the parent package."); 14409 return; 14410 } 14411 } 14412 } 14413 14414 PackageSetting ps = mSettings.mPackages.get(pkgName); 14415 if (ps != null) { 14416 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14417 14418 // Quick sanity check that we're signed correctly if updating; 14419 // we'll check this again later when scanning, but we want to 14420 // bail early here before tripping over redefined permissions. 14421 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14422 if (!checkUpgradeKeySetLP(ps, pkg)) { 14423 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14424 + pkg.packageName + " upgrade keys do not match the " 14425 + "previously installed version"); 14426 return; 14427 } 14428 } else { 14429 try { 14430 verifySignaturesLP(ps, pkg); 14431 } catch (PackageManagerException e) { 14432 res.setError(e.error, e.getMessage()); 14433 return; 14434 } 14435 } 14436 14437 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14438 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14439 systemApp = (ps.pkg.applicationInfo.flags & 14440 ApplicationInfo.FLAG_SYSTEM) != 0; 14441 } 14442 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14443 } 14444 14445 // Check whether the newly-scanned package wants to define an already-defined perm 14446 int N = pkg.permissions.size(); 14447 for (int i = N-1; i >= 0; i--) { 14448 PackageParser.Permission perm = pkg.permissions.get(i); 14449 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14450 if (bp != null) { 14451 // If the defining package is signed with our cert, it's okay. This 14452 // also includes the "updating the same package" case, of course. 14453 // "updating same package" could also involve key-rotation. 14454 final boolean sigsOk; 14455 if (bp.sourcePackage.equals(pkg.packageName) 14456 && (bp.packageSetting instanceof PackageSetting) 14457 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14458 scanFlags))) { 14459 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14460 } else { 14461 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14462 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14463 } 14464 if (!sigsOk) { 14465 // If the owning package is the system itself, we log but allow 14466 // install to proceed; we fail the install on all other permission 14467 // redefinitions. 14468 if (!bp.sourcePackage.equals("android")) { 14469 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14470 + pkg.packageName + " attempting to redeclare permission " 14471 + perm.info.name + " already owned by " + bp.sourcePackage); 14472 res.origPermission = perm.info.name; 14473 res.origPackage = bp.sourcePackage; 14474 return; 14475 } else { 14476 Slog.w(TAG, "Package " + pkg.packageName 14477 + " attempting to redeclare system permission " 14478 + perm.info.name + "; ignoring new declaration"); 14479 pkg.permissions.remove(i); 14480 } 14481 } 14482 } 14483 } 14484 } 14485 14486 if (systemApp) { 14487 if (onExternal) { 14488 // Abort update; system app can't be replaced with app on sdcard 14489 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14490 "Cannot install updates to system apps on sdcard"); 14491 return; 14492 } else if (ephemeral) { 14493 // Abort update; system app can't be replaced with an ephemeral app 14494 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14495 "Cannot update a system app with an ephemeral app"); 14496 return; 14497 } 14498 } 14499 14500 if (args.move != null) { 14501 // We did an in-place move, so dex is ready to roll 14502 scanFlags |= SCAN_NO_DEX; 14503 scanFlags |= SCAN_MOVE; 14504 14505 synchronized (mPackages) { 14506 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14507 if (ps == null) { 14508 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14509 "Missing settings for moved package " + pkgName); 14510 } 14511 14512 // We moved the entire application as-is, so bring over the 14513 // previously derived ABI information. 14514 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14515 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14516 } 14517 14518 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14519 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14520 scanFlags |= SCAN_NO_DEX; 14521 14522 try { 14523 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14524 args.abiOverride : pkg.cpuAbiOverride); 14525 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14526 true /* extract libs */); 14527 } catch (PackageManagerException pme) { 14528 Slog.e(TAG, "Error deriving application ABI", pme); 14529 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14530 return; 14531 } 14532 14533 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14534 // Do not run PackageDexOptimizer through the local performDexOpt 14535 // method because `pkg` is not in `mPackages` yet. 14536 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14537 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14538 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14539 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14540 String msg = "Extracting package failed for " + pkgName; 14541 res.setError(INSTALL_FAILED_DEXOPT, msg); 14542 return; 14543 } 14544 14545 // Notify BackgroundDexOptService that the package has been changed. 14546 // If this is an update of a package which used to fail to compile, 14547 // BDOS will remove it from its blacklist. 14548 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14549 } 14550 14551 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14552 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14553 return; 14554 } 14555 14556 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14557 14558 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14559 "installPackageLI")) { 14560 if (replace) { 14561 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14562 installerPackageName, res); 14563 } else { 14564 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14565 args.user, installerPackageName, volumeUuid, res); 14566 } 14567 } 14568 synchronized (mPackages) { 14569 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14570 if (ps != null) { 14571 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14572 } 14573 14574 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14575 for (int i = 0; i < childCount; i++) { 14576 PackageParser.Package childPkg = pkg.childPackages.get(i); 14577 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14578 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14579 if (childPs != null) { 14580 childRes.newUsers = childPs.queryInstalledUsers( 14581 sUserManager.getUserIds(), true); 14582 } 14583 } 14584 } 14585 } 14586 14587 private void startIntentFilterVerifications(int userId, boolean replacing, 14588 PackageParser.Package pkg) { 14589 if (mIntentFilterVerifierComponent == null) { 14590 Slog.w(TAG, "No IntentFilter verification will not be done as " 14591 + "there is no IntentFilterVerifier available!"); 14592 return; 14593 } 14594 14595 final int verifierUid = getPackageUid( 14596 mIntentFilterVerifierComponent.getPackageName(), 14597 MATCH_DEBUG_TRIAGED_MISSING, 14598 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14599 14600 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14601 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14602 mHandler.sendMessage(msg); 14603 14604 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14605 for (int i = 0; i < childCount; i++) { 14606 PackageParser.Package childPkg = pkg.childPackages.get(i); 14607 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14608 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14609 mHandler.sendMessage(msg); 14610 } 14611 } 14612 14613 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14614 PackageParser.Package pkg) { 14615 int size = pkg.activities.size(); 14616 if (size == 0) { 14617 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14618 "No activity, so no need to verify any IntentFilter!"); 14619 return; 14620 } 14621 14622 final boolean hasDomainURLs = hasDomainURLs(pkg); 14623 if (!hasDomainURLs) { 14624 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14625 "No domain URLs, so no need to verify any IntentFilter!"); 14626 return; 14627 } 14628 14629 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14630 + " if any IntentFilter from the " + size 14631 + " Activities needs verification ..."); 14632 14633 int count = 0; 14634 final String packageName = pkg.packageName; 14635 14636 synchronized (mPackages) { 14637 // If this is a new install and we see that we've already run verification for this 14638 // package, we have nothing to do: it means the state was restored from backup. 14639 if (!replacing) { 14640 IntentFilterVerificationInfo ivi = 14641 mSettings.getIntentFilterVerificationLPr(packageName); 14642 if (ivi != null) { 14643 if (DEBUG_DOMAIN_VERIFICATION) { 14644 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14645 + ivi.getStatusString()); 14646 } 14647 return; 14648 } 14649 } 14650 14651 // If any filters need to be verified, then all need to be. 14652 boolean needToVerify = false; 14653 for (PackageParser.Activity a : pkg.activities) { 14654 for (ActivityIntentInfo filter : a.intents) { 14655 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14656 if (DEBUG_DOMAIN_VERIFICATION) { 14657 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14658 } 14659 needToVerify = true; 14660 break; 14661 } 14662 } 14663 } 14664 14665 if (needToVerify) { 14666 final int verificationId = mIntentFilterVerificationToken++; 14667 for (PackageParser.Activity a : pkg.activities) { 14668 for (ActivityIntentInfo filter : a.intents) { 14669 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14670 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14671 "Verification needed for IntentFilter:" + filter.toString()); 14672 mIntentFilterVerifier.addOneIntentFilterVerification( 14673 verifierUid, userId, verificationId, filter, packageName); 14674 count++; 14675 } 14676 } 14677 } 14678 } 14679 } 14680 14681 if (count > 0) { 14682 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14683 + " IntentFilter verification" + (count > 1 ? "s" : "") 14684 + " for userId:" + userId); 14685 mIntentFilterVerifier.startVerifications(userId); 14686 } else { 14687 if (DEBUG_DOMAIN_VERIFICATION) { 14688 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14689 } 14690 } 14691 } 14692 14693 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14694 final ComponentName cn = filter.activity.getComponentName(); 14695 final String packageName = cn.getPackageName(); 14696 14697 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14698 packageName); 14699 if (ivi == null) { 14700 return true; 14701 } 14702 int status = ivi.getStatus(); 14703 switch (status) { 14704 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14705 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14706 return true; 14707 14708 default: 14709 // Nothing to do 14710 return false; 14711 } 14712 } 14713 14714 private static boolean isMultiArch(ApplicationInfo info) { 14715 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14716 } 14717 14718 private static boolean isExternal(PackageParser.Package pkg) { 14719 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14720 } 14721 14722 private static boolean isExternal(PackageSetting ps) { 14723 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14724 } 14725 14726 private static boolean isEphemeral(PackageParser.Package pkg) { 14727 return pkg.applicationInfo.isEphemeralApp(); 14728 } 14729 14730 private static boolean isEphemeral(PackageSetting ps) { 14731 return ps.pkg != null && isEphemeral(ps.pkg); 14732 } 14733 14734 private static boolean isSystemApp(PackageParser.Package pkg) { 14735 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14736 } 14737 14738 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14739 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14740 } 14741 14742 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14743 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14744 } 14745 14746 private static boolean isSystemApp(PackageSetting ps) { 14747 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14748 } 14749 14750 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14751 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14752 } 14753 14754 private int packageFlagsToInstallFlags(PackageSetting ps) { 14755 int installFlags = 0; 14756 if (isEphemeral(ps)) { 14757 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14758 } 14759 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14760 // This existing package was an external ASEC install when we have 14761 // the external flag without a UUID 14762 installFlags |= PackageManager.INSTALL_EXTERNAL; 14763 } 14764 if (ps.isForwardLocked()) { 14765 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14766 } 14767 return installFlags; 14768 } 14769 14770 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14771 if (isExternal(pkg)) { 14772 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14773 return StorageManager.UUID_PRIMARY_PHYSICAL; 14774 } else { 14775 return pkg.volumeUuid; 14776 } 14777 } else { 14778 return StorageManager.UUID_PRIVATE_INTERNAL; 14779 } 14780 } 14781 14782 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14783 if (isExternal(pkg)) { 14784 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14785 return mSettings.getExternalVersion(); 14786 } else { 14787 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14788 } 14789 } else { 14790 return mSettings.getInternalVersion(); 14791 } 14792 } 14793 14794 private void deleteTempPackageFiles() { 14795 final FilenameFilter filter = new FilenameFilter() { 14796 public boolean accept(File dir, String name) { 14797 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14798 } 14799 }; 14800 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14801 file.delete(); 14802 } 14803 } 14804 14805 @Override 14806 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14807 int flags) { 14808 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14809 flags); 14810 } 14811 14812 @Override 14813 public void deletePackage(final String packageName, 14814 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14815 mContext.enforceCallingOrSelfPermission( 14816 android.Manifest.permission.DELETE_PACKAGES, null); 14817 Preconditions.checkNotNull(packageName); 14818 Preconditions.checkNotNull(observer); 14819 final int uid = Binder.getCallingUid(); 14820 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14821 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14822 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14823 mContext.enforceCallingOrSelfPermission( 14824 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14825 "deletePackage for user " + userId); 14826 } 14827 14828 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14829 try { 14830 observer.onPackageDeleted(packageName, 14831 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14832 } catch (RemoteException re) { 14833 } 14834 return; 14835 } 14836 14837 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14838 try { 14839 observer.onPackageDeleted(packageName, 14840 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14841 } catch (RemoteException re) { 14842 } 14843 return; 14844 } 14845 14846 if (DEBUG_REMOVE) { 14847 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14848 + " deleteAllUsers: " + deleteAllUsers ); 14849 } 14850 // Queue up an async operation since the package deletion may take a little while. 14851 mHandler.post(new Runnable() { 14852 public void run() { 14853 mHandler.removeCallbacks(this); 14854 int returnCode; 14855 if (!deleteAllUsers) { 14856 returnCode = deletePackageX(packageName, userId, deleteFlags); 14857 } else { 14858 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14859 // If nobody is blocking uninstall, proceed with delete for all users 14860 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14861 returnCode = deletePackageX(packageName, userId, deleteFlags); 14862 } else { 14863 // Otherwise uninstall individually for users with blockUninstalls=false 14864 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14865 for (int userId : users) { 14866 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14867 returnCode = deletePackageX(packageName, userId, userFlags); 14868 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14869 Slog.w(TAG, "Package delete failed for user " + userId 14870 + ", returnCode " + returnCode); 14871 } 14872 } 14873 } 14874 // The app has only been marked uninstalled for certain users. 14875 // We still need to report that delete was blocked 14876 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14877 } 14878 } 14879 try { 14880 observer.onPackageDeleted(packageName, returnCode, null); 14881 } catch (RemoteException e) { 14882 Log.i(TAG, "Observer no longer exists."); 14883 } //end catch 14884 } //end run 14885 }); 14886 } 14887 14888 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14889 int[] result = EMPTY_INT_ARRAY; 14890 for (int userId : userIds) { 14891 if (getBlockUninstallForUser(packageName, userId)) { 14892 result = ArrayUtils.appendInt(result, userId); 14893 } 14894 } 14895 return result; 14896 } 14897 14898 @Override 14899 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14900 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14901 } 14902 14903 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14904 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14905 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14906 try { 14907 if (dpm != null) { 14908 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14909 /* callingUserOnly =*/ false); 14910 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14911 : deviceOwnerComponentName.getPackageName(); 14912 // Does the package contains the device owner? 14913 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14914 // this check is probably not needed, since DO should be registered as a device 14915 // admin on some user too. (Original bug for this: b/17657954) 14916 if (packageName.equals(deviceOwnerPackageName)) { 14917 return true; 14918 } 14919 // Does it contain a device admin for any user? 14920 int[] users; 14921 if (userId == UserHandle.USER_ALL) { 14922 users = sUserManager.getUserIds(); 14923 } else { 14924 users = new int[]{userId}; 14925 } 14926 for (int i = 0; i < users.length; ++i) { 14927 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14928 return true; 14929 } 14930 } 14931 } 14932 } catch (RemoteException e) { 14933 } 14934 return false; 14935 } 14936 14937 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14938 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14939 } 14940 14941 /** 14942 * This method is an internal method that could be get invoked either 14943 * to delete an installed package or to clean up a failed installation. 14944 * After deleting an installed package, a broadcast is sent to notify any 14945 * listeners that the package has been removed. For cleaning up a failed 14946 * installation, the broadcast is not necessary since the package's 14947 * installation wouldn't have sent the initial broadcast either 14948 * The key steps in deleting a package are 14949 * deleting the package information in internal structures like mPackages, 14950 * deleting the packages base directories through installd 14951 * updating mSettings to reflect current status 14952 * persisting settings for later use 14953 * sending a broadcast if necessary 14954 */ 14955 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14956 final PackageRemovedInfo info = new PackageRemovedInfo(); 14957 final boolean res; 14958 14959 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14960 ? UserHandle.ALL : new UserHandle(userId); 14961 14962 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14963 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14964 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14965 } 14966 14967 PackageSetting uninstalledPs = null; 14968 14969 // for the uninstall-updates case and restricted profiles, remember the per- 14970 // user handle installed state 14971 int[] allUsers; 14972 synchronized (mPackages) { 14973 uninstalledPs = mSettings.mPackages.get(packageName); 14974 if (uninstalledPs == null) { 14975 Slog.w(TAG, "Not removing non-existent package " + packageName); 14976 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14977 } 14978 allUsers = sUserManager.getUserIds(); 14979 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14980 } 14981 14982 synchronized (mInstallLock) { 14983 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14984 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 14985 "deletePackageX")) { 14986 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 14987 deleteFlags | REMOVE_CHATTY, info, true, null); 14988 } 14989 synchronized (mPackages) { 14990 if (res) { 14991 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14992 } 14993 } 14994 } 14995 14996 if (res) { 14997 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 14998 info.sendPackageRemovedBroadcasts(killApp); 14999 info.sendSystemPackageUpdatedBroadcasts(); 15000 info.sendSystemPackageAppearedBroadcasts(); 15001 } 15002 // Force a gc here. 15003 Runtime.getRuntime().gc(); 15004 // Delete the resources here after sending the broadcast to let 15005 // other processes clean up before deleting resources. 15006 if (info.args != null) { 15007 synchronized (mInstallLock) { 15008 info.args.doPostDeleteLI(true); 15009 } 15010 } 15011 15012 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15013 } 15014 15015 class PackageRemovedInfo { 15016 String removedPackage; 15017 int uid = -1; 15018 int removedAppId = -1; 15019 int[] origUsers; 15020 int[] removedUsers = null; 15021 boolean isRemovedPackageSystemUpdate = false; 15022 boolean isUpdate; 15023 boolean dataRemoved; 15024 boolean removedForAllUsers; 15025 // Clean up resources deleted packages. 15026 InstallArgs args = null; 15027 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15028 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15029 15030 void sendPackageRemovedBroadcasts(boolean killApp) { 15031 sendPackageRemovedBroadcastInternal(killApp); 15032 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15033 for (int i = 0; i < childCount; i++) { 15034 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15035 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15036 } 15037 } 15038 15039 void sendSystemPackageUpdatedBroadcasts() { 15040 if (isRemovedPackageSystemUpdate) { 15041 sendSystemPackageUpdatedBroadcastsInternal(); 15042 final int childCount = (removedChildPackages != null) 15043 ? removedChildPackages.size() : 0; 15044 for (int i = 0; i < childCount; i++) { 15045 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15046 if (childInfo.isRemovedPackageSystemUpdate) { 15047 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15048 } 15049 } 15050 } 15051 } 15052 15053 void sendSystemPackageAppearedBroadcasts() { 15054 final int packageCount = (appearedChildPackages != null) 15055 ? appearedChildPackages.size() : 0; 15056 for (int i = 0; i < packageCount; i++) { 15057 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15058 for (int userId : installedInfo.newUsers) { 15059 sendPackageAddedForUser(installedInfo.name, true, 15060 UserHandle.getAppId(installedInfo.uid), userId); 15061 } 15062 } 15063 } 15064 15065 private void sendSystemPackageUpdatedBroadcastsInternal() { 15066 Bundle extras = new Bundle(2); 15067 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15068 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15069 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15070 extras, 0, null, null, null); 15071 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15072 extras, 0, null, null, null); 15073 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15074 null, 0, removedPackage, null, null); 15075 } 15076 15077 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15078 Bundle extras = new Bundle(2); 15079 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15080 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15081 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15082 if (isUpdate || isRemovedPackageSystemUpdate) { 15083 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15084 } 15085 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15086 if (removedPackage != null) { 15087 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15088 extras, 0, null, null, removedUsers); 15089 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15090 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15091 removedPackage, extras, 0, null, null, removedUsers); 15092 } 15093 } 15094 if (removedAppId >= 0) { 15095 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15096 removedUsers); 15097 } 15098 } 15099 } 15100 15101 /* 15102 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15103 * flag is not set, the data directory is removed as well. 15104 * make sure this flag is set for partially installed apps. If not its meaningless to 15105 * delete a partially installed application. 15106 */ 15107 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15108 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15109 String packageName = ps.name; 15110 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15111 // Retrieve object to delete permissions for shared user later on 15112 final PackageParser.Package deletedPkg; 15113 final PackageSetting deletedPs; 15114 // reader 15115 synchronized (mPackages) { 15116 deletedPkg = mPackages.get(packageName); 15117 deletedPs = mSettings.mPackages.get(packageName); 15118 if (outInfo != null) { 15119 outInfo.removedPackage = packageName; 15120 outInfo.removedUsers = deletedPs != null 15121 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15122 : null; 15123 } 15124 } 15125 15126 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15127 15128 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15129 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15130 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15131 destroyAppProfilesLIF(deletedPkg); 15132 if (outInfo != null) { 15133 outInfo.dataRemoved = true; 15134 } 15135 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15136 } 15137 15138 // writer 15139 synchronized (mPackages) { 15140 if (deletedPs != null) { 15141 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15142 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15143 clearDefaultBrowserIfNeeded(packageName); 15144 if (outInfo != null) { 15145 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15146 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15147 } 15148 updatePermissionsLPw(deletedPs.name, null, 0); 15149 if (deletedPs.sharedUser != null) { 15150 // Remove permissions associated with package. Since runtime 15151 // permissions are per user we have to kill the removed package 15152 // or packages running under the shared user of the removed 15153 // package if revoking the permissions requested only by the removed 15154 // package is successful and this causes a change in gids. 15155 for (int userId : UserManagerService.getInstance().getUserIds()) { 15156 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15157 userId); 15158 if (userIdToKill == UserHandle.USER_ALL 15159 || userIdToKill >= UserHandle.USER_SYSTEM) { 15160 // If gids changed for this user, kill all affected packages. 15161 mHandler.post(new Runnable() { 15162 @Override 15163 public void run() { 15164 // This has to happen with no lock held. 15165 killApplication(deletedPs.name, deletedPs.appId, 15166 KILL_APP_REASON_GIDS_CHANGED); 15167 } 15168 }); 15169 break; 15170 } 15171 } 15172 } 15173 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15174 } 15175 // make sure to preserve per-user disabled state if this removal was just 15176 // a downgrade of a system app to the factory package 15177 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15178 if (DEBUG_REMOVE) { 15179 Slog.d(TAG, "Propagating install state across downgrade"); 15180 } 15181 for (int userId : allUserHandles) { 15182 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15183 if (DEBUG_REMOVE) { 15184 Slog.d(TAG, " user " + userId + " => " + installed); 15185 } 15186 ps.setInstalled(installed, userId); 15187 } 15188 } 15189 } 15190 // can downgrade to reader 15191 if (writeSettings) { 15192 // Save settings now 15193 mSettings.writeLPr(); 15194 } 15195 } 15196 if (outInfo != null) { 15197 // A user ID was deleted here. Go through all users and remove it 15198 // from KeyStore. 15199 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15200 } 15201 } 15202 15203 static boolean locationIsPrivileged(File path) { 15204 try { 15205 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15206 .getCanonicalPath(); 15207 return path.getCanonicalPath().startsWith(privilegedAppDir); 15208 } catch (IOException e) { 15209 Slog.e(TAG, "Unable to access code path " + path); 15210 } 15211 return false; 15212 } 15213 15214 /* 15215 * Tries to delete system package. 15216 */ 15217 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15218 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15219 boolean writeSettings) { 15220 if (deletedPs.parentPackageName != null) { 15221 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15222 return false; 15223 } 15224 15225 final boolean applyUserRestrictions 15226 = (allUserHandles != null) && (outInfo.origUsers != null); 15227 final PackageSetting disabledPs; 15228 // Confirm if the system package has been updated 15229 // An updated system app can be deleted. This will also have to restore 15230 // the system pkg from system partition 15231 // reader 15232 synchronized (mPackages) { 15233 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15234 } 15235 15236 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15237 + " disabledPs=" + disabledPs); 15238 15239 if (disabledPs == null) { 15240 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15241 return false; 15242 } else if (DEBUG_REMOVE) { 15243 Slog.d(TAG, "Deleting system pkg from data partition"); 15244 } 15245 15246 if (DEBUG_REMOVE) { 15247 if (applyUserRestrictions) { 15248 Slog.d(TAG, "Remembering install states:"); 15249 for (int userId : allUserHandles) { 15250 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15251 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15252 } 15253 } 15254 } 15255 15256 // Delete the updated package 15257 outInfo.isRemovedPackageSystemUpdate = true; 15258 if (outInfo.removedChildPackages != null) { 15259 final int childCount = (deletedPs.childPackageNames != null) 15260 ? deletedPs.childPackageNames.size() : 0; 15261 for (int i = 0; i < childCount; i++) { 15262 String childPackageName = deletedPs.childPackageNames.get(i); 15263 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15264 .contains(childPackageName)) { 15265 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15266 childPackageName); 15267 if (childInfo != null) { 15268 childInfo.isRemovedPackageSystemUpdate = true; 15269 } 15270 } 15271 } 15272 } 15273 15274 if (disabledPs.versionCode < deletedPs.versionCode) { 15275 // Delete data for downgrades 15276 flags &= ~PackageManager.DELETE_KEEP_DATA; 15277 } else { 15278 // Preserve data by setting flag 15279 flags |= PackageManager.DELETE_KEEP_DATA; 15280 } 15281 15282 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15283 outInfo, writeSettings, disabledPs.pkg); 15284 if (!ret) { 15285 return false; 15286 } 15287 15288 // writer 15289 synchronized (mPackages) { 15290 // Reinstate the old system package 15291 enableSystemPackageLPw(disabledPs.pkg); 15292 // Remove any native libraries from the upgraded package. 15293 removeNativeBinariesLI(deletedPs); 15294 } 15295 15296 // Install the system package 15297 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15298 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15299 if (locationIsPrivileged(disabledPs.codePath)) { 15300 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15301 } 15302 15303 final PackageParser.Package newPkg; 15304 try { 15305 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15306 } catch (PackageManagerException e) { 15307 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15308 + e.getMessage()); 15309 return false; 15310 } 15311 15312 prepareAppDataAfterInstallLIF(newPkg); 15313 15314 // writer 15315 synchronized (mPackages) { 15316 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15317 15318 // Propagate the permissions state as we do not want to drop on the floor 15319 // runtime permissions. The update permissions method below will take 15320 // care of removing obsolete permissions and grant install permissions. 15321 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15322 updatePermissionsLPw(newPkg.packageName, newPkg, 15323 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15324 15325 if (applyUserRestrictions) { 15326 if (DEBUG_REMOVE) { 15327 Slog.d(TAG, "Propagating install state across reinstall"); 15328 } 15329 for (int userId : allUserHandles) { 15330 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15331 if (DEBUG_REMOVE) { 15332 Slog.d(TAG, " user " + userId + " => " + installed); 15333 } 15334 ps.setInstalled(installed, userId); 15335 15336 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15337 } 15338 // Regardless of writeSettings we need to ensure that this restriction 15339 // state propagation is persisted 15340 mSettings.writeAllUsersPackageRestrictionsLPr(); 15341 } 15342 // can downgrade to reader here 15343 if (writeSettings) { 15344 mSettings.writeLPr(); 15345 } 15346 } 15347 return true; 15348 } 15349 15350 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15351 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15352 PackageRemovedInfo outInfo, boolean writeSettings, 15353 PackageParser.Package replacingPackage) { 15354 synchronized (mPackages) { 15355 if (outInfo != null) { 15356 outInfo.uid = ps.appId; 15357 } 15358 15359 if (outInfo != null && outInfo.removedChildPackages != null) { 15360 final int childCount = (ps.childPackageNames != null) 15361 ? ps.childPackageNames.size() : 0; 15362 for (int i = 0; i < childCount; i++) { 15363 String childPackageName = ps.childPackageNames.get(i); 15364 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15365 if (childPs == null) { 15366 return false; 15367 } 15368 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15369 childPackageName); 15370 if (childInfo != null) { 15371 childInfo.uid = childPs.appId; 15372 } 15373 } 15374 } 15375 } 15376 15377 // Delete package data from internal structures and also remove data if flag is set 15378 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15379 15380 // Delete the child packages data 15381 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15382 for (int i = 0; i < childCount; i++) { 15383 PackageSetting childPs; 15384 synchronized (mPackages) { 15385 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15386 } 15387 if (childPs != null) { 15388 PackageRemovedInfo childOutInfo = (outInfo != null 15389 && outInfo.removedChildPackages != null) 15390 ? outInfo.removedChildPackages.get(childPs.name) : null; 15391 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15392 && (replacingPackage != null 15393 && !replacingPackage.hasChildPackage(childPs.name)) 15394 ? flags & ~DELETE_KEEP_DATA : flags; 15395 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15396 deleteFlags, writeSettings); 15397 } 15398 } 15399 15400 // Delete application code and resources only for parent packages 15401 if (ps.parentPackageName == null) { 15402 if (deleteCodeAndResources && (outInfo != null)) { 15403 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15404 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15405 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15406 } 15407 } 15408 15409 return true; 15410 } 15411 15412 @Override 15413 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15414 int userId) { 15415 mContext.enforceCallingOrSelfPermission( 15416 android.Manifest.permission.DELETE_PACKAGES, null); 15417 synchronized (mPackages) { 15418 PackageSetting ps = mSettings.mPackages.get(packageName); 15419 if (ps == null) { 15420 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15421 return false; 15422 } 15423 if (!ps.getInstalled(userId)) { 15424 // Can't block uninstall for an app that is not installed or enabled. 15425 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15426 return false; 15427 } 15428 ps.setBlockUninstall(blockUninstall, userId); 15429 mSettings.writePackageRestrictionsLPr(userId); 15430 } 15431 return true; 15432 } 15433 15434 @Override 15435 public boolean getBlockUninstallForUser(String packageName, int userId) { 15436 synchronized (mPackages) { 15437 PackageSetting ps = mSettings.mPackages.get(packageName); 15438 if (ps == null) { 15439 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15440 return false; 15441 } 15442 return ps.getBlockUninstall(userId); 15443 } 15444 } 15445 15446 @Override 15447 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15448 int callingUid = Binder.getCallingUid(); 15449 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15450 throw new SecurityException( 15451 "setRequiredForSystemUser can only be run by the system or root"); 15452 } 15453 synchronized (mPackages) { 15454 PackageSetting ps = mSettings.mPackages.get(packageName); 15455 if (ps == null) { 15456 Log.w(TAG, "Package doesn't exist: " + packageName); 15457 return false; 15458 } 15459 if (systemUserApp) { 15460 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15461 } else { 15462 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15463 } 15464 mSettings.writeLPr(); 15465 } 15466 return true; 15467 } 15468 15469 /* 15470 * This method handles package deletion in general 15471 */ 15472 private boolean deletePackageLIF(String packageName, UserHandle user, 15473 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15474 PackageRemovedInfo outInfo, boolean writeSettings, 15475 PackageParser.Package replacingPackage) { 15476 if (packageName == null) { 15477 Slog.w(TAG, "Attempt to delete null packageName."); 15478 return false; 15479 } 15480 15481 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15482 15483 PackageSetting ps; 15484 15485 synchronized (mPackages) { 15486 ps = mSettings.mPackages.get(packageName); 15487 if (ps == null) { 15488 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15489 return false; 15490 } 15491 15492 if (ps.parentPackageName != null && (!isSystemApp(ps) 15493 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15494 if (DEBUG_REMOVE) { 15495 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15496 + ((user == null) ? UserHandle.USER_ALL : user)); 15497 } 15498 final int removedUserId = (user != null) ? user.getIdentifier() 15499 : UserHandle.USER_ALL; 15500 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15501 return false; 15502 } 15503 markPackageUninstalledForUserLPw(ps, user); 15504 scheduleWritePackageRestrictionsLocked(user); 15505 return true; 15506 } 15507 } 15508 15509 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15510 && user.getIdentifier() != UserHandle.USER_ALL)) { 15511 // The caller is asking that the package only be deleted for a single 15512 // user. To do this, we just mark its uninstalled state and delete 15513 // its data. If this is a system app, we only allow this to happen if 15514 // they have set the special DELETE_SYSTEM_APP which requests different 15515 // semantics than normal for uninstalling system apps. 15516 markPackageUninstalledForUserLPw(ps, user); 15517 15518 if (!isSystemApp(ps)) { 15519 // Do not uninstall the APK if an app should be cached 15520 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15521 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15522 // Other user still have this package installed, so all 15523 // we need to do is clear this user's data and save that 15524 // it is uninstalled. 15525 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15526 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15527 return false; 15528 } 15529 scheduleWritePackageRestrictionsLocked(user); 15530 return true; 15531 } else { 15532 // We need to set it back to 'installed' so the uninstall 15533 // broadcasts will be sent correctly. 15534 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15535 ps.setInstalled(true, user.getIdentifier()); 15536 } 15537 } else { 15538 // This is a system app, so we assume that the 15539 // other users still have this package installed, so all 15540 // we need to do is clear this user's data and save that 15541 // it is uninstalled. 15542 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15543 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15544 return false; 15545 } 15546 scheduleWritePackageRestrictionsLocked(user); 15547 return true; 15548 } 15549 } 15550 15551 // If we are deleting a composite package for all users, keep track 15552 // of result for each child. 15553 if (ps.childPackageNames != null && outInfo != null) { 15554 synchronized (mPackages) { 15555 final int childCount = ps.childPackageNames.size(); 15556 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15557 for (int i = 0; i < childCount; i++) { 15558 String childPackageName = ps.childPackageNames.get(i); 15559 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15560 childInfo.removedPackage = childPackageName; 15561 outInfo.removedChildPackages.put(childPackageName, childInfo); 15562 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15563 if (childPs != null) { 15564 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15565 } 15566 } 15567 } 15568 } 15569 15570 boolean ret = false; 15571 if (isSystemApp(ps)) { 15572 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15573 // When an updated system application is deleted we delete the existing resources 15574 // as well and fall back to existing code in system partition 15575 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15576 } else { 15577 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15578 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15579 outInfo, writeSettings, replacingPackage); 15580 } 15581 15582 // Take a note whether we deleted the package for all users 15583 if (outInfo != null) { 15584 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15585 if (outInfo.removedChildPackages != null) { 15586 synchronized (mPackages) { 15587 final int childCount = outInfo.removedChildPackages.size(); 15588 for (int i = 0; i < childCount; i++) { 15589 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15590 if (childInfo != null) { 15591 childInfo.removedForAllUsers = mPackages.get( 15592 childInfo.removedPackage) == null; 15593 } 15594 } 15595 } 15596 } 15597 // If we uninstalled an update to a system app there may be some 15598 // child packages that appeared as they are declared in the system 15599 // app but were not declared in the update. 15600 if (isSystemApp(ps)) { 15601 synchronized (mPackages) { 15602 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15603 final int childCount = (updatedPs.childPackageNames != null) 15604 ? updatedPs.childPackageNames.size() : 0; 15605 for (int i = 0; i < childCount; i++) { 15606 String childPackageName = updatedPs.childPackageNames.get(i); 15607 if (outInfo.removedChildPackages == null 15608 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15609 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15610 if (childPs == null) { 15611 continue; 15612 } 15613 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15614 installRes.name = childPackageName; 15615 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15616 installRes.pkg = mPackages.get(childPackageName); 15617 installRes.uid = childPs.pkg.applicationInfo.uid; 15618 if (outInfo.appearedChildPackages == null) { 15619 outInfo.appearedChildPackages = new ArrayMap<>(); 15620 } 15621 outInfo.appearedChildPackages.put(childPackageName, installRes); 15622 } 15623 } 15624 } 15625 } 15626 } 15627 15628 return ret; 15629 } 15630 15631 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15632 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15633 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15634 for (int nextUserId : userIds) { 15635 if (DEBUG_REMOVE) { 15636 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15637 } 15638 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15639 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15640 false /*hidden*/, false /*suspended*/, null, null, null, 15641 false /*blockUninstall*/, 15642 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15643 } 15644 } 15645 15646 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15647 PackageRemovedInfo outInfo) { 15648 final PackageParser.Package pkg; 15649 synchronized (mPackages) { 15650 pkg = mPackages.get(ps.name); 15651 } 15652 15653 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15654 : new int[] {userId}; 15655 for (int nextUserId : userIds) { 15656 if (DEBUG_REMOVE) { 15657 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15658 + nextUserId); 15659 } 15660 15661 destroyAppDataLIF(pkg, userId, 15662 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15663 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15664 schedulePackageCleaning(ps.name, nextUserId, false); 15665 synchronized (mPackages) { 15666 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15667 scheduleWritePackageRestrictionsLocked(nextUserId); 15668 } 15669 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15670 } 15671 } 15672 15673 if (outInfo != null) { 15674 outInfo.removedPackage = ps.name; 15675 outInfo.removedAppId = ps.appId; 15676 outInfo.removedUsers = userIds; 15677 } 15678 15679 return true; 15680 } 15681 15682 private final class ClearStorageConnection implements ServiceConnection { 15683 IMediaContainerService mContainerService; 15684 15685 @Override 15686 public void onServiceConnected(ComponentName name, IBinder service) { 15687 synchronized (this) { 15688 mContainerService = IMediaContainerService.Stub.asInterface(service); 15689 notifyAll(); 15690 } 15691 } 15692 15693 @Override 15694 public void onServiceDisconnected(ComponentName name) { 15695 } 15696 } 15697 15698 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15699 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15700 15701 final boolean mounted; 15702 if (Environment.isExternalStorageEmulated()) { 15703 mounted = true; 15704 } else { 15705 final String status = Environment.getExternalStorageState(); 15706 15707 mounted = status.equals(Environment.MEDIA_MOUNTED) 15708 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15709 } 15710 15711 if (!mounted) { 15712 return; 15713 } 15714 15715 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15716 int[] users; 15717 if (userId == UserHandle.USER_ALL) { 15718 users = sUserManager.getUserIds(); 15719 } else { 15720 users = new int[] { userId }; 15721 } 15722 final ClearStorageConnection conn = new ClearStorageConnection(); 15723 if (mContext.bindServiceAsUser( 15724 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15725 try { 15726 for (int curUser : users) { 15727 long timeout = SystemClock.uptimeMillis() + 5000; 15728 synchronized (conn) { 15729 long now = SystemClock.uptimeMillis(); 15730 while (conn.mContainerService == null && now < timeout) { 15731 try { 15732 conn.wait(timeout - now); 15733 } catch (InterruptedException e) { 15734 } 15735 } 15736 } 15737 if (conn.mContainerService == null) { 15738 return; 15739 } 15740 15741 final UserEnvironment userEnv = new UserEnvironment(curUser); 15742 clearDirectory(conn.mContainerService, 15743 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15744 if (allData) { 15745 clearDirectory(conn.mContainerService, 15746 userEnv.buildExternalStorageAppDataDirs(packageName)); 15747 clearDirectory(conn.mContainerService, 15748 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15749 } 15750 } 15751 } finally { 15752 mContext.unbindService(conn); 15753 } 15754 } 15755 } 15756 15757 @Override 15758 public void clearApplicationProfileData(String packageName) { 15759 enforceSystemOrRoot("Only the system can clear all profile data"); 15760 15761 final PackageParser.Package pkg; 15762 synchronized (mPackages) { 15763 pkg = mPackages.get(packageName); 15764 } 15765 15766 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15767 synchronized (mInstallLock) { 15768 clearAppProfilesLIF(pkg); 15769 } 15770 } 15771 } 15772 15773 @Override 15774 public void clearApplicationUserData(final String packageName, 15775 final IPackageDataObserver observer, final int userId) { 15776 mContext.enforceCallingOrSelfPermission( 15777 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15778 15779 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15780 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15781 15782 final DevicePolicyManagerInternal dpmi = LocalServices 15783 .getService(DevicePolicyManagerInternal.class); 15784 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15785 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15786 } 15787 // Queue up an async operation since the package deletion may take a little while. 15788 mHandler.post(new Runnable() { 15789 public void run() { 15790 mHandler.removeCallbacks(this); 15791 final boolean succeeded; 15792 try (PackageFreezer freezer = freezePackage(packageName, 15793 "clearApplicationUserData")) { 15794 synchronized (mInstallLock) { 15795 succeeded = clearApplicationUserDataLIF(packageName, userId); 15796 } 15797 clearExternalStorageDataSync(packageName, userId, true); 15798 } 15799 if (succeeded) { 15800 // invoke DeviceStorageMonitor's update method to clear any notifications 15801 DeviceStorageMonitorInternal dsm = LocalServices 15802 .getService(DeviceStorageMonitorInternal.class); 15803 if (dsm != null) { 15804 dsm.checkMemory(); 15805 } 15806 } 15807 if(observer != null) { 15808 try { 15809 observer.onRemoveCompleted(packageName, succeeded); 15810 } catch (RemoteException e) { 15811 Log.i(TAG, "Observer no longer exists."); 15812 } 15813 } //end if observer 15814 } //end run 15815 }); 15816 } 15817 15818 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15819 if (packageName == null) { 15820 Slog.w(TAG, "Attempt to delete null packageName."); 15821 return false; 15822 } 15823 15824 // Try finding details about the requested package 15825 PackageParser.Package pkg; 15826 synchronized (mPackages) { 15827 pkg = mPackages.get(packageName); 15828 if (pkg == null) { 15829 final PackageSetting ps = mSettings.mPackages.get(packageName); 15830 if (ps != null) { 15831 pkg = ps.pkg; 15832 } 15833 } 15834 15835 if (pkg == null) { 15836 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15837 return false; 15838 } 15839 15840 PackageSetting ps = (PackageSetting) pkg.mExtras; 15841 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15842 } 15843 15844 clearAppDataLIF(pkg, userId, 15845 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15846 15847 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15848 removeKeystoreDataIfNeeded(userId, appId); 15849 15850 final UserManager um = mContext.getSystemService(UserManager.class); 15851 final int flags; 15852 if (um.isUserUnlocked(userId)) { 15853 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15854 } else if (um.isUserRunning(userId)) { 15855 flags = StorageManager.FLAG_STORAGE_DE; 15856 } else { 15857 flags = 0; 15858 } 15859 prepareAppDataContentsLIF(pkg, userId, flags); 15860 15861 return true; 15862 } 15863 15864 /** 15865 * Reverts user permission state changes (permissions and flags) in 15866 * all packages for a given user. 15867 * 15868 * @param userId The device user for which to do a reset. 15869 */ 15870 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15871 final int packageCount = mPackages.size(); 15872 for (int i = 0; i < packageCount; i++) { 15873 PackageParser.Package pkg = mPackages.valueAt(i); 15874 PackageSetting ps = (PackageSetting) pkg.mExtras; 15875 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15876 } 15877 } 15878 15879 /** 15880 * Reverts user permission state changes (permissions and flags). 15881 * 15882 * @param ps The package for which to reset. 15883 * @param userId The device user for which to do a reset. 15884 */ 15885 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15886 final PackageSetting ps, final int userId) { 15887 if (ps.pkg == null) { 15888 return; 15889 } 15890 15891 // These are flags that can change base on user actions. 15892 final int userSettableMask = FLAG_PERMISSION_USER_SET 15893 | FLAG_PERMISSION_USER_FIXED 15894 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15895 | FLAG_PERMISSION_REVIEW_REQUIRED; 15896 15897 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15898 | FLAG_PERMISSION_POLICY_FIXED; 15899 15900 boolean writeInstallPermissions = false; 15901 boolean writeRuntimePermissions = false; 15902 15903 final int permissionCount = ps.pkg.requestedPermissions.size(); 15904 for (int i = 0; i < permissionCount; i++) { 15905 String permission = ps.pkg.requestedPermissions.get(i); 15906 15907 BasePermission bp = mSettings.mPermissions.get(permission); 15908 if (bp == null) { 15909 continue; 15910 } 15911 15912 // If shared user we just reset the state to which only this app contributed. 15913 if (ps.sharedUser != null) { 15914 boolean used = false; 15915 final int packageCount = ps.sharedUser.packages.size(); 15916 for (int j = 0; j < packageCount; j++) { 15917 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15918 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15919 && pkg.pkg.requestedPermissions.contains(permission)) { 15920 used = true; 15921 break; 15922 } 15923 } 15924 if (used) { 15925 continue; 15926 } 15927 } 15928 15929 PermissionsState permissionsState = ps.getPermissionsState(); 15930 15931 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15932 15933 // Always clear the user settable flags. 15934 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15935 bp.name) != null; 15936 // If permission review is enabled and this is a legacy app, mark the 15937 // permission as requiring a review as this is the initial state. 15938 int flags = 0; 15939 if (Build.PERMISSIONS_REVIEW_REQUIRED 15940 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15941 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15942 } 15943 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15944 if (hasInstallState) { 15945 writeInstallPermissions = true; 15946 } else { 15947 writeRuntimePermissions = true; 15948 } 15949 } 15950 15951 // Below is only runtime permission handling. 15952 if (!bp.isRuntime()) { 15953 continue; 15954 } 15955 15956 // Never clobber system or policy. 15957 if ((oldFlags & policyOrSystemFlags) != 0) { 15958 continue; 15959 } 15960 15961 // If this permission was granted by default, make sure it is. 15962 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15963 if (permissionsState.grantRuntimePermission(bp, userId) 15964 != PERMISSION_OPERATION_FAILURE) { 15965 writeRuntimePermissions = true; 15966 } 15967 // If permission review is enabled the permissions for a legacy apps 15968 // are represented as constantly granted runtime ones, so don't revoke. 15969 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15970 // Otherwise, reset the permission. 15971 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15972 switch (revokeResult) { 15973 case PERMISSION_OPERATION_SUCCESS: 15974 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15975 writeRuntimePermissions = true; 15976 final int appId = ps.appId; 15977 mHandler.post(new Runnable() { 15978 @Override 15979 public void run() { 15980 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15981 } 15982 }); 15983 } break; 15984 } 15985 } 15986 } 15987 15988 // Synchronously write as we are taking permissions away. 15989 if (writeRuntimePermissions) { 15990 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15991 } 15992 15993 // Synchronously write as we are taking permissions away. 15994 if (writeInstallPermissions) { 15995 mSettings.writeLPr(); 15996 } 15997 } 15998 15999 /** 16000 * Remove entries from the keystore daemon. Will only remove it if the 16001 * {@code appId} is valid. 16002 */ 16003 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16004 if (appId < 0) { 16005 return; 16006 } 16007 16008 final KeyStore keyStore = KeyStore.getInstance(); 16009 if (keyStore != null) { 16010 if (userId == UserHandle.USER_ALL) { 16011 for (final int individual : sUserManager.getUserIds()) { 16012 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16013 } 16014 } else { 16015 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16016 } 16017 } else { 16018 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16019 } 16020 } 16021 16022 @Override 16023 public void deleteApplicationCacheFiles(final String packageName, 16024 final IPackageDataObserver observer) { 16025 final int userId = UserHandle.getCallingUserId(); 16026 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16027 } 16028 16029 @Override 16030 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16031 final IPackageDataObserver observer) { 16032 mContext.enforceCallingOrSelfPermission( 16033 android.Manifest.permission.DELETE_CACHE_FILES, null); 16034 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16035 /* requireFullPermission= */ true, /* checkShell= */ false, 16036 "delete application cache files"); 16037 16038 final PackageParser.Package pkg; 16039 synchronized (mPackages) { 16040 pkg = mPackages.get(packageName); 16041 } 16042 16043 // Queue up an async operation since the package deletion may take a little while. 16044 mHandler.post(new Runnable() { 16045 public void run() { 16046 synchronized (mInstallLock) { 16047 final int flags = StorageManager.FLAG_STORAGE_DE 16048 | StorageManager.FLAG_STORAGE_CE; 16049 // We're only clearing cache files, so we don't care if the 16050 // app is unfrozen and still able to run 16051 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16052 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16053 } 16054 clearExternalStorageDataSync(packageName, userId, false); 16055 if (observer != null) { 16056 try { 16057 observer.onRemoveCompleted(packageName, true); 16058 } catch (RemoteException e) { 16059 Log.i(TAG, "Observer no longer exists."); 16060 } 16061 } 16062 } 16063 }); 16064 } 16065 16066 @Override 16067 public void getPackageSizeInfo(final String packageName, int userHandle, 16068 final IPackageStatsObserver observer) { 16069 mContext.enforceCallingOrSelfPermission( 16070 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16071 if (packageName == null) { 16072 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16073 } 16074 16075 PackageStats stats = new PackageStats(packageName, userHandle); 16076 16077 /* 16078 * Queue up an async operation since the package measurement may take a 16079 * little while. 16080 */ 16081 Message msg = mHandler.obtainMessage(INIT_COPY); 16082 msg.obj = new MeasureParams(stats, observer); 16083 mHandler.sendMessage(msg); 16084 } 16085 16086 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16087 final PackageSetting ps; 16088 synchronized (mPackages) { 16089 ps = mSettings.mPackages.get(packageName); 16090 if (ps == null) { 16091 Slog.w(TAG, "Failed to find settings for " + packageName); 16092 return false; 16093 } 16094 } 16095 try { 16096 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16097 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16098 ps.getCeDataInode(userId), ps.codePathString, stats); 16099 } catch (InstallerException e) { 16100 Slog.w(TAG, String.valueOf(e)); 16101 return false; 16102 } 16103 16104 // For now, ignore code size of packages on system partition 16105 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16106 stats.codeSize = 0; 16107 } 16108 16109 return true; 16110 } 16111 16112 private int getUidTargetSdkVersionLockedLPr(int uid) { 16113 Object obj = mSettings.getUserIdLPr(uid); 16114 if (obj instanceof SharedUserSetting) { 16115 final SharedUserSetting sus = (SharedUserSetting) obj; 16116 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16117 final Iterator<PackageSetting> it = sus.packages.iterator(); 16118 while (it.hasNext()) { 16119 final PackageSetting ps = it.next(); 16120 if (ps.pkg != null) { 16121 int v = ps.pkg.applicationInfo.targetSdkVersion; 16122 if (v < vers) vers = v; 16123 } 16124 } 16125 return vers; 16126 } else if (obj instanceof PackageSetting) { 16127 final PackageSetting ps = (PackageSetting) obj; 16128 if (ps.pkg != null) { 16129 return ps.pkg.applicationInfo.targetSdkVersion; 16130 } 16131 } 16132 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16133 } 16134 16135 @Override 16136 public void addPreferredActivity(IntentFilter filter, int match, 16137 ComponentName[] set, ComponentName activity, int userId) { 16138 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16139 "Adding preferred"); 16140 } 16141 16142 private void addPreferredActivityInternal(IntentFilter filter, int match, 16143 ComponentName[] set, ComponentName activity, boolean always, int userId, 16144 String opname) { 16145 // writer 16146 int callingUid = Binder.getCallingUid(); 16147 enforceCrossUserPermission(callingUid, userId, 16148 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16149 if (filter.countActions() == 0) { 16150 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16151 return; 16152 } 16153 synchronized (mPackages) { 16154 if (mContext.checkCallingOrSelfPermission( 16155 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16156 != PackageManager.PERMISSION_GRANTED) { 16157 if (getUidTargetSdkVersionLockedLPr(callingUid) 16158 < Build.VERSION_CODES.FROYO) { 16159 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16160 + callingUid); 16161 return; 16162 } 16163 mContext.enforceCallingOrSelfPermission( 16164 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16165 } 16166 16167 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16168 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16169 + userId + ":"); 16170 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16171 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16172 scheduleWritePackageRestrictionsLocked(userId); 16173 } 16174 } 16175 16176 @Override 16177 public void replacePreferredActivity(IntentFilter filter, int match, 16178 ComponentName[] set, ComponentName activity, int userId) { 16179 if (filter.countActions() != 1) { 16180 throw new IllegalArgumentException( 16181 "replacePreferredActivity expects filter to have only 1 action."); 16182 } 16183 if (filter.countDataAuthorities() != 0 16184 || filter.countDataPaths() != 0 16185 || filter.countDataSchemes() > 1 16186 || filter.countDataTypes() != 0) { 16187 throw new IllegalArgumentException( 16188 "replacePreferredActivity expects filter to have no data authorities, " + 16189 "paths, or types; and at most one scheme."); 16190 } 16191 16192 final int callingUid = Binder.getCallingUid(); 16193 enforceCrossUserPermission(callingUid, userId, 16194 true /* requireFullPermission */, false /* checkShell */, 16195 "replace preferred activity"); 16196 synchronized (mPackages) { 16197 if (mContext.checkCallingOrSelfPermission( 16198 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16199 != PackageManager.PERMISSION_GRANTED) { 16200 if (getUidTargetSdkVersionLockedLPr(callingUid) 16201 < Build.VERSION_CODES.FROYO) { 16202 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16203 + Binder.getCallingUid()); 16204 return; 16205 } 16206 mContext.enforceCallingOrSelfPermission( 16207 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16208 } 16209 16210 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16211 if (pir != null) { 16212 // Get all of the existing entries that exactly match this filter. 16213 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16214 if (existing != null && existing.size() == 1) { 16215 PreferredActivity cur = existing.get(0); 16216 if (DEBUG_PREFERRED) { 16217 Slog.i(TAG, "Checking replace of preferred:"); 16218 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16219 if (!cur.mPref.mAlways) { 16220 Slog.i(TAG, " -- CUR; not mAlways!"); 16221 } else { 16222 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16223 Slog.i(TAG, " -- CUR: mSet=" 16224 + Arrays.toString(cur.mPref.mSetComponents)); 16225 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16226 Slog.i(TAG, " -- NEW: mMatch=" 16227 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16228 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16229 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16230 } 16231 } 16232 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16233 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16234 && cur.mPref.sameSet(set)) { 16235 // Setting the preferred activity to what it happens to be already 16236 if (DEBUG_PREFERRED) { 16237 Slog.i(TAG, "Replacing with same preferred activity " 16238 + cur.mPref.mShortComponent + " for user " 16239 + userId + ":"); 16240 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16241 } 16242 return; 16243 } 16244 } 16245 16246 if (existing != null) { 16247 if (DEBUG_PREFERRED) { 16248 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16249 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16250 } 16251 for (int i = 0; i < existing.size(); i++) { 16252 PreferredActivity pa = existing.get(i); 16253 if (DEBUG_PREFERRED) { 16254 Slog.i(TAG, "Removing existing preferred activity " 16255 + pa.mPref.mComponent + ":"); 16256 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16257 } 16258 pir.removeFilter(pa); 16259 } 16260 } 16261 } 16262 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16263 "Replacing preferred"); 16264 } 16265 } 16266 16267 @Override 16268 public void clearPackagePreferredActivities(String packageName) { 16269 final int uid = Binder.getCallingUid(); 16270 // writer 16271 synchronized (mPackages) { 16272 PackageParser.Package pkg = mPackages.get(packageName); 16273 if (pkg == null || pkg.applicationInfo.uid != uid) { 16274 if (mContext.checkCallingOrSelfPermission( 16275 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16276 != PackageManager.PERMISSION_GRANTED) { 16277 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16278 < Build.VERSION_CODES.FROYO) { 16279 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16280 + Binder.getCallingUid()); 16281 return; 16282 } 16283 mContext.enforceCallingOrSelfPermission( 16284 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16285 } 16286 } 16287 16288 int user = UserHandle.getCallingUserId(); 16289 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16290 scheduleWritePackageRestrictionsLocked(user); 16291 } 16292 } 16293 } 16294 16295 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16296 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16297 ArrayList<PreferredActivity> removed = null; 16298 boolean changed = false; 16299 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16300 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16301 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16302 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16303 continue; 16304 } 16305 Iterator<PreferredActivity> it = pir.filterIterator(); 16306 while (it.hasNext()) { 16307 PreferredActivity pa = it.next(); 16308 // Mark entry for removal only if it matches the package name 16309 // and the entry is of type "always". 16310 if (packageName == null || 16311 (pa.mPref.mComponent.getPackageName().equals(packageName) 16312 && pa.mPref.mAlways)) { 16313 if (removed == null) { 16314 removed = new ArrayList<PreferredActivity>(); 16315 } 16316 removed.add(pa); 16317 } 16318 } 16319 if (removed != null) { 16320 for (int j=0; j<removed.size(); j++) { 16321 PreferredActivity pa = removed.get(j); 16322 pir.removeFilter(pa); 16323 } 16324 changed = true; 16325 } 16326 } 16327 return changed; 16328 } 16329 16330 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16331 private void clearIntentFilterVerificationsLPw(int userId) { 16332 final int packageCount = mPackages.size(); 16333 for (int i = 0; i < packageCount; i++) { 16334 PackageParser.Package pkg = mPackages.valueAt(i); 16335 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16336 } 16337 } 16338 16339 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16340 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16341 if (userId == UserHandle.USER_ALL) { 16342 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16343 sUserManager.getUserIds())) { 16344 for (int oneUserId : sUserManager.getUserIds()) { 16345 scheduleWritePackageRestrictionsLocked(oneUserId); 16346 } 16347 } 16348 } else { 16349 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16350 scheduleWritePackageRestrictionsLocked(userId); 16351 } 16352 } 16353 } 16354 16355 void clearDefaultBrowserIfNeeded(String packageName) { 16356 for (int oneUserId : sUserManager.getUserIds()) { 16357 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16358 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16359 if (packageName.equals(defaultBrowserPackageName)) { 16360 setDefaultBrowserPackageName(null, oneUserId); 16361 } 16362 } 16363 } 16364 16365 @Override 16366 public void resetApplicationPreferences(int userId) { 16367 mContext.enforceCallingOrSelfPermission( 16368 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16369 // writer 16370 synchronized (mPackages) { 16371 final long identity = Binder.clearCallingIdentity(); 16372 try { 16373 clearPackagePreferredActivitiesLPw(null, userId); 16374 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16375 // TODO: We have to reset the default SMS and Phone. This requires 16376 // significant refactoring to keep all default apps in the package 16377 // manager (cleaner but more work) or have the services provide 16378 // callbacks to the package manager to request a default app reset. 16379 applyFactoryDefaultBrowserLPw(userId); 16380 clearIntentFilterVerificationsLPw(userId); 16381 primeDomainVerificationsLPw(userId); 16382 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16383 scheduleWritePackageRestrictionsLocked(userId); 16384 } finally { 16385 Binder.restoreCallingIdentity(identity); 16386 } 16387 } 16388 } 16389 16390 @Override 16391 public int getPreferredActivities(List<IntentFilter> outFilters, 16392 List<ComponentName> outActivities, String packageName) { 16393 16394 int num = 0; 16395 final int userId = UserHandle.getCallingUserId(); 16396 // reader 16397 synchronized (mPackages) { 16398 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16399 if (pir != null) { 16400 final Iterator<PreferredActivity> it = pir.filterIterator(); 16401 while (it.hasNext()) { 16402 final PreferredActivity pa = it.next(); 16403 if (packageName == null 16404 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16405 && pa.mPref.mAlways)) { 16406 if (outFilters != null) { 16407 outFilters.add(new IntentFilter(pa)); 16408 } 16409 if (outActivities != null) { 16410 outActivities.add(pa.mPref.mComponent); 16411 } 16412 } 16413 } 16414 } 16415 } 16416 16417 return num; 16418 } 16419 16420 @Override 16421 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16422 int userId) { 16423 int callingUid = Binder.getCallingUid(); 16424 if (callingUid != Process.SYSTEM_UID) { 16425 throw new SecurityException( 16426 "addPersistentPreferredActivity can only be run by the system"); 16427 } 16428 if (filter.countActions() == 0) { 16429 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16430 return; 16431 } 16432 synchronized (mPackages) { 16433 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16434 ":"); 16435 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16436 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16437 new PersistentPreferredActivity(filter, activity)); 16438 scheduleWritePackageRestrictionsLocked(userId); 16439 } 16440 } 16441 16442 @Override 16443 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16444 int callingUid = Binder.getCallingUid(); 16445 if (callingUid != Process.SYSTEM_UID) { 16446 throw new SecurityException( 16447 "clearPackagePersistentPreferredActivities can only be run by the system"); 16448 } 16449 ArrayList<PersistentPreferredActivity> removed = null; 16450 boolean changed = false; 16451 synchronized (mPackages) { 16452 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16453 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16454 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16455 .valueAt(i); 16456 if (userId != thisUserId) { 16457 continue; 16458 } 16459 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16460 while (it.hasNext()) { 16461 PersistentPreferredActivity ppa = it.next(); 16462 // Mark entry for removal only if it matches the package name. 16463 if (ppa.mComponent.getPackageName().equals(packageName)) { 16464 if (removed == null) { 16465 removed = new ArrayList<PersistentPreferredActivity>(); 16466 } 16467 removed.add(ppa); 16468 } 16469 } 16470 if (removed != null) { 16471 for (int j=0; j<removed.size(); j++) { 16472 PersistentPreferredActivity ppa = removed.get(j); 16473 ppir.removeFilter(ppa); 16474 } 16475 changed = true; 16476 } 16477 } 16478 16479 if (changed) { 16480 scheduleWritePackageRestrictionsLocked(userId); 16481 } 16482 } 16483 } 16484 16485 /** 16486 * Common machinery for picking apart a restored XML blob and passing 16487 * it to a caller-supplied functor to be applied to the running system. 16488 */ 16489 private void restoreFromXml(XmlPullParser parser, int userId, 16490 String expectedStartTag, BlobXmlRestorer functor) 16491 throws IOException, XmlPullParserException { 16492 int type; 16493 while ((type = parser.next()) != XmlPullParser.START_TAG 16494 && type != XmlPullParser.END_DOCUMENT) { 16495 } 16496 if (type != XmlPullParser.START_TAG) { 16497 // oops didn't find a start tag?! 16498 if (DEBUG_BACKUP) { 16499 Slog.e(TAG, "Didn't find start tag during restore"); 16500 } 16501 return; 16502 } 16503Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16504 // this is supposed to be TAG_PREFERRED_BACKUP 16505 if (!expectedStartTag.equals(parser.getName())) { 16506 if (DEBUG_BACKUP) { 16507 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16508 } 16509 return; 16510 } 16511 16512 // skip interfering stuff, then we're aligned with the backing implementation 16513 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16514Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16515 functor.apply(parser, userId); 16516 } 16517 16518 private interface BlobXmlRestorer { 16519 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16520 } 16521 16522 /** 16523 * Non-Binder method, support for the backup/restore mechanism: write the 16524 * full set of preferred activities in its canonical XML format. Returns the 16525 * XML output as a byte array, or null if there is none. 16526 */ 16527 @Override 16528 public byte[] getPreferredActivityBackup(int userId) { 16529 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16530 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16531 } 16532 16533 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16534 try { 16535 final XmlSerializer serializer = new FastXmlSerializer(); 16536 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16537 serializer.startDocument(null, true); 16538 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16539 16540 synchronized (mPackages) { 16541 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16542 } 16543 16544 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16545 serializer.endDocument(); 16546 serializer.flush(); 16547 } catch (Exception e) { 16548 if (DEBUG_BACKUP) { 16549 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16550 } 16551 return null; 16552 } 16553 16554 return dataStream.toByteArray(); 16555 } 16556 16557 @Override 16558 public void restorePreferredActivities(byte[] backup, int userId) { 16559 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16560 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16561 } 16562 16563 try { 16564 final XmlPullParser parser = Xml.newPullParser(); 16565 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16566 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16567 new BlobXmlRestorer() { 16568 @Override 16569 public void apply(XmlPullParser parser, int userId) 16570 throws XmlPullParserException, IOException { 16571 synchronized (mPackages) { 16572 mSettings.readPreferredActivitiesLPw(parser, userId); 16573 } 16574 } 16575 } ); 16576 } catch (Exception e) { 16577 if (DEBUG_BACKUP) { 16578 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16579 } 16580 } 16581 } 16582 16583 /** 16584 * Non-Binder method, support for the backup/restore mechanism: write the 16585 * default browser (etc) settings in its canonical XML format. Returns the default 16586 * browser XML representation as a byte array, or null if there is none. 16587 */ 16588 @Override 16589 public byte[] getDefaultAppsBackup(int userId) { 16590 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16591 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16592 } 16593 16594 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16595 try { 16596 final XmlSerializer serializer = new FastXmlSerializer(); 16597 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16598 serializer.startDocument(null, true); 16599 serializer.startTag(null, TAG_DEFAULT_APPS); 16600 16601 synchronized (mPackages) { 16602 mSettings.writeDefaultAppsLPr(serializer, userId); 16603 } 16604 16605 serializer.endTag(null, TAG_DEFAULT_APPS); 16606 serializer.endDocument(); 16607 serializer.flush(); 16608 } catch (Exception e) { 16609 if (DEBUG_BACKUP) { 16610 Slog.e(TAG, "Unable to write default apps for backup", e); 16611 } 16612 return null; 16613 } 16614 16615 return dataStream.toByteArray(); 16616 } 16617 16618 @Override 16619 public void restoreDefaultApps(byte[] backup, int userId) { 16620 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16621 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16622 } 16623 16624 try { 16625 final XmlPullParser parser = Xml.newPullParser(); 16626 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16627 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16628 new BlobXmlRestorer() { 16629 @Override 16630 public void apply(XmlPullParser parser, int userId) 16631 throws XmlPullParserException, IOException { 16632 synchronized (mPackages) { 16633 mSettings.readDefaultAppsLPw(parser, userId); 16634 } 16635 } 16636 } ); 16637 } catch (Exception e) { 16638 if (DEBUG_BACKUP) { 16639 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16640 } 16641 } 16642 } 16643 16644 @Override 16645 public byte[] getIntentFilterVerificationBackup(int userId) { 16646 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16647 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16648 } 16649 16650 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16651 try { 16652 final XmlSerializer serializer = new FastXmlSerializer(); 16653 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16654 serializer.startDocument(null, true); 16655 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16656 16657 synchronized (mPackages) { 16658 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16659 } 16660 16661 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16662 serializer.endDocument(); 16663 serializer.flush(); 16664 } catch (Exception e) { 16665 if (DEBUG_BACKUP) { 16666 Slog.e(TAG, "Unable to write default apps for backup", e); 16667 } 16668 return null; 16669 } 16670 16671 return dataStream.toByteArray(); 16672 } 16673 16674 @Override 16675 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16676 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16677 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16678 } 16679 16680 try { 16681 final XmlPullParser parser = Xml.newPullParser(); 16682 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16683 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16684 new BlobXmlRestorer() { 16685 @Override 16686 public void apply(XmlPullParser parser, int userId) 16687 throws XmlPullParserException, IOException { 16688 synchronized (mPackages) { 16689 mSettings.readAllDomainVerificationsLPr(parser, userId); 16690 mSettings.writeLPr(); 16691 } 16692 } 16693 } ); 16694 } catch (Exception e) { 16695 if (DEBUG_BACKUP) { 16696 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16697 } 16698 } 16699 } 16700 16701 @Override 16702 public byte[] getPermissionGrantBackup(int userId) { 16703 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16704 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16705 } 16706 16707 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16708 try { 16709 final XmlSerializer serializer = new FastXmlSerializer(); 16710 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16711 serializer.startDocument(null, true); 16712 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16713 16714 synchronized (mPackages) { 16715 serializeRuntimePermissionGrantsLPr(serializer, userId); 16716 } 16717 16718 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16719 serializer.endDocument(); 16720 serializer.flush(); 16721 } catch (Exception e) { 16722 if (DEBUG_BACKUP) { 16723 Slog.e(TAG, "Unable to write default apps for backup", e); 16724 } 16725 return null; 16726 } 16727 16728 return dataStream.toByteArray(); 16729 } 16730 16731 @Override 16732 public void restorePermissionGrants(byte[] backup, int userId) { 16733 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16734 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16735 } 16736 16737 try { 16738 final XmlPullParser parser = Xml.newPullParser(); 16739 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16740 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16741 new BlobXmlRestorer() { 16742 @Override 16743 public void apply(XmlPullParser parser, int userId) 16744 throws XmlPullParserException, IOException { 16745 synchronized (mPackages) { 16746 processRestoredPermissionGrantsLPr(parser, userId); 16747 } 16748 } 16749 } ); 16750 } catch (Exception e) { 16751 if (DEBUG_BACKUP) { 16752 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16753 } 16754 } 16755 } 16756 16757 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16758 throws IOException { 16759 serializer.startTag(null, TAG_ALL_GRANTS); 16760 16761 final int N = mSettings.mPackages.size(); 16762 for (int i = 0; i < N; i++) { 16763 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16764 boolean pkgGrantsKnown = false; 16765 16766 PermissionsState packagePerms = ps.getPermissionsState(); 16767 16768 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16769 final int grantFlags = state.getFlags(); 16770 // only look at grants that are not system/policy fixed 16771 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16772 final boolean isGranted = state.isGranted(); 16773 // And only back up the user-twiddled state bits 16774 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16775 final String packageName = mSettings.mPackages.keyAt(i); 16776 if (!pkgGrantsKnown) { 16777 serializer.startTag(null, TAG_GRANT); 16778 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16779 pkgGrantsKnown = true; 16780 } 16781 16782 final boolean userSet = 16783 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16784 final boolean userFixed = 16785 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16786 final boolean revoke = 16787 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16788 16789 serializer.startTag(null, TAG_PERMISSION); 16790 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16791 if (isGranted) { 16792 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16793 } 16794 if (userSet) { 16795 serializer.attribute(null, ATTR_USER_SET, "true"); 16796 } 16797 if (userFixed) { 16798 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16799 } 16800 if (revoke) { 16801 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16802 } 16803 serializer.endTag(null, TAG_PERMISSION); 16804 } 16805 } 16806 } 16807 16808 if (pkgGrantsKnown) { 16809 serializer.endTag(null, TAG_GRANT); 16810 } 16811 } 16812 16813 serializer.endTag(null, TAG_ALL_GRANTS); 16814 } 16815 16816 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16817 throws XmlPullParserException, IOException { 16818 String pkgName = null; 16819 int outerDepth = parser.getDepth(); 16820 int type; 16821 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16822 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16823 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16824 continue; 16825 } 16826 16827 final String tagName = parser.getName(); 16828 if (tagName.equals(TAG_GRANT)) { 16829 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16830 if (DEBUG_BACKUP) { 16831 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16832 } 16833 } else if (tagName.equals(TAG_PERMISSION)) { 16834 16835 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16836 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16837 16838 int newFlagSet = 0; 16839 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16840 newFlagSet |= FLAG_PERMISSION_USER_SET; 16841 } 16842 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16843 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16844 } 16845 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16846 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16847 } 16848 if (DEBUG_BACKUP) { 16849 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16850 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16851 } 16852 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16853 if (ps != null) { 16854 // Already installed so we apply the grant immediately 16855 if (DEBUG_BACKUP) { 16856 Slog.v(TAG, " + already installed; applying"); 16857 } 16858 PermissionsState perms = ps.getPermissionsState(); 16859 BasePermission bp = mSettings.mPermissions.get(permName); 16860 if (bp != null) { 16861 if (isGranted) { 16862 perms.grantRuntimePermission(bp, userId); 16863 } 16864 if (newFlagSet != 0) { 16865 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16866 } 16867 } 16868 } else { 16869 // Need to wait for post-restore install to apply the grant 16870 if (DEBUG_BACKUP) { 16871 Slog.v(TAG, " - not yet installed; saving for later"); 16872 } 16873 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16874 isGranted, newFlagSet, userId); 16875 } 16876 } else { 16877 PackageManagerService.reportSettingsProblem(Log.WARN, 16878 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16879 XmlUtils.skipCurrentTag(parser); 16880 } 16881 } 16882 16883 scheduleWriteSettingsLocked(); 16884 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16885 } 16886 16887 @Override 16888 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16889 int sourceUserId, int targetUserId, int flags) { 16890 mContext.enforceCallingOrSelfPermission( 16891 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16892 int callingUid = Binder.getCallingUid(); 16893 enforceOwnerRights(ownerPackage, callingUid); 16894 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16895 if (intentFilter.countActions() == 0) { 16896 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16897 return; 16898 } 16899 synchronized (mPackages) { 16900 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16901 ownerPackage, targetUserId, flags); 16902 CrossProfileIntentResolver resolver = 16903 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16904 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16905 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16906 if (existing != null) { 16907 int size = existing.size(); 16908 for (int i = 0; i < size; i++) { 16909 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16910 return; 16911 } 16912 } 16913 } 16914 resolver.addFilter(newFilter); 16915 scheduleWritePackageRestrictionsLocked(sourceUserId); 16916 } 16917 } 16918 16919 @Override 16920 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16921 mContext.enforceCallingOrSelfPermission( 16922 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16923 int callingUid = Binder.getCallingUid(); 16924 enforceOwnerRights(ownerPackage, callingUid); 16925 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16926 synchronized (mPackages) { 16927 CrossProfileIntentResolver resolver = 16928 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16929 ArraySet<CrossProfileIntentFilter> set = 16930 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16931 for (CrossProfileIntentFilter filter : set) { 16932 if (filter.getOwnerPackage().equals(ownerPackage)) { 16933 resolver.removeFilter(filter); 16934 } 16935 } 16936 scheduleWritePackageRestrictionsLocked(sourceUserId); 16937 } 16938 } 16939 16940 // Enforcing that callingUid is owning pkg on userId 16941 private void enforceOwnerRights(String pkg, int callingUid) { 16942 // The system owns everything. 16943 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16944 return; 16945 } 16946 int callingUserId = UserHandle.getUserId(callingUid); 16947 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16948 if (pi == null) { 16949 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16950 + callingUserId); 16951 } 16952 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16953 throw new SecurityException("Calling uid " + callingUid 16954 + " does not own package " + pkg); 16955 } 16956 } 16957 16958 @Override 16959 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16960 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16961 } 16962 16963 private Intent getHomeIntent() { 16964 Intent intent = new Intent(Intent.ACTION_MAIN); 16965 intent.addCategory(Intent.CATEGORY_HOME); 16966 return intent; 16967 } 16968 16969 private IntentFilter getHomeFilter() { 16970 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16971 filter.addCategory(Intent.CATEGORY_HOME); 16972 filter.addCategory(Intent.CATEGORY_DEFAULT); 16973 return filter; 16974 } 16975 16976 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16977 int userId) { 16978 Intent intent = getHomeIntent(); 16979 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16980 PackageManager.GET_META_DATA, userId); 16981 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16982 true, false, false, userId); 16983 16984 allHomeCandidates.clear(); 16985 if (list != null) { 16986 for (ResolveInfo ri : list) { 16987 allHomeCandidates.add(ri); 16988 } 16989 } 16990 return (preferred == null || preferred.activityInfo == null) 16991 ? null 16992 : new ComponentName(preferred.activityInfo.packageName, 16993 preferred.activityInfo.name); 16994 } 16995 16996 @Override 16997 public void setHomeActivity(ComponentName comp, int userId) { 16998 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16999 getHomeActivitiesAsUser(homeActivities, userId); 17000 17001 boolean found = false; 17002 17003 final int size = homeActivities.size(); 17004 final ComponentName[] set = new ComponentName[size]; 17005 for (int i = 0; i < size; i++) { 17006 final ResolveInfo candidate = homeActivities.get(i); 17007 final ActivityInfo info = candidate.activityInfo; 17008 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17009 set[i] = activityName; 17010 if (!found && activityName.equals(comp)) { 17011 found = true; 17012 } 17013 } 17014 if (!found) { 17015 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17016 + userId); 17017 } 17018 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17019 set, comp, userId); 17020 } 17021 17022 private @Nullable String getSetupWizardPackageName() { 17023 final Intent intent = new Intent(Intent.ACTION_MAIN); 17024 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17025 17026 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17027 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17028 | MATCH_DISABLED_COMPONENTS, 17029 UserHandle.myUserId()); 17030 if (matches.size() == 1) { 17031 return matches.get(0).getComponentInfo().packageName; 17032 } else { 17033 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17034 + ": matches=" + matches); 17035 return null; 17036 } 17037 } 17038 17039 @Override 17040 public void setApplicationEnabledSetting(String appPackageName, 17041 int newState, int flags, int userId, String callingPackage) { 17042 if (!sUserManager.exists(userId)) return; 17043 if (callingPackage == null) { 17044 callingPackage = Integer.toString(Binder.getCallingUid()); 17045 } 17046 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17047 } 17048 17049 @Override 17050 public void setComponentEnabledSetting(ComponentName componentName, 17051 int newState, int flags, int userId) { 17052 if (!sUserManager.exists(userId)) return; 17053 setEnabledSetting(componentName.getPackageName(), 17054 componentName.getClassName(), newState, flags, userId, null); 17055 } 17056 17057 private void setEnabledSetting(final String packageName, String className, int newState, 17058 final int flags, int userId, String callingPackage) { 17059 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17060 || newState == COMPONENT_ENABLED_STATE_ENABLED 17061 || newState == COMPONENT_ENABLED_STATE_DISABLED 17062 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17063 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17064 throw new IllegalArgumentException("Invalid new component state: " 17065 + newState); 17066 } 17067 PackageSetting pkgSetting; 17068 final int uid = Binder.getCallingUid(); 17069 final int permission; 17070 if (uid == Process.SYSTEM_UID) { 17071 permission = PackageManager.PERMISSION_GRANTED; 17072 } else { 17073 permission = mContext.checkCallingOrSelfPermission( 17074 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17075 } 17076 enforceCrossUserPermission(uid, userId, 17077 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17078 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17079 boolean sendNow = false; 17080 boolean isApp = (className == null); 17081 String componentName = isApp ? packageName : className; 17082 int packageUid = -1; 17083 ArrayList<String> components; 17084 17085 // writer 17086 synchronized (mPackages) { 17087 pkgSetting = mSettings.mPackages.get(packageName); 17088 if (pkgSetting == null) { 17089 if (className == null) { 17090 throw new IllegalArgumentException("Unknown package: " + packageName); 17091 } 17092 throw new IllegalArgumentException( 17093 "Unknown component: " + packageName + "/" + className); 17094 } 17095 // Allow root and verify that userId is not being specified by a different user 17096 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17097 throw new SecurityException( 17098 "Permission Denial: attempt to change component state from pid=" 17099 + Binder.getCallingPid() 17100 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17101 } 17102 if (className == null) { 17103 // We're dealing with an application/package level state change 17104 if (pkgSetting.getEnabled(userId) == newState) { 17105 // Nothing to do 17106 return; 17107 } 17108 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17109 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17110 // Don't care about who enables an app. 17111 callingPackage = null; 17112 } 17113 pkgSetting.setEnabled(newState, userId, callingPackage); 17114 // pkgSetting.pkg.mSetEnabled = newState; 17115 } else { 17116 // We're dealing with a component level state change 17117 // First, verify that this is a valid class name. 17118 PackageParser.Package pkg = pkgSetting.pkg; 17119 if (pkg == null || !pkg.hasComponentClassName(className)) { 17120 if (pkg != null && 17121 pkg.applicationInfo.targetSdkVersion >= 17122 Build.VERSION_CODES.JELLY_BEAN) { 17123 throw new IllegalArgumentException("Component class " + className 17124 + " does not exist in " + packageName); 17125 } else { 17126 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17127 + className + " does not exist in " + packageName); 17128 } 17129 } 17130 switch (newState) { 17131 case COMPONENT_ENABLED_STATE_ENABLED: 17132 if (!pkgSetting.enableComponentLPw(className, userId)) { 17133 return; 17134 } 17135 break; 17136 case COMPONENT_ENABLED_STATE_DISABLED: 17137 if (!pkgSetting.disableComponentLPw(className, userId)) { 17138 return; 17139 } 17140 break; 17141 case COMPONENT_ENABLED_STATE_DEFAULT: 17142 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17143 return; 17144 } 17145 break; 17146 default: 17147 Slog.e(TAG, "Invalid new component state: " + newState); 17148 return; 17149 } 17150 } 17151 scheduleWritePackageRestrictionsLocked(userId); 17152 components = mPendingBroadcasts.get(userId, packageName); 17153 final boolean newPackage = components == null; 17154 if (newPackage) { 17155 components = new ArrayList<String>(); 17156 } 17157 if (!components.contains(componentName)) { 17158 components.add(componentName); 17159 } 17160 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17161 sendNow = true; 17162 // Purge entry from pending broadcast list if another one exists already 17163 // since we are sending one right away. 17164 mPendingBroadcasts.remove(userId, packageName); 17165 } else { 17166 if (newPackage) { 17167 mPendingBroadcasts.put(userId, packageName, components); 17168 } 17169 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17170 // Schedule a message 17171 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17172 } 17173 } 17174 } 17175 17176 long callingId = Binder.clearCallingIdentity(); 17177 try { 17178 if (sendNow) { 17179 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17180 sendPackageChangedBroadcast(packageName, 17181 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17182 } 17183 } finally { 17184 Binder.restoreCallingIdentity(callingId); 17185 } 17186 } 17187 17188 @Override 17189 public void flushPackageRestrictionsAsUser(int userId) { 17190 if (!sUserManager.exists(userId)) { 17191 return; 17192 } 17193 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17194 false /* checkShell */, "flushPackageRestrictions"); 17195 synchronized (mPackages) { 17196 mSettings.writePackageRestrictionsLPr(userId); 17197 mDirtyUsers.remove(userId); 17198 if (mDirtyUsers.isEmpty()) { 17199 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17200 } 17201 } 17202 } 17203 17204 private void sendPackageChangedBroadcast(String packageName, 17205 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17206 if (DEBUG_INSTALL) 17207 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17208 + componentNames); 17209 Bundle extras = new Bundle(4); 17210 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17211 String nameList[] = new String[componentNames.size()]; 17212 componentNames.toArray(nameList); 17213 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17214 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17215 extras.putInt(Intent.EXTRA_UID, packageUid); 17216 // If this is not reporting a change of the overall package, then only send it 17217 // to registered receivers. We don't want to launch a swath of apps for every 17218 // little component state change. 17219 final int flags = !componentNames.contains(packageName) 17220 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17221 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17222 new int[] {UserHandle.getUserId(packageUid)}); 17223 } 17224 17225 @Override 17226 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17227 if (!sUserManager.exists(userId)) return; 17228 final int uid = Binder.getCallingUid(); 17229 final int permission = mContext.checkCallingOrSelfPermission( 17230 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17231 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17232 enforceCrossUserPermission(uid, userId, 17233 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17234 // writer 17235 synchronized (mPackages) { 17236 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17237 allowedByPermission, uid, userId)) { 17238 scheduleWritePackageRestrictionsLocked(userId); 17239 } 17240 } 17241 } 17242 17243 @Override 17244 public String getInstallerPackageName(String packageName) { 17245 // reader 17246 synchronized (mPackages) { 17247 return mSettings.getInstallerPackageNameLPr(packageName); 17248 } 17249 } 17250 17251 @Override 17252 public int getApplicationEnabledSetting(String packageName, int userId) { 17253 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17254 int uid = Binder.getCallingUid(); 17255 enforceCrossUserPermission(uid, userId, 17256 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17257 // reader 17258 synchronized (mPackages) { 17259 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17260 } 17261 } 17262 17263 @Override 17264 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17265 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17266 int uid = Binder.getCallingUid(); 17267 enforceCrossUserPermission(uid, userId, 17268 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17269 // reader 17270 synchronized (mPackages) { 17271 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17272 } 17273 } 17274 17275 @Override 17276 public void enterSafeMode() { 17277 enforceSystemOrRoot("Only the system can request entering safe mode"); 17278 17279 if (!mSystemReady) { 17280 mSafeMode = true; 17281 } 17282 } 17283 17284 @Override 17285 public void systemReady() { 17286 mSystemReady = true; 17287 17288 // Read the compatibilty setting when the system is ready. 17289 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17290 mContext.getContentResolver(), 17291 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17292 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17293 if (DEBUG_SETTINGS) { 17294 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17295 } 17296 17297 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17298 17299 synchronized (mPackages) { 17300 // Verify that all of the preferred activity components actually 17301 // exist. It is possible for applications to be updated and at 17302 // that point remove a previously declared activity component that 17303 // had been set as a preferred activity. We try to clean this up 17304 // the next time we encounter that preferred activity, but it is 17305 // possible for the user flow to never be able to return to that 17306 // situation so here we do a sanity check to make sure we haven't 17307 // left any junk around. 17308 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17309 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17310 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17311 removed.clear(); 17312 for (PreferredActivity pa : pir.filterSet()) { 17313 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17314 removed.add(pa); 17315 } 17316 } 17317 if (removed.size() > 0) { 17318 for (int r=0; r<removed.size(); r++) { 17319 PreferredActivity pa = removed.get(r); 17320 Slog.w(TAG, "Removing dangling preferred activity: " 17321 + pa.mPref.mComponent); 17322 pir.removeFilter(pa); 17323 } 17324 mSettings.writePackageRestrictionsLPr( 17325 mSettings.mPreferredActivities.keyAt(i)); 17326 } 17327 } 17328 17329 for (int userId : UserManagerService.getInstance().getUserIds()) { 17330 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17331 grantPermissionsUserIds = ArrayUtils.appendInt( 17332 grantPermissionsUserIds, userId); 17333 } 17334 } 17335 } 17336 sUserManager.systemReady(); 17337 17338 // If we upgraded grant all default permissions before kicking off. 17339 for (int userId : grantPermissionsUserIds) { 17340 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17341 } 17342 17343 // Kick off any messages waiting for system ready 17344 if (mPostSystemReadyMessages != null) { 17345 for (Message msg : mPostSystemReadyMessages) { 17346 msg.sendToTarget(); 17347 } 17348 mPostSystemReadyMessages = null; 17349 } 17350 17351 // Watch for external volumes that come and go over time 17352 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17353 storage.registerListener(mStorageListener); 17354 17355 mInstallerService.systemReady(); 17356 mPackageDexOptimizer.systemReady(); 17357 17358 MountServiceInternal mountServiceInternal = LocalServices.getService( 17359 MountServiceInternal.class); 17360 mountServiceInternal.addExternalStoragePolicy( 17361 new MountServiceInternal.ExternalStorageMountPolicy() { 17362 @Override 17363 public int getMountMode(int uid, String packageName) { 17364 if (Process.isIsolated(uid)) { 17365 return Zygote.MOUNT_EXTERNAL_NONE; 17366 } 17367 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17368 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17369 } 17370 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17371 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17372 } 17373 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17374 return Zygote.MOUNT_EXTERNAL_READ; 17375 } 17376 return Zygote.MOUNT_EXTERNAL_WRITE; 17377 } 17378 17379 @Override 17380 public boolean hasExternalStorage(int uid, String packageName) { 17381 return true; 17382 } 17383 }); 17384 17385 // Now that we're mostly running, clean up stale users and apps 17386 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17387 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17388 } 17389 17390 @Override 17391 public boolean isSafeMode() { 17392 return mSafeMode; 17393 } 17394 17395 @Override 17396 public boolean hasSystemUidErrors() { 17397 return mHasSystemUidErrors; 17398 } 17399 17400 static String arrayToString(int[] array) { 17401 StringBuffer buf = new StringBuffer(128); 17402 buf.append('['); 17403 if (array != null) { 17404 for (int i=0; i<array.length; i++) { 17405 if (i > 0) buf.append(", "); 17406 buf.append(array[i]); 17407 } 17408 } 17409 buf.append(']'); 17410 return buf.toString(); 17411 } 17412 17413 static class DumpState { 17414 public static final int DUMP_LIBS = 1 << 0; 17415 public static final int DUMP_FEATURES = 1 << 1; 17416 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17417 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17418 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17419 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17420 public static final int DUMP_PERMISSIONS = 1 << 6; 17421 public static final int DUMP_PACKAGES = 1 << 7; 17422 public static final int DUMP_SHARED_USERS = 1 << 8; 17423 public static final int DUMP_MESSAGES = 1 << 9; 17424 public static final int DUMP_PROVIDERS = 1 << 10; 17425 public static final int DUMP_VERIFIERS = 1 << 11; 17426 public static final int DUMP_PREFERRED = 1 << 12; 17427 public static final int DUMP_PREFERRED_XML = 1 << 13; 17428 public static final int DUMP_KEYSETS = 1 << 14; 17429 public static final int DUMP_VERSION = 1 << 15; 17430 public static final int DUMP_INSTALLS = 1 << 16; 17431 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17432 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17433 public static final int DUMP_FROZEN = 1 << 19; 17434 17435 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17436 17437 private int mTypes; 17438 17439 private int mOptions; 17440 17441 private boolean mTitlePrinted; 17442 17443 private SharedUserSetting mSharedUser; 17444 17445 public boolean isDumping(int type) { 17446 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17447 return true; 17448 } 17449 17450 return (mTypes & type) != 0; 17451 } 17452 17453 public void setDump(int type) { 17454 mTypes |= type; 17455 } 17456 17457 public boolean isOptionEnabled(int option) { 17458 return (mOptions & option) != 0; 17459 } 17460 17461 public void setOptionEnabled(int option) { 17462 mOptions |= option; 17463 } 17464 17465 public boolean onTitlePrinted() { 17466 final boolean printed = mTitlePrinted; 17467 mTitlePrinted = true; 17468 return printed; 17469 } 17470 17471 public boolean getTitlePrinted() { 17472 return mTitlePrinted; 17473 } 17474 17475 public void setTitlePrinted(boolean enabled) { 17476 mTitlePrinted = enabled; 17477 } 17478 17479 public SharedUserSetting getSharedUser() { 17480 return mSharedUser; 17481 } 17482 17483 public void setSharedUser(SharedUserSetting user) { 17484 mSharedUser = user; 17485 } 17486 } 17487 17488 @Override 17489 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17490 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17491 (new PackageManagerShellCommand(this)).exec( 17492 this, in, out, err, args, resultReceiver); 17493 } 17494 17495 @Override 17496 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17497 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17498 != PackageManager.PERMISSION_GRANTED) { 17499 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17500 + Binder.getCallingPid() 17501 + ", uid=" + Binder.getCallingUid() 17502 + " without permission " 17503 + android.Manifest.permission.DUMP); 17504 return; 17505 } 17506 17507 DumpState dumpState = new DumpState(); 17508 boolean fullPreferred = false; 17509 boolean checkin = false; 17510 17511 String packageName = null; 17512 ArraySet<String> permissionNames = null; 17513 17514 int opti = 0; 17515 while (opti < args.length) { 17516 String opt = args[opti]; 17517 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17518 break; 17519 } 17520 opti++; 17521 17522 if ("-a".equals(opt)) { 17523 // Right now we only know how to print all. 17524 } else if ("-h".equals(opt)) { 17525 pw.println("Package manager dump options:"); 17526 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17527 pw.println(" --checkin: dump for a checkin"); 17528 pw.println(" -f: print details of intent filters"); 17529 pw.println(" -h: print this help"); 17530 pw.println(" cmd may be one of:"); 17531 pw.println(" l[ibraries]: list known shared libraries"); 17532 pw.println(" f[eatures]: list device features"); 17533 pw.println(" k[eysets]: print known keysets"); 17534 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17535 pw.println(" perm[issions]: dump permissions"); 17536 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17537 pw.println(" pref[erred]: print preferred package settings"); 17538 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17539 pw.println(" prov[iders]: dump content providers"); 17540 pw.println(" p[ackages]: dump installed packages"); 17541 pw.println(" s[hared-users]: dump shared user IDs"); 17542 pw.println(" m[essages]: print collected runtime messages"); 17543 pw.println(" v[erifiers]: print package verifier info"); 17544 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17545 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17546 pw.println(" version: print database version info"); 17547 pw.println(" write: write current settings now"); 17548 pw.println(" installs: details about install sessions"); 17549 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17550 pw.println(" <package.name>: info about given package"); 17551 return; 17552 } else if ("--checkin".equals(opt)) { 17553 checkin = true; 17554 } else if ("-f".equals(opt)) { 17555 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17556 } else { 17557 pw.println("Unknown argument: " + opt + "; use -h for help"); 17558 } 17559 } 17560 17561 // Is the caller requesting to dump a particular piece of data? 17562 if (opti < args.length) { 17563 String cmd = args[opti]; 17564 opti++; 17565 // Is this a package name? 17566 if ("android".equals(cmd) || cmd.contains(".")) { 17567 packageName = cmd; 17568 // When dumping a single package, we always dump all of its 17569 // filter information since the amount of data will be reasonable. 17570 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17571 } else if ("check-permission".equals(cmd)) { 17572 if (opti >= args.length) { 17573 pw.println("Error: check-permission missing permission argument"); 17574 return; 17575 } 17576 String perm = args[opti]; 17577 opti++; 17578 if (opti >= args.length) { 17579 pw.println("Error: check-permission missing package argument"); 17580 return; 17581 } 17582 String pkg = args[opti]; 17583 opti++; 17584 int user = UserHandle.getUserId(Binder.getCallingUid()); 17585 if (opti < args.length) { 17586 try { 17587 user = Integer.parseInt(args[opti]); 17588 } catch (NumberFormatException e) { 17589 pw.println("Error: check-permission user argument is not a number: " 17590 + args[opti]); 17591 return; 17592 } 17593 } 17594 pw.println(checkPermission(perm, pkg, user)); 17595 return; 17596 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17597 dumpState.setDump(DumpState.DUMP_LIBS); 17598 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17599 dumpState.setDump(DumpState.DUMP_FEATURES); 17600 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17601 if (opti >= args.length) { 17602 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17603 | DumpState.DUMP_SERVICE_RESOLVERS 17604 | DumpState.DUMP_RECEIVER_RESOLVERS 17605 | DumpState.DUMP_CONTENT_RESOLVERS); 17606 } else { 17607 while (opti < args.length) { 17608 String name = args[opti]; 17609 if ("a".equals(name) || "activity".equals(name)) { 17610 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17611 } else if ("s".equals(name) || "service".equals(name)) { 17612 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17613 } else if ("r".equals(name) || "receiver".equals(name)) { 17614 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17615 } else if ("c".equals(name) || "content".equals(name)) { 17616 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17617 } else { 17618 pw.println("Error: unknown resolver table type: " + name); 17619 return; 17620 } 17621 opti++; 17622 } 17623 } 17624 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17625 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17626 } else if ("permission".equals(cmd)) { 17627 if (opti >= args.length) { 17628 pw.println("Error: permission requires permission name"); 17629 return; 17630 } 17631 permissionNames = new ArraySet<>(); 17632 while (opti < args.length) { 17633 permissionNames.add(args[opti]); 17634 opti++; 17635 } 17636 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17637 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17638 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17639 dumpState.setDump(DumpState.DUMP_PREFERRED); 17640 } else if ("preferred-xml".equals(cmd)) { 17641 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17642 if (opti < args.length && "--full".equals(args[opti])) { 17643 fullPreferred = true; 17644 opti++; 17645 } 17646 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17647 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17648 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17649 dumpState.setDump(DumpState.DUMP_PACKAGES); 17650 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17651 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17652 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17653 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17654 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17655 dumpState.setDump(DumpState.DUMP_MESSAGES); 17656 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17657 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17658 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17659 || "intent-filter-verifiers".equals(cmd)) { 17660 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17661 } else if ("version".equals(cmd)) { 17662 dumpState.setDump(DumpState.DUMP_VERSION); 17663 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17664 dumpState.setDump(DumpState.DUMP_KEYSETS); 17665 } else if ("installs".equals(cmd)) { 17666 dumpState.setDump(DumpState.DUMP_INSTALLS); 17667 } else if ("frozen".equals(cmd)) { 17668 dumpState.setDump(DumpState.DUMP_FROZEN); 17669 } else if ("write".equals(cmd)) { 17670 synchronized (mPackages) { 17671 mSettings.writeLPr(); 17672 pw.println("Settings written."); 17673 return; 17674 } 17675 } 17676 } 17677 17678 if (checkin) { 17679 pw.println("vers,1"); 17680 } 17681 17682 // reader 17683 synchronized (mPackages) { 17684 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17685 if (!checkin) { 17686 if (dumpState.onTitlePrinted()) 17687 pw.println(); 17688 pw.println("Database versions:"); 17689 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17690 } 17691 } 17692 17693 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17694 if (!checkin) { 17695 if (dumpState.onTitlePrinted()) 17696 pw.println(); 17697 pw.println("Verifiers:"); 17698 pw.print(" Required: "); 17699 pw.print(mRequiredVerifierPackage); 17700 pw.print(" (uid="); 17701 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17702 UserHandle.USER_SYSTEM)); 17703 pw.println(")"); 17704 } else if (mRequiredVerifierPackage != null) { 17705 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17706 pw.print(","); 17707 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17708 UserHandle.USER_SYSTEM)); 17709 } 17710 } 17711 17712 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17713 packageName == null) { 17714 if (mIntentFilterVerifierComponent != null) { 17715 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17716 if (!checkin) { 17717 if (dumpState.onTitlePrinted()) 17718 pw.println(); 17719 pw.println("Intent Filter Verifier:"); 17720 pw.print(" Using: "); 17721 pw.print(verifierPackageName); 17722 pw.print(" (uid="); 17723 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17724 UserHandle.USER_SYSTEM)); 17725 pw.println(")"); 17726 } else if (verifierPackageName != null) { 17727 pw.print("ifv,"); pw.print(verifierPackageName); 17728 pw.print(","); 17729 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17730 UserHandle.USER_SYSTEM)); 17731 } 17732 } else { 17733 pw.println(); 17734 pw.println("No Intent Filter Verifier available!"); 17735 } 17736 } 17737 17738 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17739 boolean printedHeader = false; 17740 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17741 while (it.hasNext()) { 17742 String name = it.next(); 17743 SharedLibraryEntry ent = mSharedLibraries.get(name); 17744 if (!checkin) { 17745 if (!printedHeader) { 17746 if (dumpState.onTitlePrinted()) 17747 pw.println(); 17748 pw.println("Libraries:"); 17749 printedHeader = true; 17750 } 17751 pw.print(" "); 17752 } else { 17753 pw.print("lib,"); 17754 } 17755 pw.print(name); 17756 if (!checkin) { 17757 pw.print(" -> "); 17758 } 17759 if (ent.path != null) { 17760 if (!checkin) { 17761 pw.print("(jar) "); 17762 pw.print(ent.path); 17763 } else { 17764 pw.print(",jar,"); 17765 pw.print(ent.path); 17766 } 17767 } else { 17768 if (!checkin) { 17769 pw.print("(apk) "); 17770 pw.print(ent.apk); 17771 } else { 17772 pw.print(",apk,"); 17773 pw.print(ent.apk); 17774 } 17775 } 17776 pw.println(); 17777 } 17778 } 17779 17780 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17781 if (dumpState.onTitlePrinted()) 17782 pw.println(); 17783 if (!checkin) { 17784 pw.println("Features:"); 17785 } 17786 17787 for (FeatureInfo feat : mAvailableFeatures.values()) { 17788 if (checkin) { 17789 pw.print("feat,"); 17790 pw.print(feat.name); 17791 pw.print(","); 17792 pw.println(feat.version); 17793 } else { 17794 pw.print(" "); 17795 pw.print(feat.name); 17796 if (feat.version > 0) { 17797 pw.print(" version="); 17798 pw.print(feat.version); 17799 } 17800 pw.println(); 17801 } 17802 } 17803 } 17804 17805 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17806 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17807 : "Activity Resolver Table:", " ", packageName, 17808 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17809 dumpState.setTitlePrinted(true); 17810 } 17811 } 17812 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17813 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17814 : "Receiver Resolver Table:", " ", packageName, 17815 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17816 dumpState.setTitlePrinted(true); 17817 } 17818 } 17819 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17820 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17821 : "Service Resolver Table:", " ", packageName, 17822 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17823 dumpState.setTitlePrinted(true); 17824 } 17825 } 17826 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17827 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17828 : "Provider Resolver Table:", " ", packageName, 17829 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17830 dumpState.setTitlePrinted(true); 17831 } 17832 } 17833 17834 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17835 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17836 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17837 int user = mSettings.mPreferredActivities.keyAt(i); 17838 if (pir.dump(pw, 17839 dumpState.getTitlePrinted() 17840 ? "\nPreferred Activities User " + user + ":" 17841 : "Preferred Activities User " + user + ":", " ", 17842 packageName, true, false)) { 17843 dumpState.setTitlePrinted(true); 17844 } 17845 } 17846 } 17847 17848 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17849 pw.flush(); 17850 FileOutputStream fout = new FileOutputStream(fd); 17851 BufferedOutputStream str = new BufferedOutputStream(fout); 17852 XmlSerializer serializer = new FastXmlSerializer(); 17853 try { 17854 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17855 serializer.startDocument(null, true); 17856 serializer.setFeature( 17857 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17858 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17859 serializer.endDocument(); 17860 serializer.flush(); 17861 } catch (IllegalArgumentException e) { 17862 pw.println("Failed writing: " + e); 17863 } catch (IllegalStateException e) { 17864 pw.println("Failed writing: " + e); 17865 } catch (IOException e) { 17866 pw.println("Failed writing: " + e); 17867 } 17868 } 17869 17870 if (!checkin 17871 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17872 && packageName == null) { 17873 pw.println(); 17874 int count = mSettings.mPackages.size(); 17875 if (count == 0) { 17876 pw.println("No applications!"); 17877 pw.println(); 17878 } else { 17879 final String prefix = " "; 17880 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17881 if (allPackageSettings.size() == 0) { 17882 pw.println("No domain preferred apps!"); 17883 pw.println(); 17884 } else { 17885 pw.println("App verification status:"); 17886 pw.println(); 17887 count = 0; 17888 for (PackageSetting ps : allPackageSettings) { 17889 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17890 if (ivi == null || ivi.getPackageName() == null) continue; 17891 pw.println(prefix + "Package: " + ivi.getPackageName()); 17892 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17893 pw.println(prefix + "Status: " + ivi.getStatusString()); 17894 pw.println(); 17895 count++; 17896 } 17897 if (count == 0) { 17898 pw.println(prefix + "No app verification established."); 17899 pw.println(); 17900 } 17901 for (int userId : sUserManager.getUserIds()) { 17902 pw.println("App linkages for user " + userId + ":"); 17903 pw.println(); 17904 count = 0; 17905 for (PackageSetting ps : allPackageSettings) { 17906 final long status = ps.getDomainVerificationStatusForUser(userId); 17907 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17908 continue; 17909 } 17910 pw.println(prefix + "Package: " + ps.name); 17911 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17912 String statusStr = IntentFilterVerificationInfo. 17913 getStatusStringFromValue(status); 17914 pw.println(prefix + "Status: " + statusStr); 17915 pw.println(); 17916 count++; 17917 } 17918 if (count == 0) { 17919 pw.println(prefix + "No configured app linkages."); 17920 pw.println(); 17921 } 17922 } 17923 } 17924 } 17925 } 17926 17927 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17928 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17929 if (packageName == null && permissionNames == null) { 17930 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17931 if (iperm == 0) { 17932 if (dumpState.onTitlePrinted()) 17933 pw.println(); 17934 pw.println("AppOp Permissions:"); 17935 } 17936 pw.print(" AppOp Permission "); 17937 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17938 pw.println(":"); 17939 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17940 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17941 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17942 } 17943 } 17944 } 17945 } 17946 17947 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17948 boolean printedSomething = false; 17949 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17950 if (packageName != null && !packageName.equals(p.info.packageName)) { 17951 continue; 17952 } 17953 if (!printedSomething) { 17954 if (dumpState.onTitlePrinted()) 17955 pw.println(); 17956 pw.println("Registered ContentProviders:"); 17957 printedSomething = true; 17958 } 17959 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17960 pw.print(" "); pw.println(p.toString()); 17961 } 17962 printedSomething = false; 17963 for (Map.Entry<String, PackageParser.Provider> entry : 17964 mProvidersByAuthority.entrySet()) { 17965 PackageParser.Provider p = entry.getValue(); 17966 if (packageName != null && !packageName.equals(p.info.packageName)) { 17967 continue; 17968 } 17969 if (!printedSomething) { 17970 if (dumpState.onTitlePrinted()) 17971 pw.println(); 17972 pw.println("ContentProvider Authorities:"); 17973 printedSomething = true; 17974 } 17975 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17976 pw.print(" "); pw.println(p.toString()); 17977 if (p.info != null && p.info.applicationInfo != null) { 17978 final String appInfo = p.info.applicationInfo.toString(); 17979 pw.print(" applicationInfo="); pw.println(appInfo); 17980 } 17981 } 17982 } 17983 17984 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17985 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17986 } 17987 17988 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17989 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17990 } 17991 17992 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17993 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17994 } 17995 17996 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17997 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17998 } 17999 18000 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18001 // XXX should handle packageName != null by dumping only install data that 18002 // the given package is involved with. 18003 if (dumpState.onTitlePrinted()) pw.println(); 18004 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18005 } 18006 18007 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18008 // XXX should handle packageName != null by dumping only install data that 18009 // the given package is involved with. 18010 if (dumpState.onTitlePrinted()) pw.println(); 18011 18012 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18013 ipw.println(); 18014 ipw.println("Frozen packages:"); 18015 ipw.increaseIndent(); 18016 if (mFrozenPackages.size() == 0) { 18017 ipw.println("(none)"); 18018 } else { 18019 for (int i = 0; i < mFrozenPackages.size(); i++) { 18020 ipw.println(mFrozenPackages.valueAt(i)); 18021 } 18022 } 18023 ipw.decreaseIndent(); 18024 } 18025 18026 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18027 if (dumpState.onTitlePrinted()) pw.println(); 18028 mSettings.dumpReadMessagesLPr(pw, dumpState); 18029 18030 pw.println(); 18031 pw.println("Package warning messages:"); 18032 BufferedReader in = null; 18033 String line = null; 18034 try { 18035 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18036 while ((line = in.readLine()) != null) { 18037 if (line.contains("ignored: updated version")) continue; 18038 pw.println(line); 18039 } 18040 } catch (IOException ignored) { 18041 } finally { 18042 IoUtils.closeQuietly(in); 18043 } 18044 } 18045 18046 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18047 BufferedReader in = null; 18048 String line = null; 18049 try { 18050 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18051 while ((line = in.readLine()) != null) { 18052 if (line.contains("ignored: updated version")) continue; 18053 pw.print("msg,"); 18054 pw.println(line); 18055 } 18056 } catch (IOException ignored) { 18057 } finally { 18058 IoUtils.closeQuietly(in); 18059 } 18060 } 18061 } 18062 } 18063 18064 private String dumpDomainString(String packageName) { 18065 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18066 .getList(); 18067 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18068 18069 ArraySet<String> result = new ArraySet<>(); 18070 if (iviList.size() > 0) { 18071 for (IntentFilterVerificationInfo ivi : iviList) { 18072 for (String host : ivi.getDomains()) { 18073 result.add(host); 18074 } 18075 } 18076 } 18077 if (filters != null && filters.size() > 0) { 18078 for (IntentFilter filter : filters) { 18079 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18080 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18081 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18082 result.addAll(filter.getHostsList()); 18083 } 18084 } 18085 } 18086 18087 StringBuilder sb = new StringBuilder(result.size() * 16); 18088 for (String domain : result) { 18089 if (sb.length() > 0) sb.append(" "); 18090 sb.append(domain); 18091 } 18092 return sb.toString(); 18093 } 18094 18095 // ------- apps on sdcard specific code ------- 18096 static final boolean DEBUG_SD_INSTALL = false; 18097 18098 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18099 18100 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18101 18102 private boolean mMediaMounted = false; 18103 18104 static String getEncryptKey() { 18105 try { 18106 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18107 SD_ENCRYPTION_KEYSTORE_NAME); 18108 if (sdEncKey == null) { 18109 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18110 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18111 if (sdEncKey == null) { 18112 Slog.e(TAG, "Failed to create encryption keys"); 18113 return null; 18114 } 18115 } 18116 return sdEncKey; 18117 } catch (NoSuchAlgorithmException nsae) { 18118 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18119 return null; 18120 } catch (IOException ioe) { 18121 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18122 return null; 18123 } 18124 } 18125 18126 /* 18127 * Update media status on PackageManager. 18128 */ 18129 @Override 18130 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18131 int callingUid = Binder.getCallingUid(); 18132 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18133 throw new SecurityException("Media status can only be updated by the system"); 18134 } 18135 // reader; this apparently protects mMediaMounted, but should probably 18136 // be a different lock in that case. 18137 synchronized (mPackages) { 18138 Log.i(TAG, "Updating external media status from " 18139 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18140 + (mediaStatus ? "mounted" : "unmounted")); 18141 if (DEBUG_SD_INSTALL) 18142 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18143 + ", mMediaMounted=" + mMediaMounted); 18144 if (mediaStatus == mMediaMounted) { 18145 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18146 : 0, -1); 18147 mHandler.sendMessage(msg); 18148 return; 18149 } 18150 mMediaMounted = mediaStatus; 18151 } 18152 // Queue up an async operation since the package installation may take a 18153 // little while. 18154 mHandler.post(new Runnable() { 18155 public void run() { 18156 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18157 } 18158 }); 18159 } 18160 18161 /** 18162 * Called by MountService when the initial ASECs to scan are available. 18163 * Should block until all the ASEC containers are finished being scanned. 18164 */ 18165 public void scanAvailableAsecs() { 18166 updateExternalMediaStatusInner(true, false, false); 18167 } 18168 18169 /* 18170 * Collect information of applications on external media, map them against 18171 * existing containers and update information based on current mount status. 18172 * Please note that we always have to report status if reportStatus has been 18173 * set to true especially when unloading packages. 18174 */ 18175 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18176 boolean externalStorage) { 18177 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18178 int[] uidArr = EmptyArray.INT; 18179 18180 final String[] list = PackageHelper.getSecureContainerList(); 18181 if (ArrayUtils.isEmpty(list)) { 18182 Log.i(TAG, "No secure containers found"); 18183 } else { 18184 // Process list of secure containers and categorize them 18185 // as active or stale based on their package internal state. 18186 18187 // reader 18188 synchronized (mPackages) { 18189 for (String cid : list) { 18190 // Leave stages untouched for now; installer service owns them 18191 if (PackageInstallerService.isStageName(cid)) continue; 18192 18193 if (DEBUG_SD_INSTALL) 18194 Log.i(TAG, "Processing container " + cid); 18195 String pkgName = getAsecPackageName(cid); 18196 if (pkgName == null) { 18197 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18198 continue; 18199 } 18200 if (DEBUG_SD_INSTALL) 18201 Log.i(TAG, "Looking for pkg : " + pkgName); 18202 18203 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18204 if (ps == null) { 18205 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18206 continue; 18207 } 18208 18209 /* 18210 * Skip packages that are not external if we're unmounting 18211 * external storage. 18212 */ 18213 if (externalStorage && !isMounted && !isExternal(ps)) { 18214 continue; 18215 } 18216 18217 final AsecInstallArgs args = new AsecInstallArgs(cid, 18218 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18219 // The package status is changed only if the code path 18220 // matches between settings and the container id. 18221 if (ps.codePathString != null 18222 && ps.codePathString.startsWith(args.getCodePath())) { 18223 if (DEBUG_SD_INSTALL) { 18224 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18225 + " at code path: " + ps.codePathString); 18226 } 18227 18228 // We do have a valid package installed on sdcard 18229 processCids.put(args, ps.codePathString); 18230 final int uid = ps.appId; 18231 if (uid != -1) { 18232 uidArr = ArrayUtils.appendInt(uidArr, uid); 18233 } 18234 } else { 18235 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18236 + ps.codePathString); 18237 } 18238 } 18239 } 18240 18241 Arrays.sort(uidArr); 18242 } 18243 18244 // Process packages with valid entries. 18245 if (isMounted) { 18246 if (DEBUG_SD_INSTALL) 18247 Log.i(TAG, "Loading packages"); 18248 loadMediaPackages(processCids, uidArr, externalStorage); 18249 startCleaningPackages(); 18250 mInstallerService.onSecureContainersAvailable(); 18251 } else { 18252 if (DEBUG_SD_INSTALL) 18253 Log.i(TAG, "Unloading packages"); 18254 unloadMediaPackages(processCids, uidArr, reportStatus); 18255 } 18256 } 18257 18258 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18259 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18260 final int size = infos.size(); 18261 final String[] packageNames = new String[size]; 18262 final int[] packageUids = new int[size]; 18263 for (int i = 0; i < size; i++) { 18264 final ApplicationInfo info = infos.get(i); 18265 packageNames[i] = info.packageName; 18266 packageUids[i] = info.uid; 18267 } 18268 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18269 finishedReceiver); 18270 } 18271 18272 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18273 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18274 sendResourcesChangedBroadcast(mediaStatus, replacing, 18275 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18276 } 18277 18278 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18279 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18280 int size = pkgList.length; 18281 if (size > 0) { 18282 // Send broadcasts here 18283 Bundle extras = new Bundle(); 18284 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18285 if (uidArr != null) { 18286 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18287 } 18288 if (replacing) { 18289 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18290 } 18291 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18292 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18293 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18294 } 18295 } 18296 18297 /* 18298 * Look at potentially valid container ids from processCids If package 18299 * information doesn't match the one on record or package scanning fails, 18300 * the cid is added to list of removeCids. We currently don't delete stale 18301 * containers. 18302 */ 18303 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18304 boolean externalStorage) { 18305 ArrayList<String> pkgList = new ArrayList<String>(); 18306 Set<AsecInstallArgs> keys = processCids.keySet(); 18307 18308 for (AsecInstallArgs args : keys) { 18309 String codePath = processCids.get(args); 18310 if (DEBUG_SD_INSTALL) 18311 Log.i(TAG, "Loading container : " + args.cid); 18312 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18313 try { 18314 // Make sure there are no container errors first. 18315 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18316 Slog.e(TAG, "Failed to mount cid : " + args.cid 18317 + " when installing from sdcard"); 18318 continue; 18319 } 18320 // Check code path here. 18321 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18322 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18323 + " does not match one in settings " + codePath); 18324 continue; 18325 } 18326 // Parse package 18327 int parseFlags = mDefParseFlags; 18328 if (args.isExternalAsec()) { 18329 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18330 } 18331 if (args.isFwdLocked()) { 18332 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18333 } 18334 18335 synchronized (mInstallLock) { 18336 PackageParser.Package pkg = null; 18337 try { 18338 // Sadly we don't know the package name yet to freeze it 18339 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18340 SCAN_IGNORE_FROZEN, 0, null); 18341 } catch (PackageManagerException e) { 18342 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18343 } 18344 // Scan the package 18345 if (pkg != null) { 18346 /* 18347 * TODO why is the lock being held? doPostInstall is 18348 * called in other places without the lock. This needs 18349 * to be straightened out. 18350 */ 18351 // writer 18352 synchronized (mPackages) { 18353 retCode = PackageManager.INSTALL_SUCCEEDED; 18354 pkgList.add(pkg.packageName); 18355 // Post process args 18356 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18357 pkg.applicationInfo.uid); 18358 } 18359 } else { 18360 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18361 } 18362 } 18363 18364 } finally { 18365 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18366 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18367 } 18368 } 18369 } 18370 // writer 18371 synchronized (mPackages) { 18372 // If the platform SDK has changed since the last time we booted, 18373 // we need to re-grant app permission to catch any new ones that 18374 // appear. This is really a hack, and means that apps can in some 18375 // cases get permissions that the user didn't initially explicitly 18376 // allow... it would be nice to have some better way to handle 18377 // this situation. 18378 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18379 : mSettings.getInternalVersion(); 18380 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18381 : StorageManager.UUID_PRIVATE_INTERNAL; 18382 18383 int updateFlags = UPDATE_PERMISSIONS_ALL; 18384 if (ver.sdkVersion != mSdkVersion) { 18385 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18386 + mSdkVersion + "; regranting permissions for external"); 18387 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18388 } 18389 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18390 18391 // Yay, everything is now upgraded 18392 ver.forceCurrent(); 18393 18394 // can downgrade to reader 18395 // Persist settings 18396 mSettings.writeLPr(); 18397 } 18398 // Send a broadcast to let everyone know we are done processing 18399 if (pkgList.size() > 0) { 18400 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18401 } 18402 } 18403 18404 /* 18405 * Utility method to unload a list of specified containers 18406 */ 18407 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18408 // Just unmount all valid containers. 18409 for (AsecInstallArgs arg : cidArgs) { 18410 synchronized (mInstallLock) { 18411 arg.doPostDeleteLI(false); 18412 } 18413 } 18414 } 18415 18416 /* 18417 * Unload packages mounted on external media. This involves deleting package 18418 * data from internal structures, sending broadcasts about disabled packages, 18419 * gc'ing to free up references, unmounting all secure containers 18420 * corresponding to packages on external media, and posting a 18421 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18422 * that we always have to post this message if status has been requested no 18423 * matter what. 18424 */ 18425 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18426 final boolean reportStatus) { 18427 if (DEBUG_SD_INSTALL) 18428 Log.i(TAG, "unloading media packages"); 18429 ArrayList<String> pkgList = new ArrayList<String>(); 18430 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18431 final Set<AsecInstallArgs> keys = processCids.keySet(); 18432 for (AsecInstallArgs args : keys) { 18433 String pkgName = args.getPackageName(); 18434 if (DEBUG_SD_INSTALL) 18435 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18436 // Delete package internally 18437 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18438 synchronized (mInstallLock) { 18439 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18440 final boolean res; 18441 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18442 "unloadMediaPackages")) { 18443 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18444 null); 18445 } 18446 if (res) { 18447 pkgList.add(pkgName); 18448 } else { 18449 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18450 failedList.add(args); 18451 } 18452 } 18453 } 18454 18455 // reader 18456 synchronized (mPackages) { 18457 // We didn't update the settings after removing each package; 18458 // write them now for all packages. 18459 mSettings.writeLPr(); 18460 } 18461 18462 // We have to absolutely send UPDATED_MEDIA_STATUS only 18463 // after confirming that all the receivers processed the ordered 18464 // broadcast when packages get disabled, force a gc to clean things up. 18465 // and unload all the containers. 18466 if (pkgList.size() > 0) { 18467 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18468 new IIntentReceiver.Stub() { 18469 public void performReceive(Intent intent, int resultCode, String data, 18470 Bundle extras, boolean ordered, boolean sticky, 18471 int sendingUser) throws RemoteException { 18472 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18473 reportStatus ? 1 : 0, 1, keys); 18474 mHandler.sendMessage(msg); 18475 } 18476 }); 18477 } else { 18478 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18479 keys); 18480 mHandler.sendMessage(msg); 18481 } 18482 } 18483 18484 private void loadPrivatePackages(final VolumeInfo vol) { 18485 mHandler.post(new Runnable() { 18486 @Override 18487 public void run() { 18488 loadPrivatePackagesInner(vol); 18489 } 18490 }); 18491 } 18492 18493 private void loadPrivatePackagesInner(VolumeInfo vol) { 18494 final String volumeUuid = vol.fsUuid; 18495 if (TextUtils.isEmpty(volumeUuid)) { 18496 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18497 return; 18498 } 18499 18500 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18501 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18502 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18503 18504 final VersionInfo ver; 18505 final List<PackageSetting> packages; 18506 synchronized (mPackages) { 18507 ver = mSettings.findOrCreateVersion(volumeUuid); 18508 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18509 } 18510 18511 for (PackageSetting ps : packages) { 18512 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18513 synchronized (mInstallLock) { 18514 final PackageParser.Package pkg; 18515 try { 18516 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18517 loaded.add(pkg.applicationInfo); 18518 18519 } catch (PackageManagerException e) { 18520 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18521 } 18522 18523 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18524 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18525 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18526 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18527 } 18528 } 18529 } 18530 18531 // Reconcile app data for all started/unlocked users 18532 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18533 final UserManager um = mContext.getSystemService(UserManager.class); 18534 for (UserInfo user : um.getUsers()) { 18535 final int flags; 18536 if (um.isUserUnlocked(user.id)) { 18537 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18538 } else if (um.isUserRunning(user.id)) { 18539 flags = StorageManager.FLAG_STORAGE_DE; 18540 } else { 18541 continue; 18542 } 18543 18544 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18545 synchronized (mInstallLock) { 18546 reconcileAppsDataLI(volumeUuid, user.id, flags); 18547 } 18548 } 18549 18550 synchronized (mPackages) { 18551 int updateFlags = UPDATE_PERMISSIONS_ALL; 18552 if (ver.sdkVersion != mSdkVersion) { 18553 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18554 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18555 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18556 } 18557 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18558 18559 // Yay, everything is now upgraded 18560 ver.forceCurrent(); 18561 18562 mSettings.writeLPr(); 18563 } 18564 18565 for (PackageFreezer freezer : freezers) { 18566 freezer.close(); 18567 } 18568 18569 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18570 sendResourcesChangedBroadcast(true, false, loaded, null); 18571 } 18572 18573 private void unloadPrivatePackages(final VolumeInfo vol) { 18574 mHandler.post(new Runnable() { 18575 @Override 18576 public void run() { 18577 unloadPrivatePackagesInner(vol); 18578 } 18579 }); 18580 } 18581 18582 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18583 final String volumeUuid = vol.fsUuid; 18584 if (TextUtils.isEmpty(volumeUuid)) { 18585 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18586 return; 18587 } 18588 18589 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18590 synchronized (mInstallLock) { 18591 synchronized (mPackages) { 18592 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18593 for (PackageSetting ps : packages) { 18594 if (ps.pkg == null) continue; 18595 18596 final ApplicationInfo info = ps.pkg.applicationInfo; 18597 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18598 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18599 18600 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18601 "unloadPrivatePackagesInner")) { 18602 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18603 false, null)) { 18604 unloaded.add(info); 18605 } else { 18606 Slog.w(TAG, "Failed to unload " + ps.codePath); 18607 } 18608 } 18609 } 18610 18611 mSettings.writeLPr(); 18612 } 18613 } 18614 18615 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18616 sendResourcesChangedBroadcast(false, false, unloaded, null); 18617 } 18618 18619 /** 18620 * Prepare storage areas for given user on all mounted devices. 18621 */ 18622 void prepareUserData(int userId, int userSerial, int flags) { 18623 synchronized (mInstallLock) { 18624 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18625 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18626 final String volumeUuid = vol.getFsUuid(); 18627 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18628 } 18629 } 18630 } 18631 18632 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18633 boolean allowRecover) { 18634 // Prepare storage and verify that serial numbers are consistent; if 18635 // there's a mismatch we need to destroy to avoid leaking data 18636 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18637 try { 18638 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18639 18640 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18641 UserManagerService.enforceSerialNumber( 18642 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18643 } 18644 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18645 UserManagerService.enforceSerialNumber( 18646 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18647 } 18648 18649 synchronized (mInstallLock) { 18650 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18651 } 18652 } catch (Exception e) { 18653 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18654 + " because we failed to prepare: " + e); 18655 destroyUserDataLI(volumeUuid, userId, flags); 18656 18657 if (allowRecover) { 18658 // Try one last time; if we fail again we're really in trouble 18659 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18660 } 18661 } 18662 } 18663 18664 /** 18665 * Destroy storage areas for given user on all mounted devices. 18666 */ 18667 void destroyUserData(int userId, int flags) { 18668 synchronized (mInstallLock) { 18669 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18670 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18671 final String volumeUuid = vol.getFsUuid(); 18672 destroyUserDataLI(volumeUuid, userId, flags); 18673 } 18674 } 18675 } 18676 18677 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18678 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18679 try { 18680 // Clean up app data, profile data, and media data 18681 mInstaller.destroyUserData(volumeUuid, userId, flags); 18682 18683 // Clean up system data 18684 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18685 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18686 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18687 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18688 } 18689 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18690 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18691 } 18692 } 18693 18694 // Data with special labels is now gone, so finish the job 18695 storage.destroyUserStorage(volumeUuid, userId, flags); 18696 18697 } catch (Exception e) { 18698 logCriticalInfo(Log.WARN, 18699 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18700 } 18701 } 18702 18703 /** 18704 * Examine all users present on given mounted volume, and destroy data 18705 * belonging to users that are no longer valid, or whose user ID has been 18706 * recycled. 18707 */ 18708 private void reconcileUsers(String volumeUuid) { 18709 final List<File> files = new ArrayList<>(); 18710 Collections.addAll(files, FileUtils 18711 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18712 Collections.addAll(files, FileUtils 18713 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18714 for (File file : files) { 18715 if (!file.isDirectory()) continue; 18716 18717 final int userId; 18718 final UserInfo info; 18719 try { 18720 userId = Integer.parseInt(file.getName()); 18721 info = sUserManager.getUserInfo(userId); 18722 } catch (NumberFormatException e) { 18723 Slog.w(TAG, "Invalid user directory " + file); 18724 continue; 18725 } 18726 18727 boolean destroyUser = false; 18728 if (info == null) { 18729 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18730 + " because no matching user was found"); 18731 destroyUser = true; 18732 } else { 18733 try { 18734 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18735 } catch (IOException e) { 18736 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18737 + " because we failed to enforce serial number: " + e); 18738 destroyUser = true; 18739 } 18740 } 18741 18742 if (destroyUser) { 18743 synchronized (mInstallLock) { 18744 destroyUserDataLI(volumeUuid, userId, 18745 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18746 } 18747 } 18748 } 18749 } 18750 18751 private void assertPackageKnown(String volumeUuid, String packageName) 18752 throws PackageManagerException { 18753 synchronized (mPackages) { 18754 final PackageSetting ps = mSettings.mPackages.get(packageName); 18755 if (ps == null) { 18756 throw new PackageManagerException("Package " + packageName + " is unknown"); 18757 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18758 throw new PackageManagerException( 18759 "Package " + packageName + " found on unknown volume " + volumeUuid 18760 + "; expected volume " + ps.volumeUuid); 18761 } 18762 } 18763 } 18764 18765 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18766 throws PackageManagerException { 18767 synchronized (mPackages) { 18768 final PackageSetting ps = mSettings.mPackages.get(packageName); 18769 if (ps == null) { 18770 throw new PackageManagerException("Package " + packageName + " is unknown"); 18771 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18772 throw new PackageManagerException( 18773 "Package " + packageName + " found on unknown volume " + volumeUuid 18774 + "; expected volume " + ps.volumeUuid); 18775 } else if (!ps.getInstalled(userId)) { 18776 throw new PackageManagerException( 18777 "Package " + packageName + " not installed for user " + userId); 18778 } 18779 } 18780 } 18781 18782 /** 18783 * Examine all apps present on given mounted volume, and destroy apps that 18784 * aren't expected, either due to uninstallation or reinstallation on 18785 * another volume. 18786 */ 18787 private void reconcileApps(String volumeUuid) { 18788 final File[] files = FileUtils 18789 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18790 for (File file : files) { 18791 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18792 && !PackageInstallerService.isStageName(file.getName()); 18793 if (!isPackage) { 18794 // Ignore entries which are not packages 18795 continue; 18796 } 18797 18798 try { 18799 final PackageLite pkg = PackageParser.parsePackageLite(file, 18800 PackageParser.PARSE_MUST_BE_APK); 18801 assertPackageKnown(volumeUuid, pkg.packageName); 18802 18803 } catch (PackageParserException | PackageManagerException e) { 18804 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18805 synchronized (mInstallLock) { 18806 removeCodePathLI(file); 18807 } 18808 } 18809 } 18810 } 18811 18812 /** 18813 * Reconcile all app data for the given user. 18814 * <p> 18815 * Verifies that directories exist and that ownership and labeling is 18816 * correct for all installed apps on all mounted volumes. 18817 */ 18818 void reconcileAppsData(int userId, int flags) { 18819 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18820 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18821 final String volumeUuid = vol.getFsUuid(); 18822 synchronized (mInstallLock) { 18823 reconcileAppsDataLI(volumeUuid, userId, flags); 18824 } 18825 } 18826 } 18827 18828 /** 18829 * Reconcile all app data on given mounted volume. 18830 * <p> 18831 * Destroys app data that isn't expected, either due to uninstallation or 18832 * reinstallation on another volume. 18833 * <p> 18834 * Verifies that directories exist and that ownership and labeling is 18835 * correct for all installed apps. 18836 */ 18837 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18838 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18839 + Integer.toHexString(flags)); 18840 18841 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18842 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18843 18844 boolean restoreconNeeded = false; 18845 18846 // First look for stale data that doesn't belong, and check if things 18847 // have changed since we did our last restorecon 18848 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18849 if (!isUserKeyUnlocked(userId)) { 18850 throw new RuntimeException( 18851 "Yikes, someone asked us to reconcile CE storage while " + userId 18852 + " was still locked; this would have caused massive data loss!"); 18853 } 18854 18855 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18856 18857 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18858 for (File file : files) { 18859 final String packageName = file.getName(); 18860 try { 18861 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18862 } catch (PackageManagerException e) { 18863 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18864 try { 18865 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18866 StorageManager.FLAG_STORAGE_CE, 0); 18867 } catch (InstallerException e2) { 18868 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18869 } 18870 } 18871 } 18872 } 18873 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18874 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18875 18876 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18877 for (File file : files) { 18878 final String packageName = file.getName(); 18879 try { 18880 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18881 } catch (PackageManagerException e) { 18882 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18883 try { 18884 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18885 StorageManager.FLAG_STORAGE_DE, 0); 18886 } catch (InstallerException e2) { 18887 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18888 } 18889 } 18890 } 18891 } 18892 18893 // Ensure that data directories are ready to roll for all packages 18894 // installed for this volume and user 18895 final List<PackageSetting> packages; 18896 synchronized (mPackages) { 18897 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18898 } 18899 int preparedCount = 0; 18900 for (PackageSetting ps : packages) { 18901 final String packageName = ps.name; 18902 if (ps.pkg == null) { 18903 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18904 // TODO: might be due to legacy ASEC apps; we should circle back 18905 // and reconcile again once they're scanned 18906 continue; 18907 } 18908 18909 if (ps.getInstalled(userId)) { 18910 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18911 18912 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18913 // We may have just shuffled around app data directories, so 18914 // prepare them one more time 18915 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18916 } 18917 18918 preparedCount++; 18919 } 18920 } 18921 18922 if (restoreconNeeded) { 18923 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18924 SELinuxMMAC.setRestoreconDone(ceDir); 18925 } 18926 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18927 SELinuxMMAC.setRestoreconDone(deDir); 18928 } 18929 } 18930 18931 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18932 + " packages; restoreconNeeded was " + restoreconNeeded); 18933 } 18934 18935 /** 18936 * Prepare app data for the given app just after it was installed or 18937 * upgraded. This method carefully only touches users that it's installed 18938 * for, and it forces a restorecon to handle any seinfo changes. 18939 * <p> 18940 * Verifies that directories exist and that ownership and labeling is 18941 * correct for all installed apps. If there is an ownership mismatch, it 18942 * will try recovering system apps by wiping data; third-party app data is 18943 * left intact. 18944 * <p> 18945 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18946 */ 18947 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18948 final PackageSetting ps; 18949 synchronized (mPackages) { 18950 ps = mSettings.mPackages.get(pkg.packageName); 18951 mSettings.writeKernelMappingLPr(ps); 18952 } 18953 18954 final UserManager um = mContext.getSystemService(UserManager.class); 18955 for (UserInfo user : um.getUsers()) { 18956 final int flags; 18957 if (um.isUserUnlocked(user.id)) { 18958 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18959 } else if (um.isUserRunning(user.id)) { 18960 flags = StorageManager.FLAG_STORAGE_DE; 18961 } else { 18962 continue; 18963 } 18964 18965 if (ps.getInstalled(user.id)) { 18966 // Whenever an app changes, force a restorecon of its data 18967 // TODO: when user data is locked, mark that we're still dirty 18968 prepareAppDataLIF(pkg, user.id, flags, true); 18969 } 18970 } 18971 } 18972 18973 /** 18974 * Prepare app data for the given app. 18975 * <p> 18976 * Verifies that directories exist and that ownership and labeling is 18977 * correct for all installed apps. If there is an ownership mismatch, this 18978 * will try recovering system apps by wiping data; third-party app data is 18979 * left intact. 18980 */ 18981 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 18982 boolean restoreconNeeded) { 18983 if (pkg == null) { 18984 Slog.wtf(TAG, "Package was null!", new Throwable()); 18985 return; 18986 } 18987 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 18988 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18989 for (int i = 0; i < childCount; i++) { 18990 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 18991 } 18992 } 18993 18994 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 18995 boolean restoreconNeeded) { 18996 if (DEBUG_APP_DATA) { 18997 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18998 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18999 } 19000 19001 final String volumeUuid = pkg.volumeUuid; 19002 final String packageName = pkg.packageName; 19003 final ApplicationInfo app = pkg.applicationInfo; 19004 final int appId = UserHandle.getAppId(app.uid); 19005 19006 Preconditions.checkNotNull(app.seinfo); 19007 19008 try { 19009 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19010 appId, app.seinfo, app.targetSdkVersion); 19011 } catch (InstallerException e) { 19012 if (app.isSystemApp()) { 19013 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19014 + ", but trying to recover: " + e); 19015 destroyAppDataLeafLIF(pkg, userId, flags); 19016 try { 19017 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19018 appId, app.seinfo, app.targetSdkVersion); 19019 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19020 } catch (InstallerException e2) { 19021 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19022 } 19023 } else { 19024 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19025 } 19026 } 19027 19028 if (restoreconNeeded) { 19029 try { 19030 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19031 app.seinfo); 19032 } catch (InstallerException e) { 19033 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19034 } 19035 } 19036 19037 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19038 try { 19039 // CE storage is unlocked right now, so read out the inode and 19040 // remember for use later when it's locked 19041 // TODO: mark this structure as dirty so we persist it! 19042 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19043 StorageManager.FLAG_STORAGE_CE); 19044 synchronized (mPackages) { 19045 final PackageSetting ps = mSettings.mPackages.get(packageName); 19046 if (ps != null) { 19047 ps.setCeDataInode(ceDataInode, userId); 19048 } 19049 } 19050 } catch (InstallerException e) { 19051 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19052 } 19053 } 19054 19055 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19056 } 19057 19058 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19059 if (pkg == null) { 19060 Slog.wtf(TAG, "Package was null!", new Throwable()); 19061 return; 19062 } 19063 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19064 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19065 for (int i = 0; i < childCount; i++) { 19066 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19067 } 19068 } 19069 19070 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19071 final String volumeUuid = pkg.volumeUuid; 19072 final String packageName = pkg.packageName; 19073 final ApplicationInfo app = pkg.applicationInfo; 19074 19075 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19076 // Create a native library symlink only if we have native libraries 19077 // and if the native libraries are 32 bit libraries. We do not provide 19078 // this symlink for 64 bit libraries. 19079 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19080 final String nativeLibPath = app.nativeLibraryDir; 19081 try { 19082 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19083 nativeLibPath, userId); 19084 } catch (InstallerException e) { 19085 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19086 } 19087 } 19088 } 19089 } 19090 19091 /** 19092 * For system apps on non-FBE devices, this method migrates any existing 19093 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19094 * requested by the app. 19095 */ 19096 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19097 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19098 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19099 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19100 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19101 try { 19102 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19103 storageTarget); 19104 } catch (InstallerException e) { 19105 logCriticalInfo(Log.WARN, 19106 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19107 } 19108 return true; 19109 } else { 19110 return false; 19111 } 19112 } 19113 19114 public PackageFreezer freezePackage(String packageName, String killReason) { 19115 return new PackageFreezer(packageName, killReason); 19116 } 19117 19118 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19119 String killReason) { 19120 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19121 return new PackageFreezer(); 19122 } else { 19123 return freezePackage(packageName, killReason); 19124 } 19125 } 19126 19127 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19128 String killReason) { 19129 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19130 return new PackageFreezer(); 19131 } else { 19132 return freezePackage(packageName, killReason); 19133 } 19134 } 19135 19136 /** 19137 * Class that freezes and kills the given package upon creation, and 19138 * unfreezes it upon closing. This is typically used when doing surgery on 19139 * app code/data to prevent the app from running while you're working. 19140 */ 19141 private class PackageFreezer implements AutoCloseable { 19142 private final String mPackageName; 19143 private final PackageFreezer[] mChildren; 19144 19145 private final boolean mWeFroze; 19146 19147 private final AtomicBoolean mClosed = new AtomicBoolean(); 19148 private final CloseGuard mCloseGuard = CloseGuard.get(); 19149 19150 /** 19151 * Create and return a stub freezer that doesn't actually do anything, 19152 * typically used when someone requested 19153 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19154 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19155 */ 19156 public PackageFreezer() { 19157 mPackageName = null; 19158 mChildren = null; 19159 mWeFroze = false; 19160 mCloseGuard.open("close"); 19161 } 19162 19163 public PackageFreezer(String packageName, String killReason) { 19164 synchronized (mPackages) { 19165 mPackageName = packageName; 19166 mWeFroze = mFrozenPackages.add(mPackageName); 19167 19168 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19169 if (ps != null) { 19170 killApplication(ps.name, ps.appId, killReason); 19171 } 19172 19173 final PackageParser.Package p = mPackages.get(packageName); 19174 if (p != null && p.childPackages != null) { 19175 final int N = p.childPackages.size(); 19176 mChildren = new PackageFreezer[N]; 19177 for (int i = 0; i < N; i++) { 19178 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19179 killReason); 19180 } 19181 } else { 19182 mChildren = null; 19183 } 19184 } 19185 mCloseGuard.open("close"); 19186 } 19187 19188 @Override 19189 protected void finalize() throws Throwable { 19190 try { 19191 mCloseGuard.warnIfOpen(); 19192 close(); 19193 } finally { 19194 super.finalize(); 19195 } 19196 } 19197 19198 @Override 19199 public void close() { 19200 mCloseGuard.close(); 19201 if (mClosed.compareAndSet(false, true)) { 19202 synchronized (mPackages) { 19203 if (mWeFroze) { 19204 mFrozenPackages.remove(mPackageName); 19205 } 19206 19207 if (mChildren != null) { 19208 for (PackageFreezer freezer : mChildren) { 19209 freezer.close(); 19210 } 19211 } 19212 } 19213 } 19214 } 19215 } 19216 19217 /** 19218 * Verify that given package is currently frozen. 19219 */ 19220 private void checkPackageFrozen(String packageName) { 19221 synchronized (mPackages) { 19222 if (!mFrozenPackages.contains(packageName)) { 19223 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19224 } 19225 } 19226 } 19227 19228 @Override 19229 public int movePackage(final String packageName, final String volumeUuid) { 19230 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19231 19232 final int moveId = mNextMoveId.getAndIncrement(); 19233 mHandler.post(new Runnable() { 19234 @Override 19235 public void run() { 19236 try { 19237 movePackageInternal(packageName, volumeUuid, moveId); 19238 } catch (PackageManagerException e) { 19239 Slog.w(TAG, "Failed to move " + packageName, e); 19240 mMoveCallbacks.notifyStatusChanged(moveId, 19241 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19242 } 19243 } 19244 }); 19245 return moveId; 19246 } 19247 19248 private void movePackageInternal(final String packageName, final String volumeUuid, 19249 final int moveId) throws PackageManagerException { 19250 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19251 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19252 final PackageManager pm = mContext.getPackageManager(); 19253 19254 final boolean currentAsec; 19255 final String currentVolumeUuid; 19256 final File codeFile; 19257 final String installerPackageName; 19258 final String packageAbiOverride; 19259 final int appId; 19260 final String seinfo; 19261 final String label; 19262 final int targetSdkVersion; 19263 final PackageFreezer freezer; 19264 19265 // reader 19266 synchronized (mPackages) { 19267 final PackageParser.Package pkg = mPackages.get(packageName); 19268 final PackageSetting ps = mSettings.mPackages.get(packageName); 19269 if (pkg == null || ps == null) { 19270 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19271 } 19272 19273 if (pkg.applicationInfo.isSystemApp()) { 19274 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19275 "Cannot move system application"); 19276 } 19277 19278 if (pkg.applicationInfo.isExternalAsec()) { 19279 currentAsec = true; 19280 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19281 } else if (pkg.applicationInfo.isForwardLocked()) { 19282 currentAsec = true; 19283 currentVolumeUuid = "forward_locked"; 19284 } else { 19285 currentAsec = false; 19286 currentVolumeUuid = ps.volumeUuid; 19287 19288 final File probe = new File(pkg.codePath); 19289 final File probeOat = new File(probe, "oat"); 19290 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19291 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19292 "Move only supported for modern cluster style installs"); 19293 } 19294 } 19295 19296 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19297 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19298 "Package already moved to " + volumeUuid); 19299 } 19300 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19301 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19302 "Device admin cannot be moved"); 19303 } 19304 19305 if (mFrozenPackages.contains(packageName)) { 19306 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19307 "Failed to move already frozen package"); 19308 } 19309 19310 codeFile = new File(pkg.codePath); 19311 installerPackageName = ps.installerPackageName; 19312 packageAbiOverride = ps.cpuAbiOverrideString; 19313 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19314 seinfo = pkg.applicationInfo.seinfo; 19315 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19316 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19317 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19318 } 19319 19320 final Bundle extras = new Bundle(); 19321 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19322 extras.putString(Intent.EXTRA_TITLE, label); 19323 mMoveCallbacks.notifyCreated(moveId, extras); 19324 19325 int installFlags; 19326 final boolean moveCompleteApp; 19327 final File measurePath; 19328 19329 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19330 installFlags = INSTALL_INTERNAL; 19331 moveCompleteApp = !currentAsec; 19332 measurePath = Environment.getDataAppDirectory(volumeUuid); 19333 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19334 installFlags = INSTALL_EXTERNAL; 19335 moveCompleteApp = false; 19336 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19337 } else { 19338 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19339 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19340 || !volume.isMountedWritable()) { 19341 freezer.close(); 19342 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19343 "Move location not mounted private volume"); 19344 } 19345 19346 Preconditions.checkState(!currentAsec); 19347 19348 installFlags = INSTALL_INTERNAL; 19349 moveCompleteApp = true; 19350 measurePath = Environment.getDataAppDirectory(volumeUuid); 19351 } 19352 19353 final PackageStats stats = new PackageStats(null, -1); 19354 synchronized (mInstaller) { 19355 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19356 freezer.close(); 19357 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19358 "Failed to measure package size"); 19359 } 19360 } 19361 19362 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19363 + stats.dataSize); 19364 19365 final long startFreeBytes = measurePath.getFreeSpace(); 19366 final long sizeBytes; 19367 if (moveCompleteApp) { 19368 sizeBytes = stats.codeSize + stats.dataSize; 19369 } else { 19370 sizeBytes = stats.codeSize; 19371 } 19372 19373 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19374 freezer.close(); 19375 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19376 "Not enough free space to move"); 19377 } 19378 19379 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19380 19381 final CountDownLatch installedLatch = new CountDownLatch(1); 19382 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19383 @Override 19384 public void onUserActionRequired(Intent intent) throws RemoteException { 19385 throw new IllegalStateException(); 19386 } 19387 19388 @Override 19389 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19390 Bundle extras) throws RemoteException { 19391 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19392 + PackageManager.installStatusToString(returnCode, msg)); 19393 19394 installedLatch.countDown(); 19395 freezer.close(); 19396 19397 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19398 switch (status) { 19399 case PackageInstaller.STATUS_SUCCESS: 19400 mMoveCallbacks.notifyStatusChanged(moveId, 19401 PackageManager.MOVE_SUCCEEDED); 19402 break; 19403 case PackageInstaller.STATUS_FAILURE_STORAGE: 19404 mMoveCallbacks.notifyStatusChanged(moveId, 19405 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19406 break; 19407 default: 19408 mMoveCallbacks.notifyStatusChanged(moveId, 19409 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19410 break; 19411 } 19412 } 19413 }; 19414 19415 final MoveInfo move; 19416 if (moveCompleteApp) { 19417 // Kick off a thread to report progress estimates 19418 new Thread() { 19419 @Override 19420 public void run() { 19421 while (true) { 19422 try { 19423 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19424 break; 19425 } 19426 } catch (InterruptedException ignored) { 19427 } 19428 19429 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19430 final int progress = 10 + (int) MathUtils.constrain( 19431 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19432 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19433 } 19434 } 19435 }.start(); 19436 19437 final String dataAppName = codeFile.getName(); 19438 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19439 dataAppName, appId, seinfo, targetSdkVersion); 19440 } else { 19441 move = null; 19442 } 19443 19444 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19445 19446 final Message msg = mHandler.obtainMessage(INIT_COPY); 19447 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19448 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19449 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19450 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19451 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19452 msg.obj = params; 19453 19454 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19455 System.identityHashCode(msg.obj)); 19456 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19457 System.identityHashCode(msg.obj)); 19458 19459 mHandler.sendMessage(msg); 19460 } 19461 19462 @Override 19463 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19464 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19465 19466 final int realMoveId = mNextMoveId.getAndIncrement(); 19467 final Bundle extras = new Bundle(); 19468 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19469 mMoveCallbacks.notifyCreated(realMoveId, extras); 19470 19471 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19472 @Override 19473 public void onCreated(int moveId, Bundle extras) { 19474 // Ignored 19475 } 19476 19477 @Override 19478 public void onStatusChanged(int moveId, int status, long estMillis) { 19479 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19480 } 19481 }; 19482 19483 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19484 storage.setPrimaryStorageUuid(volumeUuid, callback); 19485 return realMoveId; 19486 } 19487 19488 @Override 19489 public int getMoveStatus(int moveId) { 19490 mContext.enforceCallingOrSelfPermission( 19491 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19492 return mMoveCallbacks.mLastStatus.get(moveId); 19493 } 19494 19495 @Override 19496 public void registerMoveCallback(IPackageMoveObserver callback) { 19497 mContext.enforceCallingOrSelfPermission( 19498 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19499 mMoveCallbacks.register(callback); 19500 } 19501 19502 @Override 19503 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19504 mContext.enforceCallingOrSelfPermission( 19505 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19506 mMoveCallbacks.unregister(callback); 19507 } 19508 19509 @Override 19510 public boolean setInstallLocation(int loc) { 19511 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19512 null); 19513 if (getInstallLocation() == loc) { 19514 return true; 19515 } 19516 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19517 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19518 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19519 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19520 return true; 19521 } 19522 return false; 19523 } 19524 19525 @Override 19526 public int getInstallLocation() { 19527 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19528 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19529 PackageHelper.APP_INSTALL_AUTO); 19530 } 19531 19532 /** Called by UserManagerService */ 19533 void cleanUpUser(UserManagerService userManager, int userHandle) { 19534 synchronized (mPackages) { 19535 mDirtyUsers.remove(userHandle); 19536 mUserNeedsBadging.delete(userHandle); 19537 mSettings.removeUserLPw(userHandle); 19538 mPendingBroadcasts.remove(userHandle); 19539 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19540 removeUnusedPackagesLPw(userManager, userHandle); 19541 } 19542 } 19543 19544 /** 19545 * We're removing userHandle and would like to remove any downloaded packages 19546 * that are no longer in use by any other user. 19547 * @param userHandle the user being removed 19548 */ 19549 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19550 final boolean DEBUG_CLEAN_APKS = false; 19551 int [] users = userManager.getUserIds(); 19552 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19553 while (psit.hasNext()) { 19554 PackageSetting ps = psit.next(); 19555 if (ps.pkg == null) { 19556 continue; 19557 } 19558 final String packageName = ps.pkg.packageName; 19559 // Skip over if system app 19560 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19561 continue; 19562 } 19563 if (DEBUG_CLEAN_APKS) { 19564 Slog.i(TAG, "Checking package " + packageName); 19565 } 19566 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19567 if (keep) { 19568 if (DEBUG_CLEAN_APKS) { 19569 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19570 } 19571 } else { 19572 for (int i = 0; i < users.length; i++) { 19573 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19574 keep = true; 19575 if (DEBUG_CLEAN_APKS) { 19576 Slog.i(TAG, " Keeping package " + packageName + " for user " 19577 + users[i]); 19578 } 19579 break; 19580 } 19581 } 19582 } 19583 if (!keep) { 19584 if (DEBUG_CLEAN_APKS) { 19585 Slog.i(TAG, " Removing package " + packageName); 19586 } 19587 mHandler.post(new Runnable() { 19588 public void run() { 19589 deletePackageX(packageName, userHandle, 0); 19590 } //end run 19591 }); 19592 } 19593 } 19594 } 19595 19596 /** Called by UserManagerService */ 19597 void createNewUser(int userHandle) { 19598 synchronized (mInstallLock) { 19599 mSettings.createNewUserLI(this, mInstaller, userHandle); 19600 } 19601 synchronized (mPackages) { 19602 applyFactoryDefaultBrowserLPw(userHandle); 19603 primeDomainVerificationsLPw(userHandle); 19604 } 19605 } 19606 19607 void newUserCreated(final int userHandle) { 19608 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19609 // If permission review for legacy apps is required, we represent 19610 // dagerous permissions for such apps as always granted runtime 19611 // permissions to keep per user flag state whether review is needed. 19612 // Hence, if a new user is added we have to propagate dangerous 19613 // permission grants for these legacy apps. 19614 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19615 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19616 | UPDATE_PERMISSIONS_REPLACE_ALL); 19617 } 19618 } 19619 19620 @Override 19621 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19622 mContext.enforceCallingOrSelfPermission( 19623 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19624 "Only package verification agents can read the verifier device identity"); 19625 19626 synchronized (mPackages) { 19627 return mSettings.getVerifierDeviceIdentityLPw(); 19628 } 19629 } 19630 19631 @Override 19632 public void setPermissionEnforced(String permission, boolean enforced) { 19633 // TODO: Now that we no longer change GID for storage, this should to away. 19634 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19635 "setPermissionEnforced"); 19636 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19637 synchronized (mPackages) { 19638 if (mSettings.mReadExternalStorageEnforced == null 19639 || mSettings.mReadExternalStorageEnforced != enforced) { 19640 mSettings.mReadExternalStorageEnforced = enforced; 19641 mSettings.writeLPr(); 19642 } 19643 } 19644 // kill any non-foreground processes so we restart them and 19645 // grant/revoke the GID. 19646 final IActivityManager am = ActivityManagerNative.getDefault(); 19647 if (am != null) { 19648 final long token = Binder.clearCallingIdentity(); 19649 try { 19650 am.killProcessesBelowForeground("setPermissionEnforcement"); 19651 } catch (RemoteException e) { 19652 } finally { 19653 Binder.restoreCallingIdentity(token); 19654 } 19655 } 19656 } else { 19657 throw new IllegalArgumentException("No selective enforcement for " + permission); 19658 } 19659 } 19660 19661 @Override 19662 @Deprecated 19663 public boolean isPermissionEnforced(String permission) { 19664 return true; 19665 } 19666 19667 @Override 19668 public boolean isStorageLow() { 19669 final long token = Binder.clearCallingIdentity(); 19670 try { 19671 final DeviceStorageMonitorInternal 19672 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19673 if (dsm != null) { 19674 return dsm.isMemoryLow(); 19675 } else { 19676 return false; 19677 } 19678 } finally { 19679 Binder.restoreCallingIdentity(token); 19680 } 19681 } 19682 19683 @Override 19684 public IPackageInstaller getPackageInstaller() { 19685 return mInstallerService; 19686 } 19687 19688 private boolean userNeedsBadging(int userId) { 19689 int index = mUserNeedsBadging.indexOfKey(userId); 19690 if (index < 0) { 19691 final UserInfo userInfo; 19692 final long token = Binder.clearCallingIdentity(); 19693 try { 19694 userInfo = sUserManager.getUserInfo(userId); 19695 } finally { 19696 Binder.restoreCallingIdentity(token); 19697 } 19698 final boolean b; 19699 if (userInfo != null && userInfo.isManagedProfile()) { 19700 b = true; 19701 } else { 19702 b = false; 19703 } 19704 mUserNeedsBadging.put(userId, b); 19705 return b; 19706 } 19707 return mUserNeedsBadging.valueAt(index); 19708 } 19709 19710 @Override 19711 public KeySet getKeySetByAlias(String packageName, String alias) { 19712 if (packageName == null || alias == null) { 19713 return null; 19714 } 19715 synchronized(mPackages) { 19716 final PackageParser.Package pkg = mPackages.get(packageName); 19717 if (pkg == null) { 19718 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19719 throw new IllegalArgumentException("Unknown package: " + packageName); 19720 } 19721 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19722 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19723 } 19724 } 19725 19726 @Override 19727 public KeySet getSigningKeySet(String packageName) { 19728 if (packageName == null) { 19729 return null; 19730 } 19731 synchronized(mPackages) { 19732 final PackageParser.Package pkg = mPackages.get(packageName); 19733 if (pkg == null) { 19734 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19735 throw new IllegalArgumentException("Unknown package: " + packageName); 19736 } 19737 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19738 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19739 throw new SecurityException("May not access signing KeySet of other apps."); 19740 } 19741 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19742 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19743 } 19744 } 19745 19746 @Override 19747 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19748 if (packageName == null || ks == null) { 19749 return false; 19750 } 19751 synchronized(mPackages) { 19752 final PackageParser.Package pkg = mPackages.get(packageName); 19753 if (pkg == null) { 19754 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19755 throw new IllegalArgumentException("Unknown package: " + packageName); 19756 } 19757 IBinder ksh = ks.getToken(); 19758 if (ksh instanceof KeySetHandle) { 19759 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19760 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19761 } 19762 return false; 19763 } 19764 } 19765 19766 @Override 19767 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19768 if (packageName == null || ks == null) { 19769 return false; 19770 } 19771 synchronized(mPackages) { 19772 final PackageParser.Package pkg = mPackages.get(packageName); 19773 if (pkg == null) { 19774 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19775 throw new IllegalArgumentException("Unknown package: " + packageName); 19776 } 19777 IBinder ksh = ks.getToken(); 19778 if (ksh instanceof KeySetHandle) { 19779 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19780 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19781 } 19782 return false; 19783 } 19784 } 19785 19786 private void deletePackageIfUnusedLPr(final String packageName) { 19787 PackageSetting ps = mSettings.mPackages.get(packageName); 19788 if (ps == null) { 19789 return; 19790 } 19791 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19792 // TODO Implement atomic delete if package is unused 19793 // It is currently possible that the package will be deleted even if it is installed 19794 // after this method returns. 19795 mHandler.post(new Runnable() { 19796 public void run() { 19797 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19798 } 19799 }); 19800 } 19801 } 19802 19803 /** 19804 * Check and throw if the given before/after packages would be considered a 19805 * downgrade. 19806 */ 19807 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19808 throws PackageManagerException { 19809 if (after.versionCode < before.mVersionCode) { 19810 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19811 "Update version code " + after.versionCode + " is older than current " 19812 + before.mVersionCode); 19813 } else if (after.versionCode == before.mVersionCode) { 19814 if (after.baseRevisionCode < before.baseRevisionCode) { 19815 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19816 "Update base revision code " + after.baseRevisionCode 19817 + " is older than current " + before.baseRevisionCode); 19818 } 19819 19820 if (!ArrayUtils.isEmpty(after.splitNames)) { 19821 for (int i = 0; i < after.splitNames.length; i++) { 19822 final String splitName = after.splitNames[i]; 19823 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19824 if (j != -1) { 19825 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19826 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19827 "Update split " + splitName + " revision code " 19828 + after.splitRevisionCodes[i] + " is older than current " 19829 + before.splitRevisionCodes[j]); 19830 } 19831 } 19832 } 19833 } 19834 } 19835 } 19836 19837 private static class MoveCallbacks extends Handler { 19838 private static final int MSG_CREATED = 1; 19839 private static final int MSG_STATUS_CHANGED = 2; 19840 19841 private final RemoteCallbackList<IPackageMoveObserver> 19842 mCallbacks = new RemoteCallbackList<>(); 19843 19844 private final SparseIntArray mLastStatus = new SparseIntArray(); 19845 19846 public MoveCallbacks(Looper looper) { 19847 super(looper); 19848 } 19849 19850 public void register(IPackageMoveObserver callback) { 19851 mCallbacks.register(callback); 19852 } 19853 19854 public void unregister(IPackageMoveObserver callback) { 19855 mCallbacks.unregister(callback); 19856 } 19857 19858 @Override 19859 public void handleMessage(Message msg) { 19860 final SomeArgs args = (SomeArgs) msg.obj; 19861 final int n = mCallbacks.beginBroadcast(); 19862 for (int i = 0; i < n; i++) { 19863 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19864 try { 19865 invokeCallback(callback, msg.what, args); 19866 } catch (RemoteException ignored) { 19867 } 19868 } 19869 mCallbacks.finishBroadcast(); 19870 args.recycle(); 19871 } 19872 19873 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19874 throws RemoteException { 19875 switch (what) { 19876 case MSG_CREATED: { 19877 callback.onCreated(args.argi1, (Bundle) args.arg2); 19878 break; 19879 } 19880 case MSG_STATUS_CHANGED: { 19881 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19882 break; 19883 } 19884 } 19885 } 19886 19887 private void notifyCreated(int moveId, Bundle extras) { 19888 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19889 19890 final SomeArgs args = SomeArgs.obtain(); 19891 args.argi1 = moveId; 19892 args.arg2 = extras; 19893 obtainMessage(MSG_CREATED, args).sendToTarget(); 19894 } 19895 19896 private void notifyStatusChanged(int moveId, int status) { 19897 notifyStatusChanged(moveId, status, -1); 19898 } 19899 19900 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19901 Slog.v(TAG, "Move " + moveId + " status " + status); 19902 19903 final SomeArgs args = SomeArgs.obtain(); 19904 args.argi1 = moveId; 19905 args.argi2 = status; 19906 args.arg3 = estMillis; 19907 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19908 19909 synchronized (mLastStatus) { 19910 mLastStatus.put(moveId, status); 19911 } 19912 } 19913 } 19914 19915 private final static class OnPermissionChangeListeners extends Handler { 19916 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19917 19918 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19919 new RemoteCallbackList<>(); 19920 19921 public OnPermissionChangeListeners(Looper looper) { 19922 super(looper); 19923 } 19924 19925 @Override 19926 public void handleMessage(Message msg) { 19927 switch (msg.what) { 19928 case MSG_ON_PERMISSIONS_CHANGED: { 19929 final int uid = msg.arg1; 19930 handleOnPermissionsChanged(uid); 19931 } break; 19932 } 19933 } 19934 19935 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19936 mPermissionListeners.register(listener); 19937 19938 } 19939 19940 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19941 mPermissionListeners.unregister(listener); 19942 } 19943 19944 public void onPermissionsChanged(int uid) { 19945 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19946 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19947 } 19948 } 19949 19950 private void handleOnPermissionsChanged(int uid) { 19951 final int count = mPermissionListeners.beginBroadcast(); 19952 try { 19953 for (int i = 0; i < count; i++) { 19954 IOnPermissionsChangeListener callback = mPermissionListeners 19955 .getBroadcastItem(i); 19956 try { 19957 callback.onPermissionsChanged(uid); 19958 } catch (RemoteException e) { 19959 Log.e(TAG, "Permission listener is dead", e); 19960 } 19961 } 19962 } finally { 19963 mPermissionListeners.finishBroadcast(); 19964 } 19965 } 19966 } 19967 19968 private class PackageManagerInternalImpl extends PackageManagerInternal { 19969 @Override 19970 public void setLocationPackagesProvider(PackagesProvider provider) { 19971 synchronized (mPackages) { 19972 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19973 } 19974 } 19975 19976 @Override 19977 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19978 synchronized (mPackages) { 19979 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19980 } 19981 } 19982 19983 @Override 19984 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19985 synchronized (mPackages) { 19986 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19987 } 19988 } 19989 19990 @Override 19991 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19992 synchronized (mPackages) { 19993 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19994 } 19995 } 19996 19997 @Override 19998 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19999 synchronized (mPackages) { 20000 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20001 } 20002 } 20003 20004 @Override 20005 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20006 synchronized (mPackages) { 20007 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20008 } 20009 } 20010 20011 @Override 20012 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20013 synchronized (mPackages) { 20014 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20015 packageName, userId); 20016 } 20017 } 20018 20019 @Override 20020 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20021 synchronized (mPackages) { 20022 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20023 packageName, userId); 20024 } 20025 } 20026 20027 @Override 20028 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20029 synchronized (mPackages) { 20030 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20031 packageName, userId); 20032 } 20033 } 20034 20035 @Override 20036 public void setKeepUninstalledPackages(final List<String> packageList) { 20037 Preconditions.checkNotNull(packageList); 20038 List<String> removedFromList = null; 20039 synchronized (mPackages) { 20040 if (mKeepUninstalledPackages != null) { 20041 final int packagesCount = mKeepUninstalledPackages.size(); 20042 for (int i = 0; i < packagesCount; i++) { 20043 String oldPackage = mKeepUninstalledPackages.get(i); 20044 if (packageList != null && packageList.contains(oldPackage)) { 20045 continue; 20046 } 20047 if (removedFromList == null) { 20048 removedFromList = new ArrayList<>(); 20049 } 20050 removedFromList.add(oldPackage); 20051 } 20052 } 20053 mKeepUninstalledPackages = new ArrayList<>(packageList); 20054 if (removedFromList != null) { 20055 final int removedCount = removedFromList.size(); 20056 for (int i = 0; i < removedCount; i++) { 20057 deletePackageIfUnusedLPr(removedFromList.get(i)); 20058 } 20059 } 20060 } 20061 } 20062 20063 @Override 20064 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20065 synchronized (mPackages) { 20066 // If we do not support permission review, done. 20067 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20068 return false; 20069 } 20070 20071 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20072 if (packageSetting == null) { 20073 return false; 20074 } 20075 20076 // Permission review applies only to apps not supporting the new permission model. 20077 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20078 return false; 20079 } 20080 20081 // Legacy apps have the permission and get user consent on launch. 20082 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20083 return permissionsState.isPermissionReviewRequired(userId); 20084 } 20085 } 20086 20087 @Override 20088 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20089 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20090 } 20091 20092 @Override 20093 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20094 int userId) { 20095 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20096 } 20097 } 20098 20099 @Override 20100 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20101 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20102 synchronized (mPackages) { 20103 final long identity = Binder.clearCallingIdentity(); 20104 try { 20105 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20106 packageNames, userId); 20107 } finally { 20108 Binder.restoreCallingIdentity(identity); 20109 } 20110 } 20111 } 20112 20113 private static void enforceSystemOrPhoneCaller(String tag) { 20114 int callingUid = Binder.getCallingUid(); 20115 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20116 throw new SecurityException( 20117 "Cannot call " + tag + " from UID " + callingUid); 20118 } 20119 } 20120 20121 boolean isHistoricalPackageUsageAvailable() { 20122 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20123 } 20124 20125 /** 20126 * Return a <b>copy</b> of the collection of packages known to the package manager. 20127 * @return A copy of the values of mPackages. 20128 */ 20129 Collection<PackageParser.Package> getPackages() { 20130 synchronized (mPackages) { 20131 return new ArrayList<>(mPackages.values()); 20132 } 20133 } 20134 20135 /** 20136 * Logs process start information (including base APK hash) to the security log. 20137 * @hide 20138 */ 20139 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20140 String apkFile, int pid) { 20141 if (!SecurityLog.isLoggingEnabled()) { 20142 return; 20143 } 20144 Bundle data = new Bundle(); 20145 data.putLong("startTimestamp", System.currentTimeMillis()); 20146 data.putString("processName", processName); 20147 data.putInt("uid", uid); 20148 data.putString("seinfo", seinfo); 20149 data.putString("apkFile", apkFile); 20150 data.putInt("pid", pid); 20151 Message msg = mProcessLoggingHandler.obtainMessage( 20152 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20153 msg.setData(data); 20154 mProcessLoggingHandler.sendMessage(msg); 20155 } 20156} 20157