PackageManagerService.java revision f8173ca8ac0efef39c79d732fd9eee80d1066302
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 UsageStatsManager usageMgr = 7089 (UsageStatsManager) mContext.getSystemService(Context.USAGE_STATS_SERVICE); 7090 7091 int curr = 0; 7092 int total = pkgs.size(); 7093 for (PackageParser.Package pkg : pkgs) { 7094 curr++; 7095 7096 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7097 if (DEBUG_DEXOPT) { 7098 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7099 } 7100 continue; 7101 } 7102 7103 if (!causeFirstBoot && usageMgr.isAppInactive(pkg.packageName)) { 7104 if (DEBUG_DEXOPT) { 7105 Log.i(TAG, "Skipping update of of idle app " + pkg.packageName); 7106 } 7107 continue; 7108 } 7109 7110 if (DEBUG_DEXOPT) { 7111 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7112 } 7113 7114 if (!isFirstBoot()) { 7115 try { 7116 ActivityManagerNative.getDefault().showBootMessage( 7117 mContext.getResources().getString(R.string.android_upgrading_apk, 7118 curr, total), true); 7119 } catch (RemoteException e) { 7120 } 7121 } 7122 7123 performDexOpt(pkg.packageName, 7124 null /* instructionSet */, 7125 false /* checkProfiles */, 7126 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7127 false /* force */); 7128 } 7129 } 7130 7131 @Override 7132 public void notifyPackageUse(String packageName) { 7133 synchronized (mPackages) { 7134 PackageParser.Package p = mPackages.get(packageName); 7135 if (p == null) { 7136 return; 7137 } 7138 p.mLastPackageUsageTimeInMills = System.currentTimeMillis(); 7139 } 7140 } 7141 7142 // TODO: this is not used nor needed. Delete it. 7143 @Override 7144 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7145 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7146 getFullCompilerFilter(), false /* force */); 7147 } 7148 7149 @Override 7150 public boolean performDexOpt(String packageName, String instructionSet, 7151 boolean checkProfiles, int compileReason, boolean force) { 7152 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7153 getCompilerFilterForReason(compileReason), force); 7154 } 7155 7156 @Override 7157 public boolean performDexOptMode(String packageName, String instructionSet, 7158 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7159 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7160 targetCompilerFilter, force); 7161 } 7162 7163 private boolean performDexOptTraced(String packageName, String instructionSet, 7164 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7165 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7166 try { 7167 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7168 targetCompilerFilter, force); 7169 } finally { 7170 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7171 } 7172 } 7173 7174 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7175 // if the package can now be considered up to date for the given filter. 7176 private boolean performDexOptInternal(String packageName, String instructionSet, 7177 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7178 PackageParser.Package p; 7179 final String targetInstructionSet; 7180 synchronized (mPackages) { 7181 p = mPackages.get(packageName); 7182 if (p == null) { 7183 return false; 7184 } 7185 mPackageUsage.write(false); 7186 7187 targetInstructionSet = instructionSet != null ? instructionSet : 7188 getPrimaryInstructionSet(p.applicationInfo); 7189 } 7190 long callingId = Binder.clearCallingIdentity(); 7191 try { 7192 synchronized (mInstallLock) { 7193 final String[] instructionSets = new String[] { targetInstructionSet }; 7194 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7195 checkProfiles, targetCompilerFilter, force); 7196 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7197 } 7198 } finally { 7199 Binder.restoreCallingIdentity(callingId); 7200 } 7201 } 7202 7203 public ArraySet<String> getOptimizablePackages() { 7204 ArraySet<String> pkgs = new ArraySet<String>(); 7205 synchronized (mPackages) { 7206 for (PackageParser.Package p : mPackages.values()) { 7207 if (PackageDexOptimizer.canOptimizePackage(p)) { 7208 pkgs.add(p.packageName); 7209 } 7210 } 7211 } 7212 return pkgs; 7213 } 7214 7215 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7216 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7217 boolean force) { 7218 // Select the dex optimizer based on the force parameter. 7219 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7220 // allocate an object here. 7221 PackageDexOptimizer pdo = force 7222 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7223 : mPackageDexOptimizer; 7224 7225 // Optimize all dependencies first. Note: we ignore the return value and march on 7226 // on errors. 7227 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7228 if (!deps.isEmpty()) { 7229 for (PackageParser.Package depPackage : deps) { 7230 // TODO: Analyze and investigate if we (should) profile libraries. 7231 // Currently this will do a full compilation of the library by default. 7232 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7233 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7234 } 7235 } 7236 7237 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7238 } 7239 7240 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7241 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7242 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7243 Set<String> collectedNames = new HashSet<>(); 7244 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7245 7246 retValue.remove(p); 7247 7248 return retValue; 7249 } else { 7250 return Collections.emptyList(); 7251 } 7252 } 7253 7254 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7255 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7256 if (!collectedNames.contains(p.packageName)) { 7257 collectedNames.add(p.packageName); 7258 collected.add(p); 7259 7260 if (p.usesLibraries != null) { 7261 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7262 } 7263 if (p.usesOptionalLibraries != null) { 7264 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7265 collectedNames); 7266 } 7267 } 7268 } 7269 7270 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7271 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7272 for (String libName : libs) { 7273 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7274 if (libPkg != null) { 7275 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7276 } 7277 } 7278 } 7279 7280 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7281 synchronized (mPackages) { 7282 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7283 if (lib != null && lib.apk != null) { 7284 return mPackages.get(lib.apk); 7285 } 7286 } 7287 return null; 7288 } 7289 7290 public void shutdown() { 7291 mPackageUsage.write(true); 7292 } 7293 7294 @Override 7295 public void forceDexOpt(String packageName) { 7296 enforceSystemOrRoot("forceDexOpt"); 7297 7298 PackageParser.Package pkg; 7299 synchronized (mPackages) { 7300 pkg = mPackages.get(packageName); 7301 if (pkg == null) { 7302 throw new IllegalArgumentException("Unknown package: " + packageName); 7303 } 7304 } 7305 7306 synchronized (mInstallLock) { 7307 final String[] instructionSets = new String[] { 7308 getPrimaryInstructionSet(pkg.applicationInfo) }; 7309 7310 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7311 7312 // Whoever is calling forceDexOpt wants a fully compiled package. 7313 // Don't use profiles since that may cause compilation to be skipped. 7314 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7315 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7316 true /* force */); 7317 7318 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7319 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7320 throw new IllegalStateException("Failed to dexopt: " + res); 7321 } 7322 } 7323 } 7324 7325 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7326 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7327 Slog.w(TAG, "Unable to update from " + oldPkg.name 7328 + " to " + newPkg.packageName 7329 + ": old package not in system partition"); 7330 return false; 7331 } else if (mPackages.get(oldPkg.name) != null) { 7332 Slog.w(TAG, "Unable to update from " + oldPkg.name 7333 + " to " + newPkg.packageName 7334 + ": old package still exists"); 7335 return false; 7336 } 7337 return true; 7338 } 7339 7340 void removeCodePathLI(File codePath) { 7341 if (codePath.isDirectory()) { 7342 try { 7343 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7344 } catch (InstallerException e) { 7345 Slog.w(TAG, "Failed to remove code path", e); 7346 } 7347 } else { 7348 codePath.delete(); 7349 } 7350 } 7351 7352 private int[] resolveUserIds(int userId) { 7353 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7354 } 7355 7356 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7357 if (pkg == null) { 7358 Slog.wtf(TAG, "Package was null!", new Throwable()); 7359 return; 7360 } 7361 clearAppDataLeafLIF(pkg, userId, flags); 7362 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7363 for (int i = 0; i < childCount; i++) { 7364 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7365 } 7366 } 7367 7368 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7369 final PackageSetting ps; 7370 synchronized (mPackages) { 7371 ps = mSettings.mPackages.get(pkg.packageName); 7372 } 7373 for (int realUserId : resolveUserIds(userId)) { 7374 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7375 try { 7376 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7377 ceDataInode); 7378 } catch (InstallerException e) { 7379 Slog.w(TAG, String.valueOf(e)); 7380 } 7381 } 7382 } 7383 7384 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7385 if (pkg == null) { 7386 Slog.wtf(TAG, "Package was null!", new Throwable()); 7387 return; 7388 } 7389 destroyAppDataLeafLIF(pkg, userId, flags); 7390 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7391 for (int i = 0; i < childCount; i++) { 7392 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7393 } 7394 } 7395 7396 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7397 final PackageSetting ps; 7398 synchronized (mPackages) { 7399 ps = mSettings.mPackages.get(pkg.packageName); 7400 } 7401 for (int realUserId : resolveUserIds(userId)) { 7402 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7403 try { 7404 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7405 ceDataInode); 7406 } catch (InstallerException e) { 7407 Slog.w(TAG, String.valueOf(e)); 7408 } 7409 } 7410 } 7411 7412 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7413 if (pkg == null) { 7414 Slog.wtf(TAG, "Package was null!", new Throwable()); 7415 return; 7416 } 7417 destroyAppProfilesLeafLIF(pkg); 7418 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7419 for (int i = 0; i < childCount; i++) { 7420 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7421 } 7422 } 7423 7424 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7425 try { 7426 mInstaller.destroyAppProfiles(pkg.packageName); 7427 } catch (InstallerException e) { 7428 Slog.w(TAG, String.valueOf(e)); 7429 } 7430 } 7431 7432 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7433 if (pkg == null) { 7434 Slog.wtf(TAG, "Package was null!", new Throwable()); 7435 return; 7436 } 7437 clearAppProfilesLeafLIF(pkg); 7438 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7439 for (int i = 0; i < childCount; i++) { 7440 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7441 } 7442 } 7443 7444 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7445 try { 7446 mInstaller.clearAppProfiles(pkg.packageName); 7447 } catch (InstallerException e) { 7448 Slog.w(TAG, String.valueOf(e)); 7449 } 7450 } 7451 7452 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7453 long lastUpdateTime) { 7454 // Set parent install/update time 7455 PackageSetting ps = (PackageSetting) pkg.mExtras; 7456 if (ps != null) { 7457 ps.firstInstallTime = firstInstallTime; 7458 ps.lastUpdateTime = lastUpdateTime; 7459 } 7460 // Set children install/update time 7461 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7462 for (int i = 0; i < childCount; i++) { 7463 PackageParser.Package childPkg = pkg.childPackages.get(i); 7464 ps = (PackageSetting) childPkg.mExtras; 7465 if (ps != null) { 7466 ps.firstInstallTime = firstInstallTime; 7467 ps.lastUpdateTime = lastUpdateTime; 7468 } 7469 } 7470 } 7471 7472 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7473 PackageParser.Package changingLib) { 7474 if (file.path != null) { 7475 usesLibraryFiles.add(file.path); 7476 return; 7477 } 7478 PackageParser.Package p = mPackages.get(file.apk); 7479 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7480 // If we are doing this while in the middle of updating a library apk, 7481 // then we need to make sure to use that new apk for determining the 7482 // dependencies here. (We haven't yet finished committing the new apk 7483 // to the package manager state.) 7484 if (p == null || p.packageName.equals(changingLib.packageName)) { 7485 p = changingLib; 7486 } 7487 } 7488 if (p != null) { 7489 usesLibraryFiles.addAll(p.getAllCodePaths()); 7490 } 7491 } 7492 7493 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7494 PackageParser.Package changingLib) throws PackageManagerException { 7495 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7496 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7497 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7498 for (int i=0; i<N; i++) { 7499 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7500 if (file == null) { 7501 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7502 "Package " + pkg.packageName + " requires unavailable shared library " 7503 + pkg.usesLibraries.get(i) + "; failing!"); 7504 } 7505 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7506 } 7507 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7508 for (int i=0; i<N; i++) { 7509 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7510 if (file == null) { 7511 Slog.w(TAG, "Package " + pkg.packageName 7512 + " desires unavailable shared library " 7513 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7514 } else { 7515 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7516 } 7517 } 7518 N = usesLibraryFiles.size(); 7519 if (N > 0) { 7520 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7521 } else { 7522 pkg.usesLibraryFiles = null; 7523 } 7524 } 7525 } 7526 7527 private static boolean hasString(List<String> list, List<String> which) { 7528 if (list == null) { 7529 return false; 7530 } 7531 for (int i=list.size()-1; i>=0; i--) { 7532 for (int j=which.size()-1; j>=0; j--) { 7533 if (which.get(j).equals(list.get(i))) { 7534 return true; 7535 } 7536 } 7537 } 7538 return false; 7539 } 7540 7541 private void updateAllSharedLibrariesLPw() { 7542 for (PackageParser.Package pkg : mPackages.values()) { 7543 try { 7544 updateSharedLibrariesLPw(pkg, null); 7545 } catch (PackageManagerException e) { 7546 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7547 } 7548 } 7549 } 7550 7551 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7552 PackageParser.Package changingPkg) { 7553 ArrayList<PackageParser.Package> res = null; 7554 for (PackageParser.Package pkg : mPackages.values()) { 7555 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7556 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7557 if (res == null) { 7558 res = new ArrayList<PackageParser.Package>(); 7559 } 7560 res.add(pkg); 7561 try { 7562 updateSharedLibrariesLPw(pkg, changingPkg); 7563 } catch (PackageManagerException e) { 7564 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7565 } 7566 } 7567 } 7568 return res; 7569 } 7570 7571 /** 7572 * Derive the value of the {@code cpuAbiOverride} based on the provided 7573 * value and an optional stored value from the package settings. 7574 */ 7575 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7576 String cpuAbiOverride = null; 7577 7578 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7579 cpuAbiOverride = null; 7580 } else if (abiOverride != null) { 7581 cpuAbiOverride = abiOverride; 7582 } else if (settings != null) { 7583 cpuAbiOverride = settings.cpuAbiOverrideString; 7584 } 7585 7586 return cpuAbiOverride; 7587 } 7588 7589 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, int parseFlags, 7590 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7591 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7592 // If the package has children and this is the first dive in the function 7593 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7594 // whether all packages (parent and children) would be successfully scanned 7595 // before the actual scan since scanning mutates internal state and we want 7596 // to atomically install the package and its children. 7597 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7598 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7599 scanFlags |= SCAN_CHECK_ONLY; 7600 } 7601 } else { 7602 scanFlags &= ~SCAN_CHECK_ONLY; 7603 } 7604 7605 final PackageParser.Package scannedPkg; 7606 try { 7607 // Scan the parent 7608 scannedPkg = scanPackageLI(pkg, parseFlags, scanFlags, currentTime, user); 7609 // Scan the children 7610 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7611 for (int i = 0; i < childCount; i++) { 7612 PackageParser.Package childPkg = pkg.childPackages.get(i); 7613 scanPackageLI(childPkg, parseFlags, 7614 scanFlags, currentTime, user); 7615 } 7616 } finally { 7617 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7618 } 7619 7620 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7621 return scanPackageTracedLI(pkg, parseFlags, scanFlags, currentTime, user); 7622 } 7623 7624 return scannedPkg; 7625 } 7626 7627 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, int parseFlags, 7628 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7629 boolean success = false; 7630 try { 7631 final PackageParser.Package res = scanPackageDirtyLI(pkg, parseFlags, scanFlags, 7632 currentTime, user); 7633 success = true; 7634 return res; 7635 } finally { 7636 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7637 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7638 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7639 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7640 destroyAppProfilesLIF(pkg); 7641 } 7642 } 7643 } 7644 7645 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, int parseFlags, 7646 int scanFlags, long currentTime, UserHandle user) 7647 throws PackageManagerException { 7648 final File scanFile = new File(pkg.codePath); 7649 if (pkg.applicationInfo.getCodePath() == null || 7650 pkg.applicationInfo.getResourcePath() == null) { 7651 // Bail out. The resource and code paths haven't been set. 7652 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7653 "Code and resource paths haven't been set correctly"); 7654 } 7655 7656 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7657 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7658 } else { 7659 // Only allow system apps to be flagged as core apps. 7660 pkg.coreApp = false; 7661 } 7662 7663 if ((parseFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7664 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7665 } 7666 7667 if (mCustomResolverComponentName != null && 7668 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7669 setUpCustomResolverActivity(pkg); 7670 } 7671 7672 if (pkg.packageName.equals("android")) { 7673 synchronized (mPackages) { 7674 if (mAndroidApplication != null) { 7675 Slog.w(TAG, "*************************************************"); 7676 Slog.w(TAG, "Core android package being redefined. Skipping."); 7677 Slog.w(TAG, " file=" + scanFile); 7678 Slog.w(TAG, "*************************************************"); 7679 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7680 "Core android package being redefined. Skipping."); 7681 } 7682 7683 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7684 // Set up information for our fall-back user intent resolution activity. 7685 mPlatformPackage = pkg; 7686 pkg.mVersionCode = mSdkVersion; 7687 mAndroidApplication = pkg.applicationInfo; 7688 7689 if (!mResolverReplaced) { 7690 mResolveActivity.applicationInfo = mAndroidApplication; 7691 mResolveActivity.name = ResolverActivity.class.getName(); 7692 mResolveActivity.packageName = mAndroidApplication.packageName; 7693 mResolveActivity.processName = "system:ui"; 7694 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7695 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7696 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7697 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7698 mResolveActivity.exported = true; 7699 mResolveActivity.enabled = true; 7700 mResolveInfo.activityInfo = mResolveActivity; 7701 mResolveInfo.priority = 0; 7702 mResolveInfo.preferredOrder = 0; 7703 mResolveInfo.match = 0; 7704 mResolveComponentName = new ComponentName( 7705 mAndroidApplication.packageName, mResolveActivity.name); 7706 } 7707 } 7708 } 7709 } 7710 7711 if (DEBUG_PACKAGE_SCANNING) { 7712 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7713 Log.d(TAG, "Scanning package " + pkg.packageName); 7714 } 7715 7716 synchronized (mPackages) { 7717 if (mPackages.containsKey(pkg.packageName) 7718 || mSharedLibraries.containsKey(pkg.packageName)) { 7719 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7720 "Application package " + pkg.packageName 7721 + " already installed. Skipping duplicate."); 7722 } 7723 7724 // If we're only installing presumed-existing packages, require that the 7725 // scanned APK is both already known and at the path previously established 7726 // for it. Previously unknown packages we pick up normally, but if we have an 7727 // a priori expectation about this package's install presence, enforce it. 7728 // With a singular exception for new system packages. When an OTA contains 7729 // a new system package, we allow the codepath to change from a system location 7730 // to the user-installed location. If we don't allow this change, any newer, 7731 // user-installed version of the application will be ignored. 7732 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7733 if (mExpectingBetter.containsKey(pkg.packageName)) { 7734 logCriticalInfo(Log.WARN, 7735 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7736 } else { 7737 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7738 if (known != null) { 7739 if (DEBUG_PACKAGE_SCANNING) { 7740 Log.d(TAG, "Examining " + pkg.codePath 7741 + " and requiring known paths " + known.codePathString 7742 + " & " + known.resourcePathString); 7743 } 7744 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7745 || !pkg.applicationInfo.getResourcePath().equals( 7746 known.resourcePathString)) { 7747 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7748 "Application package " + pkg.packageName 7749 + " found at " + pkg.applicationInfo.getCodePath() 7750 + " but expected at " + known.codePathString 7751 + "; ignoring."); 7752 } 7753 } 7754 } 7755 } 7756 } 7757 7758 // Initialize package source and resource directories 7759 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7760 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7761 7762 SharedUserSetting suid = null; 7763 PackageSetting pkgSetting = null; 7764 7765 if (!isSystemApp(pkg)) { 7766 // Only system apps can use these features. 7767 pkg.mOriginalPackages = null; 7768 pkg.mRealPackage = null; 7769 pkg.mAdoptPermissions = null; 7770 } 7771 7772 // Getting the package setting may have a side-effect, so if we 7773 // are only checking if scan would succeed, stash a copy of the 7774 // old setting to restore at the end. 7775 PackageSetting nonMutatedPs = null; 7776 7777 // writer 7778 synchronized (mPackages) { 7779 if (pkg.mSharedUserId != null) { 7780 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7781 if (suid == null) { 7782 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7783 "Creating application package " + pkg.packageName 7784 + " for shared user failed"); 7785 } 7786 if (DEBUG_PACKAGE_SCANNING) { 7787 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 7788 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7789 + "): packages=" + suid.packages); 7790 } 7791 } 7792 7793 // Check if we are renaming from an original package name. 7794 PackageSetting origPackage = null; 7795 String realName = null; 7796 if (pkg.mOriginalPackages != null) { 7797 // This package may need to be renamed to a previously 7798 // installed name. Let's check on that... 7799 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7800 if (pkg.mOriginalPackages.contains(renamed)) { 7801 // This package had originally been installed as the 7802 // original name, and we have already taken care of 7803 // transitioning to the new one. Just update the new 7804 // one to continue using the old name. 7805 realName = pkg.mRealPackage; 7806 if (!pkg.packageName.equals(renamed)) { 7807 // Callers into this function may have already taken 7808 // care of renaming the package; only do it here if 7809 // it is not already done. 7810 pkg.setPackageName(renamed); 7811 } 7812 7813 } else { 7814 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7815 if ((origPackage = mSettings.peekPackageLPr( 7816 pkg.mOriginalPackages.get(i))) != null) { 7817 // We do have the package already installed under its 7818 // original name... should we use it? 7819 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7820 // New package is not compatible with original. 7821 origPackage = null; 7822 continue; 7823 } else if (origPackage.sharedUser != null) { 7824 // Make sure uid is compatible between packages. 7825 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7826 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7827 + " to " + pkg.packageName + ": old uid " 7828 + origPackage.sharedUser.name 7829 + " differs from " + pkg.mSharedUserId); 7830 origPackage = null; 7831 continue; 7832 } 7833 } else { 7834 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7835 + pkg.packageName + " to old name " + origPackage.name); 7836 } 7837 break; 7838 } 7839 } 7840 } 7841 } 7842 7843 if (mTransferedPackages.contains(pkg.packageName)) { 7844 Slog.w(TAG, "Package " + pkg.packageName 7845 + " was transferred to another, but its .apk remains"); 7846 } 7847 7848 // See comments in nonMutatedPs declaration 7849 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7850 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 7851 if (foundPs != null) { 7852 nonMutatedPs = new PackageSetting(foundPs); 7853 } 7854 } 7855 7856 // Just create the setting, don't add it yet. For already existing packages 7857 // the PkgSetting exists already and doesn't have to be created. 7858 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 7859 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 7860 pkg.applicationInfo.primaryCpuAbi, 7861 pkg.applicationInfo.secondaryCpuAbi, 7862 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 7863 user, false); 7864 if (pkgSetting == null) { 7865 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7866 "Creating application package " + pkg.packageName + " failed"); 7867 } 7868 7869 if (pkgSetting.origPackage != null) { 7870 // If we are first transitioning from an original package, 7871 // fix up the new package's name now. We need to do this after 7872 // looking up the package under its new name, so getPackageLP 7873 // can take care of fiddling things correctly. 7874 pkg.setPackageName(origPackage.name); 7875 7876 // File a report about this. 7877 String msg = "New package " + pkgSetting.realName 7878 + " renamed to replace old package " + pkgSetting.name; 7879 reportSettingsProblem(Log.WARN, msg); 7880 7881 // Make a note of it. 7882 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7883 mTransferedPackages.add(origPackage.name); 7884 } 7885 7886 // No longer need to retain this. 7887 pkgSetting.origPackage = null; 7888 } 7889 7890 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 7891 // Make a note of it. 7892 mTransferedPackages.add(pkg.packageName); 7893 } 7894 7895 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 7896 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 7897 } 7898 7899 if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7900 // Check all shared libraries and map to their actual file path. 7901 // We only do this here for apps not on a system dir, because those 7902 // are the only ones that can fail an install due to this. We 7903 // will take care of the system apps by updating all of their 7904 // library paths after the scan is done. 7905 updateSharedLibrariesLPw(pkg, null); 7906 } 7907 7908 if (mFoundPolicyFile) { 7909 SELinuxMMAC.assignSeinfoValue(pkg); 7910 } 7911 7912 pkg.applicationInfo.uid = pkgSetting.appId; 7913 pkg.mExtras = pkgSetting; 7914 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 7915 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 7916 // We just determined the app is signed correctly, so bring 7917 // over the latest parsed certs. 7918 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7919 } else { 7920 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7921 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 7922 "Package " + pkg.packageName + " upgrade keys do not match the " 7923 + "previously installed version"); 7924 } else { 7925 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7926 String msg = "System package " + pkg.packageName 7927 + " signature changed; retaining data."; 7928 reportSettingsProblem(Log.WARN, msg); 7929 } 7930 } 7931 } else { 7932 try { 7933 verifySignaturesLP(pkgSetting, pkg); 7934 // We just determined the app is signed correctly, so bring 7935 // over the latest parsed certs. 7936 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7937 } catch (PackageManagerException e) { 7938 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 7939 throw e; 7940 } 7941 // The signature has changed, but this package is in the system 7942 // image... let's recover! 7943 pkgSetting.signatures.mSignatures = pkg.mSignatures; 7944 // However... if this package is part of a shared user, but it 7945 // doesn't match the signature of the shared user, let's fail. 7946 // What this means is that you can't change the signatures 7947 // associated with an overall shared user, which doesn't seem all 7948 // that unreasonable. 7949 if (pkgSetting.sharedUser != null) { 7950 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7951 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 7952 throw new PackageManagerException( 7953 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 7954 "Signature mismatch for shared user: " 7955 + pkgSetting.sharedUser); 7956 } 7957 } 7958 // File a report about this. 7959 String msg = "System package " + pkg.packageName 7960 + " signature changed; retaining data."; 7961 reportSettingsProblem(Log.WARN, msg); 7962 } 7963 } 7964 // Verify that this new package doesn't have any content providers 7965 // that conflict with existing packages. Only do this if the 7966 // package isn't already installed, since we don't want to break 7967 // things that are installed. 7968 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 7969 final int N = pkg.providers.size(); 7970 int i; 7971 for (i=0; i<N; i++) { 7972 PackageParser.Provider p = pkg.providers.get(i); 7973 if (p.info.authority != null) { 7974 String names[] = p.info.authority.split(";"); 7975 for (int j = 0; j < names.length; j++) { 7976 if (mProvidersByAuthority.containsKey(names[j])) { 7977 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 7978 final String otherPackageName = 7979 ((other != null && other.getComponentName() != null) ? 7980 other.getComponentName().getPackageName() : "?"); 7981 throw new PackageManagerException( 7982 INSTALL_FAILED_CONFLICTING_PROVIDER, 7983 "Can't install because provider name " + names[j] 7984 + " (in package " + pkg.applicationInfo.packageName 7985 + ") is already used by " + otherPackageName); 7986 } 7987 } 7988 } 7989 } 7990 } 7991 7992 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 7993 // This package wants to adopt ownership of permissions from 7994 // another package. 7995 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 7996 final String origName = pkg.mAdoptPermissions.get(i); 7997 final PackageSetting orig = mSettings.peekPackageLPr(origName); 7998 if (orig != null) { 7999 if (verifyPackageUpdateLPr(orig, pkg)) { 8000 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8001 + pkg.packageName); 8002 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8003 } 8004 } 8005 } 8006 } 8007 } 8008 8009 final String pkgName = pkg.packageName; 8010 8011 final long scanFileTime = scanFile.lastModified(); 8012 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8013 pkg.applicationInfo.processName = fixProcessName( 8014 pkg.applicationInfo.packageName, 8015 pkg.applicationInfo.processName, 8016 pkg.applicationInfo.uid); 8017 8018 if (pkg != mPlatformPackage) { 8019 // Get all of our default paths setup 8020 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8021 } 8022 8023 final String path = scanFile.getPath(); 8024 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8025 8026 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8027 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8028 8029 // Some system apps still use directory structure for native libraries 8030 // in which case we might end up not detecting abi solely based on apk 8031 // structure. Try to detect abi based on directory structure. 8032 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8033 pkg.applicationInfo.primaryCpuAbi == null) { 8034 setBundledAppAbisAndRoots(pkg, pkgSetting); 8035 setNativeLibraryPaths(pkg); 8036 } 8037 8038 } else { 8039 if ((scanFlags & SCAN_MOVE) != 0) { 8040 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8041 // but we already have this packages package info in the PackageSetting. We just 8042 // use that and derive the native library path based on the new codepath. 8043 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8044 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8045 } 8046 8047 // Set native library paths again. For moves, the path will be updated based on the 8048 // ABIs we've determined above. For non-moves, the path will be updated based on the 8049 // ABIs we determined during compilation, but the path will depend on the final 8050 // package path (after the rename away from the stage path). 8051 setNativeLibraryPaths(pkg); 8052 } 8053 8054 // This is a special case for the "system" package, where the ABI is 8055 // dictated by the zygote configuration (and init.rc). We should keep track 8056 // of this ABI so that we can deal with "normal" applications that run under 8057 // the same UID correctly. 8058 if (mPlatformPackage == pkg) { 8059 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8060 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8061 } 8062 8063 // If there's a mismatch between the abi-override in the package setting 8064 // and the abiOverride specified for the install. Warn about this because we 8065 // would've already compiled the app without taking the package setting into 8066 // account. 8067 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8068 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8069 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8070 " for package " + pkg.packageName); 8071 } 8072 } 8073 8074 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8075 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8076 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8077 8078 // Copy the derived override back to the parsed package, so that we can 8079 // update the package settings accordingly. 8080 pkg.cpuAbiOverride = cpuAbiOverride; 8081 8082 if (DEBUG_ABI_SELECTION) { 8083 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8084 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8085 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8086 } 8087 8088 // Push the derived path down into PackageSettings so we know what to 8089 // clean up at uninstall time. 8090 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8091 8092 if (DEBUG_ABI_SELECTION) { 8093 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8094 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8095 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8096 } 8097 8098 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8099 // We don't do this here during boot because we can do it all 8100 // at once after scanning all existing packages. 8101 // 8102 // We also do this *before* we perform dexopt on this package, so that 8103 // we can avoid redundant dexopts, and also to make sure we've got the 8104 // code and package path correct. 8105 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8106 pkg, true /* boot complete */); 8107 } 8108 8109 if (mFactoryTest && pkg.requestedPermissions.contains( 8110 android.Manifest.permission.FACTORY_TEST)) { 8111 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8112 } 8113 8114 ArrayList<PackageParser.Package> clientLibPkgs = null; 8115 8116 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8117 if (nonMutatedPs != null) { 8118 synchronized (mPackages) { 8119 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8120 } 8121 } 8122 return pkg; 8123 } 8124 8125 // Only privileged apps and updated privileged apps can add child packages. 8126 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8127 if ((parseFlags & PARSE_IS_PRIVILEGED) == 0) { 8128 throw new PackageManagerException("Only privileged apps and updated " 8129 + "privileged apps can add child packages. Ignoring package " 8130 + pkg.packageName); 8131 } 8132 final int childCount = pkg.childPackages.size(); 8133 for (int i = 0; i < childCount; i++) { 8134 PackageParser.Package childPkg = pkg.childPackages.get(i); 8135 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8136 childPkg.packageName)) { 8137 throw new PackageManagerException("Cannot override a child package of " 8138 + "another disabled system app. Ignoring package " + pkg.packageName); 8139 } 8140 } 8141 } 8142 8143 // writer 8144 synchronized (mPackages) { 8145 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8146 // Only system apps can add new shared libraries. 8147 if (pkg.libraryNames != null) { 8148 for (int i=0; i<pkg.libraryNames.size(); i++) { 8149 String name = pkg.libraryNames.get(i); 8150 boolean allowed = false; 8151 if (pkg.isUpdatedSystemApp()) { 8152 // New library entries can only be added through the 8153 // system image. This is important to get rid of a lot 8154 // of nasty edge cases: for example if we allowed a non- 8155 // system update of the app to add a library, then uninstalling 8156 // the update would make the library go away, and assumptions 8157 // we made such as through app install filtering would now 8158 // have allowed apps on the device which aren't compatible 8159 // with it. Better to just have the restriction here, be 8160 // conservative, and create many fewer cases that can negatively 8161 // impact the user experience. 8162 final PackageSetting sysPs = mSettings 8163 .getDisabledSystemPkgLPr(pkg.packageName); 8164 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8165 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8166 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8167 allowed = true; 8168 break; 8169 } 8170 } 8171 } 8172 } else { 8173 allowed = true; 8174 } 8175 if (allowed) { 8176 if (!mSharedLibraries.containsKey(name)) { 8177 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8178 } else if (!name.equals(pkg.packageName)) { 8179 Slog.w(TAG, "Package " + pkg.packageName + " library " 8180 + name + " already exists; skipping"); 8181 } 8182 } else { 8183 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8184 + name + " that is not declared on system image; skipping"); 8185 } 8186 } 8187 if ((scanFlags & SCAN_BOOTING) == 0) { 8188 // If we are not booting, we need to update any applications 8189 // that are clients of our shared library. If we are booting, 8190 // this will all be done once the scan is complete. 8191 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8192 } 8193 } 8194 } 8195 } 8196 8197 if ((scanFlags & SCAN_BOOTING) != 0) { 8198 // No apps can run during boot scan, so they don't need to be frozen 8199 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8200 // Caller asked to not kill app, so it's probably not frozen 8201 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8202 // Caller asked us to ignore frozen check for some reason; they 8203 // probably didn't know the package name 8204 } else { 8205 // We're doing major surgery on this package, so it better be frozen 8206 // right now to keep it from launching 8207 checkPackageFrozen(pkgName); 8208 } 8209 8210 // Also need to kill any apps that are dependent on the library. 8211 if (clientLibPkgs != null) { 8212 for (int i=0; i<clientLibPkgs.size(); i++) { 8213 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8214 killApplication(clientPkg.applicationInfo.packageName, 8215 clientPkg.applicationInfo.uid, "update lib"); 8216 } 8217 } 8218 8219 // Make sure we're not adding any bogus keyset info 8220 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8221 ksms.assertScannedPackageValid(pkg); 8222 8223 // writer 8224 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8225 8226 boolean createIdmapFailed = false; 8227 synchronized (mPackages) { 8228 // We don't expect installation to fail beyond this point 8229 8230 // Add the new setting to mSettings 8231 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8232 // Add the new setting to mPackages 8233 mPackages.put(pkg.applicationInfo.packageName, pkg); 8234 // Make sure we don't accidentally delete its data. 8235 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8236 while (iter.hasNext()) { 8237 PackageCleanItem item = iter.next(); 8238 if (pkgName.equals(item.packageName)) { 8239 iter.remove(); 8240 } 8241 } 8242 8243 // Take care of first install / last update times. 8244 if (currentTime != 0) { 8245 if (pkgSetting.firstInstallTime == 0) { 8246 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8247 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8248 pkgSetting.lastUpdateTime = currentTime; 8249 } 8250 } else if (pkgSetting.firstInstallTime == 0) { 8251 // We need *something*. Take time time stamp of the file. 8252 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8253 } else if ((parseFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8254 if (scanFileTime != pkgSetting.timeStamp) { 8255 // A package on the system image has changed; consider this 8256 // to be an update. 8257 pkgSetting.lastUpdateTime = scanFileTime; 8258 } 8259 } 8260 8261 // Add the package's KeySets to the global KeySetManagerService 8262 ksms.addScannedPackageLPw(pkg); 8263 8264 int N = pkg.providers.size(); 8265 StringBuilder r = null; 8266 int i; 8267 for (i=0; i<N; i++) { 8268 PackageParser.Provider p = pkg.providers.get(i); 8269 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8270 p.info.processName, pkg.applicationInfo.uid); 8271 mProviders.addProvider(p); 8272 p.syncable = p.info.isSyncable; 8273 if (p.info.authority != null) { 8274 String names[] = p.info.authority.split(";"); 8275 p.info.authority = null; 8276 for (int j = 0; j < names.length; j++) { 8277 if (j == 1 && p.syncable) { 8278 // We only want the first authority for a provider to possibly be 8279 // syncable, so if we already added this provider using a different 8280 // authority clear the syncable flag. We copy the provider before 8281 // changing it because the mProviders object contains a reference 8282 // to a provider that we don't want to change. 8283 // Only do this for the second authority since the resulting provider 8284 // object can be the same for all future authorities for this provider. 8285 p = new PackageParser.Provider(p); 8286 p.syncable = false; 8287 } 8288 if (!mProvidersByAuthority.containsKey(names[j])) { 8289 mProvidersByAuthority.put(names[j], p); 8290 if (p.info.authority == null) { 8291 p.info.authority = names[j]; 8292 } else { 8293 p.info.authority = p.info.authority + ";" + names[j]; 8294 } 8295 if (DEBUG_PACKAGE_SCANNING) { 8296 if ((parseFlags & PackageParser.PARSE_CHATTY) != 0) 8297 Log.d(TAG, "Registered content provider: " + names[j] 8298 + ", className = " + p.info.name + ", isSyncable = " 8299 + p.info.isSyncable); 8300 } 8301 } else { 8302 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8303 Slog.w(TAG, "Skipping provider name " + names[j] + 8304 " (in package " + pkg.applicationInfo.packageName + 8305 "): name already used by " 8306 + ((other != null && other.getComponentName() != null) 8307 ? other.getComponentName().getPackageName() : "?")); 8308 } 8309 } 8310 } 8311 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8312 if (r == null) { 8313 r = new StringBuilder(256); 8314 } else { 8315 r.append(' '); 8316 } 8317 r.append(p.info.name); 8318 } 8319 } 8320 if (r != null) { 8321 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8322 } 8323 8324 N = pkg.services.size(); 8325 r = null; 8326 for (i=0; i<N; i++) { 8327 PackageParser.Service s = pkg.services.get(i); 8328 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8329 s.info.processName, pkg.applicationInfo.uid); 8330 mServices.addService(s); 8331 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8332 if (r == null) { 8333 r = new StringBuilder(256); 8334 } else { 8335 r.append(' '); 8336 } 8337 r.append(s.info.name); 8338 } 8339 } 8340 if (r != null) { 8341 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8342 } 8343 8344 N = pkg.receivers.size(); 8345 r = null; 8346 for (i=0; i<N; i++) { 8347 PackageParser.Activity a = pkg.receivers.get(i); 8348 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8349 a.info.processName, pkg.applicationInfo.uid); 8350 mReceivers.addActivity(a, "receiver"); 8351 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8352 if (r == null) { 8353 r = new StringBuilder(256); 8354 } else { 8355 r.append(' '); 8356 } 8357 r.append(a.info.name); 8358 } 8359 } 8360 if (r != null) { 8361 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8362 } 8363 8364 N = pkg.activities.size(); 8365 r = null; 8366 for (i=0; i<N; i++) { 8367 PackageParser.Activity a = pkg.activities.get(i); 8368 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8369 a.info.processName, pkg.applicationInfo.uid); 8370 mActivities.addActivity(a, "activity"); 8371 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8372 if (r == null) { 8373 r = new StringBuilder(256); 8374 } else { 8375 r.append(' '); 8376 } 8377 r.append(a.info.name); 8378 } 8379 } 8380 if (r != null) { 8381 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8382 } 8383 8384 N = pkg.permissionGroups.size(); 8385 r = null; 8386 for (i=0; i<N; i++) { 8387 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8388 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8389 if (cur == null) { 8390 mPermissionGroups.put(pg.info.name, pg); 8391 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8392 if (r == null) { 8393 r = new StringBuilder(256); 8394 } else { 8395 r.append(' '); 8396 } 8397 r.append(pg.info.name); 8398 } 8399 } else { 8400 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8401 + pg.info.packageName + " ignored: original from " 8402 + cur.info.packageName); 8403 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8404 if (r == null) { 8405 r = new StringBuilder(256); 8406 } else { 8407 r.append(' '); 8408 } 8409 r.append("DUP:"); 8410 r.append(pg.info.name); 8411 } 8412 } 8413 } 8414 if (r != null) { 8415 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8416 } 8417 8418 N = pkg.permissions.size(); 8419 r = null; 8420 for (i=0; i<N; i++) { 8421 PackageParser.Permission p = pkg.permissions.get(i); 8422 8423 // Assume by default that we did not install this permission into the system. 8424 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8425 8426 // Now that permission groups have a special meaning, we ignore permission 8427 // groups for legacy apps to prevent unexpected behavior. In particular, 8428 // permissions for one app being granted to someone just becase they happen 8429 // to be in a group defined by another app (before this had no implications). 8430 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8431 p.group = mPermissionGroups.get(p.info.group); 8432 // Warn for a permission in an unknown group. 8433 if (p.info.group != null && p.group == null) { 8434 Slog.w(TAG, "Permission " + p.info.name + " from package " 8435 + p.info.packageName + " in an unknown group " + p.info.group); 8436 } 8437 } 8438 8439 ArrayMap<String, BasePermission> permissionMap = 8440 p.tree ? mSettings.mPermissionTrees 8441 : mSettings.mPermissions; 8442 BasePermission bp = permissionMap.get(p.info.name); 8443 8444 // Allow system apps to redefine non-system permissions 8445 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8446 final boolean currentOwnerIsSystem = (bp.perm != null 8447 && isSystemApp(bp.perm.owner)); 8448 if (isSystemApp(p.owner)) { 8449 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8450 // It's a built-in permission and no owner, take ownership now 8451 bp.packageSetting = pkgSetting; 8452 bp.perm = p; 8453 bp.uid = pkg.applicationInfo.uid; 8454 bp.sourcePackage = p.info.packageName; 8455 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8456 } else if (!currentOwnerIsSystem) { 8457 String msg = "New decl " + p.owner + " of permission " 8458 + p.info.name + " is system; overriding " + bp.sourcePackage; 8459 reportSettingsProblem(Log.WARN, msg); 8460 bp = null; 8461 } 8462 } 8463 } 8464 8465 if (bp == null) { 8466 bp = new BasePermission(p.info.name, p.info.packageName, 8467 BasePermission.TYPE_NORMAL); 8468 permissionMap.put(p.info.name, bp); 8469 } 8470 8471 if (bp.perm == null) { 8472 if (bp.sourcePackage == null 8473 || bp.sourcePackage.equals(p.info.packageName)) { 8474 BasePermission tree = findPermissionTreeLP(p.info.name); 8475 if (tree == null 8476 || tree.sourcePackage.equals(p.info.packageName)) { 8477 bp.packageSetting = pkgSetting; 8478 bp.perm = p; 8479 bp.uid = pkg.applicationInfo.uid; 8480 bp.sourcePackage = p.info.packageName; 8481 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8482 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8483 if (r == null) { 8484 r = new StringBuilder(256); 8485 } else { 8486 r.append(' '); 8487 } 8488 r.append(p.info.name); 8489 } 8490 } else { 8491 Slog.w(TAG, "Permission " + p.info.name + " from package " 8492 + p.info.packageName + " ignored: base tree " 8493 + tree.name + " is from package " 8494 + tree.sourcePackage); 8495 } 8496 } else { 8497 Slog.w(TAG, "Permission " + p.info.name + " from package " 8498 + p.info.packageName + " ignored: original from " 8499 + bp.sourcePackage); 8500 } 8501 } else if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8502 if (r == null) { 8503 r = new StringBuilder(256); 8504 } else { 8505 r.append(' '); 8506 } 8507 r.append("DUP:"); 8508 r.append(p.info.name); 8509 } 8510 if (bp.perm == p) { 8511 bp.protectionLevel = p.info.protectionLevel; 8512 } 8513 } 8514 8515 if (r != null) { 8516 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8517 } 8518 8519 N = pkg.instrumentation.size(); 8520 r = null; 8521 for (i=0; i<N; i++) { 8522 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8523 a.info.packageName = pkg.applicationInfo.packageName; 8524 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8525 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8526 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8527 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8528 a.info.dataDir = pkg.applicationInfo.dataDir; 8529 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8530 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8531 8532 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8533 // need other information about the application, like the ABI and what not ? 8534 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8535 mInstrumentation.put(a.getComponentName(), a); 8536 if ((parseFlags&PackageParser.PARSE_CHATTY) != 0) { 8537 if (r == null) { 8538 r = new StringBuilder(256); 8539 } else { 8540 r.append(' '); 8541 } 8542 r.append(a.info.name); 8543 } 8544 } 8545 if (r != null) { 8546 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8547 } 8548 8549 if (pkg.protectedBroadcasts != null) { 8550 N = pkg.protectedBroadcasts.size(); 8551 for (i=0; i<N; i++) { 8552 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8553 } 8554 } 8555 8556 pkgSetting.setTimeStamp(scanFileTime); 8557 8558 // Create idmap files for pairs of (packages, overlay packages). 8559 // Note: "android", ie framework-res.apk, is handled by native layers. 8560 if (pkg.mOverlayTarget != null) { 8561 // This is an overlay package. 8562 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8563 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8564 mOverlays.put(pkg.mOverlayTarget, 8565 new ArrayMap<String, PackageParser.Package>()); 8566 } 8567 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8568 map.put(pkg.packageName, pkg); 8569 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8570 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8571 createIdmapFailed = true; 8572 } 8573 } 8574 } else if (mOverlays.containsKey(pkg.packageName) && 8575 !pkg.packageName.equals("android")) { 8576 // This is a regular package, with one or more known overlay packages. 8577 createIdmapsForPackageLI(pkg); 8578 } 8579 } 8580 8581 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8582 8583 if (createIdmapFailed) { 8584 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8585 "scanPackageLI failed to createIdmap"); 8586 } 8587 return pkg; 8588 } 8589 8590 /** 8591 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8592 * is derived purely on the basis of the contents of {@code scanFile} and 8593 * {@code cpuAbiOverride}. 8594 * 8595 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8596 */ 8597 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8598 String cpuAbiOverride, boolean extractLibs) 8599 throws PackageManagerException { 8600 // TODO: We can probably be smarter about this stuff. For installed apps, 8601 // we can calculate this information at install time once and for all. For 8602 // system apps, we can probably assume that this information doesn't change 8603 // after the first boot scan. As things stand, we do lots of unnecessary work. 8604 8605 // Give ourselves some initial paths; we'll come back for another 8606 // pass once we've determined ABI below. 8607 setNativeLibraryPaths(pkg); 8608 8609 // We would never need to extract libs for forward-locked and external packages, 8610 // since the container service will do it for us. We shouldn't attempt to 8611 // extract libs from system app when it was not updated. 8612 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8613 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8614 extractLibs = false; 8615 } 8616 8617 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8618 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8619 8620 NativeLibraryHelper.Handle handle = null; 8621 try { 8622 handle = NativeLibraryHelper.Handle.create(pkg); 8623 // TODO(multiArch): This can be null for apps that didn't go through the 8624 // usual installation process. We can calculate it again, like we 8625 // do during install time. 8626 // 8627 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8628 // unnecessary. 8629 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8630 8631 // Null out the abis so that they can be recalculated. 8632 pkg.applicationInfo.primaryCpuAbi = null; 8633 pkg.applicationInfo.secondaryCpuAbi = null; 8634 if (isMultiArch(pkg.applicationInfo)) { 8635 // Warn if we've set an abiOverride for multi-lib packages.. 8636 // By definition, we need to copy both 32 and 64 bit libraries for 8637 // such packages. 8638 if (pkg.cpuAbiOverride != null 8639 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8640 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8641 } 8642 8643 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8644 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8645 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8646 if (extractLibs) { 8647 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8648 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8649 useIsaSpecificSubdirs); 8650 } else { 8651 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8652 } 8653 } 8654 8655 maybeThrowExceptionForMultiArchCopy( 8656 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8657 8658 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8659 if (extractLibs) { 8660 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8661 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8662 useIsaSpecificSubdirs); 8663 } else { 8664 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8665 } 8666 } 8667 8668 maybeThrowExceptionForMultiArchCopy( 8669 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8670 8671 if (abi64 >= 0) { 8672 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8673 } 8674 8675 if (abi32 >= 0) { 8676 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8677 if (abi64 >= 0) { 8678 if (pkg.use32bitAbi) { 8679 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8680 pkg.applicationInfo.primaryCpuAbi = abi; 8681 } else { 8682 pkg.applicationInfo.secondaryCpuAbi = abi; 8683 } 8684 } else { 8685 pkg.applicationInfo.primaryCpuAbi = abi; 8686 } 8687 } 8688 8689 } else { 8690 String[] abiList = (cpuAbiOverride != null) ? 8691 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8692 8693 // Enable gross and lame hacks for apps that are built with old 8694 // SDK tools. We must scan their APKs for renderscript bitcode and 8695 // not launch them if it's present. Don't bother checking on devices 8696 // that don't have 64 bit support. 8697 boolean needsRenderScriptOverride = false; 8698 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8699 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8700 abiList = Build.SUPPORTED_32_BIT_ABIS; 8701 needsRenderScriptOverride = true; 8702 } 8703 8704 final int copyRet; 8705 if (extractLibs) { 8706 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8707 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8708 } else { 8709 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8710 } 8711 8712 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8713 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8714 "Error unpackaging native libs for app, errorCode=" + copyRet); 8715 } 8716 8717 if (copyRet >= 0) { 8718 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8719 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8720 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8721 } else if (needsRenderScriptOverride) { 8722 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8723 } 8724 } 8725 } catch (IOException ioe) { 8726 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8727 } finally { 8728 IoUtils.closeQuietly(handle); 8729 } 8730 8731 // Now that we've calculated the ABIs and determined if it's an internal app, 8732 // we will go ahead and populate the nativeLibraryPath. 8733 setNativeLibraryPaths(pkg); 8734 } 8735 8736 /** 8737 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8738 * i.e, so that all packages can be run inside a single process if required. 8739 * 8740 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8741 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8742 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8743 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8744 * updating a package that belongs to a shared user. 8745 * 8746 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8747 * adds unnecessary complexity. 8748 */ 8749 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8750 PackageParser.Package scannedPackage, boolean bootComplete) { 8751 String requiredInstructionSet = null; 8752 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8753 requiredInstructionSet = VMRuntime.getInstructionSet( 8754 scannedPackage.applicationInfo.primaryCpuAbi); 8755 } 8756 8757 PackageSetting requirer = null; 8758 for (PackageSetting ps : packagesForUser) { 8759 // If packagesForUser contains scannedPackage, we skip it. This will happen 8760 // when scannedPackage is an update of an existing package. Without this check, 8761 // we will never be able to change the ABI of any package belonging to a shared 8762 // user, even if it's compatible with other packages. 8763 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8764 if (ps.primaryCpuAbiString == null) { 8765 continue; 8766 } 8767 8768 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8769 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8770 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8771 // this but there's not much we can do. 8772 String errorMessage = "Instruction set mismatch, " 8773 + ((requirer == null) ? "[caller]" : requirer) 8774 + " requires " + requiredInstructionSet + " whereas " + ps 8775 + " requires " + instructionSet; 8776 Slog.w(TAG, errorMessage); 8777 } 8778 8779 if (requiredInstructionSet == null) { 8780 requiredInstructionSet = instructionSet; 8781 requirer = ps; 8782 } 8783 } 8784 } 8785 8786 if (requiredInstructionSet != null) { 8787 String adjustedAbi; 8788 if (requirer != null) { 8789 // requirer != null implies that either scannedPackage was null or that scannedPackage 8790 // did not require an ABI, in which case we have to adjust scannedPackage to match 8791 // the ABI of the set (which is the same as requirer's ABI) 8792 adjustedAbi = requirer.primaryCpuAbiString; 8793 if (scannedPackage != null) { 8794 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8795 } 8796 } else { 8797 // requirer == null implies that we're updating all ABIs in the set to 8798 // match scannedPackage. 8799 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8800 } 8801 8802 for (PackageSetting ps : packagesForUser) { 8803 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8804 if (ps.primaryCpuAbiString != null) { 8805 continue; 8806 } 8807 8808 ps.primaryCpuAbiString = adjustedAbi; 8809 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8810 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8811 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8812 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8813 + " (requirer=" 8814 + (requirer == null ? "null" : requirer.pkg.packageName) 8815 + ", scannedPackage=" 8816 + (scannedPackage != null ? scannedPackage.packageName : "null") 8817 + ")"); 8818 try { 8819 mInstaller.rmdex(ps.codePathString, 8820 getDexCodeInstructionSet(getPreferredInstructionSet())); 8821 } catch (InstallerException ignored) { 8822 } 8823 } 8824 } 8825 } 8826 } 8827 } 8828 8829 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8830 synchronized (mPackages) { 8831 mResolverReplaced = true; 8832 // Set up information for custom user intent resolution activity. 8833 mResolveActivity.applicationInfo = pkg.applicationInfo; 8834 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8835 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8836 mResolveActivity.processName = pkg.applicationInfo.packageName; 8837 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8838 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8839 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8840 mResolveActivity.theme = 0; 8841 mResolveActivity.exported = true; 8842 mResolveActivity.enabled = true; 8843 mResolveInfo.activityInfo = mResolveActivity; 8844 mResolveInfo.priority = 0; 8845 mResolveInfo.preferredOrder = 0; 8846 mResolveInfo.match = 0; 8847 mResolveComponentName = mCustomResolverComponentName; 8848 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8849 mResolveComponentName); 8850 } 8851 } 8852 8853 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 8854 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 8855 8856 // Set up information for ephemeral installer activity 8857 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 8858 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 8859 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 8860 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 8861 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8862 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8863 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8864 mEphemeralInstallerActivity.theme = 0; 8865 mEphemeralInstallerActivity.exported = true; 8866 mEphemeralInstallerActivity.enabled = true; 8867 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 8868 mEphemeralInstallerInfo.priority = 0; 8869 mEphemeralInstallerInfo.preferredOrder = 0; 8870 mEphemeralInstallerInfo.match = 0; 8871 8872 if (DEBUG_EPHEMERAL) { 8873 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 8874 } 8875 } 8876 8877 private static String calculateBundledApkRoot(final String codePathString) { 8878 final File codePath = new File(codePathString); 8879 final File codeRoot; 8880 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 8881 codeRoot = Environment.getRootDirectory(); 8882 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 8883 codeRoot = Environment.getOemDirectory(); 8884 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 8885 codeRoot = Environment.getVendorDirectory(); 8886 } else { 8887 // Unrecognized code path; take its top real segment as the apk root: 8888 // e.g. /something/app/blah.apk => /something 8889 try { 8890 File f = codePath.getCanonicalFile(); 8891 File parent = f.getParentFile(); // non-null because codePath is a file 8892 File tmp; 8893 while ((tmp = parent.getParentFile()) != null) { 8894 f = parent; 8895 parent = tmp; 8896 } 8897 codeRoot = f; 8898 Slog.w(TAG, "Unrecognized code path " 8899 + codePath + " - using " + codeRoot); 8900 } catch (IOException e) { 8901 // Can't canonicalize the code path -- shenanigans? 8902 Slog.w(TAG, "Can't canonicalize code path " + codePath); 8903 return Environment.getRootDirectory().getPath(); 8904 } 8905 } 8906 return codeRoot.getPath(); 8907 } 8908 8909 /** 8910 * Derive and set the location of native libraries for the given package, 8911 * which varies depending on where and how the package was installed. 8912 */ 8913 private void setNativeLibraryPaths(PackageParser.Package pkg) { 8914 final ApplicationInfo info = pkg.applicationInfo; 8915 final String codePath = pkg.codePath; 8916 final File codeFile = new File(codePath); 8917 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 8918 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 8919 8920 info.nativeLibraryRootDir = null; 8921 info.nativeLibraryRootRequiresIsa = false; 8922 info.nativeLibraryDir = null; 8923 info.secondaryNativeLibraryDir = null; 8924 8925 if (isApkFile(codeFile)) { 8926 // Monolithic install 8927 if (bundledApp) { 8928 // If "/system/lib64/apkname" exists, assume that is the per-package 8929 // native library directory to use; otherwise use "/system/lib/apkname". 8930 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 8931 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 8932 getPrimaryInstructionSet(info)); 8933 8934 // This is a bundled system app so choose the path based on the ABI. 8935 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 8936 // is just the default path. 8937 final String apkName = deriveCodePathName(codePath); 8938 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 8939 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 8940 apkName).getAbsolutePath(); 8941 8942 if (info.secondaryCpuAbi != null) { 8943 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 8944 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 8945 secondaryLibDir, apkName).getAbsolutePath(); 8946 } 8947 } else if (asecApp) { 8948 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 8949 .getAbsolutePath(); 8950 } else { 8951 final String apkName = deriveCodePathName(codePath); 8952 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 8953 .getAbsolutePath(); 8954 } 8955 8956 info.nativeLibraryRootRequiresIsa = false; 8957 info.nativeLibraryDir = info.nativeLibraryRootDir; 8958 } else { 8959 // Cluster install 8960 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 8961 info.nativeLibraryRootRequiresIsa = true; 8962 8963 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 8964 getPrimaryInstructionSet(info)).getAbsolutePath(); 8965 8966 if (info.secondaryCpuAbi != null) { 8967 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 8968 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 8969 } 8970 } 8971 } 8972 8973 /** 8974 * Calculate the abis and roots for a bundled app. These can uniquely 8975 * be determined from the contents of the system partition, i.e whether 8976 * it contains 64 or 32 bit shared libraries etc. We do not validate any 8977 * of this information, and instead assume that the system was built 8978 * sensibly. 8979 */ 8980 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 8981 PackageSetting pkgSetting) { 8982 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 8983 8984 // If "/system/lib64/apkname" exists, assume that is the per-package 8985 // native library directory to use; otherwise use "/system/lib/apkname". 8986 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 8987 setBundledAppAbi(pkg, apkRoot, apkName); 8988 // pkgSetting might be null during rescan following uninstall of updates 8989 // to a bundled app, so accommodate that possibility. The settings in 8990 // that case will be established later from the parsed package. 8991 // 8992 // If the settings aren't null, sync them up with what we've just derived. 8993 // note that apkRoot isn't stored in the package settings. 8994 if (pkgSetting != null) { 8995 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8996 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8997 } 8998 } 8999 9000 /** 9001 * Deduces the ABI of a bundled app and sets the relevant fields on the 9002 * parsed pkg object. 9003 * 9004 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9005 * under which system libraries are installed. 9006 * @param apkName the name of the installed package. 9007 */ 9008 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9009 final File codeFile = new File(pkg.codePath); 9010 9011 final boolean has64BitLibs; 9012 final boolean has32BitLibs; 9013 if (isApkFile(codeFile)) { 9014 // Monolithic install 9015 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9016 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9017 } else { 9018 // Cluster install 9019 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9020 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9021 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9022 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9023 has64BitLibs = (new File(rootDir, isa)).exists(); 9024 } else { 9025 has64BitLibs = false; 9026 } 9027 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9028 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9029 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9030 has32BitLibs = (new File(rootDir, isa)).exists(); 9031 } else { 9032 has32BitLibs = false; 9033 } 9034 } 9035 9036 if (has64BitLibs && !has32BitLibs) { 9037 // The package has 64 bit libs, but not 32 bit libs. Its primary 9038 // ABI should be 64 bit. We can safely assume here that the bundled 9039 // native libraries correspond to the most preferred ABI in the list. 9040 9041 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9042 pkg.applicationInfo.secondaryCpuAbi = null; 9043 } else if (has32BitLibs && !has64BitLibs) { 9044 // The package has 32 bit libs but not 64 bit libs. Its primary 9045 // ABI should be 32 bit. 9046 9047 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9048 pkg.applicationInfo.secondaryCpuAbi = null; 9049 } else if (has32BitLibs && has64BitLibs) { 9050 // The application has both 64 and 32 bit bundled libraries. We check 9051 // here that the app declares multiArch support, and warn if it doesn't. 9052 // 9053 // We will be lenient here and record both ABIs. The primary will be the 9054 // ABI that's higher on the list, i.e, a device that's configured to prefer 9055 // 64 bit apps will see a 64 bit primary ABI, 9056 9057 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9058 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9059 } 9060 9061 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9062 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9063 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9064 } else { 9065 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9066 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9067 } 9068 } else { 9069 pkg.applicationInfo.primaryCpuAbi = null; 9070 pkg.applicationInfo.secondaryCpuAbi = null; 9071 } 9072 } 9073 9074 private void killApplication(String pkgName, int appId, String reason) { 9075 // Request the ActivityManager to kill the process(only for existing packages) 9076 // so that we do not end up in a confused state while the user is still using the older 9077 // version of the application while the new one gets installed. 9078 final long token = Binder.clearCallingIdentity(); 9079 try { 9080 IActivityManager am = ActivityManagerNative.getDefault(); 9081 if (am != null) { 9082 try { 9083 am.killApplicationWithAppId(pkgName, appId, reason); 9084 } catch (RemoteException e) { 9085 } 9086 } 9087 } finally { 9088 Binder.restoreCallingIdentity(token); 9089 } 9090 } 9091 9092 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9093 // Remove the parent package setting 9094 PackageSetting ps = (PackageSetting) pkg.mExtras; 9095 if (ps != null) { 9096 removePackageLI(ps, chatty); 9097 } 9098 // Remove the child package setting 9099 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9100 for (int i = 0; i < childCount; i++) { 9101 PackageParser.Package childPkg = pkg.childPackages.get(i); 9102 ps = (PackageSetting) childPkg.mExtras; 9103 if (ps != null) { 9104 removePackageLI(ps, chatty); 9105 } 9106 } 9107 } 9108 9109 void removePackageLI(PackageSetting ps, boolean chatty) { 9110 if (DEBUG_INSTALL) { 9111 if (chatty) 9112 Log.d(TAG, "Removing package " + ps.name); 9113 } 9114 9115 // writer 9116 synchronized (mPackages) { 9117 mPackages.remove(ps.name); 9118 final PackageParser.Package pkg = ps.pkg; 9119 if (pkg != null) { 9120 cleanPackageDataStructuresLILPw(pkg, chatty); 9121 } 9122 } 9123 } 9124 9125 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9126 if (DEBUG_INSTALL) { 9127 if (chatty) 9128 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9129 } 9130 9131 // writer 9132 synchronized (mPackages) { 9133 // Remove the parent package 9134 mPackages.remove(pkg.applicationInfo.packageName); 9135 cleanPackageDataStructuresLILPw(pkg, chatty); 9136 9137 // Remove the child packages 9138 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9139 for (int i = 0; i < childCount; i++) { 9140 PackageParser.Package childPkg = pkg.childPackages.get(i); 9141 mPackages.remove(childPkg.applicationInfo.packageName); 9142 cleanPackageDataStructuresLILPw(childPkg, chatty); 9143 } 9144 } 9145 } 9146 9147 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9148 int N = pkg.providers.size(); 9149 StringBuilder r = null; 9150 int i; 9151 for (i=0; i<N; i++) { 9152 PackageParser.Provider p = pkg.providers.get(i); 9153 mProviders.removeProvider(p); 9154 if (p.info.authority == null) { 9155 9156 /* There was another ContentProvider with this authority when 9157 * this app was installed so this authority is null, 9158 * Ignore it as we don't have to unregister the provider. 9159 */ 9160 continue; 9161 } 9162 String names[] = p.info.authority.split(";"); 9163 for (int j = 0; j < names.length; j++) { 9164 if (mProvidersByAuthority.get(names[j]) == p) { 9165 mProvidersByAuthority.remove(names[j]); 9166 if (DEBUG_REMOVE) { 9167 if (chatty) 9168 Log.d(TAG, "Unregistered content provider: " + names[j] 9169 + ", className = " + p.info.name + ", isSyncable = " 9170 + p.info.isSyncable); 9171 } 9172 } 9173 } 9174 if (DEBUG_REMOVE && chatty) { 9175 if (r == null) { 9176 r = new StringBuilder(256); 9177 } else { 9178 r.append(' '); 9179 } 9180 r.append(p.info.name); 9181 } 9182 } 9183 if (r != null) { 9184 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9185 } 9186 9187 N = pkg.services.size(); 9188 r = null; 9189 for (i=0; i<N; i++) { 9190 PackageParser.Service s = pkg.services.get(i); 9191 mServices.removeService(s); 9192 if (chatty) { 9193 if (r == null) { 9194 r = new StringBuilder(256); 9195 } else { 9196 r.append(' '); 9197 } 9198 r.append(s.info.name); 9199 } 9200 } 9201 if (r != null) { 9202 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9203 } 9204 9205 N = pkg.receivers.size(); 9206 r = null; 9207 for (i=0; i<N; i++) { 9208 PackageParser.Activity a = pkg.receivers.get(i); 9209 mReceivers.removeActivity(a, "receiver"); 9210 if (DEBUG_REMOVE && chatty) { 9211 if (r == null) { 9212 r = new StringBuilder(256); 9213 } else { 9214 r.append(' '); 9215 } 9216 r.append(a.info.name); 9217 } 9218 } 9219 if (r != null) { 9220 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9221 } 9222 9223 N = pkg.activities.size(); 9224 r = null; 9225 for (i=0; i<N; i++) { 9226 PackageParser.Activity a = pkg.activities.get(i); 9227 mActivities.removeActivity(a, "activity"); 9228 if (DEBUG_REMOVE && chatty) { 9229 if (r == null) { 9230 r = new StringBuilder(256); 9231 } else { 9232 r.append(' '); 9233 } 9234 r.append(a.info.name); 9235 } 9236 } 9237 if (r != null) { 9238 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9239 } 9240 9241 N = pkg.permissions.size(); 9242 r = null; 9243 for (i=0; i<N; i++) { 9244 PackageParser.Permission p = pkg.permissions.get(i); 9245 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9246 if (bp == null) { 9247 bp = mSettings.mPermissionTrees.get(p.info.name); 9248 } 9249 if (bp != null && bp.perm == p) { 9250 bp.perm = null; 9251 if (DEBUG_REMOVE && chatty) { 9252 if (r == null) { 9253 r = new StringBuilder(256); 9254 } else { 9255 r.append(' '); 9256 } 9257 r.append(p.info.name); 9258 } 9259 } 9260 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9261 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9262 if (appOpPkgs != null) { 9263 appOpPkgs.remove(pkg.packageName); 9264 } 9265 } 9266 } 9267 if (r != null) { 9268 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9269 } 9270 9271 N = pkg.requestedPermissions.size(); 9272 r = null; 9273 for (i=0; i<N; i++) { 9274 String perm = pkg.requestedPermissions.get(i); 9275 BasePermission bp = mSettings.mPermissions.get(perm); 9276 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9277 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9278 if (appOpPkgs != null) { 9279 appOpPkgs.remove(pkg.packageName); 9280 if (appOpPkgs.isEmpty()) { 9281 mAppOpPermissionPackages.remove(perm); 9282 } 9283 } 9284 } 9285 } 9286 if (r != null) { 9287 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9288 } 9289 9290 N = pkg.instrumentation.size(); 9291 r = null; 9292 for (i=0; i<N; i++) { 9293 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9294 mInstrumentation.remove(a.getComponentName()); 9295 if (DEBUG_REMOVE && chatty) { 9296 if (r == null) { 9297 r = new StringBuilder(256); 9298 } else { 9299 r.append(' '); 9300 } 9301 r.append(a.info.name); 9302 } 9303 } 9304 if (r != null) { 9305 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9306 } 9307 9308 r = null; 9309 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9310 // Only system apps can hold shared libraries. 9311 if (pkg.libraryNames != null) { 9312 for (i=0; i<pkg.libraryNames.size(); i++) { 9313 String name = pkg.libraryNames.get(i); 9314 SharedLibraryEntry cur = mSharedLibraries.get(name); 9315 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9316 mSharedLibraries.remove(name); 9317 if (DEBUG_REMOVE && chatty) { 9318 if (r == null) { 9319 r = new StringBuilder(256); 9320 } else { 9321 r.append(' '); 9322 } 9323 r.append(name); 9324 } 9325 } 9326 } 9327 } 9328 } 9329 if (r != null) { 9330 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9331 } 9332 } 9333 9334 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9335 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9336 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9337 return true; 9338 } 9339 } 9340 return false; 9341 } 9342 9343 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9344 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9345 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9346 9347 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9348 // Update the parent permissions 9349 updatePermissionsLPw(pkg.packageName, pkg, flags); 9350 // Update the child permissions 9351 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9352 for (int i = 0; i < childCount; i++) { 9353 PackageParser.Package childPkg = pkg.childPackages.get(i); 9354 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9355 } 9356 } 9357 9358 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9359 int flags) { 9360 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9361 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9362 } 9363 9364 private void updatePermissionsLPw(String changingPkg, 9365 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9366 // Make sure there are no dangling permission trees. 9367 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9368 while (it.hasNext()) { 9369 final BasePermission bp = it.next(); 9370 if (bp.packageSetting == null) { 9371 // We may not yet have parsed the package, so just see if 9372 // we still know about its settings. 9373 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9374 } 9375 if (bp.packageSetting == null) { 9376 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9377 + " from package " + bp.sourcePackage); 9378 it.remove(); 9379 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9380 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9381 Slog.i(TAG, "Removing old permission tree: " + bp.name 9382 + " from package " + bp.sourcePackage); 9383 flags |= UPDATE_PERMISSIONS_ALL; 9384 it.remove(); 9385 } 9386 } 9387 } 9388 9389 // Make sure all dynamic permissions have been assigned to a package, 9390 // and make sure there are no dangling permissions. 9391 it = mSettings.mPermissions.values().iterator(); 9392 while (it.hasNext()) { 9393 final BasePermission bp = it.next(); 9394 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9395 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9396 + bp.name + " pkg=" + bp.sourcePackage 9397 + " info=" + bp.pendingInfo); 9398 if (bp.packageSetting == null && bp.pendingInfo != null) { 9399 final BasePermission tree = findPermissionTreeLP(bp.name); 9400 if (tree != null && tree.perm != null) { 9401 bp.packageSetting = tree.packageSetting; 9402 bp.perm = new PackageParser.Permission(tree.perm.owner, 9403 new PermissionInfo(bp.pendingInfo)); 9404 bp.perm.info.packageName = tree.perm.info.packageName; 9405 bp.perm.info.name = bp.name; 9406 bp.uid = tree.uid; 9407 } 9408 } 9409 } 9410 if (bp.packageSetting == null) { 9411 // We may not yet have parsed the package, so just see if 9412 // we still know about its settings. 9413 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9414 } 9415 if (bp.packageSetting == null) { 9416 Slog.w(TAG, "Removing dangling permission: " + bp.name 9417 + " from package " + bp.sourcePackage); 9418 it.remove(); 9419 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9420 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9421 Slog.i(TAG, "Removing old permission: " + bp.name 9422 + " from package " + bp.sourcePackage); 9423 flags |= UPDATE_PERMISSIONS_ALL; 9424 it.remove(); 9425 } 9426 } 9427 } 9428 9429 // Now update the permissions for all packages, in particular 9430 // replace the granted permissions of the system packages. 9431 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9432 for (PackageParser.Package pkg : mPackages.values()) { 9433 if (pkg != pkgInfo) { 9434 // Only replace for packages on requested volume 9435 final String volumeUuid = getVolumeUuidForPackage(pkg); 9436 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9437 && Objects.equals(replaceVolumeUuid, volumeUuid); 9438 grantPermissionsLPw(pkg, replace, changingPkg); 9439 } 9440 } 9441 } 9442 9443 if (pkgInfo != null) { 9444 // Only replace for packages on requested volume 9445 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9446 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9447 && Objects.equals(replaceVolumeUuid, volumeUuid); 9448 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9449 } 9450 } 9451 9452 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9453 String packageOfInterest) { 9454 // IMPORTANT: There are two types of permissions: install and runtime. 9455 // Install time permissions are granted when the app is installed to 9456 // all device users and users added in the future. Runtime permissions 9457 // are granted at runtime explicitly to specific users. Normal and signature 9458 // protected permissions are install time permissions. Dangerous permissions 9459 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9460 // otherwise they are runtime permissions. This function does not manage 9461 // runtime permissions except for the case an app targeting Lollipop MR1 9462 // being upgraded to target a newer SDK, in which case dangerous permissions 9463 // are transformed from install time to runtime ones. 9464 9465 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9466 if (ps == null) { 9467 return; 9468 } 9469 9470 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9471 9472 PermissionsState permissionsState = ps.getPermissionsState(); 9473 PermissionsState origPermissions = permissionsState; 9474 9475 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9476 9477 boolean runtimePermissionsRevoked = false; 9478 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9479 9480 boolean changedInstallPermission = false; 9481 9482 if (replace) { 9483 ps.installPermissionsFixed = false; 9484 if (!ps.isSharedUser()) { 9485 origPermissions = new PermissionsState(permissionsState); 9486 permissionsState.reset(); 9487 } else { 9488 // We need to know only about runtime permission changes since the 9489 // calling code always writes the install permissions state but 9490 // the runtime ones are written only if changed. The only cases of 9491 // changed runtime permissions here are promotion of an install to 9492 // runtime and revocation of a runtime from a shared user. 9493 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9494 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9495 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9496 runtimePermissionsRevoked = true; 9497 } 9498 } 9499 } 9500 9501 permissionsState.setGlobalGids(mGlobalGids); 9502 9503 final int N = pkg.requestedPermissions.size(); 9504 for (int i=0; i<N; i++) { 9505 final String name = pkg.requestedPermissions.get(i); 9506 final BasePermission bp = mSettings.mPermissions.get(name); 9507 9508 if (DEBUG_INSTALL) { 9509 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9510 } 9511 9512 if (bp == null || bp.packageSetting == null) { 9513 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9514 Slog.w(TAG, "Unknown permission " + name 9515 + " in package " + pkg.packageName); 9516 } 9517 continue; 9518 } 9519 9520 final String perm = bp.name; 9521 boolean allowedSig = false; 9522 int grant = GRANT_DENIED; 9523 9524 // Keep track of app op permissions. 9525 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9526 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9527 if (pkgs == null) { 9528 pkgs = new ArraySet<>(); 9529 mAppOpPermissionPackages.put(bp.name, pkgs); 9530 } 9531 pkgs.add(pkg.packageName); 9532 } 9533 9534 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9535 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9536 >= Build.VERSION_CODES.M; 9537 switch (level) { 9538 case PermissionInfo.PROTECTION_NORMAL: { 9539 // For all apps normal permissions are install time ones. 9540 grant = GRANT_INSTALL; 9541 } break; 9542 9543 case PermissionInfo.PROTECTION_DANGEROUS: { 9544 // If a permission review is required for legacy apps we represent 9545 // their permissions as always granted runtime ones since we need 9546 // to keep the review required permission flag per user while an 9547 // install permission's state is shared across all users. 9548 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9549 // For legacy apps dangerous permissions are install time ones. 9550 grant = GRANT_INSTALL; 9551 } else if (origPermissions.hasInstallPermission(bp.name)) { 9552 // For legacy apps that became modern, install becomes runtime. 9553 grant = GRANT_UPGRADE; 9554 } else if (mPromoteSystemApps 9555 && isSystemApp(ps) 9556 && mExistingSystemPackages.contains(ps.name)) { 9557 // For legacy system apps, install becomes runtime. 9558 // We cannot check hasInstallPermission() for system apps since those 9559 // permissions were granted implicitly and not persisted pre-M. 9560 grant = GRANT_UPGRADE; 9561 } else { 9562 // For modern apps keep runtime permissions unchanged. 9563 grant = GRANT_RUNTIME; 9564 } 9565 } break; 9566 9567 case PermissionInfo.PROTECTION_SIGNATURE: { 9568 // For all apps signature permissions are install time ones. 9569 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9570 if (allowedSig) { 9571 grant = GRANT_INSTALL; 9572 } 9573 } break; 9574 } 9575 9576 if (DEBUG_INSTALL) { 9577 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9578 } 9579 9580 if (grant != GRANT_DENIED) { 9581 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9582 // If this is an existing, non-system package, then 9583 // we can't add any new permissions to it. 9584 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9585 // Except... if this is a permission that was added 9586 // to the platform (note: need to only do this when 9587 // updating the platform). 9588 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9589 grant = GRANT_DENIED; 9590 } 9591 } 9592 } 9593 9594 switch (grant) { 9595 case GRANT_INSTALL: { 9596 // Revoke this as runtime permission to handle the case of 9597 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9598 for (int userId : UserManagerService.getInstance().getUserIds()) { 9599 if (origPermissions.getRuntimePermissionState( 9600 bp.name, userId) != null) { 9601 // Revoke the runtime permission and clear the flags. 9602 origPermissions.revokeRuntimePermission(bp, userId); 9603 origPermissions.updatePermissionFlags(bp, userId, 9604 PackageManager.MASK_PERMISSION_FLAGS, 0); 9605 // If we revoked a permission permission, we have to write. 9606 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9607 changedRuntimePermissionUserIds, userId); 9608 } 9609 } 9610 // Grant an install permission. 9611 if (permissionsState.grantInstallPermission(bp) != 9612 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9613 changedInstallPermission = true; 9614 } 9615 } break; 9616 9617 case GRANT_RUNTIME: { 9618 // Grant previously granted runtime permissions. 9619 for (int userId : UserManagerService.getInstance().getUserIds()) { 9620 PermissionState permissionState = origPermissions 9621 .getRuntimePermissionState(bp.name, userId); 9622 int flags = permissionState != null 9623 ? permissionState.getFlags() : 0; 9624 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9625 if (permissionsState.grantRuntimePermission(bp, userId) == 9626 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9627 // If we cannot put the permission as it was, we have to write. 9628 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9629 changedRuntimePermissionUserIds, userId); 9630 } 9631 // If the app supports runtime permissions no need for a review. 9632 if (Build.PERMISSIONS_REVIEW_REQUIRED 9633 && appSupportsRuntimePermissions 9634 && (flags & PackageManager 9635 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9636 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9637 // Since we changed the flags, we have to write. 9638 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9639 changedRuntimePermissionUserIds, userId); 9640 } 9641 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9642 && !appSupportsRuntimePermissions) { 9643 // For legacy apps that need a permission review, every new 9644 // runtime permission is granted but it is pending a review. 9645 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9646 permissionsState.grantRuntimePermission(bp, userId); 9647 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9648 // We changed the permission and flags, hence have to write. 9649 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9650 changedRuntimePermissionUserIds, userId); 9651 } 9652 } 9653 // Propagate the permission flags. 9654 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9655 } 9656 } break; 9657 9658 case GRANT_UPGRADE: { 9659 // Grant runtime permissions for a previously held install permission. 9660 PermissionState permissionState = origPermissions 9661 .getInstallPermissionState(bp.name); 9662 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9663 9664 if (origPermissions.revokeInstallPermission(bp) 9665 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9666 // We will be transferring the permission flags, so clear them. 9667 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9668 PackageManager.MASK_PERMISSION_FLAGS, 0); 9669 changedInstallPermission = true; 9670 } 9671 9672 // If the permission is not to be promoted to runtime we ignore it and 9673 // also its other flags as they are not applicable to install permissions. 9674 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9675 for (int userId : currentUserIds) { 9676 if (permissionsState.grantRuntimePermission(bp, userId) != 9677 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9678 // Transfer the permission flags. 9679 permissionsState.updatePermissionFlags(bp, userId, 9680 flags, flags); 9681 // If we granted the permission, we have to write. 9682 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9683 changedRuntimePermissionUserIds, userId); 9684 } 9685 } 9686 } 9687 } break; 9688 9689 default: { 9690 if (packageOfInterest == null 9691 || packageOfInterest.equals(pkg.packageName)) { 9692 Slog.w(TAG, "Not granting permission " + perm 9693 + " to package " + pkg.packageName 9694 + " because it was previously installed without"); 9695 } 9696 } break; 9697 } 9698 } else { 9699 if (permissionsState.revokeInstallPermission(bp) != 9700 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9701 // Also drop the permission flags. 9702 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9703 PackageManager.MASK_PERMISSION_FLAGS, 0); 9704 changedInstallPermission = true; 9705 Slog.i(TAG, "Un-granting permission " + perm 9706 + " from package " + pkg.packageName 9707 + " (protectionLevel=" + bp.protectionLevel 9708 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9709 + ")"); 9710 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9711 // Don't print warning for app op permissions, since it is fine for them 9712 // not to be granted, there is a UI for the user to decide. 9713 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9714 Slog.w(TAG, "Not granting permission " + perm 9715 + " to package " + pkg.packageName 9716 + " (protectionLevel=" + bp.protectionLevel 9717 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9718 + ")"); 9719 } 9720 } 9721 } 9722 } 9723 9724 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9725 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9726 // This is the first that we have heard about this package, so the 9727 // permissions we have now selected are fixed until explicitly 9728 // changed. 9729 ps.installPermissionsFixed = true; 9730 } 9731 9732 // Persist the runtime permissions state for users with changes. If permissions 9733 // were revoked because no app in the shared user declares them we have to 9734 // write synchronously to avoid losing runtime permissions state. 9735 for (int userId : changedRuntimePermissionUserIds) { 9736 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9737 } 9738 9739 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9740 } 9741 9742 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9743 boolean allowed = false; 9744 final int NP = PackageParser.NEW_PERMISSIONS.length; 9745 for (int ip=0; ip<NP; ip++) { 9746 final PackageParser.NewPermissionInfo npi 9747 = PackageParser.NEW_PERMISSIONS[ip]; 9748 if (npi.name.equals(perm) 9749 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9750 allowed = true; 9751 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9752 + pkg.packageName); 9753 break; 9754 } 9755 } 9756 return allowed; 9757 } 9758 9759 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9760 BasePermission bp, PermissionsState origPermissions) { 9761 boolean allowed; 9762 allowed = (compareSignatures( 9763 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9764 == PackageManager.SIGNATURE_MATCH) 9765 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9766 == PackageManager.SIGNATURE_MATCH); 9767 if (!allowed && (bp.protectionLevel 9768 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9769 if (isSystemApp(pkg)) { 9770 // For updated system applications, a system permission 9771 // is granted only if it had been defined by the original application. 9772 if (pkg.isUpdatedSystemApp()) { 9773 final PackageSetting sysPs = mSettings 9774 .getDisabledSystemPkgLPr(pkg.packageName); 9775 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9776 // If the original was granted this permission, we take 9777 // that grant decision as read and propagate it to the 9778 // update. 9779 if (sysPs.isPrivileged()) { 9780 allowed = true; 9781 } 9782 } else { 9783 // The system apk may have been updated with an older 9784 // version of the one on the data partition, but which 9785 // granted a new system permission that it didn't have 9786 // before. In this case we do want to allow the app to 9787 // now get the new permission if the ancestral apk is 9788 // privileged to get it. 9789 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9790 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9791 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9792 allowed = true; 9793 break; 9794 } 9795 } 9796 } 9797 // Also if a privileged parent package on the system image or any of 9798 // its children requested a privileged permission, the updated child 9799 // packages can also get the permission. 9800 if (pkg.parentPackage != null) { 9801 final PackageSetting disabledSysParentPs = mSettings 9802 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9803 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9804 && disabledSysParentPs.isPrivileged()) { 9805 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9806 allowed = true; 9807 } else if (disabledSysParentPs.pkg.childPackages != null) { 9808 final int count = disabledSysParentPs.pkg.childPackages.size(); 9809 for (int i = 0; i < count; i++) { 9810 PackageParser.Package disabledSysChildPkg = 9811 disabledSysParentPs.pkg.childPackages.get(i); 9812 if (isPackageRequestingPermission(disabledSysChildPkg, 9813 perm)) { 9814 allowed = true; 9815 break; 9816 } 9817 } 9818 } 9819 } 9820 } 9821 } 9822 } else { 9823 allowed = isPrivilegedApp(pkg); 9824 } 9825 } 9826 } 9827 if (!allowed) { 9828 if (!allowed && (bp.protectionLevel 9829 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9830 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9831 // If this was a previously normal/dangerous permission that got moved 9832 // to a system permission as part of the runtime permission redesign, then 9833 // we still want to blindly grant it to old apps. 9834 allowed = true; 9835 } 9836 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9837 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9838 // If this permission is to be granted to the system installer and 9839 // this app is an installer, then it gets the permission. 9840 allowed = true; 9841 } 9842 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9843 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9844 // If this permission is to be granted to the system verifier and 9845 // this app is a verifier, then it gets the permission. 9846 allowed = true; 9847 } 9848 if (!allowed && (bp.protectionLevel 9849 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 9850 && isSystemApp(pkg)) { 9851 // Any pre-installed system app is allowed to get this permission. 9852 allowed = true; 9853 } 9854 if (!allowed && (bp.protectionLevel 9855 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 9856 // For development permissions, a development permission 9857 // is granted only if it was already granted. 9858 allowed = origPermissions.hasInstallPermission(perm); 9859 } 9860 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 9861 && pkg.packageName.equals(mSetupWizardPackage)) { 9862 // If this permission is to be granted to the system setup wizard and 9863 // this app is a setup wizard, then it gets the permission. 9864 allowed = true; 9865 } 9866 } 9867 return allowed; 9868 } 9869 9870 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 9871 final int permCount = pkg.requestedPermissions.size(); 9872 for (int j = 0; j < permCount; j++) { 9873 String requestedPermission = pkg.requestedPermissions.get(j); 9874 if (permission.equals(requestedPermission)) { 9875 return true; 9876 } 9877 } 9878 return false; 9879 } 9880 9881 final class ActivityIntentResolver 9882 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 9883 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 9884 boolean defaultOnly, int userId) { 9885 if (!sUserManager.exists(userId)) return null; 9886 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 9887 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 9888 } 9889 9890 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 9891 int userId) { 9892 if (!sUserManager.exists(userId)) return null; 9893 mFlags = flags; 9894 return super.queryIntent(intent, resolvedType, 9895 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 9896 } 9897 9898 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 9899 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 9900 if (!sUserManager.exists(userId)) return null; 9901 if (packageActivities == null) { 9902 return null; 9903 } 9904 mFlags = flags; 9905 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 9906 final int N = packageActivities.size(); 9907 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 9908 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 9909 9910 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 9911 for (int i = 0; i < N; ++i) { 9912 intentFilters = packageActivities.get(i).intents; 9913 if (intentFilters != null && intentFilters.size() > 0) { 9914 PackageParser.ActivityIntentInfo[] array = 9915 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 9916 intentFilters.toArray(array); 9917 listCut.add(array); 9918 } 9919 } 9920 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 9921 } 9922 9923 /** 9924 * Finds a privileged activity that matches the specified activity names. 9925 */ 9926 private PackageParser.Activity findMatchingActivity( 9927 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 9928 for (PackageParser.Activity sysActivity : activityList) { 9929 if (sysActivity.info.name.equals(activityInfo.name)) { 9930 return sysActivity; 9931 } 9932 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 9933 return sysActivity; 9934 } 9935 if (sysActivity.info.targetActivity != null) { 9936 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 9937 return sysActivity; 9938 } 9939 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 9940 return sysActivity; 9941 } 9942 } 9943 } 9944 return null; 9945 } 9946 9947 public class IterGenerator<E> { 9948 public Iterator<E> generate(ActivityIntentInfo info) { 9949 return null; 9950 } 9951 } 9952 9953 public class ActionIterGenerator extends IterGenerator<String> { 9954 @Override 9955 public Iterator<String> generate(ActivityIntentInfo info) { 9956 return info.actionsIterator(); 9957 } 9958 } 9959 9960 public class CategoriesIterGenerator extends IterGenerator<String> { 9961 @Override 9962 public Iterator<String> generate(ActivityIntentInfo info) { 9963 return info.categoriesIterator(); 9964 } 9965 } 9966 9967 public class SchemesIterGenerator extends IterGenerator<String> { 9968 @Override 9969 public Iterator<String> generate(ActivityIntentInfo info) { 9970 return info.schemesIterator(); 9971 } 9972 } 9973 9974 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 9975 @Override 9976 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 9977 return info.authoritiesIterator(); 9978 } 9979 } 9980 9981 /** 9982 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 9983 * MODIFIED. Do not pass in a list that should not be changed. 9984 */ 9985 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 9986 IterGenerator<T> generator, Iterator<T> searchIterator) { 9987 // loop through the set of actions; every one must be found in the intent filter 9988 while (searchIterator.hasNext()) { 9989 // we must have at least one filter in the list to consider a match 9990 if (intentList.size() == 0) { 9991 break; 9992 } 9993 9994 final T searchAction = searchIterator.next(); 9995 9996 // loop through the set of intent filters 9997 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 9998 while (intentIter.hasNext()) { 9999 final ActivityIntentInfo intentInfo = intentIter.next(); 10000 boolean selectionFound = false; 10001 10002 // loop through the intent filter's selection criteria; at least one 10003 // of them must match the searched criteria 10004 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10005 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10006 final T intentSelection = intentSelectionIter.next(); 10007 if (intentSelection != null && intentSelection.equals(searchAction)) { 10008 selectionFound = true; 10009 break; 10010 } 10011 } 10012 10013 // the selection criteria wasn't found in this filter's set; this filter 10014 // is not a potential match 10015 if (!selectionFound) { 10016 intentIter.remove(); 10017 } 10018 } 10019 } 10020 } 10021 10022 private boolean isProtectedAction(ActivityIntentInfo filter) { 10023 final Iterator<String> actionsIter = filter.actionsIterator(); 10024 while (actionsIter != null && actionsIter.hasNext()) { 10025 final String filterAction = actionsIter.next(); 10026 if (PROTECTED_ACTIONS.contains(filterAction)) { 10027 return true; 10028 } 10029 } 10030 return false; 10031 } 10032 10033 /** 10034 * Adjusts the priority of the given intent filter according to policy. 10035 * <p> 10036 * <ul> 10037 * <li>The priority for non privileged applications is capped to '0'</li> 10038 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10039 * <li>The priority for unbundled updates to privileged applications is capped to the 10040 * priority defined on the system partition</li> 10041 * </ul> 10042 * <p> 10043 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10044 * allowed to obtain any priority on any action. 10045 */ 10046 private void adjustPriority( 10047 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10048 // nothing to do; priority is fine as-is 10049 if (intent.getPriority() <= 0) { 10050 return; 10051 } 10052 10053 final ActivityInfo activityInfo = intent.activity.info; 10054 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10055 10056 final boolean privilegedApp = 10057 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10058 if (!privilegedApp) { 10059 // non-privileged applications can never define a priority >0 10060 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10061 + " package: " + applicationInfo.packageName 10062 + " activity: " + intent.activity.className 10063 + " origPrio: " + intent.getPriority()); 10064 intent.setPriority(0); 10065 return; 10066 } 10067 10068 if (systemActivities == null) { 10069 // the system package is not disabled; we're parsing the system partition 10070 if (isProtectedAction(intent)) { 10071 if (mDeferProtectedFilters) { 10072 // We can't deal with these just yet. No component should ever obtain a 10073 // >0 priority for a protected actions, with ONE exception -- the setup 10074 // wizard. The setup wizard, however, cannot be known until we're able to 10075 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10076 // until all intent filters have been processed. Chicken, meet egg. 10077 // Let the filter temporarily have a high priority and rectify the 10078 // priorities after all system packages have been scanned. 10079 mProtectedFilters.add(intent); 10080 if (DEBUG_FILTERS) { 10081 Slog.i(TAG, "Protected action; save for later;" 10082 + " package: " + applicationInfo.packageName 10083 + " activity: " + intent.activity.className 10084 + " origPrio: " + intent.getPriority()); 10085 } 10086 return; 10087 } else { 10088 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10089 Slog.i(TAG, "No setup wizard;" 10090 + " All protected intents capped to priority 0"); 10091 } 10092 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10093 if (DEBUG_FILTERS) { 10094 Slog.i(TAG, "Found setup wizard;" 10095 + " allow priority " + intent.getPriority() + ";" 10096 + " package: " + intent.activity.info.packageName 10097 + " activity: " + intent.activity.className 10098 + " priority: " + intent.getPriority()); 10099 } 10100 // setup wizard gets whatever it wants 10101 return; 10102 } 10103 Slog.w(TAG, "Protected action; cap priority to 0;" 10104 + " package: " + intent.activity.info.packageName 10105 + " activity: " + intent.activity.className 10106 + " origPrio: " + intent.getPriority()); 10107 intent.setPriority(0); 10108 return; 10109 } 10110 } 10111 // privileged apps on the system image get whatever priority they request 10112 return; 10113 } 10114 10115 // privileged app unbundled update ... try to find the same activity 10116 final PackageParser.Activity foundActivity = 10117 findMatchingActivity(systemActivities, activityInfo); 10118 if (foundActivity == null) { 10119 // this is a new activity; it cannot obtain >0 priority 10120 if (DEBUG_FILTERS) { 10121 Slog.i(TAG, "New activity; cap priority to 0;" 10122 + " package: " + applicationInfo.packageName 10123 + " activity: " + intent.activity.className 10124 + " origPrio: " + intent.getPriority()); 10125 } 10126 intent.setPriority(0); 10127 return; 10128 } 10129 10130 // found activity, now check for filter equivalence 10131 10132 // a shallow copy is enough; we modify the list, not its contents 10133 final List<ActivityIntentInfo> intentListCopy = 10134 new ArrayList<>(foundActivity.intents); 10135 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10136 10137 // find matching action subsets 10138 final Iterator<String> actionsIterator = intent.actionsIterator(); 10139 if (actionsIterator != null) { 10140 getIntentListSubset( 10141 intentListCopy, new ActionIterGenerator(), actionsIterator); 10142 if (intentListCopy.size() == 0) { 10143 // no more intents to match; we're not equivalent 10144 if (DEBUG_FILTERS) { 10145 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10146 + " package: " + applicationInfo.packageName 10147 + " activity: " + intent.activity.className 10148 + " origPrio: " + intent.getPriority()); 10149 } 10150 intent.setPriority(0); 10151 return; 10152 } 10153 } 10154 10155 // find matching category subsets 10156 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10157 if (categoriesIterator != null) { 10158 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10159 categoriesIterator); 10160 if (intentListCopy.size() == 0) { 10161 // no more intents to match; we're not equivalent 10162 if (DEBUG_FILTERS) { 10163 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10164 + " package: " + applicationInfo.packageName 10165 + " activity: " + intent.activity.className 10166 + " origPrio: " + intent.getPriority()); 10167 } 10168 intent.setPriority(0); 10169 return; 10170 } 10171 } 10172 10173 // find matching schemes subsets 10174 final Iterator<String> schemesIterator = intent.schemesIterator(); 10175 if (schemesIterator != null) { 10176 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10177 schemesIterator); 10178 if (intentListCopy.size() == 0) { 10179 // no more intents to match; we're not equivalent 10180 if (DEBUG_FILTERS) { 10181 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10182 + " package: " + applicationInfo.packageName 10183 + " activity: " + intent.activity.className 10184 + " origPrio: " + intent.getPriority()); 10185 } 10186 intent.setPriority(0); 10187 return; 10188 } 10189 } 10190 10191 // find matching authorities subsets 10192 final Iterator<IntentFilter.AuthorityEntry> 10193 authoritiesIterator = intent.authoritiesIterator(); 10194 if (authoritiesIterator != null) { 10195 getIntentListSubset(intentListCopy, 10196 new AuthoritiesIterGenerator(), 10197 authoritiesIterator); 10198 if (intentListCopy.size() == 0) { 10199 // no more intents to match; we're not equivalent 10200 if (DEBUG_FILTERS) { 10201 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10202 + " package: " + applicationInfo.packageName 10203 + " activity: " + intent.activity.className 10204 + " origPrio: " + intent.getPriority()); 10205 } 10206 intent.setPriority(0); 10207 return; 10208 } 10209 } 10210 10211 // we found matching filter(s); app gets the max priority of all intents 10212 int cappedPriority = 0; 10213 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10214 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10215 } 10216 if (intent.getPriority() > cappedPriority) { 10217 if (DEBUG_FILTERS) { 10218 Slog.i(TAG, "Found matching filter(s);" 10219 + " cap priority to " + cappedPriority + ";" 10220 + " package: " + applicationInfo.packageName 10221 + " activity: " + intent.activity.className 10222 + " origPrio: " + intent.getPriority()); 10223 } 10224 intent.setPriority(cappedPriority); 10225 return; 10226 } 10227 // all this for nothing; the requested priority was <= what was on the system 10228 } 10229 10230 public final void addActivity(PackageParser.Activity a, String type) { 10231 mActivities.put(a.getComponentName(), a); 10232 if (DEBUG_SHOW_INFO) 10233 Log.v( 10234 TAG, " " + type + " " + 10235 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10236 if (DEBUG_SHOW_INFO) 10237 Log.v(TAG, " Class=" + a.info.name); 10238 final int NI = a.intents.size(); 10239 for (int j=0; j<NI; j++) { 10240 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10241 if ("activity".equals(type)) { 10242 final PackageSetting ps = 10243 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10244 final List<PackageParser.Activity> systemActivities = 10245 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10246 adjustPriority(systemActivities, intent); 10247 } 10248 if (DEBUG_SHOW_INFO) { 10249 Log.v(TAG, " IntentFilter:"); 10250 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10251 } 10252 if (!intent.debugCheck()) { 10253 Log.w(TAG, "==> For Activity " + a.info.name); 10254 } 10255 addFilter(intent); 10256 } 10257 } 10258 10259 public final void removeActivity(PackageParser.Activity a, String type) { 10260 mActivities.remove(a.getComponentName()); 10261 if (DEBUG_SHOW_INFO) { 10262 Log.v(TAG, " " + type + " " 10263 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10264 : a.info.name) + ":"); 10265 Log.v(TAG, " Class=" + a.info.name); 10266 } 10267 final int NI = a.intents.size(); 10268 for (int j=0; j<NI; j++) { 10269 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10270 if (DEBUG_SHOW_INFO) { 10271 Log.v(TAG, " IntentFilter:"); 10272 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10273 } 10274 removeFilter(intent); 10275 } 10276 } 10277 10278 @Override 10279 protected boolean allowFilterResult( 10280 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10281 ActivityInfo filterAi = filter.activity.info; 10282 for (int i=dest.size()-1; i>=0; i--) { 10283 ActivityInfo destAi = dest.get(i).activityInfo; 10284 if (destAi.name == filterAi.name 10285 && destAi.packageName == filterAi.packageName) { 10286 return false; 10287 } 10288 } 10289 return true; 10290 } 10291 10292 @Override 10293 protected ActivityIntentInfo[] newArray(int size) { 10294 return new ActivityIntentInfo[size]; 10295 } 10296 10297 @Override 10298 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10299 if (!sUserManager.exists(userId)) return true; 10300 PackageParser.Package p = filter.activity.owner; 10301 if (p != null) { 10302 PackageSetting ps = (PackageSetting)p.mExtras; 10303 if (ps != null) { 10304 // System apps are never considered stopped for purposes of 10305 // filtering, because there may be no way for the user to 10306 // actually re-launch them. 10307 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10308 && ps.getStopped(userId); 10309 } 10310 } 10311 return false; 10312 } 10313 10314 @Override 10315 protected boolean isPackageForFilter(String packageName, 10316 PackageParser.ActivityIntentInfo info) { 10317 return packageName.equals(info.activity.owner.packageName); 10318 } 10319 10320 @Override 10321 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10322 int match, int userId) { 10323 if (!sUserManager.exists(userId)) return null; 10324 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10325 return null; 10326 } 10327 final PackageParser.Activity activity = info.activity; 10328 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10329 if (ps == null) { 10330 return null; 10331 } 10332 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10333 ps.readUserState(userId), userId); 10334 if (ai == null) { 10335 return null; 10336 } 10337 final ResolveInfo res = new ResolveInfo(); 10338 res.activityInfo = ai; 10339 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10340 res.filter = info; 10341 } 10342 if (info != null) { 10343 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10344 } 10345 res.priority = info.getPriority(); 10346 res.preferredOrder = activity.owner.mPreferredOrder; 10347 //System.out.println("Result: " + res.activityInfo.className + 10348 // " = " + res.priority); 10349 res.match = match; 10350 res.isDefault = info.hasDefault; 10351 res.labelRes = info.labelRes; 10352 res.nonLocalizedLabel = info.nonLocalizedLabel; 10353 if (userNeedsBadging(userId)) { 10354 res.noResourceId = true; 10355 } else { 10356 res.icon = info.icon; 10357 } 10358 res.iconResourceId = info.icon; 10359 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10360 return res; 10361 } 10362 10363 @Override 10364 protected void sortResults(List<ResolveInfo> results) { 10365 Collections.sort(results, mResolvePrioritySorter); 10366 } 10367 10368 @Override 10369 protected void dumpFilter(PrintWriter out, String prefix, 10370 PackageParser.ActivityIntentInfo filter) { 10371 out.print(prefix); out.print( 10372 Integer.toHexString(System.identityHashCode(filter.activity))); 10373 out.print(' '); 10374 filter.activity.printComponentShortName(out); 10375 out.print(" filter "); 10376 out.println(Integer.toHexString(System.identityHashCode(filter))); 10377 } 10378 10379 @Override 10380 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10381 return filter.activity; 10382 } 10383 10384 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10385 PackageParser.Activity activity = (PackageParser.Activity)label; 10386 out.print(prefix); out.print( 10387 Integer.toHexString(System.identityHashCode(activity))); 10388 out.print(' '); 10389 activity.printComponentShortName(out); 10390 if (count > 1) { 10391 out.print(" ("); out.print(count); out.print(" filters)"); 10392 } 10393 out.println(); 10394 } 10395 10396 // Keys are String (activity class name), values are Activity. 10397 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10398 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10399 private int mFlags; 10400 } 10401 10402 private final class ServiceIntentResolver 10403 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10404 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10405 boolean defaultOnly, int userId) { 10406 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10407 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10408 } 10409 10410 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10411 int userId) { 10412 if (!sUserManager.exists(userId)) return null; 10413 mFlags = flags; 10414 return super.queryIntent(intent, resolvedType, 10415 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10416 } 10417 10418 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10419 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10420 if (!sUserManager.exists(userId)) return null; 10421 if (packageServices == null) { 10422 return null; 10423 } 10424 mFlags = flags; 10425 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10426 final int N = packageServices.size(); 10427 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10428 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10429 10430 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10431 for (int i = 0; i < N; ++i) { 10432 intentFilters = packageServices.get(i).intents; 10433 if (intentFilters != null && intentFilters.size() > 0) { 10434 PackageParser.ServiceIntentInfo[] array = 10435 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10436 intentFilters.toArray(array); 10437 listCut.add(array); 10438 } 10439 } 10440 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10441 } 10442 10443 public final void addService(PackageParser.Service s) { 10444 mServices.put(s.getComponentName(), s); 10445 if (DEBUG_SHOW_INFO) { 10446 Log.v(TAG, " " 10447 + (s.info.nonLocalizedLabel != null 10448 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10449 Log.v(TAG, " Class=" + s.info.name); 10450 } 10451 final int NI = s.intents.size(); 10452 int j; 10453 for (j=0; j<NI; j++) { 10454 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10455 if (DEBUG_SHOW_INFO) { 10456 Log.v(TAG, " IntentFilter:"); 10457 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10458 } 10459 if (!intent.debugCheck()) { 10460 Log.w(TAG, "==> For Service " + s.info.name); 10461 } 10462 addFilter(intent); 10463 } 10464 } 10465 10466 public final void removeService(PackageParser.Service s) { 10467 mServices.remove(s.getComponentName()); 10468 if (DEBUG_SHOW_INFO) { 10469 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10470 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10471 Log.v(TAG, " Class=" + s.info.name); 10472 } 10473 final int NI = s.intents.size(); 10474 int j; 10475 for (j=0; j<NI; j++) { 10476 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10477 if (DEBUG_SHOW_INFO) { 10478 Log.v(TAG, " IntentFilter:"); 10479 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10480 } 10481 removeFilter(intent); 10482 } 10483 } 10484 10485 @Override 10486 protected boolean allowFilterResult( 10487 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10488 ServiceInfo filterSi = filter.service.info; 10489 for (int i=dest.size()-1; i>=0; i--) { 10490 ServiceInfo destAi = dest.get(i).serviceInfo; 10491 if (destAi.name == filterSi.name 10492 && destAi.packageName == filterSi.packageName) { 10493 return false; 10494 } 10495 } 10496 return true; 10497 } 10498 10499 @Override 10500 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10501 return new PackageParser.ServiceIntentInfo[size]; 10502 } 10503 10504 @Override 10505 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10506 if (!sUserManager.exists(userId)) return true; 10507 PackageParser.Package p = filter.service.owner; 10508 if (p != null) { 10509 PackageSetting ps = (PackageSetting)p.mExtras; 10510 if (ps != null) { 10511 // System apps are never considered stopped for purposes of 10512 // filtering, because there may be no way for the user to 10513 // actually re-launch them. 10514 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10515 && ps.getStopped(userId); 10516 } 10517 } 10518 return false; 10519 } 10520 10521 @Override 10522 protected boolean isPackageForFilter(String packageName, 10523 PackageParser.ServiceIntentInfo info) { 10524 return packageName.equals(info.service.owner.packageName); 10525 } 10526 10527 @Override 10528 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10529 int match, int userId) { 10530 if (!sUserManager.exists(userId)) return null; 10531 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10532 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10533 return null; 10534 } 10535 final PackageParser.Service service = info.service; 10536 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10537 if (ps == null) { 10538 return null; 10539 } 10540 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10541 ps.readUserState(userId), userId); 10542 if (si == null) { 10543 return null; 10544 } 10545 final ResolveInfo res = new ResolveInfo(); 10546 res.serviceInfo = si; 10547 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10548 res.filter = filter; 10549 } 10550 res.priority = info.getPriority(); 10551 res.preferredOrder = service.owner.mPreferredOrder; 10552 res.match = match; 10553 res.isDefault = info.hasDefault; 10554 res.labelRes = info.labelRes; 10555 res.nonLocalizedLabel = info.nonLocalizedLabel; 10556 res.icon = info.icon; 10557 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10558 return res; 10559 } 10560 10561 @Override 10562 protected void sortResults(List<ResolveInfo> results) { 10563 Collections.sort(results, mResolvePrioritySorter); 10564 } 10565 10566 @Override 10567 protected void dumpFilter(PrintWriter out, String prefix, 10568 PackageParser.ServiceIntentInfo filter) { 10569 out.print(prefix); out.print( 10570 Integer.toHexString(System.identityHashCode(filter.service))); 10571 out.print(' '); 10572 filter.service.printComponentShortName(out); 10573 out.print(" filter "); 10574 out.println(Integer.toHexString(System.identityHashCode(filter))); 10575 } 10576 10577 @Override 10578 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10579 return filter.service; 10580 } 10581 10582 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10583 PackageParser.Service service = (PackageParser.Service)label; 10584 out.print(prefix); out.print( 10585 Integer.toHexString(System.identityHashCode(service))); 10586 out.print(' '); 10587 service.printComponentShortName(out); 10588 if (count > 1) { 10589 out.print(" ("); out.print(count); out.print(" filters)"); 10590 } 10591 out.println(); 10592 } 10593 10594// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10595// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10596// final List<ResolveInfo> retList = Lists.newArrayList(); 10597// while (i.hasNext()) { 10598// final ResolveInfo resolveInfo = (ResolveInfo) i; 10599// if (isEnabledLP(resolveInfo.serviceInfo)) { 10600// retList.add(resolveInfo); 10601// } 10602// } 10603// return retList; 10604// } 10605 10606 // Keys are String (activity class name), values are Activity. 10607 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10608 = new ArrayMap<ComponentName, PackageParser.Service>(); 10609 private int mFlags; 10610 }; 10611 10612 private final class ProviderIntentResolver 10613 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10614 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10615 boolean defaultOnly, int userId) { 10616 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10617 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10618 } 10619 10620 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10621 int userId) { 10622 if (!sUserManager.exists(userId)) 10623 return null; 10624 mFlags = flags; 10625 return super.queryIntent(intent, resolvedType, 10626 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10627 } 10628 10629 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10630 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10631 if (!sUserManager.exists(userId)) 10632 return null; 10633 if (packageProviders == null) { 10634 return null; 10635 } 10636 mFlags = flags; 10637 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10638 final int N = packageProviders.size(); 10639 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10640 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10641 10642 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10643 for (int i = 0; i < N; ++i) { 10644 intentFilters = packageProviders.get(i).intents; 10645 if (intentFilters != null && intentFilters.size() > 0) { 10646 PackageParser.ProviderIntentInfo[] array = 10647 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10648 intentFilters.toArray(array); 10649 listCut.add(array); 10650 } 10651 } 10652 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10653 } 10654 10655 public final void addProvider(PackageParser.Provider p) { 10656 if (mProviders.containsKey(p.getComponentName())) { 10657 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10658 return; 10659 } 10660 10661 mProviders.put(p.getComponentName(), p); 10662 if (DEBUG_SHOW_INFO) { 10663 Log.v(TAG, " " 10664 + (p.info.nonLocalizedLabel != null 10665 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10666 Log.v(TAG, " Class=" + p.info.name); 10667 } 10668 final int NI = p.intents.size(); 10669 int j; 10670 for (j = 0; j < NI; j++) { 10671 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10672 if (DEBUG_SHOW_INFO) { 10673 Log.v(TAG, " IntentFilter:"); 10674 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10675 } 10676 if (!intent.debugCheck()) { 10677 Log.w(TAG, "==> For Provider " + p.info.name); 10678 } 10679 addFilter(intent); 10680 } 10681 } 10682 10683 public final void removeProvider(PackageParser.Provider p) { 10684 mProviders.remove(p.getComponentName()); 10685 if (DEBUG_SHOW_INFO) { 10686 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10687 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10688 Log.v(TAG, " Class=" + p.info.name); 10689 } 10690 final int NI = p.intents.size(); 10691 int j; 10692 for (j = 0; j < NI; j++) { 10693 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10694 if (DEBUG_SHOW_INFO) { 10695 Log.v(TAG, " IntentFilter:"); 10696 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10697 } 10698 removeFilter(intent); 10699 } 10700 } 10701 10702 @Override 10703 protected boolean allowFilterResult( 10704 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10705 ProviderInfo filterPi = filter.provider.info; 10706 for (int i = dest.size() - 1; i >= 0; i--) { 10707 ProviderInfo destPi = dest.get(i).providerInfo; 10708 if (destPi.name == filterPi.name 10709 && destPi.packageName == filterPi.packageName) { 10710 return false; 10711 } 10712 } 10713 return true; 10714 } 10715 10716 @Override 10717 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10718 return new PackageParser.ProviderIntentInfo[size]; 10719 } 10720 10721 @Override 10722 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10723 if (!sUserManager.exists(userId)) 10724 return true; 10725 PackageParser.Package p = filter.provider.owner; 10726 if (p != null) { 10727 PackageSetting ps = (PackageSetting) p.mExtras; 10728 if (ps != null) { 10729 // System apps are never considered stopped for purposes of 10730 // filtering, because there may be no way for the user to 10731 // actually re-launch them. 10732 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10733 && ps.getStopped(userId); 10734 } 10735 } 10736 return false; 10737 } 10738 10739 @Override 10740 protected boolean isPackageForFilter(String packageName, 10741 PackageParser.ProviderIntentInfo info) { 10742 return packageName.equals(info.provider.owner.packageName); 10743 } 10744 10745 @Override 10746 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10747 int match, int userId) { 10748 if (!sUserManager.exists(userId)) 10749 return null; 10750 final PackageParser.ProviderIntentInfo info = filter; 10751 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10752 return null; 10753 } 10754 final PackageParser.Provider provider = info.provider; 10755 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10756 if (ps == null) { 10757 return null; 10758 } 10759 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10760 ps.readUserState(userId), userId); 10761 if (pi == null) { 10762 return null; 10763 } 10764 final ResolveInfo res = new ResolveInfo(); 10765 res.providerInfo = pi; 10766 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10767 res.filter = filter; 10768 } 10769 res.priority = info.getPriority(); 10770 res.preferredOrder = provider.owner.mPreferredOrder; 10771 res.match = match; 10772 res.isDefault = info.hasDefault; 10773 res.labelRes = info.labelRes; 10774 res.nonLocalizedLabel = info.nonLocalizedLabel; 10775 res.icon = info.icon; 10776 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10777 return res; 10778 } 10779 10780 @Override 10781 protected void sortResults(List<ResolveInfo> results) { 10782 Collections.sort(results, mResolvePrioritySorter); 10783 } 10784 10785 @Override 10786 protected void dumpFilter(PrintWriter out, String prefix, 10787 PackageParser.ProviderIntentInfo filter) { 10788 out.print(prefix); 10789 out.print( 10790 Integer.toHexString(System.identityHashCode(filter.provider))); 10791 out.print(' '); 10792 filter.provider.printComponentShortName(out); 10793 out.print(" filter "); 10794 out.println(Integer.toHexString(System.identityHashCode(filter))); 10795 } 10796 10797 @Override 10798 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10799 return filter.provider; 10800 } 10801 10802 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10803 PackageParser.Provider provider = (PackageParser.Provider)label; 10804 out.print(prefix); out.print( 10805 Integer.toHexString(System.identityHashCode(provider))); 10806 out.print(' '); 10807 provider.printComponentShortName(out); 10808 if (count > 1) { 10809 out.print(" ("); out.print(count); out.print(" filters)"); 10810 } 10811 out.println(); 10812 } 10813 10814 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10815 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10816 private int mFlags; 10817 } 10818 10819 private static final class EphemeralIntentResolver 10820 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10821 @Override 10822 protected EphemeralResolveIntentInfo[] newArray(int size) { 10823 return new EphemeralResolveIntentInfo[size]; 10824 } 10825 10826 @Override 10827 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10828 return true; 10829 } 10830 10831 @Override 10832 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10833 int userId) { 10834 if (!sUserManager.exists(userId)) { 10835 return null; 10836 } 10837 return info.getEphemeralResolveInfo(); 10838 } 10839 } 10840 10841 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10842 new Comparator<ResolveInfo>() { 10843 public int compare(ResolveInfo r1, ResolveInfo r2) { 10844 int v1 = r1.priority; 10845 int v2 = r2.priority; 10846 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10847 if (v1 != v2) { 10848 return (v1 > v2) ? -1 : 1; 10849 } 10850 v1 = r1.preferredOrder; 10851 v2 = r2.preferredOrder; 10852 if (v1 != v2) { 10853 return (v1 > v2) ? -1 : 1; 10854 } 10855 if (r1.isDefault != r2.isDefault) { 10856 return r1.isDefault ? -1 : 1; 10857 } 10858 v1 = r1.match; 10859 v2 = r2.match; 10860 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 10861 if (v1 != v2) { 10862 return (v1 > v2) ? -1 : 1; 10863 } 10864 if (r1.system != r2.system) { 10865 return r1.system ? -1 : 1; 10866 } 10867 if (r1.activityInfo != null) { 10868 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 10869 } 10870 if (r1.serviceInfo != null) { 10871 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 10872 } 10873 if (r1.providerInfo != null) { 10874 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 10875 } 10876 return 0; 10877 } 10878 }; 10879 10880 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 10881 new Comparator<ProviderInfo>() { 10882 public int compare(ProviderInfo p1, ProviderInfo p2) { 10883 final int v1 = p1.initOrder; 10884 final int v2 = p2.initOrder; 10885 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 10886 } 10887 }; 10888 10889 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 10890 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 10891 final int[] userIds) { 10892 mHandler.post(new Runnable() { 10893 @Override 10894 public void run() { 10895 try { 10896 final IActivityManager am = ActivityManagerNative.getDefault(); 10897 if (am == null) return; 10898 final int[] resolvedUserIds; 10899 if (userIds == null) { 10900 resolvedUserIds = am.getRunningUserIds(); 10901 } else { 10902 resolvedUserIds = userIds; 10903 } 10904 for (int id : resolvedUserIds) { 10905 final Intent intent = new Intent(action, 10906 pkg != null ? Uri.fromParts("package", pkg, null) : null); 10907 if (extras != null) { 10908 intent.putExtras(extras); 10909 } 10910 if (targetPkg != null) { 10911 intent.setPackage(targetPkg); 10912 } 10913 // Modify the UID when posting to other users 10914 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 10915 if (uid > 0 && UserHandle.getUserId(uid) != id) { 10916 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 10917 intent.putExtra(Intent.EXTRA_UID, uid); 10918 } 10919 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 10920 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 10921 if (DEBUG_BROADCASTS) { 10922 RuntimeException here = new RuntimeException("here"); 10923 here.fillInStackTrace(); 10924 Slog.d(TAG, "Sending to user " + id + ": " 10925 + intent.toShortString(false, true, false, false) 10926 + " " + intent.getExtras(), here); 10927 } 10928 am.broadcastIntent(null, intent, null, finishedReceiver, 10929 0, null, null, null, android.app.AppOpsManager.OP_NONE, 10930 null, finishedReceiver != null, false, id); 10931 } 10932 } catch (RemoteException ex) { 10933 } 10934 } 10935 }); 10936 } 10937 10938 /** 10939 * Check if the external storage media is available. This is true if there 10940 * is a mounted external storage medium or if the external storage is 10941 * emulated. 10942 */ 10943 private boolean isExternalMediaAvailable() { 10944 return mMediaMounted || Environment.isExternalStorageEmulated(); 10945 } 10946 10947 @Override 10948 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 10949 // writer 10950 synchronized (mPackages) { 10951 if (!isExternalMediaAvailable()) { 10952 // If the external storage is no longer mounted at this point, 10953 // the caller may not have been able to delete all of this 10954 // packages files and can not delete any more. Bail. 10955 return null; 10956 } 10957 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 10958 if (lastPackage != null) { 10959 pkgs.remove(lastPackage); 10960 } 10961 if (pkgs.size() > 0) { 10962 return pkgs.get(0); 10963 } 10964 } 10965 return null; 10966 } 10967 10968 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 10969 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 10970 userId, andCode ? 1 : 0, packageName); 10971 if (mSystemReady) { 10972 msg.sendToTarget(); 10973 } else { 10974 if (mPostSystemReadyMessages == null) { 10975 mPostSystemReadyMessages = new ArrayList<>(); 10976 } 10977 mPostSystemReadyMessages.add(msg); 10978 } 10979 } 10980 10981 void startCleaningPackages() { 10982 // reader 10983 if (!isExternalMediaAvailable()) { 10984 return; 10985 } 10986 synchronized (mPackages) { 10987 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 10988 return; 10989 } 10990 } 10991 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 10992 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 10993 IActivityManager am = ActivityManagerNative.getDefault(); 10994 if (am != null) { 10995 try { 10996 am.startService(null, intent, null, mContext.getOpPackageName(), 10997 UserHandle.USER_SYSTEM); 10998 } catch (RemoteException e) { 10999 } 11000 } 11001 } 11002 11003 @Override 11004 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11005 int installFlags, String installerPackageName, int userId) { 11006 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11007 11008 final int callingUid = Binder.getCallingUid(); 11009 enforceCrossUserPermission(callingUid, userId, 11010 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11011 11012 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11013 try { 11014 if (observer != null) { 11015 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11016 } 11017 } catch (RemoteException re) { 11018 } 11019 return; 11020 } 11021 11022 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11023 installFlags |= PackageManager.INSTALL_FROM_ADB; 11024 11025 } else { 11026 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11027 // about installerPackageName. 11028 11029 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11030 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11031 } 11032 11033 UserHandle user; 11034 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11035 user = UserHandle.ALL; 11036 } else { 11037 user = new UserHandle(userId); 11038 } 11039 11040 // Only system components can circumvent runtime permissions when installing. 11041 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11042 && mContext.checkCallingOrSelfPermission(Manifest.permission 11043 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11044 throw new SecurityException("You need the " 11045 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11046 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11047 } 11048 11049 final File originFile = new File(originPath); 11050 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11051 11052 final Message msg = mHandler.obtainMessage(INIT_COPY); 11053 final VerificationInfo verificationInfo = new VerificationInfo( 11054 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11055 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11056 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11057 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11058 null /*certificates*/); 11059 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11060 msg.obj = params; 11061 11062 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11063 System.identityHashCode(msg.obj)); 11064 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11065 System.identityHashCode(msg.obj)); 11066 11067 mHandler.sendMessage(msg); 11068 } 11069 11070 void installStage(String packageName, File stagedDir, String stagedCid, 11071 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11072 String installerPackageName, int installerUid, UserHandle user, 11073 Certificate[][] certificates) { 11074 if (DEBUG_EPHEMERAL) { 11075 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11076 Slog.d(TAG, "Ephemeral install of " + packageName); 11077 } 11078 } 11079 final VerificationInfo verificationInfo = new VerificationInfo( 11080 sessionParams.originatingUri, sessionParams.referrerUri, 11081 sessionParams.originatingUid, installerUid); 11082 11083 final OriginInfo origin; 11084 if (stagedDir != null) { 11085 origin = OriginInfo.fromStagedFile(stagedDir); 11086 } else { 11087 origin = OriginInfo.fromStagedContainer(stagedCid); 11088 } 11089 11090 final Message msg = mHandler.obtainMessage(INIT_COPY); 11091 final InstallParams params = new InstallParams(origin, null, observer, 11092 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11093 verificationInfo, user, sessionParams.abiOverride, 11094 sessionParams.grantedRuntimePermissions, certificates); 11095 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11096 msg.obj = params; 11097 11098 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11099 System.identityHashCode(msg.obj)); 11100 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11101 System.identityHashCode(msg.obj)); 11102 11103 mHandler.sendMessage(msg); 11104 } 11105 11106 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11107 int userId) { 11108 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11109 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11110 } 11111 11112 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11113 int appId, int userId) { 11114 Bundle extras = new Bundle(1); 11115 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11116 11117 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11118 packageName, extras, 0, null, null, new int[] {userId}); 11119 try { 11120 IActivityManager am = ActivityManagerNative.getDefault(); 11121 if (isSystem && am.isUserRunning(userId, 0)) { 11122 // The just-installed/enabled app is bundled on the system, so presumed 11123 // to be able to run automatically without needing an explicit launch. 11124 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11125 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11126 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11127 .setPackage(packageName); 11128 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11129 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11130 } 11131 } catch (RemoteException e) { 11132 // shouldn't happen 11133 Slog.w(TAG, "Unable to bootstrap installed package", e); 11134 } 11135 } 11136 11137 @Override 11138 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11139 int userId) { 11140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11141 PackageSetting pkgSetting; 11142 final int uid = Binder.getCallingUid(); 11143 enforceCrossUserPermission(uid, userId, 11144 true /* requireFullPermission */, true /* checkShell */, 11145 "setApplicationHiddenSetting for user " + userId); 11146 11147 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11148 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11149 return false; 11150 } 11151 11152 long callingId = Binder.clearCallingIdentity(); 11153 try { 11154 boolean sendAdded = false; 11155 boolean sendRemoved = false; 11156 // writer 11157 synchronized (mPackages) { 11158 pkgSetting = mSettings.mPackages.get(packageName); 11159 if (pkgSetting == null) { 11160 return false; 11161 } 11162 if (pkgSetting.getHidden(userId) != hidden) { 11163 pkgSetting.setHidden(hidden, userId); 11164 mSettings.writePackageRestrictionsLPr(userId); 11165 if (hidden) { 11166 sendRemoved = true; 11167 } else { 11168 sendAdded = true; 11169 } 11170 } 11171 } 11172 if (sendAdded) { 11173 sendPackageAddedForUser(packageName, pkgSetting, userId); 11174 return true; 11175 } 11176 if (sendRemoved) { 11177 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11178 "hiding pkg"); 11179 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11180 return true; 11181 } 11182 } finally { 11183 Binder.restoreCallingIdentity(callingId); 11184 } 11185 return false; 11186 } 11187 11188 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11189 int userId) { 11190 final PackageRemovedInfo info = new PackageRemovedInfo(); 11191 info.removedPackage = packageName; 11192 info.removedUsers = new int[] {userId}; 11193 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11194 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11195 } 11196 11197 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11198 if (pkgList.length > 0) { 11199 Bundle extras = new Bundle(1); 11200 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11201 11202 sendPackageBroadcast( 11203 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11204 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11205 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11206 new int[] {userId}); 11207 } 11208 } 11209 11210 /** 11211 * Returns true if application is not found or there was an error. Otherwise it returns 11212 * the hidden state of the package for the given user. 11213 */ 11214 @Override 11215 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11216 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11217 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11218 true /* requireFullPermission */, false /* checkShell */, 11219 "getApplicationHidden for user " + userId); 11220 PackageSetting pkgSetting; 11221 long callingId = Binder.clearCallingIdentity(); 11222 try { 11223 // writer 11224 synchronized (mPackages) { 11225 pkgSetting = mSettings.mPackages.get(packageName); 11226 if (pkgSetting == null) { 11227 return true; 11228 } 11229 return pkgSetting.getHidden(userId); 11230 } 11231 } finally { 11232 Binder.restoreCallingIdentity(callingId); 11233 } 11234 } 11235 11236 /** 11237 * @hide 11238 */ 11239 @Override 11240 public int installExistingPackageAsUser(String packageName, int userId) { 11241 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11242 null); 11243 PackageSetting pkgSetting; 11244 final int uid = Binder.getCallingUid(); 11245 enforceCrossUserPermission(uid, userId, 11246 true /* requireFullPermission */, true /* checkShell */, 11247 "installExistingPackage for user " + userId); 11248 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11249 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11250 } 11251 11252 long callingId = Binder.clearCallingIdentity(); 11253 try { 11254 boolean installed = false; 11255 11256 // writer 11257 synchronized (mPackages) { 11258 pkgSetting = mSettings.mPackages.get(packageName); 11259 if (pkgSetting == null) { 11260 return PackageManager.INSTALL_FAILED_INVALID_URI; 11261 } 11262 if (!pkgSetting.getInstalled(userId)) { 11263 pkgSetting.setInstalled(true, userId); 11264 pkgSetting.setHidden(false, userId); 11265 mSettings.writePackageRestrictionsLPr(userId); 11266 installed = true; 11267 } 11268 } 11269 11270 if (installed) { 11271 if (pkgSetting.pkg != null) { 11272 synchronized (mInstallLock) { 11273 // We don't need to freeze for a brand new install 11274 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11275 } 11276 } 11277 sendPackageAddedForUser(packageName, pkgSetting, userId); 11278 } 11279 } finally { 11280 Binder.restoreCallingIdentity(callingId); 11281 } 11282 11283 return PackageManager.INSTALL_SUCCEEDED; 11284 } 11285 11286 boolean isUserRestricted(int userId, String restrictionKey) { 11287 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11288 if (restrictions.getBoolean(restrictionKey, false)) { 11289 Log.w(TAG, "User is restricted: " + restrictionKey); 11290 return true; 11291 } 11292 return false; 11293 } 11294 11295 @Override 11296 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11297 int userId) { 11298 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11299 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11300 true /* requireFullPermission */, true /* checkShell */, 11301 "setPackagesSuspended for user " + userId); 11302 11303 if (ArrayUtils.isEmpty(packageNames)) { 11304 return packageNames; 11305 } 11306 11307 // List of package names for whom the suspended state has changed. 11308 List<String> changedPackages = new ArrayList<>(packageNames.length); 11309 // List of package names for whom the suspended state is not set as requested in this 11310 // method. 11311 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11312 for (int i = 0; i < packageNames.length; i++) { 11313 String packageName = packageNames[i]; 11314 long callingId = Binder.clearCallingIdentity(); 11315 try { 11316 boolean changed = false; 11317 final int appId; 11318 synchronized (mPackages) { 11319 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11320 if (pkgSetting == null) { 11321 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11322 + "\". Skipping suspending/un-suspending."); 11323 unactionedPackages.add(packageName); 11324 continue; 11325 } 11326 appId = pkgSetting.appId; 11327 if (pkgSetting.getSuspended(userId) != suspended) { 11328 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11329 unactionedPackages.add(packageName); 11330 continue; 11331 } 11332 pkgSetting.setSuspended(suspended, userId); 11333 mSettings.writePackageRestrictionsLPr(userId); 11334 changed = true; 11335 changedPackages.add(packageName); 11336 } 11337 } 11338 11339 if (changed && suspended) { 11340 killApplication(packageName, UserHandle.getUid(userId, appId), 11341 "suspending package"); 11342 } 11343 } finally { 11344 Binder.restoreCallingIdentity(callingId); 11345 } 11346 } 11347 11348 if (!changedPackages.isEmpty()) { 11349 sendPackagesSuspendedForUser(changedPackages.toArray( 11350 new String[changedPackages.size()]), userId, suspended); 11351 } 11352 11353 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11354 } 11355 11356 @Override 11357 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11358 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11359 true /* requireFullPermission */, false /* checkShell */, 11360 "isPackageSuspendedForUser for user " + userId); 11361 synchronized (mPackages) { 11362 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11363 if (pkgSetting == null) { 11364 throw new IllegalArgumentException("Unknown target package: " + packageName); 11365 } 11366 return pkgSetting.getSuspended(userId); 11367 } 11368 } 11369 11370 /** 11371 * TODO: cache and disallow blocking the active dialer. 11372 * 11373 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11374 */ 11375 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11376 if (isPackageDeviceAdmin(packageName, userId)) { 11377 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11378 + "\": has an active device admin"); 11379 return false; 11380 } 11381 11382 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11383 if (packageName.equals(activeLauncherPackageName)) { 11384 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11385 + "\": contains the active launcher"); 11386 return false; 11387 } 11388 11389 if (packageName.equals(mRequiredInstallerPackage)) { 11390 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11391 + "\": required for package installation"); 11392 return false; 11393 } 11394 11395 if (packageName.equals(mRequiredVerifierPackage)) { 11396 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11397 + "\": required for package verification"); 11398 return false; 11399 } 11400 11401 final PackageParser.Package pkg = mPackages.get(packageName); 11402 if (pkg != null && isPrivilegedApp(pkg)) { 11403 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11404 + "\": is a privileged app"); 11405 return false; 11406 } 11407 11408 return true; 11409 } 11410 11411 private String getActiveLauncherPackageName(int userId) { 11412 Intent intent = new Intent(Intent.ACTION_MAIN); 11413 intent.addCategory(Intent.CATEGORY_HOME); 11414 ResolveInfo resolveInfo = resolveIntent( 11415 intent, 11416 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11417 PackageManager.MATCH_DEFAULT_ONLY, 11418 userId); 11419 11420 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11421 } 11422 11423 @Override 11424 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11425 mContext.enforceCallingOrSelfPermission( 11426 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11427 "Only package verification agents can verify applications"); 11428 11429 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11430 final PackageVerificationResponse response = new PackageVerificationResponse( 11431 verificationCode, Binder.getCallingUid()); 11432 msg.arg1 = id; 11433 msg.obj = response; 11434 mHandler.sendMessage(msg); 11435 } 11436 11437 @Override 11438 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11439 long millisecondsToDelay) { 11440 mContext.enforceCallingOrSelfPermission( 11441 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11442 "Only package verification agents can extend verification timeouts"); 11443 11444 final PackageVerificationState state = mPendingVerification.get(id); 11445 final PackageVerificationResponse response = new PackageVerificationResponse( 11446 verificationCodeAtTimeout, Binder.getCallingUid()); 11447 11448 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11449 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11450 } 11451 if (millisecondsToDelay < 0) { 11452 millisecondsToDelay = 0; 11453 } 11454 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11455 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11456 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11457 } 11458 11459 if ((state != null) && !state.timeoutExtended()) { 11460 state.extendTimeout(); 11461 11462 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11463 msg.arg1 = id; 11464 msg.obj = response; 11465 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11466 } 11467 } 11468 11469 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11470 int verificationCode, UserHandle user) { 11471 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11472 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11473 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11474 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11475 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11476 11477 mContext.sendBroadcastAsUser(intent, user, 11478 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11479 } 11480 11481 private ComponentName matchComponentForVerifier(String packageName, 11482 List<ResolveInfo> receivers) { 11483 ActivityInfo targetReceiver = null; 11484 11485 final int NR = receivers.size(); 11486 for (int i = 0; i < NR; i++) { 11487 final ResolveInfo info = receivers.get(i); 11488 if (info.activityInfo == null) { 11489 continue; 11490 } 11491 11492 if (packageName.equals(info.activityInfo.packageName)) { 11493 targetReceiver = info.activityInfo; 11494 break; 11495 } 11496 } 11497 11498 if (targetReceiver == null) { 11499 return null; 11500 } 11501 11502 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11503 } 11504 11505 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11506 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11507 if (pkgInfo.verifiers.length == 0) { 11508 return null; 11509 } 11510 11511 final int N = pkgInfo.verifiers.length; 11512 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11513 for (int i = 0; i < N; i++) { 11514 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11515 11516 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11517 receivers); 11518 if (comp == null) { 11519 continue; 11520 } 11521 11522 final int verifierUid = getUidForVerifier(verifierInfo); 11523 if (verifierUid == -1) { 11524 continue; 11525 } 11526 11527 if (DEBUG_VERIFY) { 11528 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11529 + " with the correct signature"); 11530 } 11531 sufficientVerifiers.add(comp); 11532 verificationState.addSufficientVerifier(verifierUid); 11533 } 11534 11535 return sufficientVerifiers; 11536 } 11537 11538 private int getUidForVerifier(VerifierInfo verifierInfo) { 11539 synchronized (mPackages) { 11540 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11541 if (pkg == null) { 11542 return -1; 11543 } else if (pkg.mSignatures.length != 1) { 11544 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11545 + " has more than one signature; ignoring"); 11546 return -1; 11547 } 11548 11549 /* 11550 * If the public key of the package's signature does not match 11551 * our expected public key, then this is a different package and 11552 * we should skip. 11553 */ 11554 11555 final byte[] expectedPublicKey; 11556 try { 11557 final Signature verifierSig = pkg.mSignatures[0]; 11558 final PublicKey publicKey = verifierSig.getPublicKey(); 11559 expectedPublicKey = publicKey.getEncoded(); 11560 } catch (CertificateException e) { 11561 return -1; 11562 } 11563 11564 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11565 11566 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11567 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11568 + " does not have the expected public key; ignoring"); 11569 return -1; 11570 } 11571 11572 return pkg.applicationInfo.uid; 11573 } 11574 } 11575 11576 @Override 11577 public void finishPackageInstall(int token) { 11578 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11579 11580 if (DEBUG_INSTALL) { 11581 Slog.v(TAG, "BM finishing package install for " + token); 11582 } 11583 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11584 11585 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11586 mHandler.sendMessage(msg); 11587 } 11588 11589 /** 11590 * Get the verification agent timeout. 11591 * 11592 * @return verification timeout in milliseconds 11593 */ 11594 private long getVerificationTimeout() { 11595 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11596 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11597 DEFAULT_VERIFICATION_TIMEOUT); 11598 } 11599 11600 /** 11601 * Get the default verification agent response code. 11602 * 11603 * @return default verification response code 11604 */ 11605 private int getDefaultVerificationResponse() { 11606 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11607 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11608 DEFAULT_VERIFICATION_RESPONSE); 11609 } 11610 11611 /** 11612 * Check whether or not package verification has been enabled. 11613 * 11614 * @return true if verification should be performed 11615 */ 11616 private boolean isVerificationEnabled(int userId, int installFlags) { 11617 if (!DEFAULT_VERIFY_ENABLE) { 11618 return false; 11619 } 11620 // Ephemeral apps don't get the full verification treatment 11621 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11622 if (DEBUG_EPHEMERAL) { 11623 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11624 } 11625 return false; 11626 } 11627 11628 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11629 11630 // Check if installing from ADB 11631 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11632 // Do not run verification in a test harness environment 11633 if (ActivityManager.isRunningInTestHarness()) { 11634 return false; 11635 } 11636 if (ensureVerifyAppsEnabled) { 11637 return true; 11638 } 11639 // Check if the developer does not want package verification for ADB installs 11640 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11641 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11642 return false; 11643 } 11644 } 11645 11646 if (ensureVerifyAppsEnabled) { 11647 return true; 11648 } 11649 11650 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11651 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11652 } 11653 11654 @Override 11655 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11656 throws RemoteException { 11657 mContext.enforceCallingOrSelfPermission( 11658 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11659 "Only intentfilter verification agents can verify applications"); 11660 11661 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11662 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11663 Binder.getCallingUid(), verificationCode, failedDomains); 11664 msg.arg1 = id; 11665 msg.obj = response; 11666 mHandler.sendMessage(msg); 11667 } 11668 11669 @Override 11670 public int getIntentVerificationStatus(String packageName, int userId) { 11671 synchronized (mPackages) { 11672 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11673 } 11674 } 11675 11676 @Override 11677 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11678 mContext.enforceCallingOrSelfPermission( 11679 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11680 11681 boolean result = false; 11682 synchronized (mPackages) { 11683 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11684 } 11685 if (result) { 11686 scheduleWritePackageRestrictionsLocked(userId); 11687 } 11688 return result; 11689 } 11690 11691 @Override 11692 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11693 String packageName) { 11694 synchronized (mPackages) { 11695 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11696 } 11697 } 11698 11699 @Override 11700 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11701 if (TextUtils.isEmpty(packageName)) { 11702 return ParceledListSlice.emptyList(); 11703 } 11704 synchronized (mPackages) { 11705 PackageParser.Package pkg = mPackages.get(packageName); 11706 if (pkg == null || pkg.activities == null) { 11707 return ParceledListSlice.emptyList(); 11708 } 11709 final int count = pkg.activities.size(); 11710 ArrayList<IntentFilter> result = new ArrayList<>(); 11711 for (int n=0; n<count; n++) { 11712 PackageParser.Activity activity = pkg.activities.get(n); 11713 if (activity.intents != null && activity.intents.size() > 0) { 11714 result.addAll(activity.intents); 11715 } 11716 } 11717 return new ParceledListSlice<>(result); 11718 } 11719 } 11720 11721 @Override 11722 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11723 mContext.enforceCallingOrSelfPermission( 11724 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11725 11726 synchronized (mPackages) { 11727 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11728 if (packageName != null) { 11729 result |= updateIntentVerificationStatus(packageName, 11730 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11731 userId); 11732 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11733 packageName, userId); 11734 } 11735 return result; 11736 } 11737 } 11738 11739 @Override 11740 public String getDefaultBrowserPackageName(int userId) { 11741 synchronized (mPackages) { 11742 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11743 } 11744 } 11745 11746 /** 11747 * Get the "allow unknown sources" setting. 11748 * 11749 * @return the current "allow unknown sources" setting 11750 */ 11751 private int getUnknownSourcesSettings() { 11752 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11753 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11754 -1); 11755 } 11756 11757 @Override 11758 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11759 final int uid = Binder.getCallingUid(); 11760 // writer 11761 synchronized (mPackages) { 11762 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11763 if (targetPackageSetting == null) { 11764 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11765 } 11766 11767 PackageSetting installerPackageSetting; 11768 if (installerPackageName != null) { 11769 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11770 if (installerPackageSetting == null) { 11771 throw new IllegalArgumentException("Unknown installer package: " 11772 + installerPackageName); 11773 } 11774 } else { 11775 installerPackageSetting = null; 11776 } 11777 11778 Signature[] callerSignature; 11779 Object obj = mSettings.getUserIdLPr(uid); 11780 if (obj != null) { 11781 if (obj instanceof SharedUserSetting) { 11782 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11783 } else if (obj instanceof PackageSetting) { 11784 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11785 } else { 11786 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11787 } 11788 } else { 11789 throw new SecurityException("Unknown calling UID: " + uid); 11790 } 11791 11792 // Verify: can't set installerPackageName to a package that is 11793 // not signed with the same cert as the caller. 11794 if (installerPackageSetting != null) { 11795 if (compareSignatures(callerSignature, 11796 installerPackageSetting.signatures.mSignatures) 11797 != PackageManager.SIGNATURE_MATCH) { 11798 throw new SecurityException( 11799 "Caller does not have same cert as new installer package " 11800 + installerPackageName); 11801 } 11802 } 11803 11804 // Verify: if target already has an installer package, it must 11805 // be signed with the same cert as the caller. 11806 if (targetPackageSetting.installerPackageName != null) { 11807 PackageSetting setting = mSettings.mPackages.get( 11808 targetPackageSetting.installerPackageName); 11809 // If the currently set package isn't valid, then it's always 11810 // okay to change it. 11811 if (setting != null) { 11812 if (compareSignatures(callerSignature, 11813 setting.signatures.mSignatures) 11814 != PackageManager.SIGNATURE_MATCH) { 11815 throw new SecurityException( 11816 "Caller does not have same cert as old installer package " 11817 + targetPackageSetting.installerPackageName); 11818 } 11819 } 11820 } 11821 11822 // Okay! 11823 targetPackageSetting.installerPackageName = installerPackageName; 11824 if (installerPackageName != null) { 11825 mSettings.mInstallerPackages.add(installerPackageName); 11826 } 11827 scheduleWriteSettingsLocked(); 11828 } 11829 } 11830 11831 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11832 // Queue up an async operation since the package installation may take a little while. 11833 mHandler.post(new Runnable() { 11834 public void run() { 11835 mHandler.removeCallbacks(this); 11836 // Result object to be returned 11837 PackageInstalledInfo res = new PackageInstalledInfo(); 11838 res.setReturnCode(currentStatus); 11839 res.uid = -1; 11840 res.pkg = null; 11841 res.removedInfo = null; 11842 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11843 args.doPreInstall(res.returnCode); 11844 synchronized (mInstallLock) { 11845 installPackageTracedLI(args, res); 11846 } 11847 args.doPostInstall(res.returnCode, res.uid); 11848 } 11849 11850 // A restore should be performed at this point if (a) the install 11851 // succeeded, (b) the operation is not an update, and (c) the new 11852 // package has not opted out of backup participation. 11853 final boolean update = res.removedInfo != null 11854 && res.removedInfo.removedPackage != null; 11855 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 11856 boolean doRestore = !update 11857 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 11858 11859 // Set up the post-install work request bookkeeping. This will be used 11860 // and cleaned up by the post-install event handling regardless of whether 11861 // there's a restore pass performed. Token values are >= 1. 11862 int token; 11863 if (mNextInstallToken < 0) mNextInstallToken = 1; 11864 token = mNextInstallToken++; 11865 11866 PostInstallData data = new PostInstallData(args, res); 11867 mRunningInstalls.put(token, data); 11868 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 11869 11870 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 11871 // Pass responsibility to the Backup Manager. It will perform a 11872 // restore if appropriate, then pass responsibility back to the 11873 // Package Manager to run the post-install observer callbacks 11874 // and broadcasts. 11875 IBackupManager bm = IBackupManager.Stub.asInterface( 11876 ServiceManager.getService(Context.BACKUP_SERVICE)); 11877 if (bm != null) { 11878 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 11879 + " to BM for possible restore"); 11880 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11881 try { 11882 // TODO: http://b/22388012 11883 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 11884 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 11885 } else { 11886 doRestore = false; 11887 } 11888 } catch (RemoteException e) { 11889 // can't happen; the backup manager is local 11890 } catch (Exception e) { 11891 Slog.e(TAG, "Exception trying to enqueue restore", e); 11892 doRestore = false; 11893 } 11894 } else { 11895 Slog.e(TAG, "Backup Manager not found!"); 11896 doRestore = false; 11897 } 11898 } 11899 11900 if (!doRestore) { 11901 // No restore possible, or the Backup Manager was mysteriously not 11902 // available -- just fire the post-install work request directly. 11903 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 11904 11905 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 11906 11907 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11908 mHandler.sendMessage(msg); 11909 } 11910 } 11911 }); 11912 } 11913 11914 private abstract class HandlerParams { 11915 private static final int MAX_RETRIES = 4; 11916 11917 /** 11918 * Number of times startCopy() has been attempted and had a non-fatal 11919 * error. 11920 */ 11921 private int mRetries = 0; 11922 11923 /** User handle for the user requesting the information or installation. */ 11924 private final UserHandle mUser; 11925 String traceMethod; 11926 int traceCookie; 11927 11928 HandlerParams(UserHandle user) { 11929 mUser = user; 11930 } 11931 11932 UserHandle getUser() { 11933 return mUser; 11934 } 11935 11936 HandlerParams setTraceMethod(String traceMethod) { 11937 this.traceMethod = traceMethod; 11938 return this; 11939 } 11940 11941 HandlerParams setTraceCookie(int traceCookie) { 11942 this.traceCookie = traceCookie; 11943 return this; 11944 } 11945 11946 final boolean startCopy() { 11947 boolean res; 11948 try { 11949 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 11950 11951 if (++mRetries > MAX_RETRIES) { 11952 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 11953 mHandler.sendEmptyMessage(MCS_GIVE_UP); 11954 handleServiceError(); 11955 return false; 11956 } else { 11957 handleStartCopy(); 11958 res = true; 11959 } 11960 } catch (RemoteException e) { 11961 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 11962 mHandler.sendEmptyMessage(MCS_RECONNECT); 11963 res = false; 11964 } 11965 handleReturnCode(); 11966 return res; 11967 } 11968 11969 final void serviceError() { 11970 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 11971 handleServiceError(); 11972 handleReturnCode(); 11973 } 11974 11975 abstract void handleStartCopy() throws RemoteException; 11976 abstract void handleServiceError(); 11977 abstract void handleReturnCode(); 11978 } 11979 11980 class MeasureParams extends HandlerParams { 11981 private final PackageStats mStats; 11982 private boolean mSuccess; 11983 11984 private final IPackageStatsObserver mObserver; 11985 11986 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 11987 super(new UserHandle(stats.userHandle)); 11988 mObserver = observer; 11989 mStats = stats; 11990 } 11991 11992 @Override 11993 public String toString() { 11994 return "MeasureParams{" 11995 + Integer.toHexString(System.identityHashCode(this)) 11996 + " " + mStats.packageName + "}"; 11997 } 11998 11999 @Override 12000 void handleStartCopy() throws RemoteException { 12001 synchronized (mInstallLock) { 12002 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12003 } 12004 12005 if (mSuccess) { 12006 final boolean mounted; 12007 if (Environment.isExternalStorageEmulated()) { 12008 mounted = true; 12009 } else { 12010 final String status = Environment.getExternalStorageState(); 12011 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12012 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12013 } 12014 12015 if (mounted) { 12016 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12017 12018 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12019 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12020 12021 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12022 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12023 12024 // Always subtract cache size, since it's a subdirectory 12025 mStats.externalDataSize -= mStats.externalCacheSize; 12026 12027 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12028 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12029 12030 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12031 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12032 } 12033 } 12034 } 12035 12036 @Override 12037 void handleReturnCode() { 12038 if (mObserver != null) { 12039 try { 12040 mObserver.onGetStatsCompleted(mStats, mSuccess); 12041 } catch (RemoteException e) { 12042 Slog.i(TAG, "Observer no longer exists."); 12043 } 12044 } 12045 } 12046 12047 @Override 12048 void handleServiceError() { 12049 Slog.e(TAG, "Could not measure application " + mStats.packageName 12050 + " external storage"); 12051 } 12052 } 12053 12054 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12055 throws RemoteException { 12056 long result = 0; 12057 for (File path : paths) { 12058 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12059 } 12060 return result; 12061 } 12062 12063 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12064 for (File path : paths) { 12065 try { 12066 mcs.clearDirectory(path.getAbsolutePath()); 12067 } catch (RemoteException e) { 12068 } 12069 } 12070 } 12071 12072 static class OriginInfo { 12073 /** 12074 * Location where install is coming from, before it has been 12075 * copied/renamed into place. This could be a single monolithic APK 12076 * file, or a cluster directory. This location may be untrusted. 12077 */ 12078 final File file; 12079 final String cid; 12080 12081 /** 12082 * Flag indicating that {@link #file} or {@link #cid} has already been 12083 * staged, meaning downstream users don't need to defensively copy the 12084 * contents. 12085 */ 12086 final boolean staged; 12087 12088 /** 12089 * Flag indicating that {@link #file} or {@link #cid} is an already 12090 * installed app that is being moved. 12091 */ 12092 final boolean existing; 12093 12094 final String resolvedPath; 12095 final File resolvedFile; 12096 12097 static OriginInfo fromNothing() { 12098 return new OriginInfo(null, null, false, false); 12099 } 12100 12101 static OriginInfo fromUntrustedFile(File file) { 12102 return new OriginInfo(file, null, false, false); 12103 } 12104 12105 static OriginInfo fromExistingFile(File file) { 12106 return new OriginInfo(file, null, false, true); 12107 } 12108 12109 static OriginInfo fromStagedFile(File file) { 12110 return new OriginInfo(file, null, true, false); 12111 } 12112 12113 static OriginInfo fromStagedContainer(String cid) { 12114 return new OriginInfo(null, cid, true, false); 12115 } 12116 12117 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12118 this.file = file; 12119 this.cid = cid; 12120 this.staged = staged; 12121 this.existing = existing; 12122 12123 if (cid != null) { 12124 resolvedPath = PackageHelper.getSdDir(cid); 12125 resolvedFile = new File(resolvedPath); 12126 } else if (file != null) { 12127 resolvedPath = file.getAbsolutePath(); 12128 resolvedFile = file; 12129 } else { 12130 resolvedPath = null; 12131 resolvedFile = null; 12132 } 12133 } 12134 } 12135 12136 static class MoveInfo { 12137 final int moveId; 12138 final String fromUuid; 12139 final String toUuid; 12140 final String packageName; 12141 final String dataAppName; 12142 final int appId; 12143 final String seinfo; 12144 final int targetSdkVersion; 12145 12146 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12147 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12148 this.moveId = moveId; 12149 this.fromUuid = fromUuid; 12150 this.toUuid = toUuid; 12151 this.packageName = packageName; 12152 this.dataAppName = dataAppName; 12153 this.appId = appId; 12154 this.seinfo = seinfo; 12155 this.targetSdkVersion = targetSdkVersion; 12156 } 12157 } 12158 12159 static class VerificationInfo { 12160 /** A constant used to indicate that a uid value is not present. */ 12161 public static final int NO_UID = -1; 12162 12163 /** URI referencing where the package was downloaded from. */ 12164 final Uri originatingUri; 12165 12166 /** HTTP referrer URI associated with the originatingURI. */ 12167 final Uri referrer; 12168 12169 /** UID of the application that the install request originated from. */ 12170 final int originatingUid; 12171 12172 /** UID of application requesting the install */ 12173 final int installerUid; 12174 12175 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12176 this.originatingUri = originatingUri; 12177 this.referrer = referrer; 12178 this.originatingUid = originatingUid; 12179 this.installerUid = installerUid; 12180 } 12181 } 12182 12183 class InstallParams extends HandlerParams { 12184 final OriginInfo origin; 12185 final MoveInfo move; 12186 final IPackageInstallObserver2 observer; 12187 int installFlags; 12188 final String installerPackageName; 12189 final String volumeUuid; 12190 private InstallArgs mArgs; 12191 private int mRet; 12192 final String packageAbiOverride; 12193 final String[] grantedRuntimePermissions; 12194 final VerificationInfo verificationInfo; 12195 final Certificate[][] certificates; 12196 12197 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12198 int installFlags, String installerPackageName, String volumeUuid, 12199 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12200 String[] grantedPermissions, Certificate[][] certificates) { 12201 super(user); 12202 this.origin = origin; 12203 this.move = move; 12204 this.observer = observer; 12205 this.installFlags = installFlags; 12206 this.installerPackageName = installerPackageName; 12207 this.volumeUuid = volumeUuid; 12208 this.verificationInfo = verificationInfo; 12209 this.packageAbiOverride = packageAbiOverride; 12210 this.grantedRuntimePermissions = grantedPermissions; 12211 this.certificates = certificates; 12212 } 12213 12214 @Override 12215 public String toString() { 12216 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12217 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12218 } 12219 12220 private int installLocationPolicy(PackageInfoLite pkgLite) { 12221 String packageName = pkgLite.packageName; 12222 int installLocation = pkgLite.installLocation; 12223 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12224 // reader 12225 synchronized (mPackages) { 12226 // Currently installed package which the new package is attempting to replace or 12227 // null if no such package is installed. 12228 PackageParser.Package installedPkg = mPackages.get(packageName); 12229 // Package which currently owns the data which the new package will own if installed. 12230 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12231 // will be null whereas dataOwnerPkg will contain information about the package 12232 // which was uninstalled while keeping its data. 12233 PackageParser.Package dataOwnerPkg = installedPkg; 12234 if (dataOwnerPkg == null) { 12235 PackageSetting ps = mSettings.mPackages.get(packageName); 12236 if (ps != null) { 12237 dataOwnerPkg = ps.pkg; 12238 } 12239 } 12240 12241 if (dataOwnerPkg != null) { 12242 // If installed, the package will get access to data left on the device by its 12243 // predecessor. As a security measure, this is permited only if this is not a 12244 // version downgrade or if the predecessor package is marked as debuggable and 12245 // a downgrade is explicitly requested. 12246 // 12247 // On debuggable platform builds, downgrades are permitted even for 12248 // non-debuggable packages to make testing easier. Debuggable platform builds do 12249 // not offer security guarantees and thus it's OK to disable some security 12250 // mechanisms to make debugging/testing easier on those builds. However, even on 12251 // debuggable builds downgrades of packages are permitted only if requested via 12252 // installFlags. This is because we aim to keep the behavior of debuggable 12253 // platform builds as close as possible to the behavior of non-debuggable 12254 // platform builds. 12255 final boolean downgradeRequested = 12256 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12257 final boolean packageDebuggable = 12258 (dataOwnerPkg.applicationInfo.flags 12259 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12260 final boolean downgradePermitted = 12261 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12262 if (!downgradePermitted) { 12263 try { 12264 checkDowngrade(dataOwnerPkg, pkgLite); 12265 } catch (PackageManagerException e) { 12266 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12267 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12268 } 12269 } 12270 } 12271 12272 if (installedPkg != null) { 12273 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12274 // Check for updated system application. 12275 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12276 if (onSd) { 12277 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12278 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12279 } 12280 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12281 } else { 12282 if (onSd) { 12283 // Install flag overrides everything. 12284 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12285 } 12286 // If current upgrade specifies particular preference 12287 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12288 // Application explicitly specified internal. 12289 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12290 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12291 // App explictly prefers external. Let policy decide 12292 } else { 12293 // Prefer previous location 12294 if (isExternal(installedPkg)) { 12295 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12296 } 12297 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12298 } 12299 } 12300 } else { 12301 // Invalid install. Return error code 12302 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12303 } 12304 } 12305 } 12306 // All the special cases have been taken care of. 12307 // Return result based on recommended install location. 12308 if (onSd) { 12309 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12310 } 12311 return pkgLite.recommendedInstallLocation; 12312 } 12313 12314 /* 12315 * Invoke remote method to get package information and install 12316 * location values. Override install location based on default 12317 * policy if needed and then create install arguments based 12318 * on the install location. 12319 */ 12320 public void handleStartCopy() throws RemoteException { 12321 int ret = PackageManager.INSTALL_SUCCEEDED; 12322 12323 // If we're already staged, we've firmly committed to an install location 12324 if (origin.staged) { 12325 if (origin.file != null) { 12326 installFlags |= PackageManager.INSTALL_INTERNAL; 12327 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12328 } else if (origin.cid != null) { 12329 installFlags |= PackageManager.INSTALL_EXTERNAL; 12330 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12331 } else { 12332 throw new IllegalStateException("Invalid stage location"); 12333 } 12334 } 12335 12336 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12337 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12338 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12339 PackageInfoLite pkgLite = null; 12340 12341 if (onInt && onSd) { 12342 // Check if both bits are set. 12343 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12344 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12345 } else if (onSd && ephemeral) { 12346 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12347 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12348 } else { 12349 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12350 packageAbiOverride); 12351 12352 if (DEBUG_EPHEMERAL && ephemeral) { 12353 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12354 } 12355 12356 /* 12357 * If we have too little free space, try to free cache 12358 * before giving up. 12359 */ 12360 if (!origin.staged && pkgLite.recommendedInstallLocation 12361 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12362 // TODO: focus freeing disk space on the target device 12363 final StorageManager storage = StorageManager.from(mContext); 12364 final long lowThreshold = storage.getStorageLowBytes( 12365 Environment.getDataDirectory()); 12366 12367 final long sizeBytes = mContainerService.calculateInstalledSize( 12368 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12369 12370 try { 12371 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12372 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12373 installFlags, packageAbiOverride); 12374 } catch (InstallerException e) { 12375 Slog.w(TAG, "Failed to free cache", e); 12376 } 12377 12378 /* 12379 * The cache free must have deleted the file we 12380 * downloaded to install. 12381 * 12382 * TODO: fix the "freeCache" call to not delete 12383 * the file we care about. 12384 */ 12385 if (pkgLite.recommendedInstallLocation 12386 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12387 pkgLite.recommendedInstallLocation 12388 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12389 } 12390 } 12391 } 12392 12393 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12394 int loc = pkgLite.recommendedInstallLocation; 12395 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12396 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12397 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12398 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12399 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12400 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12401 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12402 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12403 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12404 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12405 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12406 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12407 } else { 12408 // Override with defaults if needed. 12409 loc = installLocationPolicy(pkgLite); 12410 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12411 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12412 } else if (!onSd && !onInt) { 12413 // Override install location with flags 12414 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12415 // Set the flag to install on external media. 12416 installFlags |= PackageManager.INSTALL_EXTERNAL; 12417 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12418 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12419 if (DEBUG_EPHEMERAL) { 12420 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12421 } 12422 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12423 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12424 |PackageManager.INSTALL_INTERNAL); 12425 } else { 12426 // Make sure the flag for installing on external 12427 // media is unset 12428 installFlags |= PackageManager.INSTALL_INTERNAL; 12429 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12430 } 12431 } 12432 } 12433 } 12434 12435 final InstallArgs args = createInstallArgs(this); 12436 mArgs = args; 12437 12438 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12439 // TODO: http://b/22976637 12440 // Apps installed for "all" users use the device owner to verify the app 12441 UserHandle verifierUser = getUser(); 12442 if (verifierUser == UserHandle.ALL) { 12443 verifierUser = UserHandle.SYSTEM; 12444 } 12445 12446 /* 12447 * Determine if we have any installed package verifiers. If we 12448 * do, then we'll defer to them to verify the packages. 12449 */ 12450 final int requiredUid = mRequiredVerifierPackage == null ? -1 12451 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12452 verifierUser.getIdentifier()); 12453 if (!origin.existing && requiredUid != -1 12454 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12455 final Intent verification = new Intent( 12456 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12457 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12458 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12459 PACKAGE_MIME_TYPE); 12460 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12461 12462 // Query all live verifiers based on current user state 12463 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12464 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12465 12466 if (DEBUG_VERIFY) { 12467 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12468 + verification.toString() + " with " + pkgLite.verifiers.length 12469 + " optional verifiers"); 12470 } 12471 12472 final int verificationId = mPendingVerificationToken++; 12473 12474 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12475 12476 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12477 installerPackageName); 12478 12479 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12480 installFlags); 12481 12482 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12483 pkgLite.packageName); 12484 12485 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12486 pkgLite.versionCode); 12487 12488 if (verificationInfo != null) { 12489 if (verificationInfo.originatingUri != null) { 12490 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12491 verificationInfo.originatingUri); 12492 } 12493 if (verificationInfo.referrer != null) { 12494 verification.putExtra(Intent.EXTRA_REFERRER, 12495 verificationInfo.referrer); 12496 } 12497 if (verificationInfo.originatingUid >= 0) { 12498 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12499 verificationInfo.originatingUid); 12500 } 12501 if (verificationInfo.installerUid >= 0) { 12502 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12503 verificationInfo.installerUid); 12504 } 12505 } 12506 12507 final PackageVerificationState verificationState = new PackageVerificationState( 12508 requiredUid, args); 12509 12510 mPendingVerification.append(verificationId, verificationState); 12511 12512 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12513 receivers, verificationState); 12514 12515 /* 12516 * If any sufficient verifiers were listed in the package 12517 * manifest, attempt to ask them. 12518 */ 12519 if (sufficientVerifiers != null) { 12520 final int N = sufficientVerifiers.size(); 12521 if (N == 0) { 12522 Slog.i(TAG, "Additional verifiers required, but none installed."); 12523 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12524 } else { 12525 for (int i = 0; i < N; i++) { 12526 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12527 12528 final Intent sufficientIntent = new Intent(verification); 12529 sufficientIntent.setComponent(verifierComponent); 12530 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12531 } 12532 } 12533 } 12534 12535 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12536 mRequiredVerifierPackage, receivers); 12537 if (ret == PackageManager.INSTALL_SUCCEEDED 12538 && mRequiredVerifierPackage != null) { 12539 Trace.asyncTraceBegin( 12540 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12541 /* 12542 * Send the intent to the required verification agent, 12543 * but only start the verification timeout after the 12544 * target BroadcastReceivers have run. 12545 */ 12546 verification.setComponent(requiredVerifierComponent); 12547 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12548 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12549 new BroadcastReceiver() { 12550 @Override 12551 public void onReceive(Context context, Intent intent) { 12552 final Message msg = mHandler 12553 .obtainMessage(CHECK_PENDING_VERIFICATION); 12554 msg.arg1 = verificationId; 12555 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12556 } 12557 }, null, 0, null, null); 12558 12559 /* 12560 * We don't want the copy to proceed until verification 12561 * succeeds, so null out this field. 12562 */ 12563 mArgs = null; 12564 } 12565 } else { 12566 /* 12567 * No package verification is enabled, so immediately start 12568 * the remote call to initiate copy using temporary file. 12569 */ 12570 ret = args.copyApk(mContainerService, true); 12571 } 12572 } 12573 12574 mRet = ret; 12575 } 12576 12577 @Override 12578 void handleReturnCode() { 12579 // If mArgs is null, then MCS couldn't be reached. When it 12580 // reconnects, it will try again to install. At that point, this 12581 // will succeed. 12582 if (mArgs != null) { 12583 processPendingInstall(mArgs, mRet); 12584 } 12585 } 12586 12587 @Override 12588 void handleServiceError() { 12589 mArgs = createInstallArgs(this); 12590 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12591 } 12592 12593 public boolean isForwardLocked() { 12594 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12595 } 12596 } 12597 12598 /** 12599 * Used during creation of InstallArgs 12600 * 12601 * @param installFlags package installation flags 12602 * @return true if should be installed on external storage 12603 */ 12604 private static boolean installOnExternalAsec(int installFlags) { 12605 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12606 return false; 12607 } 12608 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12609 return true; 12610 } 12611 return false; 12612 } 12613 12614 /** 12615 * Used during creation of InstallArgs 12616 * 12617 * @param installFlags package installation flags 12618 * @return true if should be installed as forward locked 12619 */ 12620 private static boolean installForwardLocked(int installFlags) { 12621 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12622 } 12623 12624 private InstallArgs createInstallArgs(InstallParams params) { 12625 if (params.move != null) { 12626 return new MoveInstallArgs(params); 12627 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12628 return new AsecInstallArgs(params); 12629 } else { 12630 return new FileInstallArgs(params); 12631 } 12632 } 12633 12634 /** 12635 * Create args that describe an existing installed package. Typically used 12636 * when cleaning up old installs, or used as a move source. 12637 */ 12638 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12639 String resourcePath, String[] instructionSets) { 12640 final boolean isInAsec; 12641 if (installOnExternalAsec(installFlags)) { 12642 /* Apps on SD card are always in ASEC containers. */ 12643 isInAsec = true; 12644 } else if (installForwardLocked(installFlags) 12645 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12646 /* 12647 * Forward-locked apps are only in ASEC containers if they're the 12648 * new style 12649 */ 12650 isInAsec = true; 12651 } else { 12652 isInAsec = false; 12653 } 12654 12655 if (isInAsec) { 12656 return new AsecInstallArgs(codePath, instructionSets, 12657 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12658 } else { 12659 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12660 } 12661 } 12662 12663 static abstract class InstallArgs { 12664 /** @see InstallParams#origin */ 12665 final OriginInfo origin; 12666 /** @see InstallParams#move */ 12667 final MoveInfo move; 12668 12669 final IPackageInstallObserver2 observer; 12670 // Always refers to PackageManager flags only 12671 final int installFlags; 12672 final String installerPackageName; 12673 final String volumeUuid; 12674 final UserHandle user; 12675 final String abiOverride; 12676 final String[] installGrantPermissions; 12677 /** If non-null, drop an async trace when the install completes */ 12678 final String traceMethod; 12679 final int traceCookie; 12680 final Certificate[][] certificates; 12681 12682 // The list of instruction sets supported by this app. This is currently 12683 // only used during the rmdex() phase to clean up resources. We can get rid of this 12684 // if we move dex files under the common app path. 12685 /* nullable */ String[] instructionSets; 12686 12687 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12688 int installFlags, String installerPackageName, String volumeUuid, 12689 UserHandle user, String[] instructionSets, 12690 String abiOverride, String[] installGrantPermissions, 12691 String traceMethod, int traceCookie, Certificate[][] certificates) { 12692 this.origin = origin; 12693 this.move = move; 12694 this.installFlags = installFlags; 12695 this.observer = observer; 12696 this.installerPackageName = installerPackageName; 12697 this.volumeUuid = volumeUuid; 12698 this.user = user; 12699 this.instructionSets = instructionSets; 12700 this.abiOverride = abiOverride; 12701 this.installGrantPermissions = installGrantPermissions; 12702 this.traceMethod = traceMethod; 12703 this.traceCookie = traceCookie; 12704 this.certificates = certificates; 12705 } 12706 12707 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12708 abstract int doPreInstall(int status); 12709 12710 /** 12711 * Rename package into final resting place. All paths on the given 12712 * scanned package should be updated to reflect the rename. 12713 */ 12714 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12715 abstract int doPostInstall(int status, int uid); 12716 12717 /** @see PackageSettingBase#codePathString */ 12718 abstract String getCodePath(); 12719 /** @see PackageSettingBase#resourcePathString */ 12720 abstract String getResourcePath(); 12721 12722 // Need installer lock especially for dex file removal. 12723 abstract void cleanUpResourcesLI(); 12724 abstract boolean doPostDeleteLI(boolean delete); 12725 12726 /** 12727 * Called before the source arguments are copied. This is used mostly 12728 * for MoveParams when it needs to read the source file to put it in the 12729 * destination. 12730 */ 12731 int doPreCopy() { 12732 return PackageManager.INSTALL_SUCCEEDED; 12733 } 12734 12735 /** 12736 * Called after the source arguments are copied. This is used mostly for 12737 * MoveParams when it needs to read the source file to put it in the 12738 * destination. 12739 */ 12740 int doPostCopy(int uid) { 12741 return PackageManager.INSTALL_SUCCEEDED; 12742 } 12743 12744 protected boolean isFwdLocked() { 12745 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12746 } 12747 12748 protected boolean isExternalAsec() { 12749 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12750 } 12751 12752 protected boolean isEphemeral() { 12753 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12754 } 12755 12756 UserHandle getUser() { 12757 return user; 12758 } 12759 } 12760 12761 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12762 if (!allCodePaths.isEmpty()) { 12763 if (instructionSets == null) { 12764 throw new IllegalStateException("instructionSet == null"); 12765 } 12766 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12767 for (String codePath : allCodePaths) { 12768 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12769 try { 12770 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12771 } catch (InstallerException ignored) { 12772 } 12773 } 12774 } 12775 } 12776 } 12777 12778 /** 12779 * Logic to handle installation of non-ASEC applications, including copying 12780 * and renaming logic. 12781 */ 12782 class FileInstallArgs extends InstallArgs { 12783 private File codeFile; 12784 private File resourceFile; 12785 12786 // Example topology: 12787 // /data/app/com.example/base.apk 12788 // /data/app/com.example/split_foo.apk 12789 // /data/app/com.example/lib/arm/libfoo.so 12790 // /data/app/com.example/lib/arm64/libfoo.so 12791 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12792 12793 /** New install */ 12794 FileInstallArgs(InstallParams params) { 12795 super(params.origin, params.move, params.observer, params.installFlags, 12796 params.installerPackageName, params.volumeUuid, 12797 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12798 params.grantedRuntimePermissions, 12799 params.traceMethod, params.traceCookie, params.certificates); 12800 if (isFwdLocked()) { 12801 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12802 } 12803 } 12804 12805 /** Existing install */ 12806 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12807 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12808 null, null, null, 0, null /*certificates*/); 12809 this.codeFile = (codePath != null) ? new File(codePath) : null; 12810 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12811 } 12812 12813 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12814 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12815 try { 12816 return doCopyApk(imcs, temp); 12817 } finally { 12818 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12819 } 12820 } 12821 12822 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12823 if (origin.staged) { 12824 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12825 codeFile = origin.file; 12826 resourceFile = origin.file; 12827 return PackageManager.INSTALL_SUCCEEDED; 12828 } 12829 12830 try { 12831 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12832 final File tempDir = 12833 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12834 codeFile = tempDir; 12835 resourceFile = tempDir; 12836 } catch (IOException e) { 12837 Slog.w(TAG, "Failed to create copy file: " + e); 12838 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12839 } 12840 12841 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12842 @Override 12843 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12844 if (!FileUtils.isValidExtFilename(name)) { 12845 throw new IllegalArgumentException("Invalid filename: " + name); 12846 } 12847 try { 12848 final File file = new File(codeFile, name); 12849 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 12850 O_RDWR | O_CREAT, 0644); 12851 Os.chmod(file.getAbsolutePath(), 0644); 12852 return new ParcelFileDescriptor(fd); 12853 } catch (ErrnoException e) { 12854 throw new RemoteException("Failed to open: " + e.getMessage()); 12855 } 12856 } 12857 }; 12858 12859 int ret = PackageManager.INSTALL_SUCCEEDED; 12860 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 12861 if (ret != PackageManager.INSTALL_SUCCEEDED) { 12862 Slog.e(TAG, "Failed to copy package"); 12863 return ret; 12864 } 12865 12866 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 12867 NativeLibraryHelper.Handle handle = null; 12868 try { 12869 handle = NativeLibraryHelper.Handle.create(codeFile); 12870 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 12871 abiOverride); 12872 } catch (IOException e) { 12873 Slog.e(TAG, "Copying native libraries failed", e); 12874 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12875 } finally { 12876 IoUtils.closeQuietly(handle); 12877 } 12878 12879 return ret; 12880 } 12881 12882 int doPreInstall(int status) { 12883 if (status != PackageManager.INSTALL_SUCCEEDED) { 12884 cleanUp(); 12885 } 12886 return status; 12887 } 12888 12889 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 12890 if (status != PackageManager.INSTALL_SUCCEEDED) { 12891 cleanUp(); 12892 return false; 12893 } 12894 12895 final File targetDir = codeFile.getParentFile(); 12896 final File beforeCodeFile = codeFile; 12897 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 12898 12899 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 12900 try { 12901 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 12902 } catch (ErrnoException e) { 12903 Slog.w(TAG, "Failed to rename", e); 12904 return false; 12905 } 12906 12907 if (!SELinux.restoreconRecursive(afterCodeFile)) { 12908 Slog.w(TAG, "Failed to restorecon"); 12909 return false; 12910 } 12911 12912 // Reflect the rename internally 12913 codeFile = afterCodeFile; 12914 resourceFile = afterCodeFile; 12915 12916 // Reflect the rename in scanned details 12917 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 12918 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 12919 afterCodeFile, pkg.baseCodePath)); 12920 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 12921 afterCodeFile, pkg.splitCodePaths)); 12922 12923 // Reflect the rename in app info 12924 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 12925 pkg.setApplicationInfoCodePath(pkg.codePath); 12926 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 12927 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 12928 pkg.setApplicationInfoResourcePath(pkg.codePath); 12929 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 12930 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 12931 12932 return true; 12933 } 12934 12935 int doPostInstall(int status, int uid) { 12936 if (status != PackageManager.INSTALL_SUCCEEDED) { 12937 cleanUp(); 12938 } 12939 return status; 12940 } 12941 12942 @Override 12943 String getCodePath() { 12944 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 12945 } 12946 12947 @Override 12948 String getResourcePath() { 12949 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 12950 } 12951 12952 private boolean cleanUp() { 12953 if (codeFile == null || !codeFile.exists()) { 12954 return false; 12955 } 12956 12957 removeCodePathLI(codeFile); 12958 12959 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 12960 resourceFile.delete(); 12961 } 12962 12963 return true; 12964 } 12965 12966 void cleanUpResourcesLI() { 12967 // Try enumerating all code paths before deleting 12968 List<String> allCodePaths = Collections.EMPTY_LIST; 12969 if (codeFile != null && codeFile.exists()) { 12970 try { 12971 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 12972 allCodePaths = pkg.getAllCodePaths(); 12973 } catch (PackageParserException e) { 12974 // Ignored; we tried our best 12975 } 12976 } 12977 12978 cleanUp(); 12979 removeDexFiles(allCodePaths, instructionSets); 12980 } 12981 12982 boolean doPostDeleteLI(boolean delete) { 12983 // XXX err, shouldn't we respect the delete flag? 12984 cleanUpResourcesLI(); 12985 return true; 12986 } 12987 } 12988 12989 private boolean isAsecExternal(String cid) { 12990 final String asecPath = PackageHelper.getSdFilesystem(cid); 12991 return !asecPath.startsWith(mAsecInternalPath); 12992 } 12993 12994 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 12995 PackageManagerException { 12996 if (copyRet < 0) { 12997 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 12998 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 12999 throw new PackageManagerException(copyRet, message); 13000 } 13001 } 13002 } 13003 13004 /** 13005 * Extract the MountService "container ID" from the full code path of an 13006 * .apk. 13007 */ 13008 static String cidFromCodePath(String fullCodePath) { 13009 int eidx = fullCodePath.lastIndexOf("/"); 13010 String subStr1 = fullCodePath.substring(0, eidx); 13011 int sidx = subStr1.lastIndexOf("/"); 13012 return subStr1.substring(sidx+1, eidx); 13013 } 13014 13015 /** 13016 * Logic to handle installation of ASEC applications, including copying and 13017 * renaming logic. 13018 */ 13019 class AsecInstallArgs extends InstallArgs { 13020 static final String RES_FILE_NAME = "pkg.apk"; 13021 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13022 13023 String cid; 13024 String packagePath; 13025 String resourcePath; 13026 13027 /** New install */ 13028 AsecInstallArgs(InstallParams params) { 13029 super(params.origin, params.move, params.observer, params.installFlags, 13030 params.installerPackageName, params.volumeUuid, 13031 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13032 params.grantedRuntimePermissions, 13033 params.traceMethod, params.traceCookie, params.certificates); 13034 } 13035 13036 /** Existing install */ 13037 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13038 boolean isExternal, boolean isForwardLocked) { 13039 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13040 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13041 instructionSets, null, null, null, 0, null /*certificates*/); 13042 // Hackily pretend we're still looking at a full code path 13043 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13044 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13045 } 13046 13047 // Extract cid from fullCodePath 13048 int eidx = fullCodePath.lastIndexOf("/"); 13049 String subStr1 = fullCodePath.substring(0, eidx); 13050 int sidx = subStr1.lastIndexOf("/"); 13051 cid = subStr1.substring(sidx+1, eidx); 13052 setMountPath(subStr1); 13053 } 13054 13055 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13056 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13057 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13058 instructionSets, null, null, null, 0, null /*certificates*/); 13059 this.cid = cid; 13060 setMountPath(PackageHelper.getSdDir(cid)); 13061 } 13062 13063 void createCopyFile() { 13064 cid = mInstallerService.allocateExternalStageCidLegacy(); 13065 } 13066 13067 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13068 if (origin.staged && origin.cid != null) { 13069 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13070 cid = origin.cid; 13071 setMountPath(PackageHelper.getSdDir(cid)); 13072 return PackageManager.INSTALL_SUCCEEDED; 13073 } 13074 13075 if (temp) { 13076 createCopyFile(); 13077 } else { 13078 /* 13079 * Pre-emptively destroy the container since it's destroyed if 13080 * copying fails due to it existing anyway. 13081 */ 13082 PackageHelper.destroySdDir(cid); 13083 } 13084 13085 final String newMountPath = imcs.copyPackageToContainer( 13086 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13087 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13088 13089 if (newMountPath != null) { 13090 setMountPath(newMountPath); 13091 return PackageManager.INSTALL_SUCCEEDED; 13092 } else { 13093 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13094 } 13095 } 13096 13097 @Override 13098 String getCodePath() { 13099 return packagePath; 13100 } 13101 13102 @Override 13103 String getResourcePath() { 13104 return resourcePath; 13105 } 13106 13107 int doPreInstall(int status) { 13108 if (status != PackageManager.INSTALL_SUCCEEDED) { 13109 // Destroy container 13110 PackageHelper.destroySdDir(cid); 13111 } else { 13112 boolean mounted = PackageHelper.isContainerMounted(cid); 13113 if (!mounted) { 13114 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13115 Process.SYSTEM_UID); 13116 if (newMountPath != null) { 13117 setMountPath(newMountPath); 13118 } else { 13119 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13120 } 13121 } 13122 } 13123 return status; 13124 } 13125 13126 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13127 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13128 String newMountPath = null; 13129 if (PackageHelper.isContainerMounted(cid)) { 13130 // Unmount the container 13131 if (!PackageHelper.unMountSdDir(cid)) { 13132 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13133 return false; 13134 } 13135 } 13136 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13137 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13138 " which might be stale. Will try to clean up."); 13139 // Clean up the stale container and proceed to recreate. 13140 if (!PackageHelper.destroySdDir(newCacheId)) { 13141 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13142 return false; 13143 } 13144 // Successfully cleaned up stale container. Try to rename again. 13145 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13146 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13147 + " inspite of cleaning it up."); 13148 return false; 13149 } 13150 } 13151 if (!PackageHelper.isContainerMounted(newCacheId)) { 13152 Slog.w(TAG, "Mounting container " + newCacheId); 13153 newMountPath = PackageHelper.mountSdDir(newCacheId, 13154 getEncryptKey(), Process.SYSTEM_UID); 13155 } else { 13156 newMountPath = PackageHelper.getSdDir(newCacheId); 13157 } 13158 if (newMountPath == null) { 13159 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13160 return false; 13161 } 13162 Log.i(TAG, "Succesfully renamed " + cid + 13163 " to " + newCacheId + 13164 " at new path: " + newMountPath); 13165 cid = newCacheId; 13166 13167 final File beforeCodeFile = new File(packagePath); 13168 setMountPath(newMountPath); 13169 final File afterCodeFile = new File(packagePath); 13170 13171 // Reflect the rename in scanned details 13172 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13173 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13174 afterCodeFile, pkg.baseCodePath)); 13175 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13176 afterCodeFile, pkg.splitCodePaths)); 13177 13178 // Reflect the rename in app info 13179 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13180 pkg.setApplicationInfoCodePath(pkg.codePath); 13181 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13182 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13183 pkg.setApplicationInfoResourcePath(pkg.codePath); 13184 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13185 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13186 13187 return true; 13188 } 13189 13190 private void setMountPath(String mountPath) { 13191 final File mountFile = new File(mountPath); 13192 13193 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13194 if (monolithicFile.exists()) { 13195 packagePath = monolithicFile.getAbsolutePath(); 13196 if (isFwdLocked()) { 13197 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13198 } else { 13199 resourcePath = packagePath; 13200 } 13201 } else { 13202 packagePath = mountFile.getAbsolutePath(); 13203 resourcePath = packagePath; 13204 } 13205 } 13206 13207 int doPostInstall(int status, int uid) { 13208 if (status != PackageManager.INSTALL_SUCCEEDED) { 13209 cleanUp(); 13210 } else { 13211 final int groupOwner; 13212 final String protectedFile; 13213 if (isFwdLocked()) { 13214 groupOwner = UserHandle.getSharedAppGid(uid); 13215 protectedFile = RES_FILE_NAME; 13216 } else { 13217 groupOwner = -1; 13218 protectedFile = null; 13219 } 13220 13221 if (uid < Process.FIRST_APPLICATION_UID 13222 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13223 Slog.e(TAG, "Failed to finalize " + cid); 13224 PackageHelper.destroySdDir(cid); 13225 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13226 } 13227 13228 boolean mounted = PackageHelper.isContainerMounted(cid); 13229 if (!mounted) { 13230 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13231 } 13232 } 13233 return status; 13234 } 13235 13236 private void cleanUp() { 13237 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13238 13239 // Destroy secure container 13240 PackageHelper.destroySdDir(cid); 13241 } 13242 13243 private List<String> getAllCodePaths() { 13244 final File codeFile = new File(getCodePath()); 13245 if (codeFile != null && codeFile.exists()) { 13246 try { 13247 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13248 return pkg.getAllCodePaths(); 13249 } catch (PackageParserException e) { 13250 // Ignored; we tried our best 13251 } 13252 } 13253 return Collections.EMPTY_LIST; 13254 } 13255 13256 void cleanUpResourcesLI() { 13257 // Enumerate all code paths before deleting 13258 cleanUpResourcesLI(getAllCodePaths()); 13259 } 13260 13261 private void cleanUpResourcesLI(List<String> allCodePaths) { 13262 cleanUp(); 13263 removeDexFiles(allCodePaths, instructionSets); 13264 } 13265 13266 String getPackageName() { 13267 return getAsecPackageName(cid); 13268 } 13269 13270 boolean doPostDeleteLI(boolean delete) { 13271 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13272 final List<String> allCodePaths = getAllCodePaths(); 13273 boolean mounted = PackageHelper.isContainerMounted(cid); 13274 if (mounted) { 13275 // Unmount first 13276 if (PackageHelper.unMountSdDir(cid)) { 13277 mounted = false; 13278 } 13279 } 13280 if (!mounted && delete) { 13281 cleanUpResourcesLI(allCodePaths); 13282 } 13283 return !mounted; 13284 } 13285 13286 @Override 13287 int doPreCopy() { 13288 if (isFwdLocked()) { 13289 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13290 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13291 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13292 } 13293 } 13294 13295 return PackageManager.INSTALL_SUCCEEDED; 13296 } 13297 13298 @Override 13299 int doPostCopy(int uid) { 13300 if (isFwdLocked()) { 13301 if (uid < Process.FIRST_APPLICATION_UID 13302 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13303 RES_FILE_NAME)) { 13304 Slog.e(TAG, "Failed to finalize " + cid); 13305 PackageHelper.destroySdDir(cid); 13306 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13307 } 13308 } 13309 13310 return PackageManager.INSTALL_SUCCEEDED; 13311 } 13312 } 13313 13314 /** 13315 * Logic to handle movement of existing installed applications. 13316 */ 13317 class MoveInstallArgs extends InstallArgs { 13318 private File codeFile; 13319 private File resourceFile; 13320 13321 /** New install */ 13322 MoveInstallArgs(InstallParams params) { 13323 super(params.origin, params.move, params.observer, params.installFlags, 13324 params.installerPackageName, params.volumeUuid, 13325 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13326 params.grantedRuntimePermissions, 13327 params.traceMethod, params.traceCookie, params.certificates); 13328 } 13329 13330 int copyApk(IMediaContainerService imcs, boolean temp) { 13331 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13332 + move.fromUuid + " to " + move.toUuid); 13333 synchronized (mInstaller) { 13334 try { 13335 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13336 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13337 } catch (InstallerException e) { 13338 Slog.w(TAG, "Failed to move app", e); 13339 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13340 } 13341 } 13342 13343 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13344 resourceFile = codeFile; 13345 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13346 13347 return PackageManager.INSTALL_SUCCEEDED; 13348 } 13349 13350 int doPreInstall(int status) { 13351 if (status != PackageManager.INSTALL_SUCCEEDED) { 13352 cleanUp(move.toUuid); 13353 } 13354 return status; 13355 } 13356 13357 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13358 if (status != PackageManager.INSTALL_SUCCEEDED) { 13359 cleanUp(move.toUuid); 13360 return false; 13361 } 13362 13363 // Reflect the move in app info 13364 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13365 pkg.setApplicationInfoCodePath(pkg.codePath); 13366 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13367 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13368 pkg.setApplicationInfoResourcePath(pkg.codePath); 13369 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13370 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13371 13372 return true; 13373 } 13374 13375 int doPostInstall(int status, int uid) { 13376 if (status == PackageManager.INSTALL_SUCCEEDED) { 13377 cleanUp(move.fromUuid); 13378 } else { 13379 cleanUp(move.toUuid); 13380 } 13381 return status; 13382 } 13383 13384 @Override 13385 String getCodePath() { 13386 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13387 } 13388 13389 @Override 13390 String getResourcePath() { 13391 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13392 } 13393 13394 private boolean cleanUp(String volumeUuid) { 13395 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13396 move.dataAppName); 13397 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13398 synchronized (mInstallLock) { 13399 // Clean up both app data and code 13400 // All package moves are frozen until finished 13401 try { 13402 mInstaller.destroyAppData(volumeUuid, move.packageName, UserHandle.USER_ALL, 13403 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13404 } catch (InstallerException e) { 13405 Slog.w(TAG, String.valueOf(e)); 13406 } 13407 removeCodePathLI(codeFile); 13408 } 13409 return true; 13410 } 13411 13412 void cleanUpResourcesLI() { 13413 throw new UnsupportedOperationException(); 13414 } 13415 13416 boolean doPostDeleteLI(boolean delete) { 13417 throw new UnsupportedOperationException(); 13418 } 13419 } 13420 13421 static String getAsecPackageName(String packageCid) { 13422 int idx = packageCid.lastIndexOf("-"); 13423 if (idx == -1) { 13424 return packageCid; 13425 } 13426 return packageCid.substring(0, idx); 13427 } 13428 13429 // Utility method used to create code paths based on package name and available index. 13430 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13431 String idxStr = ""; 13432 int idx = 1; 13433 // Fall back to default value of idx=1 if prefix is not 13434 // part of oldCodePath 13435 if (oldCodePath != null) { 13436 String subStr = oldCodePath; 13437 // Drop the suffix right away 13438 if (suffix != null && subStr.endsWith(suffix)) { 13439 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13440 } 13441 // If oldCodePath already contains prefix find out the 13442 // ending index to either increment or decrement. 13443 int sidx = subStr.lastIndexOf(prefix); 13444 if (sidx != -1) { 13445 subStr = subStr.substring(sidx + prefix.length()); 13446 if (subStr != null) { 13447 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13448 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13449 } 13450 try { 13451 idx = Integer.parseInt(subStr); 13452 if (idx <= 1) { 13453 idx++; 13454 } else { 13455 idx--; 13456 } 13457 } catch(NumberFormatException e) { 13458 } 13459 } 13460 } 13461 } 13462 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13463 return prefix + idxStr; 13464 } 13465 13466 private File getNextCodePath(File targetDir, String packageName) { 13467 int suffix = 1; 13468 File result; 13469 do { 13470 result = new File(targetDir, packageName + "-" + suffix); 13471 suffix++; 13472 } while (result.exists()); 13473 return result; 13474 } 13475 13476 // Utility method that returns the relative package path with respect 13477 // to the installation directory. Like say for /data/data/com.test-1.apk 13478 // string com.test-1 is returned. 13479 static String deriveCodePathName(String codePath) { 13480 if (codePath == null) { 13481 return null; 13482 } 13483 final File codeFile = new File(codePath); 13484 final String name = codeFile.getName(); 13485 if (codeFile.isDirectory()) { 13486 return name; 13487 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13488 final int lastDot = name.lastIndexOf('.'); 13489 return name.substring(0, lastDot); 13490 } else { 13491 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13492 return null; 13493 } 13494 } 13495 13496 static class PackageInstalledInfo { 13497 String name; 13498 int uid; 13499 // The set of users that originally had this package installed. 13500 int[] origUsers; 13501 // The set of users that now have this package installed. 13502 int[] newUsers; 13503 PackageParser.Package pkg; 13504 int returnCode; 13505 String returnMsg; 13506 PackageRemovedInfo removedInfo; 13507 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13508 13509 public void setError(int code, String msg) { 13510 setReturnCode(code); 13511 setReturnMessage(msg); 13512 Slog.w(TAG, msg); 13513 } 13514 13515 public void setError(String msg, PackageParserException e) { 13516 setReturnCode(e.error); 13517 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13518 Slog.w(TAG, msg, e); 13519 } 13520 13521 public void setError(String msg, PackageManagerException e) { 13522 returnCode = e.error; 13523 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13524 Slog.w(TAG, msg, e); 13525 } 13526 13527 public void setReturnCode(int returnCode) { 13528 this.returnCode = returnCode; 13529 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13530 for (int i = 0; i < childCount; i++) { 13531 addedChildPackages.valueAt(i).returnCode = returnCode; 13532 } 13533 } 13534 13535 private void setReturnMessage(String returnMsg) { 13536 this.returnMsg = returnMsg; 13537 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13538 for (int i = 0; i < childCount; i++) { 13539 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13540 } 13541 } 13542 13543 // In some error cases we want to convey more info back to the observer 13544 String origPackage; 13545 String origPermission; 13546 } 13547 13548 /* 13549 * Install a non-existing package. 13550 */ 13551 private void installNewPackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13552 UserHandle user, String installerPackageName, String volumeUuid, 13553 PackageInstalledInfo res) { 13554 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13555 13556 // Remember this for later, in case we need to rollback this install 13557 String pkgName = pkg.packageName; 13558 13559 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13560 13561 synchronized(mPackages) { 13562 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13563 // A package with the same name is already installed, though 13564 // it has been renamed to an older name. The package we 13565 // are trying to install should be installed as an update to 13566 // the existing one, but that has not been requested, so bail. 13567 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13568 + " without first uninstalling package running as " 13569 + mSettings.mRenamedPackages.get(pkgName)); 13570 return; 13571 } 13572 if (mPackages.containsKey(pkgName)) { 13573 // Don't allow installation over an existing package with the same name. 13574 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13575 + " without first uninstalling."); 13576 return; 13577 } 13578 } 13579 13580 try { 13581 PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 13582 System.currentTimeMillis(), user); 13583 13584 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13585 13586 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13587 prepareAppDataAfterInstallLIF(newPackage); 13588 13589 } else { 13590 // Remove package from internal structures, but keep around any 13591 // data that might have already existed 13592 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13593 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13594 } 13595 } catch (PackageManagerException e) { 13596 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13597 } 13598 13599 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13600 } 13601 13602 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13603 // Can't rotate keys during boot or if sharedUser. 13604 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13605 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13606 return false; 13607 } 13608 // app is using upgradeKeySets; make sure all are valid 13609 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13610 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13611 for (int i = 0; i < upgradeKeySets.length; i++) { 13612 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13613 Slog.wtf(TAG, "Package " 13614 + (oldPs.name != null ? oldPs.name : "<null>") 13615 + " contains upgrade-key-set reference to unknown key-set: " 13616 + upgradeKeySets[i] 13617 + " reverting to signatures check."); 13618 return false; 13619 } 13620 } 13621 return true; 13622 } 13623 13624 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13625 // Upgrade keysets are being used. Determine if new package has a superset of the 13626 // required keys. 13627 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13628 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13629 for (int i = 0; i < upgradeKeySets.length; i++) { 13630 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13631 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13632 return true; 13633 } 13634 } 13635 return false; 13636 } 13637 13638 private void replacePackageLIF(PackageParser.Package pkg, int parseFlags, int scanFlags, 13639 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13640 final boolean isEphemeral = (parseFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13641 13642 final PackageParser.Package oldPackage; 13643 final String pkgName = pkg.packageName; 13644 final int[] allUsers; 13645 13646 // First find the old package info and check signatures 13647 synchronized(mPackages) { 13648 oldPackage = mPackages.get(pkgName); 13649 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13650 if (isEphemeral && !oldIsEphemeral) { 13651 // can't downgrade from full to ephemeral 13652 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13653 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13654 return; 13655 } 13656 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13657 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13658 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13659 if (!checkUpgradeKeySetLP(ps, pkg)) { 13660 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13661 "New package not signed by keys specified by upgrade-keysets: " 13662 + pkgName); 13663 return; 13664 } 13665 } else { 13666 // default to original signature matching 13667 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13668 != PackageManager.SIGNATURE_MATCH) { 13669 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13670 "New package has a different signature: " + pkgName); 13671 return; 13672 } 13673 } 13674 13675 // Check for shared user id changes 13676 String invalidPackageName = 13677 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13678 if (invalidPackageName != null) { 13679 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13680 "Package " + invalidPackageName + " tried to change user " 13681 + oldPackage.mSharedUserId); 13682 return; 13683 } 13684 13685 // In case of rollback, remember per-user/profile install state 13686 allUsers = sUserManager.getUserIds(); 13687 } 13688 13689 // Update what is removed 13690 res.removedInfo = new PackageRemovedInfo(); 13691 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13692 res.removedInfo.removedPackage = oldPackage.packageName; 13693 res.removedInfo.isUpdate = true; 13694 final int childCount = (oldPackage.childPackages != null) 13695 ? oldPackage.childPackages.size() : 0; 13696 for (int i = 0; i < childCount; i++) { 13697 boolean childPackageUpdated = false; 13698 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13699 if (res.addedChildPackages != null) { 13700 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13701 if (childRes != null) { 13702 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13703 childRes.removedInfo.removedPackage = childPkg.packageName; 13704 childRes.removedInfo.isUpdate = true; 13705 childPackageUpdated = true; 13706 } 13707 } 13708 if (!childPackageUpdated) { 13709 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13710 childRemovedRes.removedPackage = childPkg.packageName; 13711 childRemovedRes.isUpdate = false; 13712 childRemovedRes.dataRemoved = true; 13713 synchronized (mPackages) { 13714 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13715 if (childPs != null) { 13716 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13717 } 13718 } 13719 if (res.removedInfo.removedChildPackages == null) { 13720 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13721 } 13722 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13723 } 13724 } 13725 13726 boolean sysPkg = (isSystemApp(oldPackage)); 13727 if (sysPkg) { 13728 replaceSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13729 user, allUsers, installerPackageName, res); 13730 } else { 13731 replaceNonSystemPackageLIF(oldPackage, pkg, parseFlags, scanFlags, 13732 user, allUsers, installerPackageName, res); 13733 } 13734 } 13735 13736 public List<String> getPreviousCodePaths(String packageName) { 13737 final PackageSetting ps = mSettings.mPackages.get(packageName); 13738 final List<String> result = new ArrayList<String>(); 13739 if (ps != null && ps.oldCodePaths != null) { 13740 result.addAll(ps.oldCodePaths); 13741 } 13742 return result; 13743 } 13744 13745 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13746 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13747 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13748 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13749 + deletedPackage); 13750 13751 String pkgName = deletedPackage.packageName; 13752 boolean deletedPkg = true; 13753 boolean addedPkg = false; 13754 boolean updatedSettings = false; 13755 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13756 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13757 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13758 13759 final long origUpdateTime = (pkg.mExtras != null) 13760 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13761 13762 // First delete the existing package while retaining the data directory 13763 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13764 res.removedInfo, true, pkg)) { 13765 // If the existing package wasn't successfully deleted 13766 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13767 deletedPkg = false; 13768 } else { 13769 // Successfully deleted the old package; proceed with replace. 13770 13771 // If deleted package lived in a container, give users a chance to 13772 // relinquish resources before killing. 13773 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13774 if (DEBUG_INSTALL) { 13775 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13776 } 13777 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13778 final ArrayList<String> pkgList = new ArrayList<String>(1); 13779 pkgList.add(deletedPackage.applicationInfo.packageName); 13780 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13781 } 13782 13783 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13784 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13785 clearAppProfilesLIF(pkg); 13786 13787 try { 13788 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, parseFlags, 13789 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13790 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13791 13792 // Update the in-memory copy of the previous code paths. 13793 PackageSetting ps = mSettings.mPackages.get(pkgName); 13794 if (!killApp) { 13795 if (ps.oldCodePaths == null) { 13796 ps.oldCodePaths = new ArraySet<>(); 13797 } 13798 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13799 if (deletedPackage.splitCodePaths != null) { 13800 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13801 } 13802 } else { 13803 ps.oldCodePaths = null; 13804 } 13805 if (ps.childPackageNames != null) { 13806 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13807 final String childPkgName = ps.childPackageNames.get(i); 13808 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13809 childPs.oldCodePaths = ps.oldCodePaths; 13810 } 13811 } 13812 prepareAppDataAfterInstallLIF(newPackage); 13813 addedPkg = true; 13814 } catch (PackageManagerException e) { 13815 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13816 } 13817 } 13818 13819 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13820 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13821 13822 // Revert all internal state mutations and added folders for the failed install 13823 if (addedPkg) { 13824 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13825 res.removedInfo, true, null); 13826 } 13827 13828 // Restore the old package 13829 if (deletedPkg) { 13830 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13831 File restoreFile = new File(deletedPackage.codePath); 13832 // Parse old package 13833 boolean oldExternal = isExternal(deletedPackage); 13834 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13835 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13836 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13837 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13838 try { 13839 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 13840 null); 13841 } catch (PackageManagerException e) { 13842 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 13843 + e.getMessage()); 13844 return; 13845 } 13846 13847 synchronized (mPackages) { 13848 // Ensure the installer package name up to date 13849 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13850 13851 // Update permissions for restored package 13852 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13853 13854 mSettings.writeLPr(); 13855 } 13856 13857 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 13858 } 13859 } else { 13860 synchronized (mPackages) { 13861 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 13862 if (ps != null) { 13863 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 13864 if (res.removedInfo.removedChildPackages != null) { 13865 final int childCount = res.removedInfo.removedChildPackages.size(); 13866 // Iterate in reverse as we may modify the collection 13867 for (int i = childCount - 1; i >= 0; i--) { 13868 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 13869 if (res.addedChildPackages.containsKey(childPackageName)) { 13870 res.removedInfo.removedChildPackages.removeAt(i); 13871 } else { 13872 PackageRemovedInfo childInfo = res.removedInfo 13873 .removedChildPackages.valueAt(i); 13874 childInfo.removedForAllUsers = mPackages.get( 13875 childInfo.removedPackage) == null; 13876 } 13877 } 13878 } 13879 } 13880 } 13881 } 13882 } 13883 13884 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 13885 PackageParser.Package pkg, int parseFlags, int scanFlags, UserHandle user, 13886 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13887 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 13888 + ", old=" + deletedPackage); 13889 13890 final boolean disabledSystem; 13891 13892 // Set the system/privileged flags as needed 13893 parseFlags |= PackageParser.PARSE_IS_SYSTEM; 13894 if ((deletedPackage.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) 13895 != 0) { 13896 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 13897 } 13898 13899 // Remove existing system package 13900 removePackageLI(deletedPackage, true); 13901 13902 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 13903 if (!disabledSystem) { 13904 // We didn't need to disable the .apk as a current system package, 13905 // which means we are replacing another update that is already 13906 // installed. We need to make sure to delete the older one's .apk. 13907 res.removedInfo.args = createInstallArgsForExisting(0, 13908 deletedPackage.applicationInfo.getCodePath(), 13909 deletedPackage.applicationInfo.getResourcePath(), 13910 getAppDexInstructionSets(deletedPackage.applicationInfo)); 13911 } else { 13912 res.removedInfo.args = null; 13913 } 13914 13915 // Successfully disabled the old package. Now proceed with re-installation 13916 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13917 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13918 clearAppProfilesLIF(pkg); 13919 13920 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 13921 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 13922 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 13923 13924 PackageParser.Package newPackage = null; 13925 try { 13926 // Add the package to the internal data structures 13927 newPackage = scanPackageTracedLI(pkg, parseFlags, scanFlags, 0, user); 13928 13929 // Set the update and install times 13930 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 13931 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 13932 System.currentTimeMillis()); 13933 13934 // Update the package dynamic state if succeeded 13935 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13936 // Now that the install succeeded make sure we remove data 13937 // directories for any child package the update removed. 13938 final int deletedChildCount = (deletedPackage.childPackages != null) 13939 ? deletedPackage.childPackages.size() : 0; 13940 final int newChildCount = (newPackage.childPackages != null) 13941 ? newPackage.childPackages.size() : 0; 13942 for (int i = 0; i < deletedChildCount; i++) { 13943 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 13944 boolean childPackageDeleted = true; 13945 for (int j = 0; j < newChildCount; j++) { 13946 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 13947 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 13948 childPackageDeleted = false; 13949 break; 13950 } 13951 } 13952 if (childPackageDeleted) { 13953 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 13954 deletedChildPkg.packageName); 13955 if (ps != null && res.removedInfo.removedChildPackages != null) { 13956 PackageRemovedInfo removedChildRes = res.removedInfo 13957 .removedChildPackages.get(deletedChildPkg.packageName); 13958 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 13959 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 13960 } 13961 } 13962 } 13963 13964 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13965 prepareAppDataAfterInstallLIF(newPackage); 13966 } 13967 } catch (PackageManagerException e) { 13968 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 13969 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13970 } 13971 13972 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13973 // Re installation failed. Restore old information 13974 // Remove new pkg information 13975 if (newPackage != null) { 13976 removeInstalledPackageLI(newPackage, true); 13977 } 13978 // Add back the old system package 13979 try { 13980 scanPackageTracedLI(deletedPackage, parseFlags, SCAN_UPDATE_SIGNATURE, 0, user); 13981 } catch (PackageManagerException e) { 13982 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 13983 } 13984 13985 synchronized (mPackages) { 13986 if (disabledSystem) { 13987 enableSystemPackageLPw(deletedPackage); 13988 } 13989 13990 // Ensure the installer package name up to date 13991 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 13992 13993 // Update permissions for restored package 13994 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 13995 13996 mSettings.writeLPr(); 13997 } 13998 13999 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14000 + " after failed upgrade"); 14001 } 14002 } 14003 14004 /** 14005 * Checks whether the parent or any of the child packages have a change shared 14006 * user. For a package to be a valid update the shred users of the parent and 14007 * the children should match. We may later support changing child shared users. 14008 * @param oldPkg The updated package. 14009 * @param newPkg The update package. 14010 * @return The shared user that change between the versions. 14011 */ 14012 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14013 PackageParser.Package newPkg) { 14014 // Check parent shared user 14015 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14016 return newPkg.packageName; 14017 } 14018 // Check child shared users 14019 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14020 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14021 for (int i = 0; i < newChildCount; i++) { 14022 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14023 // If this child was present, did it have the same shared user? 14024 for (int j = 0; j < oldChildCount; j++) { 14025 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14026 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14027 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14028 return newChildPkg.packageName; 14029 } 14030 } 14031 } 14032 return null; 14033 } 14034 14035 private void removeNativeBinariesLI(PackageSetting ps) { 14036 // Remove the lib path for the parent package 14037 if (ps != null) { 14038 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14039 // Remove the lib path for the child packages 14040 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14041 for (int i = 0; i < childCount; i++) { 14042 PackageSetting childPs = null; 14043 synchronized (mPackages) { 14044 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14045 } 14046 if (childPs != null) { 14047 NativeLibraryHelper.removeNativeBinariesLI(childPs 14048 .legacyNativeLibraryPathString); 14049 } 14050 } 14051 } 14052 } 14053 14054 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14055 // Enable the parent package 14056 mSettings.enableSystemPackageLPw(pkg.packageName); 14057 // Enable the child packages 14058 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14059 for (int i = 0; i < childCount; i++) { 14060 PackageParser.Package childPkg = pkg.childPackages.get(i); 14061 mSettings.enableSystemPackageLPw(childPkg.packageName); 14062 } 14063 } 14064 14065 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14066 PackageParser.Package newPkg) { 14067 // Disable the parent package (parent always replaced) 14068 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14069 // Disable the child packages 14070 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14071 for (int i = 0; i < childCount; i++) { 14072 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14073 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14074 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14075 } 14076 return disabled; 14077 } 14078 14079 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14080 String installerPackageName) { 14081 // Enable the parent package 14082 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14083 // Enable the child packages 14084 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14085 for (int i = 0; i < childCount; i++) { 14086 PackageParser.Package childPkg = pkg.childPackages.get(i); 14087 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14088 } 14089 } 14090 14091 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14092 // Collect all used permissions in the UID 14093 ArraySet<String> usedPermissions = new ArraySet<>(); 14094 final int packageCount = su.packages.size(); 14095 for (int i = 0; i < packageCount; i++) { 14096 PackageSetting ps = su.packages.valueAt(i); 14097 if (ps.pkg == null) { 14098 continue; 14099 } 14100 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14101 for (int j = 0; j < requestedPermCount; j++) { 14102 String permission = ps.pkg.requestedPermissions.get(j); 14103 BasePermission bp = mSettings.mPermissions.get(permission); 14104 if (bp != null) { 14105 usedPermissions.add(permission); 14106 } 14107 } 14108 } 14109 14110 PermissionsState permissionsState = su.getPermissionsState(); 14111 // Prune install permissions 14112 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14113 final int installPermCount = installPermStates.size(); 14114 for (int i = installPermCount - 1; i >= 0; i--) { 14115 PermissionState permissionState = installPermStates.get(i); 14116 if (!usedPermissions.contains(permissionState.getName())) { 14117 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14118 if (bp != null) { 14119 permissionsState.revokeInstallPermission(bp); 14120 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14121 PackageManager.MASK_PERMISSION_FLAGS, 0); 14122 } 14123 } 14124 } 14125 14126 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14127 14128 // Prune runtime permissions 14129 for (int userId : allUserIds) { 14130 List<PermissionState> runtimePermStates = permissionsState 14131 .getRuntimePermissionStates(userId); 14132 final int runtimePermCount = runtimePermStates.size(); 14133 for (int i = runtimePermCount - 1; i >= 0; i--) { 14134 PermissionState permissionState = runtimePermStates.get(i); 14135 if (!usedPermissions.contains(permissionState.getName())) { 14136 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14137 if (bp != null) { 14138 permissionsState.revokeRuntimePermission(bp, userId); 14139 permissionsState.updatePermissionFlags(bp, userId, 14140 PackageManager.MASK_PERMISSION_FLAGS, 0); 14141 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14142 runtimePermissionChangedUserIds, userId); 14143 } 14144 } 14145 } 14146 } 14147 14148 return runtimePermissionChangedUserIds; 14149 } 14150 14151 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14152 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14153 // Update the parent package setting 14154 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14155 res, user); 14156 // Update the child packages setting 14157 final int childCount = (newPackage.childPackages != null) 14158 ? newPackage.childPackages.size() : 0; 14159 for (int i = 0; i < childCount; i++) { 14160 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14161 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14162 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14163 childRes.origUsers, childRes, user); 14164 } 14165 } 14166 14167 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14168 String installerPackageName, int[] allUsers, int[] installedForUsers, 14169 PackageInstalledInfo res, UserHandle user) { 14170 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14171 14172 String pkgName = newPackage.packageName; 14173 synchronized (mPackages) { 14174 //write settings. the installStatus will be incomplete at this stage. 14175 //note that the new package setting would have already been 14176 //added to mPackages. It hasn't been persisted yet. 14177 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14178 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14179 mSettings.writeLPr(); 14180 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14181 } 14182 14183 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14184 synchronized (mPackages) { 14185 updatePermissionsLPw(newPackage.packageName, newPackage, 14186 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14187 ? UPDATE_PERMISSIONS_ALL : 0)); 14188 // For system-bundled packages, we assume that installing an upgraded version 14189 // of the package implies that the user actually wants to run that new code, 14190 // so we enable the package. 14191 PackageSetting ps = mSettings.mPackages.get(pkgName); 14192 final int userId = user.getIdentifier(); 14193 if (ps != null) { 14194 if (isSystemApp(newPackage)) { 14195 if (DEBUG_INSTALL) { 14196 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14197 } 14198 // Enable system package for requested users 14199 if (res.origUsers != null) { 14200 for (int origUserId : res.origUsers) { 14201 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14202 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14203 origUserId, installerPackageName); 14204 } 14205 } 14206 } 14207 // Also convey the prior install/uninstall state 14208 if (allUsers != null && installedForUsers != null) { 14209 for (int currentUserId : allUsers) { 14210 final boolean installed = ArrayUtils.contains( 14211 installedForUsers, currentUserId); 14212 if (DEBUG_INSTALL) { 14213 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14214 } 14215 ps.setInstalled(installed, currentUserId); 14216 } 14217 // these install state changes will be persisted in the 14218 // upcoming call to mSettings.writeLPr(). 14219 } 14220 } 14221 // It's implied that when a user requests installation, they want the app to be 14222 // installed and enabled. 14223 if (userId != UserHandle.USER_ALL) { 14224 ps.setInstalled(true, userId); 14225 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14226 } 14227 } 14228 res.name = pkgName; 14229 res.uid = newPackage.applicationInfo.uid; 14230 res.pkg = newPackage; 14231 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14232 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14233 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14234 //to update install status 14235 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14236 mSettings.writeLPr(); 14237 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14238 } 14239 14240 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14241 } 14242 14243 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14244 try { 14245 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14246 installPackageLI(args, res); 14247 } finally { 14248 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14249 } 14250 } 14251 14252 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14253 final int installFlags = args.installFlags; 14254 final String installerPackageName = args.installerPackageName; 14255 final String volumeUuid = args.volumeUuid; 14256 final File tmpPackageFile = new File(args.getCodePath()); 14257 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14258 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14259 || (args.volumeUuid != null)); 14260 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14261 boolean replace = false; 14262 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14263 if (args.move != null) { 14264 // moving a complete application; perform an initial scan on the new install location 14265 scanFlags |= SCAN_INITIAL; 14266 } 14267 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14268 scanFlags |= SCAN_DONT_KILL_APP; 14269 } 14270 14271 // Result object to be returned 14272 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14273 14274 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14275 14276 // Sanity check 14277 if (ephemeral && (forwardLocked || onExternal)) { 14278 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14279 + " external=" + onExternal); 14280 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14281 return; 14282 } 14283 14284 // Retrieve PackageSettings and parse package 14285 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14286 | PackageParser.PARSE_ENFORCE_CODE 14287 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14288 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14289 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14290 PackageParser pp = new PackageParser(); 14291 pp.setSeparateProcesses(mSeparateProcesses); 14292 pp.setDisplayMetrics(mMetrics); 14293 14294 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14295 final PackageParser.Package pkg; 14296 try { 14297 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14298 } catch (PackageParserException e) { 14299 res.setError("Failed parse during installPackageLI", e); 14300 return; 14301 } finally { 14302 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14303 } 14304 14305 // If we are installing a clustered package add results for the children 14306 if (pkg.childPackages != null) { 14307 synchronized (mPackages) { 14308 final int childCount = pkg.childPackages.size(); 14309 for (int i = 0; i < childCount; i++) { 14310 PackageParser.Package childPkg = pkg.childPackages.get(i); 14311 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14312 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14313 childRes.pkg = childPkg; 14314 childRes.name = childPkg.packageName; 14315 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14316 if (childPs != null) { 14317 childRes.origUsers = childPs.queryInstalledUsers( 14318 sUserManager.getUserIds(), true); 14319 } 14320 if ((mPackages.containsKey(childPkg.packageName))) { 14321 childRes.removedInfo = new PackageRemovedInfo(); 14322 childRes.removedInfo.removedPackage = childPkg.packageName; 14323 } 14324 if (res.addedChildPackages == null) { 14325 res.addedChildPackages = new ArrayMap<>(); 14326 } 14327 res.addedChildPackages.put(childPkg.packageName, childRes); 14328 } 14329 } 14330 } 14331 14332 // If package doesn't declare API override, mark that we have an install 14333 // time CPU ABI override. 14334 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14335 pkg.cpuAbiOverride = args.abiOverride; 14336 } 14337 14338 String pkgName = res.name = pkg.packageName; 14339 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14340 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14341 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14342 return; 14343 } 14344 } 14345 14346 try { 14347 // either use what we've been given or parse directly from the APK 14348 if (args.certificates != null) { 14349 try { 14350 PackageParser.populateCertificates(pkg, args.certificates); 14351 } catch (PackageParserException e) { 14352 // there was something wrong with the certificates we were given; 14353 // try to pull them from the APK 14354 PackageParser.collectCertificates(pkg, parseFlags); 14355 } 14356 } else { 14357 PackageParser.collectCertificates(pkg, parseFlags); 14358 } 14359 } catch (PackageParserException e) { 14360 res.setError("Failed collect during installPackageLI", e); 14361 return; 14362 } 14363 14364 // Get rid of all references to package scan path via parser. 14365 pp = null; 14366 String oldCodePath = null; 14367 boolean systemApp = false; 14368 synchronized (mPackages) { 14369 // Check if installing already existing package 14370 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14371 String oldName = mSettings.mRenamedPackages.get(pkgName); 14372 if (pkg.mOriginalPackages != null 14373 && pkg.mOriginalPackages.contains(oldName) 14374 && mPackages.containsKey(oldName)) { 14375 // This package is derived from an original package, 14376 // and this device has been updating from that original 14377 // name. We must continue using the original name, so 14378 // rename the new package here. 14379 pkg.setPackageName(oldName); 14380 pkgName = pkg.packageName; 14381 replace = true; 14382 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14383 + oldName + " pkgName=" + pkgName); 14384 } else if (mPackages.containsKey(pkgName)) { 14385 // This package, under its official name, already exists 14386 // on the device; we should replace it. 14387 replace = true; 14388 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14389 } 14390 14391 // Child packages are installed through the parent package 14392 if (pkg.parentPackage != null) { 14393 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14394 "Package " + pkg.packageName + " is child of package " 14395 + pkg.parentPackage.parentPackage + ". Child packages " 14396 + "can be updated only through the parent package."); 14397 return; 14398 } 14399 14400 if (replace) { 14401 // Prevent apps opting out from runtime permissions 14402 PackageParser.Package oldPackage = mPackages.get(pkgName); 14403 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14404 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14405 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14406 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14407 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14408 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14409 + " doesn't support runtime permissions but the old" 14410 + " target SDK " + oldTargetSdk + " does."); 14411 return; 14412 } 14413 14414 // Prevent installing of child packages 14415 if (oldPackage.parentPackage != null) { 14416 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14417 "Package " + pkg.packageName + " is child of package " 14418 + oldPackage.parentPackage + ". Child packages " 14419 + "can be updated only through the parent package."); 14420 return; 14421 } 14422 } 14423 } 14424 14425 PackageSetting ps = mSettings.mPackages.get(pkgName); 14426 if (ps != null) { 14427 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14428 14429 // Quick sanity check that we're signed correctly if updating; 14430 // we'll check this again later when scanning, but we want to 14431 // bail early here before tripping over redefined permissions. 14432 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14433 if (!checkUpgradeKeySetLP(ps, pkg)) { 14434 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14435 + pkg.packageName + " upgrade keys do not match the " 14436 + "previously installed version"); 14437 return; 14438 } 14439 } else { 14440 try { 14441 verifySignaturesLP(ps, pkg); 14442 } catch (PackageManagerException e) { 14443 res.setError(e.error, e.getMessage()); 14444 return; 14445 } 14446 } 14447 14448 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14449 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14450 systemApp = (ps.pkg.applicationInfo.flags & 14451 ApplicationInfo.FLAG_SYSTEM) != 0; 14452 } 14453 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14454 } 14455 14456 // Check whether the newly-scanned package wants to define an already-defined perm 14457 int N = pkg.permissions.size(); 14458 for (int i = N-1; i >= 0; i--) { 14459 PackageParser.Permission perm = pkg.permissions.get(i); 14460 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14461 if (bp != null) { 14462 // If the defining package is signed with our cert, it's okay. This 14463 // also includes the "updating the same package" case, of course. 14464 // "updating same package" could also involve key-rotation. 14465 final boolean sigsOk; 14466 if (bp.sourcePackage.equals(pkg.packageName) 14467 && (bp.packageSetting instanceof PackageSetting) 14468 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14469 scanFlags))) { 14470 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14471 } else { 14472 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14473 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14474 } 14475 if (!sigsOk) { 14476 // If the owning package is the system itself, we log but allow 14477 // install to proceed; we fail the install on all other permission 14478 // redefinitions. 14479 if (!bp.sourcePackage.equals("android")) { 14480 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14481 + pkg.packageName + " attempting to redeclare permission " 14482 + perm.info.name + " already owned by " + bp.sourcePackage); 14483 res.origPermission = perm.info.name; 14484 res.origPackage = bp.sourcePackage; 14485 return; 14486 } else { 14487 Slog.w(TAG, "Package " + pkg.packageName 14488 + " attempting to redeclare system permission " 14489 + perm.info.name + "; ignoring new declaration"); 14490 pkg.permissions.remove(i); 14491 } 14492 } 14493 } 14494 } 14495 } 14496 14497 if (systemApp) { 14498 if (onExternal) { 14499 // Abort update; system app can't be replaced with app on sdcard 14500 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14501 "Cannot install updates to system apps on sdcard"); 14502 return; 14503 } else if (ephemeral) { 14504 // Abort update; system app can't be replaced with an ephemeral app 14505 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14506 "Cannot update a system app with an ephemeral app"); 14507 return; 14508 } 14509 } 14510 14511 if (args.move != null) { 14512 // We did an in-place move, so dex is ready to roll 14513 scanFlags |= SCAN_NO_DEX; 14514 scanFlags |= SCAN_MOVE; 14515 14516 synchronized (mPackages) { 14517 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14518 if (ps == null) { 14519 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14520 "Missing settings for moved package " + pkgName); 14521 } 14522 14523 // We moved the entire application as-is, so bring over the 14524 // previously derived ABI information. 14525 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14526 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14527 } 14528 14529 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14530 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14531 scanFlags |= SCAN_NO_DEX; 14532 14533 try { 14534 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14535 args.abiOverride : pkg.cpuAbiOverride); 14536 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14537 true /* extract libs */); 14538 } catch (PackageManagerException pme) { 14539 Slog.e(TAG, "Error deriving application ABI", pme); 14540 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14541 return; 14542 } 14543 14544 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14545 // Do not run PackageDexOptimizer through the local performDexOpt 14546 // method because `pkg` is not in `mPackages` yet. 14547 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14548 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14549 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14550 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14551 String msg = "Extracting package failed for " + pkgName; 14552 res.setError(INSTALL_FAILED_DEXOPT, msg); 14553 return; 14554 } 14555 14556 // Notify BackgroundDexOptService that the package has been changed. 14557 // If this is an update of a package which used to fail to compile, 14558 // BDOS will remove it from its blacklist. 14559 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14560 } 14561 14562 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14563 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14564 return; 14565 } 14566 14567 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14568 14569 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14570 "installPackageLI")) { 14571 if (replace) { 14572 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14573 installerPackageName, res); 14574 } else { 14575 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14576 args.user, installerPackageName, volumeUuid, res); 14577 } 14578 } 14579 synchronized (mPackages) { 14580 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14581 if (ps != null) { 14582 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14583 } 14584 14585 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14586 for (int i = 0; i < childCount; i++) { 14587 PackageParser.Package childPkg = pkg.childPackages.get(i); 14588 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14589 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14590 if (childPs != null) { 14591 childRes.newUsers = childPs.queryInstalledUsers( 14592 sUserManager.getUserIds(), true); 14593 } 14594 } 14595 } 14596 } 14597 14598 private void startIntentFilterVerifications(int userId, boolean replacing, 14599 PackageParser.Package pkg) { 14600 if (mIntentFilterVerifierComponent == null) { 14601 Slog.w(TAG, "No IntentFilter verification will not be done as " 14602 + "there is no IntentFilterVerifier available!"); 14603 return; 14604 } 14605 14606 final int verifierUid = getPackageUid( 14607 mIntentFilterVerifierComponent.getPackageName(), 14608 MATCH_DEBUG_TRIAGED_MISSING, 14609 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14610 14611 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14612 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14613 mHandler.sendMessage(msg); 14614 14615 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14616 for (int i = 0; i < childCount; i++) { 14617 PackageParser.Package childPkg = pkg.childPackages.get(i); 14618 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14619 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14620 mHandler.sendMessage(msg); 14621 } 14622 } 14623 14624 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14625 PackageParser.Package pkg) { 14626 int size = pkg.activities.size(); 14627 if (size == 0) { 14628 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14629 "No activity, so no need to verify any IntentFilter!"); 14630 return; 14631 } 14632 14633 final boolean hasDomainURLs = hasDomainURLs(pkg); 14634 if (!hasDomainURLs) { 14635 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14636 "No domain URLs, so no need to verify any IntentFilter!"); 14637 return; 14638 } 14639 14640 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14641 + " if any IntentFilter from the " + size 14642 + " Activities needs verification ..."); 14643 14644 int count = 0; 14645 final String packageName = pkg.packageName; 14646 14647 synchronized (mPackages) { 14648 // If this is a new install and we see that we've already run verification for this 14649 // package, we have nothing to do: it means the state was restored from backup. 14650 if (!replacing) { 14651 IntentFilterVerificationInfo ivi = 14652 mSettings.getIntentFilterVerificationLPr(packageName); 14653 if (ivi != null) { 14654 if (DEBUG_DOMAIN_VERIFICATION) { 14655 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14656 + ivi.getStatusString()); 14657 } 14658 return; 14659 } 14660 } 14661 14662 // If any filters need to be verified, then all need to be. 14663 boolean needToVerify = false; 14664 for (PackageParser.Activity a : pkg.activities) { 14665 for (ActivityIntentInfo filter : a.intents) { 14666 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14667 if (DEBUG_DOMAIN_VERIFICATION) { 14668 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14669 } 14670 needToVerify = true; 14671 break; 14672 } 14673 } 14674 } 14675 14676 if (needToVerify) { 14677 final int verificationId = mIntentFilterVerificationToken++; 14678 for (PackageParser.Activity a : pkg.activities) { 14679 for (ActivityIntentInfo filter : a.intents) { 14680 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14681 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14682 "Verification needed for IntentFilter:" + filter.toString()); 14683 mIntentFilterVerifier.addOneIntentFilterVerification( 14684 verifierUid, userId, verificationId, filter, packageName); 14685 count++; 14686 } 14687 } 14688 } 14689 } 14690 } 14691 14692 if (count > 0) { 14693 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14694 + " IntentFilter verification" + (count > 1 ? "s" : "") 14695 + " for userId:" + userId); 14696 mIntentFilterVerifier.startVerifications(userId); 14697 } else { 14698 if (DEBUG_DOMAIN_VERIFICATION) { 14699 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14700 } 14701 } 14702 } 14703 14704 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14705 final ComponentName cn = filter.activity.getComponentName(); 14706 final String packageName = cn.getPackageName(); 14707 14708 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14709 packageName); 14710 if (ivi == null) { 14711 return true; 14712 } 14713 int status = ivi.getStatus(); 14714 switch (status) { 14715 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14716 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14717 return true; 14718 14719 default: 14720 // Nothing to do 14721 return false; 14722 } 14723 } 14724 14725 private static boolean isMultiArch(ApplicationInfo info) { 14726 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14727 } 14728 14729 private static boolean isExternal(PackageParser.Package pkg) { 14730 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14731 } 14732 14733 private static boolean isExternal(PackageSetting ps) { 14734 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14735 } 14736 14737 private static boolean isEphemeral(PackageParser.Package pkg) { 14738 return pkg.applicationInfo.isEphemeralApp(); 14739 } 14740 14741 private static boolean isEphemeral(PackageSetting ps) { 14742 return ps.pkg != null && isEphemeral(ps.pkg); 14743 } 14744 14745 private static boolean isSystemApp(PackageParser.Package pkg) { 14746 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14747 } 14748 14749 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14750 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14751 } 14752 14753 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14754 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14755 } 14756 14757 private static boolean isSystemApp(PackageSetting ps) { 14758 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14759 } 14760 14761 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14762 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14763 } 14764 14765 private int packageFlagsToInstallFlags(PackageSetting ps) { 14766 int installFlags = 0; 14767 if (isEphemeral(ps)) { 14768 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14769 } 14770 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14771 // This existing package was an external ASEC install when we have 14772 // the external flag without a UUID 14773 installFlags |= PackageManager.INSTALL_EXTERNAL; 14774 } 14775 if (ps.isForwardLocked()) { 14776 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14777 } 14778 return installFlags; 14779 } 14780 14781 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14782 if (isExternal(pkg)) { 14783 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14784 return StorageManager.UUID_PRIMARY_PHYSICAL; 14785 } else { 14786 return pkg.volumeUuid; 14787 } 14788 } else { 14789 return StorageManager.UUID_PRIVATE_INTERNAL; 14790 } 14791 } 14792 14793 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14794 if (isExternal(pkg)) { 14795 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14796 return mSettings.getExternalVersion(); 14797 } else { 14798 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14799 } 14800 } else { 14801 return mSettings.getInternalVersion(); 14802 } 14803 } 14804 14805 private void deleteTempPackageFiles() { 14806 final FilenameFilter filter = new FilenameFilter() { 14807 public boolean accept(File dir, String name) { 14808 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14809 } 14810 }; 14811 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14812 file.delete(); 14813 } 14814 } 14815 14816 @Override 14817 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14818 int flags) { 14819 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14820 flags); 14821 } 14822 14823 @Override 14824 public void deletePackage(final String packageName, 14825 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14826 mContext.enforceCallingOrSelfPermission( 14827 android.Manifest.permission.DELETE_PACKAGES, null); 14828 Preconditions.checkNotNull(packageName); 14829 Preconditions.checkNotNull(observer); 14830 final int uid = Binder.getCallingUid(); 14831 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14832 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14833 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14834 mContext.enforceCallingOrSelfPermission( 14835 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14836 "deletePackage for user " + userId); 14837 } 14838 14839 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14840 try { 14841 observer.onPackageDeleted(packageName, 14842 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14843 } catch (RemoteException re) { 14844 } 14845 return; 14846 } 14847 14848 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 14849 try { 14850 observer.onPackageDeleted(packageName, 14851 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 14852 } catch (RemoteException re) { 14853 } 14854 return; 14855 } 14856 14857 if (DEBUG_REMOVE) { 14858 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 14859 + " deleteAllUsers: " + deleteAllUsers ); 14860 } 14861 // Queue up an async operation since the package deletion may take a little while. 14862 mHandler.post(new Runnable() { 14863 public void run() { 14864 mHandler.removeCallbacks(this); 14865 int returnCode; 14866 if (!deleteAllUsers) { 14867 returnCode = deletePackageX(packageName, userId, deleteFlags); 14868 } else { 14869 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 14870 // If nobody is blocking uninstall, proceed with delete for all users 14871 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 14872 returnCode = deletePackageX(packageName, userId, deleteFlags); 14873 } else { 14874 // Otherwise uninstall individually for users with blockUninstalls=false 14875 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 14876 for (int userId : users) { 14877 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 14878 returnCode = deletePackageX(packageName, userId, userFlags); 14879 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 14880 Slog.w(TAG, "Package delete failed for user " + userId 14881 + ", returnCode " + returnCode); 14882 } 14883 } 14884 } 14885 // The app has only been marked uninstalled for certain users. 14886 // We still need to report that delete was blocked 14887 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 14888 } 14889 } 14890 try { 14891 observer.onPackageDeleted(packageName, returnCode, null); 14892 } catch (RemoteException e) { 14893 Log.i(TAG, "Observer no longer exists."); 14894 } //end catch 14895 } //end run 14896 }); 14897 } 14898 14899 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 14900 int[] result = EMPTY_INT_ARRAY; 14901 for (int userId : userIds) { 14902 if (getBlockUninstallForUser(packageName, userId)) { 14903 result = ArrayUtils.appendInt(result, userId); 14904 } 14905 } 14906 return result; 14907 } 14908 14909 @Override 14910 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 14911 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 14912 } 14913 14914 private boolean isPackageDeviceAdmin(String packageName, int userId) { 14915 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 14916 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 14917 try { 14918 if (dpm != null) { 14919 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 14920 /* callingUserOnly =*/ false); 14921 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 14922 : deviceOwnerComponentName.getPackageName(); 14923 // Does the package contains the device owner? 14924 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 14925 // this check is probably not needed, since DO should be registered as a device 14926 // admin on some user too. (Original bug for this: b/17657954) 14927 if (packageName.equals(deviceOwnerPackageName)) { 14928 return true; 14929 } 14930 // Does it contain a device admin for any user? 14931 int[] users; 14932 if (userId == UserHandle.USER_ALL) { 14933 users = sUserManager.getUserIds(); 14934 } else { 14935 users = new int[]{userId}; 14936 } 14937 for (int i = 0; i < users.length; ++i) { 14938 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 14939 return true; 14940 } 14941 } 14942 } 14943 } catch (RemoteException e) { 14944 } 14945 return false; 14946 } 14947 14948 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 14949 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 14950 } 14951 14952 /** 14953 * This method is an internal method that could be get invoked either 14954 * to delete an installed package or to clean up a failed installation. 14955 * After deleting an installed package, a broadcast is sent to notify any 14956 * listeners that the package has been removed. For cleaning up a failed 14957 * installation, the broadcast is not necessary since the package's 14958 * installation wouldn't have sent the initial broadcast either 14959 * The key steps in deleting a package are 14960 * deleting the package information in internal structures like mPackages, 14961 * deleting the packages base directories through installd 14962 * updating mSettings to reflect current status 14963 * persisting settings for later use 14964 * sending a broadcast if necessary 14965 */ 14966 private int deletePackageX(String packageName, int userId, int deleteFlags) { 14967 final PackageRemovedInfo info = new PackageRemovedInfo(); 14968 final boolean res; 14969 14970 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 14971 ? UserHandle.ALL : new UserHandle(userId); 14972 14973 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 14974 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 14975 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 14976 } 14977 14978 PackageSetting uninstalledPs = null; 14979 14980 // for the uninstall-updates case and restricted profiles, remember the per- 14981 // user handle installed state 14982 int[] allUsers; 14983 synchronized (mPackages) { 14984 uninstalledPs = mSettings.mPackages.get(packageName); 14985 if (uninstalledPs == null) { 14986 Slog.w(TAG, "Not removing non-existent package " + packageName); 14987 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 14988 } 14989 allUsers = sUserManager.getUserIds(); 14990 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 14991 } 14992 14993 synchronized (mInstallLock) { 14994 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 14995 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 14996 "deletePackageX")) { 14997 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 14998 deleteFlags | REMOVE_CHATTY, info, true, null); 14999 } 15000 synchronized (mPackages) { 15001 if (res) { 15002 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15003 } 15004 } 15005 } 15006 15007 if (res) { 15008 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15009 info.sendPackageRemovedBroadcasts(killApp); 15010 info.sendSystemPackageUpdatedBroadcasts(); 15011 info.sendSystemPackageAppearedBroadcasts(); 15012 } 15013 // Force a gc here. 15014 Runtime.getRuntime().gc(); 15015 // Delete the resources here after sending the broadcast to let 15016 // other processes clean up before deleting resources. 15017 if (info.args != null) { 15018 synchronized (mInstallLock) { 15019 info.args.doPostDeleteLI(true); 15020 } 15021 } 15022 15023 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15024 } 15025 15026 class PackageRemovedInfo { 15027 String removedPackage; 15028 int uid = -1; 15029 int removedAppId = -1; 15030 int[] origUsers; 15031 int[] removedUsers = null; 15032 boolean isRemovedPackageSystemUpdate = false; 15033 boolean isUpdate; 15034 boolean dataRemoved; 15035 boolean removedForAllUsers; 15036 // Clean up resources deleted packages. 15037 InstallArgs args = null; 15038 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15039 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15040 15041 void sendPackageRemovedBroadcasts(boolean killApp) { 15042 sendPackageRemovedBroadcastInternal(killApp); 15043 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15044 for (int i = 0; i < childCount; i++) { 15045 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15046 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15047 } 15048 } 15049 15050 void sendSystemPackageUpdatedBroadcasts() { 15051 if (isRemovedPackageSystemUpdate) { 15052 sendSystemPackageUpdatedBroadcastsInternal(); 15053 final int childCount = (removedChildPackages != null) 15054 ? removedChildPackages.size() : 0; 15055 for (int i = 0; i < childCount; i++) { 15056 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15057 if (childInfo.isRemovedPackageSystemUpdate) { 15058 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15059 } 15060 } 15061 } 15062 } 15063 15064 void sendSystemPackageAppearedBroadcasts() { 15065 final int packageCount = (appearedChildPackages != null) 15066 ? appearedChildPackages.size() : 0; 15067 for (int i = 0; i < packageCount; i++) { 15068 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15069 for (int userId : installedInfo.newUsers) { 15070 sendPackageAddedForUser(installedInfo.name, true, 15071 UserHandle.getAppId(installedInfo.uid), userId); 15072 } 15073 } 15074 } 15075 15076 private void sendSystemPackageUpdatedBroadcastsInternal() { 15077 Bundle extras = new Bundle(2); 15078 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15079 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15080 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15081 extras, 0, null, null, null); 15082 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15083 extras, 0, null, null, null); 15084 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15085 null, 0, removedPackage, null, null); 15086 } 15087 15088 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15089 Bundle extras = new Bundle(2); 15090 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15091 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15092 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15093 if (isUpdate || isRemovedPackageSystemUpdate) { 15094 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15095 } 15096 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15097 if (removedPackage != null) { 15098 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15099 extras, 0, null, null, removedUsers); 15100 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15101 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15102 removedPackage, extras, 0, null, null, removedUsers); 15103 } 15104 } 15105 if (removedAppId >= 0) { 15106 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15107 removedUsers); 15108 } 15109 } 15110 } 15111 15112 /* 15113 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15114 * flag is not set, the data directory is removed as well. 15115 * make sure this flag is set for partially installed apps. If not its meaningless to 15116 * delete a partially installed application. 15117 */ 15118 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15119 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15120 String packageName = ps.name; 15121 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15122 // Retrieve object to delete permissions for shared user later on 15123 final PackageParser.Package deletedPkg; 15124 final PackageSetting deletedPs; 15125 // reader 15126 synchronized (mPackages) { 15127 deletedPkg = mPackages.get(packageName); 15128 deletedPs = mSettings.mPackages.get(packageName); 15129 if (outInfo != null) { 15130 outInfo.removedPackage = packageName; 15131 outInfo.removedUsers = deletedPs != null 15132 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15133 : null; 15134 } 15135 } 15136 15137 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15138 15139 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15140 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15141 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15142 destroyAppProfilesLIF(deletedPkg); 15143 if (outInfo != null) { 15144 outInfo.dataRemoved = true; 15145 } 15146 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15147 } 15148 15149 // writer 15150 synchronized (mPackages) { 15151 if (deletedPs != null) { 15152 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15153 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15154 clearDefaultBrowserIfNeeded(packageName); 15155 if (outInfo != null) { 15156 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15157 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15158 } 15159 updatePermissionsLPw(deletedPs.name, null, 0); 15160 if (deletedPs.sharedUser != null) { 15161 // Remove permissions associated with package. Since runtime 15162 // permissions are per user we have to kill the removed package 15163 // or packages running under the shared user of the removed 15164 // package if revoking the permissions requested only by the removed 15165 // package is successful and this causes a change in gids. 15166 for (int userId : UserManagerService.getInstance().getUserIds()) { 15167 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15168 userId); 15169 if (userIdToKill == UserHandle.USER_ALL 15170 || userIdToKill >= UserHandle.USER_SYSTEM) { 15171 // If gids changed for this user, kill all affected packages. 15172 mHandler.post(new Runnable() { 15173 @Override 15174 public void run() { 15175 // This has to happen with no lock held. 15176 killApplication(deletedPs.name, deletedPs.appId, 15177 KILL_APP_REASON_GIDS_CHANGED); 15178 } 15179 }); 15180 break; 15181 } 15182 } 15183 } 15184 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15185 } 15186 // make sure to preserve per-user disabled state if this removal was just 15187 // a downgrade of a system app to the factory package 15188 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15189 if (DEBUG_REMOVE) { 15190 Slog.d(TAG, "Propagating install state across downgrade"); 15191 } 15192 for (int userId : allUserHandles) { 15193 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15194 if (DEBUG_REMOVE) { 15195 Slog.d(TAG, " user " + userId + " => " + installed); 15196 } 15197 ps.setInstalled(installed, userId); 15198 } 15199 } 15200 } 15201 // can downgrade to reader 15202 if (writeSettings) { 15203 // Save settings now 15204 mSettings.writeLPr(); 15205 } 15206 } 15207 if (outInfo != null) { 15208 // A user ID was deleted here. Go through all users and remove it 15209 // from KeyStore. 15210 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15211 } 15212 } 15213 15214 static boolean locationIsPrivileged(File path) { 15215 try { 15216 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15217 .getCanonicalPath(); 15218 return path.getCanonicalPath().startsWith(privilegedAppDir); 15219 } catch (IOException e) { 15220 Slog.e(TAG, "Unable to access code path " + path); 15221 } 15222 return false; 15223 } 15224 15225 /* 15226 * Tries to delete system package. 15227 */ 15228 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15229 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15230 boolean writeSettings) { 15231 if (deletedPs.parentPackageName != null) { 15232 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15233 return false; 15234 } 15235 15236 final boolean applyUserRestrictions 15237 = (allUserHandles != null) && (outInfo.origUsers != null); 15238 final PackageSetting disabledPs; 15239 // Confirm if the system package has been updated 15240 // An updated system app can be deleted. This will also have to restore 15241 // the system pkg from system partition 15242 // reader 15243 synchronized (mPackages) { 15244 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15245 } 15246 15247 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15248 + " disabledPs=" + disabledPs); 15249 15250 if (disabledPs == null) { 15251 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15252 return false; 15253 } else if (DEBUG_REMOVE) { 15254 Slog.d(TAG, "Deleting system pkg from data partition"); 15255 } 15256 15257 if (DEBUG_REMOVE) { 15258 if (applyUserRestrictions) { 15259 Slog.d(TAG, "Remembering install states:"); 15260 for (int userId : allUserHandles) { 15261 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15262 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15263 } 15264 } 15265 } 15266 15267 // Delete the updated package 15268 outInfo.isRemovedPackageSystemUpdate = true; 15269 if (outInfo.removedChildPackages != null) { 15270 final int childCount = (deletedPs.childPackageNames != null) 15271 ? deletedPs.childPackageNames.size() : 0; 15272 for (int i = 0; i < childCount; i++) { 15273 String childPackageName = deletedPs.childPackageNames.get(i); 15274 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15275 .contains(childPackageName)) { 15276 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15277 childPackageName); 15278 if (childInfo != null) { 15279 childInfo.isRemovedPackageSystemUpdate = true; 15280 } 15281 } 15282 } 15283 } 15284 15285 if (disabledPs.versionCode < deletedPs.versionCode) { 15286 // Delete data for downgrades 15287 flags &= ~PackageManager.DELETE_KEEP_DATA; 15288 } else { 15289 // Preserve data by setting flag 15290 flags |= PackageManager.DELETE_KEEP_DATA; 15291 } 15292 15293 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15294 outInfo, writeSettings, disabledPs.pkg); 15295 if (!ret) { 15296 return false; 15297 } 15298 15299 // writer 15300 synchronized (mPackages) { 15301 // Reinstate the old system package 15302 enableSystemPackageLPw(disabledPs.pkg); 15303 // Remove any native libraries from the upgraded package. 15304 removeNativeBinariesLI(deletedPs); 15305 } 15306 15307 // Install the system package 15308 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15309 int parseFlags = PackageParser.PARSE_MUST_BE_APK | PackageParser.PARSE_IS_SYSTEM; 15310 if (locationIsPrivileged(disabledPs.codePath)) { 15311 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15312 } 15313 15314 final PackageParser.Package newPkg; 15315 try { 15316 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15317 } catch (PackageManagerException e) { 15318 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15319 + e.getMessage()); 15320 return false; 15321 } 15322 15323 prepareAppDataAfterInstallLIF(newPkg); 15324 15325 // writer 15326 synchronized (mPackages) { 15327 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15328 15329 // Propagate the permissions state as we do not want to drop on the floor 15330 // runtime permissions. The update permissions method below will take 15331 // care of removing obsolete permissions and grant install permissions. 15332 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15333 updatePermissionsLPw(newPkg.packageName, newPkg, 15334 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15335 15336 if (applyUserRestrictions) { 15337 if (DEBUG_REMOVE) { 15338 Slog.d(TAG, "Propagating install state across reinstall"); 15339 } 15340 for (int userId : allUserHandles) { 15341 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15342 if (DEBUG_REMOVE) { 15343 Slog.d(TAG, " user " + userId + " => " + installed); 15344 } 15345 ps.setInstalled(installed, userId); 15346 15347 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15348 } 15349 // Regardless of writeSettings we need to ensure that this restriction 15350 // state propagation is persisted 15351 mSettings.writeAllUsersPackageRestrictionsLPr(); 15352 } 15353 // can downgrade to reader here 15354 if (writeSettings) { 15355 mSettings.writeLPr(); 15356 } 15357 } 15358 return true; 15359 } 15360 15361 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15362 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15363 PackageRemovedInfo outInfo, boolean writeSettings, 15364 PackageParser.Package replacingPackage) { 15365 synchronized (mPackages) { 15366 if (outInfo != null) { 15367 outInfo.uid = ps.appId; 15368 } 15369 15370 if (outInfo != null && outInfo.removedChildPackages != null) { 15371 final int childCount = (ps.childPackageNames != null) 15372 ? ps.childPackageNames.size() : 0; 15373 for (int i = 0; i < childCount; i++) { 15374 String childPackageName = ps.childPackageNames.get(i); 15375 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15376 if (childPs == null) { 15377 return false; 15378 } 15379 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15380 childPackageName); 15381 if (childInfo != null) { 15382 childInfo.uid = childPs.appId; 15383 } 15384 } 15385 } 15386 } 15387 15388 // Delete package data from internal structures and also remove data if flag is set 15389 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15390 15391 // Delete the child packages data 15392 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15393 for (int i = 0; i < childCount; i++) { 15394 PackageSetting childPs; 15395 synchronized (mPackages) { 15396 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15397 } 15398 if (childPs != null) { 15399 PackageRemovedInfo childOutInfo = (outInfo != null 15400 && outInfo.removedChildPackages != null) 15401 ? outInfo.removedChildPackages.get(childPs.name) : null; 15402 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15403 && (replacingPackage != null 15404 && !replacingPackage.hasChildPackage(childPs.name)) 15405 ? flags & ~DELETE_KEEP_DATA : flags; 15406 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15407 deleteFlags, writeSettings); 15408 } 15409 } 15410 15411 // Delete application code and resources only for parent packages 15412 if (ps.parentPackageName == null) { 15413 if (deleteCodeAndResources && (outInfo != null)) { 15414 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15415 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15416 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15417 } 15418 } 15419 15420 return true; 15421 } 15422 15423 @Override 15424 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15425 int userId) { 15426 mContext.enforceCallingOrSelfPermission( 15427 android.Manifest.permission.DELETE_PACKAGES, null); 15428 synchronized (mPackages) { 15429 PackageSetting ps = mSettings.mPackages.get(packageName); 15430 if (ps == null) { 15431 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15432 return false; 15433 } 15434 if (!ps.getInstalled(userId)) { 15435 // Can't block uninstall for an app that is not installed or enabled. 15436 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15437 return false; 15438 } 15439 ps.setBlockUninstall(blockUninstall, userId); 15440 mSettings.writePackageRestrictionsLPr(userId); 15441 } 15442 return true; 15443 } 15444 15445 @Override 15446 public boolean getBlockUninstallForUser(String packageName, int userId) { 15447 synchronized (mPackages) { 15448 PackageSetting ps = mSettings.mPackages.get(packageName); 15449 if (ps == null) { 15450 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15451 return false; 15452 } 15453 return ps.getBlockUninstall(userId); 15454 } 15455 } 15456 15457 @Override 15458 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15459 int callingUid = Binder.getCallingUid(); 15460 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15461 throw new SecurityException( 15462 "setRequiredForSystemUser can only be run by the system or root"); 15463 } 15464 synchronized (mPackages) { 15465 PackageSetting ps = mSettings.mPackages.get(packageName); 15466 if (ps == null) { 15467 Log.w(TAG, "Package doesn't exist: " + packageName); 15468 return false; 15469 } 15470 if (systemUserApp) { 15471 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15472 } else { 15473 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15474 } 15475 mSettings.writeLPr(); 15476 } 15477 return true; 15478 } 15479 15480 /* 15481 * This method handles package deletion in general 15482 */ 15483 private boolean deletePackageLIF(String packageName, UserHandle user, 15484 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15485 PackageRemovedInfo outInfo, boolean writeSettings, 15486 PackageParser.Package replacingPackage) { 15487 if (packageName == null) { 15488 Slog.w(TAG, "Attempt to delete null packageName."); 15489 return false; 15490 } 15491 15492 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15493 15494 PackageSetting ps; 15495 15496 synchronized (mPackages) { 15497 ps = mSettings.mPackages.get(packageName); 15498 if (ps == null) { 15499 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15500 return false; 15501 } 15502 15503 if (ps.parentPackageName != null && (!isSystemApp(ps) 15504 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15505 if (DEBUG_REMOVE) { 15506 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15507 + ((user == null) ? UserHandle.USER_ALL : user)); 15508 } 15509 final int removedUserId = (user != null) ? user.getIdentifier() 15510 : UserHandle.USER_ALL; 15511 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15512 return false; 15513 } 15514 markPackageUninstalledForUserLPw(ps, user); 15515 scheduleWritePackageRestrictionsLocked(user); 15516 return true; 15517 } 15518 } 15519 15520 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15521 && user.getIdentifier() != UserHandle.USER_ALL)) { 15522 // The caller is asking that the package only be deleted for a single 15523 // user. To do this, we just mark its uninstalled state and delete 15524 // its data. If this is a system app, we only allow this to happen if 15525 // they have set the special DELETE_SYSTEM_APP which requests different 15526 // semantics than normal for uninstalling system apps. 15527 markPackageUninstalledForUserLPw(ps, user); 15528 15529 if (!isSystemApp(ps)) { 15530 // Do not uninstall the APK if an app should be cached 15531 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15532 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15533 // Other user still have this package installed, so all 15534 // we need to do is clear this user's data and save that 15535 // it is uninstalled. 15536 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15537 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15538 return false; 15539 } 15540 scheduleWritePackageRestrictionsLocked(user); 15541 return true; 15542 } else { 15543 // We need to set it back to 'installed' so the uninstall 15544 // broadcasts will be sent correctly. 15545 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15546 ps.setInstalled(true, user.getIdentifier()); 15547 } 15548 } else { 15549 // This is a system app, so we assume that the 15550 // other users still have this package installed, so all 15551 // we need to do is clear this user's data and save that 15552 // it is uninstalled. 15553 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15554 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15555 return false; 15556 } 15557 scheduleWritePackageRestrictionsLocked(user); 15558 return true; 15559 } 15560 } 15561 15562 // If we are deleting a composite package for all users, keep track 15563 // of result for each child. 15564 if (ps.childPackageNames != null && outInfo != null) { 15565 synchronized (mPackages) { 15566 final int childCount = ps.childPackageNames.size(); 15567 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15568 for (int i = 0; i < childCount; i++) { 15569 String childPackageName = ps.childPackageNames.get(i); 15570 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15571 childInfo.removedPackage = childPackageName; 15572 outInfo.removedChildPackages.put(childPackageName, childInfo); 15573 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15574 if (childPs != null) { 15575 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15576 } 15577 } 15578 } 15579 } 15580 15581 boolean ret = false; 15582 if (isSystemApp(ps)) { 15583 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15584 // When an updated system application is deleted we delete the existing resources 15585 // as well and fall back to existing code in system partition 15586 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15587 } else { 15588 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15589 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15590 outInfo, writeSettings, replacingPackage); 15591 } 15592 15593 // Take a note whether we deleted the package for all users 15594 if (outInfo != null) { 15595 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15596 if (outInfo.removedChildPackages != null) { 15597 synchronized (mPackages) { 15598 final int childCount = outInfo.removedChildPackages.size(); 15599 for (int i = 0; i < childCount; i++) { 15600 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15601 if (childInfo != null) { 15602 childInfo.removedForAllUsers = mPackages.get( 15603 childInfo.removedPackage) == null; 15604 } 15605 } 15606 } 15607 } 15608 // If we uninstalled an update to a system app there may be some 15609 // child packages that appeared as they are declared in the system 15610 // app but were not declared in the update. 15611 if (isSystemApp(ps)) { 15612 synchronized (mPackages) { 15613 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15614 final int childCount = (updatedPs.childPackageNames != null) 15615 ? updatedPs.childPackageNames.size() : 0; 15616 for (int i = 0; i < childCount; i++) { 15617 String childPackageName = updatedPs.childPackageNames.get(i); 15618 if (outInfo.removedChildPackages == null 15619 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15620 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15621 if (childPs == null) { 15622 continue; 15623 } 15624 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15625 installRes.name = childPackageName; 15626 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15627 installRes.pkg = mPackages.get(childPackageName); 15628 installRes.uid = childPs.pkg.applicationInfo.uid; 15629 if (outInfo.appearedChildPackages == null) { 15630 outInfo.appearedChildPackages = new ArrayMap<>(); 15631 } 15632 outInfo.appearedChildPackages.put(childPackageName, installRes); 15633 } 15634 } 15635 } 15636 } 15637 } 15638 15639 return ret; 15640 } 15641 15642 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15643 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15644 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15645 for (int nextUserId : userIds) { 15646 if (DEBUG_REMOVE) { 15647 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15648 } 15649 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15650 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15651 false /*hidden*/, false /*suspended*/, null, null, null, 15652 false /*blockUninstall*/, 15653 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15654 } 15655 } 15656 15657 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15658 PackageRemovedInfo outInfo) { 15659 final PackageParser.Package pkg; 15660 synchronized (mPackages) { 15661 pkg = mPackages.get(ps.name); 15662 } 15663 15664 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15665 : new int[] {userId}; 15666 for (int nextUserId : userIds) { 15667 if (DEBUG_REMOVE) { 15668 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15669 + nextUserId); 15670 } 15671 15672 destroyAppDataLIF(pkg, userId, 15673 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15674 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15675 schedulePackageCleaning(ps.name, nextUserId, false); 15676 synchronized (mPackages) { 15677 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15678 scheduleWritePackageRestrictionsLocked(nextUserId); 15679 } 15680 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15681 } 15682 } 15683 15684 if (outInfo != null) { 15685 outInfo.removedPackage = ps.name; 15686 outInfo.removedAppId = ps.appId; 15687 outInfo.removedUsers = userIds; 15688 } 15689 15690 return true; 15691 } 15692 15693 private final class ClearStorageConnection implements ServiceConnection { 15694 IMediaContainerService mContainerService; 15695 15696 @Override 15697 public void onServiceConnected(ComponentName name, IBinder service) { 15698 synchronized (this) { 15699 mContainerService = IMediaContainerService.Stub.asInterface(service); 15700 notifyAll(); 15701 } 15702 } 15703 15704 @Override 15705 public void onServiceDisconnected(ComponentName name) { 15706 } 15707 } 15708 15709 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15710 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15711 15712 final boolean mounted; 15713 if (Environment.isExternalStorageEmulated()) { 15714 mounted = true; 15715 } else { 15716 final String status = Environment.getExternalStorageState(); 15717 15718 mounted = status.equals(Environment.MEDIA_MOUNTED) 15719 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15720 } 15721 15722 if (!mounted) { 15723 return; 15724 } 15725 15726 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15727 int[] users; 15728 if (userId == UserHandle.USER_ALL) { 15729 users = sUserManager.getUserIds(); 15730 } else { 15731 users = new int[] { userId }; 15732 } 15733 final ClearStorageConnection conn = new ClearStorageConnection(); 15734 if (mContext.bindServiceAsUser( 15735 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15736 try { 15737 for (int curUser : users) { 15738 long timeout = SystemClock.uptimeMillis() + 5000; 15739 synchronized (conn) { 15740 long now = SystemClock.uptimeMillis(); 15741 while (conn.mContainerService == null && now < timeout) { 15742 try { 15743 conn.wait(timeout - now); 15744 } catch (InterruptedException e) { 15745 } 15746 } 15747 } 15748 if (conn.mContainerService == null) { 15749 return; 15750 } 15751 15752 final UserEnvironment userEnv = new UserEnvironment(curUser); 15753 clearDirectory(conn.mContainerService, 15754 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15755 if (allData) { 15756 clearDirectory(conn.mContainerService, 15757 userEnv.buildExternalStorageAppDataDirs(packageName)); 15758 clearDirectory(conn.mContainerService, 15759 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15760 } 15761 } 15762 } finally { 15763 mContext.unbindService(conn); 15764 } 15765 } 15766 } 15767 15768 @Override 15769 public void clearApplicationProfileData(String packageName) { 15770 enforceSystemOrRoot("Only the system can clear all profile data"); 15771 15772 final PackageParser.Package pkg; 15773 synchronized (mPackages) { 15774 pkg = mPackages.get(packageName); 15775 } 15776 15777 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15778 synchronized (mInstallLock) { 15779 clearAppProfilesLIF(pkg); 15780 } 15781 } 15782 } 15783 15784 @Override 15785 public void clearApplicationUserData(final String packageName, 15786 final IPackageDataObserver observer, final int userId) { 15787 mContext.enforceCallingOrSelfPermission( 15788 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15789 15790 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15791 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15792 15793 final DevicePolicyManagerInternal dpmi = LocalServices 15794 .getService(DevicePolicyManagerInternal.class); 15795 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15796 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15797 } 15798 // Queue up an async operation since the package deletion may take a little while. 15799 mHandler.post(new Runnable() { 15800 public void run() { 15801 mHandler.removeCallbacks(this); 15802 final boolean succeeded; 15803 try (PackageFreezer freezer = freezePackage(packageName, 15804 "clearApplicationUserData")) { 15805 synchronized (mInstallLock) { 15806 succeeded = clearApplicationUserDataLIF(packageName, userId); 15807 } 15808 clearExternalStorageDataSync(packageName, userId, true); 15809 } 15810 if (succeeded) { 15811 // invoke DeviceStorageMonitor's update method to clear any notifications 15812 DeviceStorageMonitorInternal dsm = LocalServices 15813 .getService(DeviceStorageMonitorInternal.class); 15814 if (dsm != null) { 15815 dsm.checkMemory(); 15816 } 15817 } 15818 if(observer != null) { 15819 try { 15820 observer.onRemoveCompleted(packageName, succeeded); 15821 } catch (RemoteException e) { 15822 Log.i(TAG, "Observer no longer exists."); 15823 } 15824 } //end if observer 15825 } //end run 15826 }); 15827 } 15828 15829 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15830 if (packageName == null) { 15831 Slog.w(TAG, "Attempt to delete null packageName."); 15832 return false; 15833 } 15834 15835 // Try finding details about the requested package 15836 PackageParser.Package pkg; 15837 synchronized (mPackages) { 15838 pkg = mPackages.get(packageName); 15839 if (pkg == null) { 15840 final PackageSetting ps = mSettings.mPackages.get(packageName); 15841 if (ps != null) { 15842 pkg = ps.pkg; 15843 } 15844 } 15845 15846 if (pkg == null) { 15847 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15848 return false; 15849 } 15850 15851 PackageSetting ps = (PackageSetting) pkg.mExtras; 15852 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15853 } 15854 15855 clearAppDataLIF(pkg, userId, 15856 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15857 15858 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 15859 removeKeystoreDataIfNeeded(userId, appId); 15860 15861 final UserManager um = mContext.getSystemService(UserManager.class); 15862 final int flags; 15863 if (um.isUserUnlocked(userId)) { 15864 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 15865 } else if (um.isUserRunning(userId)) { 15866 flags = StorageManager.FLAG_STORAGE_DE; 15867 } else { 15868 flags = 0; 15869 } 15870 prepareAppDataContentsLIF(pkg, userId, flags); 15871 15872 return true; 15873 } 15874 15875 /** 15876 * Reverts user permission state changes (permissions and flags) in 15877 * all packages for a given user. 15878 * 15879 * @param userId The device user for which to do a reset. 15880 */ 15881 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 15882 final int packageCount = mPackages.size(); 15883 for (int i = 0; i < packageCount; i++) { 15884 PackageParser.Package pkg = mPackages.valueAt(i); 15885 PackageSetting ps = (PackageSetting) pkg.mExtras; 15886 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 15887 } 15888 } 15889 15890 /** 15891 * Reverts user permission state changes (permissions and flags). 15892 * 15893 * @param ps The package for which to reset. 15894 * @param userId The device user for which to do a reset. 15895 */ 15896 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 15897 final PackageSetting ps, final int userId) { 15898 if (ps.pkg == null) { 15899 return; 15900 } 15901 15902 // These are flags that can change base on user actions. 15903 final int userSettableMask = FLAG_PERMISSION_USER_SET 15904 | FLAG_PERMISSION_USER_FIXED 15905 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 15906 | FLAG_PERMISSION_REVIEW_REQUIRED; 15907 15908 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 15909 | FLAG_PERMISSION_POLICY_FIXED; 15910 15911 boolean writeInstallPermissions = false; 15912 boolean writeRuntimePermissions = false; 15913 15914 final int permissionCount = ps.pkg.requestedPermissions.size(); 15915 for (int i = 0; i < permissionCount; i++) { 15916 String permission = ps.pkg.requestedPermissions.get(i); 15917 15918 BasePermission bp = mSettings.mPermissions.get(permission); 15919 if (bp == null) { 15920 continue; 15921 } 15922 15923 // If shared user we just reset the state to which only this app contributed. 15924 if (ps.sharedUser != null) { 15925 boolean used = false; 15926 final int packageCount = ps.sharedUser.packages.size(); 15927 for (int j = 0; j < packageCount; j++) { 15928 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 15929 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 15930 && pkg.pkg.requestedPermissions.contains(permission)) { 15931 used = true; 15932 break; 15933 } 15934 } 15935 if (used) { 15936 continue; 15937 } 15938 } 15939 15940 PermissionsState permissionsState = ps.getPermissionsState(); 15941 15942 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 15943 15944 // Always clear the user settable flags. 15945 final boolean hasInstallState = permissionsState.getInstallPermissionState( 15946 bp.name) != null; 15947 // If permission review is enabled and this is a legacy app, mark the 15948 // permission as requiring a review as this is the initial state. 15949 int flags = 0; 15950 if (Build.PERMISSIONS_REVIEW_REQUIRED 15951 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 15952 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 15953 } 15954 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 15955 if (hasInstallState) { 15956 writeInstallPermissions = true; 15957 } else { 15958 writeRuntimePermissions = true; 15959 } 15960 } 15961 15962 // Below is only runtime permission handling. 15963 if (!bp.isRuntime()) { 15964 continue; 15965 } 15966 15967 // Never clobber system or policy. 15968 if ((oldFlags & policyOrSystemFlags) != 0) { 15969 continue; 15970 } 15971 15972 // If this permission was granted by default, make sure it is. 15973 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 15974 if (permissionsState.grantRuntimePermission(bp, userId) 15975 != PERMISSION_OPERATION_FAILURE) { 15976 writeRuntimePermissions = true; 15977 } 15978 // If permission review is enabled the permissions for a legacy apps 15979 // are represented as constantly granted runtime ones, so don't revoke. 15980 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 15981 // Otherwise, reset the permission. 15982 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 15983 switch (revokeResult) { 15984 case PERMISSION_OPERATION_SUCCESS: 15985 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 15986 writeRuntimePermissions = true; 15987 final int appId = ps.appId; 15988 mHandler.post(new Runnable() { 15989 @Override 15990 public void run() { 15991 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 15992 } 15993 }); 15994 } break; 15995 } 15996 } 15997 } 15998 15999 // Synchronously write as we are taking permissions away. 16000 if (writeRuntimePermissions) { 16001 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16002 } 16003 16004 // Synchronously write as we are taking permissions away. 16005 if (writeInstallPermissions) { 16006 mSettings.writeLPr(); 16007 } 16008 } 16009 16010 /** 16011 * Remove entries from the keystore daemon. Will only remove it if the 16012 * {@code appId} is valid. 16013 */ 16014 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16015 if (appId < 0) { 16016 return; 16017 } 16018 16019 final KeyStore keyStore = KeyStore.getInstance(); 16020 if (keyStore != null) { 16021 if (userId == UserHandle.USER_ALL) { 16022 for (final int individual : sUserManager.getUserIds()) { 16023 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16024 } 16025 } else { 16026 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16027 } 16028 } else { 16029 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16030 } 16031 } 16032 16033 @Override 16034 public void deleteApplicationCacheFiles(final String packageName, 16035 final IPackageDataObserver observer) { 16036 mContext.enforceCallingOrSelfPermission( 16037 android.Manifest.permission.DELETE_CACHE_FILES, null); 16038 // Queue up an async operation since the package deletion may take a little while. 16039 final int userId = UserHandle.getCallingUserId(); 16040 16041 final PackageParser.Package pkg; 16042 synchronized (mPackages) { 16043 pkg = mPackages.get(packageName); 16044 } 16045 16046 mHandler.post(new Runnable() { 16047 public void run() { 16048 try (PackageFreezer freezer = freezePackage(packageName, 16049 "deleteApplicationCacheFiles")) { 16050 synchronized (mInstallLock) { 16051 final int flags = StorageManager.FLAG_STORAGE_DE 16052 | StorageManager.FLAG_STORAGE_CE; 16053 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16054 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16055 } 16056 clearExternalStorageDataSync(packageName, userId, false); 16057 } 16058 if (observer != null) { 16059 try { 16060 observer.onRemoveCompleted(packageName, true); 16061 } catch (RemoteException e) { 16062 Log.i(TAG, "Observer no longer exists."); 16063 } 16064 } 16065 } 16066 }); 16067 } 16068 16069 @Override 16070 public void getPackageSizeInfo(final String packageName, int userHandle, 16071 final IPackageStatsObserver observer) { 16072 mContext.enforceCallingOrSelfPermission( 16073 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16074 if (packageName == null) { 16075 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16076 } 16077 16078 PackageStats stats = new PackageStats(packageName, userHandle); 16079 16080 /* 16081 * Queue up an async operation since the package measurement may take a 16082 * little while. 16083 */ 16084 Message msg = mHandler.obtainMessage(INIT_COPY); 16085 msg.obj = new MeasureParams(stats, observer); 16086 mHandler.sendMessage(msg); 16087 } 16088 16089 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16090 final PackageSetting ps; 16091 synchronized (mPackages) { 16092 ps = mSettings.mPackages.get(packageName); 16093 if (ps == null) { 16094 Slog.w(TAG, "Failed to find settings for " + packageName); 16095 return false; 16096 } 16097 } 16098 try { 16099 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16100 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16101 ps.getCeDataInode(userId), ps.codePathString, stats); 16102 return true; 16103 } catch (InstallerException e) { 16104 Slog.w(TAG, String.valueOf(e)); 16105 return false; 16106 } 16107 } 16108 16109 private int getUidTargetSdkVersionLockedLPr(int uid) { 16110 Object obj = mSettings.getUserIdLPr(uid); 16111 if (obj instanceof SharedUserSetting) { 16112 final SharedUserSetting sus = (SharedUserSetting) obj; 16113 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16114 final Iterator<PackageSetting> it = sus.packages.iterator(); 16115 while (it.hasNext()) { 16116 final PackageSetting ps = it.next(); 16117 if (ps.pkg != null) { 16118 int v = ps.pkg.applicationInfo.targetSdkVersion; 16119 if (v < vers) vers = v; 16120 } 16121 } 16122 return vers; 16123 } else if (obj instanceof PackageSetting) { 16124 final PackageSetting ps = (PackageSetting) obj; 16125 if (ps.pkg != null) { 16126 return ps.pkg.applicationInfo.targetSdkVersion; 16127 } 16128 } 16129 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16130 } 16131 16132 @Override 16133 public void addPreferredActivity(IntentFilter filter, int match, 16134 ComponentName[] set, ComponentName activity, int userId) { 16135 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16136 "Adding preferred"); 16137 } 16138 16139 private void addPreferredActivityInternal(IntentFilter filter, int match, 16140 ComponentName[] set, ComponentName activity, boolean always, int userId, 16141 String opname) { 16142 // writer 16143 int callingUid = Binder.getCallingUid(); 16144 enforceCrossUserPermission(callingUid, userId, 16145 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16146 if (filter.countActions() == 0) { 16147 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16148 return; 16149 } 16150 synchronized (mPackages) { 16151 if (mContext.checkCallingOrSelfPermission( 16152 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16153 != PackageManager.PERMISSION_GRANTED) { 16154 if (getUidTargetSdkVersionLockedLPr(callingUid) 16155 < Build.VERSION_CODES.FROYO) { 16156 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16157 + callingUid); 16158 return; 16159 } 16160 mContext.enforceCallingOrSelfPermission( 16161 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16162 } 16163 16164 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16165 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16166 + userId + ":"); 16167 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16168 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16169 scheduleWritePackageRestrictionsLocked(userId); 16170 } 16171 } 16172 16173 @Override 16174 public void replacePreferredActivity(IntentFilter filter, int match, 16175 ComponentName[] set, ComponentName activity, int userId) { 16176 if (filter.countActions() != 1) { 16177 throw new IllegalArgumentException( 16178 "replacePreferredActivity expects filter to have only 1 action."); 16179 } 16180 if (filter.countDataAuthorities() != 0 16181 || filter.countDataPaths() != 0 16182 || filter.countDataSchemes() > 1 16183 || filter.countDataTypes() != 0) { 16184 throw new IllegalArgumentException( 16185 "replacePreferredActivity expects filter to have no data authorities, " + 16186 "paths, or types; and at most one scheme."); 16187 } 16188 16189 final int callingUid = Binder.getCallingUid(); 16190 enforceCrossUserPermission(callingUid, userId, 16191 true /* requireFullPermission */, false /* checkShell */, 16192 "replace preferred activity"); 16193 synchronized (mPackages) { 16194 if (mContext.checkCallingOrSelfPermission( 16195 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16196 != PackageManager.PERMISSION_GRANTED) { 16197 if (getUidTargetSdkVersionLockedLPr(callingUid) 16198 < Build.VERSION_CODES.FROYO) { 16199 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16200 + Binder.getCallingUid()); 16201 return; 16202 } 16203 mContext.enforceCallingOrSelfPermission( 16204 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16205 } 16206 16207 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16208 if (pir != null) { 16209 // Get all of the existing entries that exactly match this filter. 16210 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16211 if (existing != null && existing.size() == 1) { 16212 PreferredActivity cur = existing.get(0); 16213 if (DEBUG_PREFERRED) { 16214 Slog.i(TAG, "Checking replace of preferred:"); 16215 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16216 if (!cur.mPref.mAlways) { 16217 Slog.i(TAG, " -- CUR; not mAlways!"); 16218 } else { 16219 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16220 Slog.i(TAG, " -- CUR: mSet=" 16221 + Arrays.toString(cur.mPref.mSetComponents)); 16222 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16223 Slog.i(TAG, " -- NEW: mMatch=" 16224 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16225 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16226 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16227 } 16228 } 16229 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16230 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16231 && cur.mPref.sameSet(set)) { 16232 // Setting the preferred activity to what it happens to be already 16233 if (DEBUG_PREFERRED) { 16234 Slog.i(TAG, "Replacing with same preferred activity " 16235 + cur.mPref.mShortComponent + " for user " 16236 + userId + ":"); 16237 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16238 } 16239 return; 16240 } 16241 } 16242 16243 if (existing != null) { 16244 if (DEBUG_PREFERRED) { 16245 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16246 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16247 } 16248 for (int i = 0; i < existing.size(); i++) { 16249 PreferredActivity pa = existing.get(i); 16250 if (DEBUG_PREFERRED) { 16251 Slog.i(TAG, "Removing existing preferred activity " 16252 + pa.mPref.mComponent + ":"); 16253 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16254 } 16255 pir.removeFilter(pa); 16256 } 16257 } 16258 } 16259 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16260 "Replacing preferred"); 16261 } 16262 } 16263 16264 @Override 16265 public void clearPackagePreferredActivities(String packageName) { 16266 final int uid = Binder.getCallingUid(); 16267 // writer 16268 synchronized (mPackages) { 16269 PackageParser.Package pkg = mPackages.get(packageName); 16270 if (pkg == null || pkg.applicationInfo.uid != uid) { 16271 if (mContext.checkCallingOrSelfPermission( 16272 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16273 != PackageManager.PERMISSION_GRANTED) { 16274 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16275 < Build.VERSION_CODES.FROYO) { 16276 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16277 + Binder.getCallingUid()); 16278 return; 16279 } 16280 mContext.enforceCallingOrSelfPermission( 16281 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16282 } 16283 } 16284 16285 int user = UserHandle.getCallingUserId(); 16286 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16287 scheduleWritePackageRestrictionsLocked(user); 16288 } 16289 } 16290 } 16291 16292 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16293 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16294 ArrayList<PreferredActivity> removed = null; 16295 boolean changed = false; 16296 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16297 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16298 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16299 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16300 continue; 16301 } 16302 Iterator<PreferredActivity> it = pir.filterIterator(); 16303 while (it.hasNext()) { 16304 PreferredActivity pa = it.next(); 16305 // Mark entry for removal only if it matches the package name 16306 // and the entry is of type "always". 16307 if (packageName == null || 16308 (pa.mPref.mComponent.getPackageName().equals(packageName) 16309 && pa.mPref.mAlways)) { 16310 if (removed == null) { 16311 removed = new ArrayList<PreferredActivity>(); 16312 } 16313 removed.add(pa); 16314 } 16315 } 16316 if (removed != null) { 16317 for (int j=0; j<removed.size(); j++) { 16318 PreferredActivity pa = removed.get(j); 16319 pir.removeFilter(pa); 16320 } 16321 changed = true; 16322 } 16323 } 16324 return changed; 16325 } 16326 16327 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16328 private void clearIntentFilterVerificationsLPw(int userId) { 16329 final int packageCount = mPackages.size(); 16330 for (int i = 0; i < packageCount; i++) { 16331 PackageParser.Package pkg = mPackages.valueAt(i); 16332 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16333 } 16334 } 16335 16336 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16337 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16338 if (userId == UserHandle.USER_ALL) { 16339 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16340 sUserManager.getUserIds())) { 16341 for (int oneUserId : sUserManager.getUserIds()) { 16342 scheduleWritePackageRestrictionsLocked(oneUserId); 16343 } 16344 } 16345 } else { 16346 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16347 scheduleWritePackageRestrictionsLocked(userId); 16348 } 16349 } 16350 } 16351 16352 void clearDefaultBrowserIfNeeded(String packageName) { 16353 for (int oneUserId : sUserManager.getUserIds()) { 16354 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16355 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16356 if (packageName.equals(defaultBrowserPackageName)) { 16357 setDefaultBrowserPackageName(null, oneUserId); 16358 } 16359 } 16360 } 16361 16362 @Override 16363 public void resetApplicationPreferences(int userId) { 16364 mContext.enforceCallingOrSelfPermission( 16365 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16366 // writer 16367 synchronized (mPackages) { 16368 final long identity = Binder.clearCallingIdentity(); 16369 try { 16370 clearPackagePreferredActivitiesLPw(null, userId); 16371 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16372 // TODO: We have to reset the default SMS and Phone. This requires 16373 // significant refactoring to keep all default apps in the package 16374 // manager (cleaner but more work) or have the services provide 16375 // callbacks to the package manager to request a default app reset. 16376 applyFactoryDefaultBrowserLPw(userId); 16377 clearIntentFilterVerificationsLPw(userId); 16378 primeDomainVerificationsLPw(userId); 16379 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16380 scheduleWritePackageRestrictionsLocked(userId); 16381 } finally { 16382 Binder.restoreCallingIdentity(identity); 16383 } 16384 } 16385 } 16386 16387 @Override 16388 public int getPreferredActivities(List<IntentFilter> outFilters, 16389 List<ComponentName> outActivities, String packageName) { 16390 16391 int num = 0; 16392 final int userId = UserHandle.getCallingUserId(); 16393 // reader 16394 synchronized (mPackages) { 16395 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16396 if (pir != null) { 16397 final Iterator<PreferredActivity> it = pir.filterIterator(); 16398 while (it.hasNext()) { 16399 final PreferredActivity pa = it.next(); 16400 if (packageName == null 16401 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16402 && pa.mPref.mAlways)) { 16403 if (outFilters != null) { 16404 outFilters.add(new IntentFilter(pa)); 16405 } 16406 if (outActivities != null) { 16407 outActivities.add(pa.mPref.mComponent); 16408 } 16409 } 16410 } 16411 } 16412 } 16413 16414 return num; 16415 } 16416 16417 @Override 16418 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16419 int userId) { 16420 int callingUid = Binder.getCallingUid(); 16421 if (callingUid != Process.SYSTEM_UID) { 16422 throw new SecurityException( 16423 "addPersistentPreferredActivity can only be run by the system"); 16424 } 16425 if (filter.countActions() == 0) { 16426 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16427 return; 16428 } 16429 synchronized (mPackages) { 16430 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16431 ":"); 16432 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16433 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16434 new PersistentPreferredActivity(filter, activity)); 16435 scheduleWritePackageRestrictionsLocked(userId); 16436 } 16437 } 16438 16439 @Override 16440 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16441 int callingUid = Binder.getCallingUid(); 16442 if (callingUid != Process.SYSTEM_UID) { 16443 throw new SecurityException( 16444 "clearPackagePersistentPreferredActivities can only be run by the system"); 16445 } 16446 ArrayList<PersistentPreferredActivity> removed = null; 16447 boolean changed = false; 16448 synchronized (mPackages) { 16449 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16450 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16451 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16452 .valueAt(i); 16453 if (userId != thisUserId) { 16454 continue; 16455 } 16456 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16457 while (it.hasNext()) { 16458 PersistentPreferredActivity ppa = it.next(); 16459 // Mark entry for removal only if it matches the package name. 16460 if (ppa.mComponent.getPackageName().equals(packageName)) { 16461 if (removed == null) { 16462 removed = new ArrayList<PersistentPreferredActivity>(); 16463 } 16464 removed.add(ppa); 16465 } 16466 } 16467 if (removed != null) { 16468 for (int j=0; j<removed.size(); j++) { 16469 PersistentPreferredActivity ppa = removed.get(j); 16470 ppir.removeFilter(ppa); 16471 } 16472 changed = true; 16473 } 16474 } 16475 16476 if (changed) { 16477 scheduleWritePackageRestrictionsLocked(userId); 16478 } 16479 } 16480 } 16481 16482 /** 16483 * Common machinery for picking apart a restored XML blob and passing 16484 * it to a caller-supplied functor to be applied to the running system. 16485 */ 16486 private void restoreFromXml(XmlPullParser parser, int userId, 16487 String expectedStartTag, BlobXmlRestorer functor) 16488 throws IOException, XmlPullParserException { 16489 int type; 16490 while ((type = parser.next()) != XmlPullParser.START_TAG 16491 && type != XmlPullParser.END_DOCUMENT) { 16492 } 16493 if (type != XmlPullParser.START_TAG) { 16494 // oops didn't find a start tag?! 16495 if (DEBUG_BACKUP) { 16496 Slog.e(TAG, "Didn't find start tag during restore"); 16497 } 16498 return; 16499 } 16500Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16501 // this is supposed to be TAG_PREFERRED_BACKUP 16502 if (!expectedStartTag.equals(parser.getName())) { 16503 if (DEBUG_BACKUP) { 16504 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16505 } 16506 return; 16507 } 16508 16509 // skip interfering stuff, then we're aligned with the backing implementation 16510 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16511Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16512 functor.apply(parser, userId); 16513 } 16514 16515 private interface BlobXmlRestorer { 16516 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16517 } 16518 16519 /** 16520 * Non-Binder method, support for the backup/restore mechanism: write the 16521 * full set of preferred activities in its canonical XML format. Returns the 16522 * XML output as a byte array, or null if there is none. 16523 */ 16524 @Override 16525 public byte[] getPreferredActivityBackup(int userId) { 16526 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16527 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16528 } 16529 16530 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16531 try { 16532 final XmlSerializer serializer = new FastXmlSerializer(); 16533 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16534 serializer.startDocument(null, true); 16535 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16536 16537 synchronized (mPackages) { 16538 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16539 } 16540 16541 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16542 serializer.endDocument(); 16543 serializer.flush(); 16544 } catch (Exception e) { 16545 if (DEBUG_BACKUP) { 16546 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16547 } 16548 return null; 16549 } 16550 16551 return dataStream.toByteArray(); 16552 } 16553 16554 @Override 16555 public void restorePreferredActivities(byte[] backup, int userId) { 16556 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16557 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16558 } 16559 16560 try { 16561 final XmlPullParser parser = Xml.newPullParser(); 16562 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16563 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16564 new BlobXmlRestorer() { 16565 @Override 16566 public void apply(XmlPullParser parser, int userId) 16567 throws XmlPullParserException, IOException { 16568 synchronized (mPackages) { 16569 mSettings.readPreferredActivitiesLPw(parser, userId); 16570 } 16571 } 16572 } ); 16573 } catch (Exception e) { 16574 if (DEBUG_BACKUP) { 16575 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16576 } 16577 } 16578 } 16579 16580 /** 16581 * Non-Binder method, support for the backup/restore mechanism: write the 16582 * default browser (etc) settings in its canonical XML format. Returns the default 16583 * browser XML representation as a byte array, or null if there is none. 16584 */ 16585 @Override 16586 public byte[] getDefaultAppsBackup(int userId) { 16587 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16588 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16589 } 16590 16591 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16592 try { 16593 final XmlSerializer serializer = new FastXmlSerializer(); 16594 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16595 serializer.startDocument(null, true); 16596 serializer.startTag(null, TAG_DEFAULT_APPS); 16597 16598 synchronized (mPackages) { 16599 mSettings.writeDefaultAppsLPr(serializer, userId); 16600 } 16601 16602 serializer.endTag(null, TAG_DEFAULT_APPS); 16603 serializer.endDocument(); 16604 serializer.flush(); 16605 } catch (Exception e) { 16606 if (DEBUG_BACKUP) { 16607 Slog.e(TAG, "Unable to write default apps for backup", e); 16608 } 16609 return null; 16610 } 16611 16612 return dataStream.toByteArray(); 16613 } 16614 16615 @Override 16616 public void restoreDefaultApps(byte[] backup, int userId) { 16617 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16618 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16619 } 16620 16621 try { 16622 final XmlPullParser parser = Xml.newPullParser(); 16623 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16624 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16625 new BlobXmlRestorer() { 16626 @Override 16627 public void apply(XmlPullParser parser, int userId) 16628 throws XmlPullParserException, IOException { 16629 synchronized (mPackages) { 16630 mSettings.readDefaultAppsLPw(parser, userId); 16631 } 16632 } 16633 } ); 16634 } catch (Exception e) { 16635 if (DEBUG_BACKUP) { 16636 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16637 } 16638 } 16639 } 16640 16641 @Override 16642 public byte[] getIntentFilterVerificationBackup(int userId) { 16643 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16644 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16645 } 16646 16647 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16648 try { 16649 final XmlSerializer serializer = new FastXmlSerializer(); 16650 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16651 serializer.startDocument(null, true); 16652 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16653 16654 synchronized (mPackages) { 16655 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16656 } 16657 16658 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16659 serializer.endDocument(); 16660 serializer.flush(); 16661 } catch (Exception e) { 16662 if (DEBUG_BACKUP) { 16663 Slog.e(TAG, "Unable to write default apps for backup", e); 16664 } 16665 return null; 16666 } 16667 16668 return dataStream.toByteArray(); 16669 } 16670 16671 @Override 16672 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16673 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16674 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16675 } 16676 16677 try { 16678 final XmlPullParser parser = Xml.newPullParser(); 16679 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16680 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16681 new BlobXmlRestorer() { 16682 @Override 16683 public void apply(XmlPullParser parser, int userId) 16684 throws XmlPullParserException, IOException { 16685 synchronized (mPackages) { 16686 mSettings.readAllDomainVerificationsLPr(parser, userId); 16687 mSettings.writeLPr(); 16688 } 16689 } 16690 } ); 16691 } catch (Exception e) { 16692 if (DEBUG_BACKUP) { 16693 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16694 } 16695 } 16696 } 16697 16698 @Override 16699 public byte[] getPermissionGrantBackup(int userId) { 16700 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16701 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16702 } 16703 16704 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16705 try { 16706 final XmlSerializer serializer = new FastXmlSerializer(); 16707 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16708 serializer.startDocument(null, true); 16709 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16710 16711 synchronized (mPackages) { 16712 serializeRuntimePermissionGrantsLPr(serializer, userId); 16713 } 16714 16715 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16716 serializer.endDocument(); 16717 serializer.flush(); 16718 } catch (Exception e) { 16719 if (DEBUG_BACKUP) { 16720 Slog.e(TAG, "Unable to write default apps for backup", e); 16721 } 16722 return null; 16723 } 16724 16725 return dataStream.toByteArray(); 16726 } 16727 16728 @Override 16729 public void restorePermissionGrants(byte[] backup, int userId) { 16730 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16731 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16732 } 16733 16734 try { 16735 final XmlPullParser parser = Xml.newPullParser(); 16736 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16737 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16738 new BlobXmlRestorer() { 16739 @Override 16740 public void apply(XmlPullParser parser, int userId) 16741 throws XmlPullParserException, IOException { 16742 synchronized (mPackages) { 16743 processRestoredPermissionGrantsLPr(parser, userId); 16744 } 16745 } 16746 } ); 16747 } catch (Exception e) { 16748 if (DEBUG_BACKUP) { 16749 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16750 } 16751 } 16752 } 16753 16754 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16755 throws IOException { 16756 serializer.startTag(null, TAG_ALL_GRANTS); 16757 16758 final int N = mSettings.mPackages.size(); 16759 for (int i = 0; i < N; i++) { 16760 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16761 boolean pkgGrantsKnown = false; 16762 16763 PermissionsState packagePerms = ps.getPermissionsState(); 16764 16765 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16766 final int grantFlags = state.getFlags(); 16767 // only look at grants that are not system/policy fixed 16768 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16769 final boolean isGranted = state.isGranted(); 16770 // And only back up the user-twiddled state bits 16771 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16772 final String packageName = mSettings.mPackages.keyAt(i); 16773 if (!pkgGrantsKnown) { 16774 serializer.startTag(null, TAG_GRANT); 16775 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16776 pkgGrantsKnown = true; 16777 } 16778 16779 final boolean userSet = 16780 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16781 final boolean userFixed = 16782 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16783 final boolean revoke = 16784 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16785 16786 serializer.startTag(null, TAG_PERMISSION); 16787 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16788 if (isGranted) { 16789 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16790 } 16791 if (userSet) { 16792 serializer.attribute(null, ATTR_USER_SET, "true"); 16793 } 16794 if (userFixed) { 16795 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16796 } 16797 if (revoke) { 16798 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16799 } 16800 serializer.endTag(null, TAG_PERMISSION); 16801 } 16802 } 16803 } 16804 16805 if (pkgGrantsKnown) { 16806 serializer.endTag(null, TAG_GRANT); 16807 } 16808 } 16809 16810 serializer.endTag(null, TAG_ALL_GRANTS); 16811 } 16812 16813 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16814 throws XmlPullParserException, IOException { 16815 String pkgName = null; 16816 int outerDepth = parser.getDepth(); 16817 int type; 16818 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16819 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16820 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16821 continue; 16822 } 16823 16824 final String tagName = parser.getName(); 16825 if (tagName.equals(TAG_GRANT)) { 16826 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16827 if (DEBUG_BACKUP) { 16828 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 16829 } 16830 } else if (tagName.equals(TAG_PERMISSION)) { 16831 16832 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 16833 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 16834 16835 int newFlagSet = 0; 16836 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 16837 newFlagSet |= FLAG_PERMISSION_USER_SET; 16838 } 16839 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 16840 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 16841 } 16842 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 16843 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 16844 } 16845 if (DEBUG_BACKUP) { 16846 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 16847 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 16848 } 16849 final PackageSetting ps = mSettings.mPackages.get(pkgName); 16850 if (ps != null) { 16851 // Already installed so we apply the grant immediately 16852 if (DEBUG_BACKUP) { 16853 Slog.v(TAG, " + already installed; applying"); 16854 } 16855 PermissionsState perms = ps.getPermissionsState(); 16856 BasePermission bp = mSettings.mPermissions.get(permName); 16857 if (bp != null) { 16858 if (isGranted) { 16859 perms.grantRuntimePermission(bp, userId); 16860 } 16861 if (newFlagSet != 0) { 16862 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 16863 } 16864 } 16865 } else { 16866 // Need to wait for post-restore install to apply the grant 16867 if (DEBUG_BACKUP) { 16868 Slog.v(TAG, " - not yet installed; saving for later"); 16869 } 16870 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 16871 isGranted, newFlagSet, userId); 16872 } 16873 } else { 16874 PackageManagerService.reportSettingsProblem(Log.WARN, 16875 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 16876 XmlUtils.skipCurrentTag(parser); 16877 } 16878 } 16879 16880 scheduleWriteSettingsLocked(); 16881 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 16882 } 16883 16884 @Override 16885 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 16886 int sourceUserId, int targetUserId, int flags) { 16887 mContext.enforceCallingOrSelfPermission( 16888 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16889 int callingUid = Binder.getCallingUid(); 16890 enforceOwnerRights(ownerPackage, callingUid); 16891 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16892 if (intentFilter.countActions() == 0) { 16893 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 16894 return; 16895 } 16896 synchronized (mPackages) { 16897 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 16898 ownerPackage, targetUserId, flags); 16899 CrossProfileIntentResolver resolver = 16900 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16901 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 16902 // We have all those whose filter is equal. Now checking if the rest is equal as well. 16903 if (existing != null) { 16904 int size = existing.size(); 16905 for (int i = 0; i < size; i++) { 16906 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 16907 return; 16908 } 16909 } 16910 } 16911 resolver.addFilter(newFilter); 16912 scheduleWritePackageRestrictionsLocked(sourceUserId); 16913 } 16914 } 16915 16916 @Override 16917 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 16918 mContext.enforceCallingOrSelfPermission( 16919 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 16920 int callingUid = Binder.getCallingUid(); 16921 enforceOwnerRights(ownerPackage, callingUid); 16922 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 16923 synchronized (mPackages) { 16924 CrossProfileIntentResolver resolver = 16925 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 16926 ArraySet<CrossProfileIntentFilter> set = 16927 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 16928 for (CrossProfileIntentFilter filter : set) { 16929 if (filter.getOwnerPackage().equals(ownerPackage)) { 16930 resolver.removeFilter(filter); 16931 } 16932 } 16933 scheduleWritePackageRestrictionsLocked(sourceUserId); 16934 } 16935 } 16936 16937 // Enforcing that callingUid is owning pkg on userId 16938 private void enforceOwnerRights(String pkg, int callingUid) { 16939 // The system owns everything. 16940 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 16941 return; 16942 } 16943 int callingUserId = UserHandle.getUserId(callingUid); 16944 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 16945 if (pi == null) { 16946 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 16947 + callingUserId); 16948 } 16949 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 16950 throw new SecurityException("Calling uid " + callingUid 16951 + " does not own package " + pkg); 16952 } 16953 } 16954 16955 @Override 16956 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 16957 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 16958 } 16959 16960 private Intent getHomeIntent() { 16961 Intent intent = new Intent(Intent.ACTION_MAIN); 16962 intent.addCategory(Intent.CATEGORY_HOME); 16963 return intent; 16964 } 16965 16966 private IntentFilter getHomeFilter() { 16967 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 16968 filter.addCategory(Intent.CATEGORY_HOME); 16969 filter.addCategory(Intent.CATEGORY_DEFAULT); 16970 return filter; 16971 } 16972 16973 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 16974 int userId) { 16975 Intent intent = getHomeIntent(); 16976 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 16977 PackageManager.GET_META_DATA, userId); 16978 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 16979 true, false, false, userId); 16980 16981 allHomeCandidates.clear(); 16982 if (list != null) { 16983 for (ResolveInfo ri : list) { 16984 allHomeCandidates.add(ri); 16985 } 16986 } 16987 return (preferred == null || preferred.activityInfo == null) 16988 ? null 16989 : new ComponentName(preferred.activityInfo.packageName, 16990 preferred.activityInfo.name); 16991 } 16992 16993 @Override 16994 public void setHomeActivity(ComponentName comp, int userId) { 16995 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 16996 getHomeActivitiesAsUser(homeActivities, userId); 16997 16998 boolean found = false; 16999 17000 final int size = homeActivities.size(); 17001 final ComponentName[] set = new ComponentName[size]; 17002 for (int i = 0; i < size; i++) { 17003 final ResolveInfo candidate = homeActivities.get(i); 17004 final ActivityInfo info = candidate.activityInfo; 17005 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17006 set[i] = activityName; 17007 if (!found && activityName.equals(comp)) { 17008 found = true; 17009 } 17010 } 17011 if (!found) { 17012 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17013 + userId); 17014 } 17015 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17016 set, comp, userId); 17017 } 17018 17019 private @Nullable String getSetupWizardPackageName() { 17020 final Intent intent = new Intent(Intent.ACTION_MAIN); 17021 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17022 17023 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17024 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17025 | MATCH_DISABLED_COMPONENTS, 17026 UserHandle.myUserId()); 17027 if (matches.size() == 1) { 17028 return matches.get(0).getComponentInfo().packageName; 17029 } else { 17030 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17031 + ": matches=" + matches); 17032 return null; 17033 } 17034 } 17035 17036 @Override 17037 public void setApplicationEnabledSetting(String appPackageName, 17038 int newState, int flags, int userId, String callingPackage) { 17039 if (!sUserManager.exists(userId)) return; 17040 if (callingPackage == null) { 17041 callingPackage = Integer.toString(Binder.getCallingUid()); 17042 } 17043 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17044 } 17045 17046 @Override 17047 public void setComponentEnabledSetting(ComponentName componentName, 17048 int newState, int flags, int userId) { 17049 if (!sUserManager.exists(userId)) return; 17050 setEnabledSetting(componentName.getPackageName(), 17051 componentName.getClassName(), newState, flags, userId, null); 17052 } 17053 17054 private void setEnabledSetting(final String packageName, String className, int newState, 17055 final int flags, int userId, String callingPackage) { 17056 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17057 || newState == COMPONENT_ENABLED_STATE_ENABLED 17058 || newState == COMPONENT_ENABLED_STATE_DISABLED 17059 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17060 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17061 throw new IllegalArgumentException("Invalid new component state: " 17062 + newState); 17063 } 17064 PackageSetting pkgSetting; 17065 final int uid = Binder.getCallingUid(); 17066 final int permission; 17067 if (uid == Process.SYSTEM_UID) { 17068 permission = PackageManager.PERMISSION_GRANTED; 17069 } else { 17070 permission = mContext.checkCallingOrSelfPermission( 17071 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17072 } 17073 enforceCrossUserPermission(uid, userId, 17074 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17075 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17076 boolean sendNow = false; 17077 boolean isApp = (className == null); 17078 String componentName = isApp ? packageName : className; 17079 int packageUid = -1; 17080 ArrayList<String> components; 17081 17082 // writer 17083 synchronized (mPackages) { 17084 pkgSetting = mSettings.mPackages.get(packageName); 17085 if (pkgSetting == null) { 17086 if (className == null) { 17087 throw new IllegalArgumentException("Unknown package: " + packageName); 17088 } 17089 throw new IllegalArgumentException( 17090 "Unknown component: " + packageName + "/" + className); 17091 } 17092 // Allow root and verify that userId is not being specified by a different user 17093 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17094 throw new SecurityException( 17095 "Permission Denial: attempt to change component state from pid=" 17096 + Binder.getCallingPid() 17097 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17098 } 17099 if (className == null) { 17100 // We're dealing with an application/package level state change 17101 if (pkgSetting.getEnabled(userId) == newState) { 17102 // Nothing to do 17103 return; 17104 } 17105 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17106 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17107 // Don't care about who enables an app. 17108 callingPackage = null; 17109 } 17110 pkgSetting.setEnabled(newState, userId, callingPackage); 17111 // pkgSetting.pkg.mSetEnabled = newState; 17112 } else { 17113 // We're dealing with a component level state change 17114 // First, verify that this is a valid class name. 17115 PackageParser.Package pkg = pkgSetting.pkg; 17116 if (pkg == null || !pkg.hasComponentClassName(className)) { 17117 if (pkg != null && 17118 pkg.applicationInfo.targetSdkVersion >= 17119 Build.VERSION_CODES.JELLY_BEAN) { 17120 throw new IllegalArgumentException("Component class " + className 17121 + " does not exist in " + packageName); 17122 } else { 17123 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17124 + className + " does not exist in " + packageName); 17125 } 17126 } 17127 switch (newState) { 17128 case COMPONENT_ENABLED_STATE_ENABLED: 17129 if (!pkgSetting.enableComponentLPw(className, userId)) { 17130 return; 17131 } 17132 break; 17133 case COMPONENT_ENABLED_STATE_DISABLED: 17134 if (!pkgSetting.disableComponentLPw(className, userId)) { 17135 return; 17136 } 17137 break; 17138 case COMPONENT_ENABLED_STATE_DEFAULT: 17139 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17140 return; 17141 } 17142 break; 17143 default: 17144 Slog.e(TAG, "Invalid new component state: " + newState); 17145 return; 17146 } 17147 } 17148 scheduleWritePackageRestrictionsLocked(userId); 17149 components = mPendingBroadcasts.get(userId, packageName); 17150 final boolean newPackage = components == null; 17151 if (newPackage) { 17152 components = new ArrayList<String>(); 17153 } 17154 if (!components.contains(componentName)) { 17155 components.add(componentName); 17156 } 17157 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17158 sendNow = true; 17159 // Purge entry from pending broadcast list if another one exists already 17160 // since we are sending one right away. 17161 mPendingBroadcasts.remove(userId, packageName); 17162 } else { 17163 if (newPackage) { 17164 mPendingBroadcasts.put(userId, packageName, components); 17165 } 17166 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17167 // Schedule a message 17168 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17169 } 17170 } 17171 } 17172 17173 long callingId = Binder.clearCallingIdentity(); 17174 try { 17175 if (sendNow) { 17176 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17177 sendPackageChangedBroadcast(packageName, 17178 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17179 } 17180 } finally { 17181 Binder.restoreCallingIdentity(callingId); 17182 } 17183 } 17184 17185 @Override 17186 public void flushPackageRestrictionsAsUser(int userId) { 17187 if (!sUserManager.exists(userId)) { 17188 return; 17189 } 17190 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17191 false /* checkShell */, "flushPackageRestrictions"); 17192 synchronized (mPackages) { 17193 mSettings.writePackageRestrictionsLPr(userId); 17194 mDirtyUsers.remove(userId); 17195 if (mDirtyUsers.isEmpty()) { 17196 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17197 } 17198 } 17199 } 17200 17201 private void sendPackageChangedBroadcast(String packageName, 17202 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17203 if (DEBUG_INSTALL) 17204 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17205 + componentNames); 17206 Bundle extras = new Bundle(4); 17207 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17208 String nameList[] = new String[componentNames.size()]; 17209 componentNames.toArray(nameList); 17210 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17211 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17212 extras.putInt(Intent.EXTRA_UID, packageUid); 17213 // If this is not reporting a change of the overall package, then only send it 17214 // to registered receivers. We don't want to launch a swath of apps for every 17215 // little component state change. 17216 final int flags = !componentNames.contains(packageName) 17217 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17218 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17219 new int[] {UserHandle.getUserId(packageUid)}); 17220 } 17221 17222 @Override 17223 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17224 if (!sUserManager.exists(userId)) return; 17225 final int uid = Binder.getCallingUid(); 17226 final int permission = mContext.checkCallingOrSelfPermission( 17227 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17228 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17229 enforceCrossUserPermission(uid, userId, 17230 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17231 // writer 17232 synchronized (mPackages) { 17233 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17234 allowedByPermission, uid, userId)) { 17235 scheduleWritePackageRestrictionsLocked(userId); 17236 } 17237 } 17238 } 17239 17240 @Override 17241 public String getInstallerPackageName(String packageName) { 17242 // reader 17243 synchronized (mPackages) { 17244 return mSettings.getInstallerPackageNameLPr(packageName); 17245 } 17246 } 17247 17248 @Override 17249 public int getApplicationEnabledSetting(String packageName, int userId) { 17250 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17251 int uid = Binder.getCallingUid(); 17252 enforceCrossUserPermission(uid, userId, 17253 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17254 // reader 17255 synchronized (mPackages) { 17256 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17257 } 17258 } 17259 17260 @Override 17261 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17262 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17263 int uid = Binder.getCallingUid(); 17264 enforceCrossUserPermission(uid, userId, 17265 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17266 // reader 17267 synchronized (mPackages) { 17268 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17269 } 17270 } 17271 17272 @Override 17273 public void enterSafeMode() { 17274 enforceSystemOrRoot("Only the system can request entering safe mode"); 17275 17276 if (!mSystemReady) { 17277 mSafeMode = true; 17278 } 17279 } 17280 17281 @Override 17282 public void systemReady() { 17283 mSystemReady = true; 17284 17285 // Read the compatibilty setting when the system is ready. 17286 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17287 mContext.getContentResolver(), 17288 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17289 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17290 if (DEBUG_SETTINGS) { 17291 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17292 } 17293 17294 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17295 17296 synchronized (mPackages) { 17297 // Verify that all of the preferred activity components actually 17298 // exist. It is possible for applications to be updated and at 17299 // that point remove a previously declared activity component that 17300 // had been set as a preferred activity. We try to clean this up 17301 // the next time we encounter that preferred activity, but it is 17302 // possible for the user flow to never be able to return to that 17303 // situation so here we do a sanity check to make sure we haven't 17304 // left any junk around. 17305 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17306 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17307 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17308 removed.clear(); 17309 for (PreferredActivity pa : pir.filterSet()) { 17310 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17311 removed.add(pa); 17312 } 17313 } 17314 if (removed.size() > 0) { 17315 for (int r=0; r<removed.size(); r++) { 17316 PreferredActivity pa = removed.get(r); 17317 Slog.w(TAG, "Removing dangling preferred activity: " 17318 + pa.mPref.mComponent); 17319 pir.removeFilter(pa); 17320 } 17321 mSettings.writePackageRestrictionsLPr( 17322 mSettings.mPreferredActivities.keyAt(i)); 17323 } 17324 } 17325 17326 for (int userId : UserManagerService.getInstance().getUserIds()) { 17327 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17328 grantPermissionsUserIds = ArrayUtils.appendInt( 17329 grantPermissionsUserIds, userId); 17330 } 17331 } 17332 } 17333 sUserManager.systemReady(); 17334 17335 // If we upgraded grant all default permissions before kicking off. 17336 for (int userId : grantPermissionsUserIds) { 17337 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17338 } 17339 17340 // Kick off any messages waiting for system ready 17341 if (mPostSystemReadyMessages != null) { 17342 for (Message msg : mPostSystemReadyMessages) { 17343 msg.sendToTarget(); 17344 } 17345 mPostSystemReadyMessages = null; 17346 } 17347 17348 // Watch for external volumes that come and go over time 17349 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17350 storage.registerListener(mStorageListener); 17351 17352 mInstallerService.systemReady(); 17353 mPackageDexOptimizer.systemReady(); 17354 17355 MountServiceInternal mountServiceInternal = LocalServices.getService( 17356 MountServiceInternal.class); 17357 mountServiceInternal.addExternalStoragePolicy( 17358 new MountServiceInternal.ExternalStorageMountPolicy() { 17359 @Override 17360 public int getMountMode(int uid, String packageName) { 17361 if (Process.isIsolated(uid)) { 17362 return Zygote.MOUNT_EXTERNAL_NONE; 17363 } 17364 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17365 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17366 } 17367 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17368 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17369 } 17370 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17371 return Zygote.MOUNT_EXTERNAL_READ; 17372 } 17373 return Zygote.MOUNT_EXTERNAL_WRITE; 17374 } 17375 17376 @Override 17377 public boolean hasExternalStorage(int uid, String packageName) { 17378 return true; 17379 } 17380 }); 17381 } 17382 17383 @Override 17384 public boolean isSafeMode() { 17385 return mSafeMode; 17386 } 17387 17388 @Override 17389 public boolean hasSystemUidErrors() { 17390 return mHasSystemUidErrors; 17391 } 17392 17393 static String arrayToString(int[] array) { 17394 StringBuffer buf = new StringBuffer(128); 17395 buf.append('['); 17396 if (array != null) { 17397 for (int i=0; i<array.length; i++) { 17398 if (i > 0) buf.append(", "); 17399 buf.append(array[i]); 17400 } 17401 } 17402 buf.append(']'); 17403 return buf.toString(); 17404 } 17405 17406 static class DumpState { 17407 public static final int DUMP_LIBS = 1 << 0; 17408 public static final int DUMP_FEATURES = 1 << 1; 17409 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17410 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17411 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17412 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17413 public static final int DUMP_PERMISSIONS = 1 << 6; 17414 public static final int DUMP_PACKAGES = 1 << 7; 17415 public static final int DUMP_SHARED_USERS = 1 << 8; 17416 public static final int DUMP_MESSAGES = 1 << 9; 17417 public static final int DUMP_PROVIDERS = 1 << 10; 17418 public static final int DUMP_VERIFIERS = 1 << 11; 17419 public static final int DUMP_PREFERRED = 1 << 12; 17420 public static final int DUMP_PREFERRED_XML = 1 << 13; 17421 public static final int DUMP_KEYSETS = 1 << 14; 17422 public static final int DUMP_VERSION = 1 << 15; 17423 public static final int DUMP_INSTALLS = 1 << 16; 17424 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17425 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17426 public static final int DUMP_FROZEN = 1 << 19; 17427 17428 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17429 17430 private int mTypes; 17431 17432 private int mOptions; 17433 17434 private boolean mTitlePrinted; 17435 17436 private SharedUserSetting mSharedUser; 17437 17438 public boolean isDumping(int type) { 17439 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17440 return true; 17441 } 17442 17443 return (mTypes & type) != 0; 17444 } 17445 17446 public void setDump(int type) { 17447 mTypes |= type; 17448 } 17449 17450 public boolean isOptionEnabled(int option) { 17451 return (mOptions & option) != 0; 17452 } 17453 17454 public void setOptionEnabled(int option) { 17455 mOptions |= option; 17456 } 17457 17458 public boolean onTitlePrinted() { 17459 final boolean printed = mTitlePrinted; 17460 mTitlePrinted = true; 17461 return printed; 17462 } 17463 17464 public boolean getTitlePrinted() { 17465 return mTitlePrinted; 17466 } 17467 17468 public void setTitlePrinted(boolean enabled) { 17469 mTitlePrinted = enabled; 17470 } 17471 17472 public SharedUserSetting getSharedUser() { 17473 return mSharedUser; 17474 } 17475 17476 public void setSharedUser(SharedUserSetting user) { 17477 mSharedUser = user; 17478 } 17479 } 17480 17481 @Override 17482 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17483 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17484 (new PackageManagerShellCommand(this)).exec( 17485 this, in, out, err, args, resultReceiver); 17486 } 17487 17488 @Override 17489 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17490 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17491 != PackageManager.PERMISSION_GRANTED) { 17492 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17493 + Binder.getCallingPid() 17494 + ", uid=" + Binder.getCallingUid() 17495 + " without permission " 17496 + android.Manifest.permission.DUMP); 17497 return; 17498 } 17499 17500 DumpState dumpState = new DumpState(); 17501 boolean fullPreferred = false; 17502 boolean checkin = false; 17503 17504 String packageName = null; 17505 ArraySet<String> permissionNames = null; 17506 17507 int opti = 0; 17508 while (opti < args.length) { 17509 String opt = args[opti]; 17510 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17511 break; 17512 } 17513 opti++; 17514 17515 if ("-a".equals(opt)) { 17516 // Right now we only know how to print all. 17517 } else if ("-h".equals(opt)) { 17518 pw.println("Package manager dump options:"); 17519 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17520 pw.println(" --checkin: dump for a checkin"); 17521 pw.println(" -f: print details of intent filters"); 17522 pw.println(" -h: print this help"); 17523 pw.println(" cmd may be one of:"); 17524 pw.println(" l[ibraries]: list known shared libraries"); 17525 pw.println(" f[eatures]: list device features"); 17526 pw.println(" k[eysets]: print known keysets"); 17527 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17528 pw.println(" perm[issions]: dump permissions"); 17529 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17530 pw.println(" pref[erred]: print preferred package settings"); 17531 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17532 pw.println(" prov[iders]: dump content providers"); 17533 pw.println(" p[ackages]: dump installed packages"); 17534 pw.println(" s[hared-users]: dump shared user IDs"); 17535 pw.println(" m[essages]: print collected runtime messages"); 17536 pw.println(" v[erifiers]: print package verifier info"); 17537 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17538 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17539 pw.println(" version: print database version info"); 17540 pw.println(" write: write current settings now"); 17541 pw.println(" installs: details about install sessions"); 17542 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17543 pw.println(" <package.name>: info about given package"); 17544 return; 17545 } else if ("--checkin".equals(opt)) { 17546 checkin = true; 17547 } else if ("-f".equals(opt)) { 17548 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17549 } else { 17550 pw.println("Unknown argument: " + opt + "; use -h for help"); 17551 } 17552 } 17553 17554 // Is the caller requesting to dump a particular piece of data? 17555 if (opti < args.length) { 17556 String cmd = args[opti]; 17557 opti++; 17558 // Is this a package name? 17559 if ("android".equals(cmd) || cmd.contains(".")) { 17560 packageName = cmd; 17561 // When dumping a single package, we always dump all of its 17562 // filter information since the amount of data will be reasonable. 17563 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17564 } else if ("check-permission".equals(cmd)) { 17565 if (opti >= args.length) { 17566 pw.println("Error: check-permission missing permission argument"); 17567 return; 17568 } 17569 String perm = args[opti]; 17570 opti++; 17571 if (opti >= args.length) { 17572 pw.println("Error: check-permission missing package argument"); 17573 return; 17574 } 17575 String pkg = args[opti]; 17576 opti++; 17577 int user = UserHandle.getUserId(Binder.getCallingUid()); 17578 if (opti < args.length) { 17579 try { 17580 user = Integer.parseInt(args[opti]); 17581 } catch (NumberFormatException e) { 17582 pw.println("Error: check-permission user argument is not a number: " 17583 + args[opti]); 17584 return; 17585 } 17586 } 17587 pw.println(checkPermission(perm, pkg, user)); 17588 return; 17589 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17590 dumpState.setDump(DumpState.DUMP_LIBS); 17591 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17592 dumpState.setDump(DumpState.DUMP_FEATURES); 17593 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17594 if (opti >= args.length) { 17595 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17596 | DumpState.DUMP_SERVICE_RESOLVERS 17597 | DumpState.DUMP_RECEIVER_RESOLVERS 17598 | DumpState.DUMP_CONTENT_RESOLVERS); 17599 } else { 17600 while (opti < args.length) { 17601 String name = args[opti]; 17602 if ("a".equals(name) || "activity".equals(name)) { 17603 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17604 } else if ("s".equals(name) || "service".equals(name)) { 17605 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17606 } else if ("r".equals(name) || "receiver".equals(name)) { 17607 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17608 } else if ("c".equals(name) || "content".equals(name)) { 17609 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17610 } else { 17611 pw.println("Error: unknown resolver table type: " + name); 17612 return; 17613 } 17614 opti++; 17615 } 17616 } 17617 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17618 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17619 } else if ("permission".equals(cmd)) { 17620 if (opti >= args.length) { 17621 pw.println("Error: permission requires permission name"); 17622 return; 17623 } 17624 permissionNames = new ArraySet<>(); 17625 while (opti < args.length) { 17626 permissionNames.add(args[opti]); 17627 opti++; 17628 } 17629 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17630 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17631 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17632 dumpState.setDump(DumpState.DUMP_PREFERRED); 17633 } else if ("preferred-xml".equals(cmd)) { 17634 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17635 if (opti < args.length && "--full".equals(args[opti])) { 17636 fullPreferred = true; 17637 opti++; 17638 } 17639 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17640 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17641 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17642 dumpState.setDump(DumpState.DUMP_PACKAGES); 17643 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17644 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17645 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17646 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17647 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17648 dumpState.setDump(DumpState.DUMP_MESSAGES); 17649 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17650 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17651 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17652 || "intent-filter-verifiers".equals(cmd)) { 17653 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17654 } else if ("version".equals(cmd)) { 17655 dumpState.setDump(DumpState.DUMP_VERSION); 17656 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17657 dumpState.setDump(DumpState.DUMP_KEYSETS); 17658 } else if ("installs".equals(cmd)) { 17659 dumpState.setDump(DumpState.DUMP_INSTALLS); 17660 } else if ("frozen".equals(cmd)) { 17661 dumpState.setDump(DumpState.DUMP_FROZEN); 17662 } else if ("write".equals(cmd)) { 17663 synchronized (mPackages) { 17664 mSettings.writeLPr(); 17665 pw.println("Settings written."); 17666 return; 17667 } 17668 } 17669 } 17670 17671 if (checkin) { 17672 pw.println("vers,1"); 17673 } 17674 17675 // reader 17676 synchronized (mPackages) { 17677 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17678 if (!checkin) { 17679 if (dumpState.onTitlePrinted()) 17680 pw.println(); 17681 pw.println("Database versions:"); 17682 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17683 } 17684 } 17685 17686 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17687 if (!checkin) { 17688 if (dumpState.onTitlePrinted()) 17689 pw.println(); 17690 pw.println("Verifiers:"); 17691 pw.print(" Required: "); 17692 pw.print(mRequiredVerifierPackage); 17693 pw.print(" (uid="); 17694 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17695 UserHandle.USER_SYSTEM)); 17696 pw.println(")"); 17697 } else if (mRequiredVerifierPackage != null) { 17698 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17699 pw.print(","); 17700 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17701 UserHandle.USER_SYSTEM)); 17702 } 17703 } 17704 17705 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17706 packageName == null) { 17707 if (mIntentFilterVerifierComponent != null) { 17708 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17709 if (!checkin) { 17710 if (dumpState.onTitlePrinted()) 17711 pw.println(); 17712 pw.println("Intent Filter Verifier:"); 17713 pw.print(" Using: "); 17714 pw.print(verifierPackageName); 17715 pw.print(" (uid="); 17716 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17717 UserHandle.USER_SYSTEM)); 17718 pw.println(")"); 17719 } else if (verifierPackageName != null) { 17720 pw.print("ifv,"); pw.print(verifierPackageName); 17721 pw.print(","); 17722 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17723 UserHandle.USER_SYSTEM)); 17724 } 17725 } else { 17726 pw.println(); 17727 pw.println("No Intent Filter Verifier available!"); 17728 } 17729 } 17730 17731 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17732 boolean printedHeader = false; 17733 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17734 while (it.hasNext()) { 17735 String name = it.next(); 17736 SharedLibraryEntry ent = mSharedLibraries.get(name); 17737 if (!checkin) { 17738 if (!printedHeader) { 17739 if (dumpState.onTitlePrinted()) 17740 pw.println(); 17741 pw.println("Libraries:"); 17742 printedHeader = true; 17743 } 17744 pw.print(" "); 17745 } else { 17746 pw.print("lib,"); 17747 } 17748 pw.print(name); 17749 if (!checkin) { 17750 pw.print(" -> "); 17751 } 17752 if (ent.path != null) { 17753 if (!checkin) { 17754 pw.print("(jar) "); 17755 pw.print(ent.path); 17756 } else { 17757 pw.print(",jar,"); 17758 pw.print(ent.path); 17759 } 17760 } else { 17761 if (!checkin) { 17762 pw.print("(apk) "); 17763 pw.print(ent.apk); 17764 } else { 17765 pw.print(",apk,"); 17766 pw.print(ent.apk); 17767 } 17768 } 17769 pw.println(); 17770 } 17771 } 17772 17773 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17774 if (dumpState.onTitlePrinted()) 17775 pw.println(); 17776 if (!checkin) { 17777 pw.println("Features:"); 17778 } 17779 17780 for (FeatureInfo feat : mAvailableFeatures.values()) { 17781 if (checkin) { 17782 pw.print("feat,"); 17783 pw.print(feat.name); 17784 pw.print(","); 17785 pw.println(feat.version); 17786 } else { 17787 pw.print(" "); 17788 pw.print(feat.name); 17789 if (feat.version > 0) { 17790 pw.print(" version="); 17791 pw.print(feat.version); 17792 } 17793 pw.println(); 17794 } 17795 } 17796 } 17797 17798 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17799 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17800 : "Activity Resolver Table:", " ", packageName, 17801 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17802 dumpState.setTitlePrinted(true); 17803 } 17804 } 17805 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17806 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17807 : "Receiver Resolver Table:", " ", packageName, 17808 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17809 dumpState.setTitlePrinted(true); 17810 } 17811 } 17812 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17813 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17814 : "Service Resolver Table:", " ", packageName, 17815 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17816 dumpState.setTitlePrinted(true); 17817 } 17818 } 17819 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17820 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17821 : "Provider Resolver Table:", " ", packageName, 17822 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17823 dumpState.setTitlePrinted(true); 17824 } 17825 } 17826 17827 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 17828 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17829 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17830 int user = mSettings.mPreferredActivities.keyAt(i); 17831 if (pir.dump(pw, 17832 dumpState.getTitlePrinted() 17833 ? "\nPreferred Activities User " + user + ":" 17834 : "Preferred Activities User " + user + ":", " ", 17835 packageName, true, false)) { 17836 dumpState.setTitlePrinted(true); 17837 } 17838 } 17839 } 17840 17841 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 17842 pw.flush(); 17843 FileOutputStream fout = new FileOutputStream(fd); 17844 BufferedOutputStream str = new BufferedOutputStream(fout); 17845 XmlSerializer serializer = new FastXmlSerializer(); 17846 try { 17847 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 17848 serializer.startDocument(null, true); 17849 serializer.setFeature( 17850 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 17851 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 17852 serializer.endDocument(); 17853 serializer.flush(); 17854 } catch (IllegalArgumentException e) { 17855 pw.println("Failed writing: " + e); 17856 } catch (IllegalStateException e) { 17857 pw.println("Failed writing: " + e); 17858 } catch (IOException e) { 17859 pw.println("Failed writing: " + e); 17860 } 17861 } 17862 17863 if (!checkin 17864 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 17865 && packageName == null) { 17866 pw.println(); 17867 int count = mSettings.mPackages.size(); 17868 if (count == 0) { 17869 pw.println("No applications!"); 17870 pw.println(); 17871 } else { 17872 final String prefix = " "; 17873 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 17874 if (allPackageSettings.size() == 0) { 17875 pw.println("No domain preferred apps!"); 17876 pw.println(); 17877 } else { 17878 pw.println("App verification status:"); 17879 pw.println(); 17880 count = 0; 17881 for (PackageSetting ps : allPackageSettings) { 17882 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 17883 if (ivi == null || ivi.getPackageName() == null) continue; 17884 pw.println(prefix + "Package: " + ivi.getPackageName()); 17885 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 17886 pw.println(prefix + "Status: " + ivi.getStatusString()); 17887 pw.println(); 17888 count++; 17889 } 17890 if (count == 0) { 17891 pw.println(prefix + "No app verification established."); 17892 pw.println(); 17893 } 17894 for (int userId : sUserManager.getUserIds()) { 17895 pw.println("App linkages for user " + userId + ":"); 17896 pw.println(); 17897 count = 0; 17898 for (PackageSetting ps : allPackageSettings) { 17899 final long status = ps.getDomainVerificationStatusForUser(userId); 17900 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 17901 continue; 17902 } 17903 pw.println(prefix + "Package: " + ps.name); 17904 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 17905 String statusStr = IntentFilterVerificationInfo. 17906 getStatusStringFromValue(status); 17907 pw.println(prefix + "Status: " + statusStr); 17908 pw.println(); 17909 count++; 17910 } 17911 if (count == 0) { 17912 pw.println(prefix + "No configured app linkages."); 17913 pw.println(); 17914 } 17915 } 17916 } 17917 } 17918 } 17919 17920 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 17921 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 17922 if (packageName == null && permissionNames == null) { 17923 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 17924 if (iperm == 0) { 17925 if (dumpState.onTitlePrinted()) 17926 pw.println(); 17927 pw.println("AppOp Permissions:"); 17928 } 17929 pw.print(" AppOp Permission "); 17930 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 17931 pw.println(":"); 17932 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 17933 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 17934 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 17935 } 17936 } 17937 } 17938 } 17939 17940 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 17941 boolean printedSomething = false; 17942 for (PackageParser.Provider p : mProviders.mProviders.values()) { 17943 if (packageName != null && !packageName.equals(p.info.packageName)) { 17944 continue; 17945 } 17946 if (!printedSomething) { 17947 if (dumpState.onTitlePrinted()) 17948 pw.println(); 17949 pw.println("Registered ContentProviders:"); 17950 printedSomething = true; 17951 } 17952 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 17953 pw.print(" "); pw.println(p.toString()); 17954 } 17955 printedSomething = false; 17956 for (Map.Entry<String, PackageParser.Provider> entry : 17957 mProvidersByAuthority.entrySet()) { 17958 PackageParser.Provider p = entry.getValue(); 17959 if (packageName != null && !packageName.equals(p.info.packageName)) { 17960 continue; 17961 } 17962 if (!printedSomething) { 17963 if (dumpState.onTitlePrinted()) 17964 pw.println(); 17965 pw.println("ContentProvider Authorities:"); 17966 printedSomething = true; 17967 } 17968 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 17969 pw.print(" "); pw.println(p.toString()); 17970 if (p.info != null && p.info.applicationInfo != null) { 17971 final String appInfo = p.info.applicationInfo.toString(); 17972 pw.print(" applicationInfo="); pw.println(appInfo); 17973 } 17974 } 17975 } 17976 17977 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 17978 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 17979 } 17980 17981 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 17982 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 17983 } 17984 17985 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 17986 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 17987 } 17988 17989 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 17990 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 17991 } 17992 17993 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 17994 // XXX should handle packageName != null by dumping only install data that 17995 // the given package is involved with. 17996 if (dumpState.onTitlePrinted()) pw.println(); 17997 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 17998 } 17999 18000 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18001 // XXX should handle packageName != null by dumping only install data that 18002 // the given package is involved with. 18003 if (dumpState.onTitlePrinted()) pw.println(); 18004 18005 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18006 ipw.println(); 18007 ipw.println("Frozen packages:"); 18008 ipw.increaseIndent(); 18009 if (mFrozenPackages.size() == 0) { 18010 ipw.println("(none)"); 18011 } else { 18012 for (int i = 0; i < mFrozenPackages.size(); i++) { 18013 ipw.println(mFrozenPackages.valueAt(i)); 18014 } 18015 } 18016 ipw.decreaseIndent(); 18017 } 18018 18019 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18020 if (dumpState.onTitlePrinted()) pw.println(); 18021 mSettings.dumpReadMessagesLPr(pw, dumpState); 18022 18023 pw.println(); 18024 pw.println("Package warning messages:"); 18025 BufferedReader in = null; 18026 String line = null; 18027 try { 18028 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18029 while ((line = in.readLine()) != null) { 18030 if (line.contains("ignored: updated version")) continue; 18031 pw.println(line); 18032 } 18033 } catch (IOException ignored) { 18034 } finally { 18035 IoUtils.closeQuietly(in); 18036 } 18037 } 18038 18039 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18040 BufferedReader in = null; 18041 String line = null; 18042 try { 18043 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18044 while ((line = in.readLine()) != null) { 18045 if (line.contains("ignored: updated version")) continue; 18046 pw.print("msg,"); 18047 pw.println(line); 18048 } 18049 } catch (IOException ignored) { 18050 } finally { 18051 IoUtils.closeQuietly(in); 18052 } 18053 } 18054 } 18055 } 18056 18057 private String dumpDomainString(String packageName) { 18058 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18059 .getList(); 18060 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18061 18062 ArraySet<String> result = new ArraySet<>(); 18063 if (iviList.size() > 0) { 18064 for (IntentFilterVerificationInfo ivi : iviList) { 18065 for (String host : ivi.getDomains()) { 18066 result.add(host); 18067 } 18068 } 18069 } 18070 if (filters != null && filters.size() > 0) { 18071 for (IntentFilter filter : filters) { 18072 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18073 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18074 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18075 result.addAll(filter.getHostsList()); 18076 } 18077 } 18078 } 18079 18080 StringBuilder sb = new StringBuilder(result.size() * 16); 18081 for (String domain : result) { 18082 if (sb.length() > 0) sb.append(" "); 18083 sb.append(domain); 18084 } 18085 return sb.toString(); 18086 } 18087 18088 // ------- apps on sdcard specific code ------- 18089 static final boolean DEBUG_SD_INSTALL = false; 18090 18091 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18092 18093 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18094 18095 private boolean mMediaMounted = false; 18096 18097 static String getEncryptKey() { 18098 try { 18099 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18100 SD_ENCRYPTION_KEYSTORE_NAME); 18101 if (sdEncKey == null) { 18102 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18103 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18104 if (sdEncKey == null) { 18105 Slog.e(TAG, "Failed to create encryption keys"); 18106 return null; 18107 } 18108 } 18109 return sdEncKey; 18110 } catch (NoSuchAlgorithmException nsae) { 18111 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18112 return null; 18113 } catch (IOException ioe) { 18114 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18115 return null; 18116 } 18117 } 18118 18119 /* 18120 * Update media status on PackageManager. 18121 */ 18122 @Override 18123 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18124 int callingUid = Binder.getCallingUid(); 18125 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18126 throw new SecurityException("Media status can only be updated by the system"); 18127 } 18128 // reader; this apparently protects mMediaMounted, but should probably 18129 // be a different lock in that case. 18130 synchronized (mPackages) { 18131 Log.i(TAG, "Updating external media status from " 18132 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18133 + (mediaStatus ? "mounted" : "unmounted")); 18134 if (DEBUG_SD_INSTALL) 18135 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18136 + ", mMediaMounted=" + mMediaMounted); 18137 if (mediaStatus == mMediaMounted) { 18138 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18139 : 0, -1); 18140 mHandler.sendMessage(msg); 18141 return; 18142 } 18143 mMediaMounted = mediaStatus; 18144 } 18145 // Queue up an async operation since the package installation may take a 18146 // little while. 18147 mHandler.post(new Runnable() { 18148 public void run() { 18149 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18150 } 18151 }); 18152 } 18153 18154 /** 18155 * Called by MountService when the initial ASECs to scan are available. 18156 * Should block until all the ASEC containers are finished being scanned. 18157 */ 18158 public void scanAvailableAsecs() { 18159 updateExternalMediaStatusInner(true, false, false); 18160 } 18161 18162 /* 18163 * Collect information of applications on external media, map them against 18164 * existing containers and update information based on current mount status. 18165 * Please note that we always have to report status if reportStatus has been 18166 * set to true especially when unloading packages. 18167 */ 18168 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18169 boolean externalStorage) { 18170 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18171 int[] uidArr = EmptyArray.INT; 18172 18173 final String[] list = PackageHelper.getSecureContainerList(); 18174 if (ArrayUtils.isEmpty(list)) { 18175 Log.i(TAG, "No secure containers found"); 18176 } else { 18177 // Process list of secure containers and categorize them 18178 // as active or stale based on their package internal state. 18179 18180 // reader 18181 synchronized (mPackages) { 18182 for (String cid : list) { 18183 // Leave stages untouched for now; installer service owns them 18184 if (PackageInstallerService.isStageName(cid)) continue; 18185 18186 if (DEBUG_SD_INSTALL) 18187 Log.i(TAG, "Processing container " + cid); 18188 String pkgName = getAsecPackageName(cid); 18189 if (pkgName == null) { 18190 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18191 continue; 18192 } 18193 if (DEBUG_SD_INSTALL) 18194 Log.i(TAG, "Looking for pkg : " + pkgName); 18195 18196 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18197 if (ps == null) { 18198 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18199 continue; 18200 } 18201 18202 /* 18203 * Skip packages that are not external if we're unmounting 18204 * external storage. 18205 */ 18206 if (externalStorage && !isMounted && !isExternal(ps)) { 18207 continue; 18208 } 18209 18210 final AsecInstallArgs args = new AsecInstallArgs(cid, 18211 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18212 // The package status is changed only if the code path 18213 // matches between settings and the container id. 18214 if (ps.codePathString != null 18215 && ps.codePathString.startsWith(args.getCodePath())) { 18216 if (DEBUG_SD_INSTALL) { 18217 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18218 + " at code path: " + ps.codePathString); 18219 } 18220 18221 // We do have a valid package installed on sdcard 18222 processCids.put(args, ps.codePathString); 18223 final int uid = ps.appId; 18224 if (uid != -1) { 18225 uidArr = ArrayUtils.appendInt(uidArr, uid); 18226 } 18227 } else { 18228 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18229 + ps.codePathString); 18230 } 18231 } 18232 } 18233 18234 Arrays.sort(uidArr); 18235 } 18236 18237 // Process packages with valid entries. 18238 if (isMounted) { 18239 if (DEBUG_SD_INSTALL) 18240 Log.i(TAG, "Loading packages"); 18241 loadMediaPackages(processCids, uidArr, externalStorage); 18242 startCleaningPackages(); 18243 mInstallerService.onSecureContainersAvailable(); 18244 } else { 18245 if (DEBUG_SD_INSTALL) 18246 Log.i(TAG, "Unloading packages"); 18247 unloadMediaPackages(processCids, uidArr, reportStatus); 18248 } 18249 } 18250 18251 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18252 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18253 final int size = infos.size(); 18254 final String[] packageNames = new String[size]; 18255 final int[] packageUids = new int[size]; 18256 for (int i = 0; i < size; i++) { 18257 final ApplicationInfo info = infos.get(i); 18258 packageNames[i] = info.packageName; 18259 packageUids[i] = info.uid; 18260 } 18261 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18262 finishedReceiver); 18263 } 18264 18265 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18266 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18267 sendResourcesChangedBroadcast(mediaStatus, replacing, 18268 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18269 } 18270 18271 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18272 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18273 int size = pkgList.length; 18274 if (size > 0) { 18275 // Send broadcasts here 18276 Bundle extras = new Bundle(); 18277 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18278 if (uidArr != null) { 18279 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18280 } 18281 if (replacing) { 18282 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18283 } 18284 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18285 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18286 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18287 } 18288 } 18289 18290 /* 18291 * Look at potentially valid container ids from processCids If package 18292 * information doesn't match the one on record or package scanning fails, 18293 * the cid is added to list of removeCids. We currently don't delete stale 18294 * containers. 18295 */ 18296 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18297 boolean externalStorage) { 18298 ArrayList<String> pkgList = new ArrayList<String>(); 18299 Set<AsecInstallArgs> keys = processCids.keySet(); 18300 18301 for (AsecInstallArgs args : keys) { 18302 String codePath = processCids.get(args); 18303 if (DEBUG_SD_INSTALL) 18304 Log.i(TAG, "Loading container : " + args.cid); 18305 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18306 try { 18307 // Make sure there are no container errors first. 18308 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18309 Slog.e(TAG, "Failed to mount cid : " + args.cid 18310 + " when installing from sdcard"); 18311 continue; 18312 } 18313 // Check code path here. 18314 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18315 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18316 + " does not match one in settings " + codePath); 18317 continue; 18318 } 18319 // Parse package 18320 int parseFlags = mDefParseFlags; 18321 if (args.isExternalAsec()) { 18322 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18323 } 18324 if (args.isFwdLocked()) { 18325 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18326 } 18327 18328 synchronized (mInstallLock) { 18329 PackageParser.Package pkg = null; 18330 try { 18331 // Sadly we don't know the package name yet to freeze it 18332 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18333 SCAN_IGNORE_FROZEN, 0, null); 18334 } catch (PackageManagerException e) { 18335 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18336 } 18337 // Scan the package 18338 if (pkg != null) { 18339 /* 18340 * TODO why is the lock being held? doPostInstall is 18341 * called in other places without the lock. This needs 18342 * to be straightened out. 18343 */ 18344 // writer 18345 synchronized (mPackages) { 18346 retCode = PackageManager.INSTALL_SUCCEEDED; 18347 pkgList.add(pkg.packageName); 18348 // Post process args 18349 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18350 pkg.applicationInfo.uid); 18351 } 18352 } else { 18353 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18354 } 18355 } 18356 18357 } finally { 18358 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18359 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18360 } 18361 } 18362 } 18363 // writer 18364 synchronized (mPackages) { 18365 // If the platform SDK has changed since the last time we booted, 18366 // we need to re-grant app permission to catch any new ones that 18367 // appear. This is really a hack, and means that apps can in some 18368 // cases get permissions that the user didn't initially explicitly 18369 // allow... it would be nice to have some better way to handle 18370 // this situation. 18371 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18372 : mSettings.getInternalVersion(); 18373 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18374 : StorageManager.UUID_PRIVATE_INTERNAL; 18375 18376 int updateFlags = UPDATE_PERMISSIONS_ALL; 18377 if (ver.sdkVersion != mSdkVersion) { 18378 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18379 + mSdkVersion + "; regranting permissions for external"); 18380 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18381 } 18382 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18383 18384 // Yay, everything is now upgraded 18385 ver.forceCurrent(); 18386 18387 // can downgrade to reader 18388 // Persist settings 18389 mSettings.writeLPr(); 18390 } 18391 // Send a broadcast to let everyone know we are done processing 18392 if (pkgList.size() > 0) { 18393 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18394 } 18395 } 18396 18397 /* 18398 * Utility method to unload a list of specified containers 18399 */ 18400 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18401 // Just unmount all valid containers. 18402 for (AsecInstallArgs arg : cidArgs) { 18403 synchronized (mInstallLock) { 18404 arg.doPostDeleteLI(false); 18405 } 18406 } 18407 } 18408 18409 /* 18410 * Unload packages mounted on external media. This involves deleting package 18411 * data from internal structures, sending broadcasts about disabled packages, 18412 * gc'ing to free up references, unmounting all secure containers 18413 * corresponding to packages on external media, and posting a 18414 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18415 * that we always have to post this message if status has been requested no 18416 * matter what. 18417 */ 18418 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18419 final boolean reportStatus) { 18420 if (DEBUG_SD_INSTALL) 18421 Log.i(TAG, "unloading media packages"); 18422 ArrayList<String> pkgList = new ArrayList<String>(); 18423 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18424 final Set<AsecInstallArgs> keys = processCids.keySet(); 18425 for (AsecInstallArgs args : keys) { 18426 String pkgName = args.getPackageName(); 18427 if (DEBUG_SD_INSTALL) 18428 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18429 // Delete package internally 18430 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18431 synchronized (mInstallLock) { 18432 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18433 final boolean res; 18434 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18435 "unloadMediaPackages")) { 18436 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18437 null); 18438 } 18439 if (res) { 18440 pkgList.add(pkgName); 18441 } else { 18442 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18443 failedList.add(args); 18444 } 18445 } 18446 } 18447 18448 // reader 18449 synchronized (mPackages) { 18450 // We didn't update the settings after removing each package; 18451 // write them now for all packages. 18452 mSettings.writeLPr(); 18453 } 18454 18455 // We have to absolutely send UPDATED_MEDIA_STATUS only 18456 // after confirming that all the receivers processed the ordered 18457 // broadcast when packages get disabled, force a gc to clean things up. 18458 // and unload all the containers. 18459 if (pkgList.size() > 0) { 18460 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18461 new IIntentReceiver.Stub() { 18462 public void performReceive(Intent intent, int resultCode, String data, 18463 Bundle extras, boolean ordered, boolean sticky, 18464 int sendingUser) throws RemoteException { 18465 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18466 reportStatus ? 1 : 0, 1, keys); 18467 mHandler.sendMessage(msg); 18468 } 18469 }); 18470 } else { 18471 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18472 keys); 18473 mHandler.sendMessage(msg); 18474 } 18475 } 18476 18477 private void loadPrivatePackages(final VolumeInfo vol) { 18478 mHandler.post(new Runnable() { 18479 @Override 18480 public void run() { 18481 loadPrivatePackagesInner(vol); 18482 } 18483 }); 18484 } 18485 18486 private void loadPrivatePackagesInner(VolumeInfo vol) { 18487 final String volumeUuid = vol.fsUuid; 18488 if (TextUtils.isEmpty(volumeUuid)) { 18489 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18490 return; 18491 } 18492 18493 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18494 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18495 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18496 18497 final VersionInfo ver; 18498 final List<PackageSetting> packages; 18499 synchronized (mPackages) { 18500 ver = mSettings.findOrCreateVersion(volumeUuid); 18501 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18502 } 18503 18504 for (PackageSetting ps : packages) { 18505 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18506 synchronized (mInstallLock) { 18507 final PackageParser.Package pkg; 18508 try { 18509 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18510 loaded.add(pkg.applicationInfo); 18511 18512 } catch (PackageManagerException e) { 18513 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18514 } 18515 18516 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18517 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18518 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18519 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18520 } 18521 } 18522 } 18523 18524 // Reconcile app data for all started/unlocked users 18525 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18526 final UserManager um = mContext.getSystemService(UserManager.class); 18527 for (UserInfo user : um.getUsers()) { 18528 final int flags; 18529 if (um.isUserUnlocked(user.id)) { 18530 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18531 } else if (um.isUserRunning(user.id)) { 18532 flags = StorageManager.FLAG_STORAGE_DE; 18533 } else { 18534 continue; 18535 } 18536 18537 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18538 synchronized (mInstallLock) { 18539 reconcileAppsDataLI(volumeUuid, user.id, flags); 18540 } 18541 } 18542 18543 synchronized (mPackages) { 18544 int updateFlags = UPDATE_PERMISSIONS_ALL; 18545 if (ver.sdkVersion != mSdkVersion) { 18546 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18547 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18548 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18549 } 18550 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18551 18552 // Yay, everything is now upgraded 18553 ver.forceCurrent(); 18554 18555 mSettings.writeLPr(); 18556 } 18557 18558 for (PackageFreezer freezer : freezers) { 18559 freezer.close(); 18560 } 18561 18562 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18563 sendResourcesChangedBroadcast(true, false, loaded, null); 18564 } 18565 18566 private void unloadPrivatePackages(final VolumeInfo vol) { 18567 mHandler.post(new Runnable() { 18568 @Override 18569 public void run() { 18570 unloadPrivatePackagesInner(vol); 18571 } 18572 }); 18573 } 18574 18575 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18576 final String volumeUuid = vol.fsUuid; 18577 if (TextUtils.isEmpty(volumeUuid)) { 18578 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18579 return; 18580 } 18581 18582 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18583 synchronized (mInstallLock) { 18584 synchronized (mPackages) { 18585 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18586 for (PackageSetting ps : packages) { 18587 if (ps.pkg == null) continue; 18588 18589 final ApplicationInfo info = ps.pkg.applicationInfo; 18590 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18591 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18592 18593 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18594 "unloadPrivatePackagesInner")) { 18595 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18596 false, null)) { 18597 unloaded.add(info); 18598 } else { 18599 Slog.w(TAG, "Failed to unload " + ps.codePath); 18600 } 18601 } 18602 } 18603 18604 mSettings.writeLPr(); 18605 } 18606 } 18607 18608 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18609 sendResourcesChangedBroadcast(false, false, unloaded, null); 18610 } 18611 18612 /** 18613 * Examine all users present on given mounted volume, and destroy data 18614 * belonging to users that are no longer valid, or whose user ID has been 18615 * recycled. 18616 */ 18617 private void reconcileUsers(String volumeUuid) { 18618 // TODO: also reconcile DE directories 18619 final File[] files = FileUtils 18620 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid)); 18621 for (File file : files) { 18622 if (!file.isDirectory()) continue; 18623 18624 final int userId; 18625 final UserInfo info; 18626 try { 18627 userId = Integer.parseInt(file.getName()); 18628 info = sUserManager.getUserInfo(userId); 18629 } catch (NumberFormatException e) { 18630 Slog.w(TAG, "Invalid user directory " + file); 18631 continue; 18632 } 18633 18634 boolean destroyUser = false; 18635 if (info == null) { 18636 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18637 + " because no matching user was found"); 18638 destroyUser = true; 18639 } else { 18640 try { 18641 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18642 } catch (IOException e) { 18643 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18644 + " because we failed to enforce serial number: " + e); 18645 destroyUser = true; 18646 } 18647 } 18648 18649 if (destroyUser) { 18650 synchronized (mInstallLock) { 18651 try { 18652 mInstaller.removeUserDataDirs(volumeUuid, userId); 18653 } catch (InstallerException e) { 18654 Slog.w(TAG, "Failed to clean up user dirs", e); 18655 } 18656 } 18657 } 18658 } 18659 } 18660 18661 private void assertPackageKnown(String volumeUuid, String packageName) 18662 throws PackageManagerException { 18663 synchronized (mPackages) { 18664 final PackageSetting ps = mSettings.mPackages.get(packageName); 18665 if (ps == null) { 18666 throw new PackageManagerException("Package " + packageName + " is unknown"); 18667 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18668 throw new PackageManagerException( 18669 "Package " + packageName + " found on unknown volume " + volumeUuid 18670 + "; expected volume " + ps.volumeUuid); 18671 } 18672 } 18673 } 18674 18675 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18676 throws PackageManagerException { 18677 synchronized (mPackages) { 18678 final PackageSetting ps = mSettings.mPackages.get(packageName); 18679 if (ps == null) { 18680 throw new PackageManagerException("Package " + packageName + " is unknown"); 18681 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18682 throw new PackageManagerException( 18683 "Package " + packageName + " found on unknown volume " + volumeUuid 18684 + "; expected volume " + ps.volumeUuid); 18685 } else if (!ps.getInstalled(userId)) { 18686 throw new PackageManagerException( 18687 "Package " + packageName + " not installed for user " + userId); 18688 } 18689 } 18690 } 18691 18692 /** 18693 * Examine all apps present on given mounted volume, and destroy apps that 18694 * aren't expected, either due to uninstallation or reinstallation on 18695 * another volume. 18696 */ 18697 private void reconcileApps(String volumeUuid) { 18698 final File[] files = FileUtils 18699 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18700 for (File file : files) { 18701 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18702 && !PackageInstallerService.isStageName(file.getName()); 18703 if (!isPackage) { 18704 // Ignore entries which are not packages 18705 continue; 18706 } 18707 18708 try { 18709 final PackageLite pkg = PackageParser.parsePackageLite(file, 18710 PackageParser.PARSE_MUST_BE_APK); 18711 assertPackageKnown(volumeUuid, pkg.packageName); 18712 18713 } catch (PackageParserException | PackageManagerException e) { 18714 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18715 synchronized (mInstallLock) { 18716 removeCodePathLI(file); 18717 } 18718 } 18719 } 18720 } 18721 18722 /** 18723 * Reconcile all app data for the given user. 18724 * <p> 18725 * Verifies that directories exist and that ownership and labeling is 18726 * correct for all installed apps on all mounted volumes. 18727 */ 18728 void reconcileAppsData(int userId, int flags) { 18729 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18730 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18731 final String volumeUuid = vol.getFsUuid(); 18732 synchronized (mInstallLock) { 18733 reconcileAppsDataLI(volumeUuid, userId, flags); 18734 } 18735 } 18736 } 18737 18738 /** 18739 * Reconcile all app data on given mounted volume. 18740 * <p> 18741 * Destroys app data that isn't expected, either due to uninstallation or 18742 * reinstallation on another volume. 18743 * <p> 18744 * Verifies that directories exist and that ownership and labeling is 18745 * correct for all installed apps. 18746 */ 18747 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 18748 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 18749 + Integer.toHexString(flags)); 18750 18751 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 18752 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 18753 18754 boolean restoreconNeeded = false; 18755 18756 // First look for stale data that doesn't belong, and check if things 18757 // have changed since we did our last restorecon 18758 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18759 if (!isUserKeyUnlocked(userId)) { 18760 throw new RuntimeException( 18761 "Yikes, someone asked us to reconcile CE storage while " + userId 18762 + " was still locked; this would have caused massive data loss!"); 18763 } 18764 18765 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 18766 18767 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 18768 for (File file : files) { 18769 final String packageName = file.getName(); 18770 try { 18771 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18772 } catch (PackageManagerException e) { 18773 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18774 try { 18775 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18776 StorageManager.FLAG_STORAGE_CE, 0); 18777 } catch (InstallerException e2) { 18778 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18779 } 18780 } 18781 } 18782 } 18783 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18784 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 18785 18786 final File[] files = FileUtils.listFilesOrEmpty(deDir); 18787 for (File file : files) { 18788 final String packageName = file.getName(); 18789 try { 18790 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 18791 } catch (PackageManagerException e) { 18792 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18793 try { 18794 mInstaller.destroyAppData(volumeUuid, packageName, userId, 18795 StorageManager.FLAG_STORAGE_DE, 0); 18796 } catch (InstallerException e2) { 18797 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 18798 } 18799 } 18800 } 18801 } 18802 18803 // Ensure that data directories are ready to roll for all packages 18804 // installed for this volume and user 18805 final List<PackageSetting> packages; 18806 synchronized (mPackages) { 18807 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18808 } 18809 int preparedCount = 0; 18810 for (PackageSetting ps : packages) { 18811 final String packageName = ps.name; 18812 if (ps.pkg == null) { 18813 Slog.w(TAG, "Odd, missing scanned package " + packageName); 18814 // TODO: might be due to legacy ASEC apps; we should circle back 18815 // and reconcile again once they're scanned 18816 continue; 18817 } 18818 18819 if (ps.getInstalled(userId)) { 18820 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18821 18822 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 18823 // We may have just shuffled around app data directories, so 18824 // prepare them one more time 18825 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 18826 } 18827 18828 preparedCount++; 18829 } 18830 } 18831 18832 if (restoreconNeeded) { 18833 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18834 SELinuxMMAC.setRestoreconDone(ceDir); 18835 } 18836 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18837 SELinuxMMAC.setRestoreconDone(deDir); 18838 } 18839 } 18840 18841 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 18842 + " packages; restoreconNeeded was " + restoreconNeeded); 18843 } 18844 18845 /** 18846 * Prepare app data for the given app just after it was installed or 18847 * upgraded. This method carefully only touches users that it's installed 18848 * for, and it forces a restorecon to handle any seinfo changes. 18849 * <p> 18850 * Verifies that directories exist and that ownership and labeling is 18851 * correct for all installed apps. If there is an ownership mismatch, it 18852 * will try recovering system apps by wiping data; third-party app data is 18853 * left intact. 18854 * <p> 18855 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 18856 */ 18857 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 18858 final PackageSetting ps; 18859 synchronized (mPackages) { 18860 ps = mSettings.mPackages.get(pkg.packageName); 18861 mSettings.writeKernelMappingLPr(ps); 18862 } 18863 18864 final UserManager um = mContext.getSystemService(UserManager.class); 18865 for (UserInfo user : um.getUsers()) { 18866 final int flags; 18867 if (um.isUserUnlocked(user.id)) { 18868 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18869 } else if (um.isUserRunning(user.id)) { 18870 flags = StorageManager.FLAG_STORAGE_DE; 18871 } else { 18872 continue; 18873 } 18874 18875 if (ps.getInstalled(user.id)) { 18876 // Whenever an app changes, force a restorecon of its data 18877 // TODO: when user data is locked, mark that we're still dirty 18878 prepareAppDataLIF(pkg, user.id, flags, true); 18879 } 18880 } 18881 } 18882 18883 /** 18884 * Prepare app data for the given app. 18885 * <p> 18886 * Verifies that directories exist and that ownership and labeling is 18887 * correct for all installed apps. If there is an ownership mismatch, this 18888 * will try recovering system apps by wiping data; third-party app data is 18889 * left intact. 18890 */ 18891 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 18892 boolean restoreconNeeded) { 18893 if (pkg == null) { 18894 Slog.wtf(TAG, "Package was null!", new Throwable()); 18895 return; 18896 } 18897 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 18898 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18899 for (int i = 0; i < childCount; i++) { 18900 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 18901 } 18902 } 18903 18904 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 18905 boolean restoreconNeeded) { 18906 if (DEBUG_APP_DATA) { 18907 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 18908 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 18909 } 18910 18911 final String volumeUuid = pkg.volumeUuid; 18912 final String packageName = pkg.packageName; 18913 final ApplicationInfo app = pkg.applicationInfo; 18914 final int appId = UserHandle.getAppId(app.uid); 18915 18916 Preconditions.checkNotNull(app.seinfo); 18917 18918 try { 18919 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18920 appId, app.seinfo, app.targetSdkVersion); 18921 } catch (InstallerException e) { 18922 if (app.isSystemApp()) { 18923 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 18924 + ", but trying to recover: " + e); 18925 destroyAppDataLeafLIF(pkg, userId, flags); 18926 try { 18927 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 18928 appId, app.seinfo, app.targetSdkVersion); 18929 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 18930 } catch (InstallerException e2) { 18931 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 18932 } 18933 } else { 18934 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 18935 } 18936 } 18937 18938 if (restoreconNeeded) { 18939 try { 18940 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 18941 app.seinfo); 18942 } catch (InstallerException e) { 18943 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 18944 } 18945 } 18946 18947 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18948 try { 18949 // CE storage is unlocked right now, so read out the inode and 18950 // remember for use later when it's locked 18951 // TODO: mark this structure as dirty so we persist it! 18952 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 18953 StorageManager.FLAG_STORAGE_CE); 18954 synchronized (mPackages) { 18955 final PackageSetting ps = mSettings.mPackages.get(packageName); 18956 if (ps != null) { 18957 ps.setCeDataInode(ceDataInode, userId); 18958 } 18959 } 18960 } catch (InstallerException e) { 18961 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 18962 } 18963 } 18964 18965 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18966 } 18967 18968 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 18969 if (pkg == null) { 18970 Slog.wtf(TAG, "Package was null!", new Throwable()); 18971 return; 18972 } 18973 prepareAppDataContentsLeafLIF(pkg, userId, flags); 18974 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 18975 for (int i = 0; i < childCount; i++) { 18976 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 18977 } 18978 } 18979 18980 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 18981 final String volumeUuid = pkg.volumeUuid; 18982 final String packageName = pkg.packageName; 18983 final ApplicationInfo app = pkg.applicationInfo; 18984 18985 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18986 // Create a native library symlink only if we have native libraries 18987 // and if the native libraries are 32 bit libraries. We do not provide 18988 // this symlink for 64 bit libraries. 18989 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 18990 final String nativeLibPath = app.nativeLibraryDir; 18991 try { 18992 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 18993 nativeLibPath, userId); 18994 } catch (InstallerException e) { 18995 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 18996 } 18997 } 18998 } 18999 } 19000 19001 /** 19002 * For system apps on non-FBE devices, this method migrates any existing 19003 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19004 * requested by the app. 19005 */ 19006 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19007 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19008 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19009 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19010 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19011 try { 19012 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19013 storageTarget); 19014 } catch (InstallerException e) { 19015 logCriticalInfo(Log.WARN, 19016 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19017 } 19018 return true; 19019 } else { 19020 return false; 19021 } 19022 } 19023 19024 public PackageFreezer freezePackage(String packageName, String killReason) { 19025 return new PackageFreezer(packageName, killReason); 19026 } 19027 19028 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19029 String killReason) { 19030 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19031 return new PackageFreezer(); 19032 } else { 19033 return freezePackage(packageName, killReason); 19034 } 19035 } 19036 19037 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19038 String killReason) { 19039 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19040 return new PackageFreezer(); 19041 } else { 19042 return freezePackage(packageName, killReason); 19043 } 19044 } 19045 19046 /** 19047 * Class that freezes and kills the given package upon creation, and 19048 * unfreezes it upon closing. This is typically used when doing surgery on 19049 * app code/data to prevent the app from running while you're working. 19050 */ 19051 private class PackageFreezer implements AutoCloseable { 19052 private final String mPackageName; 19053 private final PackageFreezer[] mChildren; 19054 19055 private final boolean mWeFroze; 19056 19057 private final AtomicBoolean mClosed = new AtomicBoolean(); 19058 private final CloseGuard mCloseGuard = CloseGuard.get(); 19059 19060 /** 19061 * Create and return a stub freezer that doesn't actually do anything, 19062 * typically used when someone requested 19063 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19064 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19065 */ 19066 public PackageFreezer() { 19067 mPackageName = null; 19068 mChildren = null; 19069 mWeFroze = false; 19070 mCloseGuard.open("close"); 19071 } 19072 19073 public PackageFreezer(String packageName, String killReason) { 19074 synchronized (mPackages) { 19075 mPackageName = packageName; 19076 mWeFroze = mFrozenPackages.add(mPackageName); 19077 19078 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19079 if (ps != null) { 19080 killApplication(ps.name, ps.appId, killReason); 19081 } 19082 19083 final PackageParser.Package p = mPackages.get(packageName); 19084 if (p != null && p.childPackages != null) { 19085 final int N = p.childPackages.size(); 19086 mChildren = new PackageFreezer[N]; 19087 for (int i = 0; i < N; i++) { 19088 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19089 killReason); 19090 } 19091 } else { 19092 mChildren = null; 19093 } 19094 } 19095 mCloseGuard.open("close"); 19096 } 19097 19098 @Override 19099 protected void finalize() throws Throwable { 19100 try { 19101 mCloseGuard.warnIfOpen(); 19102 close(); 19103 } finally { 19104 super.finalize(); 19105 } 19106 } 19107 19108 @Override 19109 public void close() { 19110 mCloseGuard.close(); 19111 if (mClosed.compareAndSet(false, true)) { 19112 synchronized (mPackages) { 19113 if (mWeFroze) { 19114 mFrozenPackages.remove(mPackageName); 19115 } 19116 19117 if (mChildren != null) { 19118 for (PackageFreezer freezer : mChildren) { 19119 freezer.close(); 19120 } 19121 } 19122 } 19123 } 19124 } 19125 } 19126 19127 /** 19128 * Verify that given package is currently frozen. 19129 */ 19130 private void checkPackageFrozen(String packageName) { 19131 synchronized (mPackages) { 19132 if (!mFrozenPackages.contains(packageName)) { 19133 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19134 } 19135 } 19136 } 19137 19138 @Override 19139 public int movePackage(final String packageName, final String volumeUuid) { 19140 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19141 19142 final int moveId = mNextMoveId.getAndIncrement(); 19143 mHandler.post(new Runnable() { 19144 @Override 19145 public void run() { 19146 try { 19147 movePackageInternal(packageName, volumeUuid, moveId); 19148 } catch (PackageManagerException e) { 19149 Slog.w(TAG, "Failed to move " + packageName, e); 19150 mMoveCallbacks.notifyStatusChanged(moveId, 19151 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19152 } 19153 } 19154 }); 19155 return moveId; 19156 } 19157 19158 private void movePackageInternal(final String packageName, final String volumeUuid, 19159 final int moveId) throws PackageManagerException { 19160 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19161 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19162 final PackageManager pm = mContext.getPackageManager(); 19163 19164 final boolean currentAsec; 19165 final String currentVolumeUuid; 19166 final File codeFile; 19167 final String installerPackageName; 19168 final String packageAbiOverride; 19169 final int appId; 19170 final String seinfo; 19171 final String label; 19172 final int targetSdkVersion; 19173 final PackageFreezer freezer; 19174 19175 // reader 19176 synchronized (mPackages) { 19177 final PackageParser.Package pkg = mPackages.get(packageName); 19178 final PackageSetting ps = mSettings.mPackages.get(packageName); 19179 if (pkg == null || ps == null) { 19180 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19181 } 19182 19183 if (pkg.applicationInfo.isSystemApp()) { 19184 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19185 "Cannot move system application"); 19186 } 19187 19188 if (pkg.applicationInfo.isExternalAsec()) { 19189 currentAsec = true; 19190 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19191 } else if (pkg.applicationInfo.isForwardLocked()) { 19192 currentAsec = true; 19193 currentVolumeUuid = "forward_locked"; 19194 } else { 19195 currentAsec = false; 19196 currentVolumeUuid = ps.volumeUuid; 19197 19198 final File probe = new File(pkg.codePath); 19199 final File probeOat = new File(probe, "oat"); 19200 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19201 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19202 "Move only supported for modern cluster style installs"); 19203 } 19204 } 19205 19206 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19207 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19208 "Package already moved to " + volumeUuid); 19209 } 19210 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19211 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19212 "Device admin cannot be moved"); 19213 } 19214 19215 if (mFrozenPackages.contains(packageName)) { 19216 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19217 "Failed to move already frozen package"); 19218 } 19219 19220 codeFile = new File(pkg.codePath); 19221 installerPackageName = ps.installerPackageName; 19222 packageAbiOverride = ps.cpuAbiOverrideString; 19223 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19224 seinfo = pkg.applicationInfo.seinfo; 19225 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19226 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19227 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19228 } 19229 19230 final Bundle extras = new Bundle(); 19231 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19232 extras.putString(Intent.EXTRA_TITLE, label); 19233 mMoveCallbacks.notifyCreated(moveId, extras); 19234 19235 int installFlags; 19236 final boolean moveCompleteApp; 19237 final File measurePath; 19238 19239 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19240 installFlags = INSTALL_INTERNAL; 19241 moveCompleteApp = !currentAsec; 19242 measurePath = Environment.getDataAppDirectory(volumeUuid); 19243 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19244 installFlags = INSTALL_EXTERNAL; 19245 moveCompleteApp = false; 19246 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19247 } else { 19248 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19249 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19250 || !volume.isMountedWritable()) { 19251 freezer.close(); 19252 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19253 "Move location not mounted private volume"); 19254 } 19255 19256 Preconditions.checkState(!currentAsec); 19257 19258 installFlags = INSTALL_INTERNAL; 19259 moveCompleteApp = true; 19260 measurePath = Environment.getDataAppDirectory(volumeUuid); 19261 } 19262 19263 final PackageStats stats = new PackageStats(null, -1); 19264 synchronized (mInstaller) { 19265 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19266 freezer.close(); 19267 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19268 "Failed to measure package size"); 19269 } 19270 } 19271 19272 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19273 + stats.dataSize); 19274 19275 final long startFreeBytes = measurePath.getFreeSpace(); 19276 final long sizeBytes; 19277 if (moveCompleteApp) { 19278 sizeBytes = stats.codeSize + stats.dataSize; 19279 } else { 19280 sizeBytes = stats.codeSize; 19281 } 19282 19283 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19284 freezer.close(); 19285 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19286 "Not enough free space to move"); 19287 } 19288 19289 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19290 19291 final CountDownLatch installedLatch = new CountDownLatch(1); 19292 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19293 @Override 19294 public void onUserActionRequired(Intent intent) throws RemoteException { 19295 throw new IllegalStateException(); 19296 } 19297 19298 @Override 19299 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19300 Bundle extras) throws RemoteException { 19301 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19302 + PackageManager.installStatusToString(returnCode, msg)); 19303 19304 installedLatch.countDown(); 19305 freezer.close(); 19306 19307 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19308 switch (status) { 19309 case PackageInstaller.STATUS_SUCCESS: 19310 mMoveCallbacks.notifyStatusChanged(moveId, 19311 PackageManager.MOVE_SUCCEEDED); 19312 break; 19313 case PackageInstaller.STATUS_FAILURE_STORAGE: 19314 mMoveCallbacks.notifyStatusChanged(moveId, 19315 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19316 break; 19317 default: 19318 mMoveCallbacks.notifyStatusChanged(moveId, 19319 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19320 break; 19321 } 19322 } 19323 }; 19324 19325 final MoveInfo move; 19326 if (moveCompleteApp) { 19327 // Kick off a thread to report progress estimates 19328 new Thread() { 19329 @Override 19330 public void run() { 19331 while (true) { 19332 try { 19333 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19334 break; 19335 } 19336 } catch (InterruptedException ignored) { 19337 } 19338 19339 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19340 final int progress = 10 + (int) MathUtils.constrain( 19341 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19342 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19343 } 19344 } 19345 }.start(); 19346 19347 final String dataAppName = codeFile.getName(); 19348 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19349 dataAppName, appId, seinfo, targetSdkVersion); 19350 } else { 19351 move = null; 19352 } 19353 19354 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19355 19356 final Message msg = mHandler.obtainMessage(INIT_COPY); 19357 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19358 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19359 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19360 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19361 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19362 msg.obj = params; 19363 19364 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19365 System.identityHashCode(msg.obj)); 19366 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19367 System.identityHashCode(msg.obj)); 19368 19369 mHandler.sendMessage(msg); 19370 } 19371 19372 @Override 19373 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19374 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19375 19376 final int realMoveId = mNextMoveId.getAndIncrement(); 19377 final Bundle extras = new Bundle(); 19378 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19379 mMoveCallbacks.notifyCreated(realMoveId, extras); 19380 19381 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19382 @Override 19383 public void onCreated(int moveId, Bundle extras) { 19384 // Ignored 19385 } 19386 19387 @Override 19388 public void onStatusChanged(int moveId, int status, long estMillis) { 19389 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19390 } 19391 }; 19392 19393 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19394 storage.setPrimaryStorageUuid(volumeUuid, callback); 19395 return realMoveId; 19396 } 19397 19398 @Override 19399 public int getMoveStatus(int moveId) { 19400 mContext.enforceCallingOrSelfPermission( 19401 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19402 return mMoveCallbacks.mLastStatus.get(moveId); 19403 } 19404 19405 @Override 19406 public void registerMoveCallback(IPackageMoveObserver callback) { 19407 mContext.enforceCallingOrSelfPermission( 19408 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19409 mMoveCallbacks.register(callback); 19410 } 19411 19412 @Override 19413 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19414 mContext.enforceCallingOrSelfPermission( 19415 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19416 mMoveCallbacks.unregister(callback); 19417 } 19418 19419 @Override 19420 public boolean setInstallLocation(int loc) { 19421 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19422 null); 19423 if (getInstallLocation() == loc) { 19424 return true; 19425 } 19426 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19427 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19428 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19429 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19430 return true; 19431 } 19432 return false; 19433 } 19434 19435 @Override 19436 public int getInstallLocation() { 19437 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19438 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19439 PackageHelper.APP_INSTALL_AUTO); 19440 } 19441 19442 /** Called by UserManagerService */ 19443 void cleanUpUser(UserManagerService userManager, int userHandle) { 19444 synchronized (mPackages) { 19445 mDirtyUsers.remove(userHandle); 19446 mUserNeedsBadging.delete(userHandle); 19447 mSettings.removeUserLPw(userHandle); 19448 mPendingBroadcasts.remove(userHandle); 19449 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19450 } 19451 synchronized (mInstallLock) { 19452 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19453 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 19454 final String volumeUuid = vol.getFsUuid(); 19455 if (DEBUG_INSTALL) Slog.d(TAG, "Removing user data on volume " + volumeUuid); 19456 try { 19457 mInstaller.removeUserDataDirs(volumeUuid, userHandle); 19458 } catch (InstallerException e) { 19459 Slog.w(TAG, "Failed to remove user data", e); 19460 } 19461 } 19462 synchronized (mPackages) { 19463 removeUnusedPackagesLILPw(userManager, userHandle); 19464 } 19465 } 19466 } 19467 19468 /** 19469 * We're removing userHandle and would like to remove any downloaded packages 19470 * that are no longer in use by any other user. 19471 * @param userHandle the user being removed 19472 */ 19473 private void removeUnusedPackagesLILPw(UserManagerService userManager, final int userHandle) { 19474 final boolean DEBUG_CLEAN_APKS = false; 19475 int [] users = userManager.getUserIds(); 19476 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19477 while (psit.hasNext()) { 19478 PackageSetting ps = psit.next(); 19479 if (ps.pkg == null) { 19480 continue; 19481 } 19482 final String packageName = ps.pkg.packageName; 19483 // Skip over if system app 19484 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19485 continue; 19486 } 19487 if (DEBUG_CLEAN_APKS) { 19488 Slog.i(TAG, "Checking package " + packageName); 19489 } 19490 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19491 if (keep) { 19492 if (DEBUG_CLEAN_APKS) { 19493 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19494 } 19495 } else { 19496 for (int i = 0; i < users.length; i++) { 19497 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19498 keep = true; 19499 if (DEBUG_CLEAN_APKS) { 19500 Slog.i(TAG, " Keeping package " + packageName + " for user " 19501 + users[i]); 19502 } 19503 break; 19504 } 19505 } 19506 } 19507 if (!keep) { 19508 if (DEBUG_CLEAN_APKS) { 19509 Slog.i(TAG, " Removing package " + packageName); 19510 } 19511 mHandler.post(new Runnable() { 19512 public void run() { 19513 deletePackageX(packageName, userHandle, 0); 19514 } //end run 19515 }); 19516 } 19517 } 19518 } 19519 19520 /** Called by UserManagerService */ 19521 void createNewUser(int userHandle) { 19522 synchronized (mInstallLock) { 19523 try { 19524 mInstaller.createUserConfig(userHandle); 19525 } catch (InstallerException e) { 19526 Slog.w(TAG, "Failed to create user config", e); 19527 } 19528 mSettings.createNewUserLI(this, mInstaller, userHandle); 19529 } 19530 synchronized (mPackages) { 19531 applyFactoryDefaultBrowserLPw(userHandle); 19532 primeDomainVerificationsLPw(userHandle); 19533 } 19534 } 19535 19536 void newUserCreated(final int userHandle) { 19537 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19538 // If permission review for legacy apps is required, we represent 19539 // dagerous permissions for such apps as always granted runtime 19540 // permissions to keep per user flag state whether review is needed. 19541 // Hence, if a new user is added we have to propagate dangerous 19542 // permission grants for these legacy apps. 19543 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19544 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19545 | UPDATE_PERMISSIONS_REPLACE_ALL); 19546 } 19547 } 19548 19549 @Override 19550 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19551 mContext.enforceCallingOrSelfPermission( 19552 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19553 "Only package verification agents can read the verifier device identity"); 19554 19555 synchronized (mPackages) { 19556 return mSettings.getVerifierDeviceIdentityLPw(); 19557 } 19558 } 19559 19560 @Override 19561 public void setPermissionEnforced(String permission, boolean enforced) { 19562 // TODO: Now that we no longer change GID for storage, this should to away. 19563 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19564 "setPermissionEnforced"); 19565 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19566 synchronized (mPackages) { 19567 if (mSettings.mReadExternalStorageEnforced == null 19568 || mSettings.mReadExternalStorageEnforced != enforced) { 19569 mSettings.mReadExternalStorageEnforced = enforced; 19570 mSettings.writeLPr(); 19571 } 19572 } 19573 // kill any non-foreground processes so we restart them and 19574 // grant/revoke the GID. 19575 final IActivityManager am = ActivityManagerNative.getDefault(); 19576 if (am != null) { 19577 final long token = Binder.clearCallingIdentity(); 19578 try { 19579 am.killProcessesBelowForeground("setPermissionEnforcement"); 19580 } catch (RemoteException e) { 19581 } finally { 19582 Binder.restoreCallingIdentity(token); 19583 } 19584 } 19585 } else { 19586 throw new IllegalArgumentException("No selective enforcement for " + permission); 19587 } 19588 } 19589 19590 @Override 19591 @Deprecated 19592 public boolean isPermissionEnforced(String permission) { 19593 return true; 19594 } 19595 19596 @Override 19597 public boolean isStorageLow() { 19598 final long token = Binder.clearCallingIdentity(); 19599 try { 19600 final DeviceStorageMonitorInternal 19601 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19602 if (dsm != null) { 19603 return dsm.isMemoryLow(); 19604 } else { 19605 return false; 19606 } 19607 } finally { 19608 Binder.restoreCallingIdentity(token); 19609 } 19610 } 19611 19612 @Override 19613 public IPackageInstaller getPackageInstaller() { 19614 return mInstallerService; 19615 } 19616 19617 private boolean userNeedsBadging(int userId) { 19618 int index = mUserNeedsBadging.indexOfKey(userId); 19619 if (index < 0) { 19620 final UserInfo userInfo; 19621 final long token = Binder.clearCallingIdentity(); 19622 try { 19623 userInfo = sUserManager.getUserInfo(userId); 19624 } finally { 19625 Binder.restoreCallingIdentity(token); 19626 } 19627 final boolean b; 19628 if (userInfo != null && userInfo.isManagedProfile()) { 19629 b = true; 19630 } else { 19631 b = false; 19632 } 19633 mUserNeedsBadging.put(userId, b); 19634 return b; 19635 } 19636 return mUserNeedsBadging.valueAt(index); 19637 } 19638 19639 @Override 19640 public KeySet getKeySetByAlias(String packageName, String alias) { 19641 if (packageName == null || alias == null) { 19642 return null; 19643 } 19644 synchronized(mPackages) { 19645 final PackageParser.Package pkg = mPackages.get(packageName); 19646 if (pkg == null) { 19647 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19648 throw new IllegalArgumentException("Unknown package: " + packageName); 19649 } 19650 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19651 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19652 } 19653 } 19654 19655 @Override 19656 public KeySet getSigningKeySet(String packageName) { 19657 if (packageName == null) { 19658 return null; 19659 } 19660 synchronized(mPackages) { 19661 final PackageParser.Package pkg = mPackages.get(packageName); 19662 if (pkg == null) { 19663 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19664 throw new IllegalArgumentException("Unknown package: " + packageName); 19665 } 19666 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19667 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19668 throw new SecurityException("May not access signing KeySet of other apps."); 19669 } 19670 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19671 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19672 } 19673 } 19674 19675 @Override 19676 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19677 if (packageName == null || ks == null) { 19678 return false; 19679 } 19680 synchronized(mPackages) { 19681 final PackageParser.Package pkg = mPackages.get(packageName); 19682 if (pkg == null) { 19683 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19684 throw new IllegalArgumentException("Unknown package: " + packageName); 19685 } 19686 IBinder ksh = ks.getToken(); 19687 if (ksh instanceof KeySetHandle) { 19688 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19689 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19690 } 19691 return false; 19692 } 19693 } 19694 19695 @Override 19696 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19697 if (packageName == null || ks == null) { 19698 return false; 19699 } 19700 synchronized(mPackages) { 19701 final PackageParser.Package pkg = mPackages.get(packageName); 19702 if (pkg == null) { 19703 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19704 throw new IllegalArgumentException("Unknown package: " + packageName); 19705 } 19706 IBinder ksh = ks.getToken(); 19707 if (ksh instanceof KeySetHandle) { 19708 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19709 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19710 } 19711 return false; 19712 } 19713 } 19714 19715 private void deletePackageIfUnusedLPr(final String packageName) { 19716 PackageSetting ps = mSettings.mPackages.get(packageName); 19717 if (ps == null) { 19718 return; 19719 } 19720 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19721 // TODO Implement atomic delete if package is unused 19722 // It is currently possible that the package will be deleted even if it is installed 19723 // after this method returns. 19724 mHandler.post(new Runnable() { 19725 public void run() { 19726 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19727 } 19728 }); 19729 } 19730 } 19731 19732 /** 19733 * Check and throw if the given before/after packages would be considered a 19734 * downgrade. 19735 */ 19736 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19737 throws PackageManagerException { 19738 if (after.versionCode < before.mVersionCode) { 19739 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19740 "Update version code " + after.versionCode + " is older than current " 19741 + before.mVersionCode); 19742 } else if (after.versionCode == before.mVersionCode) { 19743 if (after.baseRevisionCode < before.baseRevisionCode) { 19744 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19745 "Update base revision code " + after.baseRevisionCode 19746 + " is older than current " + before.baseRevisionCode); 19747 } 19748 19749 if (!ArrayUtils.isEmpty(after.splitNames)) { 19750 for (int i = 0; i < after.splitNames.length; i++) { 19751 final String splitName = after.splitNames[i]; 19752 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19753 if (j != -1) { 19754 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19755 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19756 "Update split " + splitName + " revision code " 19757 + after.splitRevisionCodes[i] + " is older than current " 19758 + before.splitRevisionCodes[j]); 19759 } 19760 } 19761 } 19762 } 19763 } 19764 } 19765 19766 private static class MoveCallbacks extends Handler { 19767 private static final int MSG_CREATED = 1; 19768 private static final int MSG_STATUS_CHANGED = 2; 19769 19770 private final RemoteCallbackList<IPackageMoveObserver> 19771 mCallbacks = new RemoteCallbackList<>(); 19772 19773 private final SparseIntArray mLastStatus = new SparseIntArray(); 19774 19775 public MoveCallbacks(Looper looper) { 19776 super(looper); 19777 } 19778 19779 public void register(IPackageMoveObserver callback) { 19780 mCallbacks.register(callback); 19781 } 19782 19783 public void unregister(IPackageMoveObserver callback) { 19784 mCallbacks.unregister(callback); 19785 } 19786 19787 @Override 19788 public void handleMessage(Message msg) { 19789 final SomeArgs args = (SomeArgs) msg.obj; 19790 final int n = mCallbacks.beginBroadcast(); 19791 for (int i = 0; i < n; i++) { 19792 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 19793 try { 19794 invokeCallback(callback, msg.what, args); 19795 } catch (RemoteException ignored) { 19796 } 19797 } 19798 mCallbacks.finishBroadcast(); 19799 args.recycle(); 19800 } 19801 19802 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 19803 throws RemoteException { 19804 switch (what) { 19805 case MSG_CREATED: { 19806 callback.onCreated(args.argi1, (Bundle) args.arg2); 19807 break; 19808 } 19809 case MSG_STATUS_CHANGED: { 19810 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 19811 break; 19812 } 19813 } 19814 } 19815 19816 private void notifyCreated(int moveId, Bundle extras) { 19817 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 19818 19819 final SomeArgs args = SomeArgs.obtain(); 19820 args.argi1 = moveId; 19821 args.arg2 = extras; 19822 obtainMessage(MSG_CREATED, args).sendToTarget(); 19823 } 19824 19825 private void notifyStatusChanged(int moveId, int status) { 19826 notifyStatusChanged(moveId, status, -1); 19827 } 19828 19829 private void notifyStatusChanged(int moveId, int status, long estMillis) { 19830 Slog.v(TAG, "Move " + moveId + " status " + status); 19831 19832 final SomeArgs args = SomeArgs.obtain(); 19833 args.argi1 = moveId; 19834 args.argi2 = status; 19835 args.arg3 = estMillis; 19836 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 19837 19838 synchronized (mLastStatus) { 19839 mLastStatus.put(moveId, status); 19840 } 19841 } 19842 } 19843 19844 private final static class OnPermissionChangeListeners extends Handler { 19845 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 19846 19847 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 19848 new RemoteCallbackList<>(); 19849 19850 public OnPermissionChangeListeners(Looper looper) { 19851 super(looper); 19852 } 19853 19854 @Override 19855 public void handleMessage(Message msg) { 19856 switch (msg.what) { 19857 case MSG_ON_PERMISSIONS_CHANGED: { 19858 final int uid = msg.arg1; 19859 handleOnPermissionsChanged(uid); 19860 } break; 19861 } 19862 } 19863 19864 public void addListenerLocked(IOnPermissionsChangeListener listener) { 19865 mPermissionListeners.register(listener); 19866 19867 } 19868 19869 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 19870 mPermissionListeners.unregister(listener); 19871 } 19872 19873 public void onPermissionsChanged(int uid) { 19874 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 19875 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 19876 } 19877 } 19878 19879 private void handleOnPermissionsChanged(int uid) { 19880 final int count = mPermissionListeners.beginBroadcast(); 19881 try { 19882 for (int i = 0; i < count; i++) { 19883 IOnPermissionsChangeListener callback = mPermissionListeners 19884 .getBroadcastItem(i); 19885 try { 19886 callback.onPermissionsChanged(uid); 19887 } catch (RemoteException e) { 19888 Log.e(TAG, "Permission listener is dead", e); 19889 } 19890 } 19891 } finally { 19892 mPermissionListeners.finishBroadcast(); 19893 } 19894 } 19895 } 19896 19897 private class PackageManagerInternalImpl extends PackageManagerInternal { 19898 @Override 19899 public void setLocationPackagesProvider(PackagesProvider provider) { 19900 synchronized (mPackages) { 19901 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 19902 } 19903 } 19904 19905 @Override 19906 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 19907 synchronized (mPackages) { 19908 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 19909 } 19910 } 19911 19912 @Override 19913 public void setSmsAppPackagesProvider(PackagesProvider provider) { 19914 synchronized (mPackages) { 19915 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 19916 } 19917 } 19918 19919 @Override 19920 public void setDialerAppPackagesProvider(PackagesProvider provider) { 19921 synchronized (mPackages) { 19922 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 19923 } 19924 } 19925 19926 @Override 19927 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 19928 synchronized (mPackages) { 19929 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 19930 } 19931 } 19932 19933 @Override 19934 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 19935 synchronized (mPackages) { 19936 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 19937 } 19938 } 19939 19940 @Override 19941 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 19942 synchronized (mPackages) { 19943 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 19944 packageName, userId); 19945 } 19946 } 19947 19948 @Override 19949 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 19950 synchronized (mPackages) { 19951 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 19952 packageName, userId); 19953 } 19954 } 19955 19956 @Override 19957 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 19958 synchronized (mPackages) { 19959 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 19960 packageName, userId); 19961 } 19962 } 19963 19964 @Override 19965 public void setKeepUninstalledPackages(final List<String> packageList) { 19966 Preconditions.checkNotNull(packageList); 19967 List<String> removedFromList = null; 19968 synchronized (mPackages) { 19969 if (mKeepUninstalledPackages != null) { 19970 final int packagesCount = mKeepUninstalledPackages.size(); 19971 for (int i = 0; i < packagesCount; i++) { 19972 String oldPackage = mKeepUninstalledPackages.get(i); 19973 if (packageList != null && packageList.contains(oldPackage)) { 19974 continue; 19975 } 19976 if (removedFromList == null) { 19977 removedFromList = new ArrayList<>(); 19978 } 19979 removedFromList.add(oldPackage); 19980 } 19981 } 19982 mKeepUninstalledPackages = new ArrayList<>(packageList); 19983 if (removedFromList != null) { 19984 final int removedCount = removedFromList.size(); 19985 for (int i = 0; i < removedCount; i++) { 19986 deletePackageIfUnusedLPr(removedFromList.get(i)); 19987 } 19988 } 19989 } 19990 } 19991 19992 @Override 19993 public boolean isPermissionsReviewRequired(String packageName, int userId) { 19994 synchronized (mPackages) { 19995 // If we do not support permission review, done. 19996 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 19997 return false; 19998 } 19999 20000 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20001 if (packageSetting == null) { 20002 return false; 20003 } 20004 20005 // Permission review applies only to apps not supporting the new permission model. 20006 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20007 return false; 20008 } 20009 20010 // Legacy apps have the permission and get user consent on launch. 20011 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20012 return permissionsState.isPermissionReviewRequired(userId); 20013 } 20014 } 20015 20016 @Override 20017 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20018 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20019 } 20020 20021 @Override 20022 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20023 int userId) { 20024 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20025 } 20026 } 20027 20028 @Override 20029 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20030 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20031 synchronized (mPackages) { 20032 final long identity = Binder.clearCallingIdentity(); 20033 try { 20034 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20035 packageNames, userId); 20036 } finally { 20037 Binder.restoreCallingIdentity(identity); 20038 } 20039 } 20040 } 20041 20042 private static void enforceSystemOrPhoneCaller(String tag) { 20043 int callingUid = Binder.getCallingUid(); 20044 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20045 throw new SecurityException( 20046 "Cannot call " + tag + " from UID " + callingUid); 20047 } 20048 } 20049 20050 boolean isHistoricalPackageUsageAvailable() { 20051 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20052 } 20053 20054 /** 20055 * Return a <b>copy</b> of the collection of packages known to the package manager. 20056 * @return A copy of the values of mPackages. 20057 */ 20058 Collection<PackageParser.Package> getPackages() { 20059 synchronized (mPackages) { 20060 return new ArrayList<>(mPackages.values()); 20061 } 20062 } 20063 20064 /** 20065 * Logs process start information (including base APK hash) to the security log. 20066 * @hide 20067 */ 20068 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20069 String apkFile, int pid) { 20070 if (!SecurityLog.isLoggingEnabled()) { 20071 return; 20072 } 20073 Bundle data = new Bundle(); 20074 data.putLong("startTimestamp", System.currentTimeMillis()); 20075 data.putString("processName", processName); 20076 data.putInt("uid", uid); 20077 data.putString("seinfo", seinfo); 20078 data.putString("apkFile", apkFile); 20079 data.putInt("pid", pid); 20080 Message msg = mProcessLoggingHandler.obtainMessage( 20081 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20082 msg.setData(data); 20083 mProcessLoggingHandler.sendMessage(msg); 20084 } 20085} 20086