PackageManagerService.java revision 4ef1982af8f6669b6ab0ea2468f63503bc3453c5
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.app.usage.UsageStatsManager; 113import android.content.BroadcastReceiver; 114import android.content.ComponentName; 115import android.content.Context; 116import android.content.IIntentReceiver; 117import android.content.Intent; 118import android.content.IntentFilter; 119import android.content.IntentSender; 120import android.content.IntentSender.SendIntentException; 121import android.content.ServiceConnection; 122import android.content.pm.ActivityInfo; 123import android.content.pm.ApplicationInfo; 124import android.content.pm.AppsQueryHelper; 125import android.content.pm.ComponentInfo; 126import android.content.pm.EphemeralApplicationInfo; 127import android.content.pm.EphemeralResolveInfo; 128import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 129import android.content.pm.FeatureInfo; 130import android.content.pm.IOnPermissionsChangeListener; 131import android.content.pm.IPackageDataObserver; 132import android.content.pm.IPackageDeleteObserver; 133import android.content.pm.IPackageDeleteObserver2; 134import android.content.pm.IPackageInstallObserver2; 135import android.content.pm.IPackageInstaller; 136import android.content.pm.IPackageManager; 137import android.content.pm.IPackageMoveObserver; 138import android.content.pm.IPackageStatsObserver; 139import android.content.pm.InstrumentationInfo; 140import android.content.pm.IntentFilterVerificationInfo; 141import android.content.pm.KeySet; 142import android.content.pm.PackageCleanItem; 143import android.content.pm.PackageInfo; 144import android.content.pm.PackageInfoLite; 145import android.content.pm.PackageInstaller; 146import android.content.pm.PackageManager; 147import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 148import android.content.pm.PackageManagerInternal; 149import android.content.pm.PackageParser; 150import android.content.pm.PackageParser.ActivityIntentInfo; 151import android.content.pm.PackageParser.PackageLite; 152import android.content.pm.PackageParser.PackageParserException; 153import android.content.pm.PackageStats; 154import android.content.pm.PackageUserState; 155import android.content.pm.ParceledListSlice; 156import android.content.pm.PermissionGroupInfo; 157import android.content.pm.PermissionInfo; 158import android.content.pm.ProviderInfo; 159import android.content.pm.ResolveInfo; 160import android.content.pm.ServiceInfo; 161import android.content.pm.Signature; 162import android.content.pm.UserInfo; 163import android.content.pm.VerifierDeviceIdentity; 164import android.content.pm.VerifierInfo; 165import android.content.res.Resources; 166import android.graphics.Bitmap; 167import android.hardware.display.DisplayManager; 168import android.net.Uri; 169import android.os.Binder; 170import android.os.Build; 171import android.os.Bundle; 172import android.os.Debug; 173import android.os.Environment; 174import android.os.Environment.UserEnvironment; 175import android.os.FileUtils; 176import android.os.Handler; 177import android.os.IBinder; 178import android.os.Looper; 179import android.os.Message; 180import android.os.Parcel; 181import android.os.ParcelFileDescriptor; 182import android.os.Process; 183import android.os.RemoteCallbackList; 184import android.os.RemoteException; 185import android.os.ResultReceiver; 186import android.os.SELinux; 187import android.os.ServiceManager; 188import android.os.SystemClock; 189import android.os.SystemProperties; 190import android.os.Trace; 191import android.os.UserHandle; 192import android.os.UserManager; 193import android.os.storage.IMountService; 194import android.os.storage.MountServiceInternal; 195import android.os.storage.StorageEventListener; 196import android.os.storage.StorageManager; 197import android.os.storage.VolumeInfo; 198import android.os.storage.VolumeRecord; 199import android.security.KeyStore; 200import android.security.SystemKeyStore; 201import android.system.ErrnoException; 202import android.system.Os; 203import android.text.TextUtils; 204import android.text.format.DateUtils; 205import android.util.ArrayMap; 206import android.util.ArraySet; 207import android.util.AtomicFile; 208import android.util.DisplayMetrics; 209import android.util.EventLog; 210import android.util.ExceptionUtils; 211import android.util.Log; 212import android.util.LogPrinter; 213import android.util.MathUtils; 214import android.util.PrintStreamPrinter; 215import android.util.Slog; 216import android.util.SparseArray; 217import android.util.SparseBooleanArray; 218import android.util.SparseIntArray; 219import android.util.Xml; 220import android.view.Display; 221 222import com.android.internal.R; 223import com.android.internal.annotations.GuardedBy; 224import com.android.internal.app.IMediaContainerService; 225import com.android.internal.app.ResolverActivity; 226import com.android.internal.content.NativeLibraryHelper; 227import com.android.internal.content.PackageHelper; 228import com.android.internal.os.IParcelFileDescriptorFactory; 229import com.android.internal.os.InstallerConnection.InstallerException; 230import com.android.internal.os.SomeArgs; 231import com.android.internal.os.Zygote; 232import com.android.internal.telephony.CarrierAppUtils; 233import com.android.internal.util.ArrayUtils; 234import com.android.internal.util.FastPrintWriter; 235import com.android.internal.util.FastXmlSerializer; 236import com.android.internal.util.IndentingPrintWriter; 237import com.android.internal.util.Preconditions; 238import com.android.internal.util.XmlUtils; 239import com.android.server.EventLogTags; 240import com.android.server.FgThread; 241import com.android.server.IntentResolver; 242import com.android.server.LocalServices; 243import com.android.server.ServiceThread; 244import com.android.server.SystemConfig; 245import com.android.server.Watchdog; 246import com.android.server.pm.PermissionsState.PermissionState; 247import com.android.server.pm.Settings.DatabaseVersion; 248import com.android.server.pm.Settings.VersionInfo; 249import com.android.server.storage.DeviceStorageMonitorInternal; 250 251import dalvik.system.CloseGuard; 252import dalvik.system.DexFile; 253import dalvik.system.VMRuntime; 254 255import libcore.io.IoUtils; 256import libcore.util.EmptyArray; 257 258import org.xmlpull.v1.XmlPullParser; 259import org.xmlpull.v1.XmlPullParserException; 260import org.xmlpull.v1.XmlSerializer; 261 262import java.io.BufferedInputStream; 263import java.io.BufferedOutputStream; 264import java.io.BufferedReader; 265import java.io.ByteArrayInputStream; 266import java.io.ByteArrayOutputStream; 267import java.io.File; 268import java.io.FileDescriptor; 269import java.io.FileNotFoundException; 270import java.io.FileOutputStream; 271import java.io.FileReader; 272import java.io.FilenameFilter; 273import java.io.IOException; 274import java.io.InputStream; 275import java.io.PrintWriter; 276import java.nio.charset.StandardCharsets; 277import java.security.MessageDigest; 278import java.security.NoSuchAlgorithmException; 279import java.security.PublicKey; 280import java.security.cert.Certificate; 281import java.security.cert.CertificateEncodingException; 282import java.security.cert.CertificateException; 283import java.text.SimpleDateFormat; 284import java.util.ArrayList; 285import java.util.Arrays; 286import java.util.Collection; 287import java.util.Collections; 288import java.util.Comparator; 289import java.util.Date; 290import java.util.HashSet; 291import java.util.Iterator; 292import java.util.List; 293import java.util.Map; 294import java.util.Objects; 295import java.util.Set; 296import java.util.concurrent.CountDownLatch; 297import java.util.concurrent.TimeUnit; 298import java.util.concurrent.atomic.AtomicBoolean; 299import java.util.concurrent.atomic.AtomicInteger; 300import java.util.concurrent.atomic.AtomicLong; 301 302/** 303 * Keep track of all those APKs everywhere. 304 * <p> 305 * Internally there are two important locks: 306 * <ul> 307 * <li>{@link #mPackages} is used to guard all in-memory parsed package details 308 * and other related state. It is a fine-grained lock that should only be held 309 * momentarily, as it's one of the most contended locks in the system. 310 * <li>{@link #mInstallLock} is used to guard all {@code installd} access, whose 311 * operations typically involve heavy lifting of application data on disk. Since 312 * {@code installd} is single-threaded, and it's operations can often be slow, 313 * this lock should never be acquired while already holding {@link #mPackages}. 314 * Conversely, it's safe to acquire {@link #mPackages} momentarily while already 315 * holding {@link #mInstallLock}. 316 * </ul> 317 * Many internal methods rely on the caller to hold the appropriate locks, and 318 * this contract is expressed through method name suffixes: 319 * <ul> 320 * <li>fooLI(): the caller must hold {@link #mInstallLock} 321 * <li>fooLIF(): the caller must hold {@link #mInstallLock} and the package 322 * being modified must be frozen 323 * <li>fooLPr(): the caller must hold {@link #mPackages} for reading 324 * <li>fooLPw(): the caller must hold {@link #mPackages} for writing 325 * </ul> 326 * <p> 327 * Because this class is very central to the platform's security; please run all 328 * CTS and unit tests whenever making modifications: 329 * 330 * <pre> 331 * $ runtest -c android.content.pm.PackageManagerTests frameworks-core 332 * $ cts-tradefed run commandAndExit cts -m AppSecurityTests 333 * </pre> 334 */ 335public class PackageManagerService extends IPackageManager.Stub { 336 static final String TAG = "PackageManager"; 337 static final boolean DEBUG_SETTINGS = false; 338 static final boolean DEBUG_PREFERRED = false; 339 static final boolean DEBUG_UPGRADE = false; 340 static final boolean DEBUG_DOMAIN_VERIFICATION = false; 341 private static final boolean DEBUG_BACKUP = false; 342 private static final boolean DEBUG_INSTALL = false; 343 private static final boolean DEBUG_REMOVE = false; 344 private static final boolean DEBUG_BROADCASTS = false; 345 private static final boolean DEBUG_SHOW_INFO = false; 346 private static final boolean DEBUG_PACKAGE_INFO = false; 347 private static final boolean DEBUG_INTENT_MATCHING = false; 348 private static final boolean DEBUG_PACKAGE_SCANNING = false; 349 private static final boolean DEBUG_VERIFY = false; 350 private static final boolean DEBUG_FILTERS = false; 351 352 // Debug output for dexopting. This is shared between PackageManagerService, OtaDexoptService 353 // and PackageDexOptimizer. All these classes have their own flag to allow switching a single 354 // user, but by default initialize to this. 355 static final boolean DEBUG_DEXOPT = false; 356 357 private static final boolean DEBUG_ABI_SELECTION = false; 358 private static final boolean DEBUG_EPHEMERAL = false; 359 private static final boolean DEBUG_TRIAGED_MISSING = false; 360 private static final boolean DEBUG_APP_DATA = false; 361 362 static final boolean CLEAR_RUNTIME_PERMISSIONS_ON_UPGRADE = false; 363 364 private static final boolean DISABLE_EPHEMERAL_APPS = true; 365 366 private static final int RADIO_UID = Process.PHONE_UID; 367 private static final int LOG_UID = Process.LOG_UID; 368 private static final int NFC_UID = Process.NFC_UID; 369 private static final int BLUETOOTH_UID = Process.BLUETOOTH_UID; 370 private static final int SHELL_UID = Process.SHELL_UID; 371 372 // Cap the size of permission trees that 3rd party apps can define 373 private static final int MAX_PERMISSION_TREE_FOOTPRINT = 32768; // characters of text 374 375 // Suffix used during package installation when copying/moving 376 // package apks to install directory. 377 private static final String INSTALL_PACKAGE_SUFFIX = "-"; 378 379 static final int SCAN_NO_DEX = 1<<1; 380 static final int SCAN_FORCE_DEX = 1<<2; 381 static final int SCAN_UPDATE_SIGNATURE = 1<<3; 382 static final int SCAN_NEW_INSTALL = 1<<4; 383 static final int SCAN_NO_PATHS = 1<<5; 384 static final int SCAN_UPDATE_TIME = 1<<6; 385 static final int SCAN_DEFER_DEX = 1<<7; 386 static final int SCAN_BOOTING = 1<<8; 387 static final int SCAN_TRUSTED_OVERLAY = 1<<9; 388 static final int SCAN_DELETE_DATA_ON_FAILURES = 1<<10; 389 static final int SCAN_REPLACING = 1<<11; 390 static final int SCAN_REQUIRE_KNOWN = 1<<12; 391 static final int SCAN_MOVE = 1<<13; 392 static final int SCAN_INITIAL = 1<<14; 393 static final int SCAN_CHECK_ONLY = 1<<15; 394 static final int SCAN_DONT_KILL_APP = 1<<17; 395 static final int SCAN_IGNORE_FROZEN = 1<<18; 396 397 static final int REMOVE_CHATTY = 1<<16; 398 399 private static final int[] EMPTY_INT_ARRAY = new int[0]; 400 401 /** 402 * Timeout (in milliseconds) after which the watchdog should declare that 403 * our handler thread is wedged. The usual default for such things is one 404 * minute but we sometimes do very lengthy I/O operations on this thread, 405 * such as installing multi-gigabyte applications, so ours needs to be longer. 406 */ 407 private static final long WATCHDOG_TIMEOUT = 1000*60*10; // ten minutes 408 409 /** 410 * Wall-clock timeout (in milliseconds) after which we *require* that an fstrim 411 * be run on this device. We use the value in the Settings.Global.MANDATORY_FSTRIM_INTERVAL 412 * settings entry if available, otherwise we use the hardcoded default. If it's been 413 * more than this long since the last fstrim, we force one during the boot sequence. 414 * 415 * This backstops other fstrim scheduling: if the device is alive at midnight+idle, 416 * one gets run at the next available charging+idle time. This final mandatory 417 * no-fstrim check kicks in only of the other scheduling criteria is never met. 418 */ 419 private static final long DEFAULT_MANDATORY_FSTRIM_INTERVAL = 3 * DateUtils.DAY_IN_MILLIS; 420 421 /** 422 * Whether verification is enabled by default. 423 */ 424 private static final boolean DEFAULT_VERIFY_ENABLE = true; 425 426 /** 427 * The default maximum time to wait for the verification agent to return in 428 * milliseconds. 429 */ 430 private static final long DEFAULT_VERIFICATION_TIMEOUT = 10 * 1000; 431 432 /** 433 * The default response for package verification timeout. 434 * 435 * This can be either PackageManager.VERIFICATION_ALLOW or 436 * PackageManager.VERIFICATION_REJECT. 437 */ 438 private static final int DEFAULT_VERIFICATION_RESPONSE = PackageManager.VERIFICATION_ALLOW; 439 440 static final String DEFAULT_CONTAINER_PACKAGE = "com.android.defcontainer"; 441 442 static final ComponentName DEFAULT_CONTAINER_COMPONENT = new ComponentName( 443 DEFAULT_CONTAINER_PACKAGE, 444 "com.android.defcontainer.DefaultContainerService"); 445 446 private static final String KILL_APP_REASON_GIDS_CHANGED = 447 "permission grant or revoke changed gids"; 448 449 private static final String KILL_APP_REASON_PERMISSIONS_REVOKED = 450 "permissions revoked"; 451 452 private static final String PACKAGE_MIME_TYPE = "application/vnd.android.package-archive"; 453 454 private static final String VENDOR_OVERLAY_DIR = "/vendor/overlay"; 455 456 /** Permission grant: not grant the permission. */ 457 private static final int GRANT_DENIED = 1; 458 459 /** Permission grant: grant the permission as an install permission. */ 460 private static final int GRANT_INSTALL = 2; 461 462 /** Permission grant: grant the permission as a runtime one. */ 463 private static final int GRANT_RUNTIME = 3; 464 465 /** Permission grant: grant as runtime a permission that was granted as an install time one. */ 466 private static final int GRANT_UPGRADE = 4; 467 468 /** Canonical intent used to identify what counts as a "web browser" app */ 469 private static final Intent sBrowserIntent; 470 static { 471 sBrowserIntent = new Intent(); 472 sBrowserIntent.setAction(Intent.ACTION_VIEW); 473 sBrowserIntent.addCategory(Intent.CATEGORY_BROWSABLE); 474 sBrowserIntent.setData(Uri.parse("http:")); 475 } 476 477 /** 478 * The set of all protected actions [i.e. those actions for which a high priority 479 * intent filter is disallowed]. 480 */ 481 private static final Set<String> PROTECTED_ACTIONS = new ArraySet<>(); 482 static { 483 PROTECTED_ACTIONS.add(Intent.ACTION_SEND); 484 PROTECTED_ACTIONS.add(Intent.ACTION_SENDTO); 485 PROTECTED_ACTIONS.add(Intent.ACTION_SEND_MULTIPLE); 486 PROTECTED_ACTIONS.add(Intent.ACTION_VIEW); 487 } 488 489 // Compilation reasons. 490 public static final int REASON_FIRST_BOOT = 0; 491 public static final int REASON_BOOT = 1; 492 public static final int REASON_INSTALL = 2; 493 public static final int REASON_BACKGROUND_DEXOPT = 3; 494 public static final int REASON_AB_OTA = 4; 495 public static final int REASON_NON_SYSTEM_LIBRARY = 5; 496 public static final int REASON_SHARED_APK = 6; 497 public static final int REASON_FORCED_DEXOPT = 7; 498 499 public static final int REASON_LAST = REASON_FORCED_DEXOPT; 500 501 final ServiceThread mHandlerThread; 502 503 final PackageHandler mHandler; 504 505 private final ProcessLoggingHandler mProcessLoggingHandler; 506 507 /** 508 * Messages for {@link #mHandler} that need to wait for system ready before 509 * being dispatched. 510 */ 511 private ArrayList<Message> mPostSystemReadyMessages; 512 513 final int mSdkVersion = Build.VERSION.SDK_INT; 514 515 final Context mContext; 516 final boolean mFactoryTest; 517 final boolean mOnlyCore; 518 final DisplayMetrics mMetrics; 519 final int mDefParseFlags; 520 final String[] mSeparateProcesses; 521 final boolean mIsUpgrade; 522 final boolean mIsPreNUpgrade; 523 524 /** The location for ASEC container files on internal storage. */ 525 final String mAsecInternalPath; 526 527 // Used for privilege escalation. MUST NOT BE CALLED WITH mPackages 528 // LOCK HELD. Can be called with mInstallLock held. 529 @GuardedBy("mInstallLock") 530 final Installer mInstaller; 531 532 /** Directory where installed third-party apps stored */ 533 final File mAppInstallDir; 534 final File mEphemeralInstallDir; 535 536 /** 537 * Directory to which applications installed internally have their 538 * 32 bit native libraries copied. 539 */ 540 private File mAppLib32InstallDir; 541 542 // Directory containing the private parts (e.g. code and non-resource assets) of forward-locked 543 // apps. 544 final File mDrmAppPrivateInstallDir; 545 546 // ---------------------------------------------------------------- 547 548 // Lock for state used when installing and doing other long running 549 // operations. Methods that must be called with this lock held have 550 // the suffix "LI". 551 final Object mInstallLock = new Object(); 552 553 // ---------------------------------------------------------------- 554 555 // Keys are String (package name), values are Package. This also serves 556 // as the lock for the global state. Methods that must be called with 557 // this lock held have the prefix "LP". 558 @GuardedBy("mPackages") 559 final ArrayMap<String, PackageParser.Package> mPackages = 560 new ArrayMap<String, PackageParser.Package>(); 561 562 final ArrayMap<String, Set<String>> mKnownCodebase = 563 new ArrayMap<String, Set<String>>(); 564 565 // Tracks available target package names -> overlay package paths. 566 final ArrayMap<String, ArrayMap<String, PackageParser.Package>> mOverlays = 567 new ArrayMap<String, ArrayMap<String, PackageParser.Package>>(); 568 569 /** 570 * Tracks new system packages [received in an OTA] that we expect to 571 * find updated user-installed versions. Keys are package name, values 572 * are package location. 573 */ 574 final private ArrayMap<String, File> mExpectingBetter = new ArrayMap<>(); 575 /** 576 * Tracks high priority intent filters for protected actions. During boot, certain 577 * filter actions are protected and should never be allowed to have a high priority 578 * intent filter for them. However, there is one, and only one exception -- the 579 * setup wizard. It must be able to define a high priority intent filter for these 580 * actions to ensure there are no escapes from the wizard. We need to delay processing 581 * of these during boot as we need to look at all of the system packages in order 582 * to know which component is the setup wizard. 583 */ 584 private final List<PackageParser.ActivityIntentInfo> mProtectedFilters = new ArrayList<>(); 585 /** 586 * Whether or not processing protected filters should be deferred. 587 */ 588 private boolean mDeferProtectedFilters = true; 589 590 /** 591 * Tracks existing system packages prior to receiving an OTA. Keys are package name. 592 */ 593 final private ArraySet<String> mExistingSystemPackages = new ArraySet<>(); 594 /** 595 * Whether or not system app permissions should be promoted from install to runtime. 596 */ 597 boolean mPromoteSystemApps; 598 599 @GuardedBy("mPackages") 600 final Settings mSettings; 601 602 /** 603 * Set of package names that are currently "frozen", which means active 604 * surgery is being done on the code/data for that package. The platform 605 * will refuse to launch frozen packages to avoid race conditions. 606 * 607 * @see PackageFreezer 608 */ 609 @GuardedBy("mPackages") 610 final ArraySet<String> mFrozenPackages = new ArraySet<>(); 611 612 boolean mRestoredSettings; 613 614 // System configuration read by SystemConfig. 615 final int[] mGlobalGids; 616 final SparseArray<ArraySet<String>> mSystemPermissions; 617 final ArrayMap<String, FeatureInfo> mAvailableFeatures; 618 619 // If mac_permissions.xml was found for seinfo labeling. 620 boolean mFoundPolicyFile; 621 622 private final EphemeralApplicationRegistry mEphemeralApplicationRegistry; 623 624 public static final class SharedLibraryEntry { 625 public final String path; 626 public final String apk; 627 628 SharedLibraryEntry(String _path, String _apk) { 629 path = _path; 630 apk = _apk; 631 } 632 } 633 634 // Currently known shared libraries. 635 final ArrayMap<String, SharedLibraryEntry> mSharedLibraries = 636 new ArrayMap<String, SharedLibraryEntry>(); 637 638 // All available activities, for your resolving pleasure. 639 final ActivityIntentResolver mActivities = 640 new ActivityIntentResolver(); 641 642 // All available receivers, for your resolving pleasure. 643 final ActivityIntentResolver mReceivers = 644 new ActivityIntentResolver(); 645 646 // All available services, for your resolving pleasure. 647 final ServiceIntentResolver mServices = new ServiceIntentResolver(); 648 649 // All available providers, for your resolving pleasure. 650 final ProviderIntentResolver mProviders = new ProviderIntentResolver(); 651 652 // Mapping from provider base names (first directory in content URI codePath) 653 // to the provider information. 654 final ArrayMap<String, PackageParser.Provider> mProvidersByAuthority = 655 new ArrayMap<String, PackageParser.Provider>(); 656 657 // Mapping from instrumentation class names to info about them. 658 final ArrayMap<ComponentName, PackageParser.Instrumentation> mInstrumentation = 659 new ArrayMap<ComponentName, PackageParser.Instrumentation>(); 660 661 // Mapping from permission names to info about them. 662 final ArrayMap<String, PackageParser.PermissionGroup> mPermissionGroups = 663 new ArrayMap<String, PackageParser.PermissionGroup>(); 664 665 // Packages whose data we have transfered into another package, thus 666 // should no longer exist. 667 final ArraySet<String> mTransferedPackages = new ArraySet<String>(); 668 669 // Broadcast actions that are only available to the system. 670 final ArraySet<String> mProtectedBroadcasts = new ArraySet<String>(); 671 672 /** List of packages waiting for verification. */ 673 final SparseArray<PackageVerificationState> mPendingVerification 674 = new SparseArray<PackageVerificationState>(); 675 676 /** Set of packages associated with each app op permission. */ 677 final ArrayMap<String, ArraySet<String>> mAppOpPermissionPackages = new ArrayMap<>(); 678 679 final PackageInstallerService mInstallerService; 680 681 private final PackageDexOptimizer mPackageDexOptimizer; 682 683 private AtomicInteger mNextMoveId = new AtomicInteger(); 684 private final MoveCallbacks mMoveCallbacks; 685 686 private final OnPermissionChangeListeners mOnPermissionChangeListeners; 687 688 // Cache of users who need badging. 689 SparseBooleanArray mUserNeedsBadging = new SparseBooleanArray(); 690 691 /** Token for keys in mPendingVerification. */ 692 private int mPendingVerificationToken = 0; 693 694 volatile boolean mSystemReady; 695 volatile boolean mSafeMode; 696 volatile boolean mHasSystemUidErrors; 697 698 ApplicationInfo mAndroidApplication; 699 final ActivityInfo mResolveActivity = new ActivityInfo(); 700 final ResolveInfo mResolveInfo = new ResolveInfo(); 701 ComponentName mResolveComponentName; 702 PackageParser.Package mPlatformPackage; 703 ComponentName mCustomResolverComponentName; 704 705 boolean mResolverReplaced = false; 706 707 private final @Nullable ComponentName mIntentFilterVerifierComponent; 708 private final @Nullable IntentFilterVerifier<ActivityIntentInfo> mIntentFilterVerifier; 709 710 private int mIntentFilterVerificationToken = 0; 711 712 /** Component that knows whether or not an ephemeral application exists */ 713 final ComponentName mEphemeralResolverComponent; 714 /** The service connection to the ephemeral resolver */ 715 final EphemeralResolverConnection mEphemeralResolverConnection; 716 717 /** Component used to install ephemeral applications */ 718 final ComponentName mEphemeralInstallerComponent; 719 final ActivityInfo mEphemeralInstallerActivity = new ActivityInfo(); 720 final ResolveInfo mEphemeralInstallerInfo = new ResolveInfo(); 721 722 final SparseArray<IntentFilterVerificationState> mIntentFilterVerificationStates 723 = new SparseArray<IntentFilterVerificationState>(); 724 725 final DefaultPermissionGrantPolicy mDefaultPermissionPolicy = 726 new DefaultPermissionGrantPolicy(this); 727 728 // List of packages names to keep cached, even if they are uninstalled for all users 729 private List<String> mKeepUninstalledPackages; 730 731 private static class IFVerificationParams { 732 PackageParser.Package pkg; 733 boolean replacing; 734 int userId; 735 int verifierUid; 736 737 public IFVerificationParams(PackageParser.Package _pkg, boolean _replacing, 738 int _userId, int _verifierUid) { 739 pkg = _pkg; 740 replacing = _replacing; 741 userId = _userId; 742 replacing = _replacing; 743 verifierUid = _verifierUid; 744 } 745 } 746 747 private interface IntentFilterVerifier<T extends IntentFilter> { 748 boolean addOneIntentFilterVerification(int verifierId, int userId, int verificationId, 749 T filter, String packageName); 750 void startVerifications(int userId); 751 void receiveVerificationResponse(int verificationId); 752 } 753 754 private class IntentVerifierProxy implements IntentFilterVerifier<ActivityIntentInfo> { 755 private Context mContext; 756 private ComponentName mIntentFilterVerifierComponent; 757 private ArrayList<Integer> mCurrentIntentFilterVerifications = new ArrayList<Integer>(); 758 759 public IntentVerifierProxy(Context context, ComponentName verifierComponent) { 760 mContext = context; 761 mIntentFilterVerifierComponent = verifierComponent; 762 } 763 764 private String getDefaultScheme() { 765 return IntentFilter.SCHEME_HTTPS; 766 } 767 768 @Override 769 public void startVerifications(int userId) { 770 // Launch verifications requests 771 int count = mCurrentIntentFilterVerifications.size(); 772 for (int n=0; n<count; n++) { 773 int verificationId = mCurrentIntentFilterVerifications.get(n); 774 final IntentFilterVerificationState ivs = 775 mIntentFilterVerificationStates.get(verificationId); 776 777 String packageName = ivs.getPackageName(); 778 779 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 780 final int filterCount = filters.size(); 781 ArraySet<String> domainsSet = new ArraySet<>(); 782 for (int m=0; m<filterCount; m++) { 783 PackageParser.ActivityIntentInfo filter = filters.get(m); 784 domainsSet.addAll(filter.getHostsList()); 785 } 786 ArrayList<String> domainsList = new ArrayList<>(domainsSet); 787 synchronized (mPackages) { 788 if (mSettings.createIntentFilterVerificationIfNeededLPw( 789 packageName, domainsList) != null) { 790 scheduleWriteSettingsLocked(); 791 } 792 } 793 sendVerificationRequest(userId, verificationId, ivs); 794 } 795 mCurrentIntentFilterVerifications.clear(); 796 } 797 798 private void sendVerificationRequest(int userId, int verificationId, 799 IntentFilterVerificationState ivs) { 800 801 Intent verificationIntent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 802 verificationIntent.putExtra( 803 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_ID, 804 verificationId); 805 verificationIntent.putExtra( 806 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_URI_SCHEME, 807 getDefaultScheme()); 808 verificationIntent.putExtra( 809 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_HOSTS, 810 ivs.getHostsString()); 811 verificationIntent.putExtra( 812 PackageManager.EXTRA_INTENT_FILTER_VERIFICATION_PACKAGE_NAME, 813 ivs.getPackageName()); 814 verificationIntent.setComponent(mIntentFilterVerifierComponent); 815 verificationIntent.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 816 817 UserHandle user = new UserHandle(userId); 818 mContext.sendBroadcastAsUser(verificationIntent, user); 819 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 820 "Sending IntentFilter verification broadcast"); 821 } 822 823 public void receiveVerificationResponse(int verificationId) { 824 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 825 826 final boolean verified = ivs.isVerified(); 827 828 ArrayList<PackageParser.ActivityIntentInfo> filters = ivs.getFilters(); 829 final int count = filters.size(); 830 if (DEBUG_DOMAIN_VERIFICATION) { 831 Slog.i(TAG, "Received verification response " + verificationId 832 + " for " + count + " filters, verified=" + verified); 833 } 834 for (int n=0; n<count; n++) { 835 PackageParser.ActivityIntentInfo filter = filters.get(n); 836 filter.setVerified(verified); 837 838 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "IntentFilter " + filter.toString() 839 + " verified with result:" + verified + " and hosts:" 840 + ivs.getHostsString()); 841 } 842 843 mIntentFilterVerificationStates.remove(verificationId); 844 845 final String packageName = ivs.getPackageName(); 846 IntentFilterVerificationInfo ivi = null; 847 848 synchronized (mPackages) { 849 ivi = mSettings.getIntentFilterVerificationLPr(packageName); 850 } 851 if (ivi == null) { 852 Slog.w(TAG, "IntentFilterVerificationInfo not found for verificationId:" 853 + verificationId + " packageName:" + packageName); 854 return; 855 } 856 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 857 "Updating IntentFilterVerificationInfo for package " + packageName 858 +" verificationId:" + verificationId); 859 860 synchronized (mPackages) { 861 if (verified) { 862 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS); 863 } else { 864 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK); 865 } 866 scheduleWriteSettingsLocked(); 867 868 final int userId = ivs.getUserId(); 869 if (userId != UserHandle.USER_ALL) { 870 final int userStatus = 871 mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 872 873 int updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 874 boolean needUpdate = false; 875 876 // We cannot override the STATUS_ALWAYS / STATUS_NEVER states if they have 877 // already been set by the User thru the Disambiguation dialog 878 switch (userStatus) { 879 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 880 if (verified) { 881 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 882 } else { 883 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 884 } 885 needUpdate = true; 886 break; 887 888 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 889 if (verified) { 890 updatedStatus = INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 891 needUpdate = true; 892 } 893 break; 894 895 default: 896 // Nothing to do 897 } 898 899 if (needUpdate) { 900 mSettings.updateIntentFilterVerificationStatusLPw( 901 packageName, updatedStatus, userId); 902 scheduleWritePackageRestrictionsLocked(userId); 903 } 904 } 905 } 906 } 907 908 @Override 909 public boolean addOneIntentFilterVerification(int verifierUid, int userId, int verificationId, 910 ActivityIntentInfo filter, String packageName) { 911 if (!hasValidDomains(filter)) { 912 return false; 913 } 914 IntentFilterVerificationState ivs = mIntentFilterVerificationStates.get(verificationId); 915 if (ivs == null) { 916 ivs = createDomainVerificationState(verifierUid, userId, verificationId, 917 packageName); 918 } 919 if (DEBUG_DOMAIN_VERIFICATION) { 920 Slog.d(TAG, "Adding verification filter for " + packageName + ": " + filter); 921 } 922 ivs.addFilter(filter); 923 return true; 924 } 925 926 private IntentFilterVerificationState createDomainVerificationState(int verifierUid, 927 int userId, int verificationId, String packageName) { 928 IntentFilterVerificationState ivs = new IntentFilterVerificationState( 929 verifierUid, userId, packageName); 930 ivs.setPendingState(); 931 synchronized (mPackages) { 932 mIntentFilterVerificationStates.append(verificationId, ivs); 933 mCurrentIntentFilterVerifications.add(verificationId); 934 } 935 return ivs; 936 } 937 } 938 939 private static boolean hasValidDomains(ActivityIntentInfo filter) { 940 return filter.hasCategory(Intent.CATEGORY_BROWSABLE) 941 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 942 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS)); 943 } 944 945 // Set of pending broadcasts for aggregating enable/disable of components. 946 static class PendingPackageBroadcasts { 947 // for each user id, a map of <package name -> components within that package> 948 final SparseArray<ArrayMap<String, ArrayList<String>>> mUidMap; 949 950 public PendingPackageBroadcasts() { 951 mUidMap = new SparseArray<ArrayMap<String, ArrayList<String>>>(2); 952 } 953 954 public ArrayList<String> get(int userId, String packageName) { 955 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 956 return packages.get(packageName); 957 } 958 959 public void put(int userId, String packageName, ArrayList<String> components) { 960 ArrayMap<String, ArrayList<String>> packages = getOrAllocate(userId); 961 packages.put(packageName, components); 962 } 963 964 public void remove(int userId, String packageName) { 965 ArrayMap<String, ArrayList<String>> packages = mUidMap.get(userId); 966 if (packages != null) { 967 packages.remove(packageName); 968 } 969 } 970 971 public void remove(int userId) { 972 mUidMap.remove(userId); 973 } 974 975 public int userIdCount() { 976 return mUidMap.size(); 977 } 978 979 public int userIdAt(int n) { 980 return mUidMap.keyAt(n); 981 } 982 983 public ArrayMap<String, ArrayList<String>> packagesForUserId(int userId) { 984 return mUidMap.get(userId); 985 } 986 987 public int size() { 988 // total number of pending broadcast entries across all userIds 989 int num = 0; 990 for (int i = 0; i< mUidMap.size(); i++) { 991 num += mUidMap.valueAt(i).size(); 992 } 993 return num; 994 } 995 996 public void clear() { 997 mUidMap.clear(); 998 } 999 1000 private ArrayMap<String, ArrayList<String>> getOrAllocate(int userId) { 1001 ArrayMap<String, ArrayList<String>> map = mUidMap.get(userId); 1002 if (map == null) { 1003 map = new ArrayMap<String, ArrayList<String>>(); 1004 mUidMap.put(userId, map); 1005 } 1006 return map; 1007 } 1008 } 1009 final PendingPackageBroadcasts mPendingBroadcasts = new PendingPackageBroadcasts(); 1010 1011 // Service Connection to remote media container service to copy 1012 // package uri's from external media onto secure containers 1013 // or internal storage. 1014 private IMediaContainerService mContainerService = null; 1015 1016 static final int SEND_PENDING_BROADCAST = 1; 1017 static final int MCS_BOUND = 3; 1018 static final int END_COPY = 4; 1019 static final int INIT_COPY = 5; 1020 static final int MCS_UNBIND = 6; 1021 static final int START_CLEANING_PACKAGE = 7; 1022 static final int FIND_INSTALL_LOC = 8; 1023 static final int POST_INSTALL = 9; 1024 static final int MCS_RECONNECT = 10; 1025 static final int MCS_GIVE_UP = 11; 1026 static final int UPDATED_MEDIA_STATUS = 12; 1027 static final int WRITE_SETTINGS = 13; 1028 static final int WRITE_PACKAGE_RESTRICTIONS = 14; 1029 static final int PACKAGE_VERIFIED = 15; 1030 static final int CHECK_PENDING_VERIFICATION = 16; 1031 static final int START_INTENT_FILTER_VERIFICATIONS = 17; 1032 static final int INTENT_FILTER_VERIFIED = 18; 1033 1034 static final int WRITE_SETTINGS_DELAY = 10*1000; // 10 seconds 1035 1036 // Delay time in millisecs 1037 static final int BROADCAST_DELAY = 10 * 1000; 1038 1039 static UserManagerService sUserManager; 1040 1041 // Stores a list of users whose package restrictions file needs to be updated 1042 private ArraySet<Integer> mDirtyUsers = new ArraySet<Integer>(); 1043 1044 final private DefaultContainerConnection mDefContainerConn = 1045 new DefaultContainerConnection(); 1046 class DefaultContainerConnection implements ServiceConnection { 1047 public void onServiceConnected(ComponentName name, IBinder service) { 1048 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceConnected"); 1049 IMediaContainerService imcs = 1050 IMediaContainerService.Stub.asInterface(service); 1051 mHandler.sendMessage(mHandler.obtainMessage(MCS_BOUND, imcs)); 1052 } 1053 1054 public void onServiceDisconnected(ComponentName name) { 1055 if (DEBUG_SD_INSTALL) Log.i(TAG, "onServiceDisconnected"); 1056 } 1057 } 1058 1059 // Recordkeeping of restore-after-install operations that are currently in flight 1060 // between the Package Manager and the Backup Manager 1061 static class PostInstallData { 1062 public InstallArgs args; 1063 public PackageInstalledInfo res; 1064 1065 PostInstallData(InstallArgs _a, PackageInstalledInfo _r) { 1066 args = _a; 1067 res = _r; 1068 } 1069 } 1070 1071 final SparseArray<PostInstallData> mRunningInstalls = new SparseArray<PostInstallData>(); 1072 int mNextInstallToken = 1; // nonzero; will be wrapped back to 1 when ++ overflows 1073 1074 // XML tags for backup/restore of various bits of state 1075 private static final String TAG_PREFERRED_BACKUP = "pa"; 1076 private static final String TAG_DEFAULT_APPS = "da"; 1077 private static final String TAG_INTENT_FILTER_VERIFICATION = "iv"; 1078 1079 private static final String TAG_PERMISSION_BACKUP = "perm-grant-backup"; 1080 private static final String TAG_ALL_GRANTS = "rt-grants"; 1081 private static final String TAG_GRANT = "grant"; 1082 private static final String ATTR_PACKAGE_NAME = "pkg"; 1083 1084 private static final String TAG_PERMISSION = "perm"; 1085 private static final String ATTR_PERMISSION_NAME = "name"; 1086 private static final String ATTR_IS_GRANTED = "g"; 1087 private static final String ATTR_USER_SET = "set"; 1088 private static final String ATTR_USER_FIXED = "fixed"; 1089 private static final String ATTR_REVOKE_ON_UPGRADE = "rou"; 1090 1091 // System/policy permission grants are not backed up 1092 private static final int SYSTEM_RUNTIME_GRANT_MASK = 1093 FLAG_PERMISSION_POLICY_FIXED 1094 | FLAG_PERMISSION_SYSTEM_FIXED 1095 | FLAG_PERMISSION_GRANTED_BY_DEFAULT; 1096 1097 // And we back up these user-adjusted states 1098 private static final int USER_RUNTIME_GRANT_MASK = 1099 FLAG_PERMISSION_USER_SET 1100 | FLAG_PERMISSION_USER_FIXED 1101 | FLAG_PERMISSION_REVOKE_ON_UPGRADE; 1102 1103 final @Nullable String mRequiredVerifierPackage; 1104 final @NonNull String mRequiredInstallerPackage; 1105 final @Nullable String mSetupWizardPackage; 1106 final @NonNull String mServicesSystemSharedLibraryPackageName; 1107 1108 private final PackageUsage mPackageUsage = new PackageUsage(); 1109 1110 private class PackageUsage { 1111 private static final int WRITE_INTERVAL 1112 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1113 1114 private final Object mFileLock = new Object(); 1115 private final AtomicLong mLastWritten = new AtomicLong(0); 1116 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1117 1118 private boolean mIsHistoricalPackageUsageAvailable = true; 1119 1120 boolean isHistoricalPackageUsageAvailable() { 1121 return mIsHistoricalPackageUsageAvailable; 1122 } 1123 1124 void write(boolean force) { 1125 if (force) { 1126 writeInternal(); 1127 return; 1128 } 1129 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1130 && !DEBUG_DEXOPT) { 1131 return; 1132 } 1133 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1134 new Thread("PackageUsage_DiskWriter") { 1135 @Override 1136 public void run() { 1137 try { 1138 writeInternal(); 1139 } finally { 1140 mBackgroundWriteRunning.set(false); 1141 } 1142 } 1143 }.start(); 1144 } 1145 } 1146 1147 private void writeInternal() { 1148 synchronized (mPackages) { 1149 synchronized (mFileLock) { 1150 AtomicFile file = getFile(); 1151 FileOutputStream f = null; 1152 try { 1153 f = file.startWrite(); 1154 BufferedOutputStream out = new BufferedOutputStream(f); 1155 FileUtils.setPermissions(file.getBaseFile().getPath(), 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1156 StringBuilder sb = new StringBuilder(); 1157 for (PackageParser.Package pkg : mPackages.values()) { 1158 if (pkg.mLastPackageUsageTimeInMills == 0) { 1159 continue; 1160 } 1161 sb.setLength(0); 1162 sb.append(pkg.packageName); 1163 sb.append(' '); 1164 sb.append((long)pkg.mLastPackageUsageTimeInMills); 1165 sb.append('\n'); 1166 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1167 } 1168 out.flush(); 1169 file.finishWrite(f); 1170 } catch (IOException e) { 1171 if (f != null) { 1172 file.failWrite(f); 1173 } 1174 Log.e(TAG, "Failed to write package usage times", e); 1175 } 1176 } 1177 } 1178 mLastWritten.set(SystemClock.elapsedRealtime()); 1179 } 1180 1181 void readLP() { 1182 synchronized (mFileLock) { 1183 AtomicFile file = getFile(); 1184 BufferedInputStream in = null; 1185 try { 1186 in = new BufferedInputStream(file.openRead()); 1187 StringBuffer sb = new StringBuffer(); 1188 while (true) { 1189 String packageName = readToken(in, sb, ' '); 1190 if (packageName == null) { 1191 break; 1192 } 1193 String timeInMillisString = readToken(in, sb, '\n'); 1194 if (timeInMillisString == null) { 1195 throw new IOException("Failed to find last usage time for package " 1196 + packageName); 1197 } 1198 PackageParser.Package pkg = mPackages.get(packageName); 1199 if (pkg == null) { 1200 continue; 1201 } 1202 long timeInMillis; 1203 try { 1204 timeInMillis = Long.parseLong(timeInMillisString); 1205 } catch (NumberFormatException e) { 1206 throw new IOException("Failed to parse " + timeInMillisString 1207 + " as a long.", e); 1208 } 1209 pkg.mLastPackageUsageTimeInMills = timeInMillis; 1210 } 1211 } catch (FileNotFoundException expected) { 1212 mIsHistoricalPackageUsageAvailable = false; 1213 } catch (IOException e) { 1214 Log.w(TAG, "Failed to read package usage times", e); 1215 } finally { 1216 IoUtils.closeQuietly(in); 1217 } 1218 } 1219 mLastWritten.set(SystemClock.elapsedRealtime()); 1220 } 1221 1222 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1223 throws IOException { 1224 sb.setLength(0); 1225 while (true) { 1226 int ch = in.read(); 1227 if (ch == -1) { 1228 if (sb.length() == 0) { 1229 return null; 1230 } 1231 throw new IOException("Unexpected EOF"); 1232 } 1233 if (ch == endOfToken) { 1234 return sb.toString(); 1235 } 1236 sb.append((char)ch); 1237 } 1238 } 1239 1240 private AtomicFile getFile() { 1241 File dataDir = Environment.getDataDirectory(); 1242 File systemDir = new File(dataDir, "system"); 1243 File fname = new File(systemDir, "package-usage.list"); 1244 return new AtomicFile(fname); 1245 } 1246 } 1247 1248 class PackageHandler extends Handler { 1249 private boolean mBound = false; 1250 final ArrayList<HandlerParams> mPendingInstalls = 1251 new ArrayList<HandlerParams>(); 1252 1253 private boolean connectToService() { 1254 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1255 " DefaultContainerService"); 1256 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1257 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1258 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1259 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1260 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1261 mBound = true; 1262 return true; 1263 } 1264 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1265 return false; 1266 } 1267 1268 private void disconnectService() { 1269 mContainerService = null; 1270 mBound = false; 1271 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1272 mContext.unbindService(mDefContainerConn); 1273 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1274 } 1275 1276 PackageHandler(Looper looper) { 1277 super(looper); 1278 } 1279 1280 public void handleMessage(Message msg) { 1281 try { 1282 doHandleMessage(msg); 1283 } finally { 1284 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1285 } 1286 } 1287 1288 void doHandleMessage(Message msg) { 1289 switch (msg.what) { 1290 case INIT_COPY: { 1291 HandlerParams params = (HandlerParams) msg.obj; 1292 int idx = mPendingInstalls.size(); 1293 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1294 // If a bind was already initiated we dont really 1295 // need to do anything. The pending install 1296 // will be processed later on. 1297 if (!mBound) { 1298 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1299 System.identityHashCode(mHandler)); 1300 // If this is the only one pending we might 1301 // have to bind to the service again. 1302 if (!connectToService()) { 1303 Slog.e(TAG, "Failed to bind to media container service"); 1304 params.serviceError(); 1305 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1306 System.identityHashCode(mHandler)); 1307 if (params.traceMethod != null) { 1308 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1309 params.traceCookie); 1310 } 1311 return; 1312 } else { 1313 // Once we bind to the service, the first 1314 // pending request will be processed. 1315 mPendingInstalls.add(idx, params); 1316 } 1317 } else { 1318 mPendingInstalls.add(idx, params); 1319 // Already bound to the service. Just make 1320 // sure we trigger off processing the first request. 1321 if (idx == 0) { 1322 mHandler.sendEmptyMessage(MCS_BOUND); 1323 } 1324 } 1325 break; 1326 } 1327 case MCS_BOUND: { 1328 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1329 if (msg.obj != null) { 1330 mContainerService = (IMediaContainerService) msg.obj; 1331 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1332 System.identityHashCode(mHandler)); 1333 } 1334 if (mContainerService == null) { 1335 if (!mBound) { 1336 // Something seriously wrong since we are not bound and we are not 1337 // waiting for connection. Bail out. 1338 Slog.e(TAG, "Cannot bind to media container service"); 1339 for (HandlerParams params : mPendingInstalls) { 1340 // Indicate service bind error 1341 params.serviceError(); 1342 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1343 System.identityHashCode(params)); 1344 if (params.traceMethod != null) { 1345 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1346 params.traceMethod, params.traceCookie); 1347 } 1348 return; 1349 } 1350 mPendingInstalls.clear(); 1351 } else { 1352 Slog.w(TAG, "Waiting to connect to media container service"); 1353 } 1354 } else if (mPendingInstalls.size() > 0) { 1355 HandlerParams params = mPendingInstalls.get(0); 1356 if (params != null) { 1357 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1358 System.identityHashCode(params)); 1359 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1360 if (params.startCopy()) { 1361 // We are done... look for more work or to 1362 // go idle. 1363 if (DEBUG_SD_INSTALL) Log.i(TAG, 1364 "Checking for more work or unbind..."); 1365 // Delete pending install 1366 if (mPendingInstalls.size() > 0) { 1367 mPendingInstalls.remove(0); 1368 } 1369 if (mPendingInstalls.size() == 0) { 1370 if (mBound) { 1371 if (DEBUG_SD_INSTALL) Log.i(TAG, 1372 "Posting delayed MCS_UNBIND"); 1373 removeMessages(MCS_UNBIND); 1374 Message ubmsg = obtainMessage(MCS_UNBIND); 1375 // Unbind after a little delay, to avoid 1376 // continual thrashing. 1377 sendMessageDelayed(ubmsg, 10000); 1378 } 1379 } else { 1380 // There are more pending requests in queue. 1381 // Just post MCS_BOUND message to trigger processing 1382 // of next pending install. 1383 if (DEBUG_SD_INSTALL) Log.i(TAG, 1384 "Posting MCS_BOUND for next work"); 1385 mHandler.sendEmptyMessage(MCS_BOUND); 1386 } 1387 } 1388 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1389 } 1390 } else { 1391 // Should never happen ideally. 1392 Slog.w(TAG, "Empty queue"); 1393 } 1394 break; 1395 } 1396 case MCS_RECONNECT: { 1397 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1398 if (mPendingInstalls.size() > 0) { 1399 if (mBound) { 1400 disconnectService(); 1401 } 1402 if (!connectToService()) { 1403 Slog.e(TAG, "Failed to bind to media container service"); 1404 for (HandlerParams params : mPendingInstalls) { 1405 // Indicate service bind error 1406 params.serviceError(); 1407 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1408 System.identityHashCode(params)); 1409 } 1410 mPendingInstalls.clear(); 1411 } 1412 } 1413 break; 1414 } 1415 case MCS_UNBIND: { 1416 // If there is no actual work left, then time to unbind. 1417 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1418 1419 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1420 if (mBound) { 1421 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1422 1423 disconnectService(); 1424 } 1425 } else if (mPendingInstalls.size() > 0) { 1426 // There are more pending requests in queue. 1427 // Just post MCS_BOUND message to trigger processing 1428 // of next pending install. 1429 mHandler.sendEmptyMessage(MCS_BOUND); 1430 } 1431 1432 break; 1433 } 1434 case MCS_GIVE_UP: { 1435 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1436 HandlerParams params = mPendingInstalls.remove(0); 1437 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1438 System.identityHashCode(params)); 1439 break; 1440 } 1441 case SEND_PENDING_BROADCAST: { 1442 String packages[]; 1443 ArrayList<String> components[]; 1444 int size = 0; 1445 int uids[]; 1446 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1447 synchronized (mPackages) { 1448 if (mPendingBroadcasts == null) { 1449 return; 1450 } 1451 size = mPendingBroadcasts.size(); 1452 if (size <= 0) { 1453 // Nothing to be done. Just return 1454 return; 1455 } 1456 packages = new String[size]; 1457 components = new ArrayList[size]; 1458 uids = new int[size]; 1459 int i = 0; // filling out the above arrays 1460 1461 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1462 int packageUserId = mPendingBroadcasts.userIdAt(n); 1463 Iterator<Map.Entry<String, ArrayList<String>>> it 1464 = mPendingBroadcasts.packagesForUserId(packageUserId) 1465 .entrySet().iterator(); 1466 while (it.hasNext() && i < size) { 1467 Map.Entry<String, ArrayList<String>> ent = it.next(); 1468 packages[i] = ent.getKey(); 1469 components[i] = ent.getValue(); 1470 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1471 uids[i] = (ps != null) 1472 ? UserHandle.getUid(packageUserId, ps.appId) 1473 : -1; 1474 i++; 1475 } 1476 } 1477 size = i; 1478 mPendingBroadcasts.clear(); 1479 } 1480 // Send broadcasts 1481 for (int i = 0; i < size; i++) { 1482 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1483 } 1484 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1485 break; 1486 } 1487 case START_CLEANING_PACKAGE: { 1488 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1489 final String packageName = (String)msg.obj; 1490 final int userId = msg.arg1; 1491 final boolean andCode = msg.arg2 != 0; 1492 synchronized (mPackages) { 1493 if (userId == UserHandle.USER_ALL) { 1494 int[] users = sUserManager.getUserIds(); 1495 for (int user : users) { 1496 mSettings.addPackageToCleanLPw( 1497 new PackageCleanItem(user, packageName, andCode)); 1498 } 1499 } else { 1500 mSettings.addPackageToCleanLPw( 1501 new PackageCleanItem(userId, packageName, andCode)); 1502 } 1503 } 1504 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1505 startCleaningPackages(); 1506 } break; 1507 case POST_INSTALL: { 1508 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1509 1510 PostInstallData data = mRunningInstalls.get(msg.arg1); 1511 mRunningInstalls.delete(msg.arg1); 1512 1513 if (data != null) { 1514 InstallArgs args = data.args; 1515 PackageInstalledInfo parentRes = data.res; 1516 1517 final boolean grantPermissions = (args.installFlags 1518 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1519 final boolean killApp = (args.installFlags 1520 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1521 final String[] grantedPermissions = args.installGrantPermissions; 1522 1523 // Handle the parent package 1524 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1525 grantedPermissions, args.observer); 1526 1527 // Handle the child packages 1528 final int childCount = (parentRes.addedChildPackages != null) 1529 ? parentRes.addedChildPackages.size() : 0; 1530 for (int i = 0; i < childCount; i++) { 1531 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1532 handlePackagePostInstall(childRes, grantPermissions, killApp, 1533 grantedPermissions, args.observer); 1534 } 1535 1536 // Log tracing if needed 1537 if (args.traceMethod != null) { 1538 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1539 args.traceCookie); 1540 } 1541 } else { 1542 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1543 } 1544 1545 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1546 } break; 1547 case UPDATED_MEDIA_STATUS: { 1548 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1549 boolean reportStatus = msg.arg1 == 1; 1550 boolean doGc = msg.arg2 == 1; 1551 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1552 if (doGc) { 1553 // Force a gc to clear up stale containers. 1554 Runtime.getRuntime().gc(); 1555 } 1556 if (msg.obj != null) { 1557 @SuppressWarnings("unchecked") 1558 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1559 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1560 // Unload containers 1561 unloadAllContainers(args); 1562 } 1563 if (reportStatus) { 1564 try { 1565 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1566 PackageHelper.getMountService().finishMediaUpdate(); 1567 } catch (RemoteException e) { 1568 Log.e(TAG, "MountService not running?"); 1569 } 1570 } 1571 } break; 1572 case WRITE_SETTINGS: { 1573 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1574 synchronized (mPackages) { 1575 removeMessages(WRITE_SETTINGS); 1576 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1577 mSettings.writeLPr(); 1578 mDirtyUsers.clear(); 1579 } 1580 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1581 } break; 1582 case WRITE_PACKAGE_RESTRICTIONS: { 1583 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1584 synchronized (mPackages) { 1585 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1586 for (int userId : mDirtyUsers) { 1587 mSettings.writePackageRestrictionsLPr(userId); 1588 } 1589 mDirtyUsers.clear(); 1590 } 1591 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1592 } break; 1593 case CHECK_PENDING_VERIFICATION: { 1594 final int verificationId = msg.arg1; 1595 final PackageVerificationState state = mPendingVerification.get(verificationId); 1596 1597 if ((state != null) && !state.timeoutExtended()) { 1598 final InstallArgs args = state.getInstallArgs(); 1599 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1600 1601 Slog.i(TAG, "Verification timed out for " + originUri); 1602 mPendingVerification.remove(verificationId); 1603 1604 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1605 1606 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1607 Slog.i(TAG, "Continuing with installation of " + originUri); 1608 state.setVerifierResponse(Binder.getCallingUid(), 1609 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1610 broadcastPackageVerified(verificationId, originUri, 1611 PackageManager.VERIFICATION_ALLOW, 1612 state.getInstallArgs().getUser()); 1613 try { 1614 ret = args.copyApk(mContainerService, true); 1615 } catch (RemoteException e) { 1616 Slog.e(TAG, "Could not contact the ContainerService"); 1617 } 1618 } else { 1619 broadcastPackageVerified(verificationId, originUri, 1620 PackageManager.VERIFICATION_REJECT, 1621 state.getInstallArgs().getUser()); 1622 } 1623 1624 Trace.asyncTraceEnd( 1625 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1626 1627 processPendingInstall(args, ret); 1628 mHandler.sendEmptyMessage(MCS_UNBIND); 1629 } 1630 break; 1631 } 1632 case PACKAGE_VERIFIED: { 1633 final int verificationId = msg.arg1; 1634 1635 final PackageVerificationState state = mPendingVerification.get(verificationId); 1636 if (state == null) { 1637 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1638 break; 1639 } 1640 1641 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1642 1643 state.setVerifierResponse(response.callerUid, response.code); 1644 1645 if (state.isVerificationComplete()) { 1646 mPendingVerification.remove(verificationId); 1647 1648 final InstallArgs args = state.getInstallArgs(); 1649 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1650 1651 int ret; 1652 if (state.isInstallAllowed()) { 1653 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1654 broadcastPackageVerified(verificationId, originUri, 1655 response.code, state.getInstallArgs().getUser()); 1656 try { 1657 ret = args.copyApk(mContainerService, true); 1658 } catch (RemoteException e) { 1659 Slog.e(TAG, "Could not contact the ContainerService"); 1660 } 1661 } else { 1662 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1663 } 1664 1665 Trace.asyncTraceEnd( 1666 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1667 1668 processPendingInstall(args, ret); 1669 mHandler.sendEmptyMessage(MCS_UNBIND); 1670 } 1671 1672 break; 1673 } 1674 case START_INTENT_FILTER_VERIFICATIONS: { 1675 IFVerificationParams params = (IFVerificationParams) msg.obj; 1676 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1677 params.replacing, params.pkg); 1678 break; 1679 } 1680 case INTENT_FILTER_VERIFIED: { 1681 final int verificationId = msg.arg1; 1682 1683 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1684 verificationId); 1685 if (state == null) { 1686 Slog.w(TAG, "Invalid IntentFilter verification token " 1687 + verificationId + " received"); 1688 break; 1689 } 1690 1691 final int userId = state.getUserId(); 1692 1693 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1694 "Processing IntentFilter verification with token:" 1695 + verificationId + " and userId:" + userId); 1696 1697 final IntentFilterVerificationResponse response = 1698 (IntentFilterVerificationResponse) msg.obj; 1699 1700 state.setVerifierResponse(response.callerUid, response.code); 1701 1702 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1703 "IntentFilter verification with token:" + verificationId 1704 + " and userId:" + userId 1705 + " is settings verifier response with response code:" 1706 + response.code); 1707 1708 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1709 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1710 + response.getFailedDomainsString()); 1711 } 1712 1713 if (state.isVerificationComplete()) { 1714 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1715 } else { 1716 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1717 "IntentFilter verification with token:" + verificationId 1718 + " was not said to be complete"); 1719 } 1720 1721 break; 1722 } 1723 } 1724 } 1725 } 1726 1727 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1728 boolean killApp, String[] grantedPermissions, 1729 IPackageInstallObserver2 installObserver) { 1730 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1731 // Send the removed broadcasts 1732 if (res.removedInfo != null) { 1733 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1734 } 1735 1736 // Now that we successfully installed the package, grant runtime 1737 // permissions if requested before broadcasting the install. 1738 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1739 >= Build.VERSION_CODES.M) { 1740 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1741 } 1742 1743 final boolean update = res.removedInfo != null 1744 && res.removedInfo.removedPackage != null; 1745 1746 // If this is the first time we have child packages for a disabled privileged 1747 // app that had no children, we grant requested runtime permissions to the new 1748 // children if the parent on the system image had them already granted. 1749 if (res.pkg.parentPackage != null) { 1750 synchronized (mPackages) { 1751 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1752 } 1753 } 1754 1755 synchronized (mPackages) { 1756 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1757 } 1758 1759 final String packageName = res.pkg.applicationInfo.packageName; 1760 Bundle extras = new Bundle(1); 1761 extras.putInt(Intent.EXTRA_UID, res.uid); 1762 1763 // Determine the set of users who are adding this package for 1764 // the first time vs. those who are seeing an update. 1765 int[] firstUsers = EMPTY_INT_ARRAY; 1766 int[] updateUsers = EMPTY_INT_ARRAY; 1767 if (res.origUsers == null || res.origUsers.length == 0) { 1768 firstUsers = res.newUsers; 1769 } else { 1770 for (int newUser : res.newUsers) { 1771 boolean isNew = true; 1772 for (int origUser : res.origUsers) { 1773 if (origUser == newUser) { 1774 isNew = false; 1775 break; 1776 } 1777 } 1778 if (isNew) { 1779 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1780 } else { 1781 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1782 } 1783 } 1784 } 1785 1786 // Send installed broadcasts if the install/update is not ephemeral 1787 if (!isEphemeral(res.pkg)) { 1788 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1789 1790 // Send added for users that see the package for the first time 1791 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1792 extras, 0 /*flags*/, null /*targetPackage*/, 1793 null /*finishedReceiver*/, firstUsers); 1794 1795 // Send added for users that don't see the package for the first time 1796 if (update) { 1797 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1798 } 1799 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1800 extras, 0 /*flags*/, null /*targetPackage*/, 1801 null /*finishedReceiver*/, updateUsers); 1802 1803 // Send replaced for users that don't see the package for the first time 1804 if (update) { 1805 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1806 packageName, extras, 0 /*flags*/, 1807 null /*targetPackage*/, null /*finishedReceiver*/, 1808 updateUsers); 1809 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1810 null /*package*/, null /*extras*/, 0 /*flags*/, 1811 packageName /*targetPackage*/, 1812 null /*finishedReceiver*/, updateUsers); 1813 } 1814 1815 // Send broadcast package appeared if forward locked/external for all users 1816 // treat asec-hosted packages like removable media on upgrade 1817 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1818 if (DEBUG_INSTALL) { 1819 Slog.i(TAG, "upgrading pkg " + res.pkg 1820 + " is ASEC-hosted -> AVAILABLE"); 1821 } 1822 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1823 ArrayList<String> pkgList = new ArrayList<>(1); 1824 pkgList.add(packageName); 1825 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1826 } 1827 } 1828 1829 // Work that needs to happen on first install within each user 1830 if (firstUsers != null && firstUsers.length > 0) { 1831 synchronized (mPackages) { 1832 for (int userId : firstUsers) { 1833 // If this app is a browser and it's newly-installed for some 1834 // users, clear any default-browser state in those users. The 1835 // app's nature doesn't depend on the user, so we can just check 1836 // its browser nature in any user and generalize. 1837 if (packageIsBrowser(packageName, userId)) { 1838 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1839 } 1840 1841 // We may also need to apply pending (restored) runtime 1842 // permission grants within these users. 1843 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1844 } 1845 } 1846 } 1847 1848 // Log current value of "unknown sources" setting 1849 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1850 getUnknownSourcesSettings()); 1851 1852 // Force a gc to clear up things 1853 Runtime.getRuntime().gc(); 1854 1855 // Remove the replaced package's older resources safely now 1856 // We delete after a gc for applications on sdcard. 1857 if (res.removedInfo != null && res.removedInfo.args != null) { 1858 synchronized (mInstallLock) { 1859 res.removedInfo.args.doPostDeleteLI(true); 1860 } 1861 } 1862 } 1863 1864 // If someone is watching installs - notify them 1865 if (installObserver != null) { 1866 try { 1867 Bundle extras = extrasForInstallResult(res); 1868 installObserver.onPackageInstalled(res.name, res.returnCode, 1869 res.returnMsg, extras); 1870 } catch (RemoteException e) { 1871 Slog.i(TAG, "Observer no longer exists."); 1872 } 1873 } 1874 } 1875 1876 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1877 PackageParser.Package pkg) { 1878 if (pkg.parentPackage == null) { 1879 return; 1880 } 1881 if (pkg.requestedPermissions == null) { 1882 return; 1883 } 1884 final PackageSetting disabledSysParentPs = mSettings 1885 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1886 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1887 || !disabledSysParentPs.isPrivileged() 1888 || (disabledSysParentPs.childPackageNames != null 1889 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1890 return; 1891 } 1892 final int[] allUserIds = sUserManager.getUserIds(); 1893 final int permCount = pkg.requestedPermissions.size(); 1894 for (int i = 0; i < permCount; i++) { 1895 String permission = pkg.requestedPermissions.get(i); 1896 BasePermission bp = mSettings.mPermissions.get(permission); 1897 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1898 continue; 1899 } 1900 for (int userId : allUserIds) { 1901 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1902 permission, userId)) { 1903 grantRuntimePermission(pkg.packageName, permission, userId); 1904 } 1905 } 1906 } 1907 } 1908 1909 private StorageEventListener mStorageListener = new StorageEventListener() { 1910 @Override 1911 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1912 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1913 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1914 final String volumeUuid = vol.getFsUuid(); 1915 1916 // Clean up any users or apps that were removed or recreated 1917 // while this volume was missing 1918 reconcileUsers(volumeUuid); 1919 reconcileApps(volumeUuid); 1920 1921 // Clean up any install sessions that expired or were 1922 // cancelled while this volume was missing 1923 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1924 1925 loadPrivatePackages(vol); 1926 1927 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1928 unloadPrivatePackages(vol); 1929 } 1930 } 1931 1932 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1933 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1934 updateExternalMediaStatus(true, false); 1935 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1936 updateExternalMediaStatus(false, false); 1937 } 1938 } 1939 } 1940 1941 @Override 1942 public void onVolumeForgotten(String fsUuid) { 1943 if (TextUtils.isEmpty(fsUuid)) { 1944 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 1945 return; 1946 } 1947 1948 // Remove any apps installed on the forgotten volume 1949 synchronized (mPackages) { 1950 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 1951 for (PackageSetting ps : packages) { 1952 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 1953 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 1954 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 1955 } 1956 1957 mSettings.onVolumeForgotten(fsUuid); 1958 mSettings.writeLPr(); 1959 } 1960 } 1961 }; 1962 1963 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 1964 String[] grantedPermissions) { 1965 for (int userId : userIds) { 1966 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 1967 } 1968 1969 // We could have touched GID membership, so flush out packages.list 1970 synchronized (mPackages) { 1971 mSettings.writePackageListLPr(); 1972 } 1973 } 1974 1975 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 1976 String[] grantedPermissions) { 1977 SettingBase sb = (SettingBase) pkg.mExtras; 1978 if (sb == null) { 1979 return; 1980 } 1981 1982 PermissionsState permissionsState = sb.getPermissionsState(); 1983 1984 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 1985 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 1986 1987 synchronized (mPackages) { 1988 for (String permission : pkg.requestedPermissions) { 1989 BasePermission bp = mSettings.mPermissions.get(permission); 1990 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 1991 && (grantedPermissions == null 1992 || ArrayUtils.contains(grantedPermissions, permission))) { 1993 final int flags = permissionsState.getPermissionFlags(permission, userId); 1994 // Installer cannot change immutable permissions. 1995 if ((flags & immutableFlags) == 0) { 1996 grantRuntimePermission(pkg.packageName, permission, userId); 1997 } 1998 } 1999 } 2000 } 2001 } 2002 2003 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2004 Bundle extras = null; 2005 switch (res.returnCode) { 2006 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2007 extras = new Bundle(); 2008 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2009 res.origPermission); 2010 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2011 res.origPackage); 2012 break; 2013 } 2014 case PackageManager.INSTALL_SUCCEEDED: { 2015 extras = new Bundle(); 2016 extras.putBoolean(Intent.EXTRA_REPLACING, 2017 res.removedInfo != null && res.removedInfo.removedPackage != null); 2018 break; 2019 } 2020 } 2021 return extras; 2022 } 2023 2024 void scheduleWriteSettingsLocked() { 2025 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2026 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2027 } 2028 } 2029 2030 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2031 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2032 scheduleWritePackageRestrictionsLocked(userId); 2033 } 2034 2035 void scheduleWritePackageRestrictionsLocked(int userId) { 2036 final int[] userIds = (userId == UserHandle.USER_ALL) 2037 ? sUserManager.getUserIds() : new int[]{userId}; 2038 for (int nextUserId : userIds) { 2039 if (!sUserManager.exists(nextUserId)) return; 2040 mDirtyUsers.add(nextUserId); 2041 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2042 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2043 } 2044 } 2045 } 2046 2047 public static PackageManagerService main(Context context, Installer installer, 2048 boolean factoryTest, boolean onlyCore) { 2049 // Self-check for initial settings. 2050 PackageManagerServiceCompilerMapping.checkProperties(); 2051 2052 PackageManagerService m = new PackageManagerService(context, installer, 2053 factoryTest, onlyCore); 2054 m.enableSystemUserPackages(); 2055 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2056 // disabled after already being started. 2057 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2058 UserHandle.USER_SYSTEM); 2059 ServiceManager.addService("package", m); 2060 return m; 2061 } 2062 2063 private void enableSystemUserPackages() { 2064 if (!UserManager.isSplitSystemUser()) { 2065 return; 2066 } 2067 // For system user, enable apps based on the following conditions: 2068 // - app is whitelisted or belong to one of these groups: 2069 // -- system app which has no launcher icons 2070 // -- system app which has INTERACT_ACROSS_USERS permission 2071 // -- system IME app 2072 // - app is not in the blacklist 2073 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2074 Set<String> enableApps = new ArraySet<>(); 2075 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2076 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2077 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2078 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2079 enableApps.addAll(wlApps); 2080 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2081 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2082 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2083 enableApps.removeAll(blApps); 2084 Log.i(TAG, "Applications installed for system user: " + enableApps); 2085 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2086 UserHandle.SYSTEM); 2087 final int allAppsSize = allAps.size(); 2088 synchronized (mPackages) { 2089 for (int i = 0; i < allAppsSize; i++) { 2090 String pName = allAps.get(i); 2091 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2092 // Should not happen, but we shouldn't be failing if it does 2093 if (pkgSetting == null) { 2094 continue; 2095 } 2096 boolean install = enableApps.contains(pName); 2097 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2098 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2099 + " for system user"); 2100 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2101 } 2102 } 2103 } 2104 } 2105 2106 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2107 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2108 Context.DISPLAY_SERVICE); 2109 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2110 } 2111 2112 public PackageManagerService(Context context, Installer installer, 2113 boolean factoryTest, boolean onlyCore) { 2114 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2115 SystemClock.uptimeMillis()); 2116 2117 if (mSdkVersion <= 0) { 2118 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2119 } 2120 2121 mContext = context; 2122 mFactoryTest = factoryTest; 2123 mOnlyCore = onlyCore; 2124 mMetrics = new DisplayMetrics(); 2125 mSettings = new Settings(mPackages); 2126 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2127 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2128 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2129 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2130 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2131 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2132 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2133 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2134 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2135 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2136 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2137 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2138 2139 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2140 if (separateProcesses != null && separateProcesses.length() > 0) { 2141 if ("*".equals(separateProcesses)) { 2142 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2143 mSeparateProcesses = null; 2144 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2145 } else { 2146 mDefParseFlags = 0; 2147 mSeparateProcesses = separateProcesses.split(","); 2148 Slog.w(TAG, "Running with debug.separate_processes: " 2149 + separateProcesses); 2150 } 2151 } else { 2152 mDefParseFlags = 0; 2153 mSeparateProcesses = null; 2154 } 2155 2156 mInstaller = installer; 2157 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2158 "*dexopt*"); 2159 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2160 2161 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2162 FgThread.get().getLooper()); 2163 2164 getDefaultDisplayMetrics(context, mMetrics); 2165 2166 SystemConfig systemConfig = SystemConfig.getInstance(); 2167 mGlobalGids = systemConfig.getGlobalGids(); 2168 mSystemPermissions = systemConfig.getSystemPermissions(); 2169 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2170 2171 synchronized (mInstallLock) { 2172 // writer 2173 synchronized (mPackages) { 2174 mHandlerThread = new ServiceThread(TAG, 2175 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2176 mHandlerThread.start(); 2177 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2178 mProcessLoggingHandler = new ProcessLoggingHandler(); 2179 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2180 2181 File dataDir = Environment.getDataDirectory(); 2182 mAppInstallDir = new File(dataDir, "app"); 2183 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2184 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2185 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2186 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2187 2188 sUserManager = new UserManagerService(context, this, mPackages); 2189 2190 // Propagate permission configuration in to package manager. 2191 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2192 = systemConfig.getPermissions(); 2193 for (int i=0; i<permConfig.size(); i++) { 2194 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2195 BasePermission bp = mSettings.mPermissions.get(perm.name); 2196 if (bp == null) { 2197 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2198 mSettings.mPermissions.put(perm.name, bp); 2199 } 2200 if (perm.gids != null) { 2201 bp.setGids(perm.gids, perm.perUser); 2202 } 2203 } 2204 2205 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2206 for (int i=0; i<libConfig.size(); i++) { 2207 mSharedLibraries.put(libConfig.keyAt(i), 2208 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2209 } 2210 2211 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2212 2213 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2214 2215 String customResolverActivity = Resources.getSystem().getString( 2216 R.string.config_customResolverActivity); 2217 if (TextUtils.isEmpty(customResolverActivity)) { 2218 customResolverActivity = null; 2219 } else { 2220 mCustomResolverComponentName = ComponentName.unflattenFromString( 2221 customResolverActivity); 2222 } 2223 2224 long startTime = SystemClock.uptimeMillis(); 2225 2226 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2227 startTime); 2228 2229 // Set flag to monitor and not change apk file paths when 2230 // scanning install directories. 2231 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2232 2233 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2234 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2235 2236 if (bootClassPath == null) { 2237 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2238 } 2239 2240 if (systemServerClassPath == null) { 2241 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2242 } 2243 2244 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2245 final String[] dexCodeInstructionSets = 2246 getDexCodeInstructionSets( 2247 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2248 2249 /** 2250 * Ensure all external libraries have had dexopt run on them. 2251 */ 2252 if (mSharedLibraries.size() > 0) { 2253 // NOTE: For now, we're compiling these system "shared libraries" 2254 // (and framework jars) into all available architectures. It's possible 2255 // to compile them only when we come across an app that uses them (there's 2256 // already logic for that in scanPackageLI) but that adds some complexity. 2257 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2258 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2259 final String lib = libEntry.path; 2260 if (lib == null) { 2261 continue; 2262 } 2263 2264 try { 2265 // Shared libraries do not have profiles so we perform a full 2266 // AOT compilation (if needed). 2267 int dexoptNeeded = DexFile.getDexOptNeeded( 2268 lib, dexCodeInstructionSet, 2269 getCompilerFilterForReason(REASON_SHARED_APK), 2270 false /* newProfile */); 2271 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2272 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2273 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2274 getCompilerFilterForReason(REASON_SHARED_APK), 2275 StorageManager.UUID_PRIVATE_INTERNAL); 2276 } 2277 } catch (FileNotFoundException e) { 2278 Slog.w(TAG, "Library not found: " + lib); 2279 } catch (IOException | InstallerException e) { 2280 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2281 + e.getMessage()); 2282 } 2283 } 2284 } 2285 } 2286 2287 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2288 2289 final VersionInfo ver = mSettings.getInternalVersion(); 2290 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2291 2292 // when upgrading from pre-M, promote system app permissions from install to runtime 2293 mPromoteSystemApps = 2294 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2295 2296 // save off the names of pre-existing system packages prior to scanning; we don't 2297 // want to automatically grant runtime permissions for new system apps 2298 if (mPromoteSystemApps) { 2299 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2300 while (pkgSettingIter.hasNext()) { 2301 PackageSetting ps = pkgSettingIter.next(); 2302 if (isSystemApp(ps)) { 2303 mExistingSystemPackages.add(ps.name); 2304 } 2305 } 2306 } 2307 2308 // When upgrading from pre-N, we need to handle package extraction like first boot, 2309 // as there is no profiling data available. 2310 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2311 mSettings.setNWorkDone(); 2312 2313 // Collect vendor overlay packages. 2314 // (Do this before scanning any apps.) 2315 // For security and version matching reason, only consider 2316 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2317 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2318 scanDirTracedLI(vendorOverlayDir, PackageParser.PARSE_IS_SYSTEM 2319 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2320 2321 // Find base frameworks (resource packages without code). 2322 scanDirTracedLI(frameworkDir, PackageParser.PARSE_IS_SYSTEM 2323 | PackageParser.PARSE_IS_SYSTEM_DIR 2324 | PackageParser.PARSE_IS_PRIVILEGED, 2325 scanFlags | SCAN_NO_DEX, 0); 2326 2327 // Collected privileged system packages. 2328 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2329 scanDirTracedLI(privilegedAppDir, PackageParser.PARSE_IS_SYSTEM 2330 | PackageParser.PARSE_IS_SYSTEM_DIR 2331 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2332 2333 // Collect ordinary system packages. 2334 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2335 scanDirTracedLI(systemAppDir, PackageParser.PARSE_IS_SYSTEM 2336 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2337 2338 // Collect all vendor packages. 2339 File vendorAppDir = new File("/vendor/app"); 2340 try { 2341 vendorAppDir = vendorAppDir.getCanonicalFile(); 2342 } catch (IOException e) { 2343 // failed to look up canonical path, continue with original one 2344 } 2345 scanDirTracedLI(vendorAppDir, PackageParser.PARSE_IS_SYSTEM 2346 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2347 2348 // Collect all OEM packages. 2349 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2350 scanDirTracedLI(oemAppDir, PackageParser.PARSE_IS_SYSTEM 2351 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2352 2353 // Prune any system packages that no longer exist. 2354 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2355 if (!mOnlyCore) { 2356 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2357 while (psit.hasNext()) { 2358 PackageSetting ps = psit.next(); 2359 2360 /* 2361 * If this is not a system app, it can't be a 2362 * disable system app. 2363 */ 2364 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2365 continue; 2366 } 2367 2368 /* 2369 * If the package is scanned, it's not erased. 2370 */ 2371 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2372 if (scannedPkg != null) { 2373 /* 2374 * If the system app is both scanned and in the 2375 * disabled packages list, then it must have been 2376 * added via OTA. Remove it from the currently 2377 * scanned package so the previously user-installed 2378 * application can be scanned. 2379 */ 2380 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2381 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2382 + ps.name + "; removing system app. Last known codePath=" 2383 + ps.codePathString + ", installStatus=" + ps.installStatus 2384 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2385 + scannedPkg.mVersionCode); 2386 removePackageLI(scannedPkg, true); 2387 mExpectingBetter.put(ps.name, ps.codePath); 2388 } 2389 2390 continue; 2391 } 2392 2393 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2394 psit.remove(); 2395 logCriticalInfo(Log.WARN, "System package " + ps.name 2396 + " no longer exists; it's data will be wiped"); 2397 // Actual deletion of code and data will be handled by later 2398 // reconciliation step 2399 } else { 2400 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2401 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2402 possiblyDeletedUpdatedSystemApps.add(ps.name); 2403 } 2404 } 2405 } 2406 } 2407 2408 //look for any incomplete package installations 2409 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2410 for (int i = 0; i < deletePkgsList.size(); i++) { 2411 // Actual deletion of code and data will be handled by later 2412 // reconciliation step 2413 final String packageName = deletePkgsList.get(i).name; 2414 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2415 synchronized (mPackages) { 2416 mSettings.removePackageLPw(packageName); 2417 } 2418 } 2419 2420 //delete tmp files 2421 deleteTempPackageFiles(); 2422 2423 // Remove any shared userIDs that have no associated packages 2424 mSettings.pruneSharedUsersLPw(); 2425 2426 if (!mOnlyCore) { 2427 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2428 SystemClock.uptimeMillis()); 2429 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2430 2431 scanDirTracedLI(mDrmAppPrivateInstallDir, PackageParser.PARSE_FORWARD_LOCK, 2432 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2433 2434 scanDirLI(mEphemeralInstallDir, PackageParser.PARSE_IS_EPHEMERAL, 2435 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2436 2437 /** 2438 * Remove disable package settings for any updated system 2439 * apps that were removed via an OTA. If they're not a 2440 * previously-updated app, remove them completely. 2441 * Otherwise, just revoke their system-level permissions. 2442 */ 2443 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2444 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2445 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2446 2447 String msg; 2448 if (deletedPkg == null) { 2449 msg = "Updated system package " + deletedAppName 2450 + " no longer exists; it's data will be wiped"; 2451 // Actual deletion of code and data will be handled by later 2452 // reconciliation step 2453 } else { 2454 msg = "Updated system app + " + deletedAppName 2455 + " no longer present; removing system privileges for " 2456 + deletedAppName; 2457 2458 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2459 2460 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2461 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2462 } 2463 logCriticalInfo(Log.WARN, msg); 2464 } 2465 2466 /** 2467 * Make sure all system apps that we expected to appear on 2468 * the userdata partition actually showed up. If they never 2469 * appeared, crawl back and revive the system version. 2470 */ 2471 for (int i = 0; i < mExpectingBetter.size(); i++) { 2472 final String packageName = mExpectingBetter.keyAt(i); 2473 if (!mPackages.containsKey(packageName)) { 2474 final File scanFile = mExpectingBetter.valueAt(i); 2475 2476 logCriticalInfo(Log.WARN, "Expected better " + packageName 2477 + " but never showed up; reverting to system"); 2478 2479 final int reparseFlags; 2480 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2481 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2482 | PackageParser.PARSE_IS_SYSTEM_DIR 2483 | PackageParser.PARSE_IS_PRIVILEGED; 2484 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2485 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2486 | PackageParser.PARSE_IS_SYSTEM_DIR; 2487 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2488 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2489 | PackageParser.PARSE_IS_SYSTEM_DIR; 2490 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2491 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2492 | PackageParser.PARSE_IS_SYSTEM_DIR; 2493 } else { 2494 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2495 continue; 2496 } 2497 2498 mSettings.enableSystemPackageLPw(packageName); 2499 2500 try { 2501 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2502 } catch (PackageManagerException e) { 2503 Slog.e(TAG, "Failed to parse original system package: " 2504 + e.getMessage()); 2505 } 2506 } 2507 } 2508 } 2509 mExpectingBetter.clear(); 2510 2511 // Resolve protected action filters. Only the setup wizard is allowed to 2512 // have a high priority filter for these actions. 2513 mSetupWizardPackage = getSetupWizardPackageName(); 2514 if (mProtectedFilters.size() > 0) { 2515 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2516 Slog.i(TAG, "No setup wizard;" 2517 + " All protected intents capped to priority 0"); 2518 } 2519 for (ActivityIntentInfo filter : mProtectedFilters) { 2520 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2521 if (DEBUG_FILTERS) { 2522 Slog.i(TAG, "Found setup wizard;" 2523 + " allow priority " + filter.getPriority() + ";" 2524 + " package: " + filter.activity.info.packageName 2525 + " activity: " + filter.activity.className 2526 + " priority: " + filter.getPriority()); 2527 } 2528 // skip setup wizard; allow it to keep the high priority filter 2529 continue; 2530 } 2531 Slog.w(TAG, "Protected action; cap priority to 0;" 2532 + " package: " + filter.activity.info.packageName 2533 + " activity: " + filter.activity.className 2534 + " origPrio: " + filter.getPriority()); 2535 filter.setPriority(0); 2536 } 2537 } 2538 mDeferProtectedFilters = false; 2539 mProtectedFilters.clear(); 2540 2541 // Now that we know all of the shared libraries, update all clients to have 2542 // the correct library paths. 2543 updateAllSharedLibrariesLPw(); 2544 2545 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2546 // NOTE: We ignore potential failures here during a system scan (like 2547 // the rest of the commands above) because there's precious little we 2548 // can do about it. A settings error is reported, though. 2549 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2550 false /* boot complete */); 2551 } 2552 2553 // Now that we know all the packages we are keeping, 2554 // read and update their last usage times. 2555 mPackageUsage.readLP(); 2556 2557 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2558 SystemClock.uptimeMillis()); 2559 Slog.i(TAG, "Time to scan packages: " 2560 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2561 + " seconds"); 2562 2563 // If the platform SDK has changed since the last time we booted, 2564 // we need to re-grant app permission to catch any new ones that 2565 // appear. This is really a hack, and means that apps can in some 2566 // cases get permissions that the user didn't initially explicitly 2567 // allow... it would be nice to have some better way to handle 2568 // this situation. 2569 int updateFlags = UPDATE_PERMISSIONS_ALL; 2570 if (ver.sdkVersion != mSdkVersion) { 2571 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2572 + mSdkVersion + "; regranting permissions for internal storage"); 2573 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2574 } 2575 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2576 ver.sdkVersion = mSdkVersion; 2577 2578 // If this is the first boot or an update from pre-M, and it is a normal 2579 // boot, then we need to initialize the default preferred apps across 2580 // all defined users. 2581 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2582 for (UserInfo user : sUserManager.getUsers(true)) { 2583 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2584 applyFactoryDefaultBrowserLPw(user.id); 2585 primeDomainVerificationsLPw(user.id); 2586 } 2587 } 2588 2589 // Prepare storage for system user really early during boot, 2590 // since core system apps like SettingsProvider and SystemUI 2591 // can't wait for user to start 2592 final int storageFlags; 2593 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2594 storageFlags = StorageManager.FLAG_STORAGE_DE; 2595 } else { 2596 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2597 } 2598 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2599 storageFlags); 2600 2601 // If this is first boot after an OTA, and a normal boot, then 2602 // we need to clear code cache directories. 2603 if (mIsUpgrade && !onlyCore) { 2604 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2605 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2606 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2607 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2608 // No apps are running this early, so no need to freeze 2609 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2610 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2611 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2612 } 2613 clearAppProfilesLIF(ps.pkg); 2614 } 2615 ver.fingerprint = Build.FINGERPRINT; 2616 } 2617 2618 checkDefaultBrowser(); 2619 2620 // clear only after permissions and other defaults have been updated 2621 mExistingSystemPackages.clear(); 2622 mPromoteSystemApps = false; 2623 2624 // All the changes are done during package scanning. 2625 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2626 2627 // can downgrade to reader 2628 mSettings.writeLPr(); 2629 2630 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2631 SystemClock.uptimeMillis()); 2632 2633 if (!mOnlyCore) { 2634 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2635 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2636 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2637 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2638 mIntentFilterVerifierComponent); 2639 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2640 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2641 getRequiredSharedLibraryLPr( 2642 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2643 } else { 2644 mRequiredVerifierPackage = null; 2645 mRequiredInstallerPackage = null; 2646 mIntentFilterVerifierComponent = null; 2647 mIntentFilterVerifier = null; 2648 mServicesSystemSharedLibraryPackageName = null; 2649 } 2650 2651 mInstallerService = new PackageInstallerService(context, this); 2652 2653 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2654 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2655 // both the installer and resolver must be present to enable ephemeral 2656 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2657 if (DEBUG_EPHEMERAL) { 2658 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2659 + " installer:" + ephemeralInstallerComponent); 2660 } 2661 mEphemeralResolverComponent = ephemeralResolverComponent; 2662 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2663 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2664 mEphemeralResolverConnection = 2665 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2666 } else { 2667 if (DEBUG_EPHEMERAL) { 2668 final String missingComponent = 2669 (ephemeralResolverComponent == null) 2670 ? (ephemeralInstallerComponent == null) 2671 ? "resolver and installer" 2672 : "resolver" 2673 : "installer"; 2674 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2675 } 2676 mEphemeralResolverComponent = null; 2677 mEphemeralInstallerComponent = null; 2678 mEphemeralResolverConnection = null; 2679 } 2680 2681 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2682 } // synchronized (mPackages) 2683 } // synchronized (mInstallLock) 2684 2685 // Now after opening every single application zip, make sure they 2686 // are all flushed. Not really needed, but keeps things nice and 2687 // tidy. 2688 Runtime.getRuntime().gc(); 2689 2690 // The initial scanning above does many calls into installd while 2691 // holding the mPackages lock, but we're mostly interested in yelling 2692 // once we have a booted system. 2693 mInstaller.setWarnIfHeld(mPackages); 2694 2695 // Expose private service for system components to use. 2696 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2697 } 2698 2699 @Override 2700 public boolean isFirstBoot() { 2701 return !mRestoredSettings; 2702 } 2703 2704 @Override 2705 public boolean isOnlyCoreApps() { 2706 return mOnlyCore; 2707 } 2708 2709 @Override 2710 public boolean isUpgrade() { 2711 return mIsUpgrade; 2712 } 2713 2714 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2715 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2716 2717 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2718 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2719 UserHandle.USER_SYSTEM); 2720 if (matches.size() == 1) { 2721 return matches.get(0).getComponentInfo().packageName; 2722 } else { 2723 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2724 return null; 2725 } 2726 } 2727 2728 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2729 synchronized (mPackages) { 2730 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2731 if (libraryEntry == null) { 2732 throw new IllegalStateException("Missing required shared library:" + libraryName); 2733 } 2734 return libraryEntry.apk; 2735 } 2736 } 2737 2738 private @NonNull String getRequiredInstallerLPr() { 2739 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2740 intent.addCategory(Intent.CATEGORY_DEFAULT); 2741 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2742 2743 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2744 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2745 UserHandle.USER_SYSTEM); 2746 if (matches.size() == 1) { 2747 ResolveInfo resolveInfo = matches.get(0); 2748 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2749 throw new RuntimeException("The installer must be a privileged app"); 2750 } 2751 return matches.get(0).getComponentInfo().packageName; 2752 } else { 2753 throw new RuntimeException("There must be exactly one installer; found " + matches); 2754 } 2755 } 2756 2757 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2758 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2759 2760 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2761 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2762 UserHandle.USER_SYSTEM); 2763 ResolveInfo best = null; 2764 final int N = matches.size(); 2765 for (int i = 0; i < N; i++) { 2766 final ResolveInfo cur = matches.get(i); 2767 final String packageName = cur.getComponentInfo().packageName; 2768 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2769 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2770 continue; 2771 } 2772 2773 if (best == null || cur.priority > best.priority) { 2774 best = cur; 2775 } 2776 } 2777 2778 if (best != null) { 2779 return best.getComponentInfo().getComponentName(); 2780 } else { 2781 throw new RuntimeException("There must be at least one intent filter verifier"); 2782 } 2783 } 2784 2785 private @Nullable ComponentName getEphemeralResolverLPr() { 2786 final String[] packageArray = 2787 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2788 if (packageArray.length == 0) { 2789 if (DEBUG_EPHEMERAL) { 2790 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2791 } 2792 return null; 2793 } 2794 2795 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2796 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2797 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2798 UserHandle.USER_SYSTEM); 2799 2800 final int N = resolvers.size(); 2801 if (N == 0) { 2802 if (DEBUG_EPHEMERAL) { 2803 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2804 } 2805 return null; 2806 } 2807 2808 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2809 for (int i = 0; i < N; i++) { 2810 final ResolveInfo info = resolvers.get(i); 2811 2812 if (info.serviceInfo == null) { 2813 continue; 2814 } 2815 2816 final String packageName = info.serviceInfo.packageName; 2817 if (!possiblePackages.contains(packageName)) { 2818 if (DEBUG_EPHEMERAL) { 2819 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2820 + " pkg: " + packageName + ", info:" + info); 2821 } 2822 continue; 2823 } 2824 2825 if (DEBUG_EPHEMERAL) { 2826 Slog.v(TAG, "Ephemeral resolver found;" 2827 + " pkg: " + packageName + ", info:" + info); 2828 } 2829 return new ComponentName(packageName, info.serviceInfo.name); 2830 } 2831 if (DEBUG_EPHEMERAL) { 2832 Slog.v(TAG, "Ephemeral resolver NOT found"); 2833 } 2834 return null; 2835 } 2836 2837 private @Nullable ComponentName getEphemeralInstallerLPr() { 2838 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2839 intent.addCategory(Intent.CATEGORY_DEFAULT); 2840 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2841 2842 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2843 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2844 UserHandle.USER_SYSTEM); 2845 if (matches.size() == 0) { 2846 return null; 2847 } else if (matches.size() == 1) { 2848 return matches.get(0).getComponentInfo().getComponentName(); 2849 } else { 2850 throw new RuntimeException( 2851 "There must be at most one ephemeral installer; found " + matches); 2852 } 2853 } 2854 2855 private void primeDomainVerificationsLPw(int userId) { 2856 if (DEBUG_DOMAIN_VERIFICATION) { 2857 Slog.d(TAG, "Priming domain verifications in user " + userId); 2858 } 2859 2860 SystemConfig systemConfig = SystemConfig.getInstance(); 2861 ArraySet<String> packages = systemConfig.getLinkedApps(); 2862 ArraySet<String> domains = new ArraySet<String>(); 2863 2864 for (String packageName : packages) { 2865 PackageParser.Package pkg = mPackages.get(packageName); 2866 if (pkg != null) { 2867 if (!pkg.isSystemApp()) { 2868 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2869 continue; 2870 } 2871 2872 domains.clear(); 2873 for (PackageParser.Activity a : pkg.activities) { 2874 for (ActivityIntentInfo filter : a.intents) { 2875 if (hasValidDomains(filter)) { 2876 domains.addAll(filter.getHostsList()); 2877 } 2878 } 2879 } 2880 2881 if (domains.size() > 0) { 2882 if (DEBUG_DOMAIN_VERIFICATION) { 2883 Slog.v(TAG, " + " + packageName); 2884 } 2885 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2886 // state w.r.t. the formal app-linkage "no verification attempted" state; 2887 // and then 'always' in the per-user state actually used for intent resolution. 2888 final IntentFilterVerificationInfo ivi; 2889 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2890 new ArrayList<String>(domains)); 2891 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2892 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2893 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2894 } else { 2895 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2896 + "' does not handle web links"); 2897 } 2898 } else { 2899 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2900 } 2901 } 2902 2903 scheduleWritePackageRestrictionsLocked(userId); 2904 scheduleWriteSettingsLocked(); 2905 } 2906 2907 private void applyFactoryDefaultBrowserLPw(int userId) { 2908 // The default browser app's package name is stored in a string resource, 2909 // with a product-specific overlay used for vendor customization. 2910 String browserPkg = mContext.getResources().getString( 2911 com.android.internal.R.string.default_browser); 2912 if (!TextUtils.isEmpty(browserPkg)) { 2913 // non-empty string => required to be a known package 2914 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2915 if (ps == null) { 2916 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2917 browserPkg = null; 2918 } else { 2919 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2920 } 2921 } 2922 2923 // Nothing valid explicitly set? Make the factory-installed browser the explicit 2924 // default. If there's more than one, just leave everything alone. 2925 if (browserPkg == null) { 2926 calculateDefaultBrowserLPw(userId); 2927 } 2928 } 2929 2930 private void calculateDefaultBrowserLPw(int userId) { 2931 List<String> allBrowsers = resolveAllBrowserApps(userId); 2932 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 2933 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2934 } 2935 2936 private List<String> resolveAllBrowserApps(int userId) { 2937 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 2938 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2939 PackageManager.MATCH_ALL, userId); 2940 2941 final int count = list.size(); 2942 List<String> result = new ArrayList<String>(count); 2943 for (int i=0; i<count; i++) { 2944 ResolveInfo info = list.get(i); 2945 if (info.activityInfo == null 2946 || !info.handleAllWebDataURI 2947 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 2948 || result.contains(info.activityInfo.packageName)) { 2949 continue; 2950 } 2951 result.add(info.activityInfo.packageName); 2952 } 2953 2954 return result; 2955 } 2956 2957 private boolean packageIsBrowser(String packageName, int userId) { 2958 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 2959 PackageManager.MATCH_ALL, userId); 2960 final int N = list.size(); 2961 for (int i = 0; i < N; i++) { 2962 ResolveInfo info = list.get(i); 2963 if (packageName.equals(info.activityInfo.packageName)) { 2964 return true; 2965 } 2966 } 2967 return false; 2968 } 2969 2970 private void checkDefaultBrowser() { 2971 final int myUserId = UserHandle.myUserId(); 2972 final String packageName = getDefaultBrowserPackageName(myUserId); 2973 if (packageName != null) { 2974 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 2975 if (info == null) { 2976 Slog.w(TAG, "Default browser no longer installed: " + packageName); 2977 synchronized (mPackages) { 2978 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 2979 } 2980 } 2981 } 2982 } 2983 2984 @Override 2985 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 2986 throws RemoteException { 2987 try { 2988 return super.onTransact(code, data, reply, flags); 2989 } catch (RuntimeException e) { 2990 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 2991 Slog.wtf(TAG, "Package Manager Crash", e); 2992 } 2993 throw e; 2994 } 2995 } 2996 2997 static int[] appendInts(int[] cur, int[] add) { 2998 if (add == null) return cur; 2999 if (cur == null) return add; 3000 final int N = add.length; 3001 for (int i=0; i<N; i++) { 3002 cur = appendInt(cur, add[i]); 3003 } 3004 return cur; 3005 } 3006 3007 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3008 if (!sUserManager.exists(userId)) return null; 3009 if (ps == null) { 3010 return null; 3011 } 3012 final PackageParser.Package p = ps.pkg; 3013 if (p == null) { 3014 return null; 3015 } 3016 3017 final PermissionsState permissionsState = ps.getPermissionsState(); 3018 3019 final int[] gids = permissionsState.computeGids(userId); 3020 final Set<String> permissions = permissionsState.getPermissions(userId); 3021 final PackageUserState state = ps.readUserState(userId); 3022 3023 return PackageParser.generatePackageInfo(p, gids, flags, 3024 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3025 } 3026 3027 @Override 3028 public void checkPackageStartable(String packageName, int userId) { 3029 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3030 3031 synchronized (mPackages) { 3032 final PackageSetting ps = mSettings.mPackages.get(packageName); 3033 if (ps == null) { 3034 throw new SecurityException("Package " + packageName + " was not found!"); 3035 } 3036 3037 if (!ps.getInstalled(userId)) { 3038 throw new SecurityException( 3039 "Package " + packageName + " was not installed for user " + userId + "!"); 3040 } 3041 3042 if (mSafeMode && !ps.isSystem()) { 3043 throw new SecurityException("Package " + packageName + " not a system app!"); 3044 } 3045 3046 if (mFrozenPackages.contains(packageName)) { 3047 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3048 } 3049 3050 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3051 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3052 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3053 } 3054 } 3055 } 3056 3057 @Override 3058 public boolean isPackageAvailable(String packageName, int userId) { 3059 if (!sUserManager.exists(userId)) return false; 3060 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3061 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3062 synchronized (mPackages) { 3063 PackageParser.Package p = mPackages.get(packageName); 3064 if (p != null) { 3065 final PackageSetting ps = (PackageSetting) p.mExtras; 3066 if (ps != null) { 3067 final PackageUserState state = ps.readUserState(userId); 3068 if (state != null) { 3069 return PackageParser.isAvailable(state); 3070 } 3071 } 3072 } 3073 } 3074 return false; 3075 } 3076 3077 @Override 3078 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3079 if (!sUserManager.exists(userId)) return null; 3080 flags = updateFlagsForPackage(flags, userId, packageName); 3081 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3082 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3083 // reader 3084 synchronized (mPackages) { 3085 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3086 PackageParser.Package p = null; 3087 if (matchFactoryOnly) { 3088 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3089 if (ps != null) { 3090 return generatePackageInfo(ps, flags, userId); 3091 } 3092 } 3093 if (p == null) { 3094 p = mPackages.get(packageName); 3095 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3096 return null; 3097 } 3098 } 3099 if (DEBUG_PACKAGE_INFO) 3100 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3101 if (p != null) { 3102 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3103 } 3104 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3105 final PackageSetting ps = mSettings.mPackages.get(packageName); 3106 return generatePackageInfo(ps, flags, userId); 3107 } 3108 } 3109 return null; 3110 } 3111 3112 @Override 3113 public String[] currentToCanonicalPackageNames(String[] names) { 3114 String[] out = new String[names.length]; 3115 // reader 3116 synchronized (mPackages) { 3117 for (int i=names.length-1; i>=0; i--) { 3118 PackageSetting ps = mSettings.mPackages.get(names[i]); 3119 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3120 } 3121 } 3122 return out; 3123 } 3124 3125 @Override 3126 public String[] canonicalToCurrentPackageNames(String[] names) { 3127 String[] out = new String[names.length]; 3128 // reader 3129 synchronized (mPackages) { 3130 for (int i=names.length-1; i>=0; i--) { 3131 String cur = mSettings.mRenamedPackages.get(names[i]); 3132 out[i] = cur != null ? cur : names[i]; 3133 } 3134 } 3135 return out; 3136 } 3137 3138 @Override 3139 public int getPackageUid(String packageName, int flags, int userId) { 3140 if (!sUserManager.exists(userId)) return -1; 3141 flags = updateFlagsForPackage(flags, userId, packageName); 3142 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3143 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3144 3145 // reader 3146 synchronized (mPackages) { 3147 final PackageParser.Package p = mPackages.get(packageName); 3148 if (p != null && p.isMatch(flags)) { 3149 return UserHandle.getUid(userId, p.applicationInfo.uid); 3150 } 3151 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3152 final PackageSetting ps = mSettings.mPackages.get(packageName); 3153 if (ps != null && ps.isMatch(flags)) { 3154 return UserHandle.getUid(userId, ps.appId); 3155 } 3156 } 3157 } 3158 3159 return -1; 3160 } 3161 3162 @Override 3163 public int[] getPackageGids(String packageName, int flags, int userId) { 3164 if (!sUserManager.exists(userId)) return null; 3165 flags = updateFlagsForPackage(flags, userId, packageName); 3166 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3167 false /* requireFullPermission */, false /* checkShell */, 3168 "getPackageGids"); 3169 3170 // reader 3171 synchronized (mPackages) { 3172 final PackageParser.Package p = mPackages.get(packageName); 3173 if (p != null && p.isMatch(flags)) { 3174 PackageSetting ps = (PackageSetting) p.mExtras; 3175 return ps.getPermissionsState().computeGids(userId); 3176 } 3177 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3178 final PackageSetting ps = mSettings.mPackages.get(packageName); 3179 if (ps != null && ps.isMatch(flags)) { 3180 return ps.getPermissionsState().computeGids(userId); 3181 } 3182 } 3183 } 3184 3185 return null; 3186 } 3187 3188 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3189 if (bp.perm != null) { 3190 return PackageParser.generatePermissionInfo(bp.perm, flags); 3191 } 3192 PermissionInfo pi = new PermissionInfo(); 3193 pi.name = bp.name; 3194 pi.packageName = bp.sourcePackage; 3195 pi.nonLocalizedLabel = bp.name; 3196 pi.protectionLevel = bp.protectionLevel; 3197 return pi; 3198 } 3199 3200 @Override 3201 public PermissionInfo getPermissionInfo(String name, int flags) { 3202 // reader 3203 synchronized (mPackages) { 3204 final BasePermission p = mSettings.mPermissions.get(name); 3205 if (p != null) { 3206 return generatePermissionInfo(p, flags); 3207 } 3208 return null; 3209 } 3210 } 3211 3212 @Override 3213 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3214 int flags) { 3215 // reader 3216 synchronized (mPackages) { 3217 if (group != null && !mPermissionGroups.containsKey(group)) { 3218 // This is thrown as NameNotFoundException 3219 return null; 3220 } 3221 3222 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3223 for (BasePermission p : mSettings.mPermissions.values()) { 3224 if (group == null) { 3225 if (p.perm == null || p.perm.info.group == null) { 3226 out.add(generatePermissionInfo(p, flags)); 3227 } 3228 } else { 3229 if (p.perm != null && group.equals(p.perm.info.group)) { 3230 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3231 } 3232 } 3233 } 3234 return new ParceledListSlice<>(out); 3235 } 3236 } 3237 3238 @Override 3239 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3240 // reader 3241 synchronized (mPackages) { 3242 return PackageParser.generatePermissionGroupInfo( 3243 mPermissionGroups.get(name), flags); 3244 } 3245 } 3246 3247 @Override 3248 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3249 // reader 3250 synchronized (mPackages) { 3251 final int N = mPermissionGroups.size(); 3252 ArrayList<PermissionGroupInfo> out 3253 = new ArrayList<PermissionGroupInfo>(N); 3254 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3255 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3256 } 3257 return new ParceledListSlice<>(out); 3258 } 3259 } 3260 3261 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3262 int userId) { 3263 if (!sUserManager.exists(userId)) return null; 3264 PackageSetting ps = mSettings.mPackages.get(packageName); 3265 if (ps != null) { 3266 if (ps.pkg == null) { 3267 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3268 if (pInfo != null) { 3269 return pInfo.applicationInfo; 3270 } 3271 return null; 3272 } 3273 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3274 ps.readUserState(userId), userId); 3275 } 3276 return null; 3277 } 3278 3279 @Override 3280 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3281 if (!sUserManager.exists(userId)) return null; 3282 flags = updateFlagsForApplication(flags, userId, packageName); 3283 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3284 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3285 // writer 3286 synchronized (mPackages) { 3287 PackageParser.Package p = mPackages.get(packageName); 3288 if (DEBUG_PACKAGE_INFO) Log.v( 3289 TAG, "getApplicationInfo " + packageName 3290 + ": " + p); 3291 if (p != null) { 3292 PackageSetting ps = mSettings.mPackages.get(packageName); 3293 if (ps == null) return null; 3294 // Note: isEnabledLP() does not apply here - always return info 3295 return PackageParser.generateApplicationInfo( 3296 p, flags, ps.readUserState(userId), userId); 3297 } 3298 if ("android".equals(packageName)||"system".equals(packageName)) { 3299 return mAndroidApplication; 3300 } 3301 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3302 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3303 } 3304 } 3305 return null; 3306 } 3307 3308 @Override 3309 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3310 final IPackageDataObserver observer) { 3311 mContext.enforceCallingOrSelfPermission( 3312 android.Manifest.permission.CLEAR_APP_CACHE, null); 3313 // Queue up an async operation since clearing cache may take a little while. 3314 mHandler.post(new Runnable() { 3315 public void run() { 3316 mHandler.removeCallbacks(this); 3317 boolean success = true; 3318 synchronized (mInstallLock) { 3319 try { 3320 mInstaller.freeCache(volumeUuid, freeStorageSize); 3321 } catch (InstallerException e) { 3322 Slog.w(TAG, "Couldn't clear application caches: " + e); 3323 success = false; 3324 } 3325 } 3326 if (observer != null) { 3327 try { 3328 observer.onRemoveCompleted(null, success); 3329 } catch (RemoteException e) { 3330 Slog.w(TAG, "RemoveException when invoking call back"); 3331 } 3332 } 3333 } 3334 }); 3335 } 3336 3337 @Override 3338 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3339 final IntentSender pi) { 3340 mContext.enforceCallingOrSelfPermission( 3341 android.Manifest.permission.CLEAR_APP_CACHE, null); 3342 // Queue up an async operation since clearing cache may take a little while. 3343 mHandler.post(new Runnable() { 3344 public void run() { 3345 mHandler.removeCallbacks(this); 3346 boolean success = true; 3347 synchronized (mInstallLock) { 3348 try { 3349 mInstaller.freeCache(volumeUuid, freeStorageSize); 3350 } catch (InstallerException e) { 3351 Slog.w(TAG, "Couldn't clear application caches: " + e); 3352 success = false; 3353 } 3354 } 3355 if(pi != null) { 3356 try { 3357 // Callback via pending intent 3358 int code = success ? 1 : 0; 3359 pi.sendIntent(null, code, null, 3360 null, null); 3361 } catch (SendIntentException e1) { 3362 Slog.i(TAG, "Failed to send pending intent"); 3363 } 3364 } 3365 } 3366 }); 3367 } 3368 3369 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3370 synchronized (mInstallLock) { 3371 try { 3372 mInstaller.freeCache(volumeUuid, freeStorageSize); 3373 } catch (InstallerException e) { 3374 throw new IOException("Failed to free enough space", e); 3375 } 3376 } 3377 } 3378 3379 /** 3380 * Return if the user key is currently unlocked. 3381 */ 3382 private boolean isUserKeyUnlocked(int userId) { 3383 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3384 final IMountService mount = IMountService.Stub 3385 .asInterface(ServiceManager.getService("mount")); 3386 if (mount == null) { 3387 Slog.w(TAG, "Early during boot, assuming locked"); 3388 return false; 3389 } 3390 final long token = Binder.clearCallingIdentity(); 3391 try { 3392 return mount.isUserKeyUnlocked(userId); 3393 } catch (RemoteException e) { 3394 throw e.rethrowAsRuntimeException(); 3395 } finally { 3396 Binder.restoreCallingIdentity(token); 3397 } 3398 } else { 3399 return true; 3400 } 3401 } 3402 3403 /** 3404 * Update given flags based on encryption status of current user. 3405 */ 3406 private int updateFlags(int flags, int userId) { 3407 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3408 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3409 // Caller expressed an explicit opinion about what encryption 3410 // aware/unaware components they want to see, so fall through and 3411 // give them what they want 3412 } else { 3413 // Caller expressed no opinion, so match based on user state 3414 if (isUserKeyUnlocked(userId)) { 3415 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3416 } else { 3417 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3418 } 3419 } 3420 return flags; 3421 } 3422 3423 /** 3424 * Update given flags when being used to request {@link PackageInfo}. 3425 */ 3426 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3427 boolean triaged = true; 3428 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3429 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3430 // Caller is asking for component details, so they'd better be 3431 // asking for specific encryption matching behavior, or be triaged 3432 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3433 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3434 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3435 triaged = false; 3436 } 3437 } 3438 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3439 | PackageManager.MATCH_SYSTEM_ONLY 3440 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3441 triaged = false; 3442 } 3443 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3444 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3445 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3446 } 3447 return updateFlags(flags, userId); 3448 } 3449 3450 /** 3451 * Update given flags when being used to request {@link ApplicationInfo}. 3452 */ 3453 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3454 return updateFlagsForPackage(flags, userId, cookie); 3455 } 3456 3457 /** 3458 * Update given flags when being used to request {@link ComponentInfo}. 3459 */ 3460 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3461 if (cookie instanceof Intent) { 3462 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3463 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3464 } 3465 } 3466 3467 boolean triaged = true; 3468 // Caller is asking for component details, so they'd better be 3469 // asking for specific encryption matching behavior, or be triaged 3470 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3471 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3472 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3473 triaged = false; 3474 } 3475 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3476 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3477 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3478 } 3479 3480 return updateFlags(flags, userId); 3481 } 3482 3483 /** 3484 * Update given flags when being used to request {@link ResolveInfo}. 3485 */ 3486 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3487 // Safe mode means we shouldn't match any third-party components 3488 if (mSafeMode) { 3489 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3490 } 3491 3492 return updateFlagsForComponent(flags, userId, cookie); 3493 } 3494 3495 @Override 3496 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3497 if (!sUserManager.exists(userId)) return null; 3498 flags = updateFlagsForComponent(flags, userId, component); 3499 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3500 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3501 synchronized (mPackages) { 3502 PackageParser.Activity a = mActivities.mActivities.get(component); 3503 3504 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3505 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3506 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3507 if (ps == null) return null; 3508 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3509 userId); 3510 } 3511 if (mResolveComponentName.equals(component)) { 3512 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3513 new PackageUserState(), userId); 3514 } 3515 } 3516 return null; 3517 } 3518 3519 @Override 3520 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3521 String resolvedType) { 3522 synchronized (mPackages) { 3523 if (component.equals(mResolveComponentName)) { 3524 // The resolver supports EVERYTHING! 3525 return true; 3526 } 3527 PackageParser.Activity a = mActivities.mActivities.get(component); 3528 if (a == null) { 3529 return false; 3530 } 3531 for (int i=0; i<a.intents.size(); i++) { 3532 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3533 intent.getData(), intent.getCategories(), TAG) >= 0) { 3534 return true; 3535 } 3536 } 3537 return false; 3538 } 3539 } 3540 3541 @Override 3542 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3543 if (!sUserManager.exists(userId)) return null; 3544 flags = updateFlagsForComponent(flags, userId, component); 3545 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3546 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3547 synchronized (mPackages) { 3548 PackageParser.Activity a = mReceivers.mActivities.get(component); 3549 if (DEBUG_PACKAGE_INFO) Log.v( 3550 TAG, "getReceiverInfo " + component + ": " + a); 3551 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3552 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3553 if (ps == null) return null; 3554 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3555 userId); 3556 } 3557 } 3558 return null; 3559 } 3560 3561 @Override 3562 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3563 if (!sUserManager.exists(userId)) return null; 3564 flags = updateFlagsForComponent(flags, userId, component); 3565 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3566 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3567 synchronized (mPackages) { 3568 PackageParser.Service s = mServices.mServices.get(component); 3569 if (DEBUG_PACKAGE_INFO) Log.v( 3570 TAG, "getServiceInfo " + component + ": " + s); 3571 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3572 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3573 if (ps == null) return null; 3574 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3575 userId); 3576 } 3577 } 3578 return null; 3579 } 3580 3581 @Override 3582 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3583 if (!sUserManager.exists(userId)) return null; 3584 flags = updateFlagsForComponent(flags, userId, component); 3585 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3586 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3587 synchronized (mPackages) { 3588 PackageParser.Provider p = mProviders.mProviders.get(component); 3589 if (DEBUG_PACKAGE_INFO) Log.v( 3590 TAG, "getProviderInfo " + component + ": " + p); 3591 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3592 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3593 if (ps == null) return null; 3594 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3595 userId); 3596 } 3597 } 3598 return null; 3599 } 3600 3601 @Override 3602 public String[] getSystemSharedLibraryNames() { 3603 Set<String> libSet; 3604 synchronized (mPackages) { 3605 libSet = mSharedLibraries.keySet(); 3606 int size = libSet.size(); 3607 if (size > 0) { 3608 String[] libs = new String[size]; 3609 libSet.toArray(libs); 3610 return libs; 3611 } 3612 } 3613 return null; 3614 } 3615 3616 @Override 3617 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3618 synchronized (mPackages) { 3619 return mServicesSystemSharedLibraryPackageName; 3620 } 3621 } 3622 3623 @Override 3624 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3625 synchronized (mPackages) { 3626 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3627 3628 final FeatureInfo fi = new FeatureInfo(); 3629 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3630 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3631 res.add(fi); 3632 3633 return new ParceledListSlice<>(res); 3634 } 3635 } 3636 3637 @Override 3638 public boolean hasSystemFeature(String name, int version) { 3639 synchronized (mPackages) { 3640 final FeatureInfo feat = mAvailableFeatures.get(name); 3641 if (feat == null) { 3642 return false; 3643 } else { 3644 return feat.version >= version; 3645 } 3646 } 3647 } 3648 3649 @Override 3650 public int checkPermission(String permName, String pkgName, int userId) { 3651 if (!sUserManager.exists(userId)) { 3652 return PackageManager.PERMISSION_DENIED; 3653 } 3654 3655 synchronized (mPackages) { 3656 final PackageParser.Package p = mPackages.get(pkgName); 3657 if (p != null && p.mExtras != null) { 3658 final PackageSetting ps = (PackageSetting) p.mExtras; 3659 final PermissionsState permissionsState = ps.getPermissionsState(); 3660 if (permissionsState.hasPermission(permName, userId)) { 3661 return PackageManager.PERMISSION_GRANTED; 3662 } 3663 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3664 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3665 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3666 return PackageManager.PERMISSION_GRANTED; 3667 } 3668 } 3669 } 3670 3671 return PackageManager.PERMISSION_DENIED; 3672 } 3673 3674 @Override 3675 public int checkUidPermission(String permName, int uid) { 3676 final int userId = UserHandle.getUserId(uid); 3677 3678 if (!sUserManager.exists(userId)) { 3679 return PackageManager.PERMISSION_DENIED; 3680 } 3681 3682 synchronized (mPackages) { 3683 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3684 if (obj != null) { 3685 final SettingBase ps = (SettingBase) obj; 3686 final PermissionsState permissionsState = ps.getPermissionsState(); 3687 if (permissionsState.hasPermission(permName, userId)) { 3688 return PackageManager.PERMISSION_GRANTED; 3689 } 3690 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3691 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3692 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3693 return PackageManager.PERMISSION_GRANTED; 3694 } 3695 } else { 3696 ArraySet<String> perms = mSystemPermissions.get(uid); 3697 if (perms != null) { 3698 if (perms.contains(permName)) { 3699 return PackageManager.PERMISSION_GRANTED; 3700 } 3701 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3702 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3703 return PackageManager.PERMISSION_GRANTED; 3704 } 3705 } 3706 } 3707 } 3708 3709 return PackageManager.PERMISSION_DENIED; 3710 } 3711 3712 @Override 3713 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3714 if (UserHandle.getCallingUserId() != userId) { 3715 mContext.enforceCallingPermission( 3716 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3717 "isPermissionRevokedByPolicy for user " + userId); 3718 } 3719 3720 if (checkPermission(permission, packageName, userId) 3721 == PackageManager.PERMISSION_GRANTED) { 3722 return false; 3723 } 3724 3725 final long identity = Binder.clearCallingIdentity(); 3726 try { 3727 final int flags = getPermissionFlags(permission, packageName, userId); 3728 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3729 } finally { 3730 Binder.restoreCallingIdentity(identity); 3731 } 3732 } 3733 3734 @Override 3735 public String getPermissionControllerPackageName() { 3736 synchronized (mPackages) { 3737 return mRequiredInstallerPackage; 3738 } 3739 } 3740 3741 /** 3742 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3743 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3744 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3745 * @param message the message to log on security exception 3746 */ 3747 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3748 boolean checkShell, String message) { 3749 if (userId < 0) { 3750 throw new IllegalArgumentException("Invalid userId " + userId); 3751 } 3752 if (checkShell) { 3753 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3754 } 3755 if (userId == UserHandle.getUserId(callingUid)) return; 3756 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3757 if (requireFullPermission) { 3758 mContext.enforceCallingOrSelfPermission( 3759 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3760 } else { 3761 try { 3762 mContext.enforceCallingOrSelfPermission( 3763 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3764 } catch (SecurityException se) { 3765 mContext.enforceCallingOrSelfPermission( 3766 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3767 } 3768 } 3769 } 3770 } 3771 3772 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3773 if (callingUid == Process.SHELL_UID) { 3774 if (userHandle >= 0 3775 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3776 throw new SecurityException("Shell does not have permission to access user " 3777 + userHandle); 3778 } else if (userHandle < 0) { 3779 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3780 + Debug.getCallers(3)); 3781 } 3782 } 3783 } 3784 3785 private BasePermission findPermissionTreeLP(String permName) { 3786 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3787 if (permName.startsWith(bp.name) && 3788 permName.length() > bp.name.length() && 3789 permName.charAt(bp.name.length()) == '.') { 3790 return bp; 3791 } 3792 } 3793 return null; 3794 } 3795 3796 private BasePermission checkPermissionTreeLP(String permName) { 3797 if (permName != null) { 3798 BasePermission bp = findPermissionTreeLP(permName); 3799 if (bp != null) { 3800 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3801 return bp; 3802 } 3803 throw new SecurityException("Calling uid " 3804 + Binder.getCallingUid() 3805 + " is not allowed to add to permission tree " 3806 + bp.name + " owned by uid " + bp.uid); 3807 } 3808 } 3809 throw new SecurityException("No permission tree found for " + permName); 3810 } 3811 3812 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3813 if (s1 == null) { 3814 return s2 == null; 3815 } 3816 if (s2 == null) { 3817 return false; 3818 } 3819 if (s1.getClass() != s2.getClass()) { 3820 return false; 3821 } 3822 return s1.equals(s2); 3823 } 3824 3825 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3826 if (pi1.icon != pi2.icon) return false; 3827 if (pi1.logo != pi2.logo) return false; 3828 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3829 if (!compareStrings(pi1.name, pi2.name)) return false; 3830 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3831 // We'll take care of setting this one. 3832 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3833 // These are not currently stored in settings. 3834 //if (!compareStrings(pi1.group, pi2.group)) return false; 3835 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3836 //if (pi1.labelRes != pi2.labelRes) return false; 3837 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3838 return true; 3839 } 3840 3841 int permissionInfoFootprint(PermissionInfo info) { 3842 int size = info.name.length(); 3843 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3844 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3845 return size; 3846 } 3847 3848 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3849 int size = 0; 3850 for (BasePermission perm : mSettings.mPermissions.values()) { 3851 if (perm.uid == tree.uid) { 3852 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3853 } 3854 } 3855 return size; 3856 } 3857 3858 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3859 // We calculate the max size of permissions defined by this uid and throw 3860 // if that plus the size of 'info' would exceed our stated maximum. 3861 if (tree.uid != Process.SYSTEM_UID) { 3862 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3863 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3864 throw new SecurityException("Permission tree size cap exceeded"); 3865 } 3866 } 3867 } 3868 3869 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3870 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3871 throw new SecurityException("Label must be specified in permission"); 3872 } 3873 BasePermission tree = checkPermissionTreeLP(info.name); 3874 BasePermission bp = mSettings.mPermissions.get(info.name); 3875 boolean added = bp == null; 3876 boolean changed = true; 3877 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3878 if (added) { 3879 enforcePermissionCapLocked(info, tree); 3880 bp = new BasePermission(info.name, tree.sourcePackage, 3881 BasePermission.TYPE_DYNAMIC); 3882 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3883 throw new SecurityException( 3884 "Not allowed to modify non-dynamic permission " 3885 + info.name); 3886 } else { 3887 if (bp.protectionLevel == fixedLevel 3888 && bp.perm.owner.equals(tree.perm.owner) 3889 && bp.uid == tree.uid 3890 && comparePermissionInfos(bp.perm.info, info)) { 3891 changed = false; 3892 } 3893 } 3894 bp.protectionLevel = fixedLevel; 3895 info = new PermissionInfo(info); 3896 info.protectionLevel = fixedLevel; 3897 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3898 bp.perm.info.packageName = tree.perm.info.packageName; 3899 bp.uid = tree.uid; 3900 if (added) { 3901 mSettings.mPermissions.put(info.name, bp); 3902 } 3903 if (changed) { 3904 if (!async) { 3905 mSettings.writeLPr(); 3906 } else { 3907 scheduleWriteSettingsLocked(); 3908 } 3909 } 3910 return added; 3911 } 3912 3913 @Override 3914 public boolean addPermission(PermissionInfo info) { 3915 synchronized (mPackages) { 3916 return addPermissionLocked(info, false); 3917 } 3918 } 3919 3920 @Override 3921 public boolean addPermissionAsync(PermissionInfo info) { 3922 synchronized (mPackages) { 3923 return addPermissionLocked(info, true); 3924 } 3925 } 3926 3927 @Override 3928 public void removePermission(String name) { 3929 synchronized (mPackages) { 3930 checkPermissionTreeLP(name); 3931 BasePermission bp = mSettings.mPermissions.get(name); 3932 if (bp != null) { 3933 if (bp.type != BasePermission.TYPE_DYNAMIC) { 3934 throw new SecurityException( 3935 "Not allowed to modify non-dynamic permission " 3936 + name); 3937 } 3938 mSettings.mPermissions.remove(name); 3939 mSettings.writeLPr(); 3940 } 3941 } 3942 } 3943 3944 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 3945 BasePermission bp) { 3946 int index = pkg.requestedPermissions.indexOf(bp.name); 3947 if (index == -1) { 3948 throw new SecurityException("Package " + pkg.packageName 3949 + " has not requested permission " + bp.name); 3950 } 3951 if (!bp.isRuntime() && !bp.isDevelopment()) { 3952 throw new SecurityException("Permission " + bp.name 3953 + " is not a changeable permission type"); 3954 } 3955 } 3956 3957 @Override 3958 public void grantRuntimePermission(String packageName, String name, final int userId) { 3959 if (!sUserManager.exists(userId)) { 3960 Log.e(TAG, "No such user:" + userId); 3961 return; 3962 } 3963 3964 mContext.enforceCallingOrSelfPermission( 3965 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 3966 "grantRuntimePermission"); 3967 3968 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3969 true /* requireFullPermission */, true /* checkShell */, 3970 "grantRuntimePermission"); 3971 3972 final int uid; 3973 final SettingBase sb; 3974 3975 synchronized (mPackages) { 3976 final PackageParser.Package pkg = mPackages.get(packageName); 3977 if (pkg == null) { 3978 throw new IllegalArgumentException("Unknown package: " + packageName); 3979 } 3980 3981 final BasePermission bp = mSettings.mPermissions.get(name); 3982 if (bp == null) { 3983 throw new IllegalArgumentException("Unknown permission: " + name); 3984 } 3985 3986 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 3987 3988 // If a permission review is required for legacy apps we represent 3989 // their permissions as always granted runtime ones since we need 3990 // to keep the review required permission flag per user while an 3991 // install permission's state is shared across all users. 3992 if (Build.PERMISSIONS_REVIEW_REQUIRED 3993 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 3994 && bp.isRuntime()) { 3995 return; 3996 } 3997 3998 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 3999 sb = (SettingBase) pkg.mExtras; 4000 if (sb == null) { 4001 throw new IllegalArgumentException("Unknown package: " + packageName); 4002 } 4003 4004 final PermissionsState permissionsState = sb.getPermissionsState(); 4005 4006 final int flags = permissionsState.getPermissionFlags(name, userId); 4007 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4008 throw new SecurityException("Cannot grant system fixed permission " 4009 + name + " for package " + packageName); 4010 } 4011 4012 if (bp.isDevelopment()) { 4013 // Development permissions must be handled specially, since they are not 4014 // normal runtime permissions. For now they apply to all users. 4015 if (permissionsState.grantInstallPermission(bp) != 4016 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4017 scheduleWriteSettingsLocked(); 4018 } 4019 return; 4020 } 4021 4022 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4023 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4024 return; 4025 } 4026 4027 final int result = permissionsState.grantRuntimePermission(bp, userId); 4028 switch (result) { 4029 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4030 return; 4031 } 4032 4033 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4034 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4035 mHandler.post(new Runnable() { 4036 @Override 4037 public void run() { 4038 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4039 } 4040 }); 4041 } 4042 break; 4043 } 4044 4045 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4046 4047 // Not critical if that is lost - app has to request again. 4048 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4049 } 4050 4051 // Only need to do this if user is initialized. Otherwise it's a new user 4052 // and there are no processes running as the user yet and there's no need 4053 // to make an expensive call to remount processes for the changed permissions. 4054 if (READ_EXTERNAL_STORAGE.equals(name) 4055 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4056 final long token = Binder.clearCallingIdentity(); 4057 try { 4058 if (sUserManager.isInitialized(userId)) { 4059 MountServiceInternal mountServiceInternal = LocalServices.getService( 4060 MountServiceInternal.class); 4061 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4062 } 4063 } finally { 4064 Binder.restoreCallingIdentity(token); 4065 } 4066 } 4067 } 4068 4069 @Override 4070 public void revokeRuntimePermission(String packageName, String name, int userId) { 4071 if (!sUserManager.exists(userId)) { 4072 Log.e(TAG, "No such user:" + userId); 4073 return; 4074 } 4075 4076 mContext.enforceCallingOrSelfPermission( 4077 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4078 "revokeRuntimePermission"); 4079 4080 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4081 true /* requireFullPermission */, true /* checkShell */, 4082 "revokeRuntimePermission"); 4083 4084 final int appId; 4085 4086 synchronized (mPackages) { 4087 final PackageParser.Package pkg = mPackages.get(packageName); 4088 if (pkg == null) { 4089 throw new IllegalArgumentException("Unknown package: " + packageName); 4090 } 4091 4092 final BasePermission bp = mSettings.mPermissions.get(name); 4093 if (bp == null) { 4094 throw new IllegalArgumentException("Unknown permission: " + name); 4095 } 4096 4097 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4098 4099 // If a permission review is required for legacy apps we represent 4100 // their permissions as always granted runtime ones since we need 4101 // to keep the review required permission flag per user while an 4102 // install permission's state is shared across all users. 4103 if (Build.PERMISSIONS_REVIEW_REQUIRED 4104 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4105 && bp.isRuntime()) { 4106 return; 4107 } 4108 4109 SettingBase sb = (SettingBase) pkg.mExtras; 4110 if (sb == null) { 4111 throw new IllegalArgumentException("Unknown package: " + packageName); 4112 } 4113 4114 final PermissionsState permissionsState = sb.getPermissionsState(); 4115 4116 final int flags = permissionsState.getPermissionFlags(name, userId); 4117 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4118 throw new SecurityException("Cannot revoke system fixed permission " 4119 + name + " for package " + packageName); 4120 } 4121 4122 if (bp.isDevelopment()) { 4123 // Development permissions must be handled specially, since they are not 4124 // normal runtime permissions. For now they apply to all users. 4125 if (permissionsState.revokeInstallPermission(bp) != 4126 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4127 scheduleWriteSettingsLocked(); 4128 } 4129 return; 4130 } 4131 4132 if (permissionsState.revokeRuntimePermission(bp, userId) == 4133 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4134 return; 4135 } 4136 4137 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4138 4139 // Critical, after this call app should never have the permission. 4140 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4141 4142 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4143 } 4144 4145 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4146 } 4147 4148 @Override 4149 public void resetRuntimePermissions() { 4150 mContext.enforceCallingOrSelfPermission( 4151 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4152 "revokeRuntimePermission"); 4153 4154 int callingUid = Binder.getCallingUid(); 4155 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4156 mContext.enforceCallingOrSelfPermission( 4157 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4158 "resetRuntimePermissions"); 4159 } 4160 4161 synchronized (mPackages) { 4162 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4163 for (int userId : UserManagerService.getInstance().getUserIds()) { 4164 final int packageCount = mPackages.size(); 4165 for (int i = 0; i < packageCount; i++) { 4166 PackageParser.Package pkg = mPackages.valueAt(i); 4167 if (!(pkg.mExtras instanceof PackageSetting)) { 4168 continue; 4169 } 4170 PackageSetting ps = (PackageSetting) pkg.mExtras; 4171 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4172 } 4173 } 4174 } 4175 } 4176 4177 @Override 4178 public int getPermissionFlags(String name, String packageName, int userId) { 4179 if (!sUserManager.exists(userId)) { 4180 return 0; 4181 } 4182 4183 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4184 4185 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4186 true /* requireFullPermission */, false /* checkShell */, 4187 "getPermissionFlags"); 4188 4189 synchronized (mPackages) { 4190 final PackageParser.Package pkg = mPackages.get(packageName); 4191 if (pkg == null) { 4192 throw new IllegalArgumentException("Unknown package: " + packageName); 4193 } 4194 4195 final BasePermission bp = mSettings.mPermissions.get(name); 4196 if (bp == null) { 4197 throw new IllegalArgumentException("Unknown permission: " + name); 4198 } 4199 4200 SettingBase sb = (SettingBase) pkg.mExtras; 4201 if (sb == null) { 4202 throw new IllegalArgumentException("Unknown package: " + packageName); 4203 } 4204 4205 PermissionsState permissionsState = sb.getPermissionsState(); 4206 return permissionsState.getPermissionFlags(name, userId); 4207 } 4208 } 4209 4210 @Override 4211 public void updatePermissionFlags(String name, String packageName, int flagMask, 4212 int flagValues, int userId) { 4213 if (!sUserManager.exists(userId)) { 4214 return; 4215 } 4216 4217 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4218 4219 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4220 true /* requireFullPermission */, true /* checkShell */, 4221 "updatePermissionFlags"); 4222 4223 // Only the system can change these flags and nothing else. 4224 if (getCallingUid() != Process.SYSTEM_UID) { 4225 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4226 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4227 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4228 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4229 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4230 } 4231 4232 synchronized (mPackages) { 4233 final PackageParser.Package pkg = mPackages.get(packageName); 4234 if (pkg == null) { 4235 throw new IllegalArgumentException("Unknown package: " + packageName); 4236 } 4237 4238 final BasePermission bp = mSettings.mPermissions.get(name); 4239 if (bp == null) { 4240 throw new IllegalArgumentException("Unknown permission: " + name); 4241 } 4242 4243 SettingBase sb = (SettingBase) pkg.mExtras; 4244 if (sb == null) { 4245 throw new IllegalArgumentException("Unknown package: " + packageName); 4246 } 4247 4248 PermissionsState permissionsState = sb.getPermissionsState(); 4249 4250 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4251 4252 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4253 // Install and runtime permissions are stored in different places, 4254 // so figure out what permission changed and persist the change. 4255 if (permissionsState.getInstallPermissionState(name) != null) { 4256 scheduleWriteSettingsLocked(); 4257 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4258 || hadState) { 4259 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4260 } 4261 } 4262 } 4263 } 4264 4265 /** 4266 * Update the permission flags for all packages and runtime permissions of a user in order 4267 * to allow device or profile owner to remove POLICY_FIXED. 4268 */ 4269 @Override 4270 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4271 if (!sUserManager.exists(userId)) { 4272 return; 4273 } 4274 4275 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4276 4277 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4278 true /* requireFullPermission */, true /* checkShell */, 4279 "updatePermissionFlagsForAllApps"); 4280 4281 // Only the system can change system fixed flags. 4282 if (getCallingUid() != Process.SYSTEM_UID) { 4283 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4284 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4285 } 4286 4287 synchronized (mPackages) { 4288 boolean changed = false; 4289 final int packageCount = mPackages.size(); 4290 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4291 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4292 SettingBase sb = (SettingBase) pkg.mExtras; 4293 if (sb == null) { 4294 continue; 4295 } 4296 PermissionsState permissionsState = sb.getPermissionsState(); 4297 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4298 userId, flagMask, flagValues); 4299 } 4300 if (changed) { 4301 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4302 } 4303 } 4304 } 4305 4306 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4307 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4308 != PackageManager.PERMISSION_GRANTED 4309 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4310 != PackageManager.PERMISSION_GRANTED) { 4311 throw new SecurityException(message + " requires " 4312 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4313 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4314 } 4315 } 4316 4317 @Override 4318 public boolean shouldShowRequestPermissionRationale(String permissionName, 4319 String packageName, int userId) { 4320 if (UserHandle.getCallingUserId() != userId) { 4321 mContext.enforceCallingPermission( 4322 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4323 "canShowRequestPermissionRationale for user " + userId); 4324 } 4325 4326 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4327 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4328 return false; 4329 } 4330 4331 if (checkPermission(permissionName, packageName, userId) 4332 == PackageManager.PERMISSION_GRANTED) { 4333 return false; 4334 } 4335 4336 final int flags; 4337 4338 final long identity = Binder.clearCallingIdentity(); 4339 try { 4340 flags = getPermissionFlags(permissionName, 4341 packageName, userId); 4342 } finally { 4343 Binder.restoreCallingIdentity(identity); 4344 } 4345 4346 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4347 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4348 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4349 4350 if ((flags & fixedFlags) != 0) { 4351 return false; 4352 } 4353 4354 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4355 } 4356 4357 @Override 4358 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4359 mContext.enforceCallingOrSelfPermission( 4360 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4361 "addOnPermissionsChangeListener"); 4362 4363 synchronized (mPackages) { 4364 mOnPermissionChangeListeners.addListenerLocked(listener); 4365 } 4366 } 4367 4368 @Override 4369 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4370 synchronized (mPackages) { 4371 mOnPermissionChangeListeners.removeListenerLocked(listener); 4372 } 4373 } 4374 4375 @Override 4376 public boolean isProtectedBroadcast(String actionName) { 4377 synchronized (mPackages) { 4378 if (mProtectedBroadcasts.contains(actionName)) { 4379 return true; 4380 } else if (actionName != null) { 4381 // TODO: remove these terrible hacks 4382 if (actionName.startsWith("android.net.netmon.lingerExpired") 4383 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4384 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4385 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4386 return true; 4387 } 4388 } 4389 } 4390 return false; 4391 } 4392 4393 @Override 4394 public int checkSignatures(String pkg1, String pkg2) { 4395 synchronized (mPackages) { 4396 final PackageParser.Package p1 = mPackages.get(pkg1); 4397 final PackageParser.Package p2 = mPackages.get(pkg2); 4398 if (p1 == null || p1.mExtras == null 4399 || p2 == null || p2.mExtras == null) { 4400 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4401 } 4402 return compareSignatures(p1.mSignatures, p2.mSignatures); 4403 } 4404 } 4405 4406 @Override 4407 public int checkUidSignatures(int uid1, int uid2) { 4408 // Map to base uids. 4409 uid1 = UserHandle.getAppId(uid1); 4410 uid2 = UserHandle.getAppId(uid2); 4411 // reader 4412 synchronized (mPackages) { 4413 Signature[] s1; 4414 Signature[] s2; 4415 Object obj = mSettings.getUserIdLPr(uid1); 4416 if (obj != null) { 4417 if (obj instanceof SharedUserSetting) { 4418 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4419 } else if (obj instanceof PackageSetting) { 4420 s1 = ((PackageSetting)obj).signatures.mSignatures; 4421 } else { 4422 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4423 } 4424 } else { 4425 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4426 } 4427 obj = mSettings.getUserIdLPr(uid2); 4428 if (obj != null) { 4429 if (obj instanceof SharedUserSetting) { 4430 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4431 } else if (obj instanceof PackageSetting) { 4432 s2 = ((PackageSetting)obj).signatures.mSignatures; 4433 } else { 4434 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4435 } 4436 } else { 4437 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4438 } 4439 return compareSignatures(s1, s2); 4440 } 4441 } 4442 4443 /** 4444 * This method should typically only be used when granting or revoking 4445 * permissions, since the app may immediately restart after this call. 4446 * <p> 4447 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4448 * guard your work against the app being relaunched. 4449 */ 4450 private void killUid(int appId, int userId, String reason) { 4451 final long identity = Binder.clearCallingIdentity(); 4452 try { 4453 IActivityManager am = ActivityManagerNative.getDefault(); 4454 if (am != null) { 4455 try { 4456 am.killUid(appId, userId, reason); 4457 } catch (RemoteException e) { 4458 /* ignore - same process */ 4459 } 4460 } 4461 } finally { 4462 Binder.restoreCallingIdentity(identity); 4463 } 4464 } 4465 4466 /** 4467 * Compares two sets of signatures. Returns: 4468 * <br /> 4469 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4470 * <br /> 4471 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4472 * <br /> 4473 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4474 * <br /> 4475 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4476 * <br /> 4477 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4478 */ 4479 static int compareSignatures(Signature[] s1, Signature[] s2) { 4480 if (s1 == null) { 4481 return s2 == null 4482 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4483 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4484 } 4485 4486 if (s2 == null) { 4487 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4488 } 4489 4490 if (s1.length != s2.length) { 4491 return PackageManager.SIGNATURE_NO_MATCH; 4492 } 4493 4494 // Since both signature sets are of size 1, we can compare without HashSets. 4495 if (s1.length == 1) { 4496 return s1[0].equals(s2[0]) ? 4497 PackageManager.SIGNATURE_MATCH : 4498 PackageManager.SIGNATURE_NO_MATCH; 4499 } 4500 4501 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4502 for (Signature sig : s1) { 4503 set1.add(sig); 4504 } 4505 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4506 for (Signature sig : s2) { 4507 set2.add(sig); 4508 } 4509 // Make sure s2 contains all signatures in s1. 4510 if (set1.equals(set2)) { 4511 return PackageManager.SIGNATURE_MATCH; 4512 } 4513 return PackageManager.SIGNATURE_NO_MATCH; 4514 } 4515 4516 /** 4517 * If the database version for this type of package (internal storage or 4518 * external storage) is less than the version where package signatures 4519 * were updated, return true. 4520 */ 4521 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4522 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4523 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4524 } 4525 4526 /** 4527 * Used for backward compatibility to make sure any packages with 4528 * certificate chains get upgraded to the new style. {@code existingSigs} 4529 * will be in the old format (since they were stored on disk from before the 4530 * system upgrade) and {@code scannedSigs} will be in the newer format. 4531 */ 4532 private int compareSignaturesCompat(PackageSignatures existingSigs, 4533 PackageParser.Package scannedPkg) { 4534 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4535 return PackageManager.SIGNATURE_NO_MATCH; 4536 } 4537 4538 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4539 for (Signature sig : existingSigs.mSignatures) { 4540 existingSet.add(sig); 4541 } 4542 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4543 for (Signature sig : scannedPkg.mSignatures) { 4544 try { 4545 Signature[] chainSignatures = sig.getChainSignatures(); 4546 for (Signature chainSig : chainSignatures) { 4547 scannedCompatSet.add(chainSig); 4548 } 4549 } catch (CertificateEncodingException e) { 4550 scannedCompatSet.add(sig); 4551 } 4552 } 4553 /* 4554 * Make sure the expanded scanned set contains all signatures in the 4555 * existing one. 4556 */ 4557 if (scannedCompatSet.equals(existingSet)) { 4558 // Migrate the old signatures to the new scheme. 4559 existingSigs.assignSignatures(scannedPkg.mSignatures); 4560 // The new KeySets will be re-added later in the scanning process. 4561 synchronized (mPackages) { 4562 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4563 } 4564 return PackageManager.SIGNATURE_MATCH; 4565 } 4566 return PackageManager.SIGNATURE_NO_MATCH; 4567 } 4568 4569 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4570 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4571 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4572 } 4573 4574 private int compareSignaturesRecover(PackageSignatures existingSigs, 4575 PackageParser.Package scannedPkg) { 4576 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4577 return PackageManager.SIGNATURE_NO_MATCH; 4578 } 4579 4580 String msg = null; 4581 try { 4582 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4583 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4584 + scannedPkg.packageName); 4585 return PackageManager.SIGNATURE_MATCH; 4586 } 4587 } catch (CertificateException e) { 4588 msg = e.getMessage(); 4589 } 4590 4591 logCriticalInfo(Log.INFO, 4592 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4593 return PackageManager.SIGNATURE_NO_MATCH; 4594 } 4595 4596 @Override 4597 public List<String> getAllPackages() { 4598 synchronized (mPackages) { 4599 return new ArrayList<String>(mPackages.keySet()); 4600 } 4601 } 4602 4603 @Override 4604 public String[] getPackagesForUid(int uid) { 4605 uid = UserHandle.getAppId(uid); 4606 // reader 4607 synchronized (mPackages) { 4608 Object obj = mSettings.getUserIdLPr(uid); 4609 if (obj instanceof SharedUserSetting) { 4610 final SharedUserSetting sus = (SharedUserSetting) obj; 4611 final int N = sus.packages.size(); 4612 final String[] res = new String[N]; 4613 final Iterator<PackageSetting> it = sus.packages.iterator(); 4614 int i = 0; 4615 while (it.hasNext()) { 4616 res[i++] = it.next().name; 4617 } 4618 return res; 4619 } else if (obj instanceof PackageSetting) { 4620 final PackageSetting ps = (PackageSetting) obj; 4621 return new String[] { ps.name }; 4622 } 4623 } 4624 return null; 4625 } 4626 4627 @Override 4628 public String getNameForUid(int uid) { 4629 // reader 4630 synchronized (mPackages) { 4631 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4632 if (obj instanceof SharedUserSetting) { 4633 final SharedUserSetting sus = (SharedUserSetting) obj; 4634 return sus.name + ":" + sus.userId; 4635 } else if (obj instanceof PackageSetting) { 4636 final PackageSetting ps = (PackageSetting) obj; 4637 return ps.name; 4638 } 4639 } 4640 return null; 4641 } 4642 4643 @Override 4644 public int getUidForSharedUser(String sharedUserName) { 4645 if(sharedUserName == null) { 4646 return -1; 4647 } 4648 // reader 4649 synchronized (mPackages) { 4650 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4651 if (suid == null) { 4652 return -1; 4653 } 4654 return suid.userId; 4655 } 4656 } 4657 4658 @Override 4659 public int getFlagsForUid(int uid) { 4660 synchronized (mPackages) { 4661 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4662 if (obj instanceof SharedUserSetting) { 4663 final SharedUserSetting sus = (SharedUserSetting) obj; 4664 return sus.pkgFlags; 4665 } else if (obj instanceof PackageSetting) { 4666 final PackageSetting ps = (PackageSetting) obj; 4667 return ps.pkgFlags; 4668 } 4669 } 4670 return 0; 4671 } 4672 4673 @Override 4674 public int getPrivateFlagsForUid(int uid) { 4675 synchronized (mPackages) { 4676 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4677 if (obj instanceof SharedUserSetting) { 4678 final SharedUserSetting sus = (SharedUserSetting) obj; 4679 return sus.pkgPrivateFlags; 4680 } else if (obj instanceof PackageSetting) { 4681 final PackageSetting ps = (PackageSetting) obj; 4682 return ps.pkgPrivateFlags; 4683 } 4684 } 4685 return 0; 4686 } 4687 4688 @Override 4689 public boolean isUidPrivileged(int uid) { 4690 uid = UserHandle.getAppId(uid); 4691 // reader 4692 synchronized (mPackages) { 4693 Object obj = mSettings.getUserIdLPr(uid); 4694 if (obj instanceof SharedUserSetting) { 4695 final SharedUserSetting sus = (SharedUserSetting) obj; 4696 final Iterator<PackageSetting> it = sus.packages.iterator(); 4697 while (it.hasNext()) { 4698 if (it.next().isPrivileged()) { 4699 return true; 4700 } 4701 } 4702 } else if (obj instanceof PackageSetting) { 4703 final PackageSetting ps = (PackageSetting) obj; 4704 return ps.isPrivileged(); 4705 } 4706 } 4707 return false; 4708 } 4709 4710 @Override 4711 public String[] getAppOpPermissionPackages(String permissionName) { 4712 synchronized (mPackages) { 4713 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4714 if (pkgs == null) { 4715 return null; 4716 } 4717 return pkgs.toArray(new String[pkgs.size()]); 4718 } 4719 } 4720 4721 @Override 4722 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4723 int flags, int userId) { 4724 try { 4725 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4726 4727 if (!sUserManager.exists(userId)) return null; 4728 flags = updateFlagsForResolve(flags, userId, intent); 4729 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4730 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4731 4732 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4733 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4734 flags, userId); 4735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4736 4737 final ResolveInfo bestChoice = 4738 chooseBestActivity(intent, resolvedType, flags, query, userId); 4739 4740 if (isEphemeralAllowed(intent, query, userId)) { 4741 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4742 final EphemeralResolveInfo ai = 4743 getEphemeralResolveInfo(intent, resolvedType, userId); 4744 if (ai != null) { 4745 if (DEBUG_EPHEMERAL) { 4746 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4747 } 4748 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4749 bestChoice.ephemeralResolveInfo = ai; 4750 } 4751 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4752 } 4753 return bestChoice; 4754 } finally { 4755 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4756 } 4757 } 4758 4759 @Override 4760 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4761 IntentFilter filter, int match, ComponentName activity) { 4762 final int userId = UserHandle.getCallingUserId(); 4763 if (DEBUG_PREFERRED) { 4764 Log.v(TAG, "setLastChosenActivity intent=" + intent 4765 + " resolvedType=" + resolvedType 4766 + " flags=" + flags 4767 + " filter=" + filter 4768 + " match=" + match 4769 + " activity=" + activity); 4770 filter.dump(new PrintStreamPrinter(System.out), " "); 4771 } 4772 intent.setComponent(null); 4773 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4774 userId); 4775 // Find any earlier preferred or last chosen entries and nuke them 4776 findPreferredActivity(intent, resolvedType, 4777 flags, query, 0, false, true, false, userId); 4778 // Add the new activity as the last chosen for this filter 4779 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4780 "Setting last chosen"); 4781 } 4782 4783 @Override 4784 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4785 final int userId = UserHandle.getCallingUserId(); 4786 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4787 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4788 userId); 4789 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4790 false, false, false, userId); 4791 } 4792 4793 4794 private boolean isEphemeralAllowed( 4795 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4796 // Short circuit and return early if possible. 4797 if (DISABLE_EPHEMERAL_APPS) { 4798 return false; 4799 } 4800 final int callingUser = UserHandle.getCallingUserId(); 4801 if (callingUser != UserHandle.USER_SYSTEM) { 4802 return false; 4803 } 4804 if (mEphemeralResolverConnection == null) { 4805 return false; 4806 } 4807 if (intent.getComponent() != null) { 4808 return false; 4809 } 4810 if (intent.getPackage() != null) { 4811 return false; 4812 } 4813 final boolean isWebUri = hasWebURI(intent); 4814 if (!isWebUri) { 4815 return false; 4816 } 4817 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4818 synchronized (mPackages) { 4819 final int count = resolvedActivites.size(); 4820 for (int n = 0; n < count; n++) { 4821 ResolveInfo info = resolvedActivites.get(n); 4822 String packageName = info.activityInfo.packageName; 4823 PackageSetting ps = mSettings.mPackages.get(packageName); 4824 if (ps != null) { 4825 // Try to get the status from User settings first 4826 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4827 int status = (int) (packedStatus >> 32); 4828 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4829 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4830 if (DEBUG_EPHEMERAL) { 4831 Slog.v(TAG, "DENY ephemeral apps;" 4832 + " pkg: " + packageName + ", status: " + status); 4833 } 4834 return false; 4835 } 4836 } 4837 } 4838 } 4839 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4840 return true; 4841 } 4842 4843 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4844 int userId) { 4845 MessageDigest digest = null; 4846 try { 4847 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4848 } catch (NoSuchAlgorithmException e) { 4849 // If we can't create a digest, ignore ephemeral apps. 4850 return null; 4851 } 4852 4853 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4854 final byte[] digestBytes = digest.digest(hostBytes); 4855 int shaPrefix = 4856 digestBytes[0] << 24 4857 | digestBytes[1] << 16 4858 | digestBytes[2] << 8 4859 | digestBytes[3] << 0; 4860 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4861 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4862 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4863 // No hash prefix match; there are no ephemeral apps for this domain. 4864 return null; 4865 } 4866 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4867 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4868 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4869 continue; 4870 } 4871 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4872 // No filters; this should never happen. 4873 if (filters.isEmpty()) { 4874 continue; 4875 } 4876 // We have a domain match; resolve the filters to see if anything matches. 4877 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4878 for (int j = filters.size() - 1; j >= 0; --j) { 4879 final EphemeralResolveIntentInfo intentInfo = 4880 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4881 ephemeralResolver.addFilter(intentInfo); 4882 } 4883 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4884 intent, resolvedType, false /*defaultOnly*/, userId); 4885 if (!matchedResolveInfoList.isEmpty()) { 4886 return matchedResolveInfoList.get(0); 4887 } 4888 } 4889 // Hash or filter mis-match; no ephemeral apps for this domain. 4890 return null; 4891 } 4892 4893 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4894 int flags, List<ResolveInfo> query, int userId) { 4895 if (query != null) { 4896 final int N = query.size(); 4897 if (N == 1) { 4898 return query.get(0); 4899 } else if (N > 1) { 4900 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4901 // If there is more than one activity with the same priority, 4902 // then let the user decide between them. 4903 ResolveInfo r0 = query.get(0); 4904 ResolveInfo r1 = query.get(1); 4905 if (DEBUG_INTENT_MATCHING || debug) { 4906 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4907 + r1.activityInfo.name + "=" + r1.priority); 4908 } 4909 // If the first activity has a higher priority, or a different 4910 // default, then it is always desirable to pick it. 4911 if (r0.priority != r1.priority 4912 || r0.preferredOrder != r1.preferredOrder 4913 || r0.isDefault != r1.isDefault) { 4914 return query.get(0); 4915 } 4916 // If we have saved a preference for a preferred activity for 4917 // this Intent, use that. 4918 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 4919 flags, query, r0.priority, true, false, debug, userId); 4920 if (ri != null) { 4921 return ri; 4922 } 4923 ri = new ResolveInfo(mResolveInfo); 4924 ri.activityInfo = new ActivityInfo(ri.activityInfo); 4925 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 4926 ri.activityInfo.applicationInfo = new ApplicationInfo( 4927 ri.activityInfo.applicationInfo); 4928 if (userId != 0) { 4929 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 4930 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 4931 } 4932 // Make sure that the resolver is displayable in car mode 4933 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 4934 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 4935 return ri; 4936 } 4937 } 4938 return null; 4939 } 4940 4941 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 4942 int flags, List<ResolveInfo> query, boolean debug, int userId) { 4943 final int N = query.size(); 4944 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 4945 .get(userId); 4946 // Get the list of persistent preferred activities that handle the intent 4947 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 4948 List<PersistentPreferredActivity> pprefs = ppir != null 4949 ? ppir.queryIntent(intent, resolvedType, 4950 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 4951 : null; 4952 if (pprefs != null && pprefs.size() > 0) { 4953 final int M = pprefs.size(); 4954 for (int i=0; i<M; i++) { 4955 final PersistentPreferredActivity ppa = pprefs.get(i); 4956 if (DEBUG_PREFERRED || debug) { 4957 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 4958 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 4959 + "\n component=" + ppa.mComponent); 4960 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4961 } 4962 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 4963 flags | MATCH_DISABLED_COMPONENTS, userId); 4964 if (DEBUG_PREFERRED || debug) { 4965 Slog.v(TAG, "Found persistent preferred activity:"); 4966 if (ai != null) { 4967 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 4968 } else { 4969 Slog.v(TAG, " null"); 4970 } 4971 } 4972 if (ai == null) { 4973 // This previously registered persistent preferred activity 4974 // component is no longer known. Ignore it and do NOT remove it. 4975 continue; 4976 } 4977 for (int j=0; j<N; j++) { 4978 final ResolveInfo ri = query.get(j); 4979 if (!ri.activityInfo.applicationInfo.packageName 4980 .equals(ai.applicationInfo.packageName)) { 4981 continue; 4982 } 4983 if (!ri.activityInfo.name.equals(ai.name)) { 4984 continue; 4985 } 4986 // Found a persistent preference that can handle the intent. 4987 if (DEBUG_PREFERRED || debug) { 4988 Slog.v(TAG, "Returning persistent preferred activity: " + 4989 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 4990 } 4991 return ri; 4992 } 4993 } 4994 } 4995 return null; 4996 } 4997 4998 // TODO: handle preferred activities missing while user has amnesia 4999 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5000 List<ResolveInfo> query, int priority, boolean always, 5001 boolean removeMatches, boolean debug, int userId) { 5002 if (!sUserManager.exists(userId)) return null; 5003 flags = updateFlagsForResolve(flags, userId, intent); 5004 // writer 5005 synchronized (mPackages) { 5006 if (intent.getSelector() != null) { 5007 intent = intent.getSelector(); 5008 } 5009 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5010 5011 // Try to find a matching persistent preferred activity. 5012 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5013 debug, userId); 5014 5015 // If a persistent preferred activity matched, use it. 5016 if (pri != null) { 5017 return pri; 5018 } 5019 5020 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5021 // Get the list of preferred activities that handle the intent 5022 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5023 List<PreferredActivity> prefs = pir != null 5024 ? pir.queryIntent(intent, resolvedType, 5025 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5026 : null; 5027 if (prefs != null && prefs.size() > 0) { 5028 boolean changed = false; 5029 try { 5030 // First figure out how good the original match set is. 5031 // We will only allow preferred activities that came 5032 // from the same match quality. 5033 int match = 0; 5034 5035 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5036 5037 final int N = query.size(); 5038 for (int j=0; j<N; j++) { 5039 final ResolveInfo ri = query.get(j); 5040 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5041 + ": 0x" + Integer.toHexString(match)); 5042 if (ri.match > match) { 5043 match = ri.match; 5044 } 5045 } 5046 5047 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5048 + Integer.toHexString(match)); 5049 5050 match &= IntentFilter.MATCH_CATEGORY_MASK; 5051 final int M = prefs.size(); 5052 for (int i=0; i<M; i++) { 5053 final PreferredActivity pa = prefs.get(i); 5054 if (DEBUG_PREFERRED || debug) { 5055 Slog.v(TAG, "Checking PreferredActivity ds=" 5056 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5057 + "\n component=" + pa.mPref.mComponent); 5058 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5059 } 5060 if (pa.mPref.mMatch != match) { 5061 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5062 + Integer.toHexString(pa.mPref.mMatch)); 5063 continue; 5064 } 5065 // If it's not an "always" type preferred activity and that's what we're 5066 // looking for, skip it. 5067 if (always && !pa.mPref.mAlways) { 5068 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5069 continue; 5070 } 5071 final ActivityInfo ai = getActivityInfo( 5072 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5073 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5074 userId); 5075 if (DEBUG_PREFERRED || debug) { 5076 Slog.v(TAG, "Found preferred activity:"); 5077 if (ai != null) { 5078 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5079 } else { 5080 Slog.v(TAG, " null"); 5081 } 5082 } 5083 if (ai == null) { 5084 // This previously registered preferred activity 5085 // component is no longer known. Most likely an update 5086 // to the app was installed and in the new version this 5087 // component no longer exists. Clean it up by removing 5088 // it from the preferred activities list, and skip it. 5089 Slog.w(TAG, "Removing dangling preferred activity: " 5090 + pa.mPref.mComponent); 5091 pir.removeFilter(pa); 5092 changed = true; 5093 continue; 5094 } 5095 for (int j=0; j<N; j++) { 5096 final ResolveInfo ri = query.get(j); 5097 if (!ri.activityInfo.applicationInfo.packageName 5098 .equals(ai.applicationInfo.packageName)) { 5099 continue; 5100 } 5101 if (!ri.activityInfo.name.equals(ai.name)) { 5102 continue; 5103 } 5104 5105 if (removeMatches) { 5106 pir.removeFilter(pa); 5107 changed = true; 5108 if (DEBUG_PREFERRED) { 5109 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5110 } 5111 break; 5112 } 5113 5114 // Okay we found a previously set preferred or last chosen app. 5115 // If the result set is different from when this 5116 // was created, we need to clear it and re-ask the 5117 // user their preference, if we're looking for an "always" type entry. 5118 if (always && !pa.mPref.sameSet(query)) { 5119 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5120 + intent + " type " + resolvedType); 5121 if (DEBUG_PREFERRED) { 5122 Slog.v(TAG, "Removing preferred activity since set changed " 5123 + pa.mPref.mComponent); 5124 } 5125 pir.removeFilter(pa); 5126 // Re-add the filter as a "last chosen" entry (!always) 5127 PreferredActivity lastChosen = new PreferredActivity( 5128 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5129 pir.addFilter(lastChosen); 5130 changed = true; 5131 return null; 5132 } 5133 5134 // Yay! Either the set matched or we're looking for the last chosen 5135 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5136 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5137 return ri; 5138 } 5139 } 5140 } finally { 5141 if (changed) { 5142 if (DEBUG_PREFERRED) { 5143 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5144 } 5145 scheduleWritePackageRestrictionsLocked(userId); 5146 } 5147 } 5148 } 5149 } 5150 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5151 return null; 5152 } 5153 5154 /* 5155 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5156 */ 5157 @Override 5158 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5159 int targetUserId) { 5160 mContext.enforceCallingOrSelfPermission( 5161 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5162 List<CrossProfileIntentFilter> matches = 5163 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5164 if (matches != null) { 5165 int size = matches.size(); 5166 for (int i = 0; i < size; i++) { 5167 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5168 } 5169 } 5170 if (hasWebURI(intent)) { 5171 // cross-profile app linking works only towards the parent. 5172 final UserInfo parent = getProfileParent(sourceUserId); 5173 synchronized(mPackages) { 5174 int flags = updateFlagsForResolve(0, parent.id, intent); 5175 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5176 intent, resolvedType, flags, sourceUserId, parent.id); 5177 return xpDomainInfo != null; 5178 } 5179 } 5180 return false; 5181 } 5182 5183 private UserInfo getProfileParent(int userId) { 5184 final long identity = Binder.clearCallingIdentity(); 5185 try { 5186 return sUserManager.getProfileParent(userId); 5187 } finally { 5188 Binder.restoreCallingIdentity(identity); 5189 } 5190 } 5191 5192 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5193 String resolvedType, int userId) { 5194 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5195 if (resolver != null) { 5196 return resolver.queryIntent(intent, resolvedType, false, userId); 5197 } 5198 return null; 5199 } 5200 5201 @Override 5202 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5203 String resolvedType, int flags, int userId) { 5204 try { 5205 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5206 5207 return new ParceledListSlice<>( 5208 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5209 } finally { 5210 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5211 } 5212 } 5213 5214 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5215 String resolvedType, int flags, int userId) { 5216 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5217 flags = updateFlagsForResolve(flags, userId, intent); 5218 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5219 false /* requireFullPermission */, false /* checkShell */, 5220 "query intent activities"); 5221 ComponentName comp = intent.getComponent(); 5222 if (comp == null) { 5223 if (intent.getSelector() != null) { 5224 intent = intent.getSelector(); 5225 comp = intent.getComponent(); 5226 } 5227 } 5228 5229 if (comp != null) { 5230 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5231 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5232 if (ai != null) { 5233 final ResolveInfo ri = new ResolveInfo(); 5234 ri.activityInfo = ai; 5235 list.add(ri); 5236 } 5237 return list; 5238 } 5239 5240 // reader 5241 synchronized (mPackages) { 5242 final String pkgName = intent.getPackage(); 5243 if (pkgName == null) { 5244 List<CrossProfileIntentFilter> matchingFilters = 5245 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5246 // Check for results that need to skip the current profile. 5247 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5248 resolvedType, flags, userId); 5249 if (xpResolveInfo != null) { 5250 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5251 result.add(xpResolveInfo); 5252 return filterIfNotSystemUser(result, userId); 5253 } 5254 5255 // Check for results in the current profile. 5256 List<ResolveInfo> result = mActivities.queryIntent( 5257 intent, resolvedType, flags, userId); 5258 result = filterIfNotSystemUser(result, userId); 5259 5260 // Check for cross profile results. 5261 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5262 xpResolveInfo = queryCrossProfileIntents( 5263 matchingFilters, intent, resolvedType, flags, userId, 5264 hasNonNegativePriorityResult); 5265 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5266 boolean isVisibleToUser = filterIfNotSystemUser( 5267 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5268 if (isVisibleToUser) { 5269 result.add(xpResolveInfo); 5270 Collections.sort(result, mResolvePrioritySorter); 5271 } 5272 } 5273 if (hasWebURI(intent)) { 5274 CrossProfileDomainInfo xpDomainInfo = null; 5275 final UserInfo parent = getProfileParent(userId); 5276 if (parent != null) { 5277 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5278 flags, userId, parent.id); 5279 } 5280 if (xpDomainInfo != null) { 5281 if (xpResolveInfo != null) { 5282 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5283 // in the result. 5284 result.remove(xpResolveInfo); 5285 } 5286 if (result.size() == 0) { 5287 result.add(xpDomainInfo.resolveInfo); 5288 return result; 5289 } 5290 } else if (result.size() <= 1) { 5291 return result; 5292 } 5293 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5294 xpDomainInfo, userId); 5295 Collections.sort(result, mResolvePrioritySorter); 5296 } 5297 return result; 5298 } 5299 final PackageParser.Package pkg = mPackages.get(pkgName); 5300 if (pkg != null) { 5301 return filterIfNotSystemUser( 5302 mActivities.queryIntentForPackage( 5303 intent, resolvedType, flags, pkg.activities, userId), 5304 userId); 5305 } 5306 return new ArrayList<ResolveInfo>(); 5307 } 5308 } 5309 5310 private static class CrossProfileDomainInfo { 5311 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5312 ResolveInfo resolveInfo; 5313 /* Best domain verification status of the activities found in the other profile */ 5314 int bestDomainVerificationStatus; 5315 } 5316 5317 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5318 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5319 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5320 sourceUserId)) { 5321 return null; 5322 } 5323 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5324 resolvedType, flags, parentUserId); 5325 5326 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5327 return null; 5328 } 5329 CrossProfileDomainInfo result = null; 5330 int size = resultTargetUser.size(); 5331 for (int i = 0; i < size; i++) { 5332 ResolveInfo riTargetUser = resultTargetUser.get(i); 5333 // Intent filter verification is only for filters that specify a host. So don't return 5334 // those that handle all web uris. 5335 if (riTargetUser.handleAllWebDataURI) { 5336 continue; 5337 } 5338 String packageName = riTargetUser.activityInfo.packageName; 5339 PackageSetting ps = mSettings.mPackages.get(packageName); 5340 if (ps == null) { 5341 continue; 5342 } 5343 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5344 int status = (int)(verificationState >> 32); 5345 if (result == null) { 5346 result = new CrossProfileDomainInfo(); 5347 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5348 sourceUserId, parentUserId); 5349 result.bestDomainVerificationStatus = status; 5350 } else { 5351 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5352 result.bestDomainVerificationStatus); 5353 } 5354 } 5355 // Don't consider matches with status NEVER across profiles. 5356 if (result != null && result.bestDomainVerificationStatus 5357 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5358 return null; 5359 } 5360 return result; 5361 } 5362 5363 /** 5364 * Verification statuses are ordered from the worse to the best, except for 5365 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5366 */ 5367 private int bestDomainVerificationStatus(int status1, int status2) { 5368 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5369 return status2; 5370 } 5371 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5372 return status1; 5373 } 5374 return (int) MathUtils.max(status1, status2); 5375 } 5376 5377 private boolean isUserEnabled(int userId) { 5378 long callingId = Binder.clearCallingIdentity(); 5379 try { 5380 UserInfo userInfo = sUserManager.getUserInfo(userId); 5381 return userInfo != null && userInfo.isEnabled(); 5382 } finally { 5383 Binder.restoreCallingIdentity(callingId); 5384 } 5385 } 5386 5387 /** 5388 * Filter out activities with systemUserOnly flag set, when current user is not System. 5389 * 5390 * @return filtered list 5391 */ 5392 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5393 if (userId == UserHandle.USER_SYSTEM) { 5394 return resolveInfos; 5395 } 5396 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5397 ResolveInfo info = resolveInfos.get(i); 5398 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5399 resolveInfos.remove(i); 5400 } 5401 } 5402 return resolveInfos; 5403 } 5404 5405 /** 5406 * @param resolveInfos list of resolve infos in descending priority order 5407 * @return if the list contains a resolve info with non-negative priority 5408 */ 5409 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5410 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5411 } 5412 5413 private static boolean hasWebURI(Intent intent) { 5414 if (intent.getData() == null) { 5415 return false; 5416 } 5417 final String scheme = intent.getScheme(); 5418 if (TextUtils.isEmpty(scheme)) { 5419 return false; 5420 } 5421 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5422 } 5423 5424 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5425 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5426 int userId) { 5427 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5428 5429 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5430 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5431 candidates.size()); 5432 } 5433 5434 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5435 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5436 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5437 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5438 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5439 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5440 5441 synchronized (mPackages) { 5442 final int count = candidates.size(); 5443 // First, try to use linked apps. Partition the candidates into four lists: 5444 // one for the final results, one for the "do not use ever", one for "undefined status" 5445 // and finally one for "browser app type". 5446 for (int n=0; n<count; n++) { 5447 ResolveInfo info = candidates.get(n); 5448 String packageName = info.activityInfo.packageName; 5449 PackageSetting ps = mSettings.mPackages.get(packageName); 5450 if (ps != null) { 5451 // Add to the special match all list (Browser use case) 5452 if (info.handleAllWebDataURI) { 5453 matchAllList.add(info); 5454 continue; 5455 } 5456 // Try to get the status from User settings first 5457 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5458 int status = (int)(packedStatus >> 32); 5459 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5460 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5461 if (DEBUG_DOMAIN_VERIFICATION) { 5462 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5463 + " : linkgen=" + linkGeneration); 5464 } 5465 // Use link-enabled generation as preferredOrder, i.e. 5466 // prefer newly-enabled over earlier-enabled. 5467 info.preferredOrder = linkGeneration; 5468 alwaysList.add(info); 5469 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5470 if (DEBUG_DOMAIN_VERIFICATION) { 5471 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5472 } 5473 neverList.add(info); 5474 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5475 if (DEBUG_DOMAIN_VERIFICATION) { 5476 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5477 } 5478 alwaysAskList.add(info); 5479 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5480 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5481 if (DEBUG_DOMAIN_VERIFICATION) { 5482 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5483 } 5484 undefinedList.add(info); 5485 } 5486 } 5487 } 5488 5489 // We'll want to include browser possibilities in a few cases 5490 boolean includeBrowser = false; 5491 5492 // First try to add the "always" resolution(s) for the current user, if any 5493 if (alwaysList.size() > 0) { 5494 result.addAll(alwaysList); 5495 } else { 5496 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5497 result.addAll(undefinedList); 5498 // Maybe add one for the other profile. 5499 if (xpDomainInfo != null && ( 5500 xpDomainInfo.bestDomainVerificationStatus 5501 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5502 result.add(xpDomainInfo.resolveInfo); 5503 } 5504 includeBrowser = true; 5505 } 5506 5507 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5508 // If there were 'always' entries their preferred order has been set, so we also 5509 // back that off to make the alternatives equivalent 5510 if (alwaysAskList.size() > 0) { 5511 for (ResolveInfo i : result) { 5512 i.preferredOrder = 0; 5513 } 5514 result.addAll(alwaysAskList); 5515 includeBrowser = true; 5516 } 5517 5518 if (includeBrowser) { 5519 // Also add browsers (all of them or only the default one) 5520 if (DEBUG_DOMAIN_VERIFICATION) { 5521 Slog.v(TAG, " ...including browsers in candidate set"); 5522 } 5523 if ((matchFlags & MATCH_ALL) != 0) { 5524 result.addAll(matchAllList); 5525 } else { 5526 // Browser/generic handling case. If there's a default browser, go straight 5527 // to that (but only if there is no other higher-priority match). 5528 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5529 int maxMatchPrio = 0; 5530 ResolveInfo defaultBrowserMatch = null; 5531 final int numCandidates = matchAllList.size(); 5532 for (int n = 0; n < numCandidates; n++) { 5533 ResolveInfo info = matchAllList.get(n); 5534 // track the highest overall match priority... 5535 if (info.priority > maxMatchPrio) { 5536 maxMatchPrio = info.priority; 5537 } 5538 // ...and the highest-priority default browser match 5539 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5540 if (defaultBrowserMatch == null 5541 || (defaultBrowserMatch.priority < info.priority)) { 5542 if (debug) { 5543 Slog.v(TAG, "Considering default browser match " + info); 5544 } 5545 defaultBrowserMatch = info; 5546 } 5547 } 5548 } 5549 if (defaultBrowserMatch != null 5550 && defaultBrowserMatch.priority >= maxMatchPrio 5551 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5552 { 5553 if (debug) { 5554 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5555 } 5556 result.add(defaultBrowserMatch); 5557 } else { 5558 result.addAll(matchAllList); 5559 } 5560 } 5561 5562 // If there is nothing selected, add all candidates and remove the ones that the user 5563 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5564 if (result.size() == 0) { 5565 result.addAll(candidates); 5566 result.removeAll(neverList); 5567 } 5568 } 5569 } 5570 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5571 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5572 result.size()); 5573 for (ResolveInfo info : result) { 5574 Slog.v(TAG, " + " + info.activityInfo); 5575 } 5576 } 5577 return result; 5578 } 5579 5580 // Returns a packed value as a long: 5581 // 5582 // high 'int'-sized word: link status: undefined/ask/never/always. 5583 // low 'int'-sized word: relative priority among 'always' results. 5584 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5585 long result = ps.getDomainVerificationStatusForUser(userId); 5586 // if none available, get the master status 5587 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5588 if (ps.getIntentFilterVerificationInfo() != null) { 5589 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5590 } 5591 } 5592 return result; 5593 } 5594 5595 private ResolveInfo querySkipCurrentProfileIntents( 5596 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5597 int flags, int sourceUserId) { 5598 if (matchingFilters != null) { 5599 int size = matchingFilters.size(); 5600 for (int i = 0; i < size; i ++) { 5601 CrossProfileIntentFilter filter = matchingFilters.get(i); 5602 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5603 // Checking if there are activities in the target user that can handle the 5604 // intent. 5605 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5606 resolvedType, flags, sourceUserId); 5607 if (resolveInfo != null) { 5608 return resolveInfo; 5609 } 5610 } 5611 } 5612 } 5613 return null; 5614 } 5615 5616 // Return matching ResolveInfo in target user if any. 5617 private ResolveInfo queryCrossProfileIntents( 5618 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5619 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5620 if (matchingFilters != null) { 5621 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5622 // match the same intent. For performance reasons, it is better not to 5623 // run queryIntent twice for the same userId 5624 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5625 int size = matchingFilters.size(); 5626 for (int i = 0; i < size; i++) { 5627 CrossProfileIntentFilter filter = matchingFilters.get(i); 5628 int targetUserId = filter.getTargetUserId(); 5629 boolean skipCurrentProfile = 5630 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5631 boolean skipCurrentProfileIfNoMatchFound = 5632 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5633 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5634 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5635 // Checking if there are activities in the target user that can handle the 5636 // intent. 5637 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5638 resolvedType, flags, sourceUserId); 5639 if (resolveInfo != null) return resolveInfo; 5640 alreadyTriedUserIds.put(targetUserId, true); 5641 } 5642 } 5643 } 5644 return null; 5645 } 5646 5647 /** 5648 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5649 * will forward the intent to the filter's target user. 5650 * Otherwise, returns null. 5651 */ 5652 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5653 String resolvedType, int flags, int sourceUserId) { 5654 int targetUserId = filter.getTargetUserId(); 5655 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5656 resolvedType, flags, targetUserId); 5657 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5658 // If all the matches in the target profile are suspended, return null. 5659 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5660 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5661 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5662 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5663 targetUserId); 5664 } 5665 } 5666 } 5667 return null; 5668 } 5669 5670 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5671 int sourceUserId, int targetUserId) { 5672 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5673 long ident = Binder.clearCallingIdentity(); 5674 boolean targetIsProfile; 5675 try { 5676 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5677 } finally { 5678 Binder.restoreCallingIdentity(ident); 5679 } 5680 String className; 5681 if (targetIsProfile) { 5682 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5683 } else { 5684 className = FORWARD_INTENT_TO_PARENT; 5685 } 5686 ComponentName forwardingActivityComponentName = new ComponentName( 5687 mAndroidApplication.packageName, className); 5688 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5689 sourceUserId); 5690 if (!targetIsProfile) { 5691 forwardingActivityInfo.showUserIcon = targetUserId; 5692 forwardingResolveInfo.noResourceId = true; 5693 } 5694 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5695 forwardingResolveInfo.priority = 0; 5696 forwardingResolveInfo.preferredOrder = 0; 5697 forwardingResolveInfo.match = 0; 5698 forwardingResolveInfo.isDefault = true; 5699 forwardingResolveInfo.filter = filter; 5700 forwardingResolveInfo.targetUserId = targetUserId; 5701 return forwardingResolveInfo; 5702 } 5703 5704 @Override 5705 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5706 Intent[] specifics, String[] specificTypes, Intent intent, 5707 String resolvedType, int flags, int userId) { 5708 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5709 specificTypes, intent, resolvedType, flags, userId)); 5710 } 5711 5712 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5713 Intent[] specifics, String[] specificTypes, Intent intent, 5714 String resolvedType, int flags, int userId) { 5715 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5716 flags = updateFlagsForResolve(flags, userId, intent); 5717 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5718 false /* requireFullPermission */, false /* checkShell */, 5719 "query intent activity options"); 5720 final String resultsAction = intent.getAction(); 5721 5722 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5723 | PackageManager.GET_RESOLVED_FILTER, userId); 5724 5725 if (DEBUG_INTENT_MATCHING) { 5726 Log.v(TAG, "Query " + intent + ": " + results); 5727 } 5728 5729 int specificsPos = 0; 5730 int N; 5731 5732 // todo: note that the algorithm used here is O(N^2). This 5733 // isn't a problem in our current environment, but if we start running 5734 // into situations where we have more than 5 or 10 matches then this 5735 // should probably be changed to something smarter... 5736 5737 // First we go through and resolve each of the specific items 5738 // that were supplied, taking care of removing any corresponding 5739 // duplicate items in the generic resolve list. 5740 if (specifics != null) { 5741 for (int i=0; i<specifics.length; i++) { 5742 final Intent sintent = specifics[i]; 5743 if (sintent == null) { 5744 continue; 5745 } 5746 5747 if (DEBUG_INTENT_MATCHING) { 5748 Log.v(TAG, "Specific #" + i + ": " + sintent); 5749 } 5750 5751 String action = sintent.getAction(); 5752 if (resultsAction != null && resultsAction.equals(action)) { 5753 // If this action was explicitly requested, then don't 5754 // remove things that have it. 5755 action = null; 5756 } 5757 5758 ResolveInfo ri = null; 5759 ActivityInfo ai = null; 5760 5761 ComponentName comp = sintent.getComponent(); 5762 if (comp == null) { 5763 ri = resolveIntent( 5764 sintent, 5765 specificTypes != null ? specificTypes[i] : null, 5766 flags, userId); 5767 if (ri == null) { 5768 continue; 5769 } 5770 if (ri == mResolveInfo) { 5771 // ACK! Must do something better with this. 5772 } 5773 ai = ri.activityInfo; 5774 comp = new ComponentName(ai.applicationInfo.packageName, 5775 ai.name); 5776 } else { 5777 ai = getActivityInfo(comp, flags, userId); 5778 if (ai == null) { 5779 continue; 5780 } 5781 } 5782 5783 // Look for any generic query activities that are duplicates 5784 // of this specific one, and remove them from the results. 5785 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5786 N = results.size(); 5787 int j; 5788 for (j=specificsPos; j<N; j++) { 5789 ResolveInfo sri = results.get(j); 5790 if ((sri.activityInfo.name.equals(comp.getClassName()) 5791 && sri.activityInfo.applicationInfo.packageName.equals( 5792 comp.getPackageName())) 5793 || (action != null && sri.filter.matchAction(action))) { 5794 results.remove(j); 5795 if (DEBUG_INTENT_MATCHING) Log.v( 5796 TAG, "Removing duplicate item from " + j 5797 + " due to specific " + specificsPos); 5798 if (ri == null) { 5799 ri = sri; 5800 } 5801 j--; 5802 N--; 5803 } 5804 } 5805 5806 // Add this specific item to its proper place. 5807 if (ri == null) { 5808 ri = new ResolveInfo(); 5809 ri.activityInfo = ai; 5810 } 5811 results.add(specificsPos, ri); 5812 ri.specificIndex = i; 5813 specificsPos++; 5814 } 5815 } 5816 5817 // Now we go through the remaining generic results and remove any 5818 // duplicate actions that are found here. 5819 N = results.size(); 5820 for (int i=specificsPos; i<N-1; i++) { 5821 final ResolveInfo rii = results.get(i); 5822 if (rii.filter == null) { 5823 continue; 5824 } 5825 5826 // Iterate over all of the actions of this result's intent 5827 // filter... typically this should be just one. 5828 final Iterator<String> it = rii.filter.actionsIterator(); 5829 if (it == null) { 5830 continue; 5831 } 5832 while (it.hasNext()) { 5833 final String action = it.next(); 5834 if (resultsAction != null && resultsAction.equals(action)) { 5835 // If this action was explicitly requested, then don't 5836 // remove things that have it. 5837 continue; 5838 } 5839 for (int j=i+1; j<N; j++) { 5840 final ResolveInfo rij = results.get(j); 5841 if (rij.filter != null && rij.filter.hasAction(action)) { 5842 results.remove(j); 5843 if (DEBUG_INTENT_MATCHING) Log.v( 5844 TAG, "Removing duplicate item from " + j 5845 + " due to action " + action + " at " + i); 5846 j--; 5847 N--; 5848 } 5849 } 5850 } 5851 5852 // If the caller didn't request filter information, drop it now 5853 // so we don't have to marshall/unmarshall it. 5854 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5855 rii.filter = null; 5856 } 5857 } 5858 5859 // Filter out the caller activity if so requested. 5860 if (caller != null) { 5861 N = results.size(); 5862 for (int i=0; i<N; i++) { 5863 ActivityInfo ainfo = results.get(i).activityInfo; 5864 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5865 && caller.getClassName().equals(ainfo.name)) { 5866 results.remove(i); 5867 break; 5868 } 5869 } 5870 } 5871 5872 // If the caller didn't request filter information, 5873 // drop them now so we don't have to 5874 // marshall/unmarshall it. 5875 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5876 N = results.size(); 5877 for (int i=0; i<N; i++) { 5878 results.get(i).filter = null; 5879 } 5880 } 5881 5882 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5883 return results; 5884 } 5885 5886 @Override 5887 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5888 String resolvedType, int flags, int userId) { 5889 return new ParceledListSlice<>( 5890 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5891 } 5892 5893 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5894 String resolvedType, int flags, int userId) { 5895 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5896 flags = updateFlagsForResolve(flags, userId, intent); 5897 ComponentName comp = intent.getComponent(); 5898 if (comp == null) { 5899 if (intent.getSelector() != null) { 5900 intent = intent.getSelector(); 5901 comp = intent.getComponent(); 5902 } 5903 } 5904 if (comp != null) { 5905 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5906 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5907 if (ai != null) { 5908 ResolveInfo ri = new ResolveInfo(); 5909 ri.activityInfo = ai; 5910 list.add(ri); 5911 } 5912 return list; 5913 } 5914 5915 // reader 5916 synchronized (mPackages) { 5917 String pkgName = intent.getPackage(); 5918 if (pkgName == null) { 5919 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 5920 } 5921 final PackageParser.Package pkg = mPackages.get(pkgName); 5922 if (pkg != null) { 5923 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 5924 userId); 5925 } 5926 return Collections.emptyList(); 5927 } 5928 } 5929 5930 @Override 5931 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 5932 if (!sUserManager.exists(userId)) return null; 5933 flags = updateFlagsForResolve(flags, userId, intent); 5934 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 5935 if (query != null) { 5936 if (query.size() >= 1) { 5937 // If there is more than one service with the same priority, 5938 // just arbitrarily pick the first one. 5939 return query.get(0); 5940 } 5941 } 5942 return null; 5943 } 5944 5945 @Override 5946 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 5947 String resolvedType, int flags, int userId) { 5948 return new ParceledListSlice<>( 5949 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 5950 } 5951 5952 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 5953 String resolvedType, int flags, int userId) { 5954 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5955 flags = updateFlagsForResolve(flags, userId, intent); 5956 ComponentName comp = intent.getComponent(); 5957 if (comp == null) { 5958 if (intent.getSelector() != null) { 5959 intent = intent.getSelector(); 5960 comp = intent.getComponent(); 5961 } 5962 } 5963 if (comp != null) { 5964 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5965 final ServiceInfo si = getServiceInfo(comp, flags, userId); 5966 if (si != null) { 5967 final ResolveInfo ri = new ResolveInfo(); 5968 ri.serviceInfo = si; 5969 list.add(ri); 5970 } 5971 return list; 5972 } 5973 5974 // reader 5975 synchronized (mPackages) { 5976 String pkgName = intent.getPackage(); 5977 if (pkgName == null) { 5978 return mServices.queryIntent(intent, resolvedType, flags, userId); 5979 } 5980 final PackageParser.Package pkg = mPackages.get(pkgName); 5981 if (pkg != null) { 5982 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 5983 userId); 5984 } 5985 return Collections.emptyList(); 5986 } 5987 } 5988 5989 @Override 5990 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 5991 String resolvedType, int flags, int userId) { 5992 return new ParceledListSlice<>( 5993 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 5994 } 5995 5996 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 5997 Intent intent, String resolvedType, int flags, int userId) { 5998 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5999 flags = updateFlagsForResolve(flags, userId, intent); 6000 ComponentName comp = intent.getComponent(); 6001 if (comp == null) { 6002 if (intent.getSelector() != null) { 6003 intent = intent.getSelector(); 6004 comp = intent.getComponent(); 6005 } 6006 } 6007 if (comp != null) { 6008 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6009 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6010 if (pi != null) { 6011 final ResolveInfo ri = new ResolveInfo(); 6012 ri.providerInfo = pi; 6013 list.add(ri); 6014 } 6015 return list; 6016 } 6017 6018 // reader 6019 synchronized (mPackages) { 6020 String pkgName = intent.getPackage(); 6021 if (pkgName == null) { 6022 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6023 } 6024 final PackageParser.Package pkg = mPackages.get(pkgName); 6025 if (pkg != null) { 6026 return mProviders.queryIntentForPackage( 6027 intent, resolvedType, flags, pkg.providers, userId); 6028 } 6029 return Collections.emptyList(); 6030 } 6031 } 6032 6033 @Override 6034 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6035 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6036 flags = updateFlagsForPackage(flags, userId, null); 6037 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6038 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6039 true /* requireFullPermission */, false /* checkShell */, 6040 "get installed packages"); 6041 6042 // writer 6043 synchronized (mPackages) { 6044 ArrayList<PackageInfo> list; 6045 if (listUninstalled) { 6046 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6047 for (PackageSetting ps : mSettings.mPackages.values()) { 6048 final PackageInfo pi; 6049 if (ps.pkg != null) { 6050 pi = generatePackageInfo(ps, flags, userId); 6051 } else { 6052 pi = generatePackageInfo(ps, flags, userId); 6053 } 6054 if (pi != null) { 6055 list.add(pi); 6056 } 6057 } 6058 } else { 6059 list = new ArrayList<PackageInfo>(mPackages.size()); 6060 for (PackageParser.Package p : mPackages.values()) { 6061 final PackageInfo pi = 6062 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6063 if (pi != null) { 6064 list.add(pi); 6065 } 6066 } 6067 } 6068 6069 return new ParceledListSlice<PackageInfo>(list); 6070 } 6071 } 6072 6073 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6074 String[] permissions, boolean[] tmp, int flags, int userId) { 6075 int numMatch = 0; 6076 final PermissionsState permissionsState = ps.getPermissionsState(); 6077 for (int i=0; i<permissions.length; i++) { 6078 final String permission = permissions[i]; 6079 if (permissionsState.hasPermission(permission, userId)) { 6080 tmp[i] = true; 6081 numMatch++; 6082 } else { 6083 tmp[i] = false; 6084 } 6085 } 6086 if (numMatch == 0) { 6087 return; 6088 } 6089 final PackageInfo pi; 6090 if (ps.pkg != null) { 6091 pi = generatePackageInfo(ps, flags, userId); 6092 } else { 6093 pi = generatePackageInfo(ps, flags, userId); 6094 } 6095 // The above might return null in cases of uninstalled apps or install-state 6096 // skew across users/profiles. 6097 if (pi != null) { 6098 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6099 if (numMatch == permissions.length) { 6100 pi.requestedPermissions = permissions; 6101 } else { 6102 pi.requestedPermissions = new String[numMatch]; 6103 numMatch = 0; 6104 for (int i=0; i<permissions.length; i++) { 6105 if (tmp[i]) { 6106 pi.requestedPermissions[numMatch] = permissions[i]; 6107 numMatch++; 6108 } 6109 } 6110 } 6111 } 6112 list.add(pi); 6113 } 6114 } 6115 6116 @Override 6117 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6118 String[] permissions, int flags, int userId) { 6119 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6120 flags = updateFlagsForPackage(flags, userId, permissions); 6121 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6122 6123 // writer 6124 synchronized (mPackages) { 6125 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6126 boolean[] tmpBools = new boolean[permissions.length]; 6127 if (listUninstalled) { 6128 for (PackageSetting ps : mSettings.mPackages.values()) { 6129 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6130 } 6131 } else { 6132 for (PackageParser.Package pkg : mPackages.values()) { 6133 PackageSetting ps = (PackageSetting)pkg.mExtras; 6134 if (ps != null) { 6135 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6136 userId); 6137 } 6138 } 6139 } 6140 6141 return new ParceledListSlice<PackageInfo>(list); 6142 } 6143 } 6144 6145 @Override 6146 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6147 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6148 flags = updateFlagsForApplication(flags, userId, null); 6149 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6150 6151 // writer 6152 synchronized (mPackages) { 6153 ArrayList<ApplicationInfo> list; 6154 if (listUninstalled) { 6155 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6156 for (PackageSetting ps : mSettings.mPackages.values()) { 6157 ApplicationInfo ai; 6158 if (ps.pkg != null) { 6159 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6160 ps.readUserState(userId), userId); 6161 } else { 6162 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6163 } 6164 if (ai != null) { 6165 list.add(ai); 6166 } 6167 } 6168 } else { 6169 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6170 for (PackageParser.Package p : mPackages.values()) { 6171 if (p.mExtras != null) { 6172 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6173 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6174 if (ai != null) { 6175 list.add(ai); 6176 } 6177 } 6178 } 6179 } 6180 6181 return new ParceledListSlice<ApplicationInfo>(list); 6182 } 6183 } 6184 6185 @Override 6186 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6187 if (DISABLE_EPHEMERAL_APPS) { 6188 return null; 6189 } 6190 6191 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6192 "getEphemeralApplications"); 6193 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6194 true /* requireFullPermission */, false /* checkShell */, 6195 "getEphemeralApplications"); 6196 synchronized (mPackages) { 6197 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6198 .getEphemeralApplicationsLPw(userId); 6199 if (ephemeralApps != null) { 6200 return new ParceledListSlice<>(ephemeralApps); 6201 } 6202 } 6203 return null; 6204 } 6205 6206 @Override 6207 public boolean isEphemeralApplication(String packageName, int userId) { 6208 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6209 true /* requireFullPermission */, false /* checkShell */, 6210 "isEphemeral"); 6211 if (DISABLE_EPHEMERAL_APPS) { 6212 return false; 6213 } 6214 6215 if (!isCallerSameApp(packageName)) { 6216 return false; 6217 } 6218 synchronized (mPackages) { 6219 PackageParser.Package pkg = mPackages.get(packageName); 6220 if (pkg != null) { 6221 return pkg.applicationInfo.isEphemeralApp(); 6222 } 6223 } 6224 return false; 6225 } 6226 6227 @Override 6228 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6229 if (DISABLE_EPHEMERAL_APPS) { 6230 return null; 6231 } 6232 6233 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6234 true /* requireFullPermission */, false /* checkShell */, 6235 "getCookie"); 6236 if (!isCallerSameApp(packageName)) { 6237 return null; 6238 } 6239 synchronized (mPackages) { 6240 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6241 packageName, userId); 6242 } 6243 } 6244 6245 @Override 6246 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6247 if (DISABLE_EPHEMERAL_APPS) { 6248 return true; 6249 } 6250 6251 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6252 true /* requireFullPermission */, true /* checkShell */, 6253 "setCookie"); 6254 if (!isCallerSameApp(packageName)) { 6255 return false; 6256 } 6257 synchronized (mPackages) { 6258 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6259 packageName, cookie, userId); 6260 } 6261 } 6262 6263 @Override 6264 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6265 if (DISABLE_EPHEMERAL_APPS) { 6266 return null; 6267 } 6268 6269 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6270 "getEphemeralApplicationIcon"); 6271 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6272 true /* requireFullPermission */, false /* checkShell */, 6273 "getEphemeralApplicationIcon"); 6274 synchronized (mPackages) { 6275 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6276 packageName, userId); 6277 } 6278 } 6279 6280 private boolean isCallerSameApp(String packageName) { 6281 PackageParser.Package pkg = mPackages.get(packageName); 6282 return pkg != null 6283 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6284 } 6285 6286 @Override 6287 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6288 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6289 } 6290 6291 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6292 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6293 6294 // reader 6295 synchronized (mPackages) { 6296 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6297 final int userId = UserHandle.getCallingUserId(); 6298 while (i.hasNext()) { 6299 final PackageParser.Package p = i.next(); 6300 if (p.applicationInfo == null) continue; 6301 6302 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6303 && !p.applicationInfo.isDirectBootAware(); 6304 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6305 && p.applicationInfo.isDirectBootAware(); 6306 6307 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6308 && (!mSafeMode || isSystemApp(p)) 6309 && (matchesUnaware || matchesAware)) { 6310 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6311 if (ps != null) { 6312 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6313 ps.readUserState(userId), userId); 6314 if (ai != null) { 6315 finalList.add(ai); 6316 } 6317 } 6318 } 6319 } 6320 } 6321 6322 return finalList; 6323 } 6324 6325 @Override 6326 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6327 if (!sUserManager.exists(userId)) return null; 6328 flags = updateFlagsForComponent(flags, userId, name); 6329 // reader 6330 synchronized (mPackages) { 6331 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6332 PackageSetting ps = provider != null 6333 ? mSettings.mPackages.get(provider.owner.packageName) 6334 : null; 6335 return ps != null 6336 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6337 ? PackageParser.generateProviderInfo(provider, flags, 6338 ps.readUserState(userId), userId) 6339 : null; 6340 } 6341 } 6342 6343 /** 6344 * @deprecated 6345 */ 6346 @Deprecated 6347 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6348 // reader 6349 synchronized (mPackages) { 6350 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6351 .entrySet().iterator(); 6352 final int userId = UserHandle.getCallingUserId(); 6353 while (i.hasNext()) { 6354 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6355 PackageParser.Provider p = entry.getValue(); 6356 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6357 6358 if (ps != null && p.syncable 6359 && (!mSafeMode || (p.info.applicationInfo.flags 6360 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6361 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6362 ps.readUserState(userId), userId); 6363 if (info != null) { 6364 outNames.add(entry.getKey()); 6365 outInfo.add(info); 6366 } 6367 } 6368 } 6369 } 6370 } 6371 6372 @Override 6373 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6374 int uid, int flags) { 6375 final int userId = processName != null ? UserHandle.getUserId(uid) 6376 : UserHandle.getCallingUserId(); 6377 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6378 flags = updateFlagsForComponent(flags, userId, processName); 6379 6380 ArrayList<ProviderInfo> finalList = null; 6381 // reader 6382 synchronized (mPackages) { 6383 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6384 while (i.hasNext()) { 6385 final PackageParser.Provider p = i.next(); 6386 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6387 if (ps != null && p.info.authority != null 6388 && (processName == null 6389 || (p.info.processName.equals(processName) 6390 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6391 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6392 if (finalList == null) { 6393 finalList = new ArrayList<ProviderInfo>(3); 6394 } 6395 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6396 ps.readUserState(userId), userId); 6397 if (info != null) { 6398 finalList.add(info); 6399 } 6400 } 6401 } 6402 } 6403 6404 if (finalList != null) { 6405 Collections.sort(finalList, mProviderInitOrderSorter); 6406 return new ParceledListSlice<ProviderInfo>(finalList); 6407 } 6408 6409 return ParceledListSlice.emptyList(); 6410 } 6411 6412 @Override 6413 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6414 // reader 6415 synchronized (mPackages) { 6416 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6417 return PackageParser.generateInstrumentationInfo(i, flags); 6418 } 6419 } 6420 6421 @Override 6422 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6423 String targetPackage, int flags) { 6424 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6425 } 6426 6427 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6428 int flags) { 6429 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6430 6431 // reader 6432 synchronized (mPackages) { 6433 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6434 while (i.hasNext()) { 6435 final PackageParser.Instrumentation p = i.next(); 6436 if (targetPackage == null 6437 || targetPackage.equals(p.info.targetPackage)) { 6438 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6439 flags); 6440 if (ii != null) { 6441 finalList.add(ii); 6442 } 6443 } 6444 } 6445 } 6446 6447 return finalList; 6448 } 6449 6450 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6451 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6452 if (overlays == null) { 6453 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6454 return; 6455 } 6456 for (PackageParser.Package opkg : overlays.values()) { 6457 // Not much to do if idmap fails: we already logged the error 6458 // and we certainly don't want to abort installation of pkg simply 6459 // because an overlay didn't fit properly. For these reasons, 6460 // ignore the return value of createIdmapForPackagePairLI. 6461 createIdmapForPackagePairLI(pkg, opkg); 6462 } 6463 } 6464 6465 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6466 PackageParser.Package opkg) { 6467 if (!opkg.mTrustedOverlay) { 6468 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6469 opkg.baseCodePath + ": overlay not trusted"); 6470 return false; 6471 } 6472 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6473 if (overlaySet == null) { 6474 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6475 opkg.baseCodePath + " but target package has no known overlays"); 6476 return false; 6477 } 6478 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6479 // TODO: generate idmap for split APKs 6480 try { 6481 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6482 } catch (InstallerException e) { 6483 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6484 + opkg.baseCodePath); 6485 return false; 6486 } 6487 PackageParser.Package[] overlayArray = 6488 overlaySet.values().toArray(new PackageParser.Package[0]); 6489 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6490 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6491 return p1.mOverlayPriority - p2.mOverlayPriority; 6492 } 6493 }; 6494 Arrays.sort(overlayArray, cmp); 6495 6496 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6497 int i = 0; 6498 for (PackageParser.Package p : overlayArray) { 6499 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6500 } 6501 return true; 6502 } 6503 6504 private void scanDirTracedLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6505 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6506 try { 6507 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6508 } finally { 6509 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6510 } 6511 } 6512 6513 private void scanDirLI(File dir, int parseFlags, int scanFlags, long currentTime) { 6514 final File[] files = dir.listFiles(); 6515 if (ArrayUtils.isEmpty(files)) { 6516 Log.d(TAG, "No files in app dir " + dir); 6517 return; 6518 } 6519 6520 if (DEBUG_PACKAGE_SCANNING) { 6521 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6522 + " flags=0x" + Integer.toHexString(parseFlags)); 6523 } 6524 6525 for (File file : files) { 6526 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6527 && !PackageInstallerService.isStageName(file.getName()); 6528 if (!isPackage) { 6529 // Ignore entries which are not packages 6530 continue; 6531 } 6532 try { 6533 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6534 scanFlags, currentTime, null); 6535 } catch (PackageManagerException e) { 6536 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6537 6538 // Delete invalid userdata apps 6539 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6540 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6541 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6542 removeCodePathLI(file); 6543 } 6544 } 6545 } 6546 } 6547 6548 private static File getSettingsProblemFile() { 6549 File dataDir = Environment.getDataDirectory(); 6550 File systemDir = new File(dataDir, "system"); 6551 File fname = new File(systemDir, "uiderrors.txt"); 6552 return fname; 6553 } 6554 6555 static void reportSettingsProblem(int priority, String msg) { 6556 logCriticalInfo(priority, msg); 6557 } 6558 6559 static void logCriticalInfo(int priority, String msg) { 6560 Slog.println(priority, TAG, msg); 6561 EventLogTags.writePmCriticalInfo(msg); 6562 try { 6563 File fname = getSettingsProblemFile(); 6564 FileOutputStream out = new FileOutputStream(fname, true); 6565 PrintWriter pw = new FastPrintWriter(out); 6566 SimpleDateFormat formatter = new SimpleDateFormat(); 6567 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6568 pw.println(dateString + ": " + msg); 6569 pw.close(); 6570 FileUtils.setPermissions( 6571 fname.toString(), 6572 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6573 -1, -1); 6574 } catch (java.io.IOException e) { 6575 } 6576 } 6577 6578 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6579 int parseFlags) throws PackageManagerException { 6580 if (ps != null 6581 && ps.codePath.equals(srcFile) 6582 && ps.timeStamp == srcFile.lastModified() 6583 && !isCompatSignatureUpdateNeeded(pkg) 6584 && !isRecoverSignatureUpdateNeeded(pkg)) { 6585 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6586 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6587 ArraySet<PublicKey> signingKs; 6588 synchronized (mPackages) { 6589 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6590 } 6591 if (ps.signatures.mSignatures != null 6592 && ps.signatures.mSignatures.length != 0 6593 && signingKs != null) { 6594 // Optimization: reuse the existing cached certificates 6595 // if the package appears to be unchanged. 6596 pkg.mSignatures = ps.signatures.mSignatures; 6597 pkg.mSigningKeys = signingKs; 6598 return; 6599 } 6600 6601 Slog.w(TAG, "PackageSetting for " + ps.name 6602 + " is missing signatures. Collecting certs again to recover them."); 6603 } else { 6604 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6605 } 6606 6607 try { 6608 PackageParser.collectCertificates(pkg, parseFlags); 6609 } catch (PackageParserException e) { 6610 throw PackageManagerException.from(e); 6611 } 6612 } 6613 6614 /** 6615 * Traces a package scan. 6616 * @see #scanPackageLI(File, int, int, long, UserHandle) 6617 */ 6618 private PackageParser.Package scanPackageTracedLI(File scanFile, int parseFlags, int scanFlags, 6619 long currentTime, UserHandle user) throws PackageManagerException { 6620 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6621 try { 6622 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6623 } finally { 6624 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6625 } 6626 } 6627 6628 /** 6629 * Scans a package and returns the newly parsed package. 6630 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6631 */ 6632 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6633 long currentTime, UserHandle user) throws PackageManagerException { 6634 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6635 parseFlags |= mDefParseFlags; 6636 PackageParser pp = new PackageParser(); 6637 pp.setSeparateProcesses(mSeparateProcesses); 6638 pp.setOnlyCoreApps(mOnlyCore); 6639 pp.setDisplayMetrics(mMetrics); 6640 6641 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6642 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6643 } 6644 6645 final PackageParser.Package pkg; 6646 try { 6647 pkg = pp.parsePackage(scanFile, parseFlags); 6648 } catch (PackageParserException e) { 6649 throw PackageManagerException.from(e); 6650 } 6651 6652 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6653 } 6654 6655 /** 6656 * Scans a package and returns the newly parsed package. 6657 * @throws PackageManagerException on a parse error. 6658 */ 6659 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6660 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6661 throws PackageManagerException { 6662 // If the package has children and this is the first dive in the function 6663 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6664 // packages (parent and children) would be successfully scanned before the 6665 // actual scan since scanning mutates internal state and we want to atomically 6666 // install the package and its children. 6667 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6668 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6669 scanFlags |= SCAN_CHECK_ONLY; 6670 } 6671 } else { 6672 scanFlags &= ~SCAN_CHECK_ONLY; 6673 } 6674 6675 // Scan the parent 6676 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, parseFlags, 6677 scanFlags, currentTime, user); 6678 6679 // Scan the children 6680 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6681 for (int i = 0; i < childCount; i++) { 6682 PackageParser.Package childPackage = pkg.childPackages.get(i); 6683 scanPackageInternalLI(childPackage, scanFile, parseFlags, scanFlags, 6684 currentTime, user); 6685 } 6686 6687 6688 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6689 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6690 } 6691 6692 return scannedPkg; 6693 } 6694 6695 /** 6696 * Scans a package and returns the newly parsed package. 6697 * @throws PackageManagerException on a parse error. 6698 */ 6699 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6700 int parseFlags, int scanFlags, long currentTime, UserHandle user) 6701 throws PackageManagerException { 6702 PackageSetting ps = null; 6703 PackageSetting updatedPkg; 6704 // reader 6705 synchronized (mPackages) { 6706 // Look to see if we already know about this package. 6707 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6708 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6709 // This package has been renamed to its original name. Let's 6710 // use that. 6711 ps = mSettings.peekPackageLPr(oldName); 6712 } 6713 // If there was no original package, see one for the real package name. 6714 if (ps == null) { 6715 ps = mSettings.peekPackageLPr(pkg.packageName); 6716 } 6717 // Check to see if this package could be hiding/updating a system 6718 // package. Must look for it either under the original or real 6719 // package name depending on our state. 6720 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6721 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6722 6723 // If this is a package we don't know about on the system partition, we 6724 // may need to remove disabled child packages on the system partition 6725 // or may need to not add child packages if the parent apk is updated 6726 // on the data partition and no longer defines this child package. 6727 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6728 // If this is a parent package for an updated system app and this system 6729 // app got an OTA update which no longer defines some of the child packages 6730 // we have to prune them from the disabled system packages. 6731 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6732 if (disabledPs != null) { 6733 final int scannedChildCount = (pkg.childPackages != null) 6734 ? pkg.childPackages.size() : 0; 6735 final int disabledChildCount = disabledPs.childPackageNames != null 6736 ? disabledPs.childPackageNames.size() : 0; 6737 for (int i = 0; i < disabledChildCount; i++) { 6738 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6739 boolean disabledPackageAvailable = false; 6740 for (int j = 0; j < scannedChildCount; j++) { 6741 PackageParser.Package childPkg = pkg.childPackages.get(j); 6742 if (childPkg.packageName.equals(disabledChildPackageName)) { 6743 disabledPackageAvailable = true; 6744 break; 6745 } 6746 } 6747 if (!disabledPackageAvailable) { 6748 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6749 } 6750 } 6751 } 6752 } 6753 } 6754 6755 boolean updatedPkgBetter = false; 6756 // First check if this is a system package that may involve an update 6757 if (updatedPkg != null && (parseFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6758 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6759 // it needs to drop FLAG_PRIVILEGED. 6760 if (locationIsPrivileged(scanFile)) { 6761 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6762 } else { 6763 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6764 } 6765 6766 if (ps != null && !ps.codePath.equals(scanFile)) { 6767 // The path has changed from what was last scanned... check the 6768 // version of the new path against what we have stored to determine 6769 // what to do. 6770 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6771 if (pkg.mVersionCode <= ps.versionCode) { 6772 // The system package has been updated and the code path does not match 6773 // Ignore entry. Skip it. 6774 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6775 + " ignored: updated version " + ps.versionCode 6776 + " better than this " + pkg.mVersionCode); 6777 if (!updatedPkg.codePath.equals(scanFile)) { 6778 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6779 + ps.name + " changing from " + updatedPkg.codePathString 6780 + " to " + scanFile); 6781 updatedPkg.codePath = scanFile; 6782 updatedPkg.codePathString = scanFile.toString(); 6783 updatedPkg.resourcePath = scanFile; 6784 updatedPkg.resourcePathString = scanFile.toString(); 6785 } 6786 updatedPkg.pkg = pkg; 6787 updatedPkg.versionCode = pkg.mVersionCode; 6788 6789 // Update the disabled system child packages to point to the package too. 6790 final int childCount = updatedPkg.childPackageNames != null 6791 ? updatedPkg.childPackageNames.size() : 0; 6792 for (int i = 0; i < childCount; i++) { 6793 String childPackageName = updatedPkg.childPackageNames.get(i); 6794 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6795 childPackageName); 6796 if (updatedChildPkg != null) { 6797 updatedChildPkg.pkg = pkg; 6798 updatedChildPkg.versionCode = pkg.mVersionCode; 6799 } 6800 } 6801 6802 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6803 + scanFile + " ignored: updated version " + ps.versionCode 6804 + " better than this " + pkg.mVersionCode); 6805 } else { 6806 // The current app on the system partition is better than 6807 // what we have updated to on the data partition; switch 6808 // back to the system partition version. 6809 // At this point, its safely assumed that package installation for 6810 // apps in system partition will go through. If not there won't be a working 6811 // version of the app 6812 // writer 6813 synchronized (mPackages) { 6814 // Just remove the loaded entries from package lists. 6815 mPackages.remove(ps.name); 6816 } 6817 6818 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6819 + " reverting from " + ps.codePathString 6820 + ": new version " + pkg.mVersionCode 6821 + " better than installed " + ps.versionCode); 6822 6823 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6824 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6825 synchronized (mInstallLock) { 6826 args.cleanUpResourcesLI(); 6827 } 6828 synchronized (mPackages) { 6829 mSettings.enableSystemPackageLPw(ps.name); 6830 } 6831 updatedPkgBetter = true; 6832 } 6833 } 6834 } 6835 6836 if (updatedPkg != null) { 6837 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6838 // initially 6839 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 6840 6841 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6842 // flag set initially 6843 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6844 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6845 } 6846 } 6847 6848 // Verify certificates against what was last scanned 6849 collectCertificatesLI(ps, pkg, scanFile, parseFlags); 6850 6851 /* 6852 * A new system app appeared, but we already had a non-system one of the 6853 * same name installed earlier. 6854 */ 6855 boolean shouldHideSystemApp = false; 6856 if (updatedPkg == null && ps != null 6857 && (parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6858 /* 6859 * Check to make sure the signatures match first. If they don't, 6860 * wipe the installed application and its data. 6861 */ 6862 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6863 != PackageManager.SIGNATURE_MATCH) { 6864 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6865 + " signatures don't match existing userdata copy; removing"); 6866 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6867 "scanPackageInternalLI")) { 6868 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6869 } 6870 ps = null; 6871 } else { 6872 /* 6873 * If the newly-added system app is an older version than the 6874 * already installed version, hide it. It will be scanned later 6875 * and re-added like an update. 6876 */ 6877 if (pkg.mVersionCode <= ps.versionCode) { 6878 shouldHideSystemApp = true; 6879 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6880 + " but new version " + pkg.mVersionCode + " better than installed " 6881 + ps.versionCode + "; hiding system"); 6882 } else { 6883 /* 6884 * The newly found system app is a newer version that the 6885 * one previously installed. Simply remove the 6886 * already-installed application and replace it with our own 6887 * while keeping the application data. 6888 */ 6889 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6890 + " reverting from " + ps.codePathString + ": new version " 6891 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6892 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6893 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6894 synchronized (mInstallLock) { 6895 args.cleanUpResourcesLI(); 6896 } 6897 } 6898 } 6899 } 6900 6901 // The apk is forward locked (not public) if its code and resources 6902 // are kept in different files. (except for app in either system or 6903 // vendor path). 6904 // TODO grab this value from PackageSettings 6905 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6906 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6907 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 6908 } 6909 } 6910 6911 // TODO: extend to support forward-locked splits 6912 String resourcePath = null; 6913 String baseResourcePath = null; 6914 if ((parseFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 6915 if (ps != null && ps.resourcePathString != null) { 6916 resourcePath = ps.resourcePathString; 6917 baseResourcePath = ps.resourcePathString; 6918 } else { 6919 // Should not happen at all. Just log an error. 6920 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 6921 } 6922 } else { 6923 resourcePath = pkg.codePath; 6924 baseResourcePath = pkg.baseCodePath; 6925 } 6926 6927 // Set application objects path explicitly. 6928 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 6929 pkg.setApplicationInfoCodePath(pkg.codePath); 6930 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 6931 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 6932 pkg.setApplicationInfoResourcePath(resourcePath); 6933 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 6934 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 6935 6936 // Note that we invoke the following method only if we are about to unpack an application 6937 PackageParser.Package scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags 6938 | SCAN_UPDATE_SIGNATURE, currentTime, user); 6939 6940 /* 6941 * If the system app should be overridden by a previously installed 6942 * data, hide the system app now and let the /data/app scan pick it up 6943 * again. 6944 */ 6945 if (shouldHideSystemApp) { 6946 synchronized (mPackages) { 6947 mSettings.disableSystemPackageLPw(pkg.packageName, true); 6948 } 6949 } 6950 6951 return scannedPkg; 6952 } 6953 6954 private static String fixProcessName(String defProcessName, 6955 String processName, int uid) { 6956 if (processName == null) { 6957 return defProcessName; 6958 } 6959 return processName; 6960 } 6961 6962 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 6963 throws PackageManagerException { 6964 if (pkgSetting.signatures.mSignatures != null) { 6965 // Already existing package. Make sure signatures match 6966 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 6967 == PackageManager.SIGNATURE_MATCH; 6968 if (!match) { 6969 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 6970 == PackageManager.SIGNATURE_MATCH; 6971 } 6972 if (!match) { 6973 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 6974 == PackageManager.SIGNATURE_MATCH; 6975 } 6976 if (!match) { 6977 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 6978 + pkg.packageName + " signatures do not match the " 6979 + "previously installed version; ignoring!"); 6980 } 6981 } 6982 6983 // Check for shared user signatures 6984 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 6985 // Already existing package. Make sure signatures match 6986 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 6987 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 6988 if (!match) { 6989 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 6990 == PackageManager.SIGNATURE_MATCH; 6991 } 6992 if (!match) { 6993 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 6994 == PackageManager.SIGNATURE_MATCH; 6995 } 6996 if (!match) { 6997 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 6998 "Package " + pkg.packageName 6999 + " has no signatures that match those in shared user " 7000 + pkgSetting.sharedUser.name + "; ignoring!"); 7001 } 7002 } 7003 } 7004 7005 /** 7006 * Enforces that only the system UID or root's UID can call a method exposed 7007 * via Binder. 7008 * 7009 * @param message used as message if SecurityException is thrown 7010 * @throws SecurityException if the caller is not system or root 7011 */ 7012 private static final void enforceSystemOrRoot(String message) { 7013 final int uid = Binder.getCallingUid(); 7014 if (uid != Process.SYSTEM_UID && uid != 0) { 7015 throw new SecurityException(message); 7016 } 7017 } 7018 7019 @Override 7020 public void performFstrimIfNeeded() { 7021 enforceSystemOrRoot("Only the system can request fstrim"); 7022 7023 // Before everything else, see whether we need to fstrim. 7024 try { 7025 IMountService ms = PackageHelper.getMountService(); 7026 if (ms != null) { 7027 final boolean isUpgrade = isUpgrade(); 7028 boolean doTrim = isUpgrade; 7029 if (doTrim) { 7030 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7031 } else { 7032 final long interval = android.provider.Settings.Global.getLong( 7033 mContext.getContentResolver(), 7034 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7035 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7036 if (interval > 0) { 7037 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7038 if (timeSinceLast > interval) { 7039 doTrim = true; 7040 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7041 + "; running immediately"); 7042 } 7043 } 7044 } 7045 if (doTrim) { 7046 if (!isFirstBoot()) { 7047 try { 7048 ActivityManagerNative.getDefault().showBootMessage( 7049 mContext.getResources().getString( 7050 R.string.android_upgrading_fstrim), true); 7051 } catch (RemoteException e) { 7052 } 7053 } 7054 ms.runMaintenance(); 7055 } 7056 } else { 7057 Slog.e(TAG, "Mount service unavailable!"); 7058 } 7059 } catch (RemoteException e) { 7060 // Can't happen; MountService is local 7061 } 7062 } 7063 7064 @Override 7065 public void updatePackagesIfNeeded() { 7066 enforceSystemOrRoot("Only the system can request package update"); 7067 7068 // We need to re-extract after an OTA. 7069 boolean causeUpgrade = isUpgrade(); 7070 7071 // First boot or factory reset. 7072 // Note: we also handle devices that are upgrading to N right now as if it is their 7073 // first boot, as they do not have profile data. 7074 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7075 7076 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7077 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7078 7079 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7080 return; 7081 } 7082 7083 List<PackageParser.Package> pkgs; 7084 synchronized (mPackages) { 7085 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7086 } 7087 7088 int curr = 0; 7089 int total = pkgs.size(); 7090 for (PackageParser.Package pkg : pkgs) { 7091 curr++; 7092 7093 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7094 if (DEBUG_DEXOPT) { 7095 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7096 } 7097 continue; 7098 } 7099 7100 if (DEBUG_DEXOPT) { 7101 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7102 } 7103 7104 if (!isFirstBoot()) { 7105 try { 7106 ActivityManagerNative.getDefault().showBootMessage( 7107 mContext.getResources().getString(R.string.android_upgrading_apk, 7108 curr, total), true); 7109 } catch (RemoteException e) { 7110 } 7111 } 7112 7113 performDexOpt(pkg.packageName, 7114 null /* instructionSet */, 7115 false /* checkProfiles */, 7116 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7117 false /* force */); 7118 } 7119 } 7120 7121 @Override 7122 public void notifyPackageUse(String packageName) { 7123 synchronized (mPackages) { 7124 PackageParser.Package p = mPackages.get(packageName); 7125 if (p == null) { 7126 return; 7127 } 7128 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7129 } 7130 } 7131 7132 // TODO: this is not used nor needed. Delete it. 7133 @Override 7134 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7135 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7136 getFullCompilerFilter(), false /* force */); 7137 } 7138 7139 @Override 7140 public boolean performDexOpt(String packageName, String instructionSet, 7141 boolean checkProfiles, int compileReason, boolean force) { 7142 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7143 getCompilerFilterForReason(compileReason), force); 7144 } 7145 7146 @Override 7147 public boolean performDexOptMode(String packageName, String instructionSet, 7148 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7149 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7150 targetCompilerFilter, force); 7151 } 7152 7153 private boolean performDexOptTraced(String packageName, String instructionSet, 7154 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7155 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7156 try { 7157 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7158 targetCompilerFilter, force); 7159 } finally { 7160 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7161 } 7162 } 7163 7164 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7165 // if the package can now be considered up to date for the given filter. 7166 private boolean performDexOptInternal(String packageName, String instructionSet, 7167 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7168 PackageParser.Package p; 7169 final String targetInstructionSet; 7170 synchronized (mPackages) { 7171 p = mPackages.get(packageName); 7172 if (p == null) { 7173 return false; 7174 } 7175 mPackageUsage.write(false); 7176 7177 targetInstructionSet = instructionSet != null ? instructionSet : 7178 getPrimaryInstructionSet(p.applicationInfo); 7179 } 7180 long callingId = Binder.clearCallingIdentity(); 7181 try { 7182 synchronized (mInstallLock) { 7183 final String[] instructionSets = new String[] { targetInstructionSet }; 7184 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7185 checkProfiles, targetCompilerFilter, force); 7186 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7187 } 7188 } finally { 7189 Binder.restoreCallingIdentity(callingId); 7190 } 7191 } 7192 7193 public ArraySet<String> getOptimizablePackages() { 7194 ArraySet<String> pkgs = new ArraySet<String>(); 7195 synchronized (mPackages) { 7196 for (PackageParser.Package p : mPackages.values()) { 7197 if (PackageDexOptimizer.canOptimizePackage(p)) { 7198 pkgs.add(p.packageName); 7199 } 7200 } 7201 } 7202 return pkgs; 7203 } 7204 7205 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7206 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7207 boolean force) { 7208 // Select the dex optimizer based on the force parameter. 7209 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7210 // allocate an object here. 7211 PackageDexOptimizer pdo = force 7212 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7213 : mPackageDexOptimizer; 7214 7215 // Optimize all dependencies first. Note: we ignore the return value and march on 7216 // on errors. 7217 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7218 if (!deps.isEmpty()) { 7219 for (PackageParser.Package depPackage : deps) { 7220 // TODO: Analyze and investigate if we (should) profile libraries. 7221 // Currently this will do a full compilation of the library by default. 7222 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7223 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7224 } 7225 } 7226 7227 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7228 } 7229 7230 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7231 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7232 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7233 Set<String> collectedNames = new HashSet<>(); 7234 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7235 7236 retValue.remove(p); 7237 7238 return retValue; 7239 } else { 7240 return Collections.emptyList(); 7241 } 7242 } 7243 7244 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7245 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7246 if (!collectedNames.contains(p.packageName)) { 7247 collectedNames.add(p.packageName); 7248 collected.add(p); 7249 7250 if (p.usesLibraries != null) { 7251 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7252 } 7253 if (p.usesOptionalLibraries != null) { 7254 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7255 collectedNames); 7256 } 7257 } 7258 } 7259 7260 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7261 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7262 for (String libName : libs) { 7263 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7264 if (libPkg != null) { 7265 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7266 } 7267 } 7268 } 7269 7270 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7271 synchronized (mPackages) { 7272 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7273 if (lib != null && lib.apk != null) { 7274 return mPackages.get(lib.apk); 7275 } 7276 } 7277 return null; 7278 } 7279 7280 public void shutdown() { 7281 mPackageUsage.write(true); 7282 } 7283 7284 @Override 7285 public void forceDexOpt(String packageName) { 7286 enforceSystemOrRoot("forceDexOpt"); 7287 7288 PackageParser.Package pkg; 7289 synchronized (mPackages) { 7290 pkg = mPackages.get(packageName); 7291 if (pkg == null) { 7292 throw new IllegalArgumentException("Unknown package: " + packageName); 7293 } 7294 } 7295 7296 synchronized (mInstallLock) { 7297 final String[] instructionSets = new String[] { 7298 getPrimaryInstructionSet(pkg.applicationInfo) }; 7299 7300 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7301 7302 // Whoever is calling forceDexOpt wants a fully compiled package. 7303 // Don't use profiles since that may cause compilation to be skipped. 7304 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7305 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7306 true /* force */); 7307 7308 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7309 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7310 throw new IllegalStateException("Failed to dexopt: " + res); 7311 } 7312 } 7313 } 7314 7315 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7316 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7317 Slog.w(TAG, "Unable to update from " + oldPkg.name 7318 + " to " + newPkg.packageName 7319 + ": old package not in system partition"); 7320 return false; 7321 } else if (mPackages.get(oldPkg.name) != null) { 7322 Slog.w(TAG, "Unable to update from " + oldPkg.name 7323 + " to " + newPkg.packageName 7324 + ": old package still exists"); 7325 return false; 7326 } 7327 return true; 7328 } 7329 7330 void removeCodePathLI(File codePath) { 7331 if (codePath.isDirectory()) { 7332 try { 7333 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7334 } catch (InstallerException e) { 7335 Slog.w(TAG, "Failed to remove code path", e); 7336 } 7337 } else { 7338 codePath.delete(); 7339 } 7340 } 7341 7342 private int[] resolveUserIds(int userId) { 7343 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7344 } 7345 7346 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7347 if (pkg == null) { 7348 Slog.wtf(TAG, "Package was null!", new Throwable()); 7349 return; 7350 } 7351 clearAppDataLeafLIF(pkg, userId, flags); 7352 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7353 for (int i = 0; i < childCount; i++) { 7354 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7355 } 7356 } 7357 7358 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7359 final PackageSetting ps; 7360 synchronized (mPackages) { 7361 ps = mSettings.mPackages.get(pkg.packageName); 7362 } 7363 for (int realUserId : resolveUserIds(userId)) { 7364 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7365 try { 7366 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7367 ceDataInode); 7368 } catch (InstallerException e) { 7369 Slog.w(TAG, String.valueOf(e)); 7370 } 7371 } 7372 } 7373 7374 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7375 if (pkg == null) { 7376 Slog.wtf(TAG, "Package was null!", new Throwable()); 7377 return; 7378 } 7379 destroyAppDataLeafLIF(pkg, userId, flags); 7380 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7381 for (int i = 0; i < childCount; i++) { 7382 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7383 } 7384 } 7385 7386 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7387 final PackageSetting ps; 7388 synchronized (mPackages) { 7389 ps = mSettings.mPackages.get(pkg.packageName); 7390 } 7391 for (int realUserId : resolveUserIds(userId)) { 7392 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7393 try { 7394 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7395 ceDataInode); 7396 } catch (InstallerException e) { 7397 Slog.w(TAG, String.valueOf(e)); 7398 } 7399 } 7400 } 7401 7402 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7403 if (pkg == null) { 7404 Slog.wtf(TAG, "Package was null!", new Throwable()); 7405 return; 7406 } 7407 destroyAppProfilesLeafLIF(pkg); 7408 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7409 for (int i = 0; i < childCount; i++) { 7410 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7411 } 7412 } 7413 7414 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7415 try { 7416 mInstaller.destroyAppProfiles(pkg.packageName); 7417 } catch (InstallerException e) { 7418 Slog.w(TAG, String.valueOf(e)); 7419 } 7420 } 7421 7422 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7423 if (pkg == null) { 7424 Slog.wtf(TAG, "Package was null!", new Throwable()); 7425 return; 7426 } 7427 clearAppProfilesLeafLIF(pkg); 7428 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7429 for (int i = 0; i < childCount; i++) { 7430 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7431 } 7432 } 7433 7434 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7435 try { 7436 mInstaller.clearAppProfiles(pkg.packageName); 7437 } catch (InstallerException e) { 7438 Slog.w(TAG, String.valueOf(e)); 7439 } 7440 } 7441 7442 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7443 long lastUpdateTime) { 7444 // Set parent install/update time 7445 PackageSetting ps = (PackageSetting) pkg.mExtras; 7446 if (ps != null) { 7447 ps.firstInstallTime = firstInstallTime; 7448 ps.lastUpdateTime = lastUpdateTime; 7449 } 7450 // Set children install/update time 7451 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7452 for (int i = 0; i < childCount; i++) { 7453 PackageParser.Package childPkg = pkg.childPackages.get(i); 7454 ps = (PackageSetting) childPkg.mExtras; 7455 if (ps != null) { 7456 ps.firstInstallTime = firstInstallTime; 7457 ps.lastUpdateTime = lastUpdateTime; 7458 } 7459 } 7460 } 7461 7462 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7463 PackageParser.Package changingLib) { 7464 if (file.path != null) { 7465 usesLibraryFiles.add(file.path); 7466 return; 7467 } 7468 PackageParser.Package p = mPackages.get(file.apk); 7469 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7470 // If we are doing this while in the middle of updating a library apk, 7471 // then we need to make sure to use that new apk for determining the 7472 // dependencies here. (We haven't yet finished committing the new apk 7473 // to the package manager state.) 7474 if (p == null || p.packageName.equals(changingLib.packageName)) { 7475 p = changingLib; 7476 } 7477 } 7478 if (p != null) { 7479 usesLibraryFiles.addAll(p.getAllCodePaths()); 7480 } 7481 } 7482 7483 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7484 PackageParser.Package changingLib) throws PackageManagerException { 7485 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7486 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7487 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7488 for (int i=0; i<N; i++) { 7489 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7490 if (file == null) { 7491 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7492 "Package " + pkg.packageName + " requires unavailable shared library " 7493 + pkg.usesLibraries.get(i) + "; failing!"); 7494 } 7495 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7496 } 7497 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7498 for (int i=0; i<N; i++) { 7499 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7500 if (file == null) { 7501 Slog.w(TAG, "Package " + pkg.packageName 7502 + " desires unavailable shared library " 7503 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7504 } else { 7505 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7506 } 7507 } 7508 N = usesLibraryFiles.size(); 7509 if (N > 0) { 7510 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7511 } else { 7512 pkg.usesLibraryFiles = null; 7513 } 7514 } 7515 } 7516 7517 private static boolean hasString(List<String> list, List<String> which) { 7518 if (list == null) { 7519 return false; 7520 } 7521 for (int i=list.size()-1; i>=0; i--) { 7522 for (int j=which.size()-1; j>=0; j--) { 7523 if (which.get(j).equals(list.get(i))) { 7524 return true; 7525 } 7526 } 7527 } 7528 return false; 7529 } 7530 7531 private void updateAllSharedLibrariesLPw() { 7532 for (PackageParser.Package pkg : mPackages.values()) { 7533 try { 7534 updateSharedLibrariesLPw(pkg, null); 7535 } catch (PackageManagerException e) { 7536 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7537 } 7538 } 7539 } 7540 7541 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7542 PackageParser.Package changingPkg) { 7543 ArrayList<PackageParser.Package> res = null; 7544 for (PackageParser.Package pkg : mPackages.values()) { 7545 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7546 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7547 if (res == null) { 7548 res = new ArrayList<PackageParser.Package>(); 7549 } 7550 res.add(pkg); 7551 try { 7552 updateSharedLibrariesLPw(pkg, changingPkg); 7553 } catch (PackageManagerException e) { 7554 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7555 } 7556 } 7557 } 7558 return res; 7559 } 7560 7561 /** 7562 * Derive the value of the {@code cpuAbiOverride} based on the provided 7563 * value and an optional stored value from the package settings. 7564 */ 7565 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7566 String cpuAbiOverride = null; 7567 7568 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7569 cpuAbiOverride = null; 7570 } else if (abiOverride != null) { 7571 cpuAbiOverride = abiOverride; 7572 } else if (settings != null) { 7573 cpuAbiOverride = settings.cpuAbiOverrideString; 7574 } 7575 7576 return cpuAbiOverride; 7577 } 7578 7579 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7580 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7581 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7582 // If the package has children and this is the first dive in the function 7583 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7584 // whether all packages (parent and children) would be successfully scanned 7585 // before the actual scan since scanning mutates internal state and we want 7586 // to atomically install the package and its children. 7587 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7588 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7589 scanFlags |= SCAN_CHECK_ONLY; 7590 } 7591 } else { 7592 scanFlags &= ~SCAN_CHECK_ONLY; 7593 } 7594 7595 final PackageParser.Package scannedPkg; 7596 try { 7597 // Scan the parent 7598 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7599 // Scan the children 7600 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7601 for (int i = 0; i < childCount; i++) { 7602 PackageParser.Package childPkg = pkg.childPackages.get(i); 7603 scanPackageLI(childPkg, parseFlags, 7604 scanFlags, currentTime, user); 7605 } 7606 } finally { 7607 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7608 } 7609 7610 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7611 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7612 } 7613 7614 return scannedPkg; 7615 } 7616 7617 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7618 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7619 boolean success = false; 7620 try { 7621 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7622 currentTime, user); 7623 success = true; 7624 return res; 7625 } finally { 7626 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7627 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7628 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7629 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7630 destroyAppProfilesLIF(pkg); 7631 } 7632 } 7633 } 7634 7635 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7636 int scanFlags, long currentTime, UserHandle user) 7637 throws PackageManagerException { 7638 final File scanFile = new File(pkg.codePath); 7639 if (pkg.applicationInfo.getCodePath() == null || 7640 pkg.applicationInfo.getResourcePath() == null) { 7641 // Bail out. The resource and code paths haven't been set. 7642 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7643 "Code and resource paths haven't been set correctly"); 7644 } 7645 7646 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7647 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7648 } else { 7649 // Only allow system apps to be flagged as core apps. 7650 pkg.coreApp = false; 7651 } 7652 7653 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7654 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7655 } 7656 7657 if (mCustomResolverComponentName != null && 7658 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7659 setUpCustomResolverActivity(pkg); 7660 } 7661 7662 if (pkg.packageName.equals("android")) { 7663 synchronized (mPackages) { 7664 if (mAndroidApplication != null) { 7665 Slog.w(TAG, "*************************************************"); 7666 Slog.w(TAG, "Core android package being redefined. Skipping."); 7667 Slog.w(TAG, " file=" + scanFile); 7668 Slog.w(TAG, "*************************************************"); 7669 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7670 "Core android package being redefined. Skipping."); 7671 } 7672 7673 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7674 // Set up information for our fall-back user intent resolution activity. 7675 mPlatformPackage = pkg; 7676 pkg.mVersionCode = mSdkVersion; 7677 mAndroidApplication = pkg.applicationInfo; 7678 7679 if (!mResolverReplaced) { 7680 mResolveActivity.applicationInfo = mAndroidApplication; 7681 mResolveActivity.name = ResolverActivity.class.getName(); 7682 mResolveActivity.packageName = mAndroidApplication.packageName; 7683 mResolveActivity.processName = "system:ui"; 7684 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7685 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7686 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7687 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7688 mResolveActivity.exported = true; 7689 mResolveActivity.enabled = true; 7690 mResolveInfo.activityInfo = mResolveActivity; 7691 mResolveInfo.priority = 0; 7692 mResolveInfo.preferredOrder = 0; 7693 mResolveInfo.match = 0; 7694 mResolveComponentName = new ComponentName( 7695 mAndroidApplication.packageName, mResolveActivity.name); 7696 } 7697 } 7698 } 7699 } 7700 7701 if (DEBUG_PACKAGE_SCANNING) { 7702 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7703 Log.d(TAG, "Scanning package " + pkg.packageName); 7704 } 7705 7706 synchronized (mPackages) { 7707 if (mPackages.containsKey(pkg.packageName) 7708 || mSharedLibraries.containsKey(pkg.packageName)) { 7709 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7710 "Application package " + pkg.packageName 7711 + " already installed. Skipping duplicate."); 7712 } 7713 7714 // If we're only installing presumed-existing packages, require that the 7715 // scanned APK is both already known and at the path previously established 7716 // for it. Previously unknown packages we pick up normally, but if we have an 7717 // a priori expectation about this package's install presence, enforce it. 7718 // With a singular exception for new system packages. When an OTA contains 7719 // a new system package, we allow the codepath to change from a system location 7720 // to the user-installed location. If we don't allow this change, any newer, 7721 // user-installed version of the application will be ignored. 7722 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7723 if (mExpectingBetter.containsKey(pkg.packageName)) { 7724 logCriticalInfo(Log.WARN, 7725 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7726 } else { 7727 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7728 if (known != null) { 7729 if (DEBUG_PACKAGE_SCANNING) { 7730 Log.d(TAG, "Examining " + pkg.codePath 7731 + " and requiring known paths " + known.codePathString 7732 + " & " + known.resourcePathString); 7733 } 7734 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7735 || !pkg.applicationInfo.getResourcePath().equals( 7736 known.resourcePathString)) { 7737 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7738 "Application package " + pkg.packageName 7739 + " found at " + pkg.applicationInfo.getCodePath() 7740 + " but expected at " + known.codePathString 7741 + "; ignoring."); 7742 } 7743 } 7744 } 7745 } 7746 } 7747 7748 // Initialize package source and resource directories 7749 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7750 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7751 7752 SharedUserSetting suid = null; 7753 PackageSetting pkgSetting = null; 7754 7755 if (!isSystemApp(pkg)) { 7756 // Only system apps can use these features. 7757 pkg.mOriginalPackages = null; 7758 pkg.mRealPackage = null; 7759 pkg.mAdoptPermissions = null; 7760 } 7761 7762 // Getting the package setting may have a side-effect, so if we 7763 // are only checking if scan would succeed, stash a copy of the 7764 // old setting to restore at the end. 7765 PackageSetting nonMutatedPs = null; 7766 7767 // writer 7768 synchronized (mPackages) { 7769 if (pkg.mSharedUserId != null) { 7770 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7771 if (suid == null) { 7772 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7773 "Creating application package " + pkg.packageName 7774 + " for shared user failed"); 7775 } 7776 if (DEBUG_PACKAGE_SCANNING) { 7777 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7778 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7779 + "): packages=" + suid.packages); 7780 } 7781 } 7782 7783 // Check if we are renaming from an original package name. 7784 PackageSetting origPackage = null; 7785 String realName = null; 7786 if (pkg.mOriginalPackages != null) { 7787 // This package may need to be renamed to a previously 7788 // installed name. Let's check on that... 7789 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7790 if (pkg.mOriginalPackages.contains(renamed)) { 7791 // This package had originally been installed as the 7792 // original name, and we have already taken care of 7793 // transitioning to the new one. Just update the new 7794 // one to continue using the old name. 7795 realName = pkg.mRealPackage; 7796 if (!pkg.packageName.equals(renamed)) { 7797 // Callers into this function may have already taken 7798 // care of renaming the package; only do it here if 7799 // it is not already done. 7800 pkg.setPackageName(renamed); 7801 } 7802 7803 } else { 7804 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7805 if ((origPackage = mSettings.peekPackageLPr( 7806 pkg.mOriginalPackages.get(i))) != null) { 7807 // We do have the package already installed under its 7808 // original name... should we use it? 7809 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7810 // New package is not compatible with original. 7811 origPackage = null; 7812 continue; 7813 } else if (origPackage.sharedUser != null) { 7814 // Make sure uid is compatible between packages. 7815 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7816 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7817 + " to " + pkg.packageName + ": old uid " 7818 + origPackage.sharedUser.name 7819 + " differs from " + pkg.mSharedUserId); 7820 origPackage = null; 7821 continue; 7822 } 7823 } else { 7824 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7825 + pkg.packageName + " to old name " + origPackage.name); 7826 } 7827 break; 7828 } 7829 } 7830 } 7831 } 7832 7833 if (mTransferedPackages.contains(pkg.packageName)) { 7834 Slog.w(TAG, "Package " + pkg.packageName 7835 + " was transferred to another, but its .apk remains"); 7836 } 7837 7838 // See comments in nonMutatedPs declaration 7839 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7840 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7841 if (foundPs != null) { 7842 nonMutatedPs = new PackageSetting(foundPs); 7843 } 7844 } 7845 7846 // Just create the setting, don't add it yet. For already existing packages 7847 // the PkgSetting exists already and doesn't have to be created. 7848 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7849 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7850 pkg.applicationInfo.primaryCpuAbi, 7851 pkg.applicationInfo.secondaryCpuAbi, 7852 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7853 user, false); 7854 if (pkgSetting == null) { 7855 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7856 "Creating application package " + pkg.packageName + " failed"); 7857 } 7858 7859 if (pkgSetting.origPackage != null) { 7860 // If we are first transitioning from an original package, 7861 // fix up the new package's name now. We need to do this after 7862 // looking up the package under its new name, so getPackageLP 7863 // can take care of fiddling things correctly. 7864 pkg.setPackageName(origPackage.name); 7865 7866 // File a report about this. 7867 String msg = "New package " + pkgSetting.realName 7868 + " renamed to replace old package " + pkgSetting.name; 7869 reportSettingsProblem(Log.WARN, msg); 7870 7871 // Make a note of it. 7872 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7873 mTransferedPackages.add(origPackage.name); 7874 } 7875 7876 // No longer need to retain this. 7877 pkgSetting.origPackage = null; 7878 } 7879 7880 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7881 // Make a note of it. 7882 mTransferedPackages.add(pkg.packageName); 7883 } 7884 7885 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7886 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7887 } 7888 7889 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7890 // Check all shared libraries and map to their actual file path. 7891 // We only do this here for apps not on a system dir, because those 7892 // are the only ones that can fail an install due to this. We 7893 // will take care of the system apps by updating all of their 7894 // library paths after the scan is done. 7895 updateSharedLibrariesLPw(pkg, null); 7896 } 7897 7898 if (mFoundPolicyFile) { 7899 SELinuxMMAC.assignSeinfoValue(pkg); 7900 } 7901 7902 pkg.applicationInfo.uid = pkgSetting.appId; 7903 pkg.mExtras = pkgSetting; 7904 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7905 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7906 // We just determined the app is signed correctly, so bring 7907 // over the latest parsed certs. 7908 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7909 } else { 7910 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7911 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7912 "Package " + pkg.packageName + " upgrade keys do not match the " 7913 + "previously installed version"); 7914 } else { 7915 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7916 String msg = "System package " + pkg.packageName 7917 + " signature changed; retaining data."; 7918 reportSettingsProblem(Log.WARN, msg); 7919 } 7920 } 7921 } else { 7922 try { 7923 verifySignaturesLP(pkgSetting, pkg); 7924 // We just determined the app is signed correctly, so bring 7925 // over the latest parsed certs. 7926 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7927 } catch (PackageManagerException e) { 7928 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7929 throw e; 7930 } 7931 // The signature has changed, but this package is in the system 7932 // image... let's recover! 7933 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7934 // However... if this package is part of a shared user, but it 7935 // doesn't match the signature of the shared user, let's fail. 7936 // What this means is that you can't change the signatures 7937 // associated with an overall shared user, which doesn't seem all 7938 // that unreasonable. 7939 if (pkgSetting.sharedUser != null) { 7940 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7941 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7942 throw new PackageManagerException( 7943 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7944 "Signature mismatch for shared user: " 7945 + pkgSetting.sharedUser); 7946 } 7947 } 7948 // File a report about this. 7949 String msg = "System package " + pkg.packageName 7950 + " signature changed; retaining data."; 7951 reportSettingsProblem(Log.WARN, msg); 7952 } 7953 } 7954 // Verify that this new package doesn't have any content providers 7955 // that conflict with existing packages. Only do this if the 7956 // package isn't already installed, since we don't want to break 7957 // things that are installed. 7958 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7959 final int N = pkg.providers.size(); 7960 int i; 7961 for (i=0; i<N; i++) { 7962 PackageParser.Provider p = pkg.providers.get(i); 7963 if (p.info.authority != null) { 7964 String names[] = p.info.authority.split(";"); 7965 for (int j = 0; j < names.length; j++) { 7966 if (mProvidersByAuthority.containsKey(names[j])) { 7967 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7968 final String otherPackageName = 7969 ((other != null && other.getComponentName() != null) ? 7970 other.getComponentName().getPackageName() : "?"); 7971 throw new PackageManagerException( 7972 INSTALL_FAILED_CONFLICTING_PROVIDER, 7973 "Can't install because provider name " + names[j] 7974 + " (in package " + pkg.applicationInfo.packageName 7975 + ") is already used by " + otherPackageName); 7976 } 7977 } 7978 } 7979 } 7980 } 7981 7982 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7983 // This package wants to adopt ownership of permissions from 7984 // another package. 7985 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7986 final String origName = pkg.mAdoptPermissions.get(i); 7987 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7988 if (orig != null) { 7989 if (verifyPackageUpdateLPr(orig, pkg)) { 7990 Slog.i(TAG, "Adopting permissions from " + origName + " to " 7991 + pkg.packageName); 7992 mSettings.transferPermissionsLPw(origName, pkg.packageName); 7993 } 7994 } 7995 } 7996 } 7997 } 7998 7999 final String pkgName = pkg.packageName; 8000 8001 final long scanFileTime = scanFile.lastModified(); 8002 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8003 pkg.applicationInfo.processName = fixProcessName( 8004 pkg.applicationInfo.packageName, 8005 pkg.applicationInfo.processName, 8006 pkg.applicationInfo.uid); 8007 8008 if (pkg != mPlatformPackage) { 8009 // Get all of our default paths setup 8010 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8011 } 8012 8013 final String path = scanFile.getPath(); 8014 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8015 8016 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8017 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8018 8019 // Some system apps still use directory structure for native libraries 8020 // in which case we might end up not detecting abi solely based on apk 8021 // structure. Try to detect abi based on directory structure. 8022 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8023 pkg.applicationInfo.primaryCpuAbi == null) { 8024 setBundledAppAbisAndRoots(pkg, pkgSetting); 8025 setNativeLibraryPaths(pkg); 8026 } 8027 8028 } else { 8029 if ((scanFlags & SCAN_MOVE) != 0) { 8030 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8031 // but we already have this packages package info in the PackageSetting. We just 8032 // use that and derive the native library path based on the new codepath. 8033 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8034 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8035 } 8036 8037 // Set native library paths again. For moves, the path will be updated based on the 8038 // ABIs we've determined above. For non-moves, the path will be updated based on the 8039 // ABIs we determined during compilation, but the path will depend on the final 8040 // package path (after the rename away from the stage path). 8041 setNativeLibraryPaths(pkg); 8042 } 8043 8044 // This is a special case for the "system" package, where the ABI is 8045 // dictated by the zygote configuration (and init.rc). We should keep track 8046 // of this ABI so that we can deal with "normal" applications that run under 8047 // the same UID correctly. 8048 if (mPlatformPackage == pkg) { 8049 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8050 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8051 } 8052 8053 // If there's a mismatch between the abi-override in the package setting 8054 // and the abiOverride specified for the install. Warn about this because we 8055 // would've already compiled the app without taking the package setting into 8056 // account. 8057 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8058 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8059 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8060 " for package " + pkg.packageName); 8061 } 8062 } 8063 8064 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8065 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8066 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8067 8068 // Copy the derived override back to the parsed package, so that we can 8069 // update the package settings accordingly. 8070 pkg.cpuAbiOverride = cpuAbiOverride; 8071 8072 if (DEBUG_ABI_SELECTION) { 8073 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8074 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8075 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8076 } 8077 8078 // Push the derived path down into PackageSettings so we know what to 8079 // clean up at uninstall time. 8080 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8081 8082 if (DEBUG_ABI_SELECTION) { 8083 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8084 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8085 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8086 } 8087 8088 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8089 // We don't do this here during boot because we can do it all 8090 // at once after scanning all existing packages. 8091 // 8092 // We also do this *before* we perform dexopt on this package, so that 8093 // we can avoid redundant dexopts, and also to make sure we've got the 8094 // code and package path correct. 8095 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8096 pkg, true /* boot complete */); 8097 } 8098 8099 if (mFactoryTest && pkg.requestedPermissions.contains( 8100 android.Manifest.permission.FACTORY_TEST)) { 8101 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8102 } 8103 8104 ArrayList<PackageParser.Package> clientLibPkgs = null; 8105 8106 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8107 if (nonMutatedPs != null) { 8108 synchronized (mPackages) { 8109 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8110 } 8111 } 8112 return pkg; 8113 } 8114 8115 // Only privileged apps and updated privileged apps can add child packages. 8116 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8117 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8118 throw new PackageManagerException("Only privileged apps and updated " 8119 + "privileged apps can add child packages. Ignoring package " 8120 + pkg.packageName); 8121 } 8122 final int childCount = pkg.childPackages.size(); 8123 for (int i = 0; i < childCount; i++) { 8124 PackageParser.Package childPkg = pkg.childPackages.get(i); 8125 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8126 childPkg.packageName)) { 8127 throw new PackageManagerException("Cannot override a child package of " 8128 + "another disabled system app. Ignoring package " + pkg.packageName); 8129 } 8130 } 8131 } 8132 8133 // writer 8134 synchronized (mPackages) { 8135 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8136 // Only system apps can add new shared libraries. 8137 if (pkg.libraryNames != null) { 8138 for (int i=0; i<pkg.libraryNames.size(); i++) { 8139 String name = pkg.libraryNames.get(i); 8140 boolean allowed = false; 8141 if (pkg.isUpdatedSystemApp()) { 8142 // New library entries can only be added through the 8143 // system image. This is important to get rid of a lot 8144 // of nasty edge cases: for example if we allowed a non- 8145 // system update of the app to add a library, then uninstalling 8146 // the update would make the library go away, and assumptions 8147 // we made such as through app install filtering would now 8148 // have allowed apps on the device which aren't compatible 8149 // with it. Better to just have the restriction here, be 8150 // conservative, and create many fewer cases that can negatively 8151 // impact the user experience. 8152 final PackageSetting sysPs = mSettings 8153 .getDisabledSystemPkgLPr(pkg.packageName); 8154 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8155 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8156 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8157 allowed = true; 8158 break; 8159 } 8160 } 8161 } 8162 } else { 8163 allowed = true; 8164 } 8165 if (allowed) { 8166 if (!mSharedLibraries.containsKey(name)) { 8167 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8168 } else if (!name.equals(pkg.packageName)) { 8169 Slog.w(TAG, "Package " + pkg.packageName + " library " 8170 + name + " already exists; skipping"); 8171 } 8172 } else { 8173 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8174 + name + " that is not declared on system image; skipping"); 8175 } 8176 } 8177 if ((scanFlags & SCAN_BOOTING) == 0) { 8178 // If we are not booting, we need to update any applications 8179 // that are clients of our shared library. If we are booting, 8180 // this will all be done once the scan is complete. 8181 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8182 } 8183 } 8184 } 8185 } 8186 8187 if ((scanFlags & SCAN_BOOTING) != 0) { 8188 // No apps can run during boot scan, so they don't need to be frozen 8189 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8190 // Caller asked to not kill app, so it's probably not frozen 8191 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8192 // Caller asked us to ignore frozen check for some reason; they 8193 // probably didn't know the package name 8194 } else { 8195 // We're doing major surgery on this package, so it better be frozen 8196 // right now to keep it from launching 8197 checkPackageFrozen(pkgName); 8198 } 8199 8200 // Also need to kill any apps that are dependent on the library. 8201 if (clientLibPkgs != null) { 8202 for (int i=0; i<clientLibPkgs.size(); i++) { 8203 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8204 killApplication(clientPkg.applicationInfo.packageName, 8205 clientPkg.applicationInfo.uid, "update lib"); 8206 } 8207 } 8208 8209 // Make sure we're not adding any bogus keyset info 8210 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8211 ksms.assertScannedPackageValid(pkg); 8212 8213 // writer 8214 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8215 8216 boolean createIdmapFailed = false; 8217 synchronized (mPackages) { 8218 // We don't expect installation to fail beyond this point 8219 8220 // Add the new setting to mSettings 8221 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8222 // Add the new setting to mPackages 8223 mPackages.put(pkg.applicationInfo.packageName, pkg); 8224 // Make sure we don't accidentally delete its data. 8225 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8226 while (iter.hasNext()) { 8227 PackageCleanItem item = iter.next(); 8228 if (pkgName.equals(item.packageName)) { 8229 iter.remove(); 8230 } 8231 } 8232 8233 // Take care of first install / last update times. 8234 if (currentTime != 0) { 8235 if (pkgSetting.firstInstallTime == 0) { 8236 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8237 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8238 pkgSetting.lastUpdateTime = currentTime; 8239 } 8240 } else if (pkgSetting.firstInstallTime == 0) { 8241 // We need *something*. Take time time stamp of the file. 8242 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8243 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8244 if (scanFileTime != pkgSetting.timeStamp) { 8245 // A package on the system image has changed; consider this 8246 // to be an update. 8247 pkgSetting.lastUpdateTime = scanFileTime; 8248 } 8249 } 8250 8251 // Add the package's KeySets to the global KeySetManagerService 8252 ksms.addScannedPackageLPw(pkg); 8253 8254 int N = pkg.providers.size(); 8255 StringBuilder r = null; 8256 int i; 8257 for (i=0; i<N; i++) { 8258 PackageParser.Provider p = pkg.providers.get(i); 8259 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8260 p.info.processName, pkg.applicationInfo.uid); 8261 mProviders.addProvider(p); 8262 p.syncable = p.info.isSyncable; 8263 if (p.info.authority != null) { 8264 String names[] = p.info.authority.split(";"); 8265 p.info.authority = null; 8266 for (int j = 0; j < names.length; j++) { 8267 if (j == 1 && p.syncable) { 8268 // We only want the first authority for a provider to possibly be 8269 // syncable, so if we already added this provider using a different 8270 // authority clear the syncable flag. We copy the provider before 8271 // changing it because the mProviders object contains a reference 8272 // to a provider that we don't want to change. 8273 // Only do this for the second authority since the resulting provider 8274 // object can be the same for all future authorities for this provider. 8275 p = new PackageParser.Provider(p); 8276 p.syncable = false; 8277 } 8278 if (!mProvidersByAuthority.containsKey(names[j])) { 8279 mProvidersByAuthority.put(names[j], p); 8280 if (p.info.authority == null) { 8281 p.info.authority = names[j]; 8282 } else { 8283 p.info.authority = p.info.authority + ";" + names[j]; 8284 } 8285 if (DEBUG_PACKAGE_SCANNING) { 8286 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8287 Log.d(TAG, "Registered content provider: " + names[j] 8288 + ", className = " + p.info.name + ", isSyncable = " 8289 + p.info.isSyncable); 8290 } 8291 } else { 8292 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8293 Slog.w(TAG, "Skipping provider name " + names[j] + 8294 " (in package " + pkg.applicationInfo.packageName + 8295 "): name already used by " 8296 + ((other != null && other.getComponentName() != null) 8297 ? other.getComponentName().getPackageName() : "?")); 8298 } 8299 } 8300 } 8301 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8302 if (r == null) { 8303 r = new StringBuilder(256); 8304 } else { 8305 r.append(' '); 8306 } 8307 r.append(p.info.name); 8308 } 8309 } 8310 if (r != null) { 8311 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8312 } 8313 8314 N = pkg.services.size(); 8315 r = null; 8316 for (i=0; i<N; i++) { 8317 PackageParser.Service s = pkg.services.get(i); 8318 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8319 s.info.processName, pkg.applicationInfo.uid); 8320 mServices.addService(s); 8321 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8322 if (r == null) { 8323 r = new StringBuilder(256); 8324 } else { 8325 r.append(' '); 8326 } 8327 r.append(s.info.name); 8328 } 8329 } 8330 if (r != null) { 8331 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8332 } 8333 8334 N = pkg.receivers.size(); 8335 r = null; 8336 for (i=0; i<N; i++) { 8337 PackageParser.Activity a = pkg.receivers.get(i); 8338 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8339 a.info.processName, pkg.applicationInfo.uid); 8340 mReceivers.addActivity(a, "receiver"); 8341 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8342 if (r == null) { 8343 r = new StringBuilder(256); 8344 } else { 8345 r.append(' '); 8346 } 8347 r.append(a.info.name); 8348 } 8349 } 8350 if (r != null) { 8351 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8352 } 8353 8354 N = pkg.activities.size(); 8355 r = null; 8356 for (i=0; i<N; i++) { 8357 PackageParser.Activity a = pkg.activities.get(i); 8358 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8359 a.info.processName, pkg.applicationInfo.uid); 8360 mActivities.addActivity(a, "activity"); 8361 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8362 if (r == null) { 8363 r = new StringBuilder(256); 8364 } else { 8365 r.append(' '); 8366 } 8367 r.append(a.info.name); 8368 } 8369 } 8370 if (r != null) { 8371 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8372 } 8373 8374 N = pkg.permissionGroups.size(); 8375 r = null; 8376 for (i=0; i<N; i++) { 8377 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8378 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8379 if (cur == null) { 8380 mPermissionGroups.put(pg.info.name, pg); 8381 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8382 if (r == null) { 8383 r = new StringBuilder(256); 8384 } else { 8385 r.append(' '); 8386 } 8387 r.append(pg.info.name); 8388 } 8389 } else { 8390 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8391 + pg.info.packageName + " ignored: original from " 8392 + cur.info.packageName); 8393 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8394 if (r == null) { 8395 r = new StringBuilder(256); 8396 } else { 8397 r.append(' '); 8398 } 8399 r.append("DUP:"); 8400 r.append(pg.info.name); 8401 } 8402 } 8403 } 8404 if (r != null) { 8405 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8406 } 8407 8408 N = pkg.permissions.size(); 8409 r = null; 8410 for (i=0; i<N; i++) { 8411 PackageParser.Permission p = pkg.permissions.get(i); 8412 8413 // Assume by default that we did not install this permission into the system. 8414 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8415 8416 // Now that permission groups have a special meaning, we ignore permission 8417 // groups for legacy apps to prevent unexpected behavior. In particular, 8418 // permissions for one app being granted to someone just becase they happen 8419 // to be in a group defined by another app (before this had no implications). 8420 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8421 p.group = mPermissionGroups.get(p.info.group); 8422 // Warn for a permission in an unknown group. 8423 if (p.info.group != null && p.group == null) { 8424 Slog.w(TAG, "Permission " + p.info.name + " from package " 8425 + p.info.packageName + " in an unknown group " + p.info.group); 8426 } 8427 } 8428 8429 ArrayMap<String, BasePermission> permissionMap = 8430 p.tree ? mSettings.mPermissionTrees 8431 : mSettings.mPermissions; 8432 BasePermission bp = permissionMap.get(p.info.name); 8433 8434 // Allow system apps to redefine non-system permissions 8435 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8436 final boolean currentOwnerIsSystem = (bp.perm != null 8437 && isSystemApp(bp.perm.owner)); 8438 if (isSystemApp(p.owner)) { 8439 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8440 // It's a built-in permission and no owner, take ownership now 8441 bp.packageSetting = pkgSetting; 8442 bp.perm = p; 8443 bp.uid = pkg.applicationInfo.uid; 8444 bp.sourcePackage = p.info.packageName; 8445 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8446 } else if (!currentOwnerIsSystem) { 8447 String msg = "New decl " + p.owner + " of permission " 8448 + p.info.name + " is system; overriding " + bp.sourcePackage; 8449 reportSettingsProblem(Log.WARN, msg); 8450 bp = null; 8451 } 8452 } 8453 } 8454 8455 if (bp == null) { 8456 bp = new BasePermission(p.info.name, p.info.packageName, 8457 BasePermission.TYPE_NORMAL); 8458 permissionMap.put(p.info.name, bp); 8459 } 8460 8461 if (bp.perm == null) { 8462 if (bp.sourcePackage == null 8463 || bp.sourcePackage.equals(p.info.packageName)) { 8464 BasePermission tree = findPermissionTreeLP(p.info.name); 8465 if (tree == null 8466 || tree.sourcePackage.equals(p.info.packageName)) { 8467 bp.packageSetting = pkgSetting; 8468 bp.perm = p; 8469 bp.uid = pkg.applicationInfo.uid; 8470 bp.sourcePackage = p.info.packageName; 8471 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8472 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8473 if (r == null) { 8474 r = new StringBuilder(256); 8475 } else { 8476 r.append(' '); 8477 } 8478 r.append(p.info.name); 8479 } 8480 } else { 8481 Slog.w(TAG, "Permission " + p.info.name + " from package " 8482 + p.info.packageName + " ignored: base tree " 8483 + tree.name + " is from package " 8484 + tree.sourcePackage); 8485 } 8486 } else { 8487 Slog.w(TAG, "Permission " + p.info.name + " from package " 8488 + p.info.packageName + " ignored: original from " 8489 + bp.sourcePackage); 8490 } 8491 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8492 if (r == null) { 8493 r = new StringBuilder(256); 8494 } else { 8495 r.append(' '); 8496 } 8497 r.append("DUP:"); 8498 r.append(p.info.name); 8499 } 8500 if (bp.perm == p) { 8501 bp.protectionLevel = p.info.protectionLevel; 8502 } 8503 } 8504 8505 if (r != null) { 8506 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8507 } 8508 8509 N = pkg.instrumentation.size(); 8510 r = null; 8511 for (i=0; i<N; i++) { 8512 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8513 a.info.packageName = pkg.applicationInfo.packageName; 8514 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8515 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8516 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8517 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8518 a.info.dataDir = pkg.applicationInfo.dataDir; 8519 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8520 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8521 8522 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8523 // need other information about the application, like the ABI and what not ? 8524 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8525 mInstrumentation.put(a.getComponentName(), a); 8526 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8527 if (r == null) { 8528 r = new StringBuilder(256); 8529 } else { 8530 r.append(' '); 8531 } 8532 r.append(a.info.name); 8533 } 8534 } 8535 if (r != null) { 8536 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8537 } 8538 8539 if (pkg.protectedBroadcasts != null) { 8540 N = pkg.protectedBroadcasts.size(); 8541 for (i=0; i<N; i++) { 8542 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8543 } 8544 } 8545 8546 pkgSetting.setTimeStamp(scanFileTime); 8547 8548 // Create idmap files for pairs of (packages, overlay packages). 8549 // Note: "android", ie framework-res.apk, is handled by native layers. 8550 if (pkg.mOverlayTarget != null) { 8551 // This is an overlay package. 8552 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8553 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8554 mOverlays.put(pkg.mOverlayTarget, 8555 new ArrayMap<String, PackageParser.Package>()); 8556 } 8557 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8558 map.put(pkg.packageName, pkg); 8559 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8560 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8561 createIdmapFailed = true; 8562 } 8563 } 8564 } else if (mOverlays.containsKey(pkg.packageName) && 8565 !pkg.packageName.equals("android")) { 8566 // This is a regular package, with one or more known overlay packages. 8567 createIdmapsForPackageLI(pkg); 8568 } 8569 } 8570 8571 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8572 8573 if (createIdmapFailed) { 8574 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8575 "scanPackageLI failed to createIdmap"); 8576 } 8577 return pkg; 8578 } 8579 8580 /** 8581 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8582 * is derived purely on the basis of the contents of {@code scanFile} and 8583 * {@code cpuAbiOverride}. 8584 * 8585 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8586 */ 8587 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8588 String cpuAbiOverride, boolean extractLibs) 8589 throws PackageManagerException { 8590 // TODO: We can probably be smarter about this stuff. For installed apps, 8591 // we can calculate this information at install time once and for all. For 8592 // system apps, we can probably assume that this information doesn't change 8593 // after the first boot scan. As things stand, we do lots of unnecessary work. 8594 8595 // Give ourselves some initial paths; we'll come back for another 8596 // pass once we've determined ABI below. 8597 setNativeLibraryPaths(pkg); 8598 8599 // We would never need to extract libs for forward-locked and external packages, 8600 // since the container service will do it for us. We shouldn't attempt to 8601 // extract libs from system app when it was not updated. 8602 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8603 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8604 extractLibs = false; 8605 } 8606 8607 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8608 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8609 8610 NativeLibraryHelper.Handle handle = null; 8611 try { 8612 handle = NativeLibraryHelper.Handle.create(pkg); 8613 // TODO(multiArch): This can be null for apps that didn't go through the 8614 // usual installation process. We can calculate it again, like we 8615 // do during install time. 8616 // 8617 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8618 // unnecessary. 8619 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8620 8621 // Null out the abis so that they can be recalculated. 8622 pkg.applicationInfo.primaryCpuAbi = null; 8623 pkg.applicationInfo.secondaryCpuAbi = null; 8624 if (isMultiArch(pkg.applicationInfo)) { 8625 // Warn if we've set an abiOverride for multi-lib packages.. 8626 // By definition, we need to copy both 32 and 64 bit libraries for 8627 // such packages. 8628 if (pkg.cpuAbiOverride != null 8629 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8630 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8631 } 8632 8633 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8634 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8635 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8636 if (extractLibs) { 8637 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8638 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8639 useIsaSpecificSubdirs); 8640 } else { 8641 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8642 } 8643 } 8644 8645 maybeThrowExceptionForMultiArchCopy( 8646 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8647 8648 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8649 if (extractLibs) { 8650 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8651 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8652 useIsaSpecificSubdirs); 8653 } else { 8654 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8655 } 8656 } 8657 8658 maybeThrowExceptionForMultiArchCopy( 8659 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8660 8661 if (abi64 >= 0) { 8662 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8663 } 8664 8665 if (abi32 >= 0) { 8666 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8667 if (abi64 >= 0) { 8668 if (pkg.use32bitAbi) { 8669 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8670 pkg.applicationInfo.primaryCpuAbi = abi; 8671 } else { 8672 pkg.applicationInfo.secondaryCpuAbi = abi; 8673 } 8674 } else { 8675 pkg.applicationInfo.primaryCpuAbi = abi; 8676 } 8677 } 8678 8679 } else { 8680 String[] abiList = (cpuAbiOverride != null) ? 8681 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8682 8683 // Enable gross and lame hacks for apps that are built with old 8684 // SDK tools. We must scan their APKs for renderscript bitcode and 8685 // not launch them if it's present. Don't bother checking on devices 8686 // that don't have 64 bit support. 8687 boolean needsRenderScriptOverride = false; 8688 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8689 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8690 abiList = Build.SUPPORTED_32_BIT_ABIS; 8691 needsRenderScriptOverride = true; 8692 } 8693 8694 final int copyRet; 8695 if (extractLibs) { 8696 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8697 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8698 } else { 8699 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8700 } 8701 8702 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8703 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8704 "Error unpackaging native libs for app, errorCode=" + copyRet); 8705 } 8706 8707 if (copyRet >= 0) { 8708 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8709 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8710 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8711 } else if (needsRenderScriptOverride) { 8712 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8713 } 8714 } 8715 } catch (IOException ioe) { 8716 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8717 } finally { 8718 IoUtils.closeQuietly(handle); 8719 } 8720 8721 // Now that we've calculated the ABIs and determined if it's an internal app, 8722 // we will go ahead and populate the nativeLibraryPath. 8723 setNativeLibraryPaths(pkg); 8724 } 8725 8726 /** 8727 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8728 * i.e, so that all packages can be run inside a single process if required. 8729 * 8730 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8731 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8732 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8733 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8734 * updating a package that belongs to a shared user. 8735 * 8736 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8737 * adds unnecessary complexity. 8738 */ 8739 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8740 PackageParser.Package scannedPackage, boolean bootComplete) { 8741 String requiredInstructionSet = null; 8742 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8743 requiredInstructionSet = VMRuntime.getInstructionSet( 8744 scannedPackage.applicationInfo.primaryCpuAbi); 8745 } 8746 8747 PackageSetting requirer = null; 8748 for (PackageSetting ps : packagesForUser) { 8749 // If packagesForUser contains scannedPackage, we skip it. This will happen 8750 // when scannedPackage is an update of an existing package. Without this check, 8751 // we will never be able to change the ABI of any package belonging to a shared 8752 // user, even if it's compatible with other packages. 8753 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8754 if (ps.primaryCpuAbiString == null) { 8755 continue; 8756 } 8757 8758 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8759 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8760 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8761 // this but there's not much we can do. 8762 String errorMessage = "Instruction set mismatch, " 8763 + ((requirer == null) ? "[caller]" : requirer) 8764 + " requires " + requiredInstructionSet + " whereas " + ps 8765 + " requires " + instructionSet; 8766 Slog.w(TAG, errorMessage); 8767 } 8768 8769 if (requiredInstructionSet == null) { 8770 requiredInstructionSet = instructionSet; 8771 requirer = ps; 8772 } 8773 } 8774 } 8775 8776 if (requiredInstructionSet != null) { 8777 String adjustedAbi; 8778 if (requirer != null) { 8779 // requirer != null implies that either scannedPackage was null or that scannedPackage 8780 // did not require an ABI, in which case we have to adjust scannedPackage to match 8781 // the ABI of the set (which is the same as requirer's ABI) 8782 adjustedAbi = requirer.primaryCpuAbiString; 8783 if (scannedPackage != null) { 8784 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8785 } 8786 } else { 8787 // requirer == null implies that we're updating all ABIs in the set to 8788 // match scannedPackage. 8789 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8790 } 8791 8792 for (PackageSetting ps : packagesForUser) { 8793 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8794 if (ps.primaryCpuAbiString != null) { 8795 continue; 8796 } 8797 8798 ps.primaryCpuAbiString = adjustedAbi; 8799 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8800 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8801 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8802 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8803 + " (requirer=" 8804 + (requirer == null ? "null" : requirer.pkg.packageName) 8805 + ", scannedPackage=" 8806 + (scannedPackage != null ? scannedPackage.packageName : "null") 8807 + ")"); 8808 try { 8809 mInstaller.rmdex(ps.codePathString, 8810 getDexCodeInstructionSet(getPreferredInstructionSet())); 8811 } catch (InstallerException ignored) { 8812 } 8813 } 8814 } 8815 } 8816 } 8817 } 8818 8819 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8820 synchronized (mPackages) { 8821 mResolverReplaced = true; 8822 // Set up information for custom user intent resolution activity. 8823 mResolveActivity.applicationInfo = pkg.applicationInfo; 8824 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8825 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8826 mResolveActivity.processName = pkg.applicationInfo.packageName; 8827 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8828 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8829 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8830 mResolveActivity.theme = 0; 8831 mResolveActivity.exported = true; 8832 mResolveActivity.enabled = true; 8833 mResolveInfo.activityInfo = mResolveActivity; 8834 mResolveInfo.priority = 0; 8835 mResolveInfo.preferredOrder = 0; 8836 mResolveInfo.match = 0; 8837 mResolveComponentName = mCustomResolverComponentName; 8838 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8839 mResolveComponentName); 8840 } 8841 } 8842 8843 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8844 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8845 8846 // Set up information for ephemeral installer activity 8847 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8848 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8849 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8850 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8851 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8852 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8853 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8854 mEphemeralInstallerActivity.theme = 0; 8855 mEphemeralInstallerActivity.exported = true; 8856 mEphemeralInstallerActivity.enabled = true; 8857 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8858 mEphemeralInstallerInfo.priority = 0; 8859 mEphemeralInstallerInfo.preferredOrder = 0; 8860 mEphemeralInstallerInfo.match = 0; 8861 8862 if (DEBUG_EPHEMERAL) { 8863 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8864 } 8865 } 8866 8867 private static String calculateBundledApkRoot(final String codePathString) { 8868 final File codePath = new File(codePathString); 8869 final File codeRoot; 8870 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8871 codeRoot = Environment.getRootDirectory(); 8872 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8873 codeRoot = Environment.getOemDirectory(); 8874 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8875 codeRoot = Environment.getVendorDirectory(); 8876 } else { 8877 // Unrecognized code path; take its top real segment as the apk root: 8878 // e.g. /something/app/blah.apk => /something 8879 try { 8880 File f = codePath.getCanonicalFile(); 8881 File parent = f.getParentFile(); // non-null because codePath is a file 8882 File tmp; 8883 while ((tmp = parent.getParentFile()) != null) { 8884 f = parent; 8885 parent = tmp; 8886 } 8887 codeRoot = f; 8888 Slog.w(TAG, "Unrecognized code path " 8889 + codePath + " - using " + codeRoot); 8890 } catch (IOException e) { 8891 // Can't canonicalize the code path -- shenanigans? 8892 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8893 return Environment.getRootDirectory().getPath(); 8894 } 8895 } 8896 return codeRoot.getPath(); 8897 } 8898 8899 /** 8900 * Derive and set the location of native libraries for the given package, 8901 * which varies depending on where and how the package was installed. 8902 */ 8903 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8904 final ApplicationInfo info = pkg.applicationInfo; 8905 final String codePath = pkg.codePath; 8906 final File codeFile = new File(codePath); 8907 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8908 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8909 8910 info.nativeLibraryRootDir = null; 8911 info.nativeLibraryRootRequiresIsa = false; 8912 info.nativeLibraryDir = null; 8913 info.secondaryNativeLibraryDir = null; 8914 8915 if (isApkFile(codeFile)) { 8916 // Monolithic install 8917 if (bundledApp) { 8918 // If "/system/lib64/apkname" exists, assume that is the per-package 8919 // native library directory to use; otherwise use "/system/lib/apkname". 8920 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8921 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8922 getPrimaryInstructionSet(info)); 8923 8924 // This is a bundled system app so choose the path based on the ABI. 8925 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8926 // is just the default path. 8927 final String apkName = deriveCodePathName(codePath); 8928 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8929 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8930 apkName).getAbsolutePath(); 8931 8932 if (info.secondaryCpuAbi != null) { 8933 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8934 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8935 secondaryLibDir, apkName).getAbsolutePath(); 8936 } 8937 } else if (asecApp) { 8938 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8939 .getAbsolutePath(); 8940 } else { 8941 final String apkName = deriveCodePathName(codePath); 8942 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8943 .getAbsolutePath(); 8944 } 8945 8946 info.nativeLibraryRootRequiresIsa = false; 8947 info.nativeLibraryDir = info.nativeLibraryRootDir; 8948 } else { 8949 // Cluster install 8950 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8951 info.nativeLibraryRootRequiresIsa = true; 8952 8953 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8954 getPrimaryInstructionSet(info)).getAbsolutePath(); 8955 8956 if (info.secondaryCpuAbi != null) { 8957 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8958 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8959 } 8960 } 8961 } 8962 8963 /** 8964 * Calculate the abis and roots for a bundled app. These can uniquely 8965 * be determined from the contents of the system partition, i.e whether 8966 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8967 * of this information, and instead assume that the system was built 8968 * sensibly. 8969 */ 8970 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8971 PackageSetting pkgSetting) { 8972 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8973 8974 // If "/system/lib64/apkname" exists, assume that is the per-package 8975 // native library directory to use; otherwise use "/system/lib/apkname". 8976 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8977 setBundledAppAbi(pkg, apkRoot, apkName); 8978 // pkgSetting might be null during rescan following uninstall of updates 8979 // to a bundled app, so accommodate that possibility. The settings in 8980 // that case will be established later from the parsed package. 8981 // 8982 // If the settings aren't null, sync them up with what we've just derived. 8983 // note that apkRoot isn't stored in the package settings. 8984 if (pkgSetting != null) { 8985 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8986 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8987 } 8988 } 8989 8990 /** 8991 * Deduces the ABI of a bundled app and sets the relevant fields on the 8992 * parsed pkg object. 8993 * 8994 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 8995 * under which system libraries are installed. 8996 * @param apkName the name of the installed package. 8997 */ 8998 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 8999 final File codeFile = new File(pkg.codePath); 9000 9001 final boolean has64BitLibs; 9002 final boolean has32BitLibs; 9003 if (isApkFile(codeFile)) { 9004 // Monolithic install 9005 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9006 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9007 } else { 9008 // Cluster install 9009 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9010 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9011 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9012 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9013 has64BitLibs = (new File(rootDir, isa)).exists(); 9014 } else { 9015 has64BitLibs = false; 9016 } 9017 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9018 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9019 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9020 has32BitLibs = (new File(rootDir, isa)).exists(); 9021 } else { 9022 has32BitLibs = false; 9023 } 9024 } 9025 9026 if (has64BitLibs && !has32BitLibs) { 9027 // The package has 64 bit libs, but not 32 bit libs. Its primary 9028 // ABI should be 64 bit. We can safely assume here that the bundled 9029 // native libraries correspond to the most preferred ABI in the list. 9030 9031 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9032 pkg.applicationInfo.secondaryCpuAbi = null; 9033 } else if (has32BitLibs && !has64BitLibs) { 9034 // The package has 32 bit libs but not 64 bit libs. Its primary 9035 // ABI should be 32 bit. 9036 9037 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9038 pkg.applicationInfo.secondaryCpuAbi = null; 9039 } else if (has32BitLibs && has64BitLibs) { 9040 // The application has both 64 and 32 bit bundled libraries. We check 9041 // here that the app declares multiArch support, and warn if it doesn't. 9042 // 9043 // We will be lenient here and record both ABIs. The primary will be the 9044 // ABI that's higher on the list, i.e, a device that's configured to prefer 9045 // 64 bit apps will see a 64 bit primary ABI, 9046 9047 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9048 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9049 } 9050 9051 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9052 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9053 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9054 } else { 9055 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9056 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9057 } 9058 } else { 9059 pkg.applicationInfo.primaryCpuAbi = null; 9060 pkg.applicationInfo.secondaryCpuAbi = null; 9061 } 9062 } 9063 9064 private void killApplication(String pkgName, int appId, String reason) { 9065 // Request the ActivityManager to kill the process(only for existing packages) 9066 // so that we do not end up in a confused state while the user is still using the older 9067 // version of the application while the new one gets installed. 9068 final long token = Binder.clearCallingIdentity(); 9069 try { 9070 IActivityManager am = ActivityManagerNative.getDefault(); 9071 if (am != null) { 9072 try { 9073 am.killApplicationWithAppId(pkgName, appId, reason); 9074 } catch (RemoteException e) { 9075 } 9076 } 9077 } finally { 9078 Binder.restoreCallingIdentity(token); 9079 } 9080 } 9081 9082 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9083 // Remove the parent package setting 9084 PackageSetting ps = (PackageSetting) pkg.mExtras; 9085 if (ps != null) { 9086 removePackageLI(ps, chatty); 9087 } 9088 // Remove the child package setting 9089 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9090 for (int i = 0; i < childCount; i++) { 9091 PackageParser.Package childPkg = pkg.childPackages.get(i); 9092 ps = (PackageSetting) childPkg.mExtras; 9093 if (ps != null) { 9094 removePackageLI(ps, chatty); 9095 } 9096 } 9097 } 9098 9099 void removePackageLI(PackageSetting ps, boolean chatty) { 9100 if (DEBUG_INSTALL) { 9101 if (chatty) 9102 Log.d(TAG, "Removing package " + ps.name); 9103 } 9104 9105 // writer 9106 synchronized (mPackages) { 9107 mPackages.remove(ps.name); 9108 final PackageParser.Package pkg = ps.pkg; 9109 if (pkg != null) { 9110 cleanPackageDataStructuresLILPw(pkg, chatty); 9111 } 9112 } 9113 } 9114 9115 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9116 if (DEBUG_INSTALL) { 9117 if (chatty) 9118 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9119 } 9120 9121 // writer 9122 synchronized (mPackages) { 9123 // Remove the parent package 9124 mPackages.remove(pkg.applicationInfo.packageName); 9125 cleanPackageDataStructuresLILPw(pkg, chatty); 9126 9127 // Remove the child packages 9128 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9129 for (int i = 0; i < childCount; i++) { 9130 PackageParser.Package childPkg = pkg.childPackages.get(i); 9131 mPackages.remove(childPkg.applicationInfo.packageName); 9132 cleanPackageDataStructuresLILPw(childPkg, chatty); 9133 } 9134 } 9135 } 9136 9137 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9138 int N = pkg.providers.size(); 9139 StringBuilder r = null; 9140 int i; 9141 for (i=0; i<N; i++) { 9142 PackageParser.Provider p = pkg.providers.get(i); 9143 mProviders.removeProvider(p); 9144 if (p.info.authority == null) { 9145 9146 /* There was another ContentProvider with this authority when 9147 * this app was installed so this authority is null, 9148 * Ignore it as we don't have to unregister the provider. 9149 */ 9150 continue; 9151 } 9152 String names[] = p.info.authority.split(";"); 9153 for (int j = 0; j < names.length; j++) { 9154 if (mProvidersByAuthority.get(names[j]) == p) { 9155 mProvidersByAuthority.remove(names[j]); 9156 if (DEBUG_REMOVE) { 9157 if (chatty) 9158 Log.d(TAG, "Unregistered content provider: " + names[j] 9159 + ", className = " + p.info.name + ", isSyncable = " 9160 + p.info.isSyncable); 9161 } 9162 } 9163 } 9164 if (DEBUG_REMOVE && chatty) { 9165 if (r == null) { 9166 r = new StringBuilder(256); 9167 } else { 9168 r.append(' '); 9169 } 9170 r.append(p.info.name); 9171 } 9172 } 9173 if (r != null) { 9174 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9175 } 9176 9177 N = pkg.services.size(); 9178 r = null; 9179 for (i=0; i<N; i++) { 9180 PackageParser.Service s = pkg.services.get(i); 9181 mServices.removeService(s); 9182 if (chatty) { 9183 if (r == null) { 9184 r = new StringBuilder(256); 9185 } else { 9186 r.append(' '); 9187 } 9188 r.append(s.info.name); 9189 } 9190 } 9191 if (r != null) { 9192 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9193 } 9194 9195 N = pkg.receivers.size(); 9196 r = null; 9197 for (i=0; i<N; i++) { 9198 PackageParser.Activity a = pkg.receivers.get(i); 9199 mReceivers.removeActivity(a, "receiver"); 9200 if (DEBUG_REMOVE && chatty) { 9201 if (r == null) { 9202 r = new StringBuilder(256); 9203 } else { 9204 r.append(' '); 9205 } 9206 r.append(a.info.name); 9207 } 9208 } 9209 if (r != null) { 9210 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9211 } 9212 9213 N = pkg.activities.size(); 9214 r = null; 9215 for (i=0; i<N; i++) { 9216 PackageParser.Activity a = pkg.activities.get(i); 9217 mActivities.removeActivity(a, "activity"); 9218 if (DEBUG_REMOVE && chatty) { 9219 if (r == null) { 9220 r = new StringBuilder(256); 9221 } else { 9222 r.append(' '); 9223 } 9224 r.append(a.info.name); 9225 } 9226 } 9227 if (r != null) { 9228 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9229 } 9230 9231 N = pkg.permissions.size(); 9232 r = null; 9233 for (i=0; i<N; i++) { 9234 PackageParser.Permission p = pkg.permissions.get(i); 9235 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9236 if (bp == null) { 9237 bp = mSettings.mPermissionTrees.get(p.info.name); 9238 } 9239 if (bp != null && bp.perm == p) { 9240 bp.perm = null; 9241 if (DEBUG_REMOVE && chatty) { 9242 if (r == null) { 9243 r = new StringBuilder(256); 9244 } else { 9245 r.append(' '); 9246 } 9247 r.append(p.info.name); 9248 } 9249 } 9250 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9251 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9252 if (appOpPkgs != null) { 9253 appOpPkgs.remove(pkg.packageName); 9254 } 9255 } 9256 } 9257 if (r != null) { 9258 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9259 } 9260 9261 N = pkg.requestedPermissions.size(); 9262 r = null; 9263 for (i=0; i<N; i++) { 9264 String perm = pkg.requestedPermissions.get(i); 9265 BasePermission bp = mSettings.mPermissions.get(perm); 9266 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9267 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9268 if (appOpPkgs != null) { 9269 appOpPkgs.remove(pkg.packageName); 9270 if (appOpPkgs.isEmpty()) { 9271 mAppOpPermissionPackages.remove(perm); 9272 } 9273 } 9274 } 9275 } 9276 if (r != null) { 9277 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9278 } 9279 9280 N = pkg.instrumentation.size(); 9281 r = null; 9282 for (i=0; i<N; i++) { 9283 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9284 mInstrumentation.remove(a.getComponentName()); 9285 if (DEBUG_REMOVE && chatty) { 9286 if (r == null) { 9287 r = new StringBuilder(256); 9288 } else { 9289 r.append(' '); 9290 } 9291 r.append(a.info.name); 9292 } 9293 } 9294 if (r != null) { 9295 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9296 } 9297 9298 r = null; 9299 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9300 // Only system apps can hold shared libraries. 9301 if (pkg.libraryNames != null) { 9302 for (i=0; i<pkg.libraryNames.size(); i++) { 9303 String name = pkg.libraryNames.get(i); 9304 SharedLibraryEntry cur = mSharedLibraries.get(name); 9305 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9306 mSharedLibraries.remove(name); 9307 if (DEBUG_REMOVE && chatty) { 9308 if (r == null) { 9309 r = new StringBuilder(256); 9310 } else { 9311 r.append(' '); 9312 } 9313 r.append(name); 9314 } 9315 } 9316 } 9317 } 9318 } 9319 if (r != null) { 9320 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9321 } 9322 } 9323 9324 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9325 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9326 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9327 return true; 9328 } 9329 } 9330 return false; 9331 } 9332 9333 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9334 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9335 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9336 9337 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9338 // Update the parent permissions 9339 updatePermissionsLPw(pkg.packageName, pkg, flags); 9340 // Update the child permissions 9341 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9342 for (int i = 0; i < childCount; i++) { 9343 PackageParser.Package childPkg = pkg.childPackages.get(i); 9344 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9345 } 9346 } 9347 9348 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9349 int flags) { 9350 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9351 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9352 } 9353 9354 private void updatePermissionsLPw(String changingPkg, 9355 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9356 // Make sure there are no dangling permission trees. 9357 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9358 while (it.hasNext()) { 9359 final BasePermission bp = it.next(); 9360 if (bp.packageSetting == null) { 9361 // We may not yet have parsed the package, so just see if 9362 // we still know about its settings. 9363 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9364 } 9365 if (bp.packageSetting == null) { 9366 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9367 + " from package " + bp.sourcePackage); 9368 it.remove(); 9369 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9370 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9371 Slog.i(TAG, "Removing old permission tree: " + bp.name 9372 + " from package " + bp.sourcePackage); 9373 flags |= UPDATE_PERMISSIONS_ALL; 9374 it.remove(); 9375 } 9376 } 9377 } 9378 9379 // Make sure all dynamic permissions have been assigned to a package, 9380 // and make sure there are no dangling permissions. 9381 it = mSettings.mPermissions.values().iterator(); 9382 while (it.hasNext()) { 9383 final BasePermission bp = it.next(); 9384 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9385 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9386 + bp.name + " pkg=" + bp.sourcePackage 9387 + " info=" + bp.pendingInfo); 9388 if (bp.packageSetting == null && bp.pendingInfo != null) { 9389 final BasePermission tree = findPermissionTreeLP(bp.name); 9390 if (tree != null && tree.perm != null) { 9391 bp.packageSetting = tree.packageSetting; 9392 bp.perm = new PackageParser.Permission(tree.perm.owner, 9393 new PermissionInfo(bp.pendingInfo)); 9394 bp.perm.info.packageName = tree.perm.info.packageName; 9395 bp.perm.info.name = bp.name; 9396 bp.uid = tree.uid; 9397 } 9398 } 9399 } 9400 if (bp.packageSetting == null) { 9401 // We may not yet have parsed the package, so just see if 9402 // we still know about its settings. 9403 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9404 } 9405 if (bp.packageSetting == null) { 9406 Slog.w(TAG, "Removing dangling permission: " + bp.name 9407 + " from package " + bp.sourcePackage); 9408 it.remove(); 9409 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9410 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9411 Slog.i(TAG, "Removing old permission: " + bp.name 9412 + " from package " + bp.sourcePackage); 9413 flags |= UPDATE_PERMISSIONS_ALL; 9414 it.remove(); 9415 } 9416 } 9417 } 9418 9419 // Now update the permissions for all packages, in particular 9420 // replace the granted permissions of the system packages. 9421 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9422 for (PackageParser.Package pkg : mPackages.values()) { 9423 if (pkg != pkgInfo) { 9424 // Only replace for packages on requested volume 9425 final String volumeUuid = getVolumeUuidForPackage(pkg); 9426 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9427 && Objects.equals(replaceVolumeUuid, volumeUuid); 9428 grantPermissionsLPw(pkg, replace, changingPkg); 9429 } 9430 } 9431 } 9432 9433 if (pkgInfo != null) { 9434 // Only replace for packages on requested volume 9435 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9436 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9437 && Objects.equals(replaceVolumeUuid, volumeUuid); 9438 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9439 } 9440 } 9441 9442 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9443 String packageOfInterest) { 9444 // IMPORTANT: There are two types of permissions: install and runtime. 9445 // Install time permissions are granted when the app is installed to 9446 // all device users and users added in the future. Runtime permissions 9447 // are granted at runtime explicitly to specific users. Normal and signature 9448 // protected permissions are install time permissions. Dangerous permissions 9449 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9450 // otherwise they are runtime permissions. This function does not manage 9451 // runtime permissions except for the case an app targeting Lollipop MR1 9452 // being upgraded to target a newer SDK, in which case dangerous permissions 9453 // are transformed from install time to runtime ones. 9454 9455 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9456 if (ps == null) { 9457 return; 9458 } 9459 9460 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9461 9462 PermissionsState permissionsState = ps.getPermissionsState(); 9463 PermissionsState origPermissions = permissionsState; 9464 9465 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9466 9467 boolean runtimePermissionsRevoked = false; 9468 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9469 9470 boolean changedInstallPermission = false; 9471 9472 if (replace) { 9473 ps.installPermissionsFixed = false; 9474 if (!ps.isSharedUser()) { 9475 origPermissions = new PermissionsState(permissionsState); 9476 permissionsState.reset(); 9477 } else { 9478 // We need to know only about runtime permission changes since the 9479 // calling code always writes the install permissions state but 9480 // the runtime ones are written only if changed. The only cases of 9481 // changed runtime permissions here are promotion of an install to 9482 // runtime and revocation of a runtime from a shared user. 9483 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9484 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9485 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9486 runtimePermissionsRevoked = true; 9487 } 9488 } 9489 } 9490 9491 permissionsState.setGlobalGids(mGlobalGids); 9492 9493 final int N = pkg.requestedPermissions.size(); 9494 for (int i=0; i<N; i++) { 9495 final String name = pkg.requestedPermissions.get(i); 9496 final BasePermission bp = mSettings.mPermissions.get(name); 9497 9498 if (DEBUG_INSTALL) { 9499 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9500 } 9501 9502 if (bp == null || bp.packageSetting == null) { 9503 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9504 Slog.w(TAG, "Unknown permission " + name 9505 + " in package " + pkg.packageName); 9506 } 9507 continue; 9508 } 9509 9510 final String perm = bp.name; 9511 boolean allowedSig = false; 9512 int grant = GRANT_DENIED; 9513 9514 // Keep track of app op permissions. 9515 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9516 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9517 if (pkgs == null) { 9518 pkgs = new ArraySet<>(); 9519 mAppOpPermissionPackages.put(bp.name, pkgs); 9520 } 9521 pkgs.add(pkg.packageName); 9522 } 9523 9524 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9525 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9526 >= Build.VERSION_CODES.M; 9527 switch (level) { 9528 case PermissionInfo.PROTECTION_NORMAL: { 9529 // For all apps normal permissions are install time ones. 9530 grant = GRANT_INSTALL; 9531 } break; 9532 9533 case PermissionInfo.PROTECTION_DANGEROUS: { 9534 // If a permission review is required for legacy apps we represent 9535 // their permissions as always granted runtime ones since we need 9536 // to keep the review required permission flag per user while an 9537 // install permission's state is shared across all users. 9538 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9539 // For legacy apps dangerous permissions are install time ones. 9540 grant = GRANT_INSTALL; 9541 } else if (origPermissions.hasInstallPermission(bp.name)) { 9542 // For legacy apps that became modern, install becomes runtime. 9543 grant = GRANT_UPGRADE; 9544 } else if (mPromoteSystemApps 9545 && isSystemApp(ps) 9546 && mExistingSystemPackages.contains(ps.name)) { 9547 // For legacy system apps, install becomes runtime. 9548 // We cannot check hasInstallPermission() for system apps since those 9549 // permissions were granted implicitly and not persisted pre-M. 9550 grant = GRANT_UPGRADE; 9551 } else { 9552 // For modern apps keep runtime permissions unchanged. 9553 grant = GRANT_RUNTIME; 9554 } 9555 } break; 9556 9557 case PermissionInfo.PROTECTION_SIGNATURE: { 9558 // For all apps signature permissions are install time ones. 9559 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9560 if (allowedSig) { 9561 grant = GRANT_INSTALL; 9562 } 9563 } break; 9564 } 9565 9566 if (DEBUG_INSTALL) { 9567 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9568 } 9569 9570 if (grant != GRANT_DENIED) { 9571 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9572 // If this is an existing, non-system package, then 9573 // we can't add any new permissions to it. 9574 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9575 // Except... if this is a permission that was added 9576 // to the platform (note: need to only do this when 9577 // updating the platform). 9578 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9579 grant = GRANT_DENIED; 9580 } 9581 } 9582 } 9583 9584 switch (grant) { 9585 case GRANT_INSTALL: { 9586 // Revoke this as runtime permission to handle the case of 9587 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9588 for (int userId : UserManagerService.getInstance().getUserIds()) { 9589 if (origPermissions.getRuntimePermissionState( 9590 bp.name, userId) != null) { 9591 // Revoke the runtime permission and clear the flags. 9592 origPermissions.revokeRuntimePermission(bp, userId); 9593 origPermissions.updatePermissionFlags(bp, userId, 9594 PackageManager.MASK_PERMISSION_FLAGS, 0); 9595 // If we revoked a permission permission, we have to write. 9596 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9597 changedRuntimePermissionUserIds, userId); 9598 } 9599 } 9600 // Grant an install permission. 9601 if (permissionsState.grantInstallPermission(bp) != 9602 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9603 changedInstallPermission = true; 9604 } 9605 } break; 9606 9607 case GRANT_RUNTIME: { 9608 // Grant previously granted runtime permissions. 9609 for (int userId : UserManagerService.getInstance().getUserIds()) { 9610 PermissionState permissionState = origPermissions 9611 .getRuntimePermissionState(bp.name, userId); 9612 int flags = permissionState != null 9613 ? permissionState.getFlags() : 0; 9614 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9615 if (permissionsState.grantRuntimePermission(bp, userId) == 9616 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9617 // If we cannot put the permission as it was, we have to write. 9618 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9619 changedRuntimePermissionUserIds, userId); 9620 } 9621 // If the app supports runtime permissions no need for a review. 9622 if (Build.PERMISSIONS_REVIEW_REQUIRED 9623 && appSupportsRuntimePermissions 9624 && (flags & PackageManager 9625 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9626 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9627 // Since we changed the flags, we have to write. 9628 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9629 changedRuntimePermissionUserIds, userId); 9630 } 9631 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9632 && !appSupportsRuntimePermissions) { 9633 // For legacy apps that need a permission review, every new 9634 // runtime permission is granted but it is pending a review. 9635 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9636 permissionsState.grantRuntimePermission(bp, userId); 9637 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9638 // We changed the permission and flags, hence have to write. 9639 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9640 changedRuntimePermissionUserIds, userId); 9641 } 9642 } 9643 // Propagate the permission flags. 9644 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9645 } 9646 } break; 9647 9648 case GRANT_UPGRADE: { 9649 // Grant runtime permissions for a previously held install permission. 9650 PermissionState permissionState = origPermissions 9651 .getInstallPermissionState(bp.name); 9652 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9653 9654 if (origPermissions.revokeInstallPermission(bp) 9655 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9656 // We will be transferring the permission flags, so clear them. 9657 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9658 PackageManager.MASK_PERMISSION_FLAGS, 0); 9659 changedInstallPermission = true; 9660 } 9661 9662 // If the permission is not to be promoted to runtime we ignore it and 9663 // also its other flags as they are not applicable to install permissions. 9664 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9665 for (int userId : currentUserIds) { 9666 if (permissionsState.grantRuntimePermission(bp, userId) != 9667 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9668 // Transfer the permission flags. 9669 permissionsState.updatePermissionFlags(bp, userId, 9670 flags, flags); 9671 // If we granted the permission, we have to write. 9672 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9673 changedRuntimePermissionUserIds, userId); 9674 } 9675 } 9676 } 9677 } break; 9678 9679 default: { 9680 if (packageOfInterest == null 9681 || packageOfInterest.equals(pkg.packageName)) { 9682 Slog.w(TAG, "Not granting permission " + perm 9683 + " to package " + pkg.packageName 9684 + " because it was previously installed without"); 9685 } 9686 } break; 9687 } 9688 } else { 9689 if (permissionsState.revokeInstallPermission(bp) != 9690 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9691 // Also drop the permission flags. 9692 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9693 PackageManager.MASK_PERMISSION_FLAGS, 0); 9694 changedInstallPermission = true; 9695 Slog.i(TAG, "Un-granting permission " + perm 9696 + " from package " + pkg.packageName 9697 + " (protectionLevel=" + bp.protectionLevel 9698 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9699 + ")"); 9700 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9701 // Don't print warning for app op permissions, since it is fine for them 9702 // not to be granted, there is a UI for the user to decide. 9703 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9704 Slog.w(TAG, "Not granting permission " + perm 9705 + " to package " + pkg.packageName 9706 + " (protectionLevel=" + bp.protectionLevel 9707 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9708 + ")"); 9709 } 9710 } 9711 } 9712 } 9713 9714 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9715 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9716 // This is the first that we have heard about this package, so the 9717 // permissions we have now selected are fixed until explicitly 9718 // changed. 9719 ps.installPermissionsFixed = true; 9720 } 9721 9722 // Persist the runtime permissions state for users with changes. If permissions 9723 // were revoked because no app in the shared user declares them we have to 9724 // write synchronously to avoid losing runtime permissions state. 9725 for (int userId : changedRuntimePermissionUserIds) { 9726 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9727 } 9728 9729 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9730 } 9731 9732 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9733 boolean allowed = false; 9734 final int NP = PackageParser.NEW_PERMISSIONS.length; 9735 for (int ip=0; ip<NP; ip++) { 9736 final PackageParser.NewPermissionInfo npi 9737 = PackageParser.NEW_PERMISSIONS[ip]; 9738 if (npi.name.equals(perm) 9739 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9740 allowed = true; 9741 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9742 + pkg.packageName); 9743 break; 9744 } 9745 } 9746 return allowed; 9747 } 9748 9749 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9750 BasePermission bp, PermissionsState origPermissions) { 9751 boolean allowed; 9752 allowed = (compareSignatures( 9753 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9754 == PackageManager.SIGNATURE_MATCH) 9755 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9756 == PackageManager.SIGNATURE_MATCH); 9757 if (!allowed && (bp.protectionLevel 9758 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9759 if (isSystemApp(pkg)) { 9760 // For updated system applications, a system permission 9761 // is granted only if it had been defined by the original application. 9762 if (pkg.isUpdatedSystemApp()) { 9763 final PackageSetting sysPs = mSettings 9764 .getDisabledSystemPkgLPr(pkg.packageName); 9765 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9766 // If the original was granted this permission, we take 9767 // that grant decision as read and propagate it to the 9768 // update. 9769 if (sysPs.isPrivileged()) { 9770 allowed = true; 9771 } 9772 } else { 9773 // The system apk may have been updated with an older 9774 // version of the one on the data partition, but which 9775 // granted a new system permission that it didn't have 9776 // before. In this case we do want to allow the app to 9777 // now get the new permission if the ancestral apk is 9778 // privileged to get it. 9779 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9780 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9781 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9782 allowed = true; 9783 break; 9784 } 9785 } 9786 } 9787 // Also if a privileged parent package on the system image or any of 9788 // its children requested a privileged permission, the updated child 9789 // packages can also get the permission. 9790 if (pkg.parentPackage != null) { 9791 final PackageSetting disabledSysParentPs = mSettings 9792 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9793 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9794 && disabledSysParentPs.isPrivileged()) { 9795 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9796 allowed = true; 9797 } else if (disabledSysParentPs.pkg.childPackages != null) { 9798 final int count = disabledSysParentPs.pkg.childPackages.size(); 9799 for (int i = 0; i < count; i++) { 9800 PackageParser.Package disabledSysChildPkg = 9801 disabledSysParentPs.pkg.childPackages.get(i); 9802 if (isPackageRequestingPermission(disabledSysChildPkg, 9803 perm)) { 9804 allowed = true; 9805 break; 9806 } 9807 } 9808 } 9809 } 9810 } 9811 } 9812 } else { 9813 allowed = isPrivilegedApp(pkg); 9814 } 9815 } 9816 } 9817 if (!allowed) { 9818 if (!allowed && (bp.protectionLevel 9819 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9820 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9821 // If this was a previously normal/dangerous permission that got moved 9822 // to a system permission as part of the runtime permission redesign, then 9823 // we still want to blindly grant it to old apps. 9824 allowed = true; 9825 } 9826 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9827 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9828 // If this permission is to be granted to the system installer and 9829 // this app is an installer, then it gets the permission. 9830 allowed = true; 9831 } 9832 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9833 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9834 // If this permission is to be granted to the system verifier and 9835 // this app is a verifier, then it gets the permission. 9836 allowed = true; 9837 } 9838 if (!allowed && (bp.protectionLevel 9839 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9840 && isSystemApp(pkg)) { 9841 // Any pre-installed system app is allowed to get this permission. 9842 allowed = true; 9843 } 9844 if (!allowed && (bp.protectionLevel 9845 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9846 // For development permissions, a development permission 9847 // is granted only if it was already granted. 9848 allowed = origPermissions.hasInstallPermission(perm); 9849 } 9850 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9851 && pkg.packageName.equals(mSetupWizardPackage)) { 9852 // If this permission is to be granted to the system setup wizard and 9853 // this app is a setup wizard, then it gets the permission. 9854 allowed = true; 9855 } 9856 } 9857 return allowed; 9858 } 9859 9860 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9861 final int permCount = pkg.requestedPermissions.size(); 9862 for (int j = 0; j < permCount; j++) { 9863 String requestedPermission = pkg.requestedPermissions.get(j); 9864 if (permission.equals(requestedPermission)) { 9865 return true; 9866 } 9867 } 9868 return false; 9869 } 9870 9871 final class ActivityIntentResolver 9872 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9873 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9874 boolean defaultOnly, int userId) { 9875 if (!sUserManager.exists(userId)) return null; 9876 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9877 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9878 } 9879 9880 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9881 int userId) { 9882 if (!sUserManager.exists(userId)) return null; 9883 mFlags = flags; 9884 return super.queryIntent(intent, resolvedType, 9885 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9886 } 9887 9888 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9889 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9890 if (!sUserManager.exists(userId)) return null; 9891 if (packageActivities == null) { 9892 return null; 9893 } 9894 mFlags = flags; 9895 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9896 final int N = packageActivities.size(); 9897 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9898 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9899 9900 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9901 for (int i = 0; i < N; ++i) { 9902 intentFilters = packageActivities.get(i).intents; 9903 if (intentFilters != null && intentFilters.size() > 0) { 9904 PackageParser.ActivityIntentInfo[] array = 9905 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9906 intentFilters.toArray(array); 9907 listCut.add(array); 9908 } 9909 } 9910 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9911 } 9912 9913 /** 9914 * Finds a privileged activity that matches the specified activity names. 9915 */ 9916 private PackageParser.Activity findMatchingActivity( 9917 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9918 for (PackageParser.Activity sysActivity : activityList) { 9919 if (sysActivity.info.name.equals(activityInfo.name)) { 9920 return sysActivity; 9921 } 9922 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9923 return sysActivity; 9924 } 9925 if (sysActivity.info.targetActivity != null) { 9926 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9927 return sysActivity; 9928 } 9929 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9930 return sysActivity; 9931 } 9932 } 9933 } 9934 return null; 9935 } 9936 9937 public class IterGenerator<E> { 9938 public Iterator<E> generate(ActivityIntentInfo info) { 9939 return null; 9940 } 9941 } 9942 9943 public class ActionIterGenerator extends IterGenerator<String> { 9944 @Override 9945 public Iterator<String> generate(ActivityIntentInfo info) { 9946 return info.actionsIterator(); 9947 } 9948 } 9949 9950 public class CategoriesIterGenerator extends IterGenerator<String> { 9951 @Override 9952 public Iterator<String> generate(ActivityIntentInfo info) { 9953 return info.categoriesIterator(); 9954 } 9955 } 9956 9957 public class SchemesIterGenerator extends IterGenerator<String> { 9958 @Override 9959 public Iterator<String> generate(ActivityIntentInfo info) { 9960 return info.schemesIterator(); 9961 } 9962 } 9963 9964 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9965 @Override 9966 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9967 return info.authoritiesIterator(); 9968 } 9969 } 9970 9971 /** 9972 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9973 * MODIFIED. Do not pass in a list that should not be changed. 9974 */ 9975 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9976 IterGenerator<T> generator, Iterator<T> searchIterator) { 9977 // loop through the set of actions; every one must be found in the intent filter 9978 while (searchIterator.hasNext()) { 9979 // we must have at least one filter in the list to consider a match 9980 if (intentList.size() == 0) { 9981 break; 9982 } 9983 9984 final T searchAction = searchIterator.next(); 9985 9986 // loop through the set of intent filters 9987 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9988 while (intentIter.hasNext()) { 9989 final ActivityIntentInfo intentInfo = intentIter.next(); 9990 boolean selectionFound = false; 9991 9992 // loop through the intent filter's selection criteria; at least one 9993 // of them must match the searched criteria 9994 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 9995 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 9996 final T intentSelection = intentSelectionIter.next(); 9997 if (intentSelection != null && intentSelection.equals(searchAction)) { 9998 selectionFound = true; 9999 break; 10000 } 10001 } 10002 10003 // the selection criteria wasn't found in this filter's set; this filter 10004 // is not a potential match 10005 if (!selectionFound) { 10006 intentIter.remove(); 10007 } 10008 } 10009 } 10010 } 10011 10012 private boolean isProtectedAction(ActivityIntentInfo filter) { 10013 final Iterator<String> actionsIter = filter.actionsIterator(); 10014 while (actionsIter != null && actionsIter.hasNext()) { 10015 final String filterAction = actionsIter.next(); 10016 if (PROTECTED_ACTIONS.contains(filterAction)) { 10017 return true; 10018 } 10019 } 10020 return false; 10021 } 10022 10023 /** 10024 * Adjusts the priority of the given intent filter according to policy. 10025 * <p> 10026 * <ul> 10027 * <li>The priority for non privileged applications is capped to '0'</li> 10028 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10029 * <li>The priority for unbundled updates to privileged applications is capped to the 10030 * priority defined on the system partition</li> 10031 * </ul> 10032 * <p> 10033 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10034 * allowed to obtain any priority on any action. 10035 */ 10036 private void adjustPriority( 10037 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10038 // nothing to do; priority is fine as-is 10039 if (intent.getPriority() <= 0) { 10040 return; 10041 } 10042 10043 final ActivityInfo activityInfo = intent.activity.info; 10044 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10045 10046 final boolean privilegedApp = 10047 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10048 if (!privilegedApp) { 10049 // non-privileged applications can never define a priority >0 10050 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10051 + " package: " + applicationInfo.packageName 10052 + " activity: " + intent.activity.className 10053 + " origPrio: " + intent.getPriority()); 10054 intent.setPriority(0); 10055 return; 10056 } 10057 10058 if (systemActivities == null) { 10059 // the system package is not disabled; we're parsing the system partition 10060 if (isProtectedAction(intent)) { 10061 if (mDeferProtectedFilters) { 10062 // We can't deal with these just yet. No component should ever obtain a 10063 // >0 priority for a protected actions, with ONE exception -- the setup 10064 // wizard. The setup wizard, however, cannot be known until we're able to 10065 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10066 // until all intent filters have been processed. Chicken, meet egg. 10067 // Let the filter temporarily have a high priority and rectify the 10068 // priorities after all system packages have been scanned. 10069 mProtectedFilters.add(intent); 10070 if (DEBUG_FILTERS) { 10071 Slog.i(TAG, "Protected action; save for later;" 10072 + " package: " + applicationInfo.packageName 10073 + " activity: " + intent.activity.className 10074 + " origPrio: " + intent.getPriority()); 10075 } 10076 return; 10077 } else { 10078 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10079 Slog.i(TAG, "No setup wizard;" 10080 + " All protected intents capped to priority 0"); 10081 } 10082 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10083 if (DEBUG_FILTERS) { 10084 Slog.i(TAG, "Found setup wizard;" 10085 + " allow priority " + intent.getPriority() + ";" 10086 + " package: " + intent.activity.info.packageName 10087 + " activity: " + intent.activity.className 10088 + " priority: " + intent.getPriority()); 10089 } 10090 // setup wizard gets whatever it wants 10091 return; 10092 } 10093 Slog.w(TAG, "Protected action; cap priority to 0;" 10094 + " package: " + intent.activity.info.packageName 10095 + " activity: " + intent.activity.className 10096 + " origPrio: " + intent.getPriority()); 10097 intent.setPriority(0); 10098 return; 10099 } 10100 } 10101 // privileged apps on the system image get whatever priority they request 10102 return; 10103 } 10104 10105 // privileged app unbundled update ... try to find the same activity 10106 final PackageParser.Activity foundActivity = 10107 findMatchingActivity(systemActivities, activityInfo); 10108 if (foundActivity == null) { 10109 // this is a new activity; it cannot obtain >0 priority 10110 if (DEBUG_FILTERS) { 10111 Slog.i(TAG, "New activity; cap priority to 0;" 10112 + " package: " + applicationInfo.packageName 10113 + " activity: " + intent.activity.className 10114 + " origPrio: " + intent.getPriority()); 10115 } 10116 intent.setPriority(0); 10117 return; 10118 } 10119 10120 // found activity, now check for filter equivalence 10121 10122 // a shallow copy is enough; we modify the list, not its contents 10123 final List<ActivityIntentInfo> intentListCopy = 10124 new ArrayList<>(foundActivity.intents); 10125 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10126 10127 // find matching action subsets 10128 final Iterator<String> actionsIterator = intent.actionsIterator(); 10129 if (actionsIterator != null) { 10130 getIntentListSubset( 10131 intentListCopy, new ActionIterGenerator(), actionsIterator); 10132 if (intentListCopy.size() == 0) { 10133 // no more intents to match; we're not equivalent 10134 if (DEBUG_FILTERS) { 10135 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10136 + " package: " + applicationInfo.packageName 10137 + " activity: " + intent.activity.className 10138 + " origPrio: " + intent.getPriority()); 10139 } 10140 intent.setPriority(0); 10141 return; 10142 } 10143 } 10144 10145 // find matching category subsets 10146 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10147 if (categoriesIterator != null) { 10148 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10149 categoriesIterator); 10150 if (intentListCopy.size() == 0) { 10151 // no more intents to match; we're not equivalent 10152 if (DEBUG_FILTERS) { 10153 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10154 + " package: " + applicationInfo.packageName 10155 + " activity: " + intent.activity.className 10156 + " origPrio: " + intent.getPriority()); 10157 } 10158 intent.setPriority(0); 10159 return; 10160 } 10161 } 10162 10163 // find matching schemes subsets 10164 final Iterator<String> schemesIterator = intent.schemesIterator(); 10165 if (schemesIterator != null) { 10166 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10167 schemesIterator); 10168 if (intentListCopy.size() == 0) { 10169 // no more intents to match; we're not equivalent 10170 if (DEBUG_FILTERS) { 10171 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10172 + " package: " + applicationInfo.packageName 10173 + " activity: " + intent.activity.className 10174 + " origPrio: " + intent.getPriority()); 10175 } 10176 intent.setPriority(0); 10177 return; 10178 } 10179 } 10180 10181 // find matching authorities subsets 10182 final Iterator<IntentFilter.AuthorityEntry> 10183 authoritiesIterator = intent.authoritiesIterator(); 10184 if (authoritiesIterator != null) { 10185 getIntentListSubset(intentListCopy, 10186 new AuthoritiesIterGenerator(), 10187 authoritiesIterator); 10188 if (intentListCopy.size() == 0) { 10189 // no more intents to match; we're not equivalent 10190 if (DEBUG_FILTERS) { 10191 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10192 + " package: " + applicationInfo.packageName 10193 + " activity: " + intent.activity.className 10194 + " origPrio: " + intent.getPriority()); 10195 } 10196 intent.setPriority(0); 10197 return; 10198 } 10199 } 10200 10201 // we found matching filter(s); app gets the max priority of all intents 10202 int cappedPriority = 0; 10203 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10204 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10205 } 10206 if (intent.getPriority() > cappedPriority) { 10207 if (DEBUG_FILTERS) { 10208 Slog.i(TAG, "Found matching filter(s);" 10209 + " cap priority to " + cappedPriority + ";" 10210 + " package: " + applicationInfo.packageName 10211 + " activity: " + intent.activity.className 10212 + " origPrio: " + intent.getPriority()); 10213 } 10214 intent.setPriority(cappedPriority); 10215 return; 10216 } 10217 // all this for nothing; the requested priority was <= what was on the system 10218 } 10219 10220 public final void addActivity(PackageParser.Activity a, String type) { 10221 mActivities.put(a.getComponentName(), a); 10222 if (DEBUG_SHOW_INFO) 10223 Log.v( 10224 TAG, " " + type + " " + 10225 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10226 if (DEBUG_SHOW_INFO) 10227 Log.v(TAG, " Class=" + a.info.name); 10228 final int NI = a.intents.size(); 10229 for (int j=0; j<NI; j++) { 10230 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10231 if ("activity".equals(type)) { 10232 final PackageSetting ps = 10233 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10234 final List<PackageParser.Activity> systemActivities = 10235 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10236 adjustPriority(systemActivities, intent); 10237 } 10238 if (DEBUG_SHOW_INFO) { 10239 Log.v(TAG, " IntentFilter:"); 10240 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10241 } 10242 if (!intent.debugCheck()) { 10243 Log.w(TAG, "==> For Activity " + a.info.name); 10244 } 10245 addFilter(intent); 10246 } 10247 } 10248 10249 public final void removeActivity(PackageParser.Activity a, String type) { 10250 mActivities.remove(a.getComponentName()); 10251 if (DEBUG_SHOW_INFO) { 10252 Log.v(TAG, " " + type + " " 10253 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10254 : a.info.name) + ":"); 10255 Log.v(TAG, " Class=" + a.info.name); 10256 } 10257 final int NI = a.intents.size(); 10258 for (int j=0; j<NI; j++) { 10259 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10260 if (DEBUG_SHOW_INFO) { 10261 Log.v(TAG, " IntentFilter:"); 10262 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10263 } 10264 removeFilter(intent); 10265 } 10266 } 10267 10268 @Override 10269 protected boolean allowFilterResult( 10270 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10271 ActivityInfo filterAi = filter.activity.info; 10272 for (int i=dest.size()-1; i>=0; i--) { 10273 ActivityInfo destAi = dest.get(i).activityInfo; 10274 if (destAi.name == filterAi.name 10275 && destAi.packageName == filterAi.packageName) { 10276 return false; 10277 } 10278 } 10279 return true; 10280 } 10281 10282 @Override 10283 protected ActivityIntentInfo[] newArray(int size) { 10284 return new ActivityIntentInfo[size]; 10285 } 10286 10287 @Override 10288 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10289 if (!sUserManager.exists(userId)) return true; 10290 PackageParser.Package p = filter.activity.owner; 10291 if (p != null) { 10292 PackageSetting ps = (PackageSetting)p.mExtras; 10293 if (ps != null) { 10294 // System apps are never considered stopped for purposes of 10295 // filtering, because there may be no way for the user to 10296 // actually re-launch them. 10297 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10298 && ps.getStopped(userId); 10299 } 10300 } 10301 return false; 10302 } 10303 10304 @Override 10305 protected boolean isPackageForFilter(String packageName, 10306 PackageParser.ActivityIntentInfo info) { 10307 return packageName.equals(info.activity.owner.packageName); 10308 } 10309 10310 @Override 10311 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10312 int match, int userId) { 10313 if (!sUserManager.exists(userId)) return null; 10314 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10315 return null; 10316 } 10317 final PackageParser.Activity activity = info.activity; 10318 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10319 if (ps == null) { 10320 return null; 10321 } 10322 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10323 ps.readUserState(userId), userId); 10324 if (ai == null) { 10325 return null; 10326 } 10327 final ResolveInfo res = new ResolveInfo(); 10328 res.activityInfo = ai; 10329 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10330 res.filter = info; 10331 } 10332 if (info != null) { 10333 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10334 } 10335 res.priority = info.getPriority(); 10336 res.preferredOrder = activity.owner.mPreferredOrder; 10337 //System.out.println("Result: " + res.activityInfo.className + 10338 // " = " + res.priority); 10339 res.match = match; 10340 res.isDefault = info.hasDefault; 10341 res.labelRes = info.labelRes; 10342 res.nonLocalizedLabel = info.nonLocalizedLabel; 10343 if (userNeedsBadging(userId)) { 10344 res.noResourceId = true; 10345 } else { 10346 res.icon = info.icon; 10347 } 10348 res.iconResourceId = info.icon; 10349 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10350 return res; 10351 } 10352 10353 @Override 10354 protected void sortResults(List<ResolveInfo> results) { 10355 Collections.sort(results, mResolvePrioritySorter); 10356 } 10357 10358 @Override 10359 protected void dumpFilter(PrintWriter out, String prefix, 10360 PackageParser.ActivityIntentInfo filter) { 10361 out.print(prefix); out.print( 10362 Integer.toHexString(System.identityHashCode(filter.activity))); 10363 out.print(' '); 10364 filter.activity.printComponentShortName(out); 10365 out.print(" filter "); 10366 out.println(Integer.toHexString(System.identityHashCode(filter))); 10367 } 10368 10369 @Override 10370 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10371 return filter.activity; 10372 } 10373 10374 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10375 PackageParser.Activity activity = (PackageParser.Activity)label; 10376 out.print(prefix); out.print( 10377 Integer.toHexString(System.identityHashCode(activity))); 10378 out.print(' '); 10379 activity.printComponentShortName(out); 10380 if (count > 1) { 10381 out.print(" ("); out.print(count); out.print(" filters)"); 10382 } 10383 out.println(); 10384 } 10385 10386 // Keys are String (activity class name), values are Activity. 10387 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10388 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10389 private int mFlags; 10390 } 10391 10392 private final class ServiceIntentResolver 10393 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10394 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10395 boolean defaultOnly, int userId) { 10396 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10397 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10398 } 10399 10400 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10401 int userId) { 10402 if (!sUserManager.exists(userId)) return null; 10403 mFlags = flags; 10404 return super.queryIntent(intent, resolvedType, 10405 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10406 } 10407 10408 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10409 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10410 if (!sUserManager.exists(userId)) return null; 10411 if (packageServices == null) { 10412 return null; 10413 } 10414 mFlags = flags; 10415 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10416 final int N = packageServices.size(); 10417 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10418 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10419 10420 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10421 for (int i = 0; i < N; ++i) { 10422 intentFilters = packageServices.get(i).intents; 10423 if (intentFilters != null && intentFilters.size() > 0) { 10424 PackageParser.ServiceIntentInfo[] array = 10425 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10426 intentFilters.toArray(array); 10427 listCut.add(array); 10428 } 10429 } 10430 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10431 } 10432 10433 public final void addService(PackageParser.Service s) { 10434 mServices.put(s.getComponentName(), s); 10435 if (DEBUG_SHOW_INFO) { 10436 Log.v(TAG, " " 10437 + (s.info.nonLocalizedLabel != null 10438 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10439 Log.v(TAG, " Class=" + s.info.name); 10440 } 10441 final int NI = s.intents.size(); 10442 int j; 10443 for (j=0; j<NI; j++) { 10444 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10445 if (DEBUG_SHOW_INFO) { 10446 Log.v(TAG, " IntentFilter:"); 10447 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10448 } 10449 if (!intent.debugCheck()) { 10450 Log.w(TAG, "==> For Service " + s.info.name); 10451 } 10452 addFilter(intent); 10453 } 10454 } 10455 10456 public final void removeService(PackageParser.Service s) { 10457 mServices.remove(s.getComponentName()); 10458 if (DEBUG_SHOW_INFO) { 10459 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10460 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10461 Log.v(TAG, " Class=" + s.info.name); 10462 } 10463 final int NI = s.intents.size(); 10464 int j; 10465 for (j=0; j<NI; j++) { 10466 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10467 if (DEBUG_SHOW_INFO) { 10468 Log.v(TAG, " IntentFilter:"); 10469 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10470 } 10471 removeFilter(intent); 10472 } 10473 } 10474 10475 @Override 10476 protected boolean allowFilterResult( 10477 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10478 ServiceInfo filterSi = filter.service.info; 10479 for (int i=dest.size()-1; i>=0; i--) { 10480 ServiceInfo destAi = dest.get(i).serviceInfo; 10481 if (destAi.name == filterSi.name 10482 && destAi.packageName == filterSi.packageName) { 10483 return false; 10484 } 10485 } 10486 return true; 10487 } 10488 10489 @Override 10490 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10491 return new PackageParser.ServiceIntentInfo[size]; 10492 } 10493 10494 @Override 10495 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10496 if (!sUserManager.exists(userId)) return true; 10497 PackageParser.Package p = filter.service.owner; 10498 if (p != null) { 10499 PackageSetting ps = (PackageSetting)p.mExtras; 10500 if (ps != null) { 10501 // System apps are never considered stopped for purposes of 10502 // filtering, because there may be no way for the user to 10503 // actually re-launch them. 10504 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10505 && ps.getStopped(userId); 10506 } 10507 } 10508 return false; 10509 } 10510 10511 @Override 10512 protected boolean isPackageForFilter(String packageName, 10513 PackageParser.ServiceIntentInfo info) { 10514 return packageName.equals(info.service.owner.packageName); 10515 } 10516 10517 @Override 10518 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10519 int match, int userId) { 10520 if (!sUserManager.exists(userId)) return null; 10521 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10522 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10523 return null; 10524 } 10525 final PackageParser.Service service = info.service; 10526 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10527 if (ps == null) { 10528 return null; 10529 } 10530 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10531 ps.readUserState(userId), userId); 10532 if (si == null) { 10533 return null; 10534 } 10535 final ResolveInfo res = new ResolveInfo(); 10536 res.serviceInfo = si; 10537 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10538 res.filter = filter; 10539 } 10540 res.priority = info.getPriority(); 10541 res.preferredOrder = service.owner.mPreferredOrder; 10542 res.match = match; 10543 res.isDefault = info.hasDefault; 10544 res.labelRes = info.labelRes; 10545 res.nonLocalizedLabel = info.nonLocalizedLabel; 10546 res.icon = info.icon; 10547 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10548 return res; 10549 } 10550 10551 @Override 10552 protected void sortResults(List<ResolveInfo> results) { 10553 Collections.sort(results, mResolvePrioritySorter); 10554 } 10555 10556 @Override 10557 protected void dumpFilter(PrintWriter out, String prefix, 10558 PackageParser.ServiceIntentInfo filter) { 10559 out.print(prefix); out.print( 10560 Integer.toHexString(System.identityHashCode(filter.service))); 10561 out.print(' '); 10562 filter.service.printComponentShortName(out); 10563 out.print(" filter "); 10564 out.println(Integer.toHexString(System.identityHashCode(filter))); 10565 } 10566 10567 @Override 10568 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10569 return filter.service; 10570 } 10571 10572 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10573 PackageParser.Service service = (PackageParser.Service)label; 10574 out.print(prefix); out.print( 10575 Integer.toHexString(System.identityHashCode(service))); 10576 out.print(' '); 10577 service.printComponentShortName(out); 10578 if (count > 1) { 10579 out.print(" ("); out.print(count); out.print(" filters)"); 10580 } 10581 out.println(); 10582 } 10583 10584// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10585// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10586// final List<ResolveInfo> retList = Lists.newArrayList(); 10587// while (i.hasNext()) { 10588// final ResolveInfo resolveInfo = (ResolveInfo) i; 10589// if (isEnabledLP(resolveInfo.serviceInfo)) { 10590// retList.add(resolveInfo); 10591// } 10592// } 10593// return retList; 10594// } 10595 10596 // Keys are String (activity class name), values are Activity. 10597 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10598 = new ArrayMap<ComponentName, PackageParser.Service>(); 10599 private int mFlags; 10600 }; 10601 10602 private final class ProviderIntentResolver 10603 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10604 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10605 boolean defaultOnly, int userId) { 10606 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10607 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10608 } 10609 10610 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10611 int userId) { 10612 if (!sUserManager.exists(userId)) 10613 return null; 10614 mFlags = flags; 10615 return super.queryIntent(intent, resolvedType, 10616 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10617 } 10618 10619 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10620 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10621 if (!sUserManager.exists(userId)) 10622 return null; 10623 if (packageProviders == null) { 10624 return null; 10625 } 10626 mFlags = flags; 10627 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10628 final int N = packageProviders.size(); 10629 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10630 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10631 10632 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10633 for (int i = 0; i < N; ++i) { 10634 intentFilters = packageProviders.get(i).intents; 10635 if (intentFilters != null && intentFilters.size() > 0) { 10636 PackageParser.ProviderIntentInfo[] array = 10637 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10638 intentFilters.toArray(array); 10639 listCut.add(array); 10640 } 10641 } 10642 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10643 } 10644 10645 public final void addProvider(PackageParser.Provider p) { 10646 if (mProviders.containsKey(p.getComponentName())) { 10647 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10648 return; 10649 } 10650 10651 mProviders.put(p.getComponentName(), p); 10652 if (DEBUG_SHOW_INFO) { 10653 Log.v(TAG, " " 10654 + (p.info.nonLocalizedLabel != null 10655 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10656 Log.v(TAG, " Class=" + p.info.name); 10657 } 10658 final int NI = p.intents.size(); 10659 int j; 10660 for (j = 0; j < NI; j++) { 10661 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10662 if (DEBUG_SHOW_INFO) { 10663 Log.v(TAG, " IntentFilter:"); 10664 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10665 } 10666 if (!intent.debugCheck()) { 10667 Log.w(TAG, "==> For Provider " + p.info.name); 10668 } 10669 addFilter(intent); 10670 } 10671 } 10672 10673 public final void removeProvider(PackageParser.Provider p) { 10674 mProviders.remove(p.getComponentName()); 10675 if (DEBUG_SHOW_INFO) { 10676 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10677 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10678 Log.v(TAG, " Class=" + p.info.name); 10679 } 10680 final int NI = p.intents.size(); 10681 int j; 10682 for (j = 0; j < NI; j++) { 10683 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10684 if (DEBUG_SHOW_INFO) { 10685 Log.v(TAG, " IntentFilter:"); 10686 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10687 } 10688 removeFilter(intent); 10689 } 10690 } 10691 10692 @Override 10693 protected boolean allowFilterResult( 10694 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10695 ProviderInfo filterPi = filter.provider.info; 10696 for (int i = dest.size() - 1; i >= 0; i--) { 10697 ProviderInfo destPi = dest.get(i).providerInfo; 10698 if (destPi.name == filterPi.name 10699 && destPi.packageName == filterPi.packageName) { 10700 return false; 10701 } 10702 } 10703 return true; 10704 } 10705 10706 @Override 10707 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10708 return new PackageParser.ProviderIntentInfo[size]; 10709 } 10710 10711 @Override 10712 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10713 if (!sUserManager.exists(userId)) 10714 return true; 10715 PackageParser.Package p = filter.provider.owner; 10716 if (p != null) { 10717 PackageSetting ps = (PackageSetting) p.mExtras; 10718 if (ps != null) { 10719 // System apps are never considered stopped for purposes of 10720 // filtering, because there may be no way for the user to 10721 // actually re-launch them. 10722 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10723 && ps.getStopped(userId); 10724 } 10725 } 10726 return false; 10727 } 10728 10729 @Override 10730 protected boolean isPackageForFilter(String packageName, 10731 PackageParser.ProviderIntentInfo info) { 10732 return packageName.equals(info.provider.owner.packageName); 10733 } 10734 10735 @Override 10736 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10737 int match, int userId) { 10738 if (!sUserManager.exists(userId)) 10739 return null; 10740 final PackageParser.ProviderIntentInfo info = filter; 10741 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10742 return null; 10743 } 10744 final PackageParser.Provider provider = info.provider; 10745 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10746 if (ps == null) { 10747 return null; 10748 } 10749 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10750 ps.readUserState(userId), userId); 10751 if (pi == null) { 10752 return null; 10753 } 10754 final ResolveInfo res = new ResolveInfo(); 10755 res.providerInfo = pi; 10756 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10757 res.filter = filter; 10758 } 10759 res.priority = info.getPriority(); 10760 res.preferredOrder = provider.owner.mPreferredOrder; 10761 res.match = match; 10762 res.isDefault = info.hasDefault; 10763 res.labelRes = info.labelRes; 10764 res.nonLocalizedLabel = info.nonLocalizedLabel; 10765 res.icon = info.icon; 10766 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10767 return res; 10768 } 10769 10770 @Override 10771 protected void sortResults(List<ResolveInfo> results) { 10772 Collections.sort(results, mResolvePrioritySorter); 10773 } 10774 10775 @Override 10776 protected void dumpFilter(PrintWriter out, String prefix, 10777 PackageParser.ProviderIntentInfo filter) { 10778 out.print(prefix); 10779 out.print( 10780 Integer.toHexString(System.identityHashCode(filter.provider))); 10781 out.print(' '); 10782 filter.provider.printComponentShortName(out); 10783 out.print(" filter "); 10784 out.println(Integer.toHexString(System.identityHashCode(filter))); 10785 } 10786 10787 @Override 10788 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10789 return filter.provider; 10790 } 10791 10792 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10793 PackageParser.Provider provider = (PackageParser.Provider)label; 10794 out.print(prefix); out.print( 10795 Integer.toHexString(System.identityHashCode(provider))); 10796 out.print(' '); 10797 provider.printComponentShortName(out); 10798 if (count > 1) { 10799 out.print(" ("); out.print(count); out.print(" filters)"); 10800 } 10801 out.println(); 10802 } 10803 10804 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10805 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10806 private int mFlags; 10807 } 10808 10809 private static final class EphemeralIntentResolver 10810 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10811 @Override 10812 protected EphemeralResolveIntentInfo[] newArray(int size) { 10813 return new EphemeralResolveIntentInfo[size]; 10814 } 10815 10816 @Override 10817 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10818 return true; 10819 } 10820 10821 @Override 10822 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10823 int userId) { 10824 if (!sUserManager.exists(userId)) { 10825 return null; 10826 } 10827 return info.getEphemeralResolveInfo(); 10828 } 10829 } 10830 10831 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10832 new Comparator<ResolveInfo>() { 10833 public int compare(ResolveInfo r1, ResolveInfo r2) { 10834 int v1 = r1.priority; 10835 int v2 = r2.priority; 10836 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10837 if (v1 != v2) { 10838 return (v1 > v2) ? -1 : 1; 10839 } 10840 v1 = r1.preferredOrder; 10841 v2 = r2.preferredOrder; 10842 if (v1 != v2) { 10843 return (v1 > v2) ? -1 : 1; 10844 } 10845 if (r1.isDefault != r2.isDefault) { 10846 return r1.isDefault ? -1 : 1; 10847 } 10848 v1 = r1.match; 10849 v2 = r2.match; 10850 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10851 if (v1 != v2) { 10852 return (v1 > v2) ? -1 : 1; 10853 } 10854 if (r1.system != r2.system) { 10855 return r1.system ? -1 : 1; 10856 } 10857 if (r1.activityInfo != null) { 10858 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10859 } 10860 if (r1.serviceInfo != null) { 10861 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10862 } 10863 if (r1.providerInfo != null) { 10864 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10865 } 10866 return 0; 10867 } 10868 }; 10869 10870 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10871 new Comparator<ProviderInfo>() { 10872 public int compare(ProviderInfo p1, ProviderInfo p2) { 10873 final int v1 = p1.initOrder; 10874 final int v2 = p2.initOrder; 10875 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10876 } 10877 }; 10878 10879 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10880 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10881 final int[] userIds) { 10882 mHandler.post(new Runnable() { 10883 @Override 10884 public void run() { 10885 try { 10886 final IActivityManager am = ActivityManagerNative.getDefault(); 10887 if (am == null) return; 10888 final int[] resolvedUserIds; 10889 if (userIds == null) { 10890 resolvedUserIds = am.getRunningUserIds(); 10891 } else { 10892 resolvedUserIds = userIds; 10893 } 10894 for (int id : resolvedUserIds) { 10895 final Intent intent = new Intent(action, 10896 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10897 if (extras != null) { 10898 intent.putExtras(extras); 10899 } 10900 if (targetPkg != null) { 10901 intent.setPackage(targetPkg); 10902 } 10903 // Modify the UID when posting to other users 10904 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10905 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10906 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10907 intent.putExtra(Intent.EXTRA_UID, uid); 10908 } 10909 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10910 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10911 if (DEBUG_BROADCASTS) { 10912 RuntimeException here = new RuntimeException("here"); 10913 here.fillInStackTrace(); 10914 Slog.d(TAG, "Sending to user " + id + ": " 10915 + intent.toShortString(false, true, false, false) 10916 + " " + intent.getExtras(), here); 10917 } 10918 am.broadcastIntent(null, intent, null, finishedReceiver, 10919 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10920 null, finishedReceiver != null, false, id); 10921 } 10922 } catch (RemoteException ex) { 10923 } 10924 } 10925 }); 10926 } 10927 10928 /** 10929 * Check if the external storage media is available. This is true if there 10930 * is a mounted external storage medium or if the external storage is 10931 * emulated. 10932 */ 10933 private boolean isExternalMediaAvailable() { 10934 return mMediaMounted || Environment.isExternalStorageEmulated(); 10935 } 10936 10937 @Override 10938 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10939 // writer 10940 synchronized (mPackages) { 10941 if (!isExternalMediaAvailable()) { 10942 // If the external storage is no longer mounted at this point, 10943 // the caller may not have been able to delete all of this 10944 // packages files and can not delete any more. Bail. 10945 return null; 10946 } 10947 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10948 if (lastPackage != null) { 10949 pkgs.remove(lastPackage); 10950 } 10951 if (pkgs.size() > 0) { 10952 return pkgs.get(0); 10953 } 10954 } 10955 return null; 10956 } 10957 10958 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10959 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10960 userId, andCode ? 1 : 0, packageName); 10961 if (mSystemReady) { 10962 msg.sendToTarget(); 10963 } else { 10964 if (mPostSystemReadyMessages == null) { 10965 mPostSystemReadyMessages = new ArrayList<>(); 10966 } 10967 mPostSystemReadyMessages.add(msg); 10968 } 10969 } 10970 10971 void startCleaningPackages() { 10972 // reader 10973 if (!isExternalMediaAvailable()) { 10974 return; 10975 } 10976 synchronized (mPackages) { 10977 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10978 return; 10979 } 10980 } 10981 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10982 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10983 IActivityManager am = ActivityManagerNative.getDefault(); 10984 if (am != null) { 10985 try { 10986 am.startService(null, intent, null, mContext.getOpPackageName(), 10987 UserHandle.USER_SYSTEM); 10988 } catch (RemoteException e) { 10989 } 10990 } 10991 } 10992 10993 @Override 10994 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 10995 int installFlags, String installerPackageName, int userId) { 10996 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 10997 10998 final int callingUid = Binder.getCallingUid(); 10999 enforceCrossUserPermission(callingUid, userId, 11000 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11001 11002 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11003 try { 11004 if (observer != null) { 11005 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11006 } 11007 } catch (RemoteException re) { 11008 } 11009 return; 11010 } 11011 11012 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11013 installFlags |= PackageManager.INSTALL_FROM_ADB; 11014 11015 } else { 11016 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11017 // about installerPackageName. 11018 11019 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11020 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11021 } 11022 11023 UserHandle user; 11024 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11025 user = UserHandle.ALL; 11026 } else { 11027 user = new UserHandle(userId); 11028 } 11029 11030 // Only system components can circumvent runtime permissions when installing. 11031 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11032 && mContext.checkCallingOrSelfPermission(Manifest.permission 11033 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11034 throw new SecurityException("You need the " 11035 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11036 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11037 } 11038 11039 final File originFile = new File(originPath); 11040 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11041 11042 final Message msg = mHandler.obtainMessage(INIT_COPY); 11043 final VerificationInfo verificationInfo = new VerificationInfo( 11044 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11045 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11046 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11047 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11048 null /*certificates*/); 11049 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11050 msg.obj = params; 11051 11052 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11053 System.identityHashCode(msg.obj)); 11054 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11055 System.identityHashCode(msg.obj)); 11056 11057 mHandler.sendMessage(msg); 11058 } 11059 11060 void installStage(String packageName, File stagedDir, String stagedCid, 11061 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11062 String installerPackageName, int installerUid, UserHandle user, 11063 Certificate[][] certificates) { 11064 if (DEBUG_EPHEMERAL) { 11065 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11066 Slog.d(TAG, "Ephemeral install of " + packageName); 11067 } 11068 } 11069 final VerificationInfo verificationInfo = new VerificationInfo( 11070 sessionParams.originatingUri, sessionParams.referrerUri, 11071 sessionParams.originatingUid, installerUid); 11072 11073 final OriginInfo origin; 11074 if (stagedDir != null) { 11075 origin = OriginInfo.fromStagedFile(stagedDir); 11076 } else { 11077 origin = OriginInfo.fromStagedContainer(stagedCid); 11078 } 11079 11080 final Message msg = mHandler.obtainMessage(INIT_COPY); 11081 final InstallParams params = new InstallParams(origin, null, observer, 11082 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11083 verificationInfo, user, sessionParams.abiOverride, 11084 sessionParams.grantedRuntimePermissions, certificates); 11085 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11086 msg.obj = params; 11087 11088 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11089 System.identityHashCode(msg.obj)); 11090 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11091 System.identityHashCode(msg.obj)); 11092 11093 mHandler.sendMessage(msg); 11094 } 11095 11096 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11097 int userId) { 11098 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11099 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11100 } 11101 11102 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11103 int appId, int userId) { 11104 Bundle extras = new Bundle(1); 11105 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11106 11107 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11108 packageName, extras, 0, null, null, new int[] {userId}); 11109 try { 11110 IActivityManager am = ActivityManagerNative.getDefault(); 11111 if (isSystem && am.isUserRunning(userId, 0)) { 11112 // The just-installed/enabled app is bundled on the system, so presumed 11113 // to be able to run automatically without needing an explicit launch. 11114 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11115 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11116 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11117 .setPackage(packageName); 11118 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11119 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11120 } 11121 } catch (RemoteException e) { 11122 // shouldn't happen 11123 Slog.w(TAG, "Unable to bootstrap installed package", e); 11124 } 11125 } 11126 11127 @Override 11128 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11129 int userId) { 11130 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11131 PackageSetting pkgSetting; 11132 final int uid = Binder.getCallingUid(); 11133 enforceCrossUserPermission(uid, userId, 11134 true /* requireFullPermission */, true /* checkShell */, 11135 "setApplicationHiddenSetting for user " + userId); 11136 11137 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11138 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11139 return false; 11140 } 11141 11142 long callingId = Binder.clearCallingIdentity(); 11143 try { 11144 boolean sendAdded = false; 11145 boolean sendRemoved = false; 11146 // writer 11147 synchronized (mPackages) { 11148 pkgSetting = mSettings.mPackages.get(packageName); 11149 if (pkgSetting == null) { 11150 return false; 11151 } 11152 if (pkgSetting.getHidden(userId) != hidden) { 11153 pkgSetting.setHidden(hidden, userId); 11154 mSettings.writePackageRestrictionsLPr(userId); 11155 if (hidden) { 11156 sendRemoved = true; 11157 } else { 11158 sendAdded = true; 11159 } 11160 } 11161 } 11162 if (sendAdded) { 11163 sendPackageAddedForUser(packageName, pkgSetting, userId); 11164 return true; 11165 } 11166 if (sendRemoved) { 11167 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11168 "hiding pkg"); 11169 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11170 return true; 11171 } 11172 } finally { 11173 Binder.restoreCallingIdentity(callingId); 11174 } 11175 return false; 11176 } 11177 11178 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11179 int userId) { 11180 final PackageRemovedInfo info = new PackageRemovedInfo(); 11181 info.removedPackage = packageName; 11182 info.removedUsers = new int[] {userId}; 11183 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11184 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11185 } 11186 11187 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11188 if (pkgList.length > 0) { 11189 Bundle extras = new Bundle(1); 11190 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11191 11192 sendPackageBroadcast( 11193 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11194 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11195 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11196 new int[] {userId}); 11197 } 11198 } 11199 11200 /** 11201 * Returns true if application is not found or there was an error. Otherwise it returns 11202 * the hidden state of the package for the given user. 11203 */ 11204 @Override 11205 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11206 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11207 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11208 true /* requireFullPermission */, false /* checkShell */, 11209 "getApplicationHidden for user " + userId); 11210 PackageSetting pkgSetting; 11211 long callingId = Binder.clearCallingIdentity(); 11212 try { 11213 // writer 11214 synchronized (mPackages) { 11215 pkgSetting = mSettings.mPackages.get(packageName); 11216 if (pkgSetting == null) { 11217 return true; 11218 } 11219 return pkgSetting.getHidden(userId); 11220 } 11221 } finally { 11222 Binder.restoreCallingIdentity(callingId); 11223 } 11224 } 11225 11226 /** 11227 * @hide 11228 */ 11229 @Override 11230 public int installExistingPackageAsUser(String packageName, int userId) { 11231 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11232 null); 11233 PackageSetting pkgSetting; 11234 final int uid = Binder.getCallingUid(); 11235 enforceCrossUserPermission(uid, userId, 11236 true /* requireFullPermission */, true /* checkShell */, 11237 "installExistingPackage for user " + userId); 11238 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11239 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11240 } 11241 11242 long callingId = Binder.clearCallingIdentity(); 11243 try { 11244 boolean installed = false; 11245 11246 // writer 11247 synchronized (mPackages) { 11248 pkgSetting = mSettings.mPackages.get(packageName); 11249 if (pkgSetting == null) { 11250 return PackageManager.INSTALL_FAILED_INVALID_URI; 11251 } 11252 if (!pkgSetting.getInstalled(userId)) { 11253 pkgSetting.setInstalled(true, userId); 11254 pkgSetting.setHidden(false, userId); 11255 mSettings.writePackageRestrictionsLPr(userId); 11256 installed = true; 11257 } 11258 } 11259 11260 if (installed) { 11261 if (pkgSetting.pkg != null) { 11262 synchronized (mInstallLock) { 11263 // We don't need to freeze for a brand new install 11264 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11265 } 11266 } 11267 sendPackageAddedForUser(packageName, pkgSetting, userId); 11268 } 11269 } finally { 11270 Binder.restoreCallingIdentity(callingId); 11271 } 11272 11273 return PackageManager.INSTALL_SUCCEEDED; 11274 } 11275 11276 boolean isUserRestricted(int userId, String restrictionKey) { 11277 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11278 if (restrictions.getBoolean(restrictionKey, false)) { 11279 Log.w(TAG, "User is restricted: " + restrictionKey); 11280 return true; 11281 } 11282 return false; 11283 } 11284 11285 @Override 11286 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11287 int userId) { 11288 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11289 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11290 true /* requireFullPermission */, true /* checkShell */, 11291 "setPackagesSuspended for user " + userId); 11292 11293 if (ArrayUtils.isEmpty(packageNames)) { 11294 return packageNames; 11295 } 11296 11297 // List of package names for whom the suspended state has changed. 11298 List<String> changedPackages = new ArrayList<>(packageNames.length); 11299 // List of package names for whom the suspended state is not set as requested in this 11300 // method. 11301 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11302 for (int i = 0; i < packageNames.length; i++) { 11303 String packageName = packageNames[i]; 11304 long callingId = Binder.clearCallingIdentity(); 11305 try { 11306 boolean changed = false; 11307 final int appId; 11308 synchronized (mPackages) { 11309 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11310 if (pkgSetting == null) { 11311 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11312 + "\". Skipping suspending/un-suspending."); 11313 unactionedPackages.add(packageName); 11314 continue; 11315 } 11316 appId = pkgSetting.appId; 11317 if (pkgSetting.getSuspended(userId) != suspended) { 11318 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11319 unactionedPackages.add(packageName); 11320 continue; 11321 } 11322 pkgSetting.setSuspended(suspended, userId); 11323 mSettings.writePackageRestrictionsLPr(userId); 11324 changed = true; 11325 changedPackages.add(packageName); 11326 } 11327 } 11328 11329 if (changed && suspended) { 11330 killApplication(packageName, UserHandle.getUid(userId, appId), 11331 "suspending package"); 11332 } 11333 } finally { 11334 Binder.restoreCallingIdentity(callingId); 11335 } 11336 } 11337 11338 if (!changedPackages.isEmpty()) { 11339 sendPackagesSuspendedForUser(changedPackages.toArray( 11340 new String[changedPackages.size()]), userId, suspended); 11341 } 11342 11343 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11344 } 11345 11346 @Override 11347 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11348 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11349 true /* requireFullPermission */, false /* checkShell */, 11350 "isPackageSuspendedForUser for user " + userId); 11351 synchronized (mPackages) { 11352 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11353 if (pkgSetting == null) { 11354 throw new IllegalArgumentException("Unknown target package: " + packageName); 11355 } 11356 return pkgSetting.getSuspended(userId); 11357 } 11358 } 11359 11360 /** 11361 * TODO: cache and disallow blocking the active dialer. 11362 * 11363 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11364 */ 11365 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11366 if (isPackageDeviceAdmin(packageName, userId)) { 11367 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11368 + "\": has an active device admin"); 11369 return false; 11370 } 11371 11372 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11373 if (packageName.equals(activeLauncherPackageName)) { 11374 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11375 + "\": contains the active launcher"); 11376 return false; 11377 } 11378 11379 if (packageName.equals(mRequiredInstallerPackage)) { 11380 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11381 + "\": required for package installation"); 11382 return false; 11383 } 11384 11385 if (packageName.equals(mRequiredVerifierPackage)) { 11386 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11387 + "\": required for package verification"); 11388 return false; 11389 } 11390 11391 final PackageParser.Package pkg = mPackages.get(packageName); 11392 if (pkg != null && isPrivilegedApp(pkg)) { 11393 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11394 + "\": is a privileged app"); 11395 return false; 11396 } 11397 11398 return true; 11399 } 11400 11401 private String getActiveLauncherPackageName(int userId) { 11402 Intent intent = new Intent(Intent.ACTION_MAIN); 11403 intent.addCategory(Intent.CATEGORY_HOME); 11404 ResolveInfo resolveInfo = resolveIntent( 11405 intent, 11406 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11407 PackageManager.MATCH_DEFAULT_ONLY, 11408 userId); 11409 11410 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11411 } 11412 11413 @Override 11414 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11415 mContext.enforceCallingOrSelfPermission( 11416 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11417 "Only package verification agents can verify applications"); 11418 11419 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11420 final PackageVerificationResponse response = new PackageVerificationResponse( 11421 verificationCode, Binder.getCallingUid()); 11422 msg.arg1 = id; 11423 msg.obj = response; 11424 mHandler.sendMessage(msg); 11425 } 11426 11427 @Override 11428 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11429 long millisecondsToDelay) { 11430 mContext.enforceCallingOrSelfPermission( 11431 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11432 "Only package verification agents can extend verification timeouts"); 11433 11434 final PackageVerificationState state = mPendingVerification.get(id); 11435 final PackageVerificationResponse response = new PackageVerificationResponse( 11436 verificationCodeAtTimeout, Binder.getCallingUid()); 11437 11438 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11439 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11440 } 11441 if (millisecondsToDelay < 0) { 11442 millisecondsToDelay = 0; 11443 } 11444 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11445 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11446 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11447 } 11448 11449 if ((state != null) && !state.timeoutExtended()) { 11450 state.extendTimeout(); 11451 11452 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11453 msg.arg1 = id; 11454 msg.obj = response; 11455 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11456 } 11457 } 11458 11459 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11460 int verificationCode, UserHandle user) { 11461 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11462 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11463 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11464 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11465 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11466 11467 mContext.sendBroadcastAsUser(intent, user, 11468 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11469 } 11470 11471 private ComponentName matchComponentForVerifier(String packageName, 11472 List<ResolveInfo> receivers) { 11473 ActivityInfo targetReceiver = null; 11474 11475 final int NR = receivers.size(); 11476 for (int i = 0; i < NR; i++) { 11477 final ResolveInfo info = receivers.get(i); 11478 if (info.activityInfo == null) { 11479 continue; 11480 } 11481 11482 if (packageName.equals(info.activityInfo.packageName)) { 11483 targetReceiver = info.activityInfo; 11484 break; 11485 } 11486 } 11487 11488 if (targetReceiver == null) { 11489 return null; 11490 } 11491 11492 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11493 } 11494 11495 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11496 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11497 if (pkgInfo.verifiers.length == 0) { 11498 return null; 11499 } 11500 11501 final int N = pkgInfo.verifiers.length; 11502 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11503 for (int i = 0; i < N; i++) { 11504 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11505 11506 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11507 receivers); 11508 if (comp == null) { 11509 continue; 11510 } 11511 11512 final int verifierUid = getUidForVerifier(verifierInfo); 11513 if (verifierUid == -1) { 11514 continue; 11515 } 11516 11517 if (DEBUG_VERIFY) { 11518 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11519 + " with the correct signature"); 11520 } 11521 sufficientVerifiers.add(comp); 11522 verificationState.addSufficientVerifier(verifierUid); 11523 } 11524 11525 return sufficientVerifiers; 11526 } 11527 11528 private int getUidForVerifier(VerifierInfo verifierInfo) { 11529 synchronized (mPackages) { 11530 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11531 if (pkg == null) { 11532 return -1; 11533 } else if (pkg.mSignatures.length != 1) { 11534 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11535 + " has more than one signature; ignoring"); 11536 return -1; 11537 } 11538 11539 /* 11540 * If the public key of the package's signature does not match 11541 * our expected public key, then this is a different package and 11542 * we should skip. 11543 */ 11544 11545 final byte[] expectedPublicKey; 11546 try { 11547 final Signature verifierSig = pkg.mSignatures[0]; 11548 final PublicKey publicKey = verifierSig.getPublicKey(); 11549 expectedPublicKey = publicKey.getEncoded(); 11550 } catch (CertificateException e) { 11551 return -1; 11552 } 11553 11554 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11555 11556 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11557 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11558 + " does not have the expected public key; ignoring"); 11559 return -1; 11560 } 11561 11562 return pkg.applicationInfo.uid; 11563 } 11564 } 11565 11566 @Override 11567 public void finishPackageInstall(int token) { 11568 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11569 11570 if (DEBUG_INSTALL) { 11571 Slog.v(TAG, "BM finishing package install for " + token); 11572 } 11573 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11574 11575 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11576 mHandler.sendMessage(msg); 11577 } 11578 11579 /** 11580 * Get the verification agent timeout. 11581 * 11582 * @return verification timeout in milliseconds 11583 */ 11584 private long getVerificationTimeout() { 11585 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11586 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11587 DEFAULT_VERIFICATION_TIMEOUT); 11588 } 11589 11590 /** 11591 * Get the default verification agent response code. 11592 * 11593 * @return default verification response code 11594 */ 11595 private int getDefaultVerificationResponse() { 11596 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11597 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11598 DEFAULT_VERIFICATION_RESPONSE); 11599 } 11600 11601 /** 11602 * Check whether or not package verification has been enabled. 11603 * 11604 * @return true if verification should be performed 11605 */ 11606 private boolean isVerificationEnabled(int userId, int installFlags) { 11607 if (!DEFAULT_VERIFY_ENABLE) { 11608 return false; 11609 } 11610 // Ephemeral apps don't get the full verification treatment 11611 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11612 if (DEBUG_EPHEMERAL) { 11613 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11614 } 11615 return false; 11616 } 11617 11618 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11619 11620 // Check if installing from ADB 11621 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11622 // Do not run verification in a test harness environment 11623 if (ActivityManager.isRunningInTestHarness()) { 11624 return false; 11625 } 11626 if (ensureVerifyAppsEnabled) { 11627 return true; 11628 } 11629 // Check if the developer does not want package verification for ADB installs 11630 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11631 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11632 return false; 11633 } 11634 } 11635 11636 if (ensureVerifyAppsEnabled) { 11637 return true; 11638 } 11639 11640 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11641 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11642 } 11643 11644 @Override 11645 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11646 throws RemoteException { 11647 mContext.enforceCallingOrSelfPermission( 11648 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11649 "Only intentfilter verification agents can verify applications"); 11650 11651 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11652 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11653 Binder.getCallingUid(), verificationCode, failedDomains); 11654 msg.arg1 = id; 11655 msg.obj = response; 11656 mHandler.sendMessage(msg); 11657 } 11658 11659 @Override 11660 public int getIntentVerificationStatus(String packageName, int userId) { 11661 synchronized (mPackages) { 11662 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11663 } 11664 } 11665 11666 @Override 11667 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11668 mContext.enforceCallingOrSelfPermission( 11669 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11670 11671 boolean result = false; 11672 synchronized (mPackages) { 11673 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11674 } 11675 if (result) { 11676 scheduleWritePackageRestrictionsLocked(userId); 11677 } 11678 return result; 11679 } 11680 11681 @Override 11682 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11683 String packageName) { 11684 synchronized (mPackages) { 11685 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11686 } 11687 } 11688 11689 @Override 11690 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11691 if (TextUtils.isEmpty(packageName)) { 11692 return ParceledListSlice.emptyList(); 11693 } 11694 synchronized (mPackages) { 11695 PackageParser.Package pkg = mPackages.get(packageName); 11696 if (pkg == null || pkg.activities == null) { 11697 return ParceledListSlice.emptyList(); 11698 } 11699 final int count = pkg.activities.size(); 11700 ArrayList<IntentFilter> result = new ArrayList<>(); 11701 for (int n=0; n<count; n++) { 11702 PackageParser.Activity activity = pkg.activities.get(n); 11703 if (activity.intents != null && activity.intents.size() > 0) { 11704 result.addAll(activity.intents); 11705 } 11706 } 11707 return new ParceledListSlice<>(result); 11708 } 11709 } 11710 11711 @Override 11712 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11713 mContext.enforceCallingOrSelfPermission( 11714 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11715 11716 synchronized (mPackages) { 11717 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11718 if (packageName != null) { 11719 result |= updateIntentVerificationStatus(packageName, 11720 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11721 userId); 11722 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11723 packageName, userId); 11724 } 11725 return result; 11726 } 11727 } 11728 11729 @Override 11730 public String getDefaultBrowserPackageName(int userId) { 11731 synchronized (mPackages) { 11732 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11733 } 11734 } 11735 11736 /** 11737 * Get the "allow unknown sources" setting. 11738 * 11739 * @return the current "allow unknown sources" setting 11740 */ 11741 private int getUnknownSourcesSettings() { 11742 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11743 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11744 -1); 11745 } 11746 11747 @Override 11748 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11749 final int uid = Binder.getCallingUid(); 11750 // writer 11751 synchronized (mPackages) { 11752 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11753 if (targetPackageSetting == null) { 11754 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11755 } 11756 11757 PackageSetting installerPackageSetting; 11758 if (installerPackageName != null) { 11759 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11760 if (installerPackageSetting == null) { 11761 throw new IllegalArgumentException("Unknown installer package: " 11762 + installerPackageName); 11763 } 11764 } else { 11765 installerPackageSetting = null; 11766 } 11767 11768 Signature[] callerSignature; 11769 Object obj = mSettings.getUserIdLPr(uid); 11770 if (obj != null) { 11771 if (obj instanceof SharedUserSetting) { 11772 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11773 } else if (obj instanceof PackageSetting) { 11774 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11775 } else { 11776 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11777 } 11778 } else { 11779 throw new SecurityException("Unknown calling UID: " + uid); 11780 } 11781 11782 // Verify: can't set installerPackageName to a package that is 11783 // not signed with the same cert as the caller. 11784 if (installerPackageSetting != null) { 11785 if (compareSignatures(callerSignature, 11786 installerPackageSetting.signatures.mSignatures) 11787 != PackageManager.SIGNATURE_MATCH) { 11788 throw new SecurityException( 11789 "Caller does not have same cert as new installer package " 11790 + installerPackageName); 11791 } 11792 } 11793 11794 // Verify: if target already has an installer package, it must 11795 // be signed with the same cert as the caller. 11796 if (targetPackageSetting.installerPackageName != null) { 11797 PackageSetting setting = mSettings.mPackages.get( 11798 targetPackageSetting.installerPackageName); 11799 // If the currently set package isn't valid, then it's always 11800 // okay to change it. 11801 if (setting != null) { 11802 if (compareSignatures(callerSignature, 11803 setting.signatures.mSignatures) 11804 != PackageManager.SIGNATURE_MATCH) { 11805 throw new SecurityException( 11806 "Caller does not have same cert as old installer package " 11807 + targetPackageSetting.installerPackageName); 11808 } 11809 } 11810 } 11811 11812 // Okay! 11813 targetPackageSetting.installerPackageName = installerPackageName; 11814 if (installerPackageName != null) { 11815 mSettings.mInstallerPackages.add(installerPackageName); 11816 } 11817 scheduleWriteSettingsLocked(); 11818 } 11819 } 11820 11821 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11822 // Queue up an async operation since the package installation may take a little while. 11823 mHandler.post(new Runnable() { 11824 public void run() { 11825 mHandler.removeCallbacks(this); 11826 // Result object to be returned 11827 PackageInstalledInfo res = new PackageInstalledInfo(); 11828 res.setReturnCode(currentStatus); 11829 res.uid = -1; 11830 res.pkg = null; 11831 res.removedInfo = null; 11832 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11833 args.doPreInstall(res.returnCode); 11834 synchronized (mInstallLock) { 11835 installPackageTracedLI(args, res); 11836 } 11837 args.doPostInstall(res.returnCode, res.uid); 11838 } 11839 11840 // A restore should be performed at this point if (a) the install 11841 // succeeded, (b) the operation is not an update, and (c) the new 11842 // package has not opted out of backup participation. 11843 final boolean update = res.removedInfo != null 11844 && res.removedInfo.removedPackage != null; 11845 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11846 boolean doRestore = !update 11847 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11848 11849 // Set up the post-install work request bookkeeping. This will be used 11850 // and cleaned up by the post-install event handling regardless of whether 11851 // there's a restore pass performed. Token values are >= 1. 11852 int token; 11853 if (mNextInstallToken < 0) mNextInstallToken = 1; 11854 token = mNextInstallToken++; 11855 11856 PostInstallData data = new PostInstallData(args, res); 11857 mRunningInstalls.put(token, data); 11858 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11859 11860 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11861 // Pass responsibility to the Backup Manager. It will perform a 11862 // restore if appropriate, then pass responsibility back to the 11863 // Package Manager to run the post-install observer callbacks 11864 // and broadcasts. 11865 IBackupManager bm = IBackupManager.Stub.asInterface( 11866 ServiceManager.getService(Context.BACKUP_SERVICE)); 11867 if (bm != null) { 11868 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11869 + " to BM for possible restore"); 11870 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11871 try { 11872 // TODO: http://b/22388012 11873 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11874 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11875 } else { 11876 doRestore = false; 11877 } 11878 } catch (RemoteException e) { 11879 // can't happen; the backup manager is local 11880 } catch (Exception e) { 11881 Slog.e(TAG, "Exception trying to enqueue restore", e); 11882 doRestore = false; 11883 } 11884 } else { 11885 Slog.e(TAG, "Backup Manager not found!"); 11886 doRestore = false; 11887 } 11888 } 11889 11890 if (!doRestore) { 11891 // No restore possible, or the Backup Manager was mysteriously not 11892 // available -- just fire the post-install work request directly. 11893 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11894 11895 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11896 11897 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11898 mHandler.sendMessage(msg); 11899 } 11900 } 11901 }); 11902 } 11903 11904 private abstract class HandlerParams { 11905 private static final int MAX_RETRIES = 4; 11906 11907 /** 11908 * Number of times startCopy() has been attempted and had a non-fatal 11909 * error. 11910 */ 11911 private int mRetries = 0; 11912 11913 /** User handle for the user requesting the information or installation. */ 11914 private final UserHandle mUser; 11915 String traceMethod; 11916 int traceCookie; 11917 11918 HandlerParams(UserHandle user) { 11919 mUser = user; 11920 } 11921 11922 UserHandle getUser() { 11923 return mUser; 11924 } 11925 11926 HandlerParams setTraceMethod(String traceMethod) { 11927 this.traceMethod = traceMethod; 11928 return this; 11929 } 11930 11931 HandlerParams setTraceCookie(int traceCookie) { 11932 this.traceCookie = traceCookie; 11933 return this; 11934 } 11935 11936 final boolean startCopy() { 11937 boolean res; 11938 try { 11939 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11940 11941 if (++mRetries > MAX_RETRIES) { 11942 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11943 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11944 handleServiceError(); 11945 return false; 11946 } else { 11947 handleStartCopy(); 11948 res = true; 11949 } 11950 } catch (RemoteException e) { 11951 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11952 mHandler.sendEmptyMessage(MCS_RECONNECT); 11953 res = false; 11954 } 11955 handleReturnCode(); 11956 return res; 11957 } 11958 11959 final void serviceError() { 11960 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11961 handleServiceError(); 11962 handleReturnCode(); 11963 } 11964 11965 abstract void handleStartCopy() throws RemoteException; 11966 abstract void handleServiceError(); 11967 abstract void handleReturnCode(); 11968 } 11969 11970 class MeasureParams extends HandlerParams { 11971 private final PackageStats mStats; 11972 private boolean mSuccess; 11973 11974 private final IPackageStatsObserver mObserver; 11975 11976 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11977 super(new UserHandle(stats.userHandle)); 11978 mObserver = observer; 11979 mStats = stats; 11980 } 11981 11982 @Override 11983 public String toString() { 11984 return "MeasureParams{" 11985 + Integer.toHexString(System.identityHashCode(this)) 11986 + " " + mStats.packageName + "}"; 11987 } 11988 11989 @Override 11990 void handleStartCopy() throws RemoteException { 11991 synchronized (mInstallLock) { 11992 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 11993 } 11994 11995 if (mSuccess) { 11996 final boolean mounted; 11997 if (Environment.isExternalStorageEmulated()) { 11998 mounted = true; 11999 } else { 12000 final String status = Environment.getExternalStorageState(); 12001 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12002 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12003 } 12004 12005 if (mounted) { 12006 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12007 12008 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12009 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12010 12011 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12012 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12013 12014 // Always subtract cache size, since it's a subdirectory 12015 mStats.externalDataSize -= mStats.externalCacheSize; 12016 12017 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12018 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12019 12020 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12021 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12022 } 12023 } 12024 } 12025 12026 @Override 12027 void handleReturnCode() { 12028 if (mObserver != null) { 12029 try { 12030 mObserver.onGetStatsCompleted(mStats, mSuccess); 12031 } catch (RemoteException e) { 12032 Slog.i(TAG, "Observer no longer exists."); 12033 } 12034 } 12035 } 12036 12037 @Override 12038 void handleServiceError() { 12039 Slog.e(TAG, "Could not measure application " + mStats.packageName 12040 + " external storage"); 12041 } 12042 } 12043 12044 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12045 throws RemoteException { 12046 long result = 0; 12047 for (File path : paths) { 12048 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12049 } 12050 return result; 12051 } 12052 12053 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12054 for (File path : paths) { 12055 try { 12056 mcs.clearDirectory(path.getAbsolutePath()); 12057 } catch (RemoteException e) { 12058 } 12059 } 12060 } 12061 12062 static class OriginInfo { 12063 /** 12064 * Location where install is coming from, before it has been 12065 * copied/renamed into place. This could be a single monolithic APK 12066 * file, or a cluster directory. This location may be untrusted. 12067 */ 12068 final File file; 12069 final String cid; 12070 12071 /** 12072 * Flag indicating that {@link #file} or {@link #cid} has already been 12073 * staged, meaning downstream users don't need to defensively copy the 12074 * contents. 12075 */ 12076 final boolean staged; 12077 12078 /** 12079 * Flag indicating that {@link #file} or {@link #cid} is an already 12080 * installed app that is being moved. 12081 */ 12082 final boolean existing; 12083 12084 final String resolvedPath; 12085 final File resolvedFile; 12086 12087 static OriginInfo fromNothing() { 12088 return new OriginInfo(null, null, false, false); 12089 } 12090 12091 static OriginInfo fromUntrustedFile(File file) { 12092 return new OriginInfo(file, null, false, false); 12093 } 12094 12095 static OriginInfo fromExistingFile(File file) { 12096 return new OriginInfo(file, null, false, true); 12097 } 12098 12099 static OriginInfo fromStagedFile(File file) { 12100 return new OriginInfo(file, null, true, false); 12101 } 12102 12103 static OriginInfo fromStagedContainer(String cid) { 12104 return new OriginInfo(null, cid, true, false); 12105 } 12106 12107 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12108 this.file = file; 12109 this.cid = cid; 12110 this.staged = staged; 12111 this.existing = existing; 12112 12113 if (cid != null) { 12114 resolvedPath = PackageHelper.getSdDir(cid); 12115 resolvedFile = new File(resolvedPath); 12116 } else if (file != null) { 12117 resolvedPath = file.getAbsolutePath(); 12118 resolvedFile = file; 12119 } else { 12120 resolvedPath = null; 12121 resolvedFile = null; 12122 } 12123 } 12124 } 12125 12126 static class MoveInfo { 12127 final int moveId; 12128 final String fromUuid; 12129 final String toUuid; 12130 final String packageName; 12131 final String dataAppName; 12132 final int appId; 12133 final String seinfo; 12134 final int targetSdkVersion; 12135 12136 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12137 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12138 this.moveId = moveId; 12139 this.fromUuid = fromUuid; 12140 this.toUuid = toUuid; 12141 this.packageName = packageName; 12142 this.dataAppName = dataAppName; 12143 this.appId = appId; 12144 this.seinfo = seinfo; 12145 this.targetSdkVersion = targetSdkVersion; 12146 } 12147 } 12148 12149 static class VerificationInfo { 12150 /** A constant used to indicate that a uid value is not present. */ 12151 public static final int NO_UID = -1; 12152 12153 /** URI referencing where the package was downloaded from. */ 12154 final Uri originatingUri; 12155 12156 /** HTTP referrer URI associated with the originatingURI. */ 12157 final Uri referrer; 12158 12159 /** UID of the application that the install request originated from. */ 12160 final int originatingUid; 12161 12162 /** UID of application requesting the install */ 12163 final int installerUid; 12164 12165 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12166 this.originatingUri = originatingUri; 12167 this.referrer = referrer; 12168 this.originatingUid = originatingUid; 12169 this.installerUid = installerUid; 12170 } 12171 } 12172 12173 class InstallParams extends HandlerParams { 12174 final OriginInfo origin; 12175 final MoveInfo move; 12176 final IPackageInstallObserver2 observer; 12177 int installFlags; 12178 final String installerPackageName; 12179 final String volumeUuid; 12180 private InstallArgs mArgs; 12181 private int mRet; 12182 final String packageAbiOverride; 12183 final String[] grantedRuntimePermissions; 12184 final VerificationInfo verificationInfo; 12185 final Certificate[][] certificates; 12186 12187 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12188 int installFlags, String installerPackageName, String volumeUuid, 12189 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12190 String[] grantedPermissions, Certificate[][] certificates) { 12191 super(user); 12192 this.origin = origin; 12193 this.move = move; 12194 this.observer = observer; 12195 this.installFlags = installFlags; 12196 this.installerPackageName = installerPackageName; 12197 this.volumeUuid = volumeUuid; 12198 this.verificationInfo = verificationInfo; 12199 this.packageAbiOverride = packageAbiOverride; 12200 this.grantedRuntimePermissions = grantedPermissions; 12201 this.certificates = certificates; 12202 } 12203 12204 @Override 12205 public String toString() { 12206 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12207 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12208 } 12209 12210 private int installLocationPolicy(PackageInfoLite pkgLite) { 12211 String packageName = pkgLite.packageName; 12212 int installLocation = pkgLite.installLocation; 12213 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12214 // reader 12215 synchronized (mPackages) { 12216 // Currently installed package which the new package is attempting to replace or 12217 // null if no such package is installed. 12218 PackageParser.Package installedPkg = mPackages.get(packageName); 12219 // Package which currently owns the data which the new package will own if installed. 12220 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12221 // will be null whereas dataOwnerPkg will contain information about the package 12222 // which was uninstalled while keeping its data. 12223 PackageParser.Package dataOwnerPkg = installedPkg; 12224 if (dataOwnerPkg == null) { 12225 PackageSetting ps = mSettings.mPackages.get(packageName); 12226 if (ps != null) { 12227 dataOwnerPkg = ps.pkg; 12228 } 12229 } 12230 12231 if (dataOwnerPkg != null) { 12232 // If installed, the package will get access to data left on the device by its 12233 // predecessor. As a security measure, this is permited only if this is not a 12234 // version downgrade or if the predecessor package is marked as debuggable and 12235 // a downgrade is explicitly requested. 12236 // 12237 // On debuggable platform builds, downgrades are permitted even for 12238 // non-debuggable packages to make testing easier. Debuggable platform builds do 12239 // not offer security guarantees and thus it's OK to disable some security 12240 // mechanisms to make debugging/testing easier on those builds. However, even on 12241 // debuggable builds downgrades of packages are permitted only if requested via 12242 // installFlags. This is because we aim to keep the behavior of debuggable 12243 // platform builds as close as possible to the behavior of non-debuggable 12244 // platform builds. 12245 final boolean downgradeRequested = 12246 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12247 final boolean packageDebuggable = 12248 (dataOwnerPkg.applicationInfo.flags 12249 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12250 final boolean downgradePermitted = 12251 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12252 if (!downgradePermitted) { 12253 try { 12254 checkDowngrade(dataOwnerPkg, pkgLite); 12255 } catch (PackageManagerException e) { 12256 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12257 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12258 } 12259 } 12260 } 12261 12262 if (installedPkg != null) { 12263 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12264 // Check for updated system application. 12265 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12266 if (onSd) { 12267 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12268 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12269 } 12270 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12271 } else { 12272 if (onSd) { 12273 // Install flag overrides everything. 12274 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12275 } 12276 // If current upgrade specifies particular preference 12277 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12278 // Application explicitly specified internal. 12279 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12280 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12281 // App explictly prefers external. Let policy decide 12282 } else { 12283 // Prefer previous location 12284 if (isExternal(installedPkg)) { 12285 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12286 } 12287 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12288 } 12289 } 12290 } else { 12291 // Invalid install. Return error code 12292 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12293 } 12294 } 12295 } 12296 // All the special cases have been taken care of. 12297 // Return result based on recommended install location. 12298 if (onSd) { 12299 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12300 } 12301 return pkgLite.recommendedInstallLocation; 12302 } 12303 12304 /* 12305 * Invoke remote method to get package information and install 12306 * location values. Override install location based on default 12307 * policy if needed and then create install arguments based 12308 * on the install location. 12309 */ 12310 public void handleStartCopy() throws RemoteException { 12311 int ret = PackageManager.INSTALL_SUCCEEDED; 12312 12313 // If we're already staged, we've firmly committed to an install location 12314 if (origin.staged) { 12315 if (origin.file != null) { 12316 installFlags |= PackageManager.INSTALL_INTERNAL; 12317 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12318 } else if (origin.cid != null) { 12319 installFlags |= PackageManager.INSTALL_EXTERNAL; 12320 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12321 } else { 12322 throw new IllegalStateException("Invalid stage location"); 12323 } 12324 } 12325 12326 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12327 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12328 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12329 PackageInfoLite pkgLite = null; 12330 12331 if (onInt && onSd) { 12332 // Check if both bits are set. 12333 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12334 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12335 } else if (onSd && ephemeral) { 12336 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12337 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12338 } else { 12339 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12340 packageAbiOverride); 12341 12342 if (DEBUG_EPHEMERAL && ephemeral) { 12343 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12344 } 12345 12346 /* 12347 * If we have too little free space, try to free cache 12348 * before giving up. 12349 */ 12350 if (!origin.staged && pkgLite.recommendedInstallLocation 12351 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12352 // TODO: focus freeing disk space on the target device 12353 final StorageManager storage = StorageManager.from(mContext); 12354 final long lowThreshold = storage.getStorageLowBytes( 12355 Environment.getDataDirectory()); 12356 12357 final long sizeBytes = mContainerService.calculateInstalledSize( 12358 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12359 12360 try { 12361 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12362 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12363 installFlags, packageAbiOverride); 12364 } catch (InstallerException e) { 12365 Slog.w(TAG, "Failed to free cache", e); 12366 } 12367 12368 /* 12369 * The cache free must have deleted the file we 12370 * downloaded to install. 12371 * 12372 * TODO: fix the "freeCache" call to not delete 12373 * the file we care about. 12374 */ 12375 if (pkgLite.recommendedInstallLocation 12376 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12377 pkgLite.recommendedInstallLocation 12378 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12379 } 12380 } 12381 } 12382 12383 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12384 int loc = pkgLite.recommendedInstallLocation; 12385 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12386 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12387 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12388 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12389 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12390 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12391 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12392 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12393 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12394 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12395 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12396 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12397 } else { 12398 // Override with defaults if needed. 12399 loc = installLocationPolicy(pkgLite); 12400 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12401 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12402 } else if (!onSd && !onInt) { 12403 // Override install location with flags 12404 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12405 // Set the flag to install on external media. 12406 installFlags |= PackageManager.INSTALL_EXTERNAL; 12407 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12408 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12409 if (DEBUG_EPHEMERAL) { 12410 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12411 } 12412 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12413 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12414 |PackageManager.INSTALL_INTERNAL); 12415 } else { 12416 // Make sure the flag for installing on external 12417 // media is unset 12418 installFlags |= PackageManager.INSTALL_INTERNAL; 12419 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12420 } 12421 } 12422 } 12423 } 12424 12425 final InstallArgs args = createInstallArgs(this); 12426 mArgs = args; 12427 12428 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12429 // TODO: http://b/22976637 12430 // Apps installed for "all" users use the device owner to verify the app 12431 UserHandle verifierUser = getUser(); 12432 if (verifierUser == UserHandle.ALL) { 12433 verifierUser = UserHandle.SYSTEM; 12434 } 12435 12436 /* 12437 * Determine if we have any installed package verifiers. If we 12438 * do, then we'll defer to them to verify the packages. 12439 */ 12440 final int requiredUid = mRequiredVerifierPackage == null ? -1 12441 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12442 verifierUser.getIdentifier()); 12443 if (!origin.existing && requiredUid != -1 12444 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12445 final Intent verification = new Intent( 12446 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12447 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12448 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12449 PACKAGE_MIME_TYPE); 12450 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12451 12452 // Query all live verifiers based on current user state 12453 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12454 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12455 12456 if (DEBUG_VERIFY) { 12457 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12458 + verification.toString() + " with " + pkgLite.verifiers.length 12459 + " optional verifiers"); 12460 } 12461 12462 final int verificationId = mPendingVerificationToken++; 12463 12464 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12465 12466 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12467 installerPackageName); 12468 12469 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12470 installFlags); 12471 12472 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12473 pkgLite.packageName); 12474 12475 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12476 pkgLite.versionCode); 12477 12478 if (verificationInfo != null) { 12479 if (verificationInfo.originatingUri != null) { 12480 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12481 verificationInfo.originatingUri); 12482 } 12483 if (verificationInfo.referrer != null) { 12484 verification.putExtra(Intent.EXTRA_REFERRER, 12485 verificationInfo.referrer); 12486 } 12487 if (verificationInfo.originatingUid >= 0) { 12488 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12489 verificationInfo.originatingUid); 12490 } 12491 if (verificationInfo.installerUid >= 0) { 12492 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12493 verificationInfo.installerUid); 12494 } 12495 } 12496 12497 final PackageVerificationState verificationState = new PackageVerificationState( 12498 requiredUid, args); 12499 12500 mPendingVerification.append(verificationId, verificationState); 12501 12502 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12503 receivers, verificationState); 12504 12505 /* 12506 * If any sufficient verifiers were listed in the package 12507 * manifest, attempt to ask them. 12508 */ 12509 if (sufficientVerifiers != null) { 12510 final int N = sufficientVerifiers.size(); 12511 if (N == 0) { 12512 Slog.i(TAG, "Additional verifiers required, but none installed."); 12513 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12514 } else { 12515 for (int i = 0; i < N; i++) { 12516 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12517 12518 final Intent sufficientIntent = new Intent(verification); 12519 sufficientIntent.setComponent(verifierComponent); 12520 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12521 } 12522 } 12523 } 12524 12525 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12526 mRequiredVerifierPackage, receivers); 12527 if (ret == PackageManager.INSTALL_SUCCEEDED 12528 && mRequiredVerifierPackage != null) { 12529 Trace.asyncTraceBegin( 12530 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12531 /* 12532 * Send the intent to the required verification agent, 12533 * but only start the verification timeout after the 12534 * target BroadcastReceivers have run. 12535 */ 12536 verification.setComponent(requiredVerifierComponent); 12537 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12538 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12539 new BroadcastReceiver() { 12540 @Override 12541 public void onReceive(Context context, Intent intent) { 12542 final Message msg = mHandler 12543 .obtainMessage(CHECK_PENDING_VERIFICATION); 12544 msg.arg1 = verificationId; 12545 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12546 } 12547 }, null, 0, null, null); 12548 12549 /* 12550 * We don't want the copy to proceed until verification 12551 * succeeds, so null out this field. 12552 */ 12553 mArgs = null; 12554 } 12555 } else { 12556 /* 12557 * No package verification is enabled, so immediately start 12558 * the remote call to initiate copy using temporary file. 12559 */ 12560 ret = args.copyApk(mContainerService, true); 12561 } 12562 } 12563 12564 mRet = ret; 12565 } 12566 12567 @Override 12568 void handleReturnCode() { 12569 // If mArgs is null, then MCS couldn't be reached. When it 12570 // reconnects, it will try again to install. At that point, this 12571 // will succeed. 12572 if (mArgs != null) { 12573 processPendingInstall(mArgs, mRet); 12574 } 12575 } 12576 12577 @Override 12578 void handleServiceError() { 12579 mArgs = createInstallArgs(this); 12580 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12581 } 12582 12583 public boolean isForwardLocked() { 12584 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12585 } 12586 } 12587 12588 /** 12589 * Used during creation of InstallArgs 12590 * 12591 * @param installFlags package installation flags 12592 * @return true if should be installed on external storage 12593 */ 12594 private static boolean installOnExternalAsec(int installFlags) { 12595 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12596 return false; 12597 } 12598 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12599 return true; 12600 } 12601 return false; 12602 } 12603 12604 /** 12605 * Used during creation of InstallArgs 12606 * 12607 * @param installFlags package installation flags 12608 * @return true if should be installed as forward locked 12609 */ 12610 private static boolean installForwardLocked(int installFlags) { 12611 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12612 } 12613 12614 private InstallArgs createInstallArgs(InstallParams params) { 12615 if (params.move != null) { 12616 return new MoveInstallArgs(params); 12617 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12618 return new AsecInstallArgs(params); 12619 } else { 12620 return new FileInstallArgs(params); 12621 } 12622 } 12623 12624 /** 12625 * Create args that describe an existing installed package. Typically used 12626 * when cleaning up old installs, or used as a move source. 12627 */ 12628 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12629 String resourcePath, String[] instructionSets) { 12630 final boolean isInAsec; 12631 if (installOnExternalAsec(installFlags)) { 12632 /* Apps on SD card are always in ASEC containers. */ 12633 isInAsec = true; 12634 } else if (installForwardLocked(installFlags) 12635 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12636 /* 12637 * Forward-locked apps are only in ASEC containers if they're the 12638 * new style 12639 */ 12640 isInAsec = true; 12641 } else { 12642 isInAsec = false; 12643 } 12644 12645 if (isInAsec) { 12646 return new AsecInstallArgs(codePath, instructionSets, 12647 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12648 } else { 12649 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12650 } 12651 } 12652 12653 static abstract class InstallArgs { 12654 /** @see InstallParams#origin */ 12655 final OriginInfo origin; 12656 /** @see InstallParams#move */ 12657 final MoveInfo move; 12658 12659 final IPackageInstallObserver2 observer; 12660 // Always refers to PackageManager flags only 12661 final int installFlags; 12662 final String installerPackageName; 12663 final String volumeUuid; 12664 final UserHandle user; 12665 final String abiOverride; 12666 final String[] installGrantPermissions; 12667 /** If non-null, drop an async trace when the install completes */ 12668 final String traceMethod; 12669 final int traceCookie; 12670 final Certificate[][] certificates; 12671 12672 // The list of instruction sets supported by this app. This is currently 12673 // only used during the rmdex() phase to clean up resources. We can get rid of this 12674 // if we move dex files under the common app path. 12675 /* nullable */ String[] instructionSets; 12676 12677 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12678 int installFlags, String installerPackageName, String volumeUuid, 12679 UserHandle user, String[] instructionSets, 12680 String abiOverride, String[] installGrantPermissions, 12681 String traceMethod, int traceCookie, Certificate[][] certificates) { 12682 this.origin = origin; 12683 this.move = move; 12684 this.installFlags = installFlags; 12685 this.observer = observer; 12686 this.installerPackageName = installerPackageName; 12687 this.volumeUuid = volumeUuid; 12688 this.user = user; 12689 this.instructionSets = instructionSets; 12690 this.abiOverride = abiOverride; 12691 this.installGrantPermissions = installGrantPermissions; 12692 this.traceMethod = traceMethod; 12693 this.traceCookie = traceCookie; 12694 this.certificates = certificates; 12695 } 12696 12697 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12698 abstract int doPreInstall(int status); 12699 12700 /** 12701 * Rename package into final resting place. All paths on the given 12702 * scanned package should be updated to reflect the rename. 12703 */ 12704 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12705 abstract int doPostInstall(int status, int uid); 12706 12707 /** @see PackageSettingBase#codePathString */ 12708 abstract String getCodePath(); 12709 /** @see PackageSettingBase#resourcePathString */ 12710 abstract String getResourcePath(); 12711 12712 // Need installer lock especially for dex file removal. 12713 abstract void cleanUpResourcesLI(); 12714 abstract boolean doPostDeleteLI(boolean delete); 12715 12716 /** 12717 * Called before the source arguments are copied. This is used mostly 12718 * for MoveParams when it needs to read the source file to put it in the 12719 * destination. 12720 */ 12721 int doPreCopy() { 12722 return PackageManager.INSTALL_SUCCEEDED; 12723 } 12724 12725 /** 12726 * Called after the source arguments are copied. This is used mostly for 12727 * MoveParams when it needs to read the source file to put it in the 12728 * destination. 12729 */ 12730 int doPostCopy(int uid) { 12731 return PackageManager.INSTALL_SUCCEEDED; 12732 } 12733 12734 protected boolean isFwdLocked() { 12735 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12736 } 12737 12738 protected boolean isExternalAsec() { 12739 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12740 } 12741 12742 protected boolean isEphemeral() { 12743 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12744 } 12745 12746 UserHandle getUser() { 12747 return user; 12748 } 12749 } 12750 12751 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12752 if (!allCodePaths.isEmpty()) { 12753 if (instructionSets == null) { 12754 throw new IllegalStateException("instructionSet == null"); 12755 } 12756 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12757 for (String codePath : allCodePaths) { 12758 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12759 try { 12760 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12761 } catch (InstallerException ignored) { 12762 } 12763 } 12764 } 12765 } 12766 } 12767 12768 /** 12769 * Logic to handle installation of non-ASEC applications, including copying 12770 * and renaming logic. 12771 */ 12772 class FileInstallArgs extends InstallArgs { 12773 private File codeFile; 12774 private File resourceFile; 12775 12776 // Example topology: 12777 // /data/app/com.example/base.apk 12778 // /data/app/com.example/split_foo.apk 12779 // /data/app/com.example/lib/arm/libfoo.so 12780 // /data/app/com.example/lib/arm64/libfoo.so 12781 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12782 12783 /** New install */ 12784 FileInstallArgs(InstallParams params) { 12785 super(params.origin, params.move, params.observer, params.installFlags, 12786 params.installerPackageName, params.volumeUuid, 12787 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12788 params.grantedRuntimePermissions, 12789 params.traceMethod, params.traceCookie, params.certificates); 12790 if (isFwdLocked()) { 12791 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12792 } 12793 } 12794 12795 /** Existing install */ 12796 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12797 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12798 null, null, null, 0, null /*certificates*/); 12799 this.codeFile = (codePath != null) ? new File(codePath) : null; 12800 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12801 } 12802 12803 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12804 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12805 try { 12806 return doCopyApk(imcs, temp); 12807 } finally { 12808 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12809 } 12810 } 12811 12812 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12813 if (origin.staged) { 12814 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12815 codeFile = origin.file; 12816 resourceFile = origin.file; 12817 return PackageManager.INSTALL_SUCCEEDED; 12818 } 12819 12820 try { 12821 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12822 final File tempDir = 12823 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12824 codeFile = tempDir; 12825 resourceFile = tempDir; 12826 } catch (IOException e) { 12827 Slog.w(TAG, "Failed to create copy file: " + e); 12828 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12829 } 12830 12831 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12832 @Override 12833 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12834 if (!FileUtils.isValidExtFilename(name)) { 12835 throw new IllegalArgumentException("Invalid filename: " + name); 12836 } 12837 try { 12838 final File file = new File(codeFile, name); 12839 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12840 O_RDWR | O_CREAT, 0644); 12841 Os.chmod(file.getAbsolutePath(), 0644); 12842 return new ParcelFileDescriptor(fd); 12843 } catch (ErrnoException e) { 12844 throw new RemoteException("Failed to open: " + e.getMessage()); 12845 } 12846 } 12847 }; 12848 12849 int ret = PackageManager.INSTALL_SUCCEEDED; 12850 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12851 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12852 Slog.e(TAG, "Failed to copy package"); 12853 return ret; 12854 } 12855 12856 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12857 NativeLibraryHelper.Handle handle = null; 12858 try { 12859 handle = NativeLibraryHelper.Handle.create(codeFile); 12860 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12861 abiOverride); 12862 } catch (IOException e) { 12863 Slog.e(TAG, "Copying native libraries failed", e); 12864 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12865 } finally { 12866 IoUtils.closeQuietly(handle); 12867 } 12868 12869 return ret; 12870 } 12871 12872 int doPreInstall(int status) { 12873 if (status != PackageManager.INSTALL_SUCCEEDED) { 12874 cleanUp(); 12875 } 12876 return status; 12877 } 12878 12879 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12880 if (status != PackageManager.INSTALL_SUCCEEDED) { 12881 cleanUp(); 12882 return false; 12883 } 12884 12885 final File targetDir = codeFile.getParentFile(); 12886 final File beforeCodeFile = codeFile; 12887 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12888 12889 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12890 try { 12891 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12892 } catch (ErrnoException e) { 12893 Slog.w(TAG, "Failed to rename", e); 12894 return false; 12895 } 12896 12897 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12898 Slog.w(TAG, "Failed to restorecon"); 12899 return false; 12900 } 12901 12902 // Reflect the rename internally 12903 codeFile = afterCodeFile; 12904 resourceFile = afterCodeFile; 12905 12906 // Reflect the rename in scanned details 12907 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12908 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12909 afterCodeFile, pkg.baseCodePath)); 12910 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12911 afterCodeFile, pkg.splitCodePaths)); 12912 12913 // Reflect the rename in app info 12914 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12915 pkg.setApplicationInfoCodePath(pkg.codePath); 12916 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12917 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12918 pkg.setApplicationInfoResourcePath(pkg.codePath); 12919 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12920 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12921 12922 return true; 12923 } 12924 12925 int doPostInstall(int status, int uid) { 12926 if (status != PackageManager.INSTALL_SUCCEEDED) { 12927 cleanUp(); 12928 } 12929 return status; 12930 } 12931 12932 @Override 12933 String getCodePath() { 12934 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12935 } 12936 12937 @Override 12938 String getResourcePath() { 12939 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12940 } 12941 12942 private boolean cleanUp() { 12943 if (codeFile == null || !codeFile.exists()) { 12944 return false; 12945 } 12946 12947 removeCodePathLI(codeFile); 12948 12949 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12950 resourceFile.delete(); 12951 } 12952 12953 return true; 12954 } 12955 12956 void cleanUpResourcesLI() { 12957 // Try enumerating all code paths before deleting 12958 List<String> allCodePaths = Collections.EMPTY_LIST; 12959 if (codeFile != null && codeFile.exists()) { 12960 try { 12961 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12962 allCodePaths = pkg.getAllCodePaths(); 12963 } catch (PackageParserException e) { 12964 // Ignored; we tried our best 12965 } 12966 } 12967 12968 cleanUp(); 12969 removeDexFiles(allCodePaths, instructionSets); 12970 } 12971 12972 boolean doPostDeleteLI(boolean delete) { 12973 // XXX err, shouldn't we respect the delete flag? 12974 cleanUpResourcesLI(); 12975 return true; 12976 } 12977 } 12978 12979 private boolean isAsecExternal(String cid) { 12980 final String asecPath = PackageHelper.getSdFilesystem(cid); 12981 return !asecPath.startsWith(mAsecInternalPath); 12982 } 12983 12984 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12985 PackageManagerException { 12986 if (copyRet < 0) { 12987 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12988 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12989 throw new PackageManagerException(copyRet, message); 12990 } 12991 } 12992 } 12993 12994 /** 12995 * Extract the MountService "container ID" from the full code path of an 12996 * .apk. 12997 */ 12998 static String cidFromCodePath(String fullCodePath) { 12999 int eidx = fullCodePath.lastIndexOf("/"); 13000 String subStr1 = fullCodePath.substring(0, eidx); 13001 int sidx = subStr1.lastIndexOf("/"); 13002 return subStr1.substring(sidx+1, eidx); 13003 } 13004 13005 /** 13006 * Logic to handle installation of ASEC applications, including copying and 13007 * renaming logic. 13008 */ 13009 class AsecInstallArgs extends InstallArgs { 13010 static final String RES_FILE_NAME = "pkg.apk"; 13011 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13012 13013 String cid; 13014 String packagePath; 13015 String resourcePath; 13016 13017 /** New install */ 13018 AsecInstallArgs(InstallParams params) { 13019 super(params.origin, params.move, params.observer, params.installFlags, 13020 params.installerPackageName, params.volumeUuid, 13021 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13022 params.grantedRuntimePermissions, 13023 params.traceMethod, params.traceCookie, params.certificates); 13024 } 13025 13026 /** Existing install */ 13027 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13028 boolean isExternal, boolean isForwardLocked) { 13029 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13030 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13031 instructionSets, null, null, null, 0, null /*certificates*/); 13032 // Hackily pretend we're still looking at a full code path 13033 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13034 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13035 } 13036 13037 // Extract cid from fullCodePath 13038 int eidx = fullCodePath.lastIndexOf("/"); 13039 String subStr1 = fullCodePath.substring(0, eidx); 13040 int sidx = subStr1.lastIndexOf("/"); 13041 cid = subStr1.substring(sidx+1, eidx); 13042 setMountPath(subStr1); 13043 } 13044 13045 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13046 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13047 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13048 instructionSets, null, null, null, 0, null /*certificates*/); 13049 this.cid = cid; 13050 setMountPath(PackageHelper.getSdDir(cid)); 13051 } 13052 13053 void createCopyFile() { 13054 cid = mInstallerService.allocateExternalStageCidLegacy(); 13055 } 13056 13057 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13058 if (origin.staged && origin.cid != null) { 13059 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13060 cid = origin.cid; 13061 setMountPath(PackageHelper.getSdDir(cid)); 13062 return PackageManager.INSTALL_SUCCEEDED; 13063 } 13064 13065 if (temp) { 13066 createCopyFile(); 13067 } else { 13068 /* 13069 * Pre-emptively destroy the container since it's destroyed if 13070 * copying fails due to it existing anyway. 13071 */ 13072 PackageHelper.destroySdDir(cid); 13073 } 13074 13075 final String newMountPath = imcs.copyPackageToContainer( 13076 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13077 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13078 13079 if (newMountPath != null) { 13080 setMountPath(newMountPath); 13081 return PackageManager.INSTALL_SUCCEEDED; 13082 } else { 13083 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13084 } 13085 } 13086 13087 @Override 13088 String getCodePath() { 13089 return packagePath; 13090 } 13091 13092 @Override 13093 String getResourcePath() { 13094 return resourcePath; 13095 } 13096 13097 int doPreInstall(int status) { 13098 if (status != PackageManager.INSTALL_SUCCEEDED) { 13099 // Destroy container 13100 PackageHelper.destroySdDir(cid); 13101 } else { 13102 boolean mounted = PackageHelper.isContainerMounted(cid); 13103 if (!mounted) { 13104 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13105 Process.SYSTEM_UID); 13106 if (newMountPath != null) { 13107 setMountPath(newMountPath); 13108 } else { 13109 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13110 } 13111 } 13112 } 13113 return status; 13114 } 13115 13116 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13117 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13118 String newMountPath = null; 13119 if (PackageHelper.isContainerMounted(cid)) { 13120 // Unmount the container 13121 if (!PackageHelper.unMountSdDir(cid)) { 13122 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13123 return false; 13124 } 13125 } 13126 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13127 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13128 " which might be stale. Will try to clean up."); 13129 // Clean up the stale container and proceed to recreate. 13130 if (!PackageHelper.destroySdDir(newCacheId)) { 13131 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13132 return false; 13133 } 13134 // Successfully cleaned up stale container. Try to rename again. 13135 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13136 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13137 + " inspite of cleaning it up."); 13138 return false; 13139 } 13140 } 13141 if (!PackageHelper.isContainerMounted(newCacheId)) { 13142 Slog.w(TAG, "Mounting container " + newCacheId); 13143 newMountPath = PackageHelper.mountSdDir(newCacheId, 13144 getEncryptKey(), Process.SYSTEM_UID); 13145 } else { 13146 newMountPath = PackageHelper.getSdDir(newCacheId); 13147 } 13148 if (newMountPath == null) { 13149 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13150 return false; 13151 } 13152 Log.i(TAG, "Succesfully renamed " + cid + 13153 " to " + newCacheId + 13154 " at new path: " + newMountPath); 13155 cid = newCacheId; 13156 13157 final File beforeCodeFile = new File(packagePath); 13158 setMountPath(newMountPath); 13159 final File afterCodeFile = new File(packagePath); 13160 13161 // Reflect the rename in scanned details 13162 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13163 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13164 afterCodeFile, pkg.baseCodePath)); 13165 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13166 afterCodeFile, pkg.splitCodePaths)); 13167 13168 // Reflect the rename in app info 13169 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13170 pkg.setApplicationInfoCodePath(pkg.codePath); 13171 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13172 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13173 pkg.setApplicationInfoResourcePath(pkg.codePath); 13174 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13175 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13176 13177 return true; 13178 } 13179 13180 private void setMountPath(String mountPath) { 13181 final File mountFile = new File(mountPath); 13182 13183 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13184 if (monolithicFile.exists()) { 13185 packagePath = monolithicFile.getAbsolutePath(); 13186 if (isFwdLocked()) { 13187 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13188 } else { 13189 resourcePath = packagePath; 13190 } 13191 } else { 13192 packagePath = mountFile.getAbsolutePath(); 13193 resourcePath = packagePath; 13194 } 13195 } 13196 13197 int doPostInstall(int status, int uid) { 13198 if (status != PackageManager.INSTALL_SUCCEEDED) { 13199 cleanUp(); 13200 } else { 13201 final int groupOwner; 13202 final String protectedFile; 13203 if (isFwdLocked()) { 13204 groupOwner = UserHandle.getSharedAppGid(uid); 13205 protectedFile = RES_FILE_NAME; 13206 } else { 13207 groupOwner = -1; 13208 protectedFile = null; 13209 } 13210 13211 if (uid < Process.FIRST_APPLICATION_UID 13212 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13213 Slog.e(TAG, "Failed to finalize " + cid); 13214 PackageHelper.destroySdDir(cid); 13215 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13216 } 13217 13218 boolean mounted = PackageHelper.isContainerMounted(cid); 13219 if (!mounted) { 13220 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13221 } 13222 } 13223 return status; 13224 } 13225 13226 private void cleanUp() { 13227 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13228 13229 // Destroy secure container 13230 PackageHelper.destroySdDir(cid); 13231 } 13232 13233 private List<String> getAllCodePaths() { 13234 final File codeFile = new File(getCodePath()); 13235 if (codeFile != null && codeFile.exists()) { 13236 try { 13237 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13238 return pkg.getAllCodePaths(); 13239 } catch (PackageParserException e) { 13240 // Ignored; we tried our best 13241 } 13242 } 13243 return Collections.EMPTY_LIST; 13244 } 13245 13246 void cleanUpResourcesLI() { 13247 // Enumerate all code paths before deleting 13248 cleanUpResourcesLI(getAllCodePaths()); 13249 } 13250 13251 private void cleanUpResourcesLI(List<String> allCodePaths) { 13252 cleanUp(); 13253 removeDexFiles(allCodePaths, instructionSets); 13254 } 13255 13256 String getPackageName() { 13257 return getAsecPackageName(cid); 13258 } 13259 13260 boolean doPostDeleteLI(boolean delete) { 13261 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13262 final List<String> allCodePaths = getAllCodePaths(); 13263 boolean mounted = PackageHelper.isContainerMounted(cid); 13264 if (mounted) { 13265 // Unmount first 13266 if (PackageHelper.unMountSdDir(cid)) { 13267 mounted = false; 13268 } 13269 } 13270 if (!mounted && delete) { 13271 cleanUpResourcesLI(allCodePaths); 13272 } 13273 return !mounted; 13274 } 13275 13276 @Override 13277 int doPreCopy() { 13278 if (isFwdLocked()) { 13279 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13280 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13281 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13282 } 13283 } 13284 13285 return PackageManager.INSTALL_SUCCEEDED; 13286 } 13287 13288 @Override 13289 int doPostCopy(int uid) { 13290 if (isFwdLocked()) { 13291 if (uid < Process.FIRST_APPLICATION_UID 13292 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13293 RES_FILE_NAME)) { 13294 Slog.e(TAG, "Failed to finalize " + cid); 13295 PackageHelper.destroySdDir(cid); 13296 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13297 } 13298 } 13299 13300 return PackageManager.INSTALL_SUCCEEDED; 13301 } 13302 } 13303 13304 /** 13305 * Logic to handle movement of existing installed applications. 13306 */ 13307 class MoveInstallArgs extends InstallArgs { 13308 private File codeFile; 13309 private File resourceFile; 13310 13311 /** New install */ 13312 MoveInstallArgs(InstallParams params) { 13313 super(params.origin, params.move, params.observer, params.installFlags, 13314 params.installerPackageName, params.volumeUuid, 13315 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13316 params.grantedRuntimePermissions, 13317 params.traceMethod, params.traceCookie, params.certificates); 13318 } 13319 13320 int copyApk(IMediaContainerService imcs, boolean temp) { 13321 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13322 + move.fromUuid + " to " + move.toUuid); 13323 synchronized (mInstaller) { 13324 try { 13325 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13326 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13327 } catch (InstallerException e) { 13328 Slog.w(TAG, "Failed to move app", e); 13329 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13330 } 13331 } 13332 13333 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13334 resourceFile = codeFile; 13335 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13336 13337 return PackageManager.INSTALL_SUCCEEDED; 13338 } 13339 13340 int doPreInstall(int status) { 13341 if (status != PackageManager.INSTALL_SUCCEEDED) { 13342 cleanUp(move.toUuid); 13343 } 13344 return status; 13345 } 13346 13347 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13348 if (status != PackageManager.INSTALL_SUCCEEDED) { 13349 cleanUp(move.toUuid); 13350 return false; 13351 } 13352 13353 // Reflect the move in app info 13354 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13355 pkg.setApplicationInfoCodePath(pkg.codePath); 13356 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13357 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13358 pkg.setApplicationInfoResourcePath(pkg.codePath); 13359 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13360 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13361 13362 return true; 13363 } 13364 13365 int doPostInstall(int status, int uid) { 13366 if (status == PackageManager.INSTALL_SUCCEEDED) { 13367 cleanUp(move.fromUuid); 13368 } else { 13369 cleanUp(move.toUuid); 13370 } 13371 return status; 13372 } 13373 13374 @Override 13375 String getCodePath() { 13376 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13377 } 13378 13379 @Override 13380 String getResourcePath() { 13381 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13382 } 13383 13384 private boolean cleanUp(String volumeUuid) { 13385 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13386 move.dataAppName); 13387 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13388 synchronized (mInstallLock) { 13389 // Clean up both app data and code 13390 // All package moves are frozen until finished 13391 try { 13392 mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL, 13393 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13394 } catch (InstallerException e) { 13395 Slog.w(TAG, String.valueOf(e)); 13396 } 13397 removeCodePathLI(codeFile); 13398 } 13399 return true; 13400 } 13401 13402 void cleanUpResourcesLI() { 13403 throw new UnsupportedOperationException(); 13404 } 13405 13406 boolean doPostDeleteLI(boolean delete) { 13407 throw new UnsupportedOperationException(); 13408 } 13409 } 13410 13411 static String getAsecPackageName(String packageCid) { 13412 int idx = packageCid.lastIndexOf("-"); 13413 if (idx == -1) { 13414 return packageCid; 13415 } 13416 return packageCid.substring(0, idx); 13417 } 13418 13419 // Utility method used to create code paths based on package name and available index. 13420 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13421 String idxStr = ""; 13422 int idx = 1; 13423 // Fall back to default value of idx=1 if prefix is not 13424 // part of oldCodePath 13425 if (oldCodePath != null) { 13426 String subStr = oldCodePath; 13427 // Drop the suffix right away 13428 if (suffix != null && subStr.endsWith(suffix)) { 13429 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13430 } 13431 // If oldCodePath already contains prefix find out the 13432 // ending index to either increment or decrement. 13433 int sidx = subStr.lastIndexOf(prefix); 13434 if (sidx != -1) { 13435 subStr = subStr.substring(sidx + prefix.length()); 13436 if (subStr != null) { 13437 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13438 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13439 } 13440 try { 13441 idx = Integer.parseInt(subStr); 13442 if (idx <= 1) { 13443 idx++; 13444 } else { 13445 idx--; 13446 } 13447 } catch(NumberFormatException e) { 13448 } 13449 } 13450 } 13451 } 13452 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13453 return prefix + idxStr; 13454 } 13455 13456 private File getNextCodePath(File targetDir, String packageName) { 13457 int suffix = 1; 13458 File result; 13459 do { 13460 result = new File(targetDir, packageName + "-" + suffix); 13461 suffix++; 13462 } while (result.exists()); 13463 return result; 13464 } 13465 13466 // Utility method that returns the relative package path with respect 13467 // to the installation directory. Like say for /data/data/com.test-1.apk 13468 // string com.test-1 is returned. 13469 static String deriveCodePathName(String codePath) { 13470 if (codePath == null) { 13471 return null; 13472 } 13473 final File codeFile = new File(codePath); 13474 final String name = codeFile.getName(); 13475 if (codeFile.isDirectory()) { 13476 return name; 13477 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13478 final int lastDot = name.lastIndexOf('.'); 13479 return name.substring(0, lastDot); 13480 } else { 13481 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13482 return null; 13483 } 13484 } 13485 13486 static class PackageInstalledInfo { 13487 String name; 13488 int uid; 13489 // The set of users that originally had this package installed. 13490 int[] origUsers; 13491 // The set of users that now have this package installed. 13492 int[] newUsers; 13493 PackageParser.Package pkg; 13494 int returnCode; 13495 String returnMsg; 13496 PackageRemovedInfo removedInfo; 13497 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13498 13499 public void setError(int code, String msg) { 13500 setReturnCode(code); 13501 setReturnMessage(msg); 13502 Slog.w(TAG, msg); 13503 } 13504 13505 public void setError(String msg, PackageParserException e) { 13506 setReturnCode(e.error); 13507 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13508 Slog.w(TAG, msg, e); 13509 } 13510 13511 public void setError(String msg, PackageManagerException e) { 13512 returnCode = e.error; 13513 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13514 Slog.w(TAG, msg, e); 13515 } 13516 13517 public void setReturnCode(int returnCode) { 13518 this.returnCode = returnCode; 13519 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13520 for (int i = 0; i < childCount; i++) { 13521 addedChildPackages.valueAt(i).returnCode = returnCode; 13522 } 13523 } 13524 13525 private void setReturnMessage(String returnMsg) { 13526 this.returnMsg = returnMsg; 13527 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13528 for (int i = 0; i < childCount; i++) { 13529 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13530 } 13531 } 13532 13533 // In some error cases we want to convey more info back to the observer 13534 String origPackage; 13535 String origPermission; 13536 } 13537 13538 /* 13539 * Install a non-existing package. 13540 */ 13541 private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13542 UserHandle user, String installerPackageName, String volumeUuid, 13543 PackageInstalledInfo res) { 13544 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13545 13546 // Remember this for later, in case we need to rollback this install 13547 String pkgName = pkg.packageName; 13548 13549 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13550 13551 synchronized(mPackages) { 13552 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13553 // A package with the same name is already installed, though 13554 // it has been renamed to an older name. The package we 13555 // are trying to install should be installed as an update to 13556 // the existing one, but that has not been requested, so bail. 13557 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13558 + " without first uninstalling package running as " 13559 + mSettings.mRenamedPackages.get(pkgName)); 13560 return; 13561 } 13562 if (mPackages.containsKey(pkgName)) { 13563 // Don't allow installation over an existing package with the same name. 13564 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13565 + " without first uninstalling."); 13566 return; 13567 } 13568 } 13569 13570 try { 13571 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13572 System.currentTimeMillis(), user); 13573 13574 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13575 13576 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13577 prepareAppDataAfterInstallLIF(newPackage); 13578 13579 } else { 13580 // Remove package from internal structures, but keep around any 13581 // data that might have already existed 13582 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13583 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13584 } 13585 } catch (PackageManagerException e) { 13586 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13587 } 13588 13589 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13590 } 13591 13592 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13593 // Can't rotate keys during boot or if sharedUser. 13594 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13595 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13596 return false; 13597 } 13598 // app is using upgradeKeySets; make sure all are valid 13599 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13600 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13601 for (int i = 0; i < upgradeKeySets.length; i++) { 13602 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13603 Slog.wtf(TAG, "Package " 13604 + (oldPs.name != null ? oldPs.name : "<null>") 13605 + " contains upgrade-key-set reference to unknown key-set: " 13606 + upgradeKeySets[i] 13607 + " reverting to signatures check."); 13608 return false; 13609 } 13610 } 13611 return true; 13612 } 13613 13614 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13615 // Upgrade keysets are being used. Determine if new package has a superset of the 13616 // required keys. 13617 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13618 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13619 for (int i = 0; i < upgradeKeySets.length; i++) { 13620 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13621 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13622 return true; 13623 } 13624 } 13625 return false; 13626 } 13627 13628 private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13629 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13630 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13631 13632 final PackageParser.Package oldPackage; 13633 final String pkgName = pkg.packageName; 13634 final int[] allUsers; 13635 13636 // First find the old package info and check signatures 13637 synchronized(mPackages) { 13638 oldPackage = mPackages.get(pkgName); 13639 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13640 if (isEphemeral && !oldIsEphemeral) { 13641 // can't downgrade from full to ephemeral 13642 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13643 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13644 return; 13645 } 13646 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13647 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13648 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13649 if (!checkUpgradeKeySetLP(ps, pkg)) { 13650 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13651 "New package not signed by keys specified by upgrade-keysets: " 13652 + pkgName); 13653 return; 13654 } 13655 } else { 13656 // default to original signature matching 13657 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13658 != PackageManager.SIGNATURE_MATCH) { 13659 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13660 "New package has a different signature: " + pkgName); 13661 return; 13662 } 13663 } 13664 13665 // Check for shared user id changes 13666 String invalidPackageName = 13667 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13668 if (invalidPackageName != null) { 13669 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13670 "Package " + invalidPackageName + " tried to change user " 13671 + oldPackage.mSharedUserId); 13672 return; 13673 } 13674 13675 // In case of rollback, remember per-user/profile install state 13676 allUsers = sUserManager.getUserIds(); 13677 } 13678 13679 // Update what is removed 13680 res.removedInfo = new PackageRemovedInfo(); 13681 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13682 res.removedInfo.removedPackage = oldPackage.packageName; 13683 res.removedInfo.isUpdate = true; 13684 final int childCount = (oldPackage.childPackages != null) 13685 ? oldPackage.childPackages.size() : 0; 13686 for (int i = 0; i < childCount; i++) { 13687 boolean childPackageUpdated = false; 13688 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13689 if (res.addedChildPackages != null) { 13690 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13691 if (childRes != null) { 13692 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13693 childRes.removedInfo.removedPackage = childPkg.packageName; 13694 childRes.removedInfo.isUpdate = true; 13695 childPackageUpdated = true; 13696 } 13697 } 13698 if (!childPackageUpdated) { 13699 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13700 childRemovedRes.removedPackage = childPkg.packageName; 13701 childRemovedRes.isUpdate = false; 13702 childRemovedRes.dataRemoved = true; 13703 synchronized (mPackages) { 13704 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13705 if (childPs != null) { 13706 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13707 } 13708 } 13709 if (res.removedInfo.removedChildPackages == null) { 13710 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13711 } 13712 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13713 } 13714 } 13715 13716 boolean sysPkg = (isSystemApp(oldPackage)); 13717 if (sysPkg) { 13718 replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13719 user, allUsers, installerPackageName, res); 13720 } else { 13721 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13722 user, allUsers, installerPackageName, res); 13723 } 13724 } 13725 13726 public List<String> getPreviousCodePaths(String packageName) { 13727 final PackageSetting ps = mSettings.mPackages.get(packageName); 13728 final List<String> result = new ArrayList<String>(); 13729 if (ps != null && ps.oldCodePaths != null) { 13730 result.addAll(ps.oldCodePaths); 13731 } 13732 return result; 13733 } 13734 13735 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13736 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13737 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13738 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13739 + deletedPackage); 13740 13741 String pkgName = deletedPackage.packageName; 13742 boolean deletedPkg = true; 13743 boolean addedPkg = false; 13744 boolean updatedSettings = false; 13745 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13746 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13747 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13748 13749 final long origUpdateTime = (pkg.mExtras != null) 13750 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13751 13752 // First delete the existing package while retaining the data directory 13753 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13754 res.removedInfo, true, pkg)) { 13755 // If the existing package wasn't successfully deleted 13756 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13757 deletedPkg = false; 13758 } else { 13759 // Successfully deleted the old package; proceed with replace. 13760 13761 // If deleted package lived in a container, give users a chance to 13762 // relinquish resources before killing. 13763 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13764 if (DEBUG_INSTALL) { 13765 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13766 } 13767 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13768 final ArrayList<String> pkgList = new ArrayList<String>(1); 13769 pkgList.add(deletedPackage.applicationInfo.packageName); 13770 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13771 } 13772 13773 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13774 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13775 clearAppProfilesLIF(pkg); 13776 13777 try { 13778 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13779 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13780 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13781 13782 // Update the in-memory copy of the previous code paths. 13783 PackageSetting ps = mSettings.mPackages.get(pkgName); 13784 if (!killApp) { 13785 if (ps.oldCodePaths == null) { 13786 ps.oldCodePaths = new ArraySet<>(); 13787 } 13788 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13789 if (deletedPackage.splitCodePaths != null) { 13790 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13791 } 13792 } else { 13793 ps.oldCodePaths = null; 13794 } 13795 if (ps.childPackageNames != null) { 13796 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13797 final String childPkgName = ps.childPackageNames.get(i); 13798 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13799 childPs.oldCodePaths = ps.oldCodePaths; 13800 } 13801 } 13802 prepareAppDataAfterInstallLIF(newPackage); 13803 addedPkg = true; 13804 } catch (PackageManagerException e) { 13805 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13806 } 13807 } 13808 13809 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13810 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13811 13812 // Revert all internal state mutations and added folders for the failed install 13813 if (addedPkg) { 13814 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13815 res.removedInfo, true, null); 13816 } 13817 13818 // Restore the old package 13819 if (deletedPkg) { 13820 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13821 File restoreFile = new File(deletedPackage.codePath); 13822 // Parse old package 13823 boolean oldExternal = isExternal(deletedPackage); 13824 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13825 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13826 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13827 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13828 try { 13829 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13830 null); 13831 } catch (PackageManagerException e) { 13832 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13833 + e.getMessage()); 13834 return; 13835 } 13836 13837 synchronized (mPackages) { 13838 // Ensure the installer package name up to date 13839 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13840 13841 // Update permissions for restored package 13842 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13843 13844 mSettings.writeLPr(); 13845 } 13846 13847 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13848 } 13849 } else { 13850 synchronized (mPackages) { 13851 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13852 if (ps != null) { 13853 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13854 if (res.removedInfo.removedChildPackages != null) { 13855 final int childCount = res.removedInfo.removedChildPackages.size(); 13856 // Iterate in reverse as we may modify the collection 13857 for (int i = childCount - 1; i >= 0; i--) { 13858 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13859 if (res.addedChildPackages.containsKey(childPackageName)) { 13860 res.removedInfo.removedChildPackages.removeAt(i); 13861 } else { 13862 PackageRemovedInfo childInfo = res.removedInfo 13863 .removedChildPackages.valueAt(i); 13864 childInfo.removedForAllUsers = mPackages.get( 13865 childInfo.removedPackage) == null; 13866 } 13867 } 13868 } 13869 } 13870 } 13871 } 13872 } 13873 13874 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13875 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13876 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13877 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13878 + ", old=" + deletedPackage); 13879 13880 final boolean disabledSystem; 13881 13882 // Set the system/privileged flags as needed 13883 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13884 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13885 != 0) { 13886 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13887 } 13888 13889 // Remove existing system package 13890 removePackageLI(deletedPackage, true); 13891 13892 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13893 if (!disabledSystem) { 13894 // We didn't need to disable the .apk as a current system package, 13895 // which means we are replacing another update that is already 13896 // installed. We need to make sure to delete the older one's .apk. 13897 res.removedInfo.args = createInstallArgsForExisting(0, 13898 deletedPackage.applicationInfo.getCodePath(), 13899 deletedPackage.applicationInfo.getResourcePath(), 13900 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13901 } else { 13902 res.removedInfo.args = null; 13903 } 13904 13905 // Successfully disabled the old package. Now proceed with re-installation 13906 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13907 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13908 clearAppProfilesLIF(pkg); 13909 13910 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13911 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13912 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13913 13914 PackageParser.Package newPackage = null; 13915 try { 13916 // Add the package to the internal data structures 13917 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13918 13919 // Set the update and install times 13920 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13921 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13922 System.currentTimeMillis()); 13923 13924 // Update the package dynamic state if succeeded 13925 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13926 // Now that the install succeeded make sure we remove data 13927 // directories for any child package the update removed. 13928 final int deletedChildCount = (deletedPackage.childPackages != null) 13929 ? deletedPackage.childPackages.size() : 0; 13930 final int newChildCount = (newPackage.childPackages != null) 13931 ? newPackage.childPackages.size() : 0; 13932 for (int i = 0; i < deletedChildCount; i++) { 13933 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13934 boolean childPackageDeleted = true; 13935 for (int j = 0; j < newChildCount; j++) { 13936 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13937 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13938 childPackageDeleted = false; 13939 break; 13940 } 13941 } 13942 if (childPackageDeleted) { 13943 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13944 deletedChildPkg.packageName); 13945 if (ps != null && res.removedInfo.removedChildPackages != null) { 13946 PackageRemovedInfo removedChildRes = res.removedInfo 13947 .removedChildPackages.get(deletedChildPkg.packageName); 13948 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13949 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13950 } 13951 } 13952 } 13953 13954 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13955 prepareAppDataAfterInstallLIF(newPackage); 13956 } 13957 } catch (PackageManagerException e) { 13958 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13959 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13960 } 13961 13962 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13963 // Re installation failed. Restore old information 13964 // Remove new pkg information 13965 if (newPackage != null) { 13966 removeInstalledPackageLI(newPackage, true); 13967 } 13968 // Add back the old system package 13969 try { 13970 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13971 } catch (PackageManagerException e) { 13972 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13973 } 13974 13975 synchronized (mPackages) { 13976 if (disabledSystem) { 13977 enableSystemPackageLPw(deletedPackage); 13978 } 13979 13980 // Ensure the installer package name up to date 13981 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13982 13983 // Update permissions for restored package 13984 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13985 13986 mSettings.writeLPr(); 13987 } 13988 13989 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 13990 + " after failed upgrade"); 13991 } 13992 } 13993 13994 /** 13995 * Checks whether the parent or any of the child packages have a change shared 13996 * user. For a package to be a valid update the shred users of the parent and 13997 * the children should match. We may later support changing child shared users. 13998 * @param oldPkg The updated package. 13999 * @param newPkg The update package. 14000 * @return The shared user that change between the versions. 14001 */ 14002 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14003 PackageParser.Package newPkg) { 14004 // Check parent shared user 14005 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14006 return newPkg.packageName; 14007 } 14008 // Check child shared users 14009 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14010 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14011 for (int i = 0; i < newChildCount; i++) { 14012 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14013 // If this child was present, did it have the same shared user? 14014 for (int j = 0; j < oldChildCount; j++) { 14015 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14016 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14017 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14018 return newChildPkg.packageName; 14019 } 14020 } 14021 } 14022 return null; 14023 } 14024 14025 private void removeNativeBinariesLI(PackageSetting ps) { 14026 // Remove the lib path for the parent package 14027 if (ps != null) { 14028 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14029 // Remove the lib path for the child packages 14030 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14031 for (int i = 0; i < childCount; i++) { 14032 PackageSetting childPs = null; 14033 synchronized (mPackages) { 14034 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14035 } 14036 if (childPs != null) { 14037 NativeLibraryHelper.removeNativeBinariesLI(childPs 14038 .legacyNativeLibraryPathString); 14039 } 14040 } 14041 } 14042 } 14043 14044 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14045 // Enable the parent package 14046 mSettings.enableSystemPackageLPw(pkg.packageName); 14047 // Enable the child packages 14048 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14049 for (int i = 0; i < childCount; i++) { 14050 PackageParser.Package childPkg = pkg.childPackages.get(i); 14051 mSettings.enableSystemPackageLPw(childPkg.packageName); 14052 } 14053 } 14054 14055 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14056 PackageParser.Package newPkg) { 14057 // Disable the parent package (parent always replaced) 14058 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14059 // Disable the child packages 14060 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14061 for (int i = 0; i < childCount; i++) { 14062 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14063 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14064 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14065 } 14066 return disabled; 14067 } 14068 14069 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14070 String installerPackageName) { 14071 // Enable the parent package 14072 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14073 // Enable the child packages 14074 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14075 for (int i = 0; i < childCount; i++) { 14076 PackageParser.Package childPkg = pkg.childPackages.get(i); 14077 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14078 } 14079 } 14080 14081 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14082 // Collect all used permissions in the UID 14083 ArraySet<String> usedPermissions = new ArraySet<>(); 14084 final int packageCount = su.packages.size(); 14085 for (int i = 0; i < packageCount; i++) { 14086 PackageSetting ps = su.packages.valueAt(i); 14087 if (ps.pkg == null) { 14088 continue; 14089 } 14090 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14091 for (int j = 0; j < requestedPermCount; j++) { 14092 String permission = ps.pkg.requestedPermissions.get(j); 14093 BasePermission bp = mSettings.mPermissions.get(permission); 14094 if (bp != null) { 14095 usedPermissions.add(permission); 14096 } 14097 } 14098 } 14099 14100 PermissionsState permissionsState = su.getPermissionsState(); 14101 // Prune install permissions 14102 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14103 final int installPermCount = installPermStates.size(); 14104 for (int i = installPermCount - 1; i >= 0; i--) { 14105 PermissionState permissionState = installPermStates.get(i); 14106 if (!usedPermissions.contains(permissionState.getName())) { 14107 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14108 if (bp != null) { 14109 permissionsState.revokeInstallPermission(bp); 14110 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14111 PackageManager.MASK_PERMISSION_FLAGS, 0); 14112 } 14113 } 14114 } 14115 14116 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14117 14118 // Prune runtime permissions 14119 for (int userId : allUserIds) { 14120 List<PermissionState> runtimePermStates = permissionsState 14121 .getRuntimePermissionStates(userId); 14122 final int runtimePermCount = runtimePermStates.size(); 14123 for (int i = runtimePermCount - 1; i >= 0; i--) { 14124 PermissionState permissionState = runtimePermStates.get(i); 14125 if (!usedPermissions.contains(permissionState.getName())) { 14126 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14127 if (bp != null) { 14128 permissionsState.revokeRuntimePermission(bp, userId); 14129 permissionsState.updatePermissionFlags(bp, userId, 14130 PackageManager.MASK_PERMISSION_FLAGS, 0); 14131 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14132 runtimePermissionChangedUserIds, userId); 14133 } 14134 } 14135 } 14136 } 14137 14138 return runtimePermissionChangedUserIds; 14139 } 14140 14141 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14142 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14143 // Update the parent package setting 14144 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14145 res, user); 14146 // Update the child packages setting 14147 final int childCount = (newPackage.childPackages != null) 14148 ? newPackage.childPackages.size() : 0; 14149 for (int i = 0; i < childCount; i++) { 14150 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14151 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14152 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14153 childRes.origUsers, childRes, user); 14154 } 14155 } 14156 14157 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14158 String installerPackageName, int[] allUsers, int[] installedForUsers, 14159 PackageInstalledInfo res, UserHandle user) { 14160 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14161 14162 String pkgName = newPackage.packageName; 14163 synchronized (mPackages) { 14164 //write settings. the installStatus will be incomplete at this stage. 14165 //note that the new package setting would have already been 14166 //added to mPackages. It hasn't been persisted yet. 14167 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14168 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14169 mSettings.writeLPr(); 14170 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14171 } 14172 14173 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14174 synchronized (mPackages) { 14175 updatePermissionsLPw(newPackage.packageName, newPackage, 14176 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14177 ? UPDATE_PERMISSIONS_ALL : 0)); 14178 // For system-bundled packages, we assume that installing an upgraded version 14179 // of the package implies that the user actually wants to run that new code, 14180 // so we enable the package. 14181 PackageSetting ps = mSettings.mPackages.get(pkgName); 14182 final int userId = user.getIdentifier(); 14183 if (ps != null) { 14184 if (isSystemApp(newPackage)) { 14185 if (DEBUG_INSTALL) { 14186 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14187 } 14188 // Enable system package for requested users 14189 if (res.origUsers != null) { 14190 for (int origUserId : res.origUsers) { 14191 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14192 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14193 origUserId, installerPackageName); 14194 } 14195 } 14196 } 14197 // Also convey the prior install/uninstall state 14198 if (allUsers != null && installedForUsers != null) { 14199 for (int currentUserId : allUsers) { 14200 final boolean installed = ArrayUtils.contains( 14201 installedForUsers, currentUserId); 14202 if (DEBUG_INSTALL) { 14203 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14204 } 14205 ps.setInstalled(installed, currentUserId); 14206 } 14207 // these install state changes will be persisted in the 14208 // upcoming call to mSettings.writeLPr(). 14209 } 14210 } 14211 // It's implied that when a user requests installation, they want the app to be 14212 // installed and enabled. 14213 if (userId != UserHandle.USER_ALL) { 14214 ps.setInstalled(true, userId); 14215 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14216 } 14217 } 14218 res.name = pkgName; 14219 res.uid = newPackage.applicationInfo.uid; 14220 res.pkg = newPackage; 14221 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14222 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14223 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14224 //to update install status 14225 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14226 mSettings.writeLPr(); 14227 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14228 } 14229 14230 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14231 } 14232 14233 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14234 try { 14235 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14236 installPackageLI(args, res); 14237 } finally { 14238 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14239 } 14240 } 14241 14242 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14243 final int installFlags = args.installFlags; 14244 final String installerPackageName = args.installerPackageName; 14245 final String volumeUuid = args.volumeUuid; 14246 final File tmpPackageFile = new File(args.getCodePath()); 14247 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14248 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14249 || (args.volumeUuid != null)); 14250 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14251 boolean replace = false; 14252 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14253 if (args.move != null) { 14254 // moving a complete application; perform an initial scan on the new install location 14255 scanFlags |= SCAN_INITIAL; 14256 } 14257 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14258 scanFlags |= SCAN_DONT_KILL_APP; 14259 } 14260 14261 // Result object to be returned 14262 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14263 14264 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14265 14266 // Sanity check 14267 if (ephemeral && (forwardLocked || onExternal)) { 14268 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14269 + " external=" + onExternal); 14270 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14271 return; 14272 } 14273 14274 // Retrieve PackageSettings and parse package 14275 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14276 | PackageParser.PARSE_ENFORCE_CODE 14277 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14278 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14279 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14280 PackageParser pp = new PackageParser(); 14281 pp.setSeparateProcesses(mSeparateProcesses); 14282 pp.setDisplayMetrics(mMetrics); 14283 14284 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14285 final PackageParser.Package pkg; 14286 try { 14287 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14288 } catch (PackageParserException e) { 14289 res.setError("Failed parse during installPackageLI", e); 14290 return; 14291 } finally { 14292 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14293 } 14294 14295 // If we are installing a clustered package add results for the children 14296 if (pkg.childPackages != null) { 14297 synchronized (mPackages) { 14298 final int childCount = pkg.childPackages.size(); 14299 for (int i = 0; i < childCount; i++) { 14300 PackageParser.Package childPkg = pkg.childPackages.get(i); 14301 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14302 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14303 childRes.pkg = childPkg; 14304 childRes.name = childPkg.packageName; 14305 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14306 if (childPs != null) { 14307 childRes.origUsers = childPs.queryInstalledUsers( 14308 sUserManager.getUserIds(), true); 14309 } 14310 if ((mPackages.containsKey(childPkg.packageName))) { 14311 childRes.removedInfo = new PackageRemovedInfo(); 14312 childRes.removedInfo.removedPackage = childPkg.packageName; 14313 } 14314 if (res.addedChildPackages == null) { 14315 res.addedChildPackages = new ArrayMap<>(); 14316 } 14317 res.addedChildPackages.put(childPkg.packageName, childRes); 14318 } 14319 } 14320 } 14321 14322 // If package doesn't declare API override, mark that we have an install 14323 // time CPU ABI override. 14324 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14325 pkg.cpuAbiOverride = args.abiOverride; 14326 } 14327 14328 String pkgName = res.name = pkg.packageName; 14329 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14330 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14331 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14332 return; 14333 } 14334 } 14335 14336 try { 14337 // either use what we've been given or parse directly from the APK 14338 if (args.certificates != null) { 14339 try { 14340 PackageParser.populateCertificates(pkg, args.certificates); 14341 } catch (PackageParserException e) { 14342 // there was something wrong with the certificates we were given; 14343 // try to pull them from the APK 14344 PackageParser.collectCertificates(pkg, parseFlags); 14345 } 14346 } else { 14347 PackageParser.collectCertificates(pkg, parseFlags); 14348 } 14349 } catch (PackageParserException e) { 14350 res.setError("Failed collect during installPackageLI", e); 14351 return; 14352 } 14353 14354 // Get rid of all references to package scan path via parser. 14355 pp = null; 14356 String oldCodePath = null; 14357 boolean systemApp = false; 14358 synchronized (mPackages) { 14359 // Check if installing already existing package 14360 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14361 String oldName = mSettings.mRenamedPackages.get(pkgName); 14362 if (pkg.mOriginalPackages != null 14363 && pkg.mOriginalPackages.contains(oldName) 14364 && mPackages.containsKey(oldName)) { 14365 // This package is derived from an original package, 14366 // and this device has been updating from that original 14367 // name. We must continue using the original name, so 14368 // rename the new package here. 14369 pkg.setPackageName(oldName); 14370 pkgName = pkg.packageName; 14371 replace = true; 14372 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14373 + oldName + " pkgName=" + pkgName); 14374 } else if (mPackages.containsKey(pkgName)) { 14375 // This package, under its official name, already exists 14376 // on the device; we should replace it. 14377 replace = true; 14378 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14379 } 14380 14381 // Child packages are installed through the parent package 14382 if (pkg.parentPackage != null) { 14383 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14384 "Package " + pkg.packageName + " is child of package " 14385 + pkg.parentPackage.parentPackage + ". Child packages " 14386 + "can be updated only through the parent package."); 14387 return; 14388 } 14389 14390 if (replace) { 14391 // Prevent apps opting out from runtime permissions 14392 PackageParser.Package oldPackage = mPackages.get(pkgName); 14393 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14394 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14395 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14396 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14397 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14398 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14399 + " doesn't support runtime permissions but the old" 14400 + " target SDK " + oldTargetSdk + " does."); 14401 return; 14402 } 14403 14404 // Prevent installing of child packages 14405 if (oldPackage.parentPackage != null) { 14406 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14407 "Package " + pkg.packageName + " is child of package " 14408 + oldPackage.parentPackage + ". Child packages " 14409 + "can be updated only through the parent package."); 14410 return; 14411 } 14412 } 14413 } 14414 14415 PackageSetting ps = mSettings.mPackages.get(pkgName); 14416 if (ps != null) { 14417 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14418 14419 // Quick sanity check that we're signed correctly if updating; 14420 // we'll check this again later when scanning, but we want to 14421 // bail early here before tripping over redefined permissions. 14422 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14423 if (!checkUpgradeKeySetLP(ps, pkg)) { 14424 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14425 + pkg.packageName + " upgrade keys do not match the " 14426 + "previously installed version"); 14427 return; 14428 } 14429 } else { 14430 try { 14431 verifySignaturesLP(ps, pkg); 14432 } catch (PackageManagerException e) { 14433 res.setError(e.error, e.getMessage()); 14434 return; 14435 } 14436 } 14437 14438 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14439 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14440 systemApp = (ps.pkg.applicationInfo.flags & 14441 ApplicationInfo.FLAG_SYSTEM) != 0; 14442 } 14443 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14444 } 14445 14446 // Check whether the newly-scanned package wants to define an already-defined perm 14447 int N = pkg.permissions.size(); 14448 for (int i = N-1; i >= 0; i--) { 14449 PackageParser.Permission perm = pkg.permissions.get(i); 14450 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14451 if (bp != null) { 14452 // If the defining package is signed with our cert, it's okay. This 14453 // also includes the "updating the same package" case, of course. 14454 // "updating same package" could also involve key-rotation. 14455 final boolean sigsOk; 14456 if (bp.sourcePackage.equals(pkg.packageName) 14457 && (bp.packageSetting instanceof PackageSetting) 14458 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14459 scanFlags))) { 14460 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14461 } else { 14462 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14463 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14464 } 14465 if (!sigsOk) { 14466 // If the owning package is the system itself, we log but allow 14467 // install to proceed; we fail the install on all other permission 14468 // redefinitions. 14469 if (!bp.sourcePackage.equals("android")) { 14470 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14471 + pkg.packageName + " attempting to redeclare permission " 14472 + perm.info.name + " already owned by " + bp.sourcePackage); 14473 res.origPermission = perm.info.name; 14474 res.origPackage = bp.sourcePackage; 14475 return; 14476 } else { 14477 Slog.w(TAG, "Package " + pkg.packageName 14478 + " attempting to redeclare system permission " 14479 + perm.info.name + "; ignoring new declaration"); 14480 pkg.permissions.remove(i); 14481 } 14482 } 14483 } 14484 } 14485 } 14486 14487 if (systemApp) { 14488 if (onExternal) { 14489 // Abort update; system app can't be replaced with app on sdcard 14490 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14491 "Cannot install updates to system apps on sdcard"); 14492 return; 14493 } else if (ephemeral) { 14494 // Abort update; system app can't be replaced with an ephemeral app 14495 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14496 "Cannot update a system app with an ephemeral app"); 14497 return; 14498 } 14499 } 14500 14501 if (args.move != null) { 14502 // We did an in-place move, so dex is ready to roll 14503 scanFlags |= SCAN_NO_DEX; 14504 scanFlags |= SCAN_MOVE; 14505 14506 synchronized (mPackages) { 14507 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14508 if (ps == null) { 14509 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14510 "Missing settings for moved package " + pkgName); 14511 } 14512 14513 // We moved the entire application as-is, so bring over the 14514 // previously derived ABI information. 14515 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14516 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14517 } 14518 14519 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14520 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14521 scanFlags |= SCAN_NO_DEX; 14522 14523 try { 14524 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14525 args.abiOverride : pkg.cpuAbiOverride); 14526 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14527 true /* extract libs */); 14528 } catch (PackageManagerException pme) { 14529 Slog.e(TAG, "Error deriving application ABI", pme); 14530 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14531 return; 14532 } 14533 14534 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14535 // Do not run PackageDexOptimizer through the local performDexOpt 14536 // method because `pkg` is not in `mPackages` yet. 14537 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14538 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14539 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14540 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14541 String msg = "Extracting package failed for " + pkgName; 14542 res.setError(INSTALL_FAILED_DEXOPT, msg); 14543 return; 14544 } 14545 14546 // Notify BackgroundDexOptService that the package has been changed. 14547 // If this is an update of a package which used to fail to compile, 14548 // BDOS will remove it from its blacklist. 14549 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14550 } 14551 14552 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14553 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14554 return; 14555 } 14556 14557 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14558 14559 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14560 "installPackageLI")) { 14561 if (replace) { 14562 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14563 installerPackageName, res); 14564 } else { 14565 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14566 args.user, installerPackageName, volumeUuid, res); 14567 } 14568 } 14569 synchronized (mPackages) { 14570 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14571 if (ps != null) { 14572 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14573 } 14574 14575 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14576 for (int i = 0; i < childCount; i++) { 14577 PackageParser.Package childPkg = pkg.childPackages.get(i); 14578 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14579 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14580 if (childPs != null) { 14581 childRes.newUsers = childPs.queryInstalledUsers( 14582 sUserManager.getUserIds(), true); 14583 } 14584 } 14585 } 14586 } 14587 14588 private void startIntentFilterVerifications(int userId, boolean replacing, 14589 PackageParser.Package pkg) { 14590 if (mIntentFilterVerifierComponent == null) { 14591 Slog.w(TAG, "No IntentFilter verification will not be done as " 14592 + "there is no IntentFilterVerifier available!"); 14593 return; 14594 } 14595 14596 final int verifierUid = getPackageUid( 14597 mIntentFilterVerifierComponent.getPackageName(), 14598 MATCH_DEBUG_TRIAGED_MISSING, 14599 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14600 14601 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14602 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14603 mHandler.sendMessage(msg); 14604 14605 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14606 for (int i = 0; i < childCount; i++) { 14607 PackageParser.Package childPkg = pkg.childPackages.get(i); 14608 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14609 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14610 mHandler.sendMessage(msg); 14611 } 14612 } 14613 14614 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14615 PackageParser.Package pkg) { 14616 int size = pkg.activities.size(); 14617 if (size == 0) { 14618 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14619 "No activity, so no need to verify any IntentFilter!"); 14620 return; 14621 } 14622 14623 final boolean hasDomainURLs = hasDomainURLs(pkg); 14624 if (!hasDomainURLs) { 14625 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14626 "No domain URLs, so no need to verify any IntentFilter!"); 14627 return; 14628 } 14629 14630 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14631 + " if any IntentFilter from the " + size 14632 + " Activities needs verification ..."); 14633 14634 int count = 0; 14635 final String packageName = pkg.packageName; 14636 14637 synchronized (mPackages) { 14638 // If this is a new install and we see that we've already run verification for this 14639 // package, we have nothing to do: it means the state was restored from backup. 14640 if (!replacing) { 14641 IntentFilterVerificationInfo ivi = 14642 mSettings.getIntentFilterVerificationLPr(packageName); 14643 if (ivi != null) { 14644 if (DEBUG_DOMAIN_VERIFICATION) { 14645 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14646 + ivi.getStatusString()); 14647 } 14648 return; 14649 } 14650 } 14651 14652 // If any filters need to be verified, then all need to be. 14653 boolean needToVerify = false; 14654 for (PackageParser.Activity a : pkg.activities) { 14655 for (ActivityIntentInfo filter : a.intents) { 14656 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14657 if (DEBUG_DOMAIN_VERIFICATION) { 14658 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14659 } 14660 needToVerify = true; 14661 break; 14662 } 14663 } 14664 } 14665 14666 if (needToVerify) { 14667 final int verificationId = mIntentFilterVerificationToken++; 14668 for (PackageParser.Activity a : pkg.activities) { 14669 for (ActivityIntentInfo filter : a.intents) { 14670 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14671 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14672 "Verification needed for IntentFilter:" + filter.toString()); 14673 mIntentFilterVerifier.addOneIntentFilterVerification( 14674 verifierUid, userId, verificationId, filter, packageName); 14675 count++; 14676 } 14677 } 14678 } 14679 } 14680 } 14681 14682 if (count > 0) { 14683 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14684 + " IntentFilter verification" + (count > 1 ? "s" : "") 14685 + " for userId:" + userId); 14686 mIntentFilterVerifier.startVerifications(userId); 14687 } else { 14688 if (DEBUG_DOMAIN_VERIFICATION) { 14689 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14690 } 14691 } 14692 } 14693 14694 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14695 final ComponentName cn = filter.activity.getComponentName(); 14696 final String packageName = cn.getPackageName(); 14697 14698 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14699 packageName); 14700 if (ivi == null) { 14701 return true; 14702 } 14703 int status = ivi.getStatus(); 14704 switch (status) { 14705 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14706 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14707 return true; 14708 14709 default: 14710 // Nothing to do 14711 return false; 14712 } 14713 } 14714 14715 private static boolean isMultiArch(ApplicationInfo info) { 14716 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14717 } 14718 14719 private static boolean isExternal(PackageParser.Package pkg) { 14720 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14721 } 14722 14723 private static boolean isExternal(PackageSetting ps) { 14724 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14725 } 14726 14727 private static boolean isEphemeral(PackageParser.Package pkg) { 14728 return pkg.applicationInfo.isEphemeralApp(); 14729 } 14730 14731 private static boolean isEphemeral(PackageSetting ps) { 14732 return ps.pkg != null && isEphemeral(ps.pkg); 14733 } 14734 14735 private static boolean isSystemApp(PackageParser.Package pkg) { 14736 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14737 } 14738 14739 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14740 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14741 } 14742 14743 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14744 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14745 } 14746 14747 private static boolean isSystemApp(PackageSetting ps) { 14748 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14749 } 14750 14751 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14752 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14753 } 14754 14755 private int packageFlagsToInstallFlags(PackageSetting ps) { 14756 int installFlags = 0; 14757 if (isEphemeral(ps)) { 14758 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14759 } 14760 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14761 // This existing package was an external ASEC install when we have 14762 // the external flag without a UUID 14763 installFlags |= PackageManager.INSTALL_EXTERNAL; 14764 } 14765 if (ps.isForwardLocked()) { 14766 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14767 } 14768 return installFlags; 14769 } 14770 14771 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14772 if (isExternal(pkg)) { 14773 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14774 return StorageManager.UUID_PRIMARY_PHYSICAL; 14775 } else { 14776 return pkg.volumeUuid; 14777 } 14778 } else { 14779 return StorageManager.UUID_PRIVATE_INTERNAL; 14780 } 14781 } 14782 14783 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14784 if (isExternal(pkg)) { 14785 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14786 return mSettings.getExternalVersion(); 14787 } else { 14788 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14789 } 14790 } else { 14791 return mSettings.getInternalVersion(); 14792 } 14793 } 14794 14795 private void deleteTempPackageFiles() { 14796 final FilenameFilter filter = new FilenameFilter() { 14797 public boolean accept(File dir, String name) { 14798 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14799 } 14800 }; 14801 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14802 file.delete(); 14803 } 14804 } 14805 14806 @Override 14807 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14808 int flags) { 14809 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14810 flags); 14811 } 14812 14813 @Override 14814 public void deletePackage(final String packageName, 14815 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14816 mContext.enforceCallingOrSelfPermission( 14817 android.Manifest.permission.DELETE_PACKAGES, null); 14818 Preconditions.checkNotNull(packageName); 14819 Preconditions.checkNotNull(observer); 14820 final int uid = Binder.getCallingUid(); 14821 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14822 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14823 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14824 mContext.enforceCallingOrSelfPermission( 14825 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14826 "deletePackage for user " + userId); 14827 } 14828 14829 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14830 try { 14831 observer.onPackageDeleted(packageName, 14832 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14833 } catch (RemoteException re) { 14834 } 14835 return; 14836 } 14837 14838 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14839 try { 14840 observer.onPackageDeleted(packageName, 14841 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14842 } catch (RemoteException re) { 14843 } 14844 return; 14845 } 14846 14847 if (DEBUG_REMOVE) { 14848 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14849 + " deleteAllUsers: " + deleteAllUsers ); 14850 } 14851 // Queue up an async operation since the package deletion may take a little while. 14852 mHandler.post(new Runnable() { 14853 public void run() { 14854 mHandler.removeCallbacks(this); 14855 int returnCode; 14856 if (!deleteAllUsers) { 14857 returnCode = deletePackageX(packageName, userId, deleteFlags); 14858 } else { 14859 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14860 // If nobody is blocking uninstall, proceed with delete for all users 14861 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14862 returnCode = deletePackageX(packageName, userId, deleteFlags); 14863 } else { 14864 // Otherwise uninstall individually for users with blockUninstalls=false 14865 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14866 for (int userId : users) { 14867 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14868 returnCode = deletePackageX(packageName, userId, userFlags); 14869 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14870 Slog.w(TAG, "Package delete failed for user " + userId 14871 + ", returnCode " + returnCode); 14872 } 14873 } 14874 } 14875 // The app has only been marked uninstalled for certain users. 14876 // We still need to report that delete was blocked 14877 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14878 } 14879 } 14880 try { 14881 observer.onPackageDeleted(packageName, returnCode, null); 14882 } catch (RemoteException e) { 14883 Log.i(TAG, "Observer no longer exists."); 14884 } //end catch 14885 } //end run 14886 }); 14887 } 14888 14889 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14890 int[] result = EMPTY_INT_ARRAY; 14891 for (int userId : userIds) { 14892 if (getBlockUninstallForUser(packageName, userId)) { 14893 result = ArrayUtils.appendInt(result, userId); 14894 } 14895 } 14896 return result; 14897 } 14898 14899 @Override 14900 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14901 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14902 } 14903 14904 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14905 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14906 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14907 try { 14908 if (dpm != null) { 14909 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14910 /* callingUserOnly =*/ false); 14911 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14912 : deviceOwnerComponentName.getPackageName(); 14913 // Does the package contains the device owner? 14914 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14915 // this check is probably not needed, since DO should be registered as a device 14916 // admin on some user too. (Original bug for this: b/17657954) 14917 if (packageName.equals(deviceOwnerPackageName)) { 14918 return true; 14919 } 14920 // Does it contain a device admin for any user? 14921 int[] users; 14922 if (userId == UserHandle.USER_ALL) { 14923 users = sUserManager.getUserIds(); 14924 } else { 14925 users = new int[]{userId}; 14926 } 14927 for (int i = 0; i < users.length; ++i) { 14928 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14929 return true; 14930 } 14931 } 14932 } 14933 } catch (RemoteException e) { 14934 } 14935 return false; 14936 } 14937 14938 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14939 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14940 } 14941 14942 /** 14943 * This method is an internal method that could be get invoked either 14944 * to delete an installed package or to clean up a failed installation. 14945 * After deleting an installed package, a broadcast is sent to notify any 14946 * listeners that the package has been removed. For cleaning up a failed 14947 * installation, the broadcast is not necessary since the package's 14948 * installation wouldn't have sent the initial broadcast either 14949 * The key steps in deleting a package are 14950 * deleting the package information in internal structures like mPackages, 14951 * deleting the packages base directories through installd 14952 * updating mSettings to reflect current status 14953 * persisting settings for later use 14954 * sending a broadcast if necessary 14955 */ 14956 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14957 final PackageRemovedInfo info = new PackageRemovedInfo(); 14958 final boolean res; 14959 14960 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14961 ? UserHandle.ALL : new UserHandle(userId); 14962 14963 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14964 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14965 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14966 } 14967 14968 PackageSetting uninstalledPs = null; 14969 14970 // for the uninstall-updates case and restricted profiles, remember the per- 14971 // user handle installed state 14972 int[] allUsers; 14973 synchronized (mPackages) { 14974 uninstalledPs = mSettings.mPackages.get(packageName); 14975 if (uninstalledPs == null) { 14976 Slog.w(TAG, "Not removing non-existent package " + packageName); 14977 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14978 } 14979 allUsers = sUserManager.getUserIds(); 14980 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14981 } 14982 14983 synchronized (mInstallLock) { 14984 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14985 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 14986 "deletePackageX")) { 14987 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 14988 deleteFlags | REMOVE_CHATTY, info, true, null); 14989 } 14990 synchronized (mPackages) { 14991 if (res) { 14992 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 14993 } 14994 } 14995 } 14996 14997 if (res) { 14998 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 14999 info.sendPackageRemovedBroadcasts(killApp); 15000 info.sendSystemPackageUpdatedBroadcasts(); 15001 info.sendSystemPackageAppearedBroadcasts(); 15002 } 15003 // Force a gc here. 15004 Runtime.getRuntime().gc(); 15005 // Delete the resources here after sending the broadcast to let 15006 // other processes clean up before deleting resources. 15007 if (info.args != null) { 15008 synchronized (mInstallLock) { 15009 info.args.doPostDeleteLI(true); 15010 } 15011 } 15012 15013 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15014 } 15015 15016 class PackageRemovedInfo { 15017 String removedPackage; 15018 int uid = -1; 15019 int removedAppId = -1; 15020 int[] origUsers; 15021 int[] removedUsers = null; 15022 boolean isRemovedPackageSystemUpdate = false; 15023 boolean isUpdate; 15024 boolean dataRemoved; 15025 boolean removedForAllUsers; 15026 // Clean up resources deleted packages. 15027 InstallArgs args = null; 15028 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15029 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15030 15031 void sendPackageRemovedBroadcasts(boolean killApp) { 15032 sendPackageRemovedBroadcastInternal(killApp); 15033 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15034 for (int i = 0; i < childCount; i++) { 15035 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15036 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15037 } 15038 } 15039 15040 void sendSystemPackageUpdatedBroadcasts() { 15041 if (isRemovedPackageSystemUpdate) { 15042 sendSystemPackageUpdatedBroadcastsInternal(); 15043 final int childCount = (removedChildPackages != null) 15044 ? removedChildPackages.size() : 0; 15045 for (int i = 0; i < childCount; i++) { 15046 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15047 if (childInfo.isRemovedPackageSystemUpdate) { 15048 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15049 } 15050 } 15051 } 15052 } 15053 15054 void sendSystemPackageAppearedBroadcasts() { 15055 final int packageCount = (appearedChildPackages != null) 15056 ? appearedChildPackages.size() : 0; 15057 for (int i = 0; i < packageCount; i++) { 15058 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15059 for (int userId : installedInfo.newUsers) { 15060 sendPackageAddedForUser(installedInfo.name, true, 15061 UserHandle.getAppId(installedInfo.uid), userId); 15062 } 15063 } 15064 } 15065 15066 private void sendSystemPackageUpdatedBroadcastsInternal() { 15067 Bundle extras = new Bundle(2); 15068 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15069 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15070 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15071 extras, 0, null, null, null); 15072 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15073 extras, 0, null, null, null); 15074 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15075 null, 0, removedPackage, null, null); 15076 } 15077 15078 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15079 Bundle extras = new Bundle(2); 15080 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15081 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15082 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15083 if (isUpdate || isRemovedPackageSystemUpdate) { 15084 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15085 } 15086 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15087 if (removedPackage != null) { 15088 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15089 extras, 0, null, null, removedUsers); 15090 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15091 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15092 removedPackage, extras, 0, null, null, removedUsers); 15093 } 15094 } 15095 if (removedAppId >= 0) { 15096 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15097 removedUsers); 15098 } 15099 } 15100 } 15101 15102 /* 15103 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15104 * flag is not set, the data directory is removed as well. 15105 * make sure this flag is set for partially installed apps. If not its meaningless to 15106 * delete a partially installed application. 15107 */ 15108 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15109 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15110 String packageName = ps.name; 15111 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15112 // Retrieve object to delete permissions for shared user later on 15113 final PackageParser.Package deletedPkg; 15114 final PackageSetting deletedPs; 15115 // reader 15116 synchronized (mPackages) { 15117 deletedPkg = mPackages.get(packageName); 15118 deletedPs = mSettings.mPackages.get(packageName); 15119 if (outInfo != null) { 15120 outInfo.removedPackage = packageName; 15121 outInfo.removedUsers = deletedPs != null 15122 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15123 : null; 15124 } 15125 } 15126 15127 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15128 15129 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15130 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15131 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15132 destroyAppProfilesLIF(deletedPkg); 15133 if (outInfo != null) { 15134 outInfo.dataRemoved = true; 15135 } 15136 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15137 } 15138 15139 // writer 15140 synchronized (mPackages) { 15141 if (deletedPs != null) { 15142 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15143 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15144 clearDefaultBrowserIfNeeded(packageName); 15145 if (outInfo != null) { 15146 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15147 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15148 } 15149 updatePermissionsLPw(deletedPs.name, null, 0); 15150 if (deletedPs.sharedUser != null) { 15151 // Remove permissions associated with package. Since runtime 15152 // permissions are per user we have to kill the removed package 15153 // or packages running under the shared user of the removed 15154 // package if revoking the permissions requested only by the removed 15155 // package is successful and this causes a change in gids. 15156 for (int userId : UserManagerService.getInstance().getUserIds()) { 15157 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15158 userId); 15159 if (userIdToKill == UserHandle.USER_ALL 15160 || userIdToKill >= UserHandle.USER_SYSTEM) { 15161 // If gids changed for this user, kill all affected packages. 15162 mHandler.post(new Runnable() { 15163 @Override 15164 public void run() { 15165 // This has to happen with no lock held. 15166 killApplication(deletedPs.name, deletedPs.appId, 15167 KILL_APP_REASON_GIDS_CHANGED); 15168 } 15169 }); 15170 break; 15171 } 15172 } 15173 } 15174 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15175 } 15176 // make sure to preserve per-user disabled state if this removal was just 15177 // a downgrade of a system app to the factory package 15178 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15179 if (DEBUG_REMOVE) { 15180 Slog.d(TAG, "Propagating install state across downgrade"); 15181 } 15182 for (int userId : allUserHandles) { 15183 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15184 if (DEBUG_REMOVE) { 15185 Slog.d(TAG, " user " + userId + " => " + installed); 15186 } 15187 ps.setInstalled(installed, userId); 15188 } 15189 } 15190 } 15191 // can downgrade to reader 15192 if (writeSettings) { 15193 // Save settings now 15194 mSettings.writeLPr(); 15195 } 15196 } 15197 if (outInfo != null) { 15198 // A user ID was deleted here. Go through all users and remove it 15199 // from KeyStore. 15200 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15201 } 15202 } 15203 15204 static boolean locationIsPrivileged(File path) { 15205 try { 15206 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15207 .getCanonicalPath(); 15208 return path.getCanonicalPath().startsWith(privilegedAppDir); 15209 } catch (IOException e) { 15210 Slog.e(TAG, "Unable to access code path " + path); 15211 } 15212 return false; 15213 } 15214 15215 /* 15216 * Tries to delete system package. 15217 */ 15218 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15219 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15220 boolean writeSettings) { 15221 if (deletedPs.parentPackageName != null) { 15222 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15223 return false; 15224 } 15225 15226 final boolean applyUserRestrictions 15227 = (allUserHandles != null) && (outInfo.origUsers != null); 15228 final PackageSetting disabledPs; 15229 // Confirm if the system package has been updated 15230 // An updated system app can be deleted. This will also have to restore 15231 // the system pkg from system partition 15232 // reader 15233 synchronized (mPackages) { 15234 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15235 } 15236 15237 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15238 + " disabledPs=" + disabledPs); 15239 15240 if (disabledPs == null) { 15241 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15242 return false; 15243 } else if (DEBUG_REMOVE) { 15244 Slog.d(TAG, "Deleting system pkg from data partition"); 15245 } 15246 15247 if (DEBUG_REMOVE) { 15248 if (applyUserRestrictions) { 15249 Slog.d(TAG, "Remembering install states:"); 15250 for (int userId : allUserHandles) { 15251 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15252 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15253 } 15254 } 15255 } 15256 15257 // Delete the updated package 15258 outInfo.isRemovedPackageSystemUpdate = true; 15259 if (outInfo.removedChildPackages != null) { 15260 final int childCount = (deletedPs.childPackageNames != null) 15261 ? deletedPs.childPackageNames.size() : 0; 15262 for (int i = 0; i < childCount; i++) { 15263 String childPackageName = deletedPs.childPackageNames.get(i); 15264 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15265 .contains(childPackageName)) { 15266 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15267 childPackageName); 15268 if (childInfo != null) { 15269 childInfo.isRemovedPackageSystemUpdate = true; 15270 } 15271 } 15272 } 15273 } 15274 15275 if (disabledPs.versionCode < deletedPs.versionCode) { 15276 // Delete data for downgrades 15277 flags &= ~PackageManager.DELETE_KEEP_DATA; 15278 } else { 15279 // Preserve data by setting flag 15280 flags |= PackageManager.DELETE_KEEP_DATA; 15281 } 15282 15283 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15284 outInfo, writeSettings, disabledPs.pkg); 15285 if (!ret) { 15286 return false; 15287 } 15288 15289 // writer 15290 synchronized (mPackages) { 15291 // Reinstate the old system package 15292 enableSystemPackageLPw(disabledPs.pkg); 15293 // Remove any native libraries from the upgraded package. 15294 removeNativeBinariesLI(deletedPs); 15295 } 15296 15297 // Install the system package 15298 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15299 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15300 if (locationIsPrivileged(disabledPs.codePath)) { 15301 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15302 } 15303 15304 final PackageParser.Package newPkg; 15305 try { 15306 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15307 } catch (PackageManagerException e) { 15308 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15309 + e.getMessage()); 15310 return false; 15311 } 15312 15313 prepareAppDataAfterInstallLIF(newPkg); 15314 15315 // writer 15316 synchronized (mPackages) { 15317 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15318 15319 // Propagate the permissions state as we do not want to drop on the floor 15320 // runtime permissions. The update permissions method below will take 15321 // care of removing obsolete permissions and grant install permissions. 15322 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15323 updatePermissionsLPw(newPkg.packageName, newPkg, 15324 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15325 15326 if (applyUserRestrictions) { 15327 if (DEBUG_REMOVE) { 15328 Slog.d(TAG, "Propagating install state across reinstall"); 15329 } 15330 for (int userId : allUserHandles) { 15331 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15332 if (DEBUG_REMOVE) { 15333 Slog.d(TAG, " user " + userId + " => " + installed); 15334 } 15335 ps.setInstalled(installed, userId); 15336 15337 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15338 } 15339 // Regardless of writeSettings we need to ensure that this restriction 15340 // state propagation is persisted 15341 mSettings.writeAllUsersPackageRestrictionsLPr(); 15342 } 15343 // can downgrade to reader here 15344 if (writeSettings) { 15345 mSettings.writeLPr(); 15346 } 15347 } 15348 return true; 15349 } 15350 15351 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15352 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15353 PackageRemovedInfo outInfo, boolean writeSettings, 15354 PackageParser.Package replacingPackage) { 15355 synchronized (mPackages) { 15356 if (outInfo != null) { 15357 outInfo.uid = ps.appId; 15358 } 15359 15360 if (outInfo != null && outInfo.removedChildPackages != null) { 15361 final int childCount = (ps.childPackageNames != null) 15362 ? ps.childPackageNames.size() : 0; 15363 for (int i = 0; i < childCount; i++) { 15364 String childPackageName = ps.childPackageNames.get(i); 15365 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15366 if (childPs == null) { 15367 return false; 15368 } 15369 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15370 childPackageName); 15371 if (childInfo != null) { 15372 childInfo.uid = childPs.appId; 15373 } 15374 } 15375 } 15376 } 15377 15378 // Delete package data from internal structures and also remove data if flag is set 15379 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15380 15381 // Delete the child packages data 15382 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15383 for (int i = 0; i < childCount; i++) { 15384 PackageSetting childPs; 15385 synchronized (mPackages) { 15386 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15387 } 15388 if (childPs != null) { 15389 PackageRemovedInfo childOutInfo = (outInfo != null 15390 && outInfo.removedChildPackages != null) 15391 ? outInfo.removedChildPackages.get(childPs.name) : null; 15392 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15393 && (replacingPackage != null 15394 && !replacingPackage.hasChildPackage(childPs.name)) 15395 ? flags & ~DELETE_KEEP_DATA : flags; 15396 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15397 deleteFlags, writeSettings); 15398 } 15399 } 15400 15401 // Delete application code and resources only for parent packages 15402 if (ps.parentPackageName == null) { 15403 if (deleteCodeAndResources && (outInfo != null)) { 15404 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15405 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15406 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15407 } 15408 } 15409 15410 return true; 15411 } 15412 15413 @Override 15414 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15415 int userId) { 15416 mContext.enforceCallingOrSelfPermission( 15417 android.Manifest.permission.DELETE_PACKAGES, null); 15418 synchronized (mPackages) { 15419 PackageSetting ps = mSettings.mPackages.get(packageName); 15420 if (ps == null) { 15421 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15422 return false; 15423 } 15424 if (!ps.getInstalled(userId)) { 15425 // Can't block uninstall for an app that is not installed or enabled. 15426 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15427 return false; 15428 } 15429 ps.setBlockUninstall(blockUninstall, userId); 15430 mSettings.writePackageRestrictionsLPr(userId); 15431 } 15432 return true; 15433 } 15434 15435 @Override 15436 public boolean getBlockUninstallForUser(String packageName, int userId) { 15437 synchronized (mPackages) { 15438 PackageSetting ps = mSettings.mPackages.get(packageName); 15439 if (ps == null) { 15440 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15441 return false; 15442 } 15443 return ps.getBlockUninstall(userId); 15444 } 15445 } 15446 15447 @Override 15448 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15449 int callingUid = Binder.getCallingUid(); 15450 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15451 throw new SecurityException( 15452 "setRequiredForSystemUser can only be run by the system or root"); 15453 } 15454 synchronized (mPackages) { 15455 PackageSetting ps = mSettings.mPackages.get(packageName); 15456 if (ps == null) { 15457 Log.w(TAG, "Package doesn't exist: " + packageName); 15458 return false; 15459 } 15460 if (systemUserApp) { 15461 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15462 } else { 15463 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15464 } 15465 mSettings.writeLPr(); 15466 } 15467 return true; 15468 } 15469 15470 /* 15471 * This method handles package deletion in general 15472 */ 15473 private boolean deletePackageLIF(String packageName, UserHandle user, 15474 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15475 PackageRemovedInfo outInfo, boolean writeSettings, 15476 PackageParser.Package replacingPackage) { 15477 if (packageName == null) { 15478 Slog.w(TAG, "Attempt to delete null packageName."); 15479 return false; 15480 } 15481 15482 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15483 15484 PackageSetting ps; 15485 15486 synchronized (mPackages) { 15487 ps = mSettings.mPackages.get(packageName); 15488 if (ps == null) { 15489 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15490 return false; 15491 } 15492 15493 if (ps.parentPackageName != null && (!isSystemApp(ps) 15494 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15495 if (DEBUG_REMOVE) { 15496 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15497 + ((user == null) ? UserHandle.USER_ALL : user)); 15498 } 15499 final int removedUserId = (user != null) ? user.getIdentifier() 15500 : UserHandle.USER_ALL; 15501 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15502 return false; 15503 } 15504 markPackageUninstalledForUserLPw(ps, user); 15505 scheduleWritePackageRestrictionsLocked(user); 15506 return true; 15507 } 15508 } 15509 15510 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15511 && user.getIdentifier() != UserHandle.USER_ALL)) { 15512 // The caller is asking that the package only be deleted for a single 15513 // user. To do this, we just mark its uninstalled state and delete 15514 // its data. If this is a system app, we only allow this to happen if 15515 // they have set the special DELETE_SYSTEM_APP which requests different 15516 // semantics than normal for uninstalling system apps. 15517 markPackageUninstalledForUserLPw(ps, user); 15518 15519 if (!isSystemApp(ps)) { 15520 // Do not uninstall the APK if an app should be cached 15521 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15522 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15523 // Other user still have this package installed, so all 15524 // we need to do is clear this user's data and save that 15525 // it is uninstalled. 15526 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15527 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15528 return false; 15529 } 15530 scheduleWritePackageRestrictionsLocked(user); 15531 return true; 15532 } else { 15533 // We need to set it back to 'installed' so the uninstall 15534 // broadcasts will be sent correctly. 15535 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15536 ps.setInstalled(true, user.getIdentifier()); 15537 } 15538 } else { 15539 // This is a system app, so we assume that the 15540 // other users still have this package installed, so all 15541 // we need to do is clear this user's data and save that 15542 // it is uninstalled. 15543 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15544 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15545 return false; 15546 } 15547 scheduleWritePackageRestrictionsLocked(user); 15548 return true; 15549 } 15550 } 15551 15552 // If we are deleting a composite package for all users, keep track 15553 // of result for each child. 15554 if (ps.childPackageNames != null && outInfo != null) { 15555 synchronized (mPackages) { 15556 final int childCount = ps.childPackageNames.size(); 15557 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15558 for (int i = 0; i < childCount; i++) { 15559 String childPackageName = ps.childPackageNames.get(i); 15560 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15561 childInfo.removedPackage = childPackageName; 15562 outInfo.removedChildPackages.put(childPackageName, childInfo); 15563 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15564 if (childPs != null) { 15565 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15566 } 15567 } 15568 } 15569 } 15570 15571 boolean ret = false; 15572 if (isSystemApp(ps)) { 15573 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15574 // When an updated system application is deleted we delete the existing resources 15575 // as well and fall back to existing code in system partition 15576 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15577 } else { 15578 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15579 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15580 outInfo, writeSettings, replacingPackage); 15581 } 15582 15583 // Take a note whether we deleted the package for all users 15584 if (outInfo != null) { 15585 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15586 if (outInfo.removedChildPackages != null) { 15587 synchronized (mPackages) { 15588 final int childCount = outInfo.removedChildPackages.size(); 15589 for (int i = 0; i < childCount; i++) { 15590 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15591 if (childInfo != null) { 15592 childInfo.removedForAllUsers = mPackages.get( 15593 childInfo.removedPackage) == null; 15594 } 15595 } 15596 } 15597 } 15598 // If we uninstalled an update to a system app there may be some 15599 // child packages that appeared as they are declared in the system 15600 // app but were not declared in the update. 15601 if (isSystemApp(ps)) { 15602 synchronized (mPackages) { 15603 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15604 final int childCount = (updatedPs.childPackageNames != null) 15605 ? updatedPs.childPackageNames.size() : 0; 15606 for (int i = 0; i < childCount; i++) { 15607 String childPackageName = updatedPs.childPackageNames.get(i); 15608 if (outInfo.removedChildPackages == null 15609 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15610 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15611 if (childPs == null) { 15612 continue; 15613 } 15614 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15615 installRes.name = childPackageName; 15616 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15617 installRes.pkg = mPackages.get(childPackageName); 15618 installRes.uid = childPs.pkg.applicationInfo.uid; 15619 if (outInfo.appearedChildPackages == null) { 15620 outInfo.appearedChildPackages = new ArrayMap<>(); 15621 } 15622 outInfo.appearedChildPackages.put(childPackageName, installRes); 15623 } 15624 } 15625 } 15626 } 15627 } 15628 15629 return ret; 15630 } 15631 15632 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15633 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15634 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15635 for (int nextUserId : userIds) { 15636 if (DEBUG_REMOVE) { 15637 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15638 } 15639 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15640 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15641 false /*hidden*/, false /*suspended*/, null, null, null, 15642 false /*blockUninstall*/, 15643 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15644 } 15645 } 15646 15647 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15648 PackageRemovedInfo outInfo) { 15649 final PackageParser.Package pkg; 15650 synchronized (mPackages) { 15651 pkg = mPackages.get(ps.name); 15652 } 15653 15654 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15655 : new int[] {userId}; 15656 for (int nextUserId : userIds) { 15657 if (DEBUG_REMOVE) { 15658 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15659 + nextUserId); 15660 } 15661 15662 destroyAppDataLIF(pkg, userId, 15663 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15664 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15665 schedulePackageCleaning(ps.name, nextUserId, false); 15666 synchronized (mPackages) { 15667 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15668 scheduleWritePackageRestrictionsLocked(nextUserId); 15669 } 15670 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15671 } 15672 } 15673 15674 if (outInfo != null) { 15675 outInfo.removedPackage = ps.name; 15676 outInfo.removedAppId = ps.appId; 15677 outInfo.removedUsers = userIds; 15678 } 15679 15680 return true; 15681 } 15682 15683 private final class ClearStorageConnection implements ServiceConnection { 15684 IMediaContainerService mContainerService; 15685 15686 @Override 15687 public void onServiceConnected(ComponentName name, IBinder service) { 15688 synchronized (this) { 15689 mContainerService = IMediaContainerService.Stub.asInterface(service); 15690 notifyAll(); 15691 } 15692 } 15693 15694 @Override 15695 public void onServiceDisconnected(ComponentName name) { 15696 } 15697 } 15698 15699 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15700 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15701 15702 final boolean mounted; 15703 if (Environment.isExternalStorageEmulated()) { 15704 mounted = true; 15705 } else { 15706 final String status = Environment.getExternalStorageState(); 15707 15708 mounted = status.equals(Environment.MEDIA_MOUNTED) 15709 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15710 } 15711 15712 if (!mounted) { 15713 return; 15714 } 15715 15716 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15717 int[] users; 15718 if (userId == UserHandle.USER_ALL) { 15719 users = sUserManager.getUserIds(); 15720 } else { 15721 users = new int[] { userId }; 15722 } 15723 final ClearStorageConnection conn = new ClearStorageConnection(); 15724 if (mContext.bindServiceAsUser( 15725 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15726 try { 15727 for (int curUser : users) { 15728 long timeout = SystemClock.uptimeMillis() + 5000; 15729 synchronized (conn) { 15730 long now = SystemClock.uptimeMillis(); 15731 while (conn.mContainerService == null && now < timeout) { 15732 try { 15733 conn.wait(timeout - now); 15734 } catch (InterruptedException e) { 15735 } 15736 } 15737 } 15738 if (conn.mContainerService == null) { 15739 return; 15740 } 15741 15742 final UserEnvironment userEnv = new UserEnvironment(curUser); 15743 clearDirectory(conn.mContainerService, 15744 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15745 if (allData) { 15746 clearDirectory(conn.mContainerService, 15747 userEnv.buildExternalStorageAppDataDirs(packageName)); 15748 clearDirectory(conn.mContainerService, 15749 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15750 } 15751 } 15752 } finally { 15753 mContext.unbindService(conn); 15754 } 15755 } 15756 } 15757 15758 @Override 15759 public void clearApplicationProfileData(String packageName) { 15760 enforceSystemOrRoot("Only the system can clear all profile data"); 15761 15762 final PackageParser.Package pkg; 15763 synchronized (mPackages) { 15764 pkg = mPackages.get(packageName); 15765 } 15766 15767 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15768 synchronized (mInstallLock) { 15769 clearAppProfilesLIF(pkg); 15770 } 15771 } 15772 } 15773 15774 @Override 15775 public void clearApplicationUserData(final String packageName, 15776 final IPackageDataObserver observer, final int userId) { 15777 mContext.enforceCallingOrSelfPermission( 15778 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15779 15780 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15781 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15782 15783 final DevicePolicyManagerInternal dpmi = LocalServices 15784 .getService(DevicePolicyManagerInternal.class); 15785 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15786 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15787 } 15788 // Queue up an async operation since the package deletion may take a little while. 15789 mHandler.post(new Runnable() { 15790 public void run() { 15791 mHandler.removeCallbacks(this); 15792 final boolean succeeded; 15793 try (PackageFreezer freezer = freezePackage(packageName, 15794 "clearApplicationUserData")) { 15795 synchronized (mInstallLock) { 15796 succeeded = clearApplicationUserDataLIF(packageName, userId); 15797 } 15798 clearExternalStorageDataSync(packageName, userId, true); 15799 } 15800 if (succeeded) { 15801 // invoke DeviceStorageMonitor's update method to clear any notifications 15802 DeviceStorageMonitorInternal dsm = LocalServices 15803 .getService(DeviceStorageMonitorInternal.class); 15804 if (dsm != null) { 15805 dsm.checkMemory(); 15806 } 15807 } 15808 if(observer != null) { 15809 try { 15810 observer.onRemoveCompleted(packageName, succeeded); 15811 } catch (RemoteException e) { 15812 Log.i(TAG, "Observer no longer exists."); 15813 } 15814 } //end if observer 15815 } //end run 15816 }); 15817 } 15818 15819 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15820 if (packageName == null) { 15821 Slog.w(TAG, "Attempt to delete null packageName."); 15822 return false; 15823 } 15824 15825 // Try finding details about the requested package 15826 PackageParser.Package pkg; 15827 synchronized (mPackages) { 15828 pkg = mPackages.get(packageName); 15829 if (pkg == null) { 15830 final PackageSetting ps = mSettings.mPackages.get(packageName); 15831 if (ps != null) { 15832 pkg = ps.pkg; 15833 } 15834 } 15835 15836 if (pkg == null) { 15837 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15838 return false; 15839 } 15840 15841 PackageSetting ps = (PackageSetting) pkg.mExtras; 15842 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15843 } 15844 15845 clearAppDataLIF(pkg, userId, 15846 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15847 15848 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15849 removeKeystoreDataIfNeeded(userId, appId); 15850 15851 final UserManager um = mContext.getSystemService(UserManager.class); 15852 final int flags; 15853 if (um.isUserUnlocked(userId)) { 15854 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15855 } else if (um.isUserRunning(userId)) { 15856 flags = StorageManager.FLAG_STORAGE_DE; 15857 } else { 15858 flags = 0; 15859 } 15860 prepareAppDataContentsLIF(pkg, userId, flags); 15861 15862 return true; 15863 } 15864 15865 /** 15866 * Reverts user permission state changes (permissions and flags) in 15867 * all packages for a given user. 15868 * 15869 * @param userId The device user for which to do a reset. 15870 */ 15871 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15872 final int packageCount = mPackages.size(); 15873 for (int i = 0; i < packageCount; i++) { 15874 PackageParser.Package pkg = mPackages.valueAt(i); 15875 PackageSetting ps = (PackageSetting) pkg.mExtras; 15876 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15877 } 15878 } 15879 15880 /** 15881 * Reverts user permission state changes (permissions and flags). 15882 * 15883 * @param ps The package for which to reset. 15884 * @param userId The device user for which to do a reset. 15885 */ 15886 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15887 final PackageSetting ps, final int userId) { 15888 if (ps.pkg == null) { 15889 return; 15890 } 15891 15892 // These are flags that can change base on user actions. 15893 final int userSettableMask = FLAG_PERMISSION_USER_SET 15894 | FLAG_PERMISSION_USER_FIXED 15895 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15896 | FLAG_PERMISSION_REVIEW_REQUIRED; 15897 15898 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15899 | FLAG_PERMISSION_POLICY_FIXED; 15900 15901 boolean writeInstallPermissions = false; 15902 boolean writeRuntimePermissions = false; 15903 15904 final int permissionCount = ps.pkg.requestedPermissions.size(); 15905 for (int i = 0; i < permissionCount; i++) { 15906 String permission = ps.pkg.requestedPermissions.get(i); 15907 15908 BasePermission bp = mSettings.mPermissions.get(permission); 15909 if (bp == null) { 15910 continue; 15911 } 15912 15913 // If shared user we just reset the state to which only this app contributed. 15914 if (ps.sharedUser != null) { 15915 boolean used = false; 15916 final int packageCount = ps.sharedUser.packages.size(); 15917 for (int j = 0; j < packageCount; j++) { 15918 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15919 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15920 && pkg.pkg.requestedPermissions.contains(permission)) { 15921 used = true; 15922 break; 15923 } 15924 } 15925 if (used) { 15926 continue; 15927 } 15928 } 15929 15930 PermissionsState permissionsState = ps.getPermissionsState(); 15931 15932 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15933 15934 // Always clear the user settable flags. 15935 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15936 bp.name) != null; 15937 // If permission review is enabled and this is a legacy app, mark the 15938 // permission as requiring a review as this is the initial state. 15939 int flags = 0; 15940 if (Build.PERMISSIONS_REVIEW_REQUIRED 15941 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15942 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15943 } 15944 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15945 if (hasInstallState) { 15946 writeInstallPermissions = true; 15947 } else { 15948 writeRuntimePermissions = true; 15949 } 15950 } 15951 15952 // Below is only runtime permission handling. 15953 if (!bp.isRuntime()) { 15954 continue; 15955 } 15956 15957 // Never clobber system or policy. 15958 if ((oldFlags & policyOrSystemFlags) != 0) { 15959 continue; 15960 } 15961 15962 // If this permission was granted by default, make sure it is. 15963 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15964 if (permissionsState.grantRuntimePermission(bp, userId) 15965 != PERMISSION_OPERATION_FAILURE) { 15966 writeRuntimePermissions = true; 15967 } 15968 // If permission review is enabled the permissions for a legacy apps 15969 // are represented as constantly granted runtime ones, so don't revoke. 15970 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15971 // Otherwise, reset the permission. 15972 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15973 switch (revokeResult) { 15974 case PERMISSION_OPERATION_SUCCESS: 15975 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15976 writeRuntimePermissions = true; 15977 final int appId = ps.appId; 15978 mHandler.post(new Runnable() { 15979 @Override 15980 public void run() { 15981 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15982 } 15983 }); 15984 } break; 15985 } 15986 } 15987 } 15988 15989 // Synchronously write as we are taking permissions away. 15990 if (writeRuntimePermissions) { 15991 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 15992 } 15993 15994 // Synchronously write as we are taking permissions away. 15995 if (writeInstallPermissions) { 15996 mSettings.writeLPr(); 15997 } 15998 } 15999 16000 /** 16001 * Remove entries from the keystore daemon. Will only remove it if the 16002 * {@code appId} is valid. 16003 */ 16004 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16005 if (appId < 0) { 16006 return; 16007 } 16008 16009 final KeyStore keyStore = KeyStore.getInstance(); 16010 if (keyStore != null) { 16011 if (userId == UserHandle.USER_ALL) { 16012 for (final int individual : sUserManager.getUserIds()) { 16013 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16014 } 16015 } else { 16016 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16017 } 16018 } else { 16019 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16020 } 16021 } 16022 16023 @Override 16024 public void deleteApplicationCacheFiles(final String packageName, 16025 final IPackageDataObserver observer) { 16026 final int userId = UserHandle.getCallingUserId(); 16027 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16028 } 16029 16030 @Override 16031 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16032 final IPackageDataObserver observer) { 16033 mContext.enforceCallingOrSelfPermission( 16034 android.Manifest.permission.DELETE_CACHE_FILES, null); 16035 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16036 /* requireFullPermission= */ true, /* checkShell= */ false, 16037 "delete application cache files"); 16038 16039 final PackageParser.Package pkg; 16040 synchronized (mPackages) { 16041 pkg = mPackages.get(packageName); 16042 } 16043 16044 // Queue up an async operation since the package deletion may take a little while. 16045 mHandler.post(new Runnable() { 16046 public void run() { 16047 synchronized (mInstallLock) { 16048 final int flags = StorageManager.FLAG_STORAGE_DE 16049 | StorageManager.FLAG_STORAGE_CE; 16050 // We're only clearing cache files, so we don't care if the 16051 // app is unfrozen and still able to run 16052 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16053 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16054 } 16055 clearExternalStorageDataSync(packageName, userId, false); 16056 if (observer != null) { 16057 try { 16058 observer.onRemoveCompleted(packageName, true); 16059 } catch (RemoteException e) { 16060 Log.i(TAG, "Observer no longer exists."); 16061 } 16062 } 16063 } 16064 }); 16065 } 16066 16067 @Override 16068 public void getPackageSizeInfo(final String packageName, int userHandle, 16069 final IPackageStatsObserver observer) { 16070 mContext.enforceCallingOrSelfPermission( 16071 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16072 if (packageName == null) { 16073 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16074 } 16075 16076 PackageStats stats = new PackageStats(packageName, userHandle); 16077 16078 /* 16079 * Queue up an async operation since the package measurement may take a 16080 * little while. 16081 */ 16082 Message msg = mHandler.obtainMessage(INIT_COPY); 16083 msg.obj = new MeasureParams(stats, observer); 16084 mHandler.sendMessage(msg); 16085 } 16086 16087 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16088 final PackageSetting ps; 16089 synchronized (mPackages) { 16090 ps = mSettings.mPackages.get(packageName); 16091 if (ps == null) { 16092 Slog.w(TAG, "Failed to find settings for " + packageName); 16093 return false; 16094 } 16095 } 16096 try { 16097 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16098 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16099 ps.getCeDataInode(userId), ps.codePathString, stats); 16100 } catch (InstallerException e) { 16101 Slog.w(TAG, String.valueOf(e)); 16102 return false; 16103 } 16104 16105 // For now, ignore code size of packages on system partition 16106 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16107 stats.codeSize = 0; 16108 } 16109 16110 return true; 16111 } 16112 16113 private int getUidTargetSdkVersionLockedLPr(int uid) { 16114 Object obj = mSettings.getUserIdLPr(uid); 16115 if (obj instanceof SharedUserSetting) { 16116 final SharedUserSetting sus = (SharedUserSetting) obj; 16117 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16118 final Iterator<PackageSetting> it = sus.packages.iterator(); 16119 while (it.hasNext()) { 16120 final PackageSetting ps = it.next(); 16121 if (ps.pkg != null) { 16122 int v = ps.pkg.applicationInfo.targetSdkVersion; 16123 if (v < vers) vers = v; 16124 } 16125 } 16126 return vers; 16127 } else if (obj instanceof PackageSetting) { 16128 final PackageSetting ps = (PackageSetting) obj; 16129 if (ps.pkg != null) { 16130 return ps.pkg.applicationInfo.targetSdkVersion; 16131 } 16132 } 16133 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16134 } 16135 16136 @Override 16137 public void addPreferredActivity(IntentFilter filter, int match, 16138 ComponentName[] set, ComponentName activity, int userId) { 16139 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16140 "Adding preferred"); 16141 } 16142 16143 private void addPreferredActivityInternal(IntentFilter filter, int match, 16144 ComponentName[] set, ComponentName activity, boolean always, int userId, 16145 String opname) { 16146 // writer 16147 int callingUid = Binder.getCallingUid(); 16148 enforceCrossUserPermission(callingUid, userId, 16149 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16150 if (filter.countActions() == 0) { 16151 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16152 return; 16153 } 16154 synchronized (mPackages) { 16155 if (mContext.checkCallingOrSelfPermission( 16156 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16157 != PackageManager.PERMISSION_GRANTED) { 16158 if (getUidTargetSdkVersionLockedLPr(callingUid) 16159 < Build.VERSION_CODES.FROYO) { 16160 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16161 + callingUid); 16162 return; 16163 } 16164 mContext.enforceCallingOrSelfPermission( 16165 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16166 } 16167 16168 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16169 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16170 + userId + ":"); 16171 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16172 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16173 scheduleWritePackageRestrictionsLocked(userId); 16174 } 16175 } 16176 16177 @Override 16178 public void replacePreferredActivity(IntentFilter filter, int match, 16179 ComponentName[] set, ComponentName activity, int userId) { 16180 if (filter.countActions() != 1) { 16181 throw new IllegalArgumentException( 16182 "replacePreferredActivity expects filter to have only 1 action."); 16183 } 16184 if (filter.countDataAuthorities() != 0 16185 || filter.countDataPaths() != 0 16186 || filter.countDataSchemes() > 1 16187 || filter.countDataTypes() != 0) { 16188 throw new IllegalArgumentException( 16189 "replacePreferredActivity expects filter to have no data authorities, " + 16190 "paths, or types; and at most one scheme."); 16191 } 16192 16193 final int callingUid = Binder.getCallingUid(); 16194 enforceCrossUserPermission(callingUid, userId, 16195 true /* requireFullPermission */, false /* checkShell */, 16196 "replace preferred activity"); 16197 synchronized (mPackages) { 16198 if (mContext.checkCallingOrSelfPermission( 16199 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16200 != PackageManager.PERMISSION_GRANTED) { 16201 if (getUidTargetSdkVersionLockedLPr(callingUid) 16202 < Build.VERSION_CODES.FROYO) { 16203 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16204 + Binder.getCallingUid()); 16205 return; 16206 } 16207 mContext.enforceCallingOrSelfPermission( 16208 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16209 } 16210 16211 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16212 if (pir != null) { 16213 // Get all of the existing entries that exactly match this filter. 16214 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16215 if (existing != null && existing.size() == 1) { 16216 PreferredActivity cur = existing.get(0); 16217 if (DEBUG_PREFERRED) { 16218 Slog.i(TAG, "Checking replace of preferred:"); 16219 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16220 if (!cur.mPref.mAlways) { 16221 Slog.i(TAG, " -- CUR; not mAlways!"); 16222 } else { 16223 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16224 Slog.i(TAG, " -- CUR: mSet=" 16225 + Arrays.toString(cur.mPref.mSetComponents)); 16226 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16227 Slog.i(TAG, " -- NEW: mMatch=" 16228 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16229 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16230 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16231 } 16232 } 16233 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16234 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16235 && cur.mPref.sameSet(set)) { 16236 // Setting the preferred activity to what it happens to be already 16237 if (DEBUG_PREFERRED) { 16238 Slog.i(TAG, "Replacing with same preferred activity " 16239 + cur.mPref.mShortComponent + " for user " 16240 + userId + ":"); 16241 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16242 } 16243 return; 16244 } 16245 } 16246 16247 if (existing != null) { 16248 if (DEBUG_PREFERRED) { 16249 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16250 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16251 } 16252 for (int i = 0; i < existing.size(); i++) { 16253 PreferredActivity pa = existing.get(i); 16254 if (DEBUG_PREFERRED) { 16255 Slog.i(TAG, "Removing existing preferred activity " 16256 + pa.mPref.mComponent + ":"); 16257 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16258 } 16259 pir.removeFilter(pa); 16260 } 16261 } 16262 } 16263 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16264 "Replacing preferred"); 16265 } 16266 } 16267 16268 @Override 16269 public void clearPackagePreferredActivities(String packageName) { 16270 final int uid = Binder.getCallingUid(); 16271 // writer 16272 synchronized (mPackages) { 16273 PackageParser.Package pkg = mPackages.get(packageName); 16274 if (pkg == null || pkg.applicationInfo.uid != uid) { 16275 if (mContext.checkCallingOrSelfPermission( 16276 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16277 != PackageManager.PERMISSION_GRANTED) { 16278 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16279 < Build.VERSION_CODES.FROYO) { 16280 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16281 + Binder.getCallingUid()); 16282 return; 16283 } 16284 mContext.enforceCallingOrSelfPermission( 16285 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16286 } 16287 } 16288 16289 int user = UserHandle.getCallingUserId(); 16290 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16291 scheduleWritePackageRestrictionsLocked(user); 16292 } 16293 } 16294 } 16295 16296 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16297 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16298 ArrayList<PreferredActivity> removed = null; 16299 boolean changed = false; 16300 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16301 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16302 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16303 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16304 continue; 16305 } 16306 Iterator<PreferredActivity> it = pir.filterIterator(); 16307 while (it.hasNext()) { 16308 PreferredActivity pa = it.next(); 16309 // Mark entry for removal only if it matches the package name 16310 // and the entry is of type "always". 16311 if (packageName == null || 16312 (pa.mPref.mComponent.getPackageName().equals(packageName) 16313 && pa.mPref.mAlways)) { 16314 if (removed == null) { 16315 removed = new ArrayList<PreferredActivity>(); 16316 } 16317 removed.add(pa); 16318 } 16319 } 16320 if (removed != null) { 16321 for (int j=0; j<removed.size(); j++) { 16322 PreferredActivity pa = removed.get(j); 16323 pir.removeFilter(pa); 16324 } 16325 changed = true; 16326 } 16327 } 16328 return changed; 16329 } 16330 16331 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16332 private void clearIntentFilterVerificationsLPw(int userId) { 16333 final int packageCount = mPackages.size(); 16334 for (int i = 0; i < packageCount; i++) { 16335 PackageParser.Package pkg = mPackages.valueAt(i); 16336 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16337 } 16338 } 16339 16340 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16341 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16342 if (userId == UserHandle.USER_ALL) { 16343 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16344 sUserManager.getUserIds())) { 16345 for (int oneUserId : sUserManager.getUserIds()) { 16346 scheduleWritePackageRestrictionsLocked(oneUserId); 16347 } 16348 } 16349 } else { 16350 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16351 scheduleWritePackageRestrictionsLocked(userId); 16352 } 16353 } 16354 } 16355 16356 void clearDefaultBrowserIfNeeded(String packageName) { 16357 for (int oneUserId : sUserManager.getUserIds()) { 16358 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16359 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16360 if (packageName.equals(defaultBrowserPackageName)) { 16361 setDefaultBrowserPackageName(null, oneUserId); 16362 } 16363 } 16364 } 16365 16366 @Override 16367 public void resetApplicationPreferences(int userId) { 16368 mContext.enforceCallingOrSelfPermission( 16369 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16370 // writer 16371 synchronized (mPackages) { 16372 final long identity = Binder.clearCallingIdentity(); 16373 try { 16374 clearPackagePreferredActivitiesLPw(null, userId); 16375 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16376 // TODO: We have to reset the default SMS and Phone. This requires 16377 // significant refactoring to keep all default apps in the package 16378 // manager (cleaner but more work) or have the services provide 16379 // callbacks to the package manager to request a default app reset. 16380 applyFactoryDefaultBrowserLPw(userId); 16381 clearIntentFilterVerificationsLPw(userId); 16382 primeDomainVerificationsLPw(userId); 16383 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16384 scheduleWritePackageRestrictionsLocked(userId); 16385 } finally { 16386 Binder.restoreCallingIdentity(identity); 16387 } 16388 } 16389 } 16390 16391 @Override 16392 public int getPreferredActivities(List<IntentFilter> outFilters, 16393 List<ComponentName> outActivities, String packageName) { 16394 16395 int num = 0; 16396 final int userId = UserHandle.getCallingUserId(); 16397 // reader 16398 synchronized (mPackages) { 16399 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16400 if (pir != null) { 16401 final Iterator<PreferredActivity> it = pir.filterIterator(); 16402 while (it.hasNext()) { 16403 final PreferredActivity pa = it.next(); 16404 if (packageName == null 16405 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16406 && pa.mPref.mAlways)) { 16407 if (outFilters != null) { 16408 outFilters.add(new IntentFilter(pa)); 16409 } 16410 if (outActivities != null) { 16411 outActivities.add(pa.mPref.mComponent); 16412 } 16413 } 16414 } 16415 } 16416 } 16417 16418 return num; 16419 } 16420 16421 @Override 16422 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16423 int userId) { 16424 int callingUid = Binder.getCallingUid(); 16425 if (callingUid != Process.SYSTEM_UID) { 16426 throw new SecurityException( 16427 "addPersistentPreferredActivity can only be run by the system"); 16428 } 16429 if (filter.countActions() == 0) { 16430 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16431 return; 16432 } 16433 synchronized (mPackages) { 16434 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16435 ":"); 16436 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16437 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16438 new PersistentPreferredActivity(filter, activity)); 16439 scheduleWritePackageRestrictionsLocked(userId); 16440 } 16441 } 16442 16443 @Override 16444 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16445 int callingUid = Binder.getCallingUid(); 16446 if (callingUid != Process.SYSTEM_UID) { 16447 throw new SecurityException( 16448 "clearPackagePersistentPreferredActivities can only be run by the system"); 16449 } 16450 ArrayList<PersistentPreferredActivity> removed = null; 16451 boolean changed = false; 16452 synchronized (mPackages) { 16453 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16454 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16455 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16456 .valueAt(i); 16457 if (userId != thisUserId) { 16458 continue; 16459 } 16460 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16461 while (it.hasNext()) { 16462 PersistentPreferredActivity ppa = it.next(); 16463 // Mark entry for removal only if it matches the package name. 16464 if (ppa.mComponent.getPackageName().equals(packageName)) { 16465 if (removed == null) { 16466 removed = new ArrayList<PersistentPreferredActivity>(); 16467 } 16468 removed.add(ppa); 16469 } 16470 } 16471 if (removed != null) { 16472 for (int j=0; j<removed.size(); j++) { 16473 PersistentPreferredActivity ppa = removed.get(j); 16474 ppir.removeFilter(ppa); 16475 } 16476 changed = true; 16477 } 16478 } 16479 16480 if (changed) { 16481 scheduleWritePackageRestrictionsLocked(userId); 16482 } 16483 } 16484 } 16485 16486 /** 16487 * Common machinery for picking apart a restored XML blob and passing 16488 * it to a caller-supplied functor to be applied to the running system. 16489 */ 16490 private void restoreFromXml(XmlPullParser parser, int userId, 16491 String expectedStartTag, BlobXmlRestorer functor) 16492 throws IOException, XmlPullParserException { 16493 int type; 16494 while ((type = parser.next()) != XmlPullParser.START_TAG 16495 && type != XmlPullParser.END_DOCUMENT) { 16496 } 16497 if (type != XmlPullParser.START_TAG) { 16498 // oops didn't find a start tag?! 16499 if (DEBUG_BACKUP) { 16500 Slog.e(TAG, "Didn't find start tag during restore"); 16501 } 16502 return; 16503 } 16504Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16505 // this is supposed to be TAG_PREFERRED_BACKUP 16506 if (!expectedStartTag.equals(parser.getName())) { 16507 if (DEBUG_BACKUP) { 16508 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16509 } 16510 return; 16511 } 16512 16513 // skip interfering stuff, then we're aligned with the backing implementation 16514 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16515Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16516 functor.apply(parser, userId); 16517 } 16518 16519 private interface BlobXmlRestorer { 16520 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16521 } 16522 16523 /** 16524 * Non-Binder method, support for the backup/restore mechanism: write the 16525 * full set of preferred activities in its canonical XML format. Returns the 16526 * XML output as a byte array, or null if there is none. 16527 */ 16528 @Override 16529 public byte[] getPreferredActivityBackup(int userId) { 16530 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16531 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16532 } 16533 16534 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16535 try { 16536 final XmlSerializer serializer = new FastXmlSerializer(); 16537 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16538 serializer.startDocument(null, true); 16539 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16540 16541 synchronized (mPackages) { 16542 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16543 } 16544 16545 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16546 serializer.endDocument(); 16547 serializer.flush(); 16548 } catch (Exception e) { 16549 if (DEBUG_BACKUP) { 16550 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16551 } 16552 return null; 16553 } 16554 16555 return dataStream.toByteArray(); 16556 } 16557 16558 @Override 16559 public void restorePreferredActivities(byte[] backup, int userId) { 16560 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16561 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16562 } 16563 16564 try { 16565 final XmlPullParser parser = Xml.newPullParser(); 16566 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16567 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16568 new BlobXmlRestorer() { 16569 @Override 16570 public void apply(XmlPullParser parser, int userId) 16571 throws XmlPullParserException, IOException { 16572 synchronized (mPackages) { 16573 mSettings.readPreferredActivitiesLPw(parser, userId); 16574 } 16575 } 16576 } ); 16577 } catch (Exception e) { 16578 if (DEBUG_BACKUP) { 16579 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16580 } 16581 } 16582 } 16583 16584 /** 16585 * Non-Binder method, support for the backup/restore mechanism: write the 16586 * default browser (etc) settings in its canonical XML format. Returns the default 16587 * browser XML representation as a byte array, or null if there is none. 16588 */ 16589 @Override 16590 public byte[] getDefaultAppsBackup(int userId) { 16591 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16592 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16593 } 16594 16595 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16596 try { 16597 final XmlSerializer serializer = new FastXmlSerializer(); 16598 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16599 serializer.startDocument(null, true); 16600 serializer.startTag(null, TAG_DEFAULT_APPS); 16601 16602 synchronized (mPackages) { 16603 mSettings.writeDefaultAppsLPr(serializer, userId); 16604 } 16605 16606 serializer.endTag(null, TAG_DEFAULT_APPS); 16607 serializer.endDocument(); 16608 serializer.flush(); 16609 } catch (Exception e) { 16610 if (DEBUG_BACKUP) { 16611 Slog.e(TAG, "Unable to write default apps for backup", e); 16612 } 16613 return null; 16614 } 16615 16616 return dataStream.toByteArray(); 16617 } 16618 16619 @Override 16620 public void restoreDefaultApps(byte[] backup, int userId) { 16621 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16622 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16623 } 16624 16625 try { 16626 final XmlPullParser parser = Xml.newPullParser(); 16627 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16628 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16629 new BlobXmlRestorer() { 16630 @Override 16631 public void apply(XmlPullParser parser, int userId) 16632 throws XmlPullParserException, IOException { 16633 synchronized (mPackages) { 16634 mSettings.readDefaultAppsLPw(parser, userId); 16635 } 16636 } 16637 } ); 16638 } catch (Exception e) { 16639 if (DEBUG_BACKUP) { 16640 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16641 } 16642 } 16643 } 16644 16645 @Override 16646 public byte[] getIntentFilterVerificationBackup(int userId) { 16647 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16648 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16649 } 16650 16651 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16652 try { 16653 final XmlSerializer serializer = new FastXmlSerializer(); 16654 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16655 serializer.startDocument(null, true); 16656 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16657 16658 synchronized (mPackages) { 16659 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16660 } 16661 16662 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16663 serializer.endDocument(); 16664 serializer.flush(); 16665 } catch (Exception e) { 16666 if (DEBUG_BACKUP) { 16667 Slog.e(TAG, "Unable to write default apps for backup", e); 16668 } 16669 return null; 16670 } 16671 16672 return dataStream.toByteArray(); 16673 } 16674 16675 @Override 16676 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16677 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16678 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16679 } 16680 16681 try { 16682 final XmlPullParser parser = Xml.newPullParser(); 16683 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16684 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16685 new BlobXmlRestorer() { 16686 @Override 16687 public void apply(XmlPullParser parser, int userId) 16688 throws XmlPullParserException, IOException { 16689 synchronized (mPackages) { 16690 mSettings.readAllDomainVerificationsLPr(parser, userId); 16691 mSettings.writeLPr(); 16692 } 16693 } 16694 } ); 16695 } catch (Exception e) { 16696 if (DEBUG_BACKUP) { 16697 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16698 } 16699 } 16700 } 16701 16702 @Override 16703 public byte[] getPermissionGrantBackup(int userId) { 16704 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16705 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16706 } 16707 16708 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16709 try { 16710 final XmlSerializer serializer = new FastXmlSerializer(); 16711 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16712 serializer.startDocument(null, true); 16713 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16714 16715 synchronized (mPackages) { 16716 serializeRuntimePermissionGrantsLPr(serializer, userId); 16717 } 16718 16719 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16720 serializer.endDocument(); 16721 serializer.flush(); 16722 } catch (Exception e) { 16723 if (DEBUG_BACKUP) { 16724 Slog.e(TAG, "Unable to write default apps for backup", e); 16725 } 16726 return null; 16727 } 16728 16729 return dataStream.toByteArray(); 16730 } 16731 16732 @Override 16733 public void restorePermissionGrants(byte[] backup, int userId) { 16734 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16735 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16736 } 16737 16738 try { 16739 final XmlPullParser parser = Xml.newPullParser(); 16740 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16741 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16742 new BlobXmlRestorer() { 16743 @Override 16744 public void apply(XmlPullParser parser, int userId) 16745 throws XmlPullParserException, IOException { 16746 synchronized (mPackages) { 16747 processRestoredPermissionGrantsLPr(parser, userId); 16748 } 16749 } 16750 } ); 16751 } catch (Exception e) { 16752 if (DEBUG_BACKUP) { 16753 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16754 } 16755 } 16756 } 16757 16758 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16759 throws IOException { 16760 serializer.startTag(null, TAG_ALL_GRANTS); 16761 16762 final int N = mSettings.mPackages.size(); 16763 for (int i = 0; i < N; i++) { 16764 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16765 boolean pkgGrantsKnown = false; 16766 16767 PermissionsState packagePerms = ps.getPermissionsState(); 16768 16769 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16770 final int grantFlags = state.getFlags(); 16771 // only look at grants that are not system/policy fixed 16772 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16773 final boolean isGranted = state.isGranted(); 16774 // And only back up the user-twiddled state bits 16775 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16776 final String packageName = mSettings.mPackages.keyAt(i); 16777 if (!pkgGrantsKnown) { 16778 serializer.startTag(null, TAG_GRANT); 16779 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16780 pkgGrantsKnown = true; 16781 } 16782 16783 final boolean userSet = 16784 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16785 final boolean userFixed = 16786 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16787 final boolean revoke = 16788 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16789 16790 serializer.startTag(null, TAG_PERMISSION); 16791 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16792 if (isGranted) { 16793 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16794 } 16795 if (userSet) { 16796 serializer.attribute(null, ATTR_USER_SET, "true"); 16797 } 16798 if (userFixed) { 16799 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16800 } 16801 if (revoke) { 16802 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16803 } 16804 serializer.endTag(null, TAG_PERMISSION); 16805 } 16806 } 16807 } 16808 16809 if (pkgGrantsKnown) { 16810 serializer.endTag(null, TAG_GRANT); 16811 } 16812 } 16813 16814 serializer.endTag(null, TAG_ALL_GRANTS); 16815 } 16816 16817 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16818 throws XmlPullParserException, IOException { 16819 String pkgName = null; 16820 int outerDepth = parser.getDepth(); 16821 int type; 16822 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16823 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16824 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16825 continue; 16826 } 16827 16828 final String tagName = parser.getName(); 16829 if (tagName.equals(TAG_GRANT)) { 16830 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16831 if (DEBUG_BACKUP) { 16832 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16833 } 16834 } else if (tagName.equals(TAG_PERMISSION)) { 16835 16836 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16837 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16838 16839 int newFlagSet = 0; 16840 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16841 newFlagSet |= FLAG_PERMISSION_USER_SET; 16842 } 16843 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16844 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16845 } 16846 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16847 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16848 } 16849 if (DEBUG_BACKUP) { 16850 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16851 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16852 } 16853 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16854 if (ps != null) { 16855 // Already installed so we apply the grant immediately 16856 if (DEBUG_BACKUP) { 16857 Slog.v(TAG, " + already installed; applying"); 16858 } 16859 PermissionsState perms = ps.getPermissionsState(); 16860 BasePermission bp = mSettings.mPermissions.get(permName); 16861 if (bp != null) { 16862 if (isGranted) { 16863 perms.grantRuntimePermission(bp, userId); 16864 } 16865 if (newFlagSet != 0) { 16866 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16867 } 16868 } 16869 } else { 16870 // Need to wait for post-restore install to apply the grant 16871 if (DEBUG_BACKUP) { 16872 Slog.v(TAG, " - not yet installed; saving for later"); 16873 } 16874 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16875 isGranted, newFlagSet, userId); 16876 } 16877 } else { 16878 PackageManagerService.reportSettingsProblem(Log.WARN, 16879 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16880 XmlUtils.skipCurrentTag(parser); 16881 } 16882 } 16883 16884 scheduleWriteSettingsLocked(); 16885 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16886 } 16887 16888 @Override 16889 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16890 int sourceUserId, int targetUserId, int flags) { 16891 mContext.enforceCallingOrSelfPermission( 16892 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16893 int callingUid = Binder.getCallingUid(); 16894 enforceOwnerRights(ownerPackage, callingUid); 16895 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16896 if (intentFilter.countActions() == 0) { 16897 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16898 return; 16899 } 16900 synchronized (mPackages) { 16901 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16902 ownerPackage, targetUserId, flags); 16903 CrossProfileIntentResolver resolver = 16904 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16905 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16906 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16907 if (existing != null) { 16908 int size = existing.size(); 16909 for (int i = 0; i < size; i++) { 16910 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16911 return; 16912 } 16913 } 16914 } 16915 resolver.addFilter(newFilter); 16916 scheduleWritePackageRestrictionsLocked(sourceUserId); 16917 } 16918 } 16919 16920 @Override 16921 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16922 mContext.enforceCallingOrSelfPermission( 16923 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16924 int callingUid = Binder.getCallingUid(); 16925 enforceOwnerRights(ownerPackage, callingUid); 16926 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16927 synchronized (mPackages) { 16928 CrossProfileIntentResolver resolver = 16929 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16930 ArraySet<CrossProfileIntentFilter> set = 16931 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16932 for (CrossProfileIntentFilter filter : set) { 16933 if (filter.getOwnerPackage().equals(ownerPackage)) { 16934 resolver.removeFilter(filter); 16935 } 16936 } 16937 scheduleWritePackageRestrictionsLocked(sourceUserId); 16938 } 16939 } 16940 16941 // Enforcing that callingUid is owning pkg on userId 16942 private void enforceOwnerRights(String pkg, int callingUid) { 16943 // The system owns everything. 16944 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16945 return; 16946 } 16947 int callingUserId = UserHandle.getUserId(callingUid); 16948 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16949 if (pi == null) { 16950 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16951 + callingUserId); 16952 } 16953 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16954 throw new SecurityException("Calling uid " + callingUid 16955 + " does not own package " + pkg); 16956 } 16957 } 16958 16959 @Override 16960 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16961 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16962 } 16963 16964 private Intent getHomeIntent() { 16965 Intent intent = new Intent(Intent.ACTION_MAIN); 16966 intent.addCategory(Intent.CATEGORY_HOME); 16967 return intent; 16968 } 16969 16970 private IntentFilter getHomeFilter() { 16971 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16972 filter.addCategory(Intent.CATEGORY_HOME); 16973 filter.addCategory(Intent.CATEGORY_DEFAULT); 16974 return filter; 16975 } 16976 16977 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16978 int userId) { 16979 Intent intent = getHomeIntent(); 16980 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16981 PackageManager.GET_META_DATA, userId); 16982 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16983 true, false, false, userId); 16984 16985 allHomeCandidates.clear(); 16986 if (list != null) { 16987 for (ResolveInfo ri : list) { 16988 allHomeCandidates.add(ri); 16989 } 16990 } 16991 return (preferred == null || preferred.activityInfo == null) 16992 ? null 16993 : new ComponentName(preferred.activityInfo.packageName, 16994 preferred.activityInfo.name); 16995 } 16996 16997 @Override 16998 public void setHomeActivity(ComponentName comp, int userId) { 16999 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17000 getHomeActivitiesAsUser(homeActivities, userId); 17001 17002 boolean found = false; 17003 17004 final int size = homeActivities.size(); 17005 final ComponentName[] set = new ComponentName[size]; 17006 for (int i = 0; i < size; i++) { 17007 final ResolveInfo candidate = homeActivities.get(i); 17008 final ActivityInfo info = candidate.activityInfo; 17009 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17010 set[i] = activityName; 17011 if (!found && activityName.equals(comp)) { 17012 found = true; 17013 } 17014 } 17015 if (!found) { 17016 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17017 + userId); 17018 } 17019 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17020 set, comp, userId); 17021 } 17022 17023 private @Nullable String getSetupWizardPackageName() { 17024 final Intent intent = new Intent(Intent.ACTION_MAIN); 17025 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17026 17027 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17028 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17029 | MATCH_DISABLED_COMPONENTS, 17030 UserHandle.myUserId()); 17031 if (matches.size() == 1) { 17032 return matches.get(0).getComponentInfo().packageName; 17033 } else { 17034 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17035 + ": matches=" + matches); 17036 return null; 17037 } 17038 } 17039 17040 @Override 17041 public void setApplicationEnabledSetting(String appPackageName, 17042 int newState, int flags, int userId, String callingPackage) { 17043 if (!sUserManager.exists(userId)) return; 17044 if (callingPackage == null) { 17045 callingPackage = Integer.toString(Binder.getCallingUid()); 17046 } 17047 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17048 } 17049 17050 @Override 17051 public void setComponentEnabledSetting(ComponentName componentName, 17052 int newState, int flags, int userId) { 17053 if (!sUserManager.exists(userId)) return; 17054 setEnabledSetting(componentName.getPackageName(), 17055 componentName.getClassName(), newState, flags, userId, null); 17056 } 17057 17058 private void setEnabledSetting(final String packageName, String className, int newState, 17059 final int flags, int userId, String callingPackage) { 17060 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17061 || newState == COMPONENT_ENABLED_STATE_ENABLED 17062 || newState == COMPONENT_ENABLED_STATE_DISABLED 17063 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17064 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17065 throw new IllegalArgumentException("Invalid new component state: " 17066 + newState); 17067 } 17068 PackageSetting pkgSetting; 17069 final int uid = Binder.getCallingUid(); 17070 final int permission; 17071 if (uid == Process.SYSTEM_UID) { 17072 permission = PackageManager.PERMISSION_GRANTED; 17073 } else { 17074 permission = mContext.checkCallingOrSelfPermission( 17075 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17076 } 17077 enforceCrossUserPermission(uid, userId, 17078 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17079 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17080 boolean sendNow = false; 17081 boolean isApp = (className == null); 17082 String componentName = isApp ? packageName : className; 17083 int packageUid = -1; 17084 ArrayList<String> components; 17085 17086 // writer 17087 synchronized (mPackages) { 17088 pkgSetting = mSettings.mPackages.get(packageName); 17089 if (pkgSetting == null) { 17090 if (className == null) { 17091 throw new IllegalArgumentException("Unknown package: " + packageName); 17092 } 17093 throw new IllegalArgumentException( 17094 "Unknown component: " + packageName + "/" + className); 17095 } 17096 // Allow root and verify that userId is not being specified by a different user 17097 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17098 throw new SecurityException( 17099 "Permission Denial: attempt to change component state from pid=" 17100 + Binder.getCallingPid() 17101 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17102 } 17103 if (className == null) { 17104 // We're dealing with an application/package level state change 17105 if (pkgSetting.getEnabled(userId) == newState) { 17106 // Nothing to do 17107 return; 17108 } 17109 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17110 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17111 // Don't care about who enables an app. 17112 callingPackage = null; 17113 } 17114 pkgSetting.setEnabled(newState, userId, callingPackage); 17115 // pkgSetting.pkg.mSetEnabled = newState; 17116 } else { 17117 // We're dealing with a component level state change 17118 // First, verify that this is a valid class name. 17119 PackageParser.Package pkg = pkgSetting.pkg; 17120 if (pkg == null || !pkg.hasComponentClassName(className)) { 17121 if (pkg != null && 17122 pkg.applicationInfo.targetSdkVersion >= 17123 Build.VERSION_CODES.JELLY_BEAN) { 17124 throw new IllegalArgumentException("Component class " + className 17125 + " does not exist in " + packageName); 17126 } else { 17127 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17128 + className + " does not exist in " + packageName); 17129 } 17130 } 17131 switch (newState) { 17132 case COMPONENT_ENABLED_STATE_ENABLED: 17133 if (!pkgSetting.enableComponentLPw(className, userId)) { 17134 return; 17135 } 17136 break; 17137 case COMPONENT_ENABLED_STATE_DISABLED: 17138 if (!pkgSetting.disableComponentLPw(className, userId)) { 17139 return; 17140 } 17141 break; 17142 case COMPONENT_ENABLED_STATE_DEFAULT: 17143 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17144 return; 17145 } 17146 break; 17147 default: 17148 Slog.e(TAG, "Invalid new component state: " + newState); 17149 return; 17150 } 17151 } 17152 scheduleWritePackageRestrictionsLocked(userId); 17153 components = mPendingBroadcasts.get(userId, packageName); 17154 final boolean newPackage = components == null; 17155 if (newPackage) { 17156 components = new ArrayList<String>(); 17157 } 17158 if (!components.contains(componentName)) { 17159 components.add(componentName); 17160 } 17161 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17162 sendNow = true; 17163 // Purge entry from pending broadcast list if another one exists already 17164 // since we are sending one right away. 17165 mPendingBroadcasts.remove(userId, packageName); 17166 } else { 17167 if (newPackage) { 17168 mPendingBroadcasts.put(userId, packageName, components); 17169 } 17170 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17171 // Schedule a message 17172 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17173 } 17174 } 17175 } 17176 17177 long callingId = Binder.clearCallingIdentity(); 17178 try { 17179 if (sendNow) { 17180 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17181 sendPackageChangedBroadcast(packageName, 17182 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17183 } 17184 } finally { 17185 Binder.restoreCallingIdentity(callingId); 17186 } 17187 } 17188 17189 @Override 17190 public void flushPackageRestrictionsAsUser(int userId) { 17191 if (!sUserManager.exists(userId)) { 17192 return; 17193 } 17194 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17195 false /* checkShell */, "flushPackageRestrictions"); 17196 synchronized (mPackages) { 17197 mSettings.writePackageRestrictionsLPr(userId); 17198 mDirtyUsers.remove(userId); 17199 if (mDirtyUsers.isEmpty()) { 17200 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17201 } 17202 } 17203 } 17204 17205 private void sendPackageChangedBroadcast(String packageName, 17206 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17207 if (DEBUG_INSTALL) 17208 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17209 + componentNames); 17210 Bundle extras = new Bundle(4); 17211 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17212 String nameList[] = new String[componentNames.size()]; 17213 componentNames.toArray(nameList); 17214 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17215 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17216 extras.putInt(Intent.EXTRA_UID, packageUid); 17217 // If this is not reporting a change of the overall package, then only send it 17218 // to registered receivers. We don't want to launch a swath of apps for every 17219 // little component state change. 17220 final int flags = !componentNames.contains(packageName) 17221 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17222 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17223 new int[] {UserHandle.getUserId(packageUid)}); 17224 } 17225 17226 @Override 17227 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17228 if (!sUserManager.exists(userId)) return; 17229 final int uid = Binder.getCallingUid(); 17230 final int permission = mContext.checkCallingOrSelfPermission( 17231 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17232 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17233 enforceCrossUserPermission(uid, userId, 17234 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17235 // writer 17236 synchronized (mPackages) { 17237 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17238 allowedByPermission, uid, userId)) { 17239 scheduleWritePackageRestrictionsLocked(userId); 17240 } 17241 } 17242 } 17243 17244 @Override 17245 public String getInstallerPackageName(String packageName) { 17246 // reader 17247 synchronized (mPackages) { 17248 return mSettings.getInstallerPackageNameLPr(packageName); 17249 } 17250 } 17251 17252 @Override 17253 public int getApplicationEnabledSetting(String packageName, int userId) { 17254 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17255 int uid = Binder.getCallingUid(); 17256 enforceCrossUserPermission(uid, userId, 17257 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17258 // reader 17259 synchronized (mPackages) { 17260 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17261 } 17262 } 17263 17264 @Override 17265 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17266 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17267 int uid = Binder.getCallingUid(); 17268 enforceCrossUserPermission(uid, userId, 17269 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17270 // reader 17271 synchronized (mPackages) { 17272 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17273 } 17274 } 17275 17276 @Override 17277 public void enterSafeMode() { 17278 enforceSystemOrRoot("Only the system can request entering safe mode"); 17279 17280 if (!mSystemReady) { 17281 mSafeMode = true; 17282 } 17283 } 17284 17285 @Override 17286 public void systemReady() { 17287 mSystemReady = true; 17288 17289 // Read the compatibilty setting when the system is ready. 17290 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17291 mContext.getContentResolver(), 17292 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17293 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17294 if (DEBUG_SETTINGS) { 17295 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17296 } 17297 17298 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17299 17300 synchronized (mPackages) { 17301 // Verify that all of the preferred activity components actually 17302 // exist. It is possible for applications to be updated and at 17303 // that point remove a previously declared activity component that 17304 // had been set as a preferred activity. We try to clean this up 17305 // the next time we encounter that preferred activity, but it is 17306 // possible for the user flow to never be able to return to that 17307 // situation so here we do a sanity check to make sure we haven't 17308 // left any junk around. 17309 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17310 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17311 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17312 removed.clear(); 17313 for (PreferredActivity pa : pir.filterSet()) { 17314 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17315 removed.add(pa); 17316 } 17317 } 17318 if (removed.size() > 0) { 17319 for (int r=0; r<removed.size(); r++) { 17320 PreferredActivity pa = removed.get(r); 17321 Slog.w(TAG, "Removing dangling preferred activity: " 17322 + pa.mPref.mComponent); 17323 pir.removeFilter(pa); 17324 } 17325 mSettings.writePackageRestrictionsLPr( 17326 mSettings.mPreferredActivities.keyAt(i)); 17327 } 17328 } 17329 17330 for (int userId : UserManagerService.getInstance().getUserIds()) { 17331 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17332 grantPermissionsUserIds = ArrayUtils.appendInt( 17333 grantPermissionsUserIds, userId); 17334 } 17335 } 17336 } 17337 sUserManager.systemReady(); 17338 17339 // If we upgraded grant all default permissions before kicking off. 17340 for (int userId : grantPermissionsUserIds) { 17341 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17342 } 17343 17344 // Kick off any messages waiting for system ready 17345 if (mPostSystemReadyMessages != null) { 17346 for (Message msg : mPostSystemReadyMessages) { 17347 msg.sendToTarget(); 17348 } 17349 mPostSystemReadyMessages = null; 17350 } 17351 17352 // Watch for external volumes that come and go over time 17353 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17354 storage.registerListener(mStorageListener); 17355 17356 mInstallerService.systemReady(); 17357 mPackageDexOptimizer.systemReady(); 17358 17359 MountServiceInternal mountServiceInternal = LocalServices.getService( 17360 MountServiceInternal.class); 17361 mountServiceInternal.addExternalStoragePolicy( 17362 new MountServiceInternal.ExternalStorageMountPolicy() { 17363 @Override 17364 public int getMountMode(int uid, String packageName) { 17365 if (Process.isIsolated(uid)) { 17366 return Zygote.MOUNT_EXTERNAL_NONE; 17367 } 17368 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17369 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17370 } 17371 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17372 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17373 } 17374 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17375 return Zygote.MOUNT_EXTERNAL_READ; 17376 } 17377 return Zygote.MOUNT_EXTERNAL_WRITE; 17378 } 17379 17380 @Override 17381 public boolean hasExternalStorage(int uid, String packageName) { 17382 return true; 17383 } 17384 }); 17385 } 17386 17387 @Override 17388 public boolean isSafeMode() { 17389 return mSafeMode; 17390 } 17391 17392 @Override 17393 public boolean hasSystemUidErrors() { 17394 return mHasSystemUidErrors; 17395 } 17396 17397 static String arrayToString(int[] array) { 17398 StringBuffer buf = new StringBuffer(128); 17399 buf.append('['); 17400 if (array != null) { 17401 for (int i=0; i<array.length; i++) { 17402 if (i > 0) buf.append(", "); 17403 buf.append(array[i]); 17404 } 17405 } 17406 buf.append(']'); 17407 return buf.toString(); 17408 } 17409 17410 static class DumpState { 17411 public static final int DUMP_LIBS = 1 << 0; 17412 public static final int DUMP_FEATURES = 1 << 1; 17413 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17414 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17415 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17416 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17417 public static final int DUMP_PERMISSIONS = 1 << 6; 17418 public static final int DUMP_PACKAGES = 1 << 7; 17419 public static final int DUMP_SHARED_USERS = 1 << 8; 17420 public static final int DUMP_MESSAGES = 1 << 9; 17421 public static final int DUMP_PROVIDERS = 1 << 10; 17422 public static final int DUMP_VERIFIERS = 1 << 11; 17423 public static final int DUMP_PREFERRED = 1 << 12; 17424 public static final int DUMP_PREFERRED_XML = 1 << 13; 17425 public static final int DUMP_KEYSETS = 1 << 14; 17426 public static final int DUMP_VERSION = 1 << 15; 17427 public static final int DUMP_INSTALLS = 1 << 16; 17428 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17429 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17430 public static final int DUMP_FROZEN = 1 << 19; 17431 17432 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17433 17434 private int mTypes; 17435 17436 private int mOptions; 17437 17438 private boolean mTitlePrinted; 17439 17440 private SharedUserSetting mSharedUser; 17441 17442 public boolean isDumping(int type) { 17443 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17444 return true; 17445 } 17446 17447 return (mTypes & type) != 0; 17448 } 17449 17450 public void setDump(int type) { 17451 mTypes |= type; 17452 } 17453 17454 public boolean isOptionEnabled(int option) { 17455 return (mOptions & option) != 0; 17456 } 17457 17458 public void setOptionEnabled(int option) { 17459 mOptions |= option; 17460 } 17461 17462 public boolean onTitlePrinted() { 17463 final boolean printed = mTitlePrinted; 17464 mTitlePrinted = true; 17465 return printed; 17466 } 17467 17468 public boolean getTitlePrinted() { 17469 return mTitlePrinted; 17470 } 17471 17472 public void setTitlePrinted(boolean enabled) { 17473 mTitlePrinted = enabled; 17474 } 17475 17476 public SharedUserSetting getSharedUser() { 17477 return mSharedUser; 17478 } 17479 17480 public void setSharedUser(SharedUserSetting user) { 17481 mSharedUser = user; 17482 } 17483 } 17484 17485 @Override 17486 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17487 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17488 (new PackageManagerShellCommand(this)).exec( 17489 this, in, out, err, args, resultReceiver); 17490 } 17491 17492 @Override 17493 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17494 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17495 != PackageManager.PERMISSION_GRANTED) { 17496 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17497 + Binder.getCallingPid() 17498 + ", uid=" + Binder.getCallingUid() 17499 + " without permission " 17500 + android.Manifest.permission.DUMP); 17501 return; 17502 } 17503 17504 DumpState dumpState = new DumpState(); 17505 boolean fullPreferred = false; 17506 boolean checkin = false; 17507 17508 String packageName = null; 17509 ArraySet<String> permissionNames = null; 17510 17511 int opti = 0; 17512 while (opti < args.length) { 17513 String opt = args[opti]; 17514 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17515 break; 17516 } 17517 opti++; 17518 17519 if ("-a".equals(opt)) { 17520 // Right now we only know how to print all. 17521 } else if ("-h".equals(opt)) { 17522 pw.println("Package manager dump options:"); 17523 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17524 pw.println(" --checkin: dump for a checkin"); 17525 pw.println(" -f: print details of intent filters"); 17526 pw.println(" -h: print this help"); 17527 pw.println(" cmd may be one of:"); 17528 pw.println(" l[ibraries]: list known shared libraries"); 17529 pw.println(" f[eatures]: list device features"); 17530 pw.println(" k[eysets]: print known keysets"); 17531 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17532 pw.println(" perm[issions]: dump permissions"); 17533 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17534 pw.println(" pref[erred]: print preferred package settings"); 17535 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17536 pw.println(" prov[iders]: dump content providers"); 17537 pw.println(" p[ackages]: dump installed packages"); 17538 pw.println(" s[hared-users]: dump shared user IDs"); 17539 pw.println(" m[essages]: print collected runtime messages"); 17540 pw.println(" v[erifiers]: print package verifier info"); 17541 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17542 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17543 pw.println(" version: print database version info"); 17544 pw.println(" write: write current settings now"); 17545 pw.println(" installs: details about install sessions"); 17546 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17547 pw.println(" <package.name>: info about given package"); 17548 return; 17549 } else if ("--checkin".equals(opt)) { 17550 checkin = true; 17551 } else if ("-f".equals(opt)) { 17552 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17553 } else { 17554 pw.println("Unknown argument: " + opt + "; use -h for help"); 17555 } 17556 } 17557 17558 // Is the caller requesting to dump a particular piece of data? 17559 if (opti < args.length) { 17560 String cmd = args[opti]; 17561 opti++; 17562 // Is this a package name? 17563 if ("android".equals(cmd) || cmd.contains(".")) { 17564 packageName = cmd; 17565 // When dumping a single package, we always dump all of its 17566 // filter information since the amount of data will be reasonable. 17567 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17568 } else if ("check-permission".equals(cmd)) { 17569 if (opti >= args.length) { 17570 pw.println("Error: check-permission missing permission argument"); 17571 return; 17572 } 17573 String perm = args[opti]; 17574 opti++; 17575 if (opti >= args.length) { 17576 pw.println("Error: check-permission missing package argument"); 17577 return; 17578 } 17579 String pkg = args[opti]; 17580 opti++; 17581 int user = UserHandle.getUserId(Binder.getCallingUid()); 17582 if (opti < args.length) { 17583 try { 17584 user = Integer.parseInt(args[opti]); 17585 } catch (NumberFormatException e) { 17586 pw.println("Error: check-permission user argument is not a number: " 17587 + args[opti]); 17588 return; 17589 } 17590 } 17591 pw.println(checkPermission(perm, pkg, user)); 17592 return; 17593 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17594 dumpState.setDump(DumpState.DUMP_LIBS); 17595 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17596 dumpState.setDump(DumpState.DUMP_FEATURES); 17597 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17598 if (opti >= args.length) { 17599 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17600 | DumpState.DUMP_SERVICE_RESOLVERS 17601 | DumpState.DUMP_RECEIVER_RESOLVERS 17602 | DumpState.DUMP_CONTENT_RESOLVERS); 17603 } else { 17604 while (opti < args.length) { 17605 String name = args[opti]; 17606 if ("a".equals(name) || "activity".equals(name)) { 17607 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17608 } else if ("s".equals(name) || "service".equals(name)) { 17609 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17610 } else if ("r".equals(name) || "receiver".equals(name)) { 17611 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17612 } else if ("c".equals(name) || "content".equals(name)) { 17613 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17614 } else { 17615 pw.println("Error: unknown resolver table type: " + name); 17616 return; 17617 } 17618 opti++; 17619 } 17620 } 17621 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17622 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17623 } else if ("permission".equals(cmd)) { 17624 if (opti >= args.length) { 17625 pw.println("Error: permission requires permission name"); 17626 return; 17627 } 17628 permissionNames = new ArraySet<>(); 17629 while (opti < args.length) { 17630 permissionNames.add(args[opti]); 17631 opti++; 17632 } 17633 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17634 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17635 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17636 dumpState.setDump(DumpState.DUMP_PREFERRED); 17637 } else if ("preferred-xml".equals(cmd)) { 17638 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17639 if (opti < args.length && "--full".equals(args[opti])) { 17640 fullPreferred = true; 17641 opti++; 17642 } 17643 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17644 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17645 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17646 dumpState.setDump(DumpState.DUMP_PACKAGES); 17647 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17648 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17649 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17650 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17651 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17652 dumpState.setDump(DumpState.DUMP_MESSAGES); 17653 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17654 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17655 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17656 || "intent-filter-verifiers".equals(cmd)) { 17657 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17658 } else if ("version".equals(cmd)) { 17659 dumpState.setDump(DumpState.DUMP_VERSION); 17660 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17661 dumpState.setDump(DumpState.DUMP_KEYSETS); 17662 } else if ("installs".equals(cmd)) { 17663 dumpState.setDump(DumpState.DUMP_INSTALLS); 17664 } else if ("frozen".equals(cmd)) { 17665 dumpState.setDump(DumpState.DUMP_FROZEN); 17666 } else if ("write".equals(cmd)) { 17667 synchronized (mPackages) { 17668 mSettings.writeLPr(); 17669 pw.println("Settings written."); 17670 return; 17671 } 17672 } 17673 } 17674 17675 if (checkin) { 17676 pw.println("vers,1"); 17677 } 17678 17679 // reader 17680 synchronized (mPackages) { 17681 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17682 if (!checkin) { 17683 if (dumpState.onTitlePrinted()) 17684 pw.println(); 17685 pw.println("Database versions:"); 17686 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17687 } 17688 } 17689 17690 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17691 if (!checkin) { 17692 if (dumpState.onTitlePrinted()) 17693 pw.println(); 17694 pw.println("Verifiers:"); 17695 pw.print(" Required: "); 17696 pw.print(mRequiredVerifierPackage); 17697 pw.print(" (uid="); 17698 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17699 UserHandle.USER_SYSTEM)); 17700 pw.println(")"); 17701 } else if (mRequiredVerifierPackage != null) { 17702 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17703 pw.print(","); 17704 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17705 UserHandle.USER_SYSTEM)); 17706 } 17707 } 17708 17709 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17710 packageName == null) { 17711 if (mIntentFilterVerifierComponent != null) { 17712 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17713 if (!checkin) { 17714 if (dumpState.onTitlePrinted()) 17715 pw.println(); 17716 pw.println("Intent Filter Verifier:"); 17717 pw.print(" Using: "); 17718 pw.print(verifierPackageName); 17719 pw.print(" (uid="); 17720 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17721 UserHandle.USER_SYSTEM)); 17722 pw.println(")"); 17723 } else if (verifierPackageName != null) { 17724 pw.print("ifv,"); pw.print(verifierPackageName); 17725 pw.print(","); 17726 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17727 UserHandle.USER_SYSTEM)); 17728 } 17729 } else { 17730 pw.println(); 17731 pw.println("No Intent Filter Verifier available!"); 17732 } 17733 } 17734 17735 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17736 boolean printedHeader = false; 17737 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17738 while (it.hasNext()) { 17739 String name = it.next(); 17740 SharedLibraryEntry ent = mSharedLibraries.get(name); 17741 if (!checkin) { 17742 if (!printedHeader) { 17743 if (dumpState.onTitlePrinted()) 17744 pw.println(); 17745 pw.println("Libraries:"); 17746 printedHeader = true; 17747 } 17748 pw.print(" "); 17749 } else { 17750 pw.print("lib,"); 17751 } 17752 pw.print(name); 17753 if (!checkin) { 17754 pw.print(" -> "); 17755 } 17756 if (ent.path != null) { 17757 if (!checkin) { 17758 pw.print("(jar) "); 17759 pw.print(ent.path); 17760 } else { 17761 pw.print(",jar,"); 17762 pw.print(ent.path); 17763 } 17764 } else { 17765 if (!checkin) { 17766 pw.print("(apk) "); 17767 pw.print(ent.apk); 17768 } else { 17769 pw.print(",apk,"); 17770 pw.print(ent.apk); 17771 } 17772 } 17773 pw.println(); 17774 } 17775 } 17776 17777 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17778 if (dumpState.onTitlePrinted()) 17779 pw.println(); 17780 if (!checkin) { 17781 pw.println("Features:"); 17782 } 17783 17784 for (FeatureInfo feat : mAvailableFeatures.values()) { 17785 if (checkin) { 17786 pw.print("feat,"); 17787 pw.print(feat.name); 17788 pw.print(","); 17789 pw.println(feat.version); 17790 } else { 17791 pw.print(" "); 17792 pw.print(feat.name); 17793 if (feat.version > 0) { 17794 pw.print(" version="); 17795 pw.print(feat.version); 17796 } 17797 pw.println(); 17798 } 17799 } 17800 } 17801 17802 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17803 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17804 : "Activity Resolver Table:", " ", packageName, 17805 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17806 dumpState.setTitlePrinted(true); 17807 } 17808 } 17809 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17810 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17811 : "Receiver Resolver Table:", " ", packageName, 17812 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17813 dumpState.setTitlePrinted(true); 17814 } 17815 } 17816 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17817 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17818 : "Service Resolver Table:", " ", packageName, 17819 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17820 dumpState.setTitlePrinted(true); 17821 } 17822 } 17823 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17824 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17825 : "Provider Resolver Table:", " ", packageName, 17826 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17827 dumpState.setTitlePrinted(true); 17828 } 17829 } 17830 17831 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17832 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17833 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17834 int user = mSettings.mPreferredActivities.keyAt(i); 17835 if (pir.dump(pw, 17836 dumpState.getTitlePrinted() 17837 ? "\nPreferred Activities User " + user + ":" 17838 : "Preferred Activities User " + user + ":", " ", 17839 packageName, true, false)) { 17840 dumpState.setTitlePrinted(true); 17841 } 17842 } 17843 } 17844 17845 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17846 pw.flush(); 17847 FileOutputStream fout = new FileOutputStream(fd); 17848 BufferedOutputStream str = new BufferedOutputStream(fout); 17849 XmlSerializer serializer = new FastXmlSerializer(); 17850 try { 17851 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17852 serializer.startDocument(null, true); 17853 serializer.setFeature( 17854 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17855 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17856 serializer.endDocument(); 17857 serializer.flush(); 17858 } catch (IllegalArgumentException e) { 17859 pw.println("Failed writing: " + e); 17860 } catch (IllegalStateException e) { 17861 pw.println("Failed writing: " + e); 17862 } catch (IOException e) { 17863 pw.println("Failed writing: " + e); 17864 } 17865 } 17866 17867 if (!checkin 17868 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17869 && packageName == null) { 17870 pw.println(); 17871 int count = mSettings.mPackages.size(); 17872 if (count == 0) { 17873 pw.println("No applications!"); 17874 pw.println(); 17875 } else { 17876 final String prefix = " "; 17877 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17878 if (allPackageSettings.size() == 0) { 17879 pw.println("No domain preferred apps!"); 17880 pw.println(); 17881 } else { 17882 pw.println("App verification status:"); 17883 pw.println(); 17884 count = 0; 17885 for (PackageSetting ps : allPackageSettings) { 17886 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17887 if (ivi == null || ivi.getPackageName() == null) continue; 17888 pw.println(prefix + "Package: " + ivi.getPackageName()); 17889 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17890 pw.println(prefix + "Status: " + ivi.getStatusString()); 17891 pw.println(); 17892 count++; 17893 } 17894 if (count == 0) { 17895 pw.println(prefix + "No app verification established."); 17896 pw.println(); 17897 } 17898 for (int userId : sUserManager.getUserIds()) { 17899 pw.println("App linkages for user " + userId + ":"); 17900 pw.println(); 17901 count = 0; 17902 for (PackageSetting ps : allPackageSettings) { 17903 final long status = ps.getDomainVerificationStatusForUser(userId); 17904 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17905 continue; 17906 } 17907 pw.println(prefix + "Package: " + ps.name); 17908 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17909 String statusStr = IntentFilterVerificationInfo. 17910 getStatusStringFromValue(status); 17911 pw.println(prefix + "Status: " + statusStr); 17912 pw.println(); 17913 count++; 17914 } 17915 if (count == 0) { 17916 pw.println(prefix + "No configured app linkages."); 17917 pw.println(); 17918 } 17919 } 17920 } 17921 } 17922 } 17923 17924 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17925 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17926 if (packageName == null && permissionNames == null) { 17927 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17928 if (iperm == 0) { 17929 if (dumpState.onTitlePrinted()) 17930 pw.println(); 17931 pw.println("AppOp Permissions:"); 17932 } 17933 pw.print(" AppOp Permission "); 17934 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17935 pw.println(":"); 17936 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17937 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17938 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17939 } 17940 } 17941 } 17942 } 17943 17944 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17945 boolean printedSomething = false; 17946 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17947 if (packageName != null && !packageName.equals(p.info.packageName)) { 17948 continue; 17949 } 17950 if (!printedSomething) { 17951 if (dumpState.onTitlePrinted()) 17952 pw.println(); 17953 pw.println("Registered ContentProviders:"); 17954 printedSomething = true; 17955 } 17956 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17957 pw.print(" "); pw.println(p.toString()); 17958 } 17959 printedSomething = false; 17960 for (Map.Entry<String, PackageParser.Provider> entry : 17961 mProvidersByAuthority.entrySet()) { 17962 PackageParser.Provider p = entry.getValue(); 17963 if (packageName != null && !packageName.equals(p.info.packageName)) { 17964 continue; 17965 } 17966 if (!printedSomething) { 17967 if (dumpState.onTitlePrinted()) 17968 pw.println(); 17969 pw.println("ContentProvider Authorities:"); 17970 printedSomething = true; 17971 } 17972 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17973 pw.print(" "); pw.println(p.toString()); 17974 if (p.info != null && p.info.applicationInfo != null) { 17975 final String appInfo = p.info.applicationInfo.toString(); 17976 pw.print(" applicationInfo="); pw.println(appInfo); 17977 } 17978 } 17979 } 17980 17981 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17982 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17983 } 17984 17985 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17986 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17987 } 17988 17989 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17990 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17991 } 17992 17993 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17994 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17995 } 17996 17997 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17998 // XXX should handle packageName != null by dumping only install data that 17999 // the given package is involved with. 18000 if (dumpState.onTitlePrinted()) pw.println(); 18001 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18002 } 18003 18004 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18005 // XXX should handle packageName != null by dumping only install data that 18006 // the given package is involved with. 18007 if (dumpState.onTitlePrinted()) pw.println(); 18008 18009 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18010 ipw.println(); 18011 ipw.println("Frozen packages:"); 18012 ipw.increaseIndent(); 18013 if (mFrozenPackages.size() == 0) { 18014 ipw.println("(none)"); 18015 } else { 18016 for (int i = 0; i < mFrozenPackages.size(); i++) { 18017 ipw.println(mFrozenPackages.valueAt(i)); 18018 } 18019 } 18020 ipw.decreaseIndent(); 18021 } 18022 18023 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18024 if (dumpState.onTitlePrinted()) pw.println(); 18025 mSettings.dumpReadMessagesLPr(pw, dumpState); 18026 18027 pw.println(); 18028 pw.println("Package warning messages:"); 18029 BufferedReader in = null; 18030 String line = null; 18031 try { 18032 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18033 while ((line = in.readLine()) != null) { 18034 if (line.contains("ignored: updated version")) continue; 18035 pw.println(line); 18036 } 18037 } catch (IOException ignored) { 18038 } finally { 18039 IoUtils.closeQuietly(in); 18040 } 18041 } 18042 18043 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18044 BufferedReader in = null; 18045 String line = null; 18046 try { 18047 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18048 while ((line = in.readLine()) != null) { 18049 if (line.contains("ignored: updated version")) continue; 18050 pw.print("msg,"); 18051 pw.println(line); 18052 } 18053 } catch (IOException ignored) { 18054 } finally { 18055 IoUtils.closeQuietly(in); 18056 } 18057 } 18058 } 18059 } 18060 18061 private String dumpDomainString(String packageName) { 18062 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18063 .getList(); 18064 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18065 18066 ArraySet<String> result = new ArraySet<>(); 18067 if (iviList.size() > 0) { 18068 for (IntentFilterVerificationInfo ivi : iviList) { 18069 for (String host : ivi.getDomains()) { 18070 result.add(host); 18071 } 18072 } 18073 } 18074 if (filters != null && filters.size() > 0) { 18075 for (IntentFilter filter : filters) { 18076 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18077 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18078 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18079 result.addAll(filter.getHostsList()); 18080 } 18081 } 18082 } 18083 18084 StringBuilder sb = new StringBuilder(result.size() * 16); 18085 for (String domain : result) { 18086 if (sb.length() > 0) sb.append(" "); 18087 sb.append(domain); 18088 } 18089 return sb.toString(); 18090 } 18091 18092 // ------- apps on sdcard specific code ------- 18093 static final boolean DEBUG_SD_INSTALL = false; 18094 18095 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18096 18097 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18098 18099 private boolean mMediaMounted = false; 18100 18101 static String getEncryptKey() { 18102 try { 18103 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18104 SD_ENCRYPTION_KEYSTORE_NAME); 18105 if (sdEncKey == null) { 18106 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18107 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18108 if (sdEncKey == null) { 18109 Slog.e(TAG, "Failed to create encryption keys"); 18110 return null; 18111 } 18112 } 18113 return sdEncKey; 18114 } catch (NoSuchAlgorithmException nsae) { 18115 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18116 return null; 18117 } catch (IOException ioe) { 18118 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18119 return null; 18120 } 18121 } 18122 18123 /* 18124 * Update media status on PackageManager. 18125 */ 18126 @Override 18127 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18128 int callingUid = Binder.getCallingUid(); 18129 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18130 throw new SecurityException("Media status can only be updated by the system"); 18131 } 18132 // reader; this apparently protects mMediaMounted, but should probably 18133 // be a different lock in that case. 18134 synchronized (mPackages) { 18135 Log.i(TAG, "Updating external media status from " 18136 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18137 + (mediaStatus ? "mounted" : "unmounted")); 18138 if (DEBUG_SD_INSTALL) 18139 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18140 + ", mMediaMounted=" + mMediaMounted); 18141 if (mediaStatus == mMediaMounted) { 18142 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18143 : 0, -1); 18144 mHandler.sendMessage(msg); 18145 return; 18146 } 18147 mMediaMounted = mediaStatus; 18148 } 18149 // Queue up an async operation since the package installation may take a 18150 // little while. 18151 mHandler.post(new Runnable() { 18152 public void run() { 18153 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18154 } 18155 }); 18156 } 18157 18158 /** 18159 * Called by MountService when the initial ASECs to scan are available. 18160 * Should block until all the ASEC containers are finished being scanned. 18161 */ 18162 public void scanAvailableAsecs() { 18163 updateExternalMediaStatusInner(true, false, false); 18164 } 18165 18166 /* 18167 * Collect information of applications on external media, map them against 18168 * existing containers and update information based on current mount status. 18169 * Please note that we always have to report status if reportStatus has been 18170 * set to true especially when unloading packages. 18171 */ 18172 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18173 boolean externalStorage) { 18174 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18175 int[] uidArr = EmptyArray.INT; 18176 18177 final String[] list = PackageHelper.getSecureContainerList(); 18178 if (ArrayUtils.isEmpty(list)) { 18179 Log.i(TAG, "No secure containers found"); 18180 } else { 18181 // Process list of secure containers and categorize them 18182 // as active or stale based on their package internal state. 18183 18184 // reader 18185 synchronized (mPackages) { 18186 for (String cid : list) { 18187 // Leave stages untouched for now; installer service owns them 18188 if (PackageInstallerService.isStageName(cid)) continue; 18189 18190 if (DEBUG_SD_INSTALL) 18191 Log.i(TAG, "Processing container " + cid); 18192 String pkgName = getAsecPackageName(cid); 18193 if (pkgName == null) { 18194 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18195 continue; 18196 } 18197 if (DEBUG_SD_INSTALL) 18198 Log.i(TAG, "Looking for pkg : " + pkgName); 18199 18200 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18201 if (ps == null) { 18202 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18203 continue; 18204 } 18205 18206 /* 18207 * Skip packages that are not external if we're unmounting 18208 * external storage. 18209 */ 18210 if (externalStorage && !isMounted && !isExternal(ps)) { 18211 continue; 18212 } 18213 18214 final AsecInstallArgs args = new AsecInstallArgs(cid, 18215 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18216 // The package status is changed only if the code path 18217 // matches between settings and the container id. 18218 if (ps.codePathString != null 18219 && ps.codePathString.startsWith(args.getCodePath())) { 18220 if (DEBUG_SD_INSTALL) { 18221 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18222 + " at code path: " + ps.codePathString); 18223 } 18224 18225 // We do have a valid package installed on sdcard 18226 processCids.put(args, ps.codePathString); 18227 final int uid = ps.appId; 18228 if (uid != -1) { 18229 uidArr = ArrayUtils.appendInt(uidArr, uid); 18230 } 18231 } else { 18232 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18233 + ps.codePathString); 18234 } 18235 } 18236 } 18237 18238 Arrays.sort(uidArr); 18239 } 18240 18241 // Process packages with valid entries. 18242 if (isMounted) { 18243 if (DEBUG_SD_INSTALL) 18244 Log.i(TAG, "Loading packages"); 18245 loadMediaPackages(processCids, uidArr, externalStorage); 18246 startCleaningPackages(); 18247 mInstallerService.onSecureContainersAvailable(); 18248 } else { 18249 if (DEBUG_SD_INSTALL) 18250 Log.i(TAG, "Unloading packages"); 18251 unloadMediaPackages(processCids, uidArr, reportStatus); 18252 } 18253 } 18254 18255 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18256 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18257 final int size = infos.size(); 18258 final String[] packageNames = new String[size]; 18259 final int[] packageUids = new int[size]; 18260 for (int i = 0; i < size; i++) { 18261 final ApplicationInfo info = infos.get(i); 18262 packageNames[i] = info.packageName; 18263 packageUids[i] = info.uid; 18264 } 18265 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18266 finishedReceiver); 18267 } 18268 18269 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18270 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18271 sendResourcesChangedBroadcast(mediaStatus, replacing, 18272 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18273 } 18274 18275 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18276 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18277 int size = pkgList.length; 18278 if (size > 0) { 18279 // Send broadcasts here 18280 Bundle extras = new Bundle(); 18281 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18282 if (uidArr != null) { 18283 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18284 } 18285 if (replacing) { 18286 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18287 } 18288 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18289 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18290 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18291 } 18292 } 18293 18294 /* 18295 * Look at potentially valid container ids from processCids If package 18296 * information doesn't match the one on record or package scanning fails, 18297 * the cid is added to list of removeCids. We currently don't delete stale 18298 * containers. 18299 */ 18300 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18301 boolean externalStorage) { 18302 ArrayList<String> pkgList = new ArrayList<String>(); 18303 Set<AsecInstallArgs> keys = processCids.keySet(); 18304 18305 for (AsecInstallArgs args : keys) { 18306 String codePath = processCids.get(args); 18307 if (DEBUG_SD_INSTALL) 18308 Log.i(TAG, "Loading container : " + args.cid); 18309 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18310 try { 18311 // Make sure there are no container errors first. 18312 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18313 Slog.e(TAG, "Failed to mount cid : " + args.cid 18314 + " when installing from sdcard"); 18315 continue; 18316 } 18317 // Check code path here. 18318 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18319 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18320 + " does not match one in settings " + codePath); 18321 continue; 18322 } 18323 // Parse package 18324 int parseFlags = mDefParseFlags; 18325 if (args.isExternalAsec()) { 18326 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18327 } 18328 if (args.isFwdLocked()) { 18329 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18330 } 18331 18332 synchronized (mInstallLock) { 18333 PackageParser.Package pkg = null; 18334 try { 18335 // Sadly we don't know the package name yet to freeze it 18336 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18337 SCAN_IGNORE_FROZEN, 0, null); 18338 } catch (PackageManagerException e) { 18339 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18340 } 18341 // Scan the package 18342 if (pkg != null) { 18343 /* 18344 * TODO why is the lock being held? doPostInstall is 18345 * called in other places without the lock. This needs 18346 * to be straightened out. 18347 */ 18348 // writer 18349 synchronized (mPackages) { 18350 retCode = PackageManager.INSTALL_SUCCEEDED; 18351 pkgList.add(pkg.packageName); 18352 // Post process args 18353 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18354 pkg.applicationInfo.uid); 18355 } 18356 } else { 18357 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18358 } 18359 } 18360 18361 } finally { 18362 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18363 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18364 } 18365 } 18366 } 18367 // writer 18368 synchronized (mPackages) { 18369 // If the platform SDK has changed since the last time we booted, 18370 // we need to re-grant app permission to catch any new ones that 18371 // appear. This is really a hack, and means that apps can in some 18372 // cases get permissions that the user didn't initially explicitly 18373 // allow... it would be nice to have some better way to handle 18374 // this situation. 18375 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18376 : mSettings.getInternalVersion(); 18377 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18378 : StorageManager.UUID_PRIVATE_INTERNAL; 18379 18380 int updateFlags = UPDATE_PERMISSIONS_ALL; 18381 if (ver.sdkVersion != mSdkVersion) { 18382 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18383 + mSdkVersion + "; regranting permissions for external"); 18384 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18385 } 18386 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18387 18388 // Yay, everything is now upgraded 18389 ver.forceCurrent(); 18390 18391 // can downgrade to reader 18392 // Persist settings 18393 mSettings.writeLPr(); 18394 } 18395 // Send a broadcast to let everyone know we are done processing 18396 if (pkgList.size() > 0) { 18397 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18398 } 18399 } 18400 18401 /* 18402 * Utility method to unload a list of specified containers 18403 */ 18404 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18405 // Just unmount all valid containers. 18406 for (AsecInstallArgs arg : cidArgs) { 18407 synchronized (mInstallLock) { 18408 arg.doPostDeleteLI(false); 18409 } 18410 } 18411 } 18412 18413 /* 18414 * Unload packages mounted on external media. This involves deleting package 18415 * data from internal structures, sending broadcasts about disabled packages, 18416 * gc'ing to free up references, unmounting all secure containers 18417 * corresponding to packages on external media, and posting a 18418 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18419 * that we always have to post this message if status has been requested no 18420 * matter what. 18421 */ 18422 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18423 final boolean reportStatus) { 18424 if (DEBUG_SD_INSTALL) 18425 Log.i(TAG, "unloading media packages"); 18426 ArrayList<String> pkgList = new ArrayList<String>(); 18427 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18428 final Set<AsecInstallArgs> keys = processCids.keySet(); 18429 for (AsecInstallArgs args : keys) { 18430 String pkgName = args.getPackageName(); 18431 if (DEBUG_SD_INSTALL) 18432 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18433 // Delete package internally 18434 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18435 synchronized (mInstallLock) { 18436 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18437 final boolean res; 18438 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18439 "unloadMediaPackages")) { 18440 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18441 null); 18442 } 18443 if (res) { 18444 pkgList.add(pkgName); 18445 } else { 18446 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18447 failedList.add(args); 18448 } 18449 } 18450 } 18451 18452 // reader 18453 synchronized (mPackages) { 18454 // We didn't update the settings after removing each package; 18455 // write them now for all packages. 18456 mSettings.writeLPr(); 18457 } 18458 18459 // We have to absolutely send UPDATED_MEDIA_STATUS only 18460 // after confirming that all the receivers processed the ordered 18461 // broadcast when packages get disabled, force a gc to clean things up. 18462 // and unload all the containers. 18463 if (pkgList.size() > 0) { 18464 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18465 new IIntentReceiver.Stub() { 18466 public void performReceive(Intent intent, int resultCode, String data, 18467 Bundle extras, boolean ordered, boolean sticky, 18468 int sendingUser) throws RemoteException { 18469 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18470 reportStatus ? 1 : 0, 1, keys); 18471 mHandler.sendMessage(msg); 18472 } 18473 }); 18474 } else { 18475 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18476 keys); 18477 mHandler.sendMessage(msg); 18478 } 18479 } 18480 18481 private void loadPrivatePackages(final VolumeInfo vol) { 18482 mHandler.post(new Runnable() { 18483 @Override 18484 public void run() { 18485 loadPrivatePackagesInner(vol); 18486 } 18487 }); 18488 } 18489 18490 private void loadPrivatePackagesInner(VolumeInfo vol) { 18491 final String volumeUuid = vol.fsUuid; 18492 if (TextUtils.isEmpty(volumeUuid)) { 18493 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18494 return; 18495 } 18496 18497 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18498 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18499 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18500 18501 final VersionInfo ver; 18502 final List<PackageSetting> packages; 18503 synchronized (mPackages) { 18504 ver = mSettings.findOrCreateVersion(volumeUuid); 18505 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18506 } 18507 18508 for (PackageSetting ps : packages) { 18509 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18510 synchronized (mInstallLock) { 18511 final PackageParser.Package pkg; 18512 try { 18513 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18514 loaded.add(pkg.applicationInfo); 18515 18516 } catch (PackageManagerException e) { 18517 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18518 } 18519 18520 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18521 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18522 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18523 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18524 } 18525 } 18526 } 18527 18528 // Reconcile app data for all started/unlocked users 18529 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18530 final UserManager um = mContext.getSystemService(UserManager.class); 18531 for (UserInfo user : um.getUsers()) { 18532 final int flags; 18533 if (um.isUserUnlocked(user.id)) { 18534 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18535 } else if (um.isUserRunning(user.id)) { 18536 flags = StorageManager.FLAG_STORAGE_DE; 18537 } else { 18538 continue; 18539 } 18540 18541 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18542 synchronized (mInstallLock) { 18543 reconcileAppsDataLI(volumeUuid, user.id, flags); 18544 } 18545 } 18546 18547 synchronized (mPackages) { 18548 int updateFlags = UPDATE_PERMISSIONS_ALL; 18549 if (ver.sdkVersion != mSdkVersion) { 18550 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18551 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18552 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18553 } 18554 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18555 18556 // Yay, everything is now upgraded 18557 ver.forceCurrent(); 18558 18559 mSettings.writeLPr(); 18560 } 18561 18562 for (PackageFreezer freezer : freezers) { 18563 freezer.close(); 18564 } 18565 18566 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18567 sendResourcesChangedBroadcast(true, false, loaded, null); 18568 } 18569 18570 private void unloadPrivatePackages(final VolumeInfo vol) { 18571 mHandler.post(new Runnable() { 18572 @Override 18573 public void run() { 18574 unloadPrivatePackagesInner(vol); 18575 } 18576 }); 18577 } 18578 18579 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18580 final String volumeUuid = vol.fsUuid; 18581 if (TextUtils.isEmpty(volumeUuid)) { 18582 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18583 return; 18584 } 18585 18586 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18587 synchronized (mInstallLock) { 18588 synchronized (mPackages) { 18589 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18590 for (PackageSetting ps : packages) { 18591 if (ps.pkg == null) continue; 18592 18593 final ApplicationInfo info = ps.pkg.applicationInfo; 18594 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18595 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18596 18597 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18598 "unloadPrivatePackagesInner")) { 18599 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18600 false, null)) { 18601 unloaded.add(info); 18602 } else { 18603 Slog.w(TAG, "Failed to unload " + ps.codePath); 18604 } 18605 } 18606 } 18607 18608 mSettings.writeLPr(); 18609 } 18610 } 18611 18612 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18613 sendResourcesChangedBroadcast(false, false, unloaded, null); 18614 } 18615 18616 /** 18617 * Examine all users present on given mounted volume, and destroy data 18618 * belonging to users that are no longer valid, or whose user ID has been 18619 * recycled. 18620 */ 18621 private void reconcileUsers(String volumeUuid) { 18622 // TODO: also reconcile DE directories 18623 final File[] files = FileUtils 18624 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18625 for (File file : files) { 18626 if (!file.isDirectory()) continue; 18627 18628 final int userId; 18629 final UserInfo info; 18630 try { 18631 userId = Integer.parseInt(file.getName()); 18632 info = sUserManager.getUserInfo(userId); 18633 } catch (NumberFormatException e) { 18634 Slog.w(TAG, "Invalid user directory " + file); 18635 continue; 18636 } 18637 18638 boolean destroyUser = false; 18639 if (info == null) { 18640 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18641 + " because no matching user was found"); 18642 destroyUser = true; 18643 } else { 18644 try { 18645 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18646 } catch (IOException e) { 18647 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18648 + " because we failed to enforce serial number: " + e); 18649 destroyUser = true; 18650 } 18651 } 18652 18653 if (destroyUser) { 18654 synchronized (mInstallLock) { 18655 try { 18656 mInstaller.removeUserDataDirs(volumeUuid, userId); 18657 } catch (InstallerException e) { 18658 Slog.w(TAG, "Failed to clean up user dirs", e); 18659 } 18660 } 18661 } 18662 } 18663 } 18664 18665 private void assertPackageKnown(String volumeUuid, String packageName) 18666 throws PackageManagerException { 18667 synchronized (mPackages) { 18668 final PackageSetting ps = mSettings.mPackages.get(packageName); 18669 if (ps == null) { 18670 throw new PackageManagerException("Package " + packageName + " is unknown"); 18671 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18672 throw new PackageManagerException( 18673 "Package " + packageName + " found on unknown volume " + volumeUuid 18674 + "; expected volume " + ps.volumeUuid); 18675 } 18676 } 18677 } 18678 18679 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18680 throws PackageManagerException { 18681 synchronized (mPackages) { 18682 final PackageSetting ps = mSettings.mPackages.get(packageName); 18683 if (ps == null) { 18684 throw new PackageManagerException("Package " + packageName + " is unknown"); 18685 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18686 throw new PackageManagerException( 18687 "Package " + packageName + " found on unknown volume " + volumeUuid 18688 + "; expected volume " + ps.volumeUuid); 18689 } else if (!ps.getInstalled(userId)) { 18690 throw new PackageManagerException( 18691 "Package " + packageName + " not installed for user " + userId); 18692 } 18693 } 18694 } 18695 18696 /** 18697 * Examine all apps present on given mounted volume, and destroy apps that 18698 * aren't expected, either due to uninstallation or reinstallation on 18699 * another volume. 18700 */ 18701 private void reconcileApps(String volumeUuid) { 18702 final File[] files = FileUtils 18703 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18704 for (File file : files) { 18705 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18706 && !PackageInstallerService.isStageName(file.getName()); 18707 if (!isPackage) { 18708 // Ignore entries which are not packages 18709 continue; 18710 } 18711 18712 try { 18713 final PackageLite pkg = PackageParser.parsePackageLite(file, 18714 PackageParser.PARSE_MUST_BE_APK); 18715 assertPackageKnown(volumeUuid, pkg.packageName); 18716 18717 } catch (PackageParserException | PackageManagerException e) { 18718 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18719 synchronized (mInstallLock) { 18720 removeCodePathLI(file); 18721 } 18722 } 18723 } 18724 } 18725 18726 /** 18727 * Reconcile all app data for the given user. 18728 * <p> 18729 * Verifies that directories exist and that ownership and labeling is 18730 * correct for all installed apps on all mounted volumes. 18731 */ 18732 void reconcileAppsData(int userId, int flags) { 18733 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18734 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18735 final String volumeUuid = vol.getFsUuid(); 18736 synchronized (mInstallLock) { 18737 reconcileAppsDataLI(volumeUuid, userId, flags); 18738 } 18739 } 18740 } 18741 18742 /** 18743 * Reconcile all app data on given mounted volume. 18744 * <p> 18745 * Destroys app data that isn't expected, either due to uninstallation or 18746 * reinstallation on another volume. 18747 * <p> 18748 * Verifies that directories exist and that ownership and labeling is 18749 * correct for all installed apps. 18750 */ 18751 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18752 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18753 + Integer.toHexString(flags)); 18754 18755 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18756 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18757 18758 boolean restoreconNeeded = false; 18759 18760 // First look for stale data that doesn't belong, and check if things 18761 // have changed since we did our last restorecon 18762 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18763 if (!isUserKeyUnlocked(userId)) { 18764 throw new RuntimeException( 18765 "Yikes, someone asked us to reconcile CE storage while " + userId 18766 + " was still locked; this would have caused massive data loss!"); 18767 } 18768 18769 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18770 18771 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18772 for (File file : files) { 18773 final String packageName = file.getName(); 18774 try { 18775 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18776 } catch (PackageManagerException e) { 18777 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18778 try { 18779 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18780 StorageManager.FLAG_STORAGE_CE, 0); 18781 } catch (InstallerException e2) { 18782 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18783 } 18784 } 18785 } 18786 } 18787 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18788 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18789 18790 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18791 for (File file : files) { 18792 final String packageName = file.getName(); 18793 try { 18794 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18795 } catch (PackageManagerException e) { 18796 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18797 try { 18798 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18799 StorageManager.FLAG_STORAGE_DE, 0); 18800 } catch (InstallerException e2) { 18801 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18802 } 18803 } 18804 } 18805 } 18806 18807 // Ensure that data directories are ready to roll for all packages 18808 // installed for this volume and user 18809 final List<PackageSetting> packages; 18810 synchronized (mPackages) { 18811 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18812 } 18813 int preparedCount = 0; 18814 for (PackageSetting ps : packages) { 18815 final String packageName = ps.name; 18816 if (ps.pkg == null) { 18817 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18818 // TODO: might be due to legacy ASEC apps; we should circle back 18819 // and reconcile again once they're scanned 18820 continue; 18821 } 18822 18823 if (ps.getInstalled(userId)) { 18824 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18825 18826 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18827 // We may have just shuffled around app data directories, so 18828 // prepare them one more time 18829 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18830 } 18831 18832 preparedCount++; 18833 } 18834 } 18835 18836 if (restoreconNeeded) { 18837 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18838 SELinuxMMAC.setRestoreconDone(ceDir); 18839 } 18840 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18841 SELinuxMMAC.setRestoreconDone(deDir); 18842 } 18843 } 18844 18845 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18846 + " packages; restoreconNeeded was " + restoreconNeeded); 18847 } 18848 18849 /** 18850 * Prepare app data for the given app just after it was installed or 18851 * upgraded. This method carefully only touches users that it's installed 18852 * for, and it forces a restorecon to handle any seinfo changes. 18853 * <p> 18854 * Verifies that directories exist and that ownership and labeling is 18855 * correct for all installed apps. If there is an ownership mismatch, it 18856 * will try recovering system apps by wiping data; third-party app data is 18857 * left intact. 18858 * <p> 18859 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18860 */ 18861 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18862 final PackageSetting ps; 18863 synchronized (mPackages) { 18864 ps = mSettings.mPackages.get(pkg.packageName); 18865 mSettings.writeKernelMappingLPr(ps); 18866 } 18867 18868 final UserManager um = mContext.getSystemService(UserManager.class); 18869 for (UserInfo user : um.getUsers()) { 18870 final int flags; 18871 if (um.isUserUnlocked(user.id)) { 18872 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18873 } else if (um.isUserRunning(user.id)) { 18874 flags = StorageManager.FLAG_STORAGE_DE; 18875 } else { 18876 continue; 18877 } 18878 18879 if (ps.getInstalled(user.id)) { 18880 // Whenever an app changes, force a restorecon of its data 18881 // TODO: when user data is locked, mark that we're still dirty 18882 prepareAppDataLIF(pkg, user.id, flags, true); 18883 } 18884 } 18885 } 18886 18887 /** 18888 * Prepare app data for the given app. 18889 * <p> 18890 * Verifies that directories exist and that ownership and labeling is 18891 * correct for all installed apps. If there is an ownership mismatch, this 18892 * will try recovering system apps by wiping data; third-party app data is 18893 * left intact. 18894 */ 18895 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 18896 boolean restoreconNeeded) { 18897 if (pkg == null) { 18898 Slog.wtf(TAG, "Package was null!", new Throwable()); 18899 return; 18900 } 18901 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 18902 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18903 for (int i = 0; i < childCount; i++) { 18904 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 18905 } 18906 } 18907 18908 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 18909 boolean restoreconNeeded) { 18910 if (DEBUG_APP_DATA) { 18911 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18912 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18913 } 18914 18915 final String volumeUuid = pkg.volumeUuid; 18916 final String packageName = pkg.packageName; 18917 final ApplicationInfo app = pkg.applicationInfo; 18918 final int appId = UserHandle.getAppId(app.uid); 18919 18920 Preconditions.checkNotNull(app.seinfo); 18921 18922 try { 18923 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18924 appId, app.seinfo, app.targetSdkVersion); 18925 } catch (InstallerException e) { 18926 if (app.isSystemApp()) { 18927 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18928 + ", but trying to recover: " + e); 18929 destroyAppDataLeafLIF(pkg, userId, flags); 18930 try { 18931 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18932 appId, app.seinfo, app.targetSdkVersion); 18933 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18934 } catch (InstallerException e2) { 18935 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18936 } 18937 } else { 18938 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18939 } 18940 } 18941 18942 if (restoreconNeeded) { 18943 try { 18944 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 18945 app.seinfo); 18946 } catch (InstallerException e) { 18947 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 18948 } 18949 } 18950 18951 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18952 try { 18953 // CE storage is unlocked right now, so read out the inode and 18954 // remember for use later when it's locked 18955 // TODO: mark this structure as dirty so we persist it! 18956 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 18957 StorageManager.FLAG_STORAGE_CE); 18958 synchronized (mPackages) { 18959 final PackageSetting ps = mSettings.mPackages.get(packageName); 18960 if (ps != null) { 18961 ps.setCeDataInode(ceDataInode, userId); 18962 } 18963 } 18964 } catch (InstallerException e) { 18965 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 18966 } 18967 } 18968 18969 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18970 } 18971 18972 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 18973 if (pkg == null) { 18974 Slog.wtf(TAG, "Package was null!", new Throwable()); 18975 return; 18976 } 18977 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18978 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18979 for (int i = 0; i < childCount; i++) { 18980 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 18981 } 18982 } 18983 18984 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 18985 final String volumeUuid = pkg.volumeUuid; 18986 final String packageName = pkg.packageName; 18987 final ApplicationInfo app = pkg.applicationInfo; 18988 18989 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18990 // Create a native library symlink only if we have native libraries 18991 // and if the native libraries are 32 bit libraries. We do not provide 18992 // this symlink for 64 bit libraries. 18993 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18994 final String nativeLibPath = app.nativeLibraryDir; 18995 try { 18996 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18997 nativeLibPath, userId); 18998 } catch (InstallerException e) { 18999 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19000 } 19001 } 19002 } 19003 } 19004 19005 /** 19006 * For system apps on non-FBE devices, this method migrates any existing 19007 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19008 * requested by the app. 19009 */ 19010 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19011 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19012 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19013 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19014 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19015 try { 19016 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19017 storageTarget); 19018 } catch (InstallerException e) { 19019 logCriticalInfo(Log.WARN, 19020 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19021 } 19022 return true; 19023 } else { 19024 return false; 19025 } 19026 } 19027 19028 public PackageFreezer freezePackage(String packageName, String killReason) { 19029 return new PackageFreezer(packageName, killReason); 19030 } 19031 19032 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19033 String killReason) { 19034 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19035 return new PackageFreezer(); 19036 } else { 19037 return freezePackage(packageName, killReason); 19038 } 19039 } 19040 19041 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19042 String killReason) { 19043 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19044 return new PackageFreezer(); 19045 } else { 19046 return freezePackage(packageName, killReason); 19047 } 19048 } 19049 19050 /** 19051 * Class that freezes and kills the given package upon creation, and 19052 * unfreezes it upon closing. This is typically used when doing surgery on 19053 * app code/data to prevent the app from running while you're working. 19054 */ 19055 private class PackageFreezer implements AutoCloseable { 19056 private final String mPackageName; 19057 private final PackageFreezer[] mChildren; 19058 19059 private final boolean mWeFroze; 19060 19061 private final AtomicBoolean mClosed = new AtomicBoolean(); 19062 private final CloseGuard mCloseGuard = CloseGuard.get(); 19063 19064 /** 19065 * Create and return a stub freezer that doesn't actually do anything, 19066 * typically used when someone requested 19067 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19068 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19069 */ 19070 public PackageFreezer() { 19071 mPackageName = null; 19072 mChildren = null; 19073 mWeFroze = false; 19074 mCloseGuard.open("close"); 19075 } 19076 19077 public PackageFreezer(String packageName, String killReason) { 19078 synchronized (mPackages) { 19079 mPackageName = packageName; 19080 mWeFroze = mFrozenPackages.add(mPackageName); 19081 19082 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19083 if (ps != null) { 19084 killApplication(ps.name, ps.appId, killReason); 19085 } 19086 19087 final PackageParser.Package p = mPackages.get(packageName); 19088 if (p != null && p.childPackages != null) { 19089 final int N = p.childPackages.size(); 19090 mChildren = new PackageFreezer[N]; 19091 for (int i = 0; i < N; i++) { 19092 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19093 killReason); 19094 } 19095 } else { 19096 mChildren = null; 19097 } 19098 } 19099 mCloseGuard.open("close"); 19100 } 19101 19102 @Override 19103 protected void finalize() throws Throwable { 19104 try { 19105 mCloseGuard.warnIfOpen(); 19106 close(); 19107 } finally { 19108 super.finalize(); 19109 } 19110 } 19111 19112 @Override 19113 public void close() { 19114 mCloseGuard.close(); 19115 if (mClosed.compareAndSet(false, true)) { 19116 synchronized (mPackages) { 19117 if (mWeFroze) { 19118 mFrozenPackages.remove(mPackageName); 19119 } 19120 19121 if (mChildren != null) { 19122 for (PackageFreezer freezer : mChildren) { 19123 freezer.close(); 19124 } 19125 } 19126 } 19127 } 19128 } 19129 } 19130 19131 /** 19132 * Verify that given package is currently frozen. 19133 */ 19134 private void checkPackageFrozen(String packageName) { 19135 synchronized (mPackages) { 19136 if (!mFrozenPackages.contains(packageName)) { 19137 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19138 } 19139 } 19140 } 19141 19142 @Override 19143 public int movePackage(final String packageName, final String volumeUuid) { 19144 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19145 19146 final int moveId = mNextMoveId.getAndIncrement(); 19147 mHandler.post(new Runnable() { 19148 @Override 19149 public void run() { 19150 try { 19151 movePackageInternal(packageName, volumeUuid, moveId); 19152 } catch (PackageManagerException e) { 19153 Slog.w(TAG, "Failed to move " + packageName, e); 19154 mMoveCallbacks.notifyStatusChanged(moveId, 19155 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19156 } 19157 } 19158 }); 19159 return moveId; 19160 } 19161 19162 private void movePackageInternal(final String packageName, final String volumeUuid, 19163 final int moveId) throws PackageManagerException { 19164 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19165 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19166 final PackageManager pm = mContext.getPackageManager(); 19167 19168 final boolean currentAsec; 19169 final String currentVolumeUuid; 19170 final File codeFile; 19171 final String installerPackageName; 19172 final String packageAbiOverride; 19173 final int appId; 19174 final String seinfo; 19175 final String label; 19176 final int targetSdkVersion; 19177 final PackageFreezer freezer; 19178 19179 // reader 19180 synchronized (mPackages) { 19181 final PackageParser.Package pkg = mPackages.get(packageName); 19182 final PackageSetting ps = mSettings.mPackages.get(packageName); 19183 if (pkg == null || ps == null) { 19184 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19185 } 19186 19187 if (pkg.applicationInfo.isSystemApp()) { 19188 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19189 "Cannot move system application"); 19190 } 19191 19192 if (pkg.applicationInfo.isExternalAsec()) { 19193 currentAsec = true; 19194 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19195 } else if (pkg.applicationInfo.isForwardLocked()) { 19196 currentAsec = true; 19197 currentVolumeUuid = "forward_locked"; 19198 } else { 19199 currentAsec = false; 19200 currentVolumeUuid = ps.volumeUuid; 19201 19202 final File probe = new File(pkg.codePath); 19203 final File probeOat = new File(probe, "oat"); 19204 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19205 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19206 "Move only supported for modern cluster style installs"); 19207 } 19208 } 19209 19210 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19211 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19212 "Package already moved to " + volumeUuid); 19213 } 19214 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19215 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19216 "Device admin cannot be moved"); 19217 } 19218 19219 if (mFrozenPackages.contains(packageName)) { 19220 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19221 "Failed to move already frozen package"); 19222 } 19223 19224 codeFile = new File(pkg.codePath); 19225 installerPackageName = ps.installerPackageName; 19226 packageAbiOverride = ps.cpuAbiOverrideString; 19227 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19228 seinfo = pkg.applicationInfo.seinfo; 19229 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19230 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19231 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19232 } 19233 19234 final Bundle extras = new Bundle(); 19235 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19236 extras.putString(Intent.EXTRA_TITLE, label); 19237 mMoveCallbacks.notifyCreated(moveId, extras); 19238 19239 int installFlags; 19240 final boolean moveCompleteApp; 19241 final File measurePath; 19242 19243 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19244 installFlags = INSTALL_INTERNAL; 19245 moveCompleteApp = !currentAsec; 19246 measurePath = Environment.getDataAppDirectory(volumeUuid); 19247 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19248 installFlags = INSTALL_EXTERNAL; 19249 moveCompleteApp = false; 19250 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19251 } else { 19252 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19253 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19254 || !volume.isMountedWritable()) { 19255 freezer.close(); 19256 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19257 "Move location not mounted private volume"); 19258 } 19259 19260 Preconditions.checkState(!currentAsec); 19261 19262 installFlags = INSTALL_INTERNAL; 19263 moveCompleteApp = true; 19264 measurePath = Environment.getDataAppDirectory(volumeUuid); 19265 } 19266 19267 final PackageStats stats = new PackageStats(null, -1); 19268 synchronized (mInstaller) { 19269 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19270 freezer.close(); 19271 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19272 "Failed to measure package size"); 19273 } 19274 } 19275 19276 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19277 + stats.dataSize); 19278 19279 final long startFreeBytes = measurePath.getFreeSpace(); 19280 final long sizeBytes; 19281 if (moveCompleteApp) { 19282 sizeBytes = stats.codeSize + stats.dataSize; 19283 } else { 19284 sizeBytes = stats.codeSize; 19285 } 19286 19287 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19288 freezer.close(); 19289 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19290 "Not enough free space to move"); 19291 } 19292 19293 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19294 19295 final CountDownLatch installedLatch = new CountDownLatch(1); 19296 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19297 @Override 19298 public void onUserActionRequired(Intent intent) throws RemoteException { 19299 throw new IllegalStateException(); 19300 } 19301 19302 @Override 19303 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19304 Bundle extras) throws RemoteException { 19305 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19306 + PackageManager.installStatusToString(returnCode, msg)); 19307 19308 installedLatch.countDown(); 19309 freezer.close(); 19310 19311 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19312 switch (status) { 19313 case PackageInstaller.STATUS_SUCCESS: 19314 mMoveCallbacks.notifyStatusChanged(moveId, 19315 PackageManager.MOVE_SUCCEEDED); 19316 break; 19317 case PackageInstaller.STATUS_FAILURE_STORAGE: 19318 mMoveCallbacks.notifyStatusChanged(moveId, 19319 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19320 break; 19321 default: 19322 mMoveCallbacks.notifyStatusChanged(moveId, 19323 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19324 break; 19325 } 19326 } 19327 }; 19328 19329 final MoveInfo move; 19330 if (moveCompleteApp) { 19331 // Kick off a thread to report progress estimates 19332 new Thread() { 19333 @Override 19334 public void run() { 19335 while (true) { 19336 try { 19337 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19338 break; 19339 } 19340 } catch (InterruptedException ignored) { 19341 } 19342 19343 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19344 final int progress = 10 + (int) MathUtils.constrain( 19345 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19346 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19347 } 19348 } 19349 }.start(); 19350 19351 final String dataAppName = codeFile.getName(); 19352 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19353 dataAppName, appId, seinfo, targetSdkVersion); 19354 } else { 19355 move = null; 19356 } 19357 19358 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19359 19360 final Message msg = mHandler.obtainMessage(INIT_COPY); 19361 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19362 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19363 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19364 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19365 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19366 msg.obj = params; 19367 19368 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19369 System.identityHashCode(msg.obj)); 19370 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19371 System.identityHashCode(msg.obj)); 19372 19373 mHandler.sendMessage(msg); 19374 } 19375 19376 @Override 19377 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19378 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19379 19380 final int realMoveId = mNextMoveId.getAndIncrement(); 19381 final Bundle extras = new Bundle(); 19382 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19383 mMoveCallbacks.notifyCreated(realMoveId, extras); 19384 19385 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19386 @Override 19387 public void onCreated(int moveId, Bundle extras) { 19388 // Ignored 19389 } 19390 19391 @Override 19392 public void onStatusChanged(int moveId, int status, long estMillis) { 19393 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19394 } 19395 }; 19396 19397 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19398 storage.setPrimaryStorageUuid(volumeUuid, callback); 19399 return realMoveId; 19400 } 19401 19402 @Override 19403 public int getMoveStatus(int moveId) { 19404 mContext.enforceCallingOrSelfPermission( 19405 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19406 return mMoveCallbacks.mLastStatus.get(moveId); 19407 } 19408 19409 @Override 19410 public void registerMoveCallback(IPackageMoveObserver callback) { 19411 mContext.enforceCallingOrSelfPermission( 19412 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19413 mMoveCallbacks.register(callback); 19414 } 19415 19416 @Override 19417 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19418 mContext.enforceCallingOrSelfPermission( 19419 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19420 mMoveCallbacks.unregister(callback); 19421 } 19422 19423 @Override 19424 public boolean setInstallLocation(int loc) { 19425 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19426 null); 19427 if (getInstallLocation() == loc) { 19428 return true; 19429 } 19430 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19431 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19432 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19433 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19434 return true; 19435 } 19436 return false; 19437 } 19438 19439 @Override 19440 public int getInstallLocation() { 19441 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19442 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19443 PackageHelper.APP_INSTALL_AUTO); 19444 } 19445 19446 /** Called by UserManagerService */ 19447 void cleanUpUser(UserManagerService userManager, int userHandle) { 19448 synchronized (mPackages) { 19449 mDirtyUsers.remove(userHandle); 19450 mUserNeedsBadging.delete(userHandle); 19451 mSettings.removeUserLPw(userHandle); 19452 mPendingBroadcasts.remove(userHandle); 19453 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19454 } 19455 synchronized (mInstallLock) { 19456 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19457 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19458 final String volumeUuid = vol.getFsUuid(); 19459 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19460 try { 19461 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19462 } catch (InstallerException e) { 19463 Slog.w(TAG, "Failed to remove user data", e); 19464 } 19465 } 19466 synchronized (mPackages) { 19467 removeUnusedPackagesLILPw(userManager, userHandle); 19468 } 19469 } 19470 } 19471 19472 /** 19473 * We're removing userHandle and would like to remove any downloaded packages 19474 * that are no longer in use by any other user. 19475 * @param userHandle the user being removed 19476 */ 19477 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19478 final boolean DEBUG_CLEAN_APKS = false; 19479 int [] users = userManager.getUserIds(); 19480 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19481 while (psit.hasNext()) { 19482 PackageSetting ps = psit.next(); 19483 if (ps.pkg == null) { 19484 continue; 19485 } 19486 final String packageName = ps.pkg.packageName; 19487 // Skip over if system app 19488 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19489 continue; 19490 } 19491 if (DEBUG_CLEAN_APKS) { 19492 Slog.i(TAG, "Checking package " + packageName); 19493 } 19494 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19495 if (keep) { 19496 if (DEBUG_CLEAN_APKS) { 19497 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19498 } 19499 } else { 19500 for (int i = 0; i < users.length; i++) { 19501 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19502 keep = true; 19503 if (DEBUG_CLEAN_APKS) { 19504 Slog.i(TAG, " Keeping package " + packageName + " for user " 19505 + users[i]); 19506 } 19507 break; 19508 } 19509 } 19510 } 19511 if (!keep) { 19512 if (DEBUG_CLEAN_APKS) { 19513 Slog.i(TAG, " Removing package " + packageName); 19514 } 19515 mHandler.post(new Runnable() { 19516 public void run() { 19517 deletePackageX(packageName, userHandle, 0); 19518 } //end run 19519 }); 19520 } 19521 } 19522 } 19523 19524 /** Called by UserManagerService */ 19525 void createNewUser(int userHandle) { 19526 synchronized (mInstallLock) { 19527 try { 19528 mInstaller.createUserConfig(userHandle); 19529 } catch (InstallerException e) { 19530 Slog.w(TAG, "Failed to create user config", e); 19531 } 19532 mSettings.createNewUserLI(this, mInstaller, userHandle); 19533 } 19534 synchronized (mPackages) { 19535 applyFactoryDefaultBrowserLPw(userHandle); 19536 primeDomainVerificationsLPw(userHandle); 19537 } 19538 } 19539 19540 void newUserCreated(final int userHandle) { 19541 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19542 // If permission review for legacy apps is required, we represent 19543 // dagerous permissions for such apps as always granted runtime 19544 // permissions to keep per user flag state whether review is needed. 19545 // Hence, if a new user is added we have to propagate dangerous 19546 // permission grants for these legacy apps. 19547 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19548 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19549 | UPDATE_PERMISSIONS_REPLACE_ALL); 19550 } 19551 } 19552 19553 @Override 19554 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19555 mContext.enforceCallingOrSelfPermission( 19556 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19557 "Only package verification agents can read the verifier device identity"); 19558 19559 synchronized (mPackages) { 19560 return mSettings.getVerifierDeviceIdentityLPw(); 19561 } 19562 } 19563 19564 @Override 19565 public void setPermissionEnforced(String permission, boolean enforced) { 19566 // TODO: Now that we no longer change GID for storage, this should to away. 19567 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19568 "setPermissionEnforced"); 19569 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19570 synchronized (mPackages) { 19571 if (mSettings.mReadExternalStorageEnforced == null 19572 || mSettings.mReadExternalStorageEnforced != enforced) { 19573 mSettings.mReadExternalStorageEnforced = enforced; 19574 mSettings.writeLPr(); 19575 } 19576 } 19577 // kill any non-foreground processes so we restart them and 19578 // grant/revoke the GID. 19579 final IActivityManager am = ActivityManagerNative.getDefault(); 19580 if (am != null) { 19581 final long token = Binder.clearCallingIdentity(); 19582 try { 19583 am.killProcessesBelowForeground("setPermissionEnforcement"); 19584 } catch (RemoteException e) { 19585 } finally { 19586 Binder.restoreCallingIdentity(token); 19587 } 19588 } 19589 } else { 19590 throw new IllegalArgumentException("No selective enforcement for " + permission); 19591 } 19592 } 19593 19594 @Override 19595 @Deprecated 19596 public boolean isPermissionEnforced(String permission) { 19597 return true; 19598 } 19599 19600 @Override 19601 public boolean isStorageLow() { 19602 final long token = Binder.clearCallingIdentity(); 19603 try { 19604 final DeviceStorageMonitorInternal 19605 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19606 if (dsm != null) { 19607 return dsm.isMemoryLow(); 19608 } else { 19609 return false; 19610 } 19611 } finally { 19612 Binder.restoreCallingIdentity(token); 19613 } 19614 } 19615 19616 @Override 19617 public IPackageInstaller getPackageInstaller() { 19618 return mInstallerService; 19619 } 19620 19621 private boolean userNeedsBadging(int userId) { 19622 int index = mUserNeedsBadging.indexOfKey(userId); 19623 if (index < 0) { 19624 final UserInfo userInfo; 19625 final long token = Binder.clearCallingIdentity(); 19626 try { 19627 userInfo = sUserManager.getUserInfo(userId); 19628 } finally { 19629 Binder.restoreCallingIdentity(token); 19630 } 19631 final boolean b; 19632 if (userInfo != null && userInfo.isManagedProfile()) { 19633 b = true; 19634 } else { 19635 b = false; 19636 } 19637 mUserNeedsBadging.put(userId, b); 19638 return b; 19639 } 19640 return mUserNeedsBadging.valueAt(index); 19641 } 19642 19643 @Override 19644 public KeySet getKeySetByAlias(String packageName, String alias) { 19645 if (packageName == null || alias == null) { 19646 return null; 19647 } 19648 synchronized(mPackages) { 19649 final PackageParser.Package pkg = mPackages.get(packageName); 19650 if (pkg == null) { 19651 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19652 throw new IllegalArgumentException("Unknown package: " + packageName); 19653 } 19654 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19655 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19656 } 19657 } 19658 19659 @Override 19660 public KeySet getSigningKeySet(String packageName) { 19661 if (packageName == null) { 19662 return null; 19663 } 19664 synchronized(mPackages) { 19665 final PackageParser.Package pkg = mPackages.get(packageName); 19666 if (pkg == null) { 19667 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19668 throw new IllegalArgumentException("Unknown package: " + packageName); 19669 } 19670 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19671 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19672 throw new SecurityException("May not access signing KeySet of other apps."); 19673 } 19674 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19675 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19676 } 19677 } 19678 19679 @Override 19680 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19681 if (packageName == null || ks == null) { 19682 return false; 19683 } 19684 synchronized(mPackages) { 19685 final PackageParser.Package pkg = mPackages.get(packageName); 19686 if (pkg == null) { 19687 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19688 throw new IllegalArgumentException("Unknown package: " + packageName); 19689 } 19690 IBinder ksh = ks.getToken(); 19691 if (ksh instanceof KeySetHandle) { 19692 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19693 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19694 } 19695 return false; 19696 } 19697 } 19698 19699 @Override 19700 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19701 if (packageName == null || ks == null) { 19702 return false; 19703 } 19704 synchronized(mPackages) { 19705 final PackageParser.Package pkg = mPackages.get(packageName); 19706 if (pkg == null) { 19707 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19708 throw new IllegalArgumentException("Unknown package: " + packageName); 19709 } 19710 IBinder ksh = ks.getToken(); 19711 if (ksh instanceof KeySetHandle) { 19712 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19713 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19714 } 19715 return false; 19716 } 19717 } 19718 19719 private void deletePackageIfUnusedLPr(final String packageName) { 19720 PackageSetting ps = mSettings.mPackages.get(packageName); 19721 if (ps == null) { 19722 return; 19723 } 19724 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19725 // TODO Implement atomic delete if package is unused 19726 // It is currently possible that the package will be deleted even if it is installed 19727 // after this method returns. 19728 mHandler.post(new Runnable() { 19729 public void run() { 19730 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19731 } 19732 }); 19733 } 19734 } 19735 19736 /** 19737 * Check and throw if the given before/after packages would be considered a 19738 * downgrade. 19739 */ 19740 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19741 throws PackageManagerException { 19742 if (after.versionCode < before.mVersionCode) { 19743 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19744 "Update version code " + after.versionCode + " is older than current " 19745 + before.mVersionCode); 19746 } else if (after.versionCode == before.mVersionCode) { 19747 if (after.baseRevisionCode < before.baseRevisionCode) { 19748 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19749 "Update base revision code " + after.baseRevisionCode 19750 + " is older than current " + before.baseRevisionCode); 19751 } 19752 19753 if (!ArrayUtils.isEmpty(after.splitNames)) { 19754 for (int i = 0; i < after.splitNames.length; i++) { 19755 final String splitName = after.splitNames[i]; 19756 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19757 if (j != -1) { 19758 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19759 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19760 "Update split " + splitName + " revision code " 19761 + after.splitRevisionCodes[i] + " is older than current " 19762 + before.splitRevisionCodes[j]); 19763 } 19764 } 19765 } 19766 } 19767 } 19768 } 19769 19770 private static class MoveCallbacks extends Handler { 19771 private static final int MSG_CREATED = 1; 19772 private static final int MSG_STATUS_CHANGED = 2; 19773 19774 private final RemoteCallbackList<IPackageMoveObserver> 19775 mCallbacks = new RemoteCallbackList<>(); 19776 19777 private final SparseIntArray mLastStatus = new SparseIntArray(); 19778 19779 public MoveCallbacks(Looper looper) { 19780 super(looper); 19781 } 19782 19783 public void register(IPackageMoveObserver callback) { 19784 mCallbacks.register(callback); 19785 } 19786 19787 public void unregister(IPackageMoveObserver callback) { 19788 mCallbacks.unregister(callback); 19789 } 19790 19791 @Override 19792 public void handleMessage(Message msg) { 19793 final SomeArgs args = (SomeArgs) msg.obj; 19794 final int n = mCallbacks.beginBroadcast(); 19795 for (int i = 0; i < n; i++) { 19796 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19797 try { 19798 invokeCallback(callback, msg.what, args); 19799 } catch (RemoteException ignored) { 19800 } 19801 } 19802 mCallbacks.finishBroadcast(); 19803 args.recycle(); 19804 } 19805 19806 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19807 throws RemoteException { 19808 switch (what) { 19809 case MSG_CREATED: { 19810 callback.onCreated(args.argi1, (Bundle) args.arg2); 19811 break; 19812 } 19813 case MSG_STATUS_CHANGED: { 19814 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19815 break; 19816 } 19817 } 19818 } 19819 19820 private void notifyCreated(int moveId, Bundle extras) { 19821 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19822 19823 final SomeArgs args = SomeArgs.obtain(); 19824 args.argi1 = moveId; 19825 args.arg2 = extras; 19826 obtainMessage(MSG_CREATED, args).sendToTarget(); 19827 } 19828 19829 private void notifyStatusChanged(int moveId, int status) { 19830 notifyStatusChanged(moveId, status, -1); 19831 } 19832 19833 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19834 Slog.v(TAG, "Move " + moveId + " status " + status); 19835 19836 final SomeArgs args = SomeArgs.obtain(); 19837 args.argi1 = moveId; 19838 args.argi2 = status; 19839 args.arg3 = estMillis; 19840 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19841 19842 synchronized (mLastStatus) { 19843 mLastStatus.put(moveId, status); 19844 } 19845 } 19846 } 19847 19848 private final static class OnPermissionChangeListeners extends Handler { 19849 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19850 19851 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19852 new RemoteCallbackList<>(); 19853 19854 public OnPermissionChangeListeners(Looper looper) { 19855 super(looper); 19856 } 19857 19858 @Override 19859 public void handleMessage(Message msg) { 19860 switch (msg.what) { 19861 case MSG_ON_PERMISSIONS_CHANGED: { 19862 final int uid = msg.arg1; 19863 handleOnPermissionsChanged(uid); 19864 } break; 19865 } 19866 } 19867 19868 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19869 mPermissionListeners.register(listener); 19870 19871 } 19872 19873 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19874 mPermissionListeners.unregister(listener); 19875 } 19876 19877 public void onPermissionsChanged(int uid) { 19878 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19879 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19880 } 19881 } 19882 19883 private void handleOnPermissionsChanged(int uid) { 19884 final int count = mPermissionListeners.beginBroadcast(); 19885 try { 19886 for (int i = 0; i < count; i++) { 19887 IOnPermissionsChangeListener callback = mPermissionListeners 19888 .getBroadcastItem(i); 19889 try { 19890 callback.onPermissionsChanged(uid); 19891 } catch (RemoteException e) { 19892 Log.e(TAG, "Permission listener is dead", e); 19893 } 19894 } 19895 } finally { 19896 mPermissionListeners.finishBroadcast(); 19897 } 19898 } 19899 } 19900 19901 private class PackageManagerInternalImpl extends PackageManagerInternal { 19902 @Override 19903 public void setLocationPackagesProvider(PackagesProvider provider) { 19904 synchronized (mPackages) { 19905 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19906 } 19907 } 19908 19909 @Override 19910 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19911 synchronized (mPackages) { 19912 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19913 } 19914 } 19915 19916 @Override 19917 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19918 synchronized (mPackages) { 19919 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19920 } 19921 } 19922 19923 @Override 19924 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19925 synchronized (mPackages) { 19926 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19927 } 19928 } 19929 19930 @Override 19931 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19932 synchronized (mPackages) { 19933 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19934 } 19935 } 19936 19937 @Override 19938 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19939 synchronized (mPackages) { 19940 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19941 } 19942 } 19943 19944 @Override 19945 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19946 synchronized (mPackages) { 19947 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19948 packageName, userId); 19949 } 19950 } 19951 19952 @Override 19953 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19954 synchronized (mPackages) { 19955 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19956 packageName, userId); 19957 } 19958 } 19959 19960 @Override 19961 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19962 synchronized (mPackages) { 19963 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19964 packageName, userId); 19965 } 19966 } 19967 19968 @Override 19969 public void setKeepUninstalledPackages(final List<String> packageList) { 19970 Preconditions.checkNotNull(packageList); 19971 List<String> removedFromList = null; 19972 synchronized (mPackages) { 19973 if (mKeepUninstalledPackages != null) { 19974 final int packagesCount = mKeepUninstalledPackages.size(); 19975 for (int i = 0; i < packagesCount; i++) { 19976 String oldPackage = mKeepUninstalledPackages.get(i); 19977 if (packageList != null && packageList.contains(oldPackage)) { 19978 continue; 19979 } 19980 if (removedFromList == null) { 19981 removedFromList = new ArrayList<>(); 19982 } 19983 removedFromList.add(oldPackage); 19984 } 19985 } 19986 mKeepUninstalledPackages = new ArrayList<>(packageList); 19987 if (removedFromList != null) { 19988 final int removedCount = removedFromList.size(); 19989 for (int i = 0; i < removedCount; i++) { 19990 deletePackageIfUnusedLPr(removedFromList.get(i)); 19991 } 19992 } 19993 } 19994 } 19995 19996 @Override 19997 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19998 synchronized (mPackages) { 19999 // If we do not support permission review, done. 20000 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20001 return false; 20002 } 20003 20004 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20005 if (packageSetting == null) { 20006 return false; 20007 } 20008 20009 // Permission review applies only to apps not supporting the new permission model. 20010 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20011 return false; 20012 } 20013 20014 // Legacy apps have the permission and get user consent on launch. 20015 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20016 return permissionsState.isPermissionReviewRequired(userId); 20017 } 20018 } 20019 20020 @Override 20021 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20022 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20023 } 20024 20025 @Override 20026 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20027 int userId) { 20028 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20029 } 20030 } 20031 20032 @Override 20033 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20034 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20035 synchronized (mPackages) { 20036 final long identity = Binder.clearCallingIdentity(); 20037 try { 20038 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20039 packageNames, userId); 20040 } finally { 20041 Binder.restoreCallingIdentity(identity); 20042 } 20043 } 20044 } 20045 20046 private static void enforceSystemOrPhoneCaller(String tag) { 20047 int callingUid = Binder.getCallingUid(); 20048 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20049 throw new SecurityException( 20050 "Cannot call " + tag + " from UID " + callingUid); 20051 } 20052 } 20053 20054 boolean isHistoricalPackageUsageAvailable() { 20055 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20056 } 20057 20058 /** 20059 * Return a <b>copy</b> of the collection of packages known to the package manager. 20060 * @return A copy of the values of mPackages. 20061 */ 20062 Collection<PackageParser.Package> getPackages() { 20063 synchronized (mPackages) { 20064 return new ArrayList<>(mPackages.values()); 20065 } 20066 } 20067 20068 /** 20069 * Logs process start information (including base APK hash) to the security log. 20070 * @hide 20071 */ 20072 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20073 String apkFile, int pid) { 20074 if (!SecurityLog.isLoggingEnabled()) { 20075 return; 20076 } 20077 Bundle data = new Bundle(); 20078 data.putLong("startTimestamp", System.currentTimeMillis()); 20079 data.putString("processName", processName); 20080 data.putInt("uid", uid); 20081 data.putString("seinfo", seinfo); 20082 data.putString("apkFile", apkFile); 20083 data.putInt("pid", pid); 20084 Message msg = mProcessLoggingHandler.obtainMessage( 20085 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20086 msg.setData(data); 20087 mProcessLoggingHandler.sendMessage(msg); 20088 } 20089} 20090