PackageManagerService.java revision d5e295f9192522176796271cb29558a53d37c875
1/* 2 * Copyright (C) 2006 The Android Open Source Project 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.android.server.pm; 18 19import static android.Manifest.permission.READ_EXTERNAL_STORAGE; 20import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; 21import static android.Manifest.permission.WRITE_MEDIA_STORAGE; 22import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DEFAULT; 23import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED; 24import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED; 25import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_DISABLED_USER; 26import static android.content.pm.PackageManager.COMPONENT_ENABLED_STATE_ENABLED; 27import static android.content.pm.PackageManager.DELETE_KEEP_DATA; 28import static android.content.pm.PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 29import static android.content.pm.PackageManager.FLAG_PERMISSION_POLICY_FIXED; 30import static android.content.pm.PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 31import static android.content.pm.PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE; 32import static android.content.pm.PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 33import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_FIXED; 34import static android.content.pm.PackageManager.FLAG_PERMISSION_USER_SET; 35import static android.content.pm.PackageManager.INSTALL_EXTERNAL; 36import static android.content.pm.PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 37import static android.content.pm.PackageManager.INSTALL_FAILED_CONFLICTING_PROVIDER; 38import static android.content.pm.PackageManager.INSTALL_FAILED_DEXOPT; 39import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PACKAGE; 40import static android.content.pm.PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION; 41import static android.content.pm.PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID; 42import static android.content.pm.PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 43import static android.content.pm.PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 44import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_APK; 45import static android.content.pm.PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 46import static android.content.pm.PackageManager.INSTALL_FAILED_MISSING_SHARED_LIBRARY; 47import static android.content.pm.PackageManager.INSTALL_FAILED_PACKAGE_CHANGED; 48import static android.content.pm.PackageManager.INSTALL_FAILED_REPLACE_COULDNT_DELETE; 49import static android.content.pm.PackageManager.INSTALL_FAILED_SHARED_USER_INCOMPATIBLE; 50import static android.content.pm.PackageManager.INSTALL_FAILED_TEST_ONLY; 51import static android.content.pm.PackageManager.INSTALL_FAILED_UPDATE_INCOMPATIBLE; 52import static android.content.pm.PackageManager.INSTALL_FAILED_USER_RESTRICTED; 53import static android.content.pm.PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 54import static android.content.pm.PackageManager.INSTALL_FORWARD_LOCK; 55import static android.content.pm.PackageManager.INSTALL_INTERNAL; 56import static android.content.pm.PackageManager.INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES; 57import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS; 58import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK; 59import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK; 60import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER; 61import static android.content.pm.PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED; 62import static android.content.pm.PackageManager.MATCH_ALL; 63import static android.content.pm.PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 64import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_AWARE; 65import static android.content.pm.PackageManager.MATCH_DIRECT_BOOT_UNAWARE; 66import static android.content.pm.PackageManager.MATCH_DISABLED_COMPONENTS; 67import static android.content.pm.PackageManager.MATCH_FACTORY_ONLY; 68import static android.content.pm.PackageManager.MATCH_SYSTEM_ONLY; 69import static android.content.pm.PackageManager.MATCH_UNINSTALLED_PACKAGES; 70import static android.content.pm.PackageManager.MOVE_FAILED_DEVICE_ADMIN; 71import static android.content.pm.PackageManager.MOVE_FAILED_DOESNT_EXIST; 72import static android.content.pm.PackageManager.MOVE_FAILED_INTERNAL_ERROR; 73import static android.content.pm.PackageManager.MOVE_FAILED_OPERATION_PENDING; 74import static android.content.pm.PackageManager.MOVE_FAILED_SYSTEM_PACKAGE; 75import static android.content.pm.PackageManager.PERMISSION_DENIED; 76import static android.content.pm.PackageManager.PERMISSION_GRANTED; 77import static android.content.pm.PackageParser.PARSE_IS_PRIVILEGED; 78import static android.content.pm.PackageParser.isApkFile; 79import static android.os.Process.PACKAGE_INFO_GID; 80import static android.os.Process.SYSTEM_UID; 81import static android.os.Trace.TRACE_TAG_PACKAGE_MANAGER; 82import static android.system.OsConstants.O_CREAT; 83import static android.system.OsConstants.O_RDWR; 84 85import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_MANAGED_PROFILE; 86import static com.android.internal.app.IntentForwarderActivity.FORWARD_INTENT_TO_PARENT; 87import static com.android.internal.content.NativeLibraryHelper.LIB64_DIR_NAME; 88import static com.android.internal.content.NativeLibraryHelper.LIB_DIR_NAME; 89import static com.android.internal.util.ArrayUtils.appendInt; 90import static com.android.server.pm.Installer.DEXOPT_PUBLIC; 91import static com.android.server.pm.InstructionSets.getAppDexInstructionSets; 92import static com.android.server.pm.InstructionSets.getDexCodeInstructionSet; 93import static com.android.server.pm.InstructionSets.getDexCodeInstructionSets; 94import static com.android.server.pm.InstructionSets.getPreferredInstructionSet; 95import static com.android.server.pm.InstructionSets.getPrimaryInstructionSet; 96import static com.android.server.pm.PackageManagerServiceCompilerMapping.getCompilerFilterForReason; 97import static com.android.server.pm.PackageManagerServiceCompilerMapping.getFullCompilerFilter; 98import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_FAILURE; 99import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS; 100import static com.android.server.pm.PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED; 101 102import android.Manifest; 103import android.annotation.NonNull; 104import android.annotation.Nullable; 105import android.app.ActivityManager; 106import android.app.ActivityManagerNative; 107import android.app.IActivityManager; 108import android.app.admin.DevicePolicyManagerInternal; 109import android.app.admin.IDevicePolicyManager; 110import android.app.admin.SecurityLog; 111import android.app.backup.IBackupManager; 112import android.content.BroadcastReceiver; 113import android.content.ComponentName; 114import android.content.Context; 115import android.content.IIntentReceiver; 116import android.content.Intent; 117import android.content.IntentFilter; 118import android.content.IntentSender; 119import android.content.IntentSender.SendIntentException; 120import android.content.ServiceConnection; 121import android.content.pm.ActivityInfo; 122import android.content.pm.ApplicationInfo; 123import android.content.pm.AppsQueryHelper; 124import android.content.pm.ComponentInfo; 125import android.content.pm.EphemeralApplicationInfo; 126import android.content.pm.EphemeralResolveInfo; 127import android.content.pm.EphemeralResolveInfo.EphemeralResolveIntentInfo; 128import android.content.pm.FeatureInfo; 129import android.content.pm.IOnPermissionsChangeListener; 130import android.content.pm.IPackageDataObserver; 131import android.content.pm.IPackageDeleteObserver; 132import android.content.pm.IPackageDeleteObserver2; 133import android.content.pm.IPackageInstallObserver2; 134import android.content.pm.IPackageInstaller; 135import android.content.pm.IPackageManager; 136import android.content.pm.IPackageMoveObserver; 137import android.content.pm.IPackageStatsObserver; 138import android.content.pm.InstrumentationInfo; 139import android.content.pm.IntentFilterVerificationInfo; 140import android.content.pm.KeySet; 141import android.content.pm.PackageCleanItem; 142import android.content.pm.PackageInfo; 143import android.content.pm.PackageInfoLite; 144import android.content.pm.PackageInstaller; 145import android.content.pm.PackageManager; 146import android.content.pm.PackageManager.LegacyPackageDeleteObserver; 147import android.content.pm.PackageManagerInternal; 148import android.content.pm.PackageParser; 149import android.content.pm.PackageParser.ActivityIntentInfo; 150import android.content.pm.PackageParser.PackageLite; 151import android.content.pm.PackageParser.PackageParserException; 152import android.content.pm.PackageStats; 153import android.content.pm.PackageUserState; 154import android.content.pm.ParceledListSlice; 155import android.content.pm.PermissionGroupInfo; 156import android.content.pm.PermissionInfo; 157import android.content.pm.ProviderInfo; 158import android.content.pm.ResolveInfo; 159import android.content.pm.ServiceInfo; 160import android.content.pm.Signature; 161import android.content.pm.UserInfo; 162import android.content.pm.VerifierDeviceIdentity; 163import android.content.pm.VerifierInfo; 164import android.content.res.Resources; 165import android.graphics.Bitmap; 166import android.hardware.display.DisplayManager; 167import android.net.Uri; 168import android.os.Binder; 169import android.os.Build; 170import android.os.Bundle; 171import android.os.Debug; 172import android.os.Environment; 173import android.os.Environment.UserEnvironment; 174import android.os.FileUtils; 175import android.os.Handler; 176import android.os.IBinder; 177import android.os.Looper; 178import android.os.Message; 179import android.os.Parcel; 180import android.os.ParcelFileDescriptor; 181import android.os.Process; 182import android.os.RemoteCallbackList; 183import android.os.RemoteException; 184import android.os.ResultReceiver; 185import android.os.SELinux; 186import android.os.ServiceManager; 187import android.os.SystemClock; 188import android.os.SystemProperties; 189import android.os.Trace; 190import android.os.UserHandle; 191import android.os.UserManager; 192import android.os.storage.IMountService; 193import android.os.storage.MountServiceInternal; 194import android.os.storage.StorageEventListener; 195import android.os.storage.StorageManager; 196import android.os.storage.VolumeInfo; 197import android.os.storage.VolumeRecord; 198import android.security.KeyStore; 199import android.security.SystemKeyStore; 200import android.system.ErrnoException; 201import android.system.Os; 202import android.text.TextUtils; 203import android.text.format.DateUtils; 204import android.util.ArrayMap; 205import android.util.ArraySet; 206import android.util.AtomicFile; 207import android.util.DisplayMetrics; 208import android.util.EventLog; 209import android.util.ExceptionUtils; 210import android.util.Log; 211import android.util.LogPrinter; 212import android.util.MathUtils; 213import android.util.PrintStreamPrinter; 214import android.util.Slog; 215import android.util.SparseArray; 216import android.util.SparseBooleanArray; 217import android.util.SparseIntArray; 218import android.util.Xml; 219import android.util.jar.StrictJarFile; 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 final @NonNull String mSharedSystemSharedLibraryPackageName; 1108 1109 private final PackageUsage mPackageUsage = new PackageUsage(); 1110 1111 private class PackageUsage { 1112 private static final int WRITE_INTERVAL 1113 = (DEBUG_DEXOPT) ? 0 : 30*60*1000; // 30m in ms 1114 1115 private final Object mFileLock = new Object(); 1116 private final AtomicLong mLastWritten = new AtomicLong(0); 1117 private final AtomicBoolean mBackgroundWriteRunning = new AtomicBoolean(false); 1118 1119 private boolean mIsHistoricalPackageUsageAvailable = true; 1120 1121 boolean isHistoricalPackageUsageAvailable() { 1122 return mIsHistoricalPackageUsageAvailable; 1123 } 1124 1125 void write(boolean force) { 1126 if (force) { 1127 writeInternal(); 1128 return; 1129 } 1130 if (SystemClock.elapsedRealtime() - mLastWritten.get() < WRITE_INTERVAL 1131 && !DEBUG_DEXOPT) { 1132 return; 1133 } 1134 if (mBackgroundWriteRunning.compareAndSet(false, true)) { 1135 new Thread("PackageUsage_DiskWriter") { 1136 @Override 1137 public void run() { 1138 try { 1139 writeInternal(); 1140 } finally { 1141 mBackgroundWriteRunning.set(false); 1142 } 1143 } 1144 }.start(); 1145 } 1146 } 1147 1148 private void writeInternal() { 1149 synchronized (mPackages) { 1150 synchronized (mFileLock) { 1151 AtomicFile file = getFile(); 1152 FileOutputStream f = null; 1153 try { 1154 f = file.startWrite(); 1155 BufferedOutputStream out = new BufferedOutputStream(f); 1156 FileUtils.setPermissions(file.getBaseFile().getPath(), 1157 0640, SYSTEM_UID, PACKAGE_INFO_GID); 1158 StringBuilder sb = new StringBuilder(); 1159 1160 sb.append(USAGE_FILE_MAGIC_VERSION_1); 1161 sb.append('\n'); 1162 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1163 1164 for (PackageParser.Package pkg : mPackages.values()) { 1165 if (pkg.getLatestPackageUseTimeInMills() == 0L) { 1166 continue; 1167 } 1168 sb.setLength(0); 1169 sb.append(pkg.packageName); 1170 for (long usageTimeInMillis : pkg.mLastPackageUsageTimeInMills) { 1171 sb.append(' '); 1172 sb.append(usageTimeInMillis); 1173 } 1174 sb.append('\n'); 1175 out.write(sb.toString().getBytes(StandardCharsets.US_ASCII)); 1176 } 1177 out.flush(); 1178 file.finishWrite(f); 1179 } catch (IOException e) { 1180 if (f != null) { 1181 file.failWrite(f); 1182 } 1183 Log.e(TAG, "Failed to write package usage times", e); 1184 } 1185 } 1186 } 1187 mLastWritten.set(SystemClock.elapsedRealtime()); 1188 } 1189 1190 void readLP() { 1191 synchronized (mFileLock) { 1192 AtomicFile file = getFile(); 1193 BufferedInputStream in = null; 1194 try { 1195 in = new BufferedInputStream(file.openRead()); 1196 StringBuffer sb = new StringBuffer(); 1197 1198 String firstLine = readLine(in, sb); 1199 if (firstLine.equals(USAGE_FILE_MAGIC_VERSION_1)) { 1200 readVersion1LP(in, sb); 1201 } else { 1202 readVersion0LP(in, sb, firstLine); 1203 } 1204 } catch (FileNotFoundException expected) { 1205 mIsHistoricalPackageUsageAvailable = false; 1206 } catch (IOException e) { 1207 Log.w(TAG, "Failed to read package usage times", e); 1208 } finally { 1209 IoUtils.closeQuietly(in); 1210 } 1211 } 1212 mLastWritten.set(SystemClock.elapsedRealtime()); 1213 } 1214 1215 private void readVersion0LP(InputStream in, StringBuffer sb, String firstLine) 1216 throws IOException { 1217 // Initial version of the file had no version number and stored one 1218 // package-timestamp pair per line. 1219 // Note that the first line has already been read from the InputStream. 1220 String line = firstLine; 1221 while (true) { 1222 if (line == null) { 1223 break; 1224 } 1225 1226 String[] tokens = line.split(" "); 1227 if (tokens.length != 2) { 1228 throw new IOException("Failed to parse " + line + 1229 " as package-timestamp pair."); 1230 } 1231 1232 String packageName = tokens[0]; 1233 PackageParser.Package pkg = mPackages.get(packageName); 1234 if (pkg == null) { 1235 continue; 1236 } 1237 1238 long timestamp = parseAsLong(tokens[1]); 1239 for (int reason = 0; 1240 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1241 reason++) { 1242 pkg.mLastPackageUsageTimeInMills[reason] = timestamp; 1243 } 1244 1245 line = readLine(in, sb); 1246 } 1247 } 1248 1249 private void readVersion1LP(InputStream in, StringBuffer sb) throws IOException { 1250 // Version 1 of the file started with the corresponding version 1251 // number and then stored a package name and eight timestamps per line. 1252 String line; 1253 while ((line = readLine(in, sb)) != null) { 1254 String[] tokens = line.split(" "); 1255 if (tokens.length != PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT + 1) { 1256 throw new IOException("Failed to parse " + line + " as a timestamp array."); 1257 } 1258 1259 String packageName = tokens[0]; 1260 PackageParser.Package pkg = mPackages.get(packageName); 1261 if (pkg == null) { 1262 continue; 1263 } 1264 1265 for (int reason = 0; 1266 reason < PackageManager.NOTIFY_PACKAGE_USE_REASONS_COUNT; 1267 reason++) { 1268 pkg.mLastPackageUsageTimeInMills[reason] = parseAsLong(tokens[reason + 1]); 1269 } 1270 } 1271 } 1272 1273 private long parseAsLong(String token) throws IOException { 1274 try { 1275 return Long.parseLong(token); 1276 } catch (NumberFormatException e) { 1277 throw new IOException("Failed to parse " + token + " as a long.", e); 1278 } 1279 } 1280 1281 private String readLine(InputStream in, StringBuffer sb) throws IOException { 1282 return readToken(in, sb, '\n'); 1283 } 1284 1285 private String readToken(InputStream in, StringBuffer sb, char endOfToken) 1286 throws IOException { 1287 sb.setLength(0); 1288 while (true) { 1289 int ch = in.read(); 1290 if (ch == -1) { 1291 if (sb.length() == 0) { 1292 return null; 1293 } 1294 throw new IOException("Unexpected EOF"); 1295 } 1296 if (ch == endOfToken) { 1297 return sb.toString(); 1298 } 1299 sb.append((char)ch); 1300 } 1301 } 1302 1303 private AtomicFile getFile() { 1304 File dataDir = Environment.getDataDirectory(); 1305 File systemDir = new File(dataDir, "system"); 1306 File fname = new File(systemDir, "package-usage.list"); 1307 return new AtomicFile(fname); 1308 } 1309 1310 private static final String USAGE_FILE_MAGIC = "PACKAGE_USAGE__VERSION_"; 1311 private static final String USAGE_FILE_MAGIC_VERSION_1 = USAGE_FILE_MAGIC + "1"; 1312 } 1313 1314 class PackageHandler extends Handler { 1315 private boolean mBound = false; 1316 final ArrayList<HandlerParams> mPendingInstalls = 1317 new ArrayList<HandlerParams>(); 1318 1319 private boolean connectToService() { 1320 if (DEBUG_SD_INSTALL) Log.i(TAG, "Trying to bind to" + 1321 " DefaultContainerService"); 1322 Intent service = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 1323 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1324 if (mContext.bindServiceAsUser(service, mDefContainerConn, 1325 Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 1326 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1327 mBound = true; 1328 return true; 1329 } 1330 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1331 return false; 1332 } 1333 1334 private void disconnectService() { 1335 mContainerService = null; 1336 mBound = false; 1337 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1338 mContext.unbindService(mDefContainerConn); 1339 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1340 } 1341 1342 PackageHandler(Looper looper) { 1343 super(looper); 1344 } 1345 1346 public void handleMessage(Message msg) { 1347 try { 1348 doHandleMessage(msg); 1349 } finally { 1350 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1351 } 1352 } 1353 1354 void doHandleMessage(Message msg) { 1355 switch (msg.what) { 1356 case INIT_COPY: { 1357 HandlerParams params = (HandlerParams) msg.obj; 1358 int idx = mPendingInstalls.size(); 1359 if (DEBUG_INSTALL) Slog.i(TAG, "init_copy idx=" + idx + ": " + params); 1360 // If a bind was already initiated we dont really 1361 // need to do anything. The pending install 1362 // will be processed later on. 1363 if (!mBound) { 1364 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1365 System.identityHashCode(mHandler)); 1366 // If this is the only one pending we might 1367 // have to bind to the service again. 1368 if (!connectToService()) { 1369 Slog.e(TAG, "Failed to bind to media container service"); 1370 params.serviceError(); 1371 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1372 System.identityHashCode(mHandler)); 1373 if (params.traceMethod != null) { 1374 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, params.traceMethod, 1375 params.traceCookie); 1376 } 1377 return; 1378 } else { 1379 // Once we bind to the service, the first 1380 // pending request will be processed. 1381 mPendingInstalls.add(idx, params); 1382 } 1383 } else { 1384 mPendingInstalls.add(idx, params); 1385 // Already bound to the service. Just make 1386 // sure we trigger off processing the first request. 1387 if (idx == 0) { 1388 mHandler.sendEmptyMessage(MCS_BOUND); 1389 } 1390 } 1391 break; 1392 } 1393 case MCS_BOUND: { 1394 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_bound"); 1395 if (msg.obj != null) { 1396 mContainerService = (IMediaContainerService) msg.obj; 1397 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "bindingMCS", 1398 System.identityHashCode(mHandler)); 1399 } 1400 if (mContainerService == null) { 1401 if (!mBound) { 1402 // Something seriously wrong since we are not bound and we are not 1403 // waiting for connection. Bail out. 1404 Slog.e(TAG, "Cannot bind to media container service"); 1405 for (HandlerParams params : mPendingInstalls) { 1406 // Indicate service bind error 1407 params.serviceError(); 1408 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1409 System.identityHashCode(params)); 1410 if (params.traceMethod != null) { 1411 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, 1412 params.traceMethod, params.traceCookie); 1413 } 1414 return; 1415 } 1416 mPendingInstalls.clear(); 1417 } else { 1418 Slog.w(TAG, "Waiting to connect to media container service"); 1419 } 1420 } else if (mPendingInstalls.size() > 0) { 1421 HandlerParams params = mPendingInstalls.get(0); 1422 if (params != null) { 1423 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1424 System.identityHashCode(params)); 1425 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "startCopy"); 1426 if (params.startCopy()) { 1427 // We are done... look for more work or to 1428 // go idle. 1429 if (DEBUG_SD_INSTALL) Log.i(TAG, 1430 "Checking for more work or unbind..."); 1431 // Delete pending install 1432 if (mPendingInstalls.size() > 0) { 1433 mPendingInstalls.remove(0); 1434 } 1435 if (mPendingInstalls.size() == 0) { 1436 if (mBound) { 1437 if (DEBUG_SD_INSTALL) Log.i(TAG, 1438 "Posting delayed MCS_UNBIND"); 1439 removeMessages(MCS_UNBIND); 1440 Message ubmsg = obtainMessage(MCS_UNBIND); 1441 // Unbind after a little delay, to avoid 1442 // continual thrashing. 1443 sendMessageDelayed(ubmsg, 10000); 1444 } 1445 } else { 1446 // There are more pending requests in queue. 1447 // Just post MCS_BOUND message to trigger processing 1448 // of next pending install. 1449 if (DEBUG_SD_INSTALL) Log.i(TAG, 1450 "Posting MCS_BOUND for next work"); 1451 mHandler.sendEmptyMessage(MCS_BOUND); 1452 } 1453 } 1454 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 1455 } 1456 } else { 1457 // Should never happen ideally. 1458 Slog.w(TAG, "Empty queue"); 1459 } 1460 break; 1461 } 1462 case MCS_RECONNECT: { 1463 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_reconnect"); 1464 if (mPendingInstalls.size() > 0) { 1465 if (mBound) { 1466 disconnectService(); 1467 } 1468 if (!connectToService()) { 1469 Slog.e(TAG, "Failed to bind to media container service"); 1470 for (HandlerParams params : mPendingInstalls) { 1471 // Indicate service bind error 1472 params.serviceError(); 1473 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1474 System.identityHashCode(params)); 1475 } 1476 mPendingInstalls.clear(); 1477 } 1478 } 1479 break; 1480 } 1481 case MCS_UNBIND: { 1482 // If there is no actual work left, then time to unbind. 1483 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_unbind"); 1484 1485 if (mPendingInstalls.size() == 0 && mPendingVerification.size() == 0) { 1486 if (mBound) { 1487 if (DEBUG_INSTALL) Slog.i(TAG, "calling disconnectService()"); 1488 1489 disconnectService(); 1490 } 1491 } else if (mPendingInstalls.size() > 0) { 1492 // There are more pending requests in queue. 1493 // Just post MCS_BOUND message to trigger processing 1494 // of next pending install. 1495 mHandler.sendEmptyMessage(MCS_BOUND); 1496 } 1497 1498 break; 1499 } 1500 case MCS_GIVE_UP: { 1501 if (DEBUG_INSTALL) Slog.i(TAG, "mcs_giveup too many retries"); 1502 HandlerParams params = mPendingInstalls.remove(0); 1503 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 1504 System.identityHashCode(params)); 1505 break; 1506 } 1507 case SEND_PENDING_BROADCAST: { 1508 String packages[]; 1509 ArrayList<String> components[]; 1510 int size = 0; 1511 int uids[]; 1512 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1513 synchronized (mPackages) { 1514 if (mPendingBroadcasts == null) { 1515 return; 1516 } 1517 size = mPendingBroadcasts.size(); 1518 if (size <= 0) { 1519 // Nothing to be done. Just return 1520 return; 1521 } 1522 packages = new String[size]; 1523 components = new ArrayList[size]; 1524 uids = new int[size]; 1525 int i = 0; // filling out the above arrays 1526 1527 for (int n = 0; n < mPendingBroadcasts.userIdCount(); n++) { 1528 int packageUserId = mPendingBroadcasts.userIdAt(n); 1529 Iterator<Map.Entry<String, ArrayList<String>>> it 1530 = mPendingBroadcasts.packagesForUserId(packageUserId) 1531 .entrySet().iterator(); 1532 while (it.hasNext() && i < size) { 1533 Map.Entry<String, ArrayList<String>> ent = it.next(); 1534 packages[i] = ent.getKey(); 1535 components[i] = ent.getValue(); 1536 PackageSetting ps = mSettings.mPackages.get(ent.getKey()); 1537 uids[i] = (ps != null) 1538 ? UserHandle.getUid(packageUserId, ps.appId) 1539 : -1; 1540 i++; 1541 } 1542 } 1543 size = i; 1544 mPendingBroadcasts.clear(); 1545 } 1546 // Send broadcasts 1547 for (int i = 0; i < size; i++) { 1548 sendPackageChangedBroadcast(packages[i], true, components[i], uids[i]); 1549 } 1550 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1551 break; 1552 } 1553 case START_CLEANING_PACKAGE: { 1554 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1555 final String packageName = (String)msg.obj; 1556 final int userId = msg.arg1; 1557 final boolean andCode = msg.arg2 != 0; 1558 synchronized (mPackages) { 1559 if (userId == UserHandle.USER_ALL) { 1560 int[] users = sUserManager.getUserIds(); 1561 for (int user : users) { 1562 mSettings.addPackageToCleanLPw( 1563 new PackageCleanItem(user, packageName, andCode)); 1564 } 1565 } else { 1566 mSettings.addPackageToCleanLPw( 1567 new PackageCleanItem(userId, packageName, andCode)); 1568 } 1569 } 1570 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1571 startCleaningPackages(); 1572 } break; 1573 case POST_INSTALL: { 1574 if (DEBUG_INSTALL) Log.v(TAG, "Handling post-install for " + msg.arg1); 1575 1576 PostInstallData data = mRunningInstalls.get(msg.arg1); 1577 mRunningInstalls.delete(msg.arg1); 1578 1579 if (data != null) { 1580 InstallArgs args = data.args; 1581 PackageInstalledInfo parentRes = data.res; 1582 1583 final boolean grantPermissions = (args.installFlags 1584 & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0; 1585 final boolean killApp = (args.installFlags 1586 & PackageManager.INSTALL_DONT_KILL_APP) == 0; 1587 final String[] grantedPermissions = args.installGrantPermissions; 1588 1589 // Handle the parent package 1590 handlePackagePostInstall(parentRes, grantPermissions, killApp, 1591 grantedPermissions, args.observer); 1592 1593 // Handle the child packages 1594 final int childCount = (parentRes.addedChildPackages != null) 1595 ? parentRes.addedChildPackages.size() : 0; 1596 for (int i = 0; i < childCount; i++) { 1597 PackageInstalledInfo childRes = parentRes.addedChildPackages.valueAt(i); 1598 handlePackagePostInstall(childRes, grantPermissions, killApp, 1599 grantedPermissions, args.observer); 1600 } 1601 1602 // Log tracing if needed 1603 if (args.traceMethod != null) { 1604 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, args.traceMethod, 1605 args.traceCookie); 1606 } 1607 } else { 1608 Slog.e(TAG, "Bogus post-install token " + msg.arg1); 1609 } 1610 1611 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "postInstall", msg.arg1); 1612 } break; 1613 case UPDATED_MEDIA_STATUS: { 1614 if (DEBUG_SD_INSTALL) Log.i(TAG, "Got message UPDATED_MEDIA_STATUS"); 1615 boolean reportStatus = msg.arg1 == 1; 1616 boolean doGc = msg.arg2 == 1; 1617 if (DEBUG_SD_INSTALL) Log.i(TAG, "reportStatus=" + reportStatus + ", doGc = " + doGc); 1618 if (doGc) { 1619 // Force a gc to clear up stale containers. 1620 Runtime.getRuntime().gc(); 1621 } 1622 if (msg.obj != null) { 1623 @SuppressWarnings("unchecked") 1624 Set<AsecInstallArgs> args = (Set<AsecInstallArgs>) msg.obj; 1625 if (DEBUG_SD_INSTALL) Log.i(TAG, "Unloading all containers"); 1626 // Unload containers 1627 unloadAllContainers(args); 1628 } 1629 if (reportStatus) { 1630 try { 1631 if (DEBUG_SD_INSTALL) Log.i(TAG, "Invoking MountService call back"); 1632 PackageHelper.getMountService().finishMediaUpdate(); 1633 } catch (RemoteException e) { 1634 Log.e(TAG, "MountService not running?"); 1635 } 1636 } 1637 } break; 1638 case WRITE_SETTINGS: { 1639 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1640 synchronized (mPackages) { 1641 removeMessages(WRITE_SETTINGS); 1642 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1643 mSettings.writeLPr(); 1644 mDirtyUsers.clear(); 1645 } 1646 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1647 } break; 1648 case WRITE_PACKAGE_RESTRICTIONS: { 1649 Process.setThreadPriority(Process.THREAD_PRIORITY_DEFAULT); 1650 synchronized (mPackages) { 1651 removeMessages(WRITE_PACKAGE_RESTRICTIONS); 1652 for (int userId : mDirtyUsers) { 1653 mSettings.writePackageRestrictionsLPr(userId); 1654 } 1655 mDirtyUsers.clear(); 1656 } 1657 Process.setThreadPriority(Process.THREAD_PRIORITY_BACKGROUND); 1658 } break; 1659 case CHECK_PENDING_VERIFICATION: { 1660 final int verificationId = msg.arg1; 1661 final PackageVerificationState state = mPendingVerification.get(verificationId); 1662 1663 if ((state != null) && !state.timeoutExtended()) { 1664 final InstallArgs args = state.getInstallArgs(); 1665 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1666 1667 Slog.i(TAG, "Verification timed out for " + originUri); 1668 mPendingVerification.remove(verificationId); 1669 1670 int ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1671 1672 if (getDefaultVerificationResponse() == PackageManager.VERIFICATION_ALLOW) { 1673 Slog.i(TAG, "Continuing with installation of " + originUri); 1674 state.setVerifierResponse(Binder.getCallingUid(), 1675 PackageManager.VERIFICATION_ALLOW_WITHOUT_SUFFICIENT); 1676 broadcastPackageVerified(verificationId, originUri, 1677 PackageManager.VERIFICATION_ALLOW, 1678 state.getInstallArgs().getUser()); 1679 try { 1680 ret = args.copyApk(mContainerService, true); 1681 } catch (RemoteException e) { 1682 Slog.e(TAG, "Could not contact the ContainerService"); 1683 } 1684 } else { 1685 broadcastPackageVerified(verificationId, originUri, 1686 PackageManager.VERIFICATION_REJECT, 1687 state.getInstallArgs().getUser()); 1688 } 1689 1690 Trace.asyncTraceEnd( 1691 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1692 1693 processPendingInstall(args, ret); 1694 mHandler.sendEmptyMessage(MCS_UNBIND); 1695 } 1696 break; 1697 } 1698 case PACKAGE_VERIFIED: { 1699 final int verificationId = msg.arg1; 1700 1701 final PackageVerificationState state = mPendingVerification.get(verificationId); 1702 if (state == null) { 1703 Slog.w(TAG, "Invalid verification token " + verificationId + " received"); 1704 break; 1705 } 1706 1707 final PackageVerificationResponse response = (PackageVerificationResponse) msg.obj; 1708 1709 state.setVerifierResponse(response.callerUid, response.code); 1710 1711 if (state.isVerificationComplete()) { 1712 mPendingVerification.remove(verificationId); 1713 1714 final InstallArgs args = state.getInstallArgs(); 1715 final Uri originUri = Uri.fromFile(args.origin.resolvedFile); 1716 1717 int ret; 1718 if (state.isInstallAllowed()) { 1719 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 1720 broadcastPackageVerified(verificationId, originUri, 1721 response.code, state.getInstallArgs().getUser()); 1722 try { 1723 ret = args.copyApk(mContainerService, true); 1724 } catch (RemoteException e) { 1725 Slog.e(TAG, "Could not contact the ContainerService"); 1726 } 1727 } else { 1728 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 1729 } 1730 1731 Trace.asyncTraceEnd( 1732 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 1733 1734 processPendingInstall(args, ret); 1735 mHandler.sendEmptyMessage(MCS_UNBIND); 1736 } 1737 1738 break; 1739 } 1740 case START_INTENT_FILTER_VERIFICATIONS: { 1741 IFVerificationParams params = (IFVerificationParams) msg.obj; 1742 verifyIntentFiltersIfNeeded(params.userId, params.verifierUid, 1743 params.replacing, params.pkg); 1744 break; 1745 } 1746 case INTENT_FILTER_VERIFIED: { 1747 final int verificationId = msg.arg1; 1748 1749 final IntentFilterVerificationState state = mIntentFilterVerificationStates.get( 1750 verificationId); 1751 if (state == null) { 1752 Slog.w(TAG, "Invalid IntentFilter verification token " 1753 + verificationId + " received"); 1754 break; 1755 } 1756 1757 final int userId = state.getUserId(); 1758 1759 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1760 "Processing IntentFilter verification with token:" 1761 + verificationId + " and userId:" + userId); 1762 1763 final IntentFilterVerificationResponse response = 1764 (IntentFilterVerificationResponse) msg.obj; 1765 1766 state.setVerifierResponse(response.callerUid, response.code); 1767 1768 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1769 "IntentFilter verification with token:" + verificationId 1770 + " and userId:" + userId 1771 + " is settings verifier response with response code:" 1772 + response.code); 1773 1774 if (response.code == PackageManager.INTENT_FILTER_VERIFICATION_FAILURE) { 1775 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Domains failing verification: " 1776 + response.getFailedDomainsString()); 1777 } 1778 1779 if (state.isVerificationComplete()) { 1780 mIntentFilterVerifier.receiveVerificationResponse(verificationId); 1781 } else { 1782 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 1783 "IntentFilter verification with token:" + verificationId 1784 + " was not said to be complete"); 1785 } 1786 1787 break; 1788 } 1789 } 1790 } 1791 } 1792 1793 private void handlePackagePostInstall(PackageInstalledInfo res, boolean grantPermissions, 1794 boolean killApp, String[] grantedPermissions, 1795 IPackageInstallObserver2 installObserver) { 1796 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 1797 // Send the removed broadcasts 1798 if (res.removedInfo != null) { 1799 res.removedInfo.sendPackageRemovedBroadcasts(killApp); 1800 } 1801 1802 // Now that we successfully installed the package, grant runtime 1803 // permissions if requested before broadcasting the install. 1804 if (grantPermissions && res.pkg.applicationInfo.targetSdkVersion 1805 >= Build.VERSION_CODES.M) { 1806 grantRequestedRuntimePermissions(res.pkg, res.newUsers, grantedPermissions); 1807 } 1808 1809 final boolean update = res.removedInfo != null 1810 && res.removedInfo.removedPackage != null; 1811 1812 // If this is the first time we have child packages for a disabled privileged 1813 // app that had no children, we grant requested runtime permissions to the new 1814 // children if the parent on the system image had them already granted. 1815 if (res.pkg.parentPackage != null) { 1816 synchronized (mPackages) { 1817 grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw(res.pkg); 1818 } 1819 } 1820 1821 synchronized (mPackages) { 1822 mEphemeralApplicationRegistry.onPackageInstalledLPw(res.pkg); 1823 } 1824 1825 final String packageName = res.pkg.applicationInfo.packageName; 1826 Bundle extras = new Bundle(1); 1827 extras.putInt(Intent.EXTRA_UID, res.uid); 1828 1829 // Determine the set of users who are adding this package for 1830 // the first time vs. those who are seeing an update. 1831 int[] firstUsers = EMPTY_INT_ARRAY; 1832 int[] updateUsers = EMPTY_INT_ARRAY; 1833 if (res.origUsers == null || res.origUsers.length == 0) { 1834 firstUsers = res.newUsers; 1835 } else { 1836 for (int newUser : res.newUsers) { 1837 boolean isNew = true; 1838 for (int origUser : res.origUsers) { 1839 if (origUser == newUser) { 1840 isNew = false; 1841 break; 1842 } 1843 } 1844 if (isNew) { 1845 firstUsers = ArrayUtils.appendInt(firstUsers, newUser); 1846 } else { 1847 updateUsers = ArrayUtils.appendInt(updateUsers, newUser); 1848 } 1849 } 1850 } 1851 1852 // Send installed broadcasts if the install/update is not ephemeral 1853 if (!isEphemeral(res.pkg)) { 1854 mProcessLoggingHandler.invalidateProcessLoggingBaseApkHash(res.pkg.baseCodePath); 1855 1856 // Send added for users that see the package for the first time 1857 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1858 extras, 0 /*flags*/, null /*targetPackage*/, 1859 null /*finishedReceiver*/, firstUsers); 1860 1861 // Send added for users that don't see the package for the first time 1862 if (update) { 1863 extras.putBoolean(Intent.EXTRA_REPLACING, true); 1864 } 1865 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, packageName, 1866 extras, 0 /*flags*/, null /*targetPackage*/, 1867 null /*finishedReceiver*/, updateUsers); 1868 1869 // Send replaced for users that don't see the package for the first time 1870 if (update) { 1871 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, 1872 packageName, extras, 0 /*flags*/, 1873 null /*targetPackage*/, null /*finishedReceiver*/, 1874 updateUsers); 1875 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, 1876 null /*package*/, null /*extras*/, 0 /*flags*/, 1877 packageName /*targetPackage*/, 1878 null /*finishedReceiver*/, updateUsers); 1879 } 1880 1881 // Send broadcast package appeared if forward locked/external for all users 1882 // treat asec-hosted packages like removable media on upgrade 1883 if (res.pkg.isForwardLocked() || isExternal(res.pkg)) { 1884 if (DEBUG_INSTALL) { 1885 Slog.i(TAG, "upgrading pkg " + res.pkg 1886 + " is ASEC-hosted -> AVAILABLE"); 1887 } 1888 final int[] uidArray = new int[]{res.pkg.applicationInfo.uid}; 1889 ArrayList<String> pkgList = new ArrayList<>(1); 1890 pkgList.add(packageName); 1891 sendResourcesChangedBroadcast(true, true, pkgList, uidArray, null); 1892 } 1893 } 1894 1895 // Work that needs to happen on first install within each user 1896 if (firstUsers != null && firstUsers.length > 0) { 1897 synchronized (mPackages) { 1898 for (int userId : firstUsers) { 1899 // If this app is a browser and it's newly-installed for some 1900 // users, clear any default-browser state in those users. The 1901 // app's nature doesn't depend on the user, so we can just check 1902 // its browser nature in any user and generalize. 1903 if (packageIsBrowser(packageName, userId)) { 1904 mSettings.setDefaultBrowserPackageNameLPw(null, userId); 1905 } 1906 1907 // We may also need to apply pending (restored) runtime 1908 // permission grants within these users. 1909 mSettings.applyPendingPermissionGrantsLPw(packageName, userId); 1910 } 1911 } 1912 } 1913 1914 // Log current value of "unknown sources" setting 1915 EventLog.writeEvent(EventLogTags.UNKNOWN_SOURCES_ENABLED, 1916 getUnknownSourcesSettings()); 1917 1918 // Force a gc to clear up things 1919 Runtime.getRuntime().gc(); 1920 1921 // Remove the replaced package's older resources safely now 1922 // We delete after a gc for applications on sdcard. 1923 if (res.removedInfo != null && res.removedInfo.args != null) { 1924 synchronized (mInstallLock) { 1925 res.removedInfo.args.doPostDeleteLI(true); 1926 } 1927 } 1928 } 1929 1930 // If someone is watching installs - notify them 1931 if (installObserver != null) { 1932 try { 1933 Bundle extras = extrasForInstallResult(res); 1934 installObserver.onPackageInstalled(res.name, res.returnCode, 1935 res.returnMsg, extras); 1936 } catch (RemoteException e) { 1937 Slog.i(TAG, "Observer no longer exists."); 1938 } 1939 } 1940 } 1941 1942 private void grantRuntimePermissionsGrantedToDisabledPrivSysPackageParentLPw( 1943 PackageParser.Package pkg) { 1944 if (pkg.parentPackage == null) { 1945 return; 1946 } 1947 if (pkg.requestedPermissions == null) { 1948 return; 1949 } 1950 final PackageSetting disabledSysParentPs = mSettings 1951 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 1952 if (disabledSysParentPs == null || disabledSysParentPs.pkg == null 1953 || !disabledSysParentPs.isPrivileged() 1954 || (disabledSysParentPs.childPackageNames != null 1955 && !disabledSysParentPs.childPackageNames.isEmpty())) { 1956 return; 1957 } 1958 final int[] allUserIds = sUserManager.getUserIds(); 1959 final int permCount = pkg.requestedPermissions.size(); 1960 for (int i = 0; i < permCount; i++) { 1961 String permission = pkg.requestedPermissions.get(i); 1962 BasePermission bp = mSettings.mPermissions.get(permission); 1963 if (bp == null || !(bp.isRuntime() || bp.isDevelopment())) { 1964 continue; 1965 } 1966 for (int userId : allUserIds) { 1967 if (disabledSysParentPs.getPermissionsState().hasRuntimePermission( 1968 permission, userId)) { 1969 grantRuntimePermission(pkg.packageName, permission, userId); 1970 } 1971 } 1972 } 1973 } 1974 1975 private StorageEventListener mStorageListener = new StorageEventListener() { 1976 @Override 1977 public void onVolumeStateChanged(VolumeInfo vol, int oldState, int newState) { 1978 if (vol.type == VolumeInfo.TYPE_PRIVATE) { 1979 if (vol.state == VolumeInfo.STATE_MOUNTED) { 1980 final String volumeUuid = vol.getFsUuid(); 1981 1982 // Clean up any users or apps that were removed or recreated 1983 // while this volume was missing 1984 reconcileUsers(volumeUuid); 1985 reconcileApps(volumeUuid); 1986 1987 // Clean up any install sessions that expired or were 1988 // cancelled while this volume was missing 1989 mInstallerService.onPrivateVolumeMounted(volumeUuid); 1990 1991 loadPrivatePackages(vol); 1992 1993 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 1994 unloadPrivatePackages(vol); 1995 } 1996 } 1997 1998 if (vol.type == VolumeInfo.TYPE_PUBLIC && vol.isPrimary()) { 1999 if (vol.state == VolumeInfo.STATE_MOUNTED) { 2000 updateExternalMediaStatus(true, false); 2001 } else if (vol.state == VolumeInfo.STATE_EJECTING) { 2002 updateExternalMediaStatus(false, false); 2003 } 2004 } 2005 } 2006 2007 @Override 2008 public void onVolumeForgotten(String fsUuid) { 2009 if (TextUtils.isEmpty(fsUuid)) { 2010 Slog.e(TAG, "Forgetting internal storage is probably a mistake; ignoring"); 2011 return; 2012 } 2013 2014 // Remove any apps installed on the forgotten volume 2015 synchronized (mPackages) { 2016 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(fsUuid); 2017 for (PackageSetting ps : packages) { 2018 Slog.d(TAG, "Destroying " + ps.name + " because volume was forgotten"); 2019 deletePackage(ps.name, new LegacyPackageDeleteObserver(null).getBinder(), 2020 UserHandle.USER_SYSTEM, PackageManager.DELETE_ALL_USERS); 2021 } 2022 2023 mSettings.onVolumeForgotten(fsUuid); 2024 mSettings.writeLPr(); 2025 } 2026 } 2027 }; 2028 2029 private void grantRequestedRuntimePermissions(PackageParser.Package pkg, int[] userIds, 2030 String[] grantedPermissions) { 2031 for (int userId : userIds) { 2032 grantRequestedRuntimePermissionsForUser(pkg, userId, grantedPermissions); 2033 } 2034 2035 // We could have touched GID membership, so flush out packages.list 2036 synchronized (mPackages) { 2037 mSettings.writePackageListLPr(); 2038 } 2039 } 2040 2041 private void grantRequestedRuntimePermissionsForUser(PackageParser.Package pkg, int userId, 2042 String[] grantedPermissions) { 2043 SettingBase sb = (SettingBase) pkg.mExtras; 2044 if (sb == null) { 2045 return; 2046 } 2047 2048 PermissionsState permissionsState = sb.getPermissionsState(); 2049 2050 final int immutableFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 2051 | PackageManager.FLAG_PERMISSION_POLICY_FIXED; 2052 2053 for (String permission : pkg.requestedPermissions) { 2054 final BasePermission bp; 2055 synchronized (mPackages) { 2056 bp = mSettings.mPermissions.get(permission); 2057 } 2058 if (bp != null && (bp.isRuntime() || bp.isDevelopment()) 2059 && (grantedPermissions == null 2060 || ArrayUtils.contains(grantedPermissions, permission))) { 2061 final int flags = permissionsState.getPermissionFlags(permission, userId); 2062 // Installer cannot change immutable permissions. 2063 if ((flags & immutableFlags) == 0) { 2064 grantRuntimePermission(pkg.packageName, permission, userId); 2065 } 2066 } 2067 } 2068 } 2069 2070 Bundle extrasForInstallResult(PackageInstalledInfo res) { 2071 Bundle extras = null; 2072 switch (res.returnCode) { 2073 case PackageManager.INSTALL_FAILED_DUPLICATE_PERMISSION: { 2074 extras = new Bundle(); 2075 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PERMISSION, 2076 res.origPermission); 2077 extras.putString(PackageManager.EXTRA_FAILURE_EXISTING_PACKAGE, 2078 res.origPackage); 2079 break; 2080 } 2081 case PackageManager.INSTALL_SUCCEEDED: { 2082 extras = new Bundle(); 2083 extras.putBoolean(Intent.EXTRA_REPLACING, 2084 res.removedInfo != null && res.removedInfo.removedPackage != null); 2085 break; 2086 } 2087 } 2088 return extras; 2089 } 2090 2091 void scheduleWriteSettingsLocked() { 2092 if (!mHandler.hasMessages(WRITE_SETTINGS)) { 2093 mHandler.sendEmptyMessageDelayed(WRITE_SETTINGS, WRITE_SETTINGS_DELAY); 2094 } 2095 } 2096 2097 void scheduleWritePackageRestrictionsLocked(UserHandle user) { 2098 final int userId = user == null ? UserHandle.USER_ALL : user.getIdentifier(); 2099 scheduleWritePackageRestrictionsLocked(userId); 2100 } 2101 2102 void scheduleWritePackageRestrictionsLocked(int userId) { 2103 final int[] userIds = (userId == UserHandle.USER_ALL) 2104 ? sUserManager.getUserIds() : new int[]{userId}; 2105 for (int nextUserId : userIds) { 2106 if (!sUserManager.exists(nextUserId)) return; 2107 mDirtyUsers.add(nextUserId); 2108 if (!mHandler.hasMessages(WRITE_PACKAGE_RESTRICTIONS)) { 2109 mHandler.sendEmptyMessageDelayed(WRITE_PACKAGE_RESTRICTIONS, WRITE_SETTINGS_DELAY); 2110 } 2111 } 2112 } 2113 2114 public static PackageManagerService main(Context context, Installer installer, 2115 boolean factoryTest, boolean onlyCore) { 2116 // Self-check for initial settings. 2117 PackageManagerServiceCompilerMapping.checkProperties(); 2118 2119 PackageManagerService m = new PackageManagerService(context, installer, 2120 factoryTest, onlyCore); 2121 m.enableSystemUserPackages(); 2122 // Disable any carrier apps. We do this very early in boot to prevent the apps from being 2123 // disabled after already being started. 2124 CarrierAppUtils.disableCarrierAppsUntilPrivileged(context.getOpPackageName(), m, 2125 UserHandle.USER_SYSTEM); 2126 ServiceManager.addService("package", m); 2127 return m; 2128 } 2129 2130 private void enableSystemUserPackages() { 2131 if (!UserManager.isSplitSystemUser()) { 2132 return; 2133 } 2134 // For system user, enable apps based on the following conditions: 2135 // - app is whitelisted or belong to one of these groups: 2136 // -- system app which has no launcher icons 2137 // -- system app which has INTERACT_ACROSS_USERS permission 2138 // -- system IME app 2139 // - app is not in the blacklist 2140 AppsQueryHelper queryHelper = new AppsQueryHelper(this); 2141 Set<String> enableApps = new ArraySet<>(); 2142 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_NON_LAUNCHABLE_APPS 2143 | AppsQueryHelper.GET_APPS_WITH_INTERACT_ACROSS_USERS_PERM 2144 | AppsQueryHelper.GET_IMES, /* systemAppsOnly */ true, UserHandle.SYSTEM)); 2145 ArraySet<String> wlApps = SystemConfig.getInstance().getSystemUserWhitelistedApps(); 2146 enableApps.addAll(wlApps); 2147 enableApps.addAll(queryHelper.queryApps(AppsQueryHelper.GET_REQUIRED_FOR_SYSTEM_USER, 2148 /* systemAppsOnly */ false, UserHandle.SYSTEM)); 2149 ArraySet<String> blApps = SystemConfig.getInstance().getSystemUserBlacklistedApps(); 2150 enableApps.removeAll(blApps); 2151 Log.i(TAG, "Applications installed for system user: " + enableApps); 2152 List<String> allAps = queryHelper.queryApps(0, /* systemAppsOnly */ false, 2153 UserHandle.SYSTEM); 2154 final int allAppsSize = allAps.size(); 2155 synchronized (mPackages) { 2156 for (int i = 0; i < allAppsSize; i++) { 2157 String pName = allAps.get(i); 2158 PackageSetting pkgSetting = mSettings.mPackages.get(pName); 2159 // Should not happen, but we shouldn't be failing if it does 2160 if (pkgSetting == null) { 2161 continue; 2162 } 2163 boolean install = enableApps.contains(pName); 2164 if (pkgSetting.getInstalled(UserHandle.USER_SYSTEM) != install) { 2165 Log.i(TAG, (install ? "Installing " : "Uninstalling ") + pName 2166 + " for system user"); 2167 pkgSetting.setInstalled(install, UserHandle.USER_SYSTEM); 2168 } 2169 } 2170 } 2171 } 2172 2173 private static void getDefaultDisplayMetrics(Context context, DisplayMetrics metrics) { 2174 DisplayManager displayManager = (DisplayManager) context.getSystemService( 2175 Context.DISPLAY_SERVICE); 2176 displayManager.getDisplay(Display.DEFAULT_DISPLAY).getMetrics(metrics); 2177 } 2178 2179 public PackageManagerService(Context context, Installer installer, 2180 boolean factoryTest, boolean onlyCore) { 2181 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_START, 2182 SystemClock.uptimeMillis()); 2183 2184 if (mSdkVersion <= 0) { 2185 Slog.w(TAG, "**** ro.build.version.sdk not set!"); 2186 } 2187 2188 mContext = context; 2189 mFactoryTest = factoryTest; 2190 mOnlyCore = onlyCore; 2191 mMetrics = new DisplayMetrics(); 2192 mSettings = new Settings(mPackages); 2193 mSettings.addSharedUserLPw("android.uid.system", Process.SYSTEM_UID, 2194 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2195 mSettings.addSharedUserLPw("android.uid.phone", RADIO_UID, 2196 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2197 mSettings.addSharedUserLPw("android.uid.log", LOG_UID, 2198 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2199 mSettings.addSharedUserLPw("android.uid.nfc", NFC_UID, 2200 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2201 mSettings.addSharedUserLPw("android.uid.bluetooth", BLUETOOTH_UID, 2202 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2203 mSettings.addSharedUserLPw("android.uid.shell", SHELL_UID, 2204 ApplicationInfo.FLAG_SYSTEM, ApplicationInfo.PRIVATE_FLAG_PRIVILEGED); 2205 2206 String separateProcesses = SystemProperties.get("debug.separate_processes"); 2207 if (separateProcesses != null && separateProcesses.length() > 0) { 2208 if ("*".equals(separateProcesses)) { 2209 mDefParseFlags = PackageParser.PARSE_IGNORE_PROCESSES; 2210 mSeparateProcesses = null; 2211 Slog.w(TAG, "Running with debug.separate_processes: * (ALL)"); 2212 } else { 2213 mDefParseFlags = 0; 2214 mSeparateProcesses = separateProcesses.split(","); 2215 Slog.w(TAG, "Running with debug.separate_processes: " 2216 + separateProcesses); 2217 } 2218 } else { 2219 mDefParseFlags = 0; 2220 mSeparateProcesses = null; 2221 } 2222 2223 mInstaller = installer; 2224 mPackageDexOptimizer = new PackageDexOptimizer(installer, mInstallLock, context, 2225 "*dexopt*"); 2226 mMoveCallbacks = new MoveCallbacks(FgThread.get().getLooper()); 2227 2228 mOnPermissionChangeListeners = new OnPermissionChangeListeners( 2229 FgThread.get().getLooper()); 2230 2231 getDefaultDisplayMetrics(context, mMetrics); 2232 2233 SystemConfig systemConfig = SystemConfig.getInstance(); 2234 mGlobalGids = systemConfig.getGlobalGids(); 2235 mSystemPermissions = systemConfig.getSystemPermissions(); 2236 mAvailableFeatures = systemConfig.getAvailableFeatures(); 2237 2238 synchronized (mInstallLock) { 2239 // writer 2240 synchronized (mPackages) { 2241 mHandlerThread = new ServiceThread(TAG, 2242 Process.THREAD_PRIORITY_BACKGROUND, true /*allowIo*/); 2243 mHandlerThread.start(); 2244 mHandler = new PackageHandler(mHandlerThread.getLooper()); 2245 mProcessLoggingHandler = new ProcessLoggingHandler(); 2246 Watchdog.getInstance().addThread(mHandler, WATCHDOG_TIMEOUT); 2247 2248 File dataDir = Environment.getDataDirectory(); 2249 mAppInstallDir = new File(dataDir, "app"); 2250 mAppLib32InstallDir = new File(dataDir, "app-lib"); 2251 mEphemeralInstallDir = new File(dataDir, "app-ephemeral"); 2252 mAsecInternalPath = new File(dataDir, "app-asec").getPath(); 2253 mDrmAppPrivateInstallDir = new File(dataDir, "app-private"); 2254 2255 sUserManager = new UserManagerService(context, this, mPackages); 2256 2257 // Propagate permission configuration in to package manager. 2258 ArrayMap<String, SystemConfig.PermissionEntry> permConfig 2259 = systemConfig.getPermissions(); 2260 for (int i=0; i<permConfig.size(); i++) { 2261 SystemConfig.PermissionEntry perm = permConfig.valueAt(i); 2262 BasePermission bp = mSettings.mPermissions.get(perm.name); 2263 if (bp == null) { 2264 bp = new BasePermission(perm.name, "android", BasePermission.TYPE_BUILTIN); 2265 mSettings.mPermissions.put(perm.name, bp); 2266 } 2267 if (perm.gids != null) { 2268 bp.setGids(perm.gids, perm.perUser); 2269 } 2270 } 2271 2272 ArrayMap<String, String> libConfig = systemConfig.getSharedLibraries(); 2273 for (int i=0; i<libConfig.size(); i++) { 2274 mSharedLibraries.put(libConfig.keyAt(i), 2275 new SharedLibraryEntry(libConfig.valueAt(i), null)); 2276 } 2277 2278 mFoundPolicyFile = SELinuxMMAC.readInstallPolicy(); 2279 2280 mRestoredSettings = mSettings.readLPw(sUserManager.getUsers(false)); 2281 2282 String customResolverActivity = Resources.getSystem().getString( 2283 R.string.config_customResolverActivity); 2284 if (TextUtils.isEmpty(customResolverActivity)) { 2285 customResolverActivity = null; 2286 } else { 2287 mCustomResolverComponentName = ComponentName.unflattenFromString( 2288 customResolverActivity); 2289 } 2290 2291 long startTime = SystemClock.uptimeMillis(); 2292 2293 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SYSTEM_SCAN_START, 2294 startTime); 2295 2296 // Set flag to monitor and not change apk file paths when 2297 // scanning install directories. 2298 final int scanFlags = SCAN_NO_PATHS | SCAN_DEFER_DEX | SCAN_BOOTING | SCAN_INITIAL; 2299 2300 final String bootClassPath = System.getenv("BOOTCLASSPATH"); 2301 final String systemServerClassPath = System.getenv("SYSTEMSERVERCLASSPATH"); 2302 2303 if (bootClassPath == null) { 2304 Slog.w(TAG, "No BOOTCLASSPATH found!"); 2305 } 2306 2307 if (systemServerClassPath == null) { 2308 Slog.w(TAG, "No SYSTEMSERVERCLASSPATH found!"); 2309 } 2310 2311 final List<String> allInstructionSets = InstructionSets.getAllInstructionSets(); 2312 final String[] dexCodeInstructionSets = 2313 getDexCodeInstructionSets( 2314 allInstructionSets.toArray(new String[allInstructionSets.size()])); 2315 2316 /** 2317 * Ensure all external libraries have had dexopt run on them. 2318 */ 2319 if (mSharedLibraries.size() > 0) { 2320 // NOTE: For now, we're compiling these system "shared libraries" 2321 // (and framework jars) into all available architectures. It's possible 2322 // to compile them only when we come across an app that uses them (there's 2323 // already logic for that in scanPackageLI) but that adds some complexity. 2324 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 2325 for (SharedLibraryEntry libEntry : mSharedLibraries.values()) { 2326 final String lib = libEntry.path; 2327 if (lib == null) { 2328 continue; 2329 } 2330 2331 try { 2332 // Shared libraries do not have profiles so we perform a full 2333 // AOT compilation (if needed). 2334 int dexoptNeeded = DexFile.getDexOptNeeded( 2335 lib, dexCodeInstructionSet, 2336 getCompilerFilterForReason(REASON_SHARED_APK), 2337 false /* newProfile */); 2338 if (dexoptNeeded != DexFile.NO_DEXOPT_NEEDED) { 2339 mInstaller.dexopt(lib, Process.SYSTEM_UID, dexCodeInstructionSet, 2340 dexoptNeeded, DEXOPT_PUBLIC /*dexFlags*/, 2341 getCompilerFilterForReason(REASON_SHARED_APK), 2342 StorageManager.UUID_PRIVATE_INTERNAL); 2343 } 2344 } catch (FileNotFoundException e) { 2345 Slog.w(TAG, "Library not found: " + lib); 2346 } catch (IOException | InstallerException e) { 2347 Slog.w(TAG, "Cannot dexopt " + lib + "; is it an APK or JAR? " 2348 + e.getMessage()); 2349 } 2350 } 2351 } 2352 } 2353 2354 File frameworkDir = new File(Environment.getRootDirectory(), "framework"); 2355 2356 final VersionInfo ver = mSettings.getInternalVersion(); 2357 mIsUpgrade = !Build.FINGERPRINT.equals(ver.fingerprint); 2358 2359 // when upgrading from pre-M, promote system app permissions from install to runtime 2360 mPromoteSystemApps = 2361 mIsUpgrade && ver.sdkVersion <= Build.VERSION_CODES.LOLLIPOP_MR1; 2362 2363 // save off the names of pre-existing system packages prior to scanning; we don't 2364 // want to automatically grant runtime permissions for new system apps 2365 if (mPromoteSystemApps) { 2366 Iterator<PackageSetting> pkgSettingIter = mSettings.mPackages.values().iterator(); 2367 while (pkgSettingIter.hasNext()) { 2368 PackageSetting ps = pkgSettingIter.next(); 2369 if (isSystemApp(ps)) { 2370 mExistingSystemPackages.add(ps.name); 2371 } 2372 } 2373 } 2374 2375 // When upgrading from pre-N, we need to handle package extraction like first boot, 2376 // as there is no profiling data available. 2377 mIsPreNUpgrade = !mSettings.isNWorkDone(); 2378 mSettings.setNWorkDone(); 2379 2380 // Collect vendor overlay packages. 2381 // (Do this before scanning any apps.) 2382 // For security and version matching reason, only consider 2383 // overlay packages if they reside in VENDOR_OVERLAY_DIR. 2384 File vendorOverlayDir = new File(VENDOR_OVERLAY_DIR); 2385 scanDirTracedLI(vendorOverlayDir, mDefParseFlags 2386 | PackageParser.PARSE_IS_SYSTEM 2387 | PackageParser.PARSE_IS_SYSTEM_DIR 2388 | PackageParser.PARSE_TRUSTED_OVERLAY, scanFlags | SCAN_TRUSTED_OVERLAY, 0); 2389 2390 // Find base frameworks (resource packages without code). 2391 scanDirTracedLI(frameworkDir, mDefParseFlags 2392 | PackageParser.PARSE_IS_SYSTEM 2393 | PackageParser.PARSE_IS_SYSTEM_DIR 2394 | PackageParser.PARSE_IS_PRIVILEGED, 2395 scanFlags | SCAN_NO_DEX, 0); 2396 2397 // Collected privileged system packages. 2398 final File privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app"); 2399 scanDirTracedLI(privilegedAppDir, mDefParseFlags 2400 | PackageParser.PARSE_IS_SYSTEM 2401 | PackageParser.PARSE_IS_SYSTEM_DIR 2402 | PackageParser.PARSE_IS_PRIVILEGED, scanFlags, 0); 2403 2404 // Collect ordinary system packages. 2405 final File systemAppDir = new File(Environment.getRootDirectory(), "app"); 2406 scanDirTracedLI(systemAppDir, mDefParseFlags 2407 | PackageParser.PARSE_IS_SYSTEM 2408 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2409 2410 // Collect all vendor packages. 2411 File vendorAppDir = new File("/vendor/app"); 2412 try { 2413 vendorAppDir = vendorAppDir.getCanonicalFile(); 2414 } catch (IOException e) { 2415 // failed to look up canonical path, continue with original one 2416 } 2417 scanDirTracedLI(vendorAppDir, mDefParseFlags 2418 | PackageParser.PARSE_IS_SYSTEM 2419 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2420 2421 // Collect all OEM packages. 2422 final File oemAppDir = new File(Environment.getOemDirectory(), "app"); 2423 scanDirTracedLI(oemAppDir, mDefParseFlags 2424 | PackageParser.PARSE_IS_SYSTEM 2425 | PackageParser.PARSE_IS_SYSTEM_DIR, scanFlags, 0); 2426 2427 // Prune any system packages that no longer exist. 2428 final List<String> possiblyDeletedUpdatedSystemApps = new ArrayList<String>(); 2429 if (!mOnlyCore) { 2430 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 2431 while (psit.hasNext()) { 2432 PackageSetting ps = psit.next(); 2433 2434 /* 2435 * If this is not a system app, it can't be a 2436 * disable system app. 2437 */ 2438 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0) { 2439 continue; 2440 } 2441 2442 /* 2443 * If the package is scanned, it's not erased. 2444 */ 2445 final PackageParser.Package scannedPkg = mPackages.get(ps.name); 2446 if (scannedPkg != null) { 2447 /* 2448 * If the system app is both scanned and in the 2449 * disabled packages list, then it must have been 2450 * added via OTA. Remove it from the currently 2451 * scanned package so the previously user-installed 2452 * application can be scanned. 2453 */ 2454 if (mSettings.isDisabledSystemPackageLPr(ps.name)) { 2455 logCriticalInfo(Log.WARN, "Expecting better updated system app for " 2456 + ps.name + "; removing system app. Last known codePath=" 2457 + ps.codePathString + ", installStatus=" + ps.installStatus 2458 + ", versionCode=" + ps.versionCode + "; scanned versionCode=" 2459 + scannedPkg.mVersionCode); 2460 removePackageLI(scannedPkg, true); 2461 mExpectingBetter.put(ps.name, ps.codePath); 2462 } 2463 2464 continue; 2465 } 2466 2467 if (!mSettings.isDisabledSystemPackageLPr(ps.name)) { 2468 psit.remove(); 2469 logCriticalInfo(Log.WARN, "System package " + ps.name 2470 + " no longer exists; it's data will be wiped"); 2471 // Actual deletion of code and data will be handled by later 2472 // reconciliation step 2473 } else { 2474 final PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(ps.name); 2475 if (disabledPs.codePath == null || !disabledPs.codePath.exists()) { 2476 possiblyDeletedUpdatedSystemApps.add(ps.name); 2477 } 2478 } 2479 } 2480 } 2481 2482 //look for any incomplete package installations 2483 ArrayList<PackageSetting> deletePkgsList = mSettings.getListOfIncompleteInstallPackagesLPr(); 2484 for (int i = 0; i < deletePkgsList.size(); i++) { 2485 // Actual deletion of code and data will be handled by later 2486 // reconciliation step 2487 final String packageName = deletePkgsList.get(i).name; 2488 logCriticalInfo(Log.WARN, "Cleaning up incompletely installed app: " + packageName); 2489 synchronized (mPackages) { 2490 mSettings.removePackageLPw(packageName); 2491 } 2492 } 2493 2494 //delete tmp files 2495 deleteTempPackageFiles(); 2496 2497 // Remove any shared userIDs that have no associated packages 2498 mSettings.pruneSharedUsersLPw(); 2499 2500 if (!mOnlyCore) { 2501 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_DATA_SCAN_START, 2502 SystemClock.uptimeMillis()); 2503 scanDirTracedLI(mAppInstallDir, 0, scanFlags | SCAN_REQUIRE_KNOWN, 0); 2504 2505 scanDirTracedLI(mDrmAppPrivateInstallDir, mDefParseFlags 2506 | PackageParser.PARSE_FORWARD_LOCK, 2507 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2508 2509 scanDirLI(mEphemeralInstallDir, mDefParseFlags 2510 | PackageParser.PARSE_IS_EPHEMERAL, 2511 scanFlags | SCAN_REQUIRE_KNOWN, 0); 2512 2513 /** 2514 * Remove disable package settings for any updated system 2515 * apps that were removed via an OTA. If they're not a 2516 * previously-updated app, remove them completely. 2517 * Otherwise, just revoke their system-level permissions. 2518 */ 2519 for (String deletedAppName : possiblyDeletedUpdatedSystemApps) { 2520 PackageParser.Package deletedPkg = mPackages.get(deletedAppName); 2521 mSettings.removeDisabledSystemPackageLPw(deletedAppName); 2522 2523 String msg; 2524 if (deletedPkg == null) { 2525 msg = "Updated system package " + deletedAppName 2526 + " no longer exists; it's data will be wiped"; 2527 // Actual deletion of code and data will be handled by later 2528 // reconciliation step 2529 } else { 2530 msg = "Updated system app + " + deletedAppName 2531 + " no longer present; removing system privileges for " 2532 + deletedAppName; 2533 2534 deletedPkg.applicationInfo.flags &= ~ApplicationInfo.FLAG_SYSTEM; 2535 2536 PackageSetting deletedPs = mSettings.mPackages.get(deletedAppName); 2537 deletedPs.pkgFlags &= ~ApplicationInfo.FLAG_SYSTEM; 2538 } 2539 logCriticalInfo(Log.WARN, msg); 2540 } 2541 2542 /** 2543 * Make sure all system apps that we expected to appear on 2544 * the userdata partition actually showed up. If they never 2545 * appeared, crawl back and revive the system version. 2546 */ 2547 for (int i = 0; i < mExpectingBetter.size(); i++) { 2548 final String packageName = mExpectingBetter.keyAt(i); 2549 if (!mPackages.containsKey(packageName)) { 2550 final File scanFile = mExpectingBetter.valueAt(i); 2551 2552 logCriticalInfo(Log.WARN, "Expected better " + packageName 2553 + " but never showed up; reverting to system"); 2554 2555 int reparseFlags = mDefParseFlags; 2556 if (FileUtils.contains(privilegedAppDir, scanFile)) { 2557 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2558 | PackageParser.PARSE_IS_SYSTEM_DIR 2559 | PackageParser.PARSE_IS_PRIVILEGED; 2560 } else if (FileUtils.contains(systemAppDir, scanFile)) { 2561 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2562 | PackageParser.PARSE_IS_SYSTEM_DIR; 2563 } else if (FileUtils.contains(vendorAppDir, scanFile)) { 2564 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2565 | PackageParser.PARSE_IS_SYSTEM_DIR; 2566 } else if (FileUtils.contains(oemAppDir, scanFile)) { 2567 reparseFlags = PackageParser.PARSE_IS_SYSTEM 2568 | PackageParser.PARSE_IS_SYSTEM_DIR; 2569 } else { 2570 Slog.e(TAG, "Ignoring unexpected fallback path " + scanFile); 2571 continue; 2572 } 2573 2574 mSettings.enableSystemPackageLPw(packageName); 2575 2576 try { 2577 scanPackageTracedLI(scanFile, reparseFlags, scanFlags, 0, null); 2578 } catch (PackageManagerException e) { 2579 Slog.e(TAG, "Failed to parse original system package: " 2580 + e.getMessage()); 2581 } 2582 } 2583 } 2584 } 2585 mExpectingBetter.clear(); 2586 2587 // Resolve protected action filters. Only the setup wizard is allowed to 2588 // have a high priority filter for these actions. 2589 mSetupWizardPackage = getSetupWizardPackageName(); 2590 if (mProtectedFilters.size() > 0) { 2591 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 2592 Slog.i(TAG, "No setup wizard;" 2593 + " All protected intents capped to priority 0"); 2594 } 2595 for (ActivityIntentInfo filter : mProtectedFilters) { 2596 if (filter.activity.info.packageName.equals(mSetupWizardPackage)) { 2597 if (DEBUG_FILTERS) { 2598 Slog.i(TAG, "Found setup wizard;" 2599 + " allow priority " + filter.getPriority() + ";" 2600 + " package: " + filter.activity.info.packageName 2601 + " activity: " + filter.activity.className 2602 + " priority: " + filter.getPriority()); 2603 } 2604 // skip setup wizard; allow it to keep the high priority filter 2605 continue; 2606 } 2607 Slog.w(TAG, "Protected action; cap priority to 0;" 2608 + " package: " + filter.activity.info.packageName 2609 + " activity: " + filter.activity.className 2610 + " origPrio: " + filter.getPriority()); 2611 filter.setPriority(0); 2612 } 2613 } 2614 mDeferProtectedFilters = false; 2615 mProtectedFilters.clear(); 2616 2617 // Now that we know all of the shared libraries, update all clients to have 2618 // the correct library paths. 2619 updateAllSharedLibrariesLPw(); 2620 2621 for (SharedUserSetting setting : mSettings.getAllSharedUsersLPw()) { 2622 // NOTE: We ignore potential failures here during a system scan (like 2623 // the rest of the commands above) because there's precious little we 2624 // can do about it. A settings error is reported, though. 2625 adjustCpuAbisForSharedUserLPw(setting.packages, null /* scanned package */, 2626 false /* boot complete */); 2627 } 2628 2629 // Now that we know all the packages we are keeping, 2630 // read and update their last usage times. 2631 mPackageUsage.readLP(); 2632 2633 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_SCAN_END, 2634 SystemClock.uptimeMillis()); 2635 Slog.i(TAG, "Time to scan packages: " 2636 + ((SystemClock.uptimeMillis()-startTime)/1000f) 2637 + " seconds"); 2638 2639 // If the platform SDK has changed since the last time we booted, 2640 // we need to re-grant app permission to catch any new ones that 2641 // appear. This is really a hack, and means that apps can in some 2642 // cases get permissions that the user didn't initially explicitly 2643 // allow... it would be nice to have some better way to handle 2644 // this situation. 2645 int updateFlags = UPDATE_PERMISSIONS_ALL; 2646 if (ver.sdkVersion != mSdkVersion) { 2647 Slog.i(TAG, "Platform changed from " + ver.sdkVersion + " to " 2648 + mSdkVersion + "; regranting permissions for internal storage"); 2649 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 2650 } 2651 updatePermissionsLPw(null, null, StorageManager.UUID_PRIVATE_INTERNAL, updateFlags); 2652 ver.sdkVersion = mSdkVersion; 2653 2654 // If this is the first boot or an update from pre-M, and it is a normal 2655 // boot, then we need to initialize the default preferred apps across 2656 // all defined users. 2657 if (!onlyCore && (mPromoteSystemApps || !mRestoredSettings)) { 2658 for (UserInfo user : sUserManager.getUsers(true)) { 2659 mSettings.applyDefaultPreferredAppsLPw(this, user.id); 2660 applyFactoryDefaultBrowserLPw(user.id); 2661 primeDomainVerificationsLPw(user.id); 2662 } 2663 } 2664 2665 // Prepare storage for system user really early during boot, 2666 // since core system apps like SettingsProvider and SystemUI 2667 // can't wait for user to start 2668 final int storageFlags; 2669 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 2670 storageFlags = StorageManager.FLAG_STORAGE_DE; 2671 } else { 2672 storageFlags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 2673 } 2674 reconcileAppsDataLI(StorageManager.UUID_PRIVATE_INTERNAL, UserHandle.USER_SYSTEM, 2675 storageFlags); 2676 2677 // If this is first boot after an OTA, and a normal boot, then 2678 // we need to clear code cache directories. 2679 if (mIsUpgrade && !onlyCore) { 2680 Slog.i(TAG, "Build fingerprint changed; clearing code caches"); 2681 for (int i = 0; i < mSettings.mPackages.size(); i++) { 2682 final PackageSetting ps = mSettings.mPackages.valueAt(i); 2683 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, ps.volumeUuid)) { 2684 // No apps are running this early, so no need to freeze 2685 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 2686 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 2687 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 2688 } 2689 clearAppProfilesLIF(ps.pkg); 2690 } 2691 ver.fingerprint = Build.FINGERPRINT; 2692 } 2693 2694 checkDefaultBrowser(); 2695 2696 // clear only after permissions and other defaults have been updated 2697 mExistingSystemPackages.clear(); 2698 mPromoteSystemApps = false; 2699 2700 // All the changes are done during package scanning. 2701 ver.databaseVersion = Settings.CURRENT_DATABASE_VERSION; 2702 2703 // can downgrade to reader 2704 mSettings.writeLPr(); 2705 2706 EventLog.writeEvent(EventLogTags.BOOT_PROGRESS_PMS_READY, 2707 SystemClock.uptimeMillis()); 2708 2709 if (!mOnlyCore) { 2710 mRequiredVerifierPackage = getRequiredButNotReallyRequiredVerifierLPr(); 2711 mRequiredInstallerPackage = getRequiredInstallerLPr(); 2712 mIntentFilterVerifierComponent = getIntentFilterVerifierComponentNameLPr(); 2713 mIntentFilterVerifier = new IntentVerifierProxy(mContext, 2714 mIntentFilterVerifierComponent); 2715 mServicesSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2716 PackageManager.SYSTEM_SHARED_LIBRARY_SERVICES); 2717 mSharedSystemSharedLibraryPackageName = getRequiredSharedLibraryLPr( 2718 PackageManager.SYSTEM_SHARED_LIBRARY_SHARED); 2719 } else { 2720 mRequiredVerifierPackage = null; 2721 mRequiredInstallerPackage = null; 2722 mIntentFilterVerifierComponent = null; 2723 mIntentFilterVerifier = null; 2724 mServicesSystemSharedLibraryPackageName = null; 2725 mSharedSystemSharedLibraryPackageName = null; 2726 } 2727 2728 mInstallerService = new PackageInstallerService(context, this); 2729 2730 final ComponentName ephemeralResolverComponent = getEphemeralResolverLPr(); 2731 final ComponentName ephemeralInstallerComponent = getEphemeralInstallerLPr(); 2732 // both the installer and resolver must be present to enable ephemeral 2733 if (ephemeralInstallerComponent != null && ephemeralResolverComponent != null) { 2734 if (DEBUG_EPHEMERAL) { 2735 Slog.i(TAG, "Ephemeral activated; resolver: " + ephemeralResolverComponent 2736 + " installer:" + ephemeralInstallerComponent); 2737 } 2738 mEphemeralResolverComponent = ephemeralResolverComponent; 2739 mEphemeralInstallerComponent = ephemeralInstallerComponent; 2740 setUpEphemeralInstallerActivityLP(mEphemeralInstallerComponent); 2741 mEphemeralResolverConnection = 2742 new EphemeralResolverConnection(mContext, mEphemeralResolverComponent); 2743 } else { 2744 if (DEBUG_EPHEMERAL) { 2745 final String missingComponent = 2746 (ephemeralResolverComponent == null) 2747 ? (ephemeralInstallerComponent == null) 2748 ? "resolver and installer" 2749 : "resolver" 2750 : "installer"; 2751 Slog.i(TAG, "Ephemeral deactivated; missing " + missingComponent); 2752 } 2753 mEphemeralResolverComponent = null; 2754 mEphemeralInstallerComponent = null; 2755 mEphemeralResolverConnection = null; 2756 } 2757 2758 mEphemeralApplicationRegistry = new EphemeralApplicationRegistry(this); 2759 } // synchronized (mPackages) 2760 } // synchronized (mInstallLock) 2761 2762 // Now after opening every single application zip, make sure they 2763 // are all flushed. Not really needed, but keeps things nice and 2764 // tidy. 2765 Runtime.getRuntime().gc(); 2766 2767 // The initial scanning above does many calls into installd while 2768 // holding the mPackages lock, but we're mostly interested in yelling 2769 // once we have a booted system. 2770 mInstaller.setWarnIfHeld(mPackages); 2771 2772 // Expose private service for system components to use. 2773 LocalServices.addService(PackageManagerInternal.class, new PackageManagerInternalImpl()); 2774 } 2775 2776 @Override 2777 public boolean isFirstBoot() { 2778 return !mRestoredSettings; 2779 } 2780 2781 @Override 2782 public boolean isOnlyCoreApps() { 2783 return mOnlyCore; 2784 } 2785 2786 @Override 2787 public boolean isUpgrade() { 2788 return mIsUpgrade; 2789 } 2790 2791 private @Nullable String getRequiredButNotReallyRequiredVerifierLPr() { 2792 final Intent intent = new Intent(Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 2793 2794 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2795 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2796 UserHandle.USER_SYSTEM); 2797 if (matches.size() == 1) { 2798 return matches.get(0).getComponentInfo().packageName; 2799 } else { 2800 Log.e(TAG, "There should probably be exactly one verifier; found " + matches); 2801 return null; 2802 } 2803 } 2804 2805 private @NonNull String getRequiredSharedLibraryLPr(String libraryName) { 2806 synchronized (mPackages) { 2807 SharedLibraryEntry libraryEntry = mSharedLibraries.get(libraryName); 2808 if (libraryEntry == null) { 2809 throw new IllegalStateException("Missing required shared library:" + libraryName); 2810 } 2811 return libraryEntry.apk; 2812 } 2813 } 2814 2815 private @NonNull String getRequiredInstallerLPr() { 2816 final Intent intent = new Intent(Intent.ACTION_INSTALL_PACKAGE); 2817 intent.addCategory(Intent.CATEGORY_DEFAULT); 2818 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2819 2820 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2821 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2822 UserHandle.USER_SYSTEM); 2823 if (matches.size() == 1) { 2824 ResolveInfo resolveInfo = matches.get(0); 2825 if (!resolveInfo.activityInfo.applicationInfo.isPrivilegedApp()) { 2826 throw new RuntimeException("The installer must be a privileged app"); 2827 } 2828 return matches.get(0).getComponentInfo().packageName; 2829 } else { 2830 throw new RuntimeException("There must be exactly one installer; found " + matches); 2831 } 2832 } 2833 2834 private @NonNull ComponentName getIntentFilterVerifierComponentNameLPr() { 2835 final Intent intent = new Intent(Intent.ACTION_INTENT_FILTER_NEEDS_VERIFICATION); 2836 2837 final List<ResolveInfo> matches = queryIntentReceiversInternal(intent, PACKAGE_MIME_TYPE, 2838 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2839 UserHandle.USER_SYSTEM); 2840 ResolveInfo best = null; 2841 final int N = matches.size(); 2842 for (int i = 0; i < N; i++) { 2843 final ResolveInfo cur = matches.get(i); 2844 final String packageName = cur.getComponentInfo().packageName; 2845 if (checkPermission(android.Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 2846 packageName, UserHandle.USER_SYSTEM) != PackageManager.PERMISSION_GRANTED) { 2847 continue; 2848 } 2849 2850 if (best == null || cur.priority > best.priority) { 2851 best = cur; 2852 } 2853 } 2854 2855 if (best != null) { 2856 return best.getComponentInfo().getComponentName(); 2857 } else { 2858 throw new RuntimeException("There must be at least one intent filter verifier"); 2859 } 2860 } 2861 2862 private @Nullable ComponentName getEphemeralResolverLPr() { 2863 final String[] packageArray = 2864 mContext.getResources().getStringArray(R.array.config_ephemeralResolverPackage); 2865 if (packageArray.length == 0) { 2866 if (DEBUG_EPHEMERAL) { 2867 Slog.d(TAG, "Ephemeral resolver NOT found; empty package list"); 2868 } 2869 return null; 2870 } 2871 2872 final Intent resolverIntent = new Intent(Intent.ACTION_RESOLVE_EPHEMERAL_PACKAGE); 2873 final List<ResolveInfo> resolvers = queryIntentServicesInternal(resolverIntent, null, 2874 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2875 UserHandle.USER_SYSTEM); 2876 2877 final int N = resolvers.size(); 2878 if (N == 0) { 2879 if (DEBUG_EPHEMERAL) { 2880 Slog.d(TAG, "Ephemeral resolver NOT found; no matching intent filters"); 2881 } 2882 return null; 2883 } 2884 2885 final Set<String> possiblePackages = new ArraySet<>(Arrays.asList(packageArray)); 2886 for (int i = 0; i < N; i++) { 2887 final ResolveInfo info = resolvers.get(i); 2888 2889 if (info.serviceInfo == null) { 2890 continue; 2891 } 2892 2893 final String packageName = info.serviceInfo.packageName; 2894 if (!possiblePackages.contains(packageName)) { 2895 if (DEBUG_EPHEMERAL) { 2896 Slog.d(TAG, "Ephemeral resolver not in allowed package list;" 2897 + " pkg: " + packageName + ", info:" + info); 2898 } 2899 continue; 2900 } 2901 2902 if (DEBUG_EPHEMERAL) { 2903 Slog.v(TAG, "Ephemeral resolver found;" 2904 + " pkg: " + packageName + ", info:" + info); 2905 } 2906 return new ComponentName(packageName, info.serviceInfo.name); 2907 } 2908 if (DEBUG_EPHEMERAL) { 2909 Slog.v(TAG, "Ephemeral resolver NOT found"); 2910 } 2911 return null; 2912 } 2913 2914 private @Nullable ComponentName getEphemeralInstallerLPr() { 2915 final Intent intent = new Intent(Intent.ACTION_INSTALL_EPHEMERAL_PACKAGE); 2916 intent.addCategory(Intent.CATEGORY_DEFAULT); 2917 intent.setDataAndType(Uri.fromFile(new File("foo.apk")), PACKAGE_MIME_TYPE); 2918 2919 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, PACKAGE_MIME_TYPE, 2920 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 2921 UserHandle.USER_SYSTEM); 2922 if (matches.size() == 0) { 2923 return null; 2924 } else if (matches.size() == 1) { 2925 return matches.get(0).getComponentInfo().getComponentName(); 2926 } else { 2927 throw new RuntimeException( 2928 "There must be at most one ephemeral installer; found " + matches); 2929 } 2930 } 2931 2932 private void primeDomainVerificationsLPw(int userId) { 2933 if (DEBUG_DOMAIN_VERIFICATION) { 2934 Slog.d(TAG, "Priming domain verifications in user " + userId); 2935 } 2936 2937 SystemConfig systemConfig = SystemConfig.getInstance(); 2938 ArraySet<String> packages = systemConfig.getLinkedApps(); 2939 ArraySet<String> domains = new ArraySet<String>(); 2940 2941 for (String packageName : packages) { 2942 PackageParser.Package pkg = mPackages.get(packageName); 2943 if (pkg != null) { 2944 if (!pkg.isSystemApp()) { 2945 Slog.w(TAG, "Non-system app '" + packageName + "' in sysconfig <app-link>"); 2946 continue; 2947 } 2948 2949 domains.clear(); 2950 for (PackageParser.Activity a : pkg.activities) { 2951 for (ActivityIntentInfo filter : a.intents) { 2952 if (hasValidDomains(filter)) { 2953 domains.addAll(filter.getHostsList()); 2954 } 2955 } 2956 } 2957 2958 if (domains.size() > 0) { 2959 if (DEBUG_DOMAIN_VERIFICATION) { 2960 Slog.v(TAG, " + " + packageName); 2961 } 2962 // 'Undefined' in the global IntentFilterVerificationInfo, i.e. the usual 2963 // state w.r.t. the formal app-linkage "no verification attempted" state; 2964 // and then 'always' in the per-user state actually used for intent resolution. 2965 final IntentFilterVerificationInfo ivi; 2966 ivi = mSettings.createIntentFilterVerificationIfNeededLPw(packageName, 2967 new ArrayList<String>(domains)); 2968 ivi.setStatus(INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED); 2969 mSettings.updateIntentFilterVerificationStatusLPw(packageName, 2970 INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, userId); 2971 } else { 2972 Slog.w(TAG, "Sysconfig <app-link> package '" + packageName 2973 + "' does not handle web links"); 2974 } 2975 } else { 2976 Slog.w(TAG, "Unknown package " + packageName + " in sysconfig <app-link>"); 2977 } 2978 } 2979 2980 scheduleWritePackageRestrictionsLocked(userId); 2981 scheduleWriteSettingsLocked(); 2982 } 2983 2984 private void applyFactoryDefaultBrowserLPw(int userId) { 2985 // The default browser app's package name is stored in a string resource, 2986 // with a product-specific overlay used for vendor customization. 2987 String browserPkg = mContext.getResources().getString( 2988 com.android.internal.R.string.default_browser); 2989 if (!TextUtils.isEmpty(browserPkg)) { 2990 // non-empty string => required to be a known package 2991 PackageSetting ps = mSettings.mPackages.get(browserPkg); 2992 if (ps == null) { 2993 Slog.e(TAG, "Product default browser app does not exist: " + browserPkg); 2994 browserPkg = null; 2995 } else { 2996 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 2997 } 2998 } 2999 3000 // Nothing valid explicitly set? Make the factory-installed browser the explicit 3001 // default. If there's more than one, just leave everything alone. 3002 if (browserPkg == null) { 3003 calculateDefaultBrowserLPw(userId); 3004 } 3005 } 3006 3007 private void calculateDefaultBrowserLPw(int userId) { 3008 List<String> allBrowsers = resolveAllBrowserApps(userId); 3009 final String browserPkg = (allBrowsers.size() == 1) ? allBrowsers.get(0) : null; 3010 mSettings.setDefaultBrowserPackageNameLPw(browserPkg, userId); 3011 } 3012 3013 private List<String> resolveAllBrowserApps(int userId) { 3014 // Resolve the canonical browser intent and check that the handleAllWebDataURI boolean is set 3015 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3016 PackageManager.MATCH_ALL, userId); 3017 3018 final int count = list.size(); 3019 List<String> result = new ArrayList<String>(count); 3020 for (int i=0; i<count; i++) { 3021 ResolveInfo info = list.get(i); 3022 if (info.activityInfo == null 3023 || !info.handleAllWebDataURI 3024 || (info.activityInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) == 0 3025 || result.contains(info.activityInfo.packageName)) { 3026 continue; 3027 } 3028 result.add(info.activityInfo.packageName); 3029 } 3030 3031 return result; 3032 } 3033 3034 private boolean packageIsBrowser(String packageName, int userId) { 3035 List<ResolveInfo> list = queryIntentActivitiesInternal(sBrowserIntent, null, 3036 PackageManager.MATCH_ALL, userId); 3037 final int N = list.size(); 3038 for (int i = 0; i < N; i++) { 3039 ResolveInfo info = list.get(i); 3040 if (packageName.equals(info.activityInfo.packageName)) { 3041 return true; 3042 } 3043 } 3044 return false; 3045 } 3046 3047 private void checkDefaultBrowser() { 3048 final int myUserId = UserHandle.myUserId(); 3049 final String packageName = getDefaultBrowserPackageName(myUserId); 3050 if (packageName != null) { 3051 PackageInfo info = getPackageInfo(packageName, 0, myUserId); 3052 if (info == null) { 3053 Slog.w(TAG, "Default browser no longer installed: " + packageName); 3054 synchronized (mPackages) { 3055 applyFactoryDefaultBrowserLPw(myUserId); // leaves ambiguous when > 1 3056 } 3057 } 3058 } 3059 } 3060 3061 @Override 3062 public boolean onTransact(int code, Parcel data, Parcel reply, int flags) 3063 throws RemoteException { 3064 try { 3065 return super.onTransact(code, data, reply, flags); 3066 } catch (RuntimeException e) { 3067 if (!(e instanceof SecurityException) && !(e instanceof IllegalArgumentException)) { 3068 Slog.wtf(TAG, "Package Manager Crash", e); 3069 } 3070 throw e; 3071 } 3072 } 3073 3074 static int[] appendInts(int[] cur, int[] add) { 3075 if (add == null) return cur; 3076 if (cur == null) return add; 3077 final int N = add.length; 3078 for (int i=0; i<N; i++) { 3079 cur = appendInt(cur, add[i]); 3080 } 3081 return cur; 3082 } 3083 3084 private PackageInfo generatePackageInfo(PackageSetting ps, int flags, int userId) { 3085 if (!sUserManager.exists(userId)) return null; 3086 if (ps == null) { 3087 return null; 3088 } 3089 final PackageParser.Package p = ps.pkg; 3090 if (p == null) { 3091 return null; 3092 } 3093 3094 final PermissionsState permissionsState = ps.getPermissionsState(); 3095 3096 final int[] gids = permissionsState.computeGids(userId); 3097 final Set<String> permissions = permissionsState.getPermissions(userId); 3098 final PackageUserState state = ps.readUserState(userId); 3099 3100 return PackageParser.generatePackageInfo(p, gids, flags, 3101 ps.firstInstallTime, ps.lastUpdateTime, permissions, state, userId); 3102 } 3103 3104 @Override 3105 public void checkPackageStartable(String packageName, int userId) { 3106 final boolean userKeyUnlocked = isUserKeyUnlocked(userId); 3107 3108 synchronized (mPackages) { 3109 final PackageSetting ps = mSettings.mPackages.get(packageName); 3110 if (ps == null) { 3111 throw new SecurityException("Package " + packageName + " was not found!"); 3112 } 3113 3114 if (!ps.getInstalled(userId)) { 3115 throw new SecurityException( 3116 "Package " + packageName + " was not installed for user " + userId + "!"); 3117 } 3118 3119 if (mSafeMode && !ps.isSystem()) { 3120 throw new SecurityException("Package " + packageName + " not a system app!"); 3121 } 3122 3123 if (mFrozenPackages.contains(packageName)) { 3124 throw new SecurityException("Package " + packageName + " is currently frozen!"); 3125 } 3126 3127 if (!userKeyUnlocked && !(ps.pkg.applicationInfo.isDirectBootAware() 3128 || ps.pkg.applicationInfo.isPartiallyDirectBootAware())) { 3129 throw new SecurityException("Package " + packageName + " is not encryption aware!"); 3130 } 3131 } 3132 } 3133 3134 @Override 3135 public boolean isPackageAvailable(String packageName, int userId) { 3136 if (!sUserManager.exists(userId)) return false; 3137 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3138 false /* requireFullPermission */, false /* checkShell */, "is package available"); 3139 synchronized (mPackages) { 3140 PackageParser.Package p = mPackages.get(packageName); 3141 if (p != null) { 3142 final PackageSetting ps = (PackageSetting) p.mExtras; 3143 if (ps != null) { 3144 final PackageUserState state = ps.readUserState(userId); 3145 if (state != null) { 3146 return PackageParser.isAvailable(state); 3147 } 3148 } 3149 } 3150 } 3151 return false; 3152 } 3153 3154 @Override 3155 public PackageInfo getPackageInfo(String packageName, int flags, int userId) { 3156 if (!sUserManager.exists(userId)) return null; 3157 flags = updateFlagsForPackage(flags, userId, packageName); 3158 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3159 false /* requireFullPermission */, false /* checkShell */, "get package info"); 3160 // reader 3161 synchronized (mPackages) { 3162 final boolean matchFactoryOnly = (flags & MATCH_FACTORY_ONLY) != 0; 3163 PackageParser.Package p = null; 3164 if (matchFactoryOnly) { 3165 final PackageSetting ps = mSettings.getDisabledSystemPkgLPr(packageName); 3166 if (ps != null) { 3167 return generatePackageInfo(ps, flags, userId); 3168 } 3169 } 3170 if (p == null) { 3171 p = mPackages.get(packageName); 3172 if (matchFactoryOnly && p != null && !isSystemApp(p)) { 3173 return null; 3174 } 3175 } 3176 if (DEBUG_PACKAGE_INFO) 3177 Log.v(TAG, "getPackageInfo " + packageName + ": " + p); 3178 if (p != null) { 3179 return generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 3180 } 3181 if (!matchFactoryOnly && (flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3182 final PackageSetting ps = mSettings.mPackages.get(packageName); 3183 return generatePackageInfo(ps, flags, userId); 3184 } 3185 } 3186 return null; 3187 } 3188 3189 @Override 3190 public String[] currentToCanonicalPackageNames(String[] names) { 3191 String[] out = new String[names.length]; 3192 // reader 3193 synchronized (mPackages) { 3194 for (int i=names.length-1; i>=0; i--) { 3195 PackageSetting ps = mSettings.mPackages.get(names[i]); 3196 out[i] = ps != null && ps.realName != null ? ps.realName : names[i]; 3197 } 3198 } 3199 return out; 3200 } 3201 3202 @Override 3203 public String[] canonicalToCurrentPackageNames(String[] names) { 3204 String[] out = new String[names.length]; 3205 // reader 3206 synchronized (mPackages) { 3207 for (int i=names.length-1; i>=0; i--) { 3208 String cur = mSettings.mRenamedPackages.get(names[i]); 3209 out[i] = cur != null ? cur : names[i]; 3210 } 3211 } 3212 return out; 3213 } 3214 3215 @Override 3216 public int getPackageUid(String packageName, int flags, int userId) { 3217 if (!sUserManager.exists(userId)) return -1; 3218 flags = updateFlagsForPackage(flags, userId, packageName); 3219 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3220 false /* requireFullPermission */, false /* checkShell */, "get package uid"); 3221 3222 // reader 3223 synchronized (mPackages) { 3224 final PackageParser.Package p = mPackages.get(packageName); 3225 if (p != null && p.isMatch(flags)) { 3226 return UserHandle.getUid(userId, p.applicationInfo.uid); 3227 } 3228 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3229 final PackageSetting ps = mSettings.mPackages.get(packageName); 3230 if (ps != null && ps.isMatch(flags)) { 3231 return UserHandle.getUid(userId, ps.appId); 3232 } 3233 } 3234 } 3235 3236 return -1; 3237 } 3238 3239 @Override 3240 public int[] getPackageGids(String packageName, int flags, int userId) { 3241 if (!sUserManager.exists(userId)) return null; 3242 flags = updateFlagsForPackage(flags, userId, packageName); 3243 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3244 false /* requireFullPermission */, false /* checkShell */, 3245 "getPackageGids"); 3246 3247 // reader 3248 synchronized (mPackages) { 3249 final PackageParser.Package p = mPackages.get(packageName); 3250 if (p != null && p.isMatch(flags)) { 3251 PackageSetting ps = (PackageSetting) p.mExtras; 3252 return ps.getPermissionsState().computeGids(userId); 3253 } 3254 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3255 final PackageSetting ps = mSettings.mPackages.get(packageName); 3256 if (ps != null && ps.isMatch(flags)) { 3257 return ps.getPermissionsState().computeGids(userId); 3258 } 3259 } 3260 } 3261 3262 return null; 3263 } 3264 3265 static PermissionInfo generatePermissionInfo(BasePermission bp, int flags) { 3266 if (bp.perm != null) { 3267 return PackageParser.generatePermissionInfo(bp.perm, flags); 3268 } 3269 PermissionInfo pi = new PermissionInfo(); 3270 pi.name = bp.name; 3271 pi.packageName = bp.sourcePackage; 3272 pi.nonLocalizedLabel = bp.name; 3273 pi.protectionLevel = bp.protectionLevel; 3274 return pi; 3275 } 3276 3277 @Override 3278 public PermissionInfo getPermissionInfo(String name, int flags) { 3279 // reader 3280 synchronized (mPackages) { 3281 final BasePermission p = mSettings.mPermissions.get(name); 3282 if (p != null) { 3283 return generatePermissionInfo(p, flags); 3284 } 3285 return null; 3286 } 3287 } 3288 3289 @Override 3290 public @Nullable ParceledListSlice<PermissionInfo> queryPermissionsByGroup(String group, 3291 int flags) { 3292 // reader 3293 synchronized (mPackages) { 3294 if (group != null && !mPermissionGroups.containsKey(group)) { 3295 // This is thrown as NameNotFoundException 3296 return null; 3297 } 3298 3299 ArrayList<PermissionInfo> out = new ArrayList<PermissionInfo>(10); 3300 for (BasePermission p : mSettings.mPermissions.values()) { 3301 if (group == null) { 3302 if (p.perm == null || p.perm.info.group == null) { 3303 out.add(generatePermissionInfo(p, flags)); 3304 } 3305 } else { 3306 if (p.perm != null && group.equals(p.perm.info.group)) { 3307 out.add(PackageParser.generatePermissionInfo(p.perm, flags)); 3308 } 3309 } 3310 } 3311 return new ParceledListSlice<>(out); 3312 } 3313 } 3314 3315 @Override 3316 public PermissionGroupInfo getPermissionGroupInfo(String name, int flags) { 3317 // reader 3318 synchronized (mPackages) { 3319 return PackageParser.generatePermissionGroupInfo( 3320 mPermissionGroups.get(name), flags); 3321 } 3322 } 3323 3324 @Override 3325 public @NonNull ParceledListSlice<PermissionGroupInfo> getAllPermissionGroups(int flags) { 3326 // reader 3327 synchronized (mPackages) { 3328 final int N = mPermissionGroups.size(); 3329 ArrayList<PermissionGroupInfo> out 3330 = new ArrayList<PermissionGroupInfo>(N); 3331 for (PackageParser.PermissionGroup pg : mPermissionGroups.values()) { 3332 out.add(PackageParser.generatePermissionGroupInfo(pg, flags)); 3333 } 3334 return new ParceledListSlice<>(out); 3335 } 3336 } 3337 3338 private ApplicationInfo generateApplicationInfoFromSettingsLPw(String packageName, int flags, 3339 int userId) { 3340 if (!sUserManager.exists(userId)) return null; 3341 PackageSetting ps = mSettings.mPackages.get(packageName); 3342 if (ps != null) { 3343 if (ps.pkg == null) { 3344 final PackageInfo pInfo = generatePackageInfo(ps, flags, userId); 3345 if (pInfo != null) { 3346 return pInfo.applicationInfo; 3347 } 3348 return null; 3349 } 3350 return PackageParser.generateApplicationInfo(ps.pkg, flags, 3351 ps.readUserState(userId), userId); 3352 } 3353 return null; 3354 } 3355 3356 @Override 3357 public ApplicationInfo getApplicationInfo(String packageName, int flags, int userId) { 3358 if (!sUserManager.exists(userId)) return null; 3359 flags = updateFlagsForApplication(flags, userId, packageName); 3360 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3361 false /* requireFullPermission */, false /* checkShell */, "get application info"); 3362 // writer 3363 synchronized (mPackages) { 3364 PackageParser.Package p = mPackages.get(packageName); 3365 if (DEBUG_PACKAGE_INFO) Log.v( 3366 TAG, "getApplicationInfo " + packageName 3367 + ": " + p); 3368 if (p != null) { 3369 PackageSetting ps = mSettings.mPackages.get(packageName); 3370 if (ps == null) return null; 3371 // Note: isEnabledLP() does not apply here - always return info 3372 return PackageParser.generateApplicationInfo( 3373 p, flags, ps.readUserState(userId), userId); 3374 } 3375 if ("android".equals(packageName)||"system".equals(packageName)) { 3376 return mAndroidApplication; 3377 } 3378 if ((flags & MATCH_UNINSTALLED_PACKAGES) != 0) { 3379 return generateApplicationInfoFromSettingsLPw(packageName, flags, userId); 3380 } 3381 } 3382 return null; 3383 } 3384 3385 @Override 3386 public void freeStorageAndNotify(final String volumeUuid, final long freeStorageSize, 3387 final IPackageDataObserver observer) { 3388 mContext.enforceCallingOrSelfPermission( 3389 android.Manifest.permission.CLEAR_APP_CACHE, null); 3390 // Queue up an async operation since clearing cache may take a little while. 3391 mHandler.post(new Runnable() { 3392 public void run() { 3393 mHandler.removeCallbacks(this); 3394 boolean success = true; 3395 synchronized (mInstallLock) { 3396 try { 3397 mInstaller.freeCache(volumeUuid, freeStorageSize); 3398 } catch (InstallerException e) { 3399 Slog.w(TAG, "Couldn't clear application caches: " + e); 3400 success = false; 3401 } 3402 } 3403 if (observer != null) { 3404 try { 3405 observer.onRemoveCompleted(null, success); 3406 } catch (RemoteException e) { 3407 Slog.w(TAG, "RemoveException when invoking call back"); 3408 } 3409 } 3410 } 3411 }); 3412 } 3413 3414 @Override 3415 public void freeStorage(final String volumeUuid, final long freeStorageSize, 3416 final IntentSender pi) { 3417 mContext.enforceCallingOrSelfPermission( 3418 android.Manifest.permission.CLEAR_APP_CACHE, null); 3419 // Queue up an async operation since clearing cache may take a little while. 3420 mHandler.post(new Runnable() { 3421 public void run() { 3422 mHandler.removeCallbacks(this); 3423 boolean success = true; 3424 synchronized (mInstallLock) { 3425 try { 3426 mInstaller.freeCache(volumeUuid, freeStorageSize); 3427 } catch (InstallerException e) { 3428 Slog.w(TAG, "Couldn't clear application caches: " + e); 3429 success = false; 3430 } 3431 } 3432 if(pi != null) { 3433 try { 3434 // Callback via pending intent 3435 int code = success ? 1 : 0; 3436 pi.sendIntent(null, code, null, 3437 null, null); 3438 } catch (SendIntentException e1) { 3439 Slog.i(TAG, "Failed to send pending intent"); 3440 } 3441 } 3442 } 3443 }); 3444 } 3445 3446 void freeStorage(String volumeUuid, long freeStorageSize) throws IOException { 3447 synchronized (mInstallLock) { 3448 try { 3449 mInstaller.freeCache(volumeUuid, freeStorageSize); 3450 } catch (InstallerException e) { 3451 throw new IOException("Failed to free enough space", e); 3452 } 3453 } 3454 } 3455 3456 /** 3457 * Return if the user key is currently unlocked. 3458 */ 3459 private boolean isUserKeyUnlocked(int userId) { 3460 if (StorageManager.isFileEncryptedNativeOrEmulated()) { 3461 final IMountService mount = IMountService.Stub 3462 .asInterface(ServiceManager.getService("mount")); 3463 if (mount == null) { 3464 Slog.w(TAG, "Early during boot, assuming locked"); 3465 return false; 3466 } 3467 final long token = Binder.clearCallingIdentity(); 3468 try { 3469 return mount.isUserKeyUnlocked(userId); 3470 } catch (RemoteException e) { 3471 throw e.rethrowAsRuntimeException(); 3472 } finally { 3473 Binder.restoreCallingIdentity(token); 3474 } 3475 } else { 3476 return true; 3477 } 3478 } 3479 3480 /** 3481 * Update given flags based on encryption status of current user. 3482 */ 3483 private int updateFlags(int flags, int userId) { 3484 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3485 | PackageManager.MATCH_DIRECT_BOOT_AWARE)) != 0) { 3486 // Caller expressed an explicit opinion about what encryption 3487 // aware/unaware components they want to see, so fall through and 3488 // give them what they want 3489 } else { 3490 // Caller expressed no opinion, so match based on user state 3491 if (isUserKeyUnlocked(userId)) { 3492 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE; 3493 } else { 3494 flags |= PackageManager.MATCH_DIRECT_BOOT_AWARE; 3495 } 3496 } 3497 return flags; 3498 } 3499 3500 /** 3501 * Update given flags when being used to request {@link PackageInfo}. 3502 */ 3503 private int updateFlagsForPackage(int flags, int userId, Object cookie) { 3504 boolean triaged = true; 3505 if ((flags & (PackageManager.GET_ACTIVITIES | PackageManager.GET_RECEIVERS 3506 | PackageManager.GET_SERVICES | PackageManager.GET_PROVIDERS)) != 0) { 3507 // Caller is asking for component details, so they'd better be 3508 // asking for specific encryption matching behavior, or be triaged 3509 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3510 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3511 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3512 triaged = false; 3513 } 3514 } 3515 if ((flags & (PackageManager.MATCH_UNINSTALLED_PACKAGES 3516 | PackageManager.MATCH_SYSTEM_ONLY 3517 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3518 triaged = false; 3519 } 3520 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3521 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3522 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3523 } 3524 return updateFlags(flags, userId); 3525 } 3526 3527 /** 3528 * Update given flags when being used to request {@link ApplicationInfo}. 3529 */ 3530 private int updateFlagsForApplication(int flags, int userId, Object cookie) { 3531 return updateFlagsForPackage(flags, userId, cookie); 3532 } 3533 3534 /** 3535 * Update given flags when being used to request {@link ComponentInfo}. 3536 */ 3537 private int updateFlagsForComponent(int flags, int userId, Object cookie) { 3538 if (cookie instanceof Intent) { 3539 if ((((Intent) cookie).getFlags() & Intent.FLAG_DEBUG_TRIAGED_MISSING) != 0) { 3540 flags |= PackageManager.MATCH_DEBUG_TRIAGED_MISSING; 3541 } 3542 } 3543 3544 boolean triaged = true; 3545 // Caller is asking for component details, so they'd better be 3546 // asking for specific encryption matching behavior, or be triaged 3547 if ((flags & (PackageManager.MATCH_DIRECT_BOOT_UNAWARE 3548 | PackageManager.MATCH_DIRECT_BOOT_AWARE 3549 | PackageManager.MATCH_DEBUG_TRIAGED_MISSING)) == 0) { 3550 triaged = false; 3551 } 3552 if (DEBUG_TRIAGED_MISSING && (Binder.getCallingUid() == Process.SYSTEM_UID) && !triaged) { 3553 Log.w(TAG, "Caller hasn't been triaged for missing apps; they asked about " + cookie 3554 + " with flags 0x" + Integer.toHexString(flags), new Throwable()); 3555 } 3556 3557 return updateFlags(flags, userId); 3558 } 3559 3560 /** 3561 * Update given flags when being used to request {@link ResolveInfo}. 3562 */ 3563 int updateFlagsForResolve(int flags, int userId, Object cookie) { 3564 // Safe mode means we shouldn't match any third-party components 3565 if (mSafeMode) { 3566 flags |= PackageManager.MATCH_SYSTEM_ONLY; 3567 } 3568 3569 return updateFlagsForComponent(flags, userId, cookie); 3570 } 3571 3572 @Override 3573 public ActivityInfo getActivityInfo(ComponentName component, int flags, int userId) { 3574 if (!sUserManager.exists(userId)) return null; 3575 flags = updateFlagsForComponent(flags, userId, component); 3576 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3577 false /* requireFullPermission */, false /* checkShell */, "get activity info"); 3578 synchronized (mPackages) { 3579 PackageParser.Activity a = mActivities.mActivities.get(component); 3580 3581 if (DEBUG_PACKAGE_INFO) Log.v(TAG, "getActivityInfo " + component + ": " + a); 3582 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3583 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3584 if (ps == null) return null; 3585 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3586 userId); 3587 } 3588 if (mResolveComponentName.equals(component)) { 3589 return PackageParser.generateActivityInfo(mResolveActivity, flags, 3590 new PackageUserState(), userId); 3591 } 3592 } 3593 return null; 3594 } 3595 3596 @Override 3597 public boolean activitySupportsIntent(ComponentName component, Intent intent, 3598 String resolvedType) { 3599 synchronized (mPackages) { 3600 if (component.equals(mResolveComponentName)) { 3601 // The resolver supports EVERYTHING! 3602 return true; 3603 } 3604 PackageParser.Activity a = mActivities.mActivities.get(component); 3605 if (a == null) { 3606 return false; 3607 } 3608 for (int i=0; i<a.intents.size(); i++) { 3609 if (a.intents.get(i).match(intent.getAction(), resolvedType, intent.getScheme(), 3610 intent.getData(), intent.getCategories(), TAG) >= 0) { 3611 return true; 3612 } 3613 } 3614 return false; 3615 } 3616 } 3617 3618 @Override 3619 public ActivityInfo getReceiverInfo(ComponentName component, int flags, int userId) { 3620 if (!sUserManager.exists(userId)) return null; 3621 flags = updateFlagsForComponent(flags, userId, component); 3622 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3623 false /* requireFullPermission */, false /* checkShell */, "get receiver info"); 3624 synchronized (mPackages) { 3625 PackageParser.Activity a = mReceivers.mActivities.get(component); 3626 if (DEBUG_PACKAGE_INFO) Log.v( 3627 TAG, "getReceiverInfo " + component + ": " + a); 3628 if (a != null && mSettings.isEnabledAndMatchLPr(a.info, flags, userId)) { 3629 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3630 if (ps == null) return null; 3631 return PackageParser.generateActivityInfo(a, flags, ps.readUserState(userId), 3632 userId); 3633 } 3634 } 3635 return null; 3636 } 3637 3638 @Override 3639 public ServiceInfo getServiceInfo(ComponentName component, int flags, int userId) { 3640 if (!sUserManager.exists(userId)) return null; 3641 flags = updateFlagsForComponent(flags, userId, component); 3642 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3643 false /* requireFullPermission */, false /* checkShell */, "get service info"); 3644 synchronized (mPackages) { 3645 PackageParser.Service s = mServices.mServices.get(component); 3646 if (DEBUG_PACKAGE_INFO) Log.v( 3647 TAG, "getServiceInfo " + component + ": " + s); 3648 if (s != null && mSettings.isEnabledAndMatchLPr(s.info, flags, userId)) { 3649 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3650 if (ps == null) return null; 3651 return PackageParser.generateServiceInfo(s, flags, ps.readUserState(userId), 3652 userId); 3653 } 3654 } 3655 return null; 3656 } 3657 3658 @Override 3659 public ProviderInfo getProviderInfo(ComponentName component, int flags, int userId) { 3660 if (!sUserManager.exists(userId)) return null; 3661 flags = updateFlagsForComponent(flags, userId, component); 3662 enforceCrossUserPermission(Binder.getCallingUid(), userId, 3663 false /* requireFullPermission */, false /* checkShell */, "get provider info"); 3664 synchronized (mPackages) { 3665 PackageParser.Provider p = mProviders.mProviders.get(component); 3666 if (DEBUG_PACKAGE_INFO) Log.v( 3667 TAG, "getProviderInfo " + component + ": " + p); 3668 if (p != null && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 3669 PackageSetting ps = mSettings.mPackages.get(component.getPackageName()); 3670 if (ps == null) return null; 3671 return PackageParser.generateProviderInfo(p, flags, ps.readUserState(userId), 3672 userId); 3673 } 3674 } 3675 return null; 3676 } 3677 3678 @Override 3679 public String[] getSystemSharedLibraryNames() { 3680 Set<String> libSet; 3681 synchronized (mPackages) { 3682 libSet = mSharedLibraries.keySet(); 3683 int size = libSet.size(); 3684 if (size > 0) { 3685 String[] libs = new String[size]; 3686 libSet.toArray(libs); 3687 return libs; 3688 } 3689 } 3690 return null; 3691 } 3692 3693 @Override 3694 public @NonNull String getServicesSystemSharedLibraryPackageName() { 3695 synchronized (mPackages) { 3696 return mServicesSystemSharedLibraryPackageName; 3697 } 3698 } 3699 3700 @Override 3701 public @NonNull String getSharedSystemSharedLibraryPackageName() { 3702 synchronized (mPackages) { 3703 return mSharedSystemSharedLibraryPackageName; 3704 } 3705 } 3706 3707 @Override 3708 public @NonNull ParceledListSlice<FeatureInfo> getSystemAvailableFeatures() { 3709 synchronized (mPackages) { 3710 final ArrayList<FeatureInfo> res = new ArrayList<>(mAvailableFeatures.values()); 3711 3712 final FeatureInfo fi = new FeatureInfo(); 3713 fi.reqGlEsVersion = SystemProperties.getInt("ro.opengles.version", 3714 FeatureInfo.GL_ES_VERSION_UNDEFINED); 3715 res.add(fi); 3716 3717 return new ParceledListSlice<>(res); 3718 } 3719 } 3720 3721 @Override 3722 public boolean hasSystemFeature(String name, int version) { 3723 synchronized (mPackages) { 3724 final FeatureInfo feat = mAvailableFeatures.get(name); 3725 if (feat == null) { 3726 return false; 3727 } else { 3728 return feat.version >= version; 3729 } 3730 } 3731 } 3732 3733 @Override 3734 public int checkPermission(String permName, String pkgName, int userId) { 3735 if (!sUserManager.exists(userId)) { 3736 return PackageManager.PERMISSION_DENIED; 3737 } 3738 3739 synchronized (mPackages) { 3740 final PackageParser.Package p = mPackages.get(pkgName); 3741 if (p != null && p.mExtras != null) { 3742 final PackageSetting ps = (PackageSetting) p.mExtras; 3743 final PermissionsState permissionsState = ps.getPermissionsState(); 3744 if (permissionsState.hasPermission(permName, userId)) { 3745 return PackageManager.PERMISSION_GRANTED; 3746 } 3747 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3748 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3749 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3750 return PackageManager.PERMISSION_GRANTED; 3751 } 3752 } 3753 } 3754 3755 return PackageManager.PERMISSION_DENIED; 3756 } 3757 3758 @Override 3759 public int checkUidPermission(String permName, int uid) { 3760 final int userId = UserHandle.getUserId(uid); 3761 3762 if (!sUserManager.exists(userId)) { 3763 return PackageManager.PERMISSION_DENIED; 3764 } 3765 3766 synchronized (mPackages) { 3767 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 3768 if (obj != null) { 3769 final SettingBase ps = (SettingBase) obj; 3770 final PermissionsState permissionsState = ps.getPermissionsState(); 3771 if (permissionsState.hasPermission(permName, userId)) { 3772 return PackageManager.PERMISSION_GRANTED; 3773 } 3774 // Special case: ACCESS_FINE_LOCATION permission includes ACCESS_COARSE_LOCATION 3775 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && permissionsState 3776 .hasPermission(Manifest.permission.ACCESS_FINE_LOCATION, userId)) { 3777 return PackageManager.PERMISSION_GRANTED; 3778 } 3779 } else { 3780 ArraySet<String> perms = mSystemPermissions.get(uid); 3781 if (perms != null) { 3782 if (perms.contains(permName)) { 3783 return PackageManager.PERMISSION_GRANTED; 3784 } 3785 if (Manifest.permission.ACCESS_COARSE_LOCATION.equals(permName) && perms 3786 .contains(Manifest.permission.ACCESS_FINE_LOCATION)) { 3787 return PackageManager.PERMISSION_GRANTED; 3788 } 3789 } 3790 } 3791 } 3792 3793 return PackageManager.PERMISSION_DENIED; 3794 } 3795 3796 @Override 3797 public boolean isPermissionRevokedByPolicy(String permission, String packageName, int userId) { 3798 if (UserHandle.getCallingUserId() != userId) { 3799 mContext.enforceCallingPermission( 3800 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 3801 "isPermissionRevokedByPolicy for user " + userId); 3802 } 3803 3804 if (checkPermission(permission, packageName, userId) 3805 == PackageManager.PERMISSION_GRANTED) { 3806 return false; 3807 } 3808 3809 final long identity = Binder.clearCallingIdentity(); 3810 try { 3811 final int flags = getPermissionFlags(permission, packageName, userId); 3812 return (flags & PackageManager.FLAG_PERMISSION_POLICY_FIXED) != 0; 3813 } finally { 3814 Binder.restoreCallingIdentity(identity); 3815 } 3816 } 3817 3818 @Override 3819 public String getPermissionControllerPackageName() { 3820 synchronized (mPackages) { 3821 return mRequiredInstallerPackage; 3822 } 3823 } 3824 3825 /** 3826 * Checks if the request is from the system or an app that has INTERACT_ACROSS_USERS 3827 * or INTERACT_ACROSS_USERS_FULL permissions, if the userid is not for the caller. 3828 * @param checkShell whether to prevent shell from access if there's a debugging restriction 3829 * @param message the message to log on security exception 3830 */ 3831 void enforceCrossUserPermission(int callingUid, int userId, boolean requireFullPermission, 3832 boolean checkShell, String message) { 3833 if (userId < 0) { 3834 throw new IllegalArgumentException("Invalid userId " + userId); 3835 } 3836 if (checkShell) { 3837 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, userId); 3838 } 3839 if (userId == UserHandle.getUserId(callingUid)) return; 3840 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 3841 if (requireFullPermission) { 3842 mContext.enforceCallingOrSelfPermission( 3843 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3844 } else { 3845 try { 3846 mContext.enforceCallingOrSelfPermission( 3847 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, message); 3848 } catch (SecurityException se) { 3849 mContext.enforceCallingOrSelfPermission( 3850 android.Manifest.permission.INTERACT_ACROSS_USERS, message); 3851 } 3852 } 3853 } 3854 } 3855 3856 void enforceShellRestriction(String restriction, int callingUid, int userHandle) { 3857 if (callingUid == Process.SHELL_UID) { 3858 if (userHandle >= 0 3859 && sUserManager.hasUserRestriction(restriction, userHandle)) { 3860 throw new SecurityException("Shell does not have permission to access user " 3861 + userHandle); 3862 } else if (userHandle < 0) { 3863 Slog.e(TAG, "Unable to check shell permission for user " + userHandle + "\n\t" 3864 + Debug.getCallers(3)); 3865 } 3866 } 3867 } 3868 3869 private BasePermission findPermissionTreeLP(String permName) { 3870 for(BasePermission bp : mSettings.mPermissionTrees.values()) { 3871 if (permName.startsWith(bp.name) && 3872 permName.length() > bp.name.length() && 3873 permName.charAt(bp.name.length()) == '.') { 3874 return bp; 3875 } 3876 } 3877 return null; 3878 } 3879 3880 private BasePermission checkPermissionTreeLP(String permName) { 3881 if (permName != null) { 3882 BasePermission bp = findPermissionTreeLP(permName); 3883 if (bp != null) { 3884 if (bp.uid == UserHandle.getAppId(Binder.getCallingUid())) { 3885 return bp; 3886 } 3887 throw new SecurityException("Calling uid " 3888 + Binder.getCallingUid() 3889 + " is not allowed to add to permission tree " 3890 + bp.name + " owned by uid " + bp.uid); 3891 } 3892 } 3893 throw new SecurityException("No permission tree found for " + permName); 3894 } 3895 3896 static boolean compareStrings(CharSequence s1, CharSequence s2) { 3897 if (s1 == null) { 3898 return s2 == null; 3899 } 3900 if (s2 == null) { 3901 return false; 3902 } 3903 if (s1.getClass() != s2.getClass()) { 3904 return false; 3905 } 3906 return s1.equals(s2); 3907 } 3908 3909 static boolean comparePermissionInfos(PermissionInfo pi1, PermissionInfo pi2) { 3910 if (pi1.icon != pi2.icon) return false; 3911 if (pi1.logo != pi2.logo) return false; 3912 if (pi1.protectionLevel != pi2.protectionLevel) return false; 3913 if (!compareStrings(pi1.name, pi2.name)) return false; 3914 if (!compareStrings(pi1.nonLocalizedLabel, pi2.nonLocalizedLabel)) return false; 3915 // We'll take care of setting this one. 3916 if (!compareStrings(pi1.packageName, pi2.packageName)) return false; 3917 // These are not currently stored in settings. 3918 //if (!compareStrings(pi1.group, pi2.group)) return false; 3919 //if (!compareStrings(pi1.nonLocalizedDescription, pi2.nonLocalizedDescription)) return false; 3920 //if (pi1.labelRes != pi2.labelRes) return false; 3921 //if (pi1.descriptionRes != pi2.descriptionRes) return false; 3922 return true; 3923 } 3924 3925 int permissionInfoFootprint(PermissionInfo info) { 3926 int size = info.name.length(); 3927 if (info.nonLocalizedLabel != null) size += info.nonLocalizedLabel.length(); 3928 if (info.nonLocalizedDescription != null) size += info.nonLocalizedDescription.length(); 3929 return size; 3930 } 3931 3932 int calculateCurrentPermissionFootprintLocked(BasePermission tree) { 3933 int size = 0; 3934 for (BasePermission perm : mSettings.mPermissions.values()) { 3935 if (perm.uid == tree.uid) { 3936 size += perm.name.length() + permissionInfoFootprint(perm.perm.info); 3937 } 3938 } 3939 return size; 3940 } 3941 3942 void enforcePermissionCapLocked(PermissionInfo info, BasePermission tree) { 3943 // We calculate the max size of permissions defined by this uid and throw 3944 // if that plus the size of 'info' would exceed our stated maximum. 3945 if (tree.uid != Process.SYSTEM_UID) { 3946 final int curTreeSize = calculateCurrentPermissionFootprintLocked(tree); 3947 if (curTreeSize + permissionInfoFootprint(info) > MAX_PERMISSION_TREE_FOOTPRINT) { 3948 throw new SecurityException("Permission tree size cap exceeded"); 3949 } 3950 } 3951 } 3952 3953 boolean addPermissionLocked(PermissionInfo info, boolean async) { 3954 if (info.labelRes == 0 && info.nonLocalizedLabel == null) { 3955 throw new SecurityException("Label must be specified in permission"); 3956 } 3957 BasePermission tree = checkPermissionTreeLP(info.name); 3958 BasePermission bp = mSettings.mPermissions.get(info.name); 3959 boolean added = bp == null; 3960 boolean changed = true; 3961 int fixedLevel = PermissionInfo.fixProtectionLevel(info.protectionLevel); 3962 if (added) { 3963 enforcePermissionCapLocked(info, tree); 3964 bp = new BasePermission(info.name, tree.sourcePackage, 3965 BasePermission.TYPE_DYNAMIC); 3966 } else if (bp.type != BasePermission.TYPE_DYNAMIC) { 3967 throw new SecurityException( 3968 "Not allowed to modify non-dynamic permission " 3969 + info.name); 3970 } else { 3971 if (bp.protectionLevel == fixedLevel 3972 && bp.perm.owner.equals(tree.perm.owner) 3973 && bp.uid == tree.uid 3974 && comparePermissionInfos(bp.perm.info, info)) { 3975 changed = false; 3976 } 3977 } 3978 bp.protectionLevel = fixedLevel; 3979 info = new PermissionInfo(info); 3980 info.protectionLevel = fixedLevel; 3981 bp.perm = new PackageParser.Permission(tree.perm.owner, info); 3982 bp.perm.info.packageName = tree.perm.info.packageName; 3983 bp.uid = tree.uid; 3984 if (added) { 3985 mSettings.mPermissions.put(info.name, bp); 3986 } 3987 if (changed) { 3988 if (!async) { 3989 mSettings.writeLPr(); 3990 } else { 3991 scheduleWriteSettingsLocked(); 3992 } 3993 } 3994 return added; 3995 } 3996 3997 @Override 3998 public boolean addPermission(PermissionInfo info) { 3999 synchronized (mPackages) { 4000 return addPermissionLocked(info, false); 4001 } 4002 } 4003 4004 @Override 4005 public boolean addPermissionAsync(PermissionInfo info) { 4006 synchronized (mPackages) { 4007 return addPermissionLocked(info, true); 4008 } 4009 } 4010 4011 @Override 4012 public void removePermission(String name) { 4013 synchronized (mPackages) { 4014 checkPermissionTreeLP(name); 4015 BasePermission bp = mSettings.mPermissions.get(name); 4016 if (bp != null) { 4017 if (bp.type != BasePermission.TYPE_DYNAMIC) { 4018 throw new SecurityException( 4019 "Not allowed to modify non-dynamic permission " 4020 + name); 4021 } 4022 mSettings.mPermissions.remove(name); 4023 mSettings.writeLPr(); 4024 } 4025 } 4026 } 4027 4028 private static void enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(PackageParser.Package pkg, 4029 BasePermission bp) { 4030 int index = pkg.requestedPermissions.indexOf(bp.name); 4031 if (index == -1) { 4032 throw new SecurityException("Package " + pkg.packageName 4033 + " has not requested permission " + bp.name); 4034 } 4035 if (!bp.isRuntime() && !bp.isDevelopment()) { 4036 throw new SecurityException("Permission " + bp.name 4037 + " is not a changeable permission type"); 4038 } 4039 } 4040 4041 @Override 4042 public void grantRuntimePermission(String packageName, String name, final int userId) { 4043 if (!sUserManager.exists(userId)) { 4044 Log.e(TAG, "No such user:" + userId); 4045 return; 4046 } 4047 4048 mContext.enforceCallingOrSelfPermission( 4049 android.Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 4050 "grantRuntimePermission"); 4051 4052 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4053 true /* requireFullPermission */, true /* checkShell */, 4054 "grantRuntimePermission"); 4055 4056 final int uid; 4057 final SettingBase sb; 4058 4059 synchronized (mPackages) { 4060 final PackageParser.Package pkg = mPackages.get(packageName); 4061 if (pkg == null) { 4062 throw new IllegalArgumentException("Unknown package: " + packageName); 4063 } 4064 4065 final BasePermission bp = mSettings.mPermissions.get(name); 4066 if (bp == null) { 4067 throw new IllegalArgumentException("Unknown permission: " + name); 4068 } 4069 4070 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4071 4072 // If a permission review is required for legacy apps we represent 4073 // their permissions as always granted runtime ones since we need 4074 // to keep the review required permission flag per user while an 4075 // install permission's state is shared across all users. 4076 if (Build.PERMISSIONS_REVIEW_REQUIRED 4077 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4078 && bp.isRuntime()) { 4079 return; 4080 } 4081 4082 uid = UserHandle.getUid(userId, pkg.applicationInfo.uid); 4083 sb = (SettingBase) pkg.mExtras; 4084 if (sb == null) { 4085 throw new IllegalArgumentException("Unknown package: " + packageName); 4086 } 4087 4088 final PermissionsState permissionsState = sb.getPermissionsState(); 4089 4090 final int flags = permissionsState.getPermissionFlags(name, userId); 4091 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4092 throw new SecurityException("Cannot grant system fixed permission " 4093 + name + " for package " + packageName); 4094 } 4095 4096 if (bp.isDevelopment()) { 4097 // Development permissions must be handled specially, since they are not 4098 // normal runtime permissions. For now they apply to all users. 4099 if (permissionsState.grantInstallPermission(bp) != 4100 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4101 scheduleWriteSettingsLocked(); 4102 } 4103 return; 4104 } 4105 4106 if (pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 4107 Slog.w(TAG, "Cannot grant runtime permission to a legacy app"); 4108 return; 4109 } 4110 4111 final int result = permissionsState.grantRuntimePermission(bp, userId); 4112 switch (result) { 4113 case PermissionsState.PERMISSION_OPERATION_FAILURE: { 4114 return; 4115 } 4116 4117 case PermissionsState.PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 4118 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4119 mHandler.post(new Runnable() { 4120 @Override 4121 public void run() { 4122 killUid(appId, userId, KILL_APP_REASON_GIDS_CHANGED); 4123 } 4124 }); 4125 } 4126 break; 4127 } 4128 4129 mOnPermissionChangeListeners.onPermissionsChanged(uid); 4130 4131 // Not critical if that is lost - app has to request again. 4132 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4133 } 4134 4135 // Only need to do this if user is initialized. Otherwise it's a new user 4136 // and there are no processes running as the user yet and there's no need 4137 // to make an expensive call to remount processes for the changed permissions. 4138 if (READ_EXTERNAL_STORAGE.equals(name) 4139 || WRITE_EXTERNAL_STORAGE.equals(name)) { 4140 final long token = Binder.clearCallingIdentity(); 4141 try { 4142 if (sUserManager.isInitialized(userId)) { 4143 MountServiceInternal mountServiceInternal = LocalServices.getService( 4144 MountServiceInternal.class); 4145 mountServiceInternal.onExternalStoragePolicyChanged(uid, packageName); 4146 } 4147 } finally { 4148 Binder.restoreCallingIdentity(token); 4149 } 4150 } 4151 } 4152 4153 @Override 4154 public void revokeRuntimePermission(String packageName, String name, int userId) { 4155 if (!sUserManager.exists(userId)) { 4156 Log.e(TAG, "No such user:" + userId); 4157 return; 4158 } 4159 4160 mContext.enforceCallingOrSelfPermission( 4161 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4162 "revokeRuntimePermission"); 4163 4164 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4165 true /* requireFullPermission */, true /* checkShell */, 4166 "revokeRuntimePermission"); 4167 4168 final int appId; 4169 4170 synchronized (mPackages) { 4171 final PackageParser.Package pkg = mPackages.get(packageName); 4172 if (pkg == null) { 4173 throw new IllegalArgumentException("Unknown package: " + packageName); 4174 } 4175 4176 final BasePermission bp = mSettings.mPermissions.get(name); 4177 if (bp == null) { 4178 throw new IllegalArgumentException("Unknown permission: " + name); 4179 } 4180 4181 enforceDeclaredAsUsedAndRuntimeOrDevelopmentPermission(pkg, bp); 4182 4183 // If a permission review is required for legacy apps we represent 4184 // their permissions as always granted runtime ones since we need 4185 // to keep the review required permission flag per user while an 4186 // install permission's state is shared across all users. 4187 if (Build.PERMISSIONS_REVIEW_REQUIRED 4188 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M 4189 && bp.isRuntime()) { 4190 return; 4191 } 4192 4193 SettingBase sb = (SettingBase) pkg.mExtras; 4194 if (sb == null) { 4195 throw new IllegalArgumentException("Unknown package: " + packageName); 4196 } 4197 4198 final PermissionsState permissionsState = sb.getPermissionsState(); 4199 4200 final int flags = permissionsState.getPermissionFlags(name, userId); 4201 if ((flags & PackageManager.FLAG_PERMISSION_SYSTEM_FIXED) != 0) { 4202 throw new SecurityException("Cannot revoke system fixed permission " 4203 + name + " for package " + packageName); 4204 } 4205 4206 if (bp.isDevelopment()) { 4207 // Development permissions must be handled specially, since they are not 4208 // normal runtime permissions. For now they apply to all users. 4209 if (permissionsState.revokeInstallPermission(bp) != 4210 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4211 scheduleWriteSettingsLocked(); 4212 } 4213 return; 4214 } 4215 4216 if (permissionsState.revokeRuntimePermission(bp, userId) == 4217 PermissionsState.PERMISSION_OPERATION_FAILURE) { 4218 return; 4219 } 4220 4221 mOnPermissionChangeListeners.onPermissionsChanged(pkg.applicationInfo.uid); 4222 4223 // Critical, after this call app should never have the permission. 4224 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 4225 4226 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 4227 } 4228 4229 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 4230 } 4231 4232 @Override 4233 public void resetRuntimePermissions() { 4234 mContext.enforceCallingOrSelfPermission( 4235 android.Manifest.permission.REVOKE_RUNTIME_PERMISSIONS, 4236 "revokeRuntimePermission"); 4237 4238 int callingUid = Binder.getCallingUid(); 4239 if (callingUid != Process.SYSTEM_UID && callingUid != 0) { 4240 mContext.enforceCallingOrSelfPermission( 4241 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4242 "resetRuntimePermissions"); 4243 } 4244 4245 synchronized (mPackages) { 4246 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL); 4247 for (int userId : UserManagerService.getInstance().getUserIds()) { 4248 final int packageCount = mPackages.size(); 4249 for (int i = 0; i < packageCount; i++) { 4250 PackageParser.Package pkg = mPackages.valueAt(i); 4251 if (!(pkg.mExtras instanceof PackageSetting)) { 4252 continue; 4253 } 4254 PackageSetting ps = (PackageSetting) pkg.mExtras; 4255 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 4256 } 4257 } 4258 } 4259 } 4260 4261 @Override 4262 public int getPermissionFlags(String name, String packageName, int userId) { 4263 if (!sUserManager.exists(userId)) { 4264 return 0; 4265 } 4266 4267 enforceGrantRevokeRuntimePermissionPermissions("getPermissionFlags"); 4268 4269 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4270 true /* requireFullPermission */, false /* checkShell */, 4271 "getPermissionFlags"); 4272 4273 synchronized (mPackages) { 4274 final PackageParser.Package pkg = mPackages.get(packageName); 4275 if (pkg == null) { 4276 throw new IllegalArgumentException("Unknown package: " + packageName); 4277 } 4278 4279 final BasePermission bp = mSettings.mPermissions.get(name); 4280 if (bp == null) { 4281 throw new IllegalArgumentException("Unknown permission: " + name); 4282 } 4283 4284 SettingBase sb = (SettingBase) pkg.mExtras; 4285 if (sb == null) { 4286 throw new IllegalArgumentException("Unknown package: " + packageName); 4287 } 4288 4289 PermissionsState permissionsState = sb.getPermissionsState(); 4290 return permissionsState.getPermissionFlags(name, userId); 4291 } 4292 } 4293 4294 @Override 4295 public void updatePermissionFlags(String name, String packageName, int flagMask, 4296 int flagValues, int userId) { 4297 if (!sUserManager.exists(userId)) { 4298 return; 4299 } 4300 4301 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlags"); 4302 4303 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4304 true /* requireFullPermission */, true /* checkShell */, 4305 "updatePermissionFlags"); 4306 4307 // Only the system can change these flags and nothing else. 4308 if (getCallingUid() != Process.SYSTEM_UID) { 4309 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4310 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4311 flagMask &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4312 flagValues &= ~PackageManager.FLAG_PERMISSION_GRANTED_BY_DEFAULT; 4313 flagValues &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 4314 } 4315 4316 synchronized (mPackages) { 4317 final PackageParser.Package pkg = mPackages.get(packageName); 4318 if (pkg == null) { 4319 throw new IllegalArgumentException("Unknown package: " + packageName); 4320 } 4321 4322 final BasePermission bp = mSettings.mPermissions.get(name); 4323 if (bp == null) { 4324 throw new IllegalArgumentException("Unknown permission: " + name); 4325 } 4326 4327 SettingBase sb = (SettingBase) pkg.mExtras; 4328 if (sb == null) { 4329 throw new IllegalArgumentException("Unknown package: " + packageName); 4330 } 4331 4332 PermissionsState permissionsState = sb.getPermissionsState(); 4333 4334 boolean hadState = permissionsState.getRuntimePermissionState(name, userId) != null; 4335 4336 if (permissionsState.updatePermissionFlags(bp, userId, flagMask, flagValues)) { 4337 // Install and runtime permissions are stored in different places, 4338 // so figure out what permission changed and persist the change. 4339 if (permissionsState.getInstallPermissionState(name) != null) { 4340 scheduleWriteSettingsLocked(); 4341 } else if (permissionsState.getRuntimePermissionState(name, userId) != null 4342 || hadState) { 4343 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4344 } 4345 } 4346 } 4347 } 4348 4349 /** 4350 * Update the permission flags for all packages and runtime permissions of a user in order 4351 * to allow device or profile owner to remove POLICY_FIXED. 4352 */ 4353 @Override 4354 public void updatePermissionFlagsForAllApps(int flagMask, int flagValues, int userId) { 4355 if (!sUserManager.exists(userId)) { 4356 return; 4357 } 4358 4359 enforceGrantRevokeRuntimePermissionPermissions("updatePermissionFlagsForAllApps"); 4360 4361 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4362 true /* requireFullPermission */, true /* checkShell */, 4363 "updatePermissionFlagsForAllApps"); 4364 4365 // Only the system can change system fixed flags. 4366 if (getCallingUid() != Process.SYSTEM_UID) { 4367 flagMask &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4368 flagValues &= ~PackageManager.FLAG_PERMISSION_SYSTEM_FIXED; 4369 } 4370 4371 synchronized (mPackages) { 4372 boolean changed = false; 4373 final int packageCount = mPackages.size(); 4374 for (int pkgIndex = 0; pkgIndex < packageCount; pkgIndex++) { 4375 final PackageParser.Package pkg = mPackages.valueAt(pkgIndex); 4376 SettingBase sb = (SettingBase) pkg.mExtras; 4377 if (sb == null) { 4378 continue; 4379 } 4380 PermissionsState permissionsState = sb.getPermissionsState(); 4381 changed |= permissionsState.updatePermissionFlagsForAllPermissions( 4382 userId, flagMask, flagValues); 4383 } 4384 if (changed) { 4385 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 4386 } 4387 } 4388 } 4389 4390 private void enforceGrantRevokeRuntimePermissionPermissions(String message) { 4391 if (mContext.checkCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS) 4392 != PackageManager.PERMISSION_GRANTED 4393 && mContext.checkCallingOrSelfPermission(Manifest.permission.REVOKE_RUNTIME_PERMISSIONS) 4394 != PackageManager.PERMISSION_GRANTED) { 4395 throw new SecurityException(message + " requires " 4396 + Manifest.permission.GRANT_RUNTIME_PERMISSIONS + " or " 4397 + Manifest.permission.REVOKE_RUNTIME_PERMISSIONS); 4398 } 4399 } 4400 4401 @Override 4402 public boolean shouldShowRequestPermissionRationale(String permissionName, 4403 String packageName, int userId) { 4404 if (UserHandle.getCallingUserId() != userId) { 4405 mContext.enforceCallingPermission( 4406 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 4407 "canShowRequestPermissionRationale for user " + userId); 4408 } 4409 4410 final int uid = getPackageUid(packageName, MATCH_DEBUG_TRIAGED_MISSING, userId); 4411 if (UserHandle.getAppId(getCallingUid()) != UserHandle.getAppId(uid)) { 4412 return false; 4413 } 4414 4415 if (checkPermission(permissionName, packageName, userId) 4416 == PackageManager.PERMISSION_GRANTED) { 4417 return false; 4418 } 4419 4420 final int flags; 4421 4422 final long identity = Binder.clearCallingIdentity(); 4423 try { 4424 flags = getPermissionFlags(permissionName, 4425 packageName, userId); 4426 } finally { 4427 Binder.restoreCallingIdentity(identity); 4428 } 4429 4430 final int fixedFlags = PackageManager.FLAG_PERMISSION_SYSTEM_FIXED 4431 | PackageManager.FLAG_PERMISSION_POLICY_FIXED 4432 | PackageManager.FLAG_PERMISSION_USER_FIXED; 4433 4434 if ((flags & fixedFlags) != 0) { 4435 return false; 4436 } 4437 4438 return (flags & PackageManager.FLAG_PERMISSION_USER_SET) != 0; 4439 } 4440 4441 @Override 4442 public void addOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4443 mContext.enforceCallingOrSelfPermission( 4444 Manifest.permission.OBSERVE_GRANT_REVOKE_PERMISSIONS, 4445 "addOnPermissionsChangeListener"); 4446 4447 synchronized (mPackages) { 4448 mOnPermissionChangeListeners.addListenerLocked(listener); 4449 } 4450 } 4451 4452 @Override 4453 public void removeOnPermissionsChangeListener(IOnPermissionsChangeListener listener) { 4454 synchronized (mPackages) { 4455 mOnPermissionChangeListeners.removeListenerLocked(listener); 4456 } 4457 } 4458 4459 @Override 4460 public boolean isProtectedBroadcast(String actionName) { 4461 synchronized (mPackages) { 4462 if (mProtectedBroadcasts.contains(actionName)) { 4463 return true; 4464 } else if (actionName != null) { 4465 // TODO: remove these terrible hacks 4466 if (actionName.startsWith("android.net.netmon.lingerExpired") 4467 || actionName.startsWith("com.android.server.sip.SipWakeupTimer") 4468 || actionName.startsWith("com.android.internal.telephony.data-reconnect") 4469 || actionName.startsWith("android.net.netmon.launchCaptivePortalApp")) { 4470 return true; 4471 } 4472 } 4473 } 4474 return false; 4475 } 4476 4477 @Override 4478 public int checkSignatures(String pkg1, String pkg2) { 4479 synchronized (mPackages) { 4480 final PackageParser.Package p1 = mPackages.get(pkg1); 4481 final PackageParser.Package p2 = mPackages.get(pkg2); 4482 if (p1 == null || p1.mExtras == null 4483 || p2 == null || p2.mExtras == null) { 4484 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4485 } 4486 return compareSignatures(p1.mSignatures, p2.mSignatures); 4487 } 4488 } 4489 4490 @Override 4491 public int checkUidSignatures(int uid1, int uid2) { 4492 // Map to base uids. 4493 uid1 = UserHandle.getAppId(uid1); 4494 uid2 = UserHandle.getAppId(uid2); 4495 // reader 4496 synchronized (mPackages) { 4497 Signature[] s1; 4498 Signature[] s2; 4499 Object obj = mSettings.getUserIdLPr(uid1); 4500 if (obj != null) { 4501 if (obj instanceof SharedUserSetting) { 4502 s1 = ((SharedUserSetting)obj).signatures.mSignatures; 4503 } else if (obj instanceof PackageSetting) { 4504 s1 = ((PackageSetting)obj).signatures.mSignatures; 4505 } else { 4506 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4507 } 4508 } else { 4509 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4510 } 4511 obj = mSettings.getUserIdLPr(uid2); 4512 if (obj != null) { 4513 if (obj instanceof SharedUserSetting) { 4514 s2 = ((SharedUserSetting)obj).signatures.mSignatures; 4515 } else if (obj instanceof PackageSetting) { 4516 s2 = ((PackageSetting)obj).signatures.mSignatures; 4517 } else { 4518 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4519 } 4520 } else { 4521 return PackageManager.SIGNATURE_UNKNOWN_PACKAGE; 4522 } 4523 return compareSignatures(s1, s2); 4524 } 4525 } 4526 4527 /** 4528 * This method should typically only be used when granting or revoking 4529 * permissions, since the app may immediately restart after this call. 4530 * <p> 4531 * If you're doing surgery on app code/data, use {@link PackageFreezer} to 4532 * guard your work against the app being relaunched. 4533 */ 4534 private void killUid(int appId, int userId, String reason) { 4535 final long identity = Binder.clearCallingIdentity(); 4536 try { 4537 IActivityManager am = ActivityManagerNative.getDefault(); 4538 if (am != null) { 4539 try { 4540 am.killUid(appId, userId, reason); 4541 } catch (RemoteException e) { 4542 /* ignore - same process */ 4543 } 4544 } 4545 } finally { 4546 Binder.restoreCallingIdentity(identity); 4547 } 4548 } 4549 4550 /** 4551 * Compares two sets of signatures. Returns: 4552 * <br /> 4553 * {@link PackageManager#SIGNATURE_NEITHER_SIGNED}: if both signature sets are null, 4554 * <br /> 4555 * {@link PackageManager#SIGNATURE_FIRST_NOT_SIGNED}: if the first signature set is null, 4556 * <br /> 4557 * {@link PackageManager#SIGNATURE_SECOND_NOT_SIGNED}: if the second signature set is null, 4558 * <br /> 4559 * {@link PackageManager#SIGNATURE_MATCH}: if the two signature sets are identical, 4560 * <br /> 4561 * {@link PackageManager#SIGNATURE_NO_MATCH}: if the two signature sets differ. 4562 */ 4563 static int compareSignatures(Signature[] s1, Signature[] s2) { 4564 if (s1 == null) { 4565 return s2 == null 4566 ? PackageManager.SIGNATURE_NEITHER_SIGNED 4567 : PackageManager.SIGNATURE_FIRST_NOT_SIGNED; 4568 } 4569 4570 if (s2 == null) { 4571 return PackageManager.SIGNATURE_SECOND_NOT_SIGNED; 4572 } 4573 4574 if (s1.length != s2.length) { 4575 return PackageManager.SIGNATURE_NO_MATCH; 4576 } 4577 4578 // Since both signature sets are of size 1, we can compare without HashSets. 4579 if (s1.length == 1) { 4580 return s1[0].equals(s2[0]) ? 4581 PackageManager.SIGNATURE_MATCH : 4582 PackageManager.SIGNATURE_NO_MATCH; 4583 } 4584 4585 ArraySet<Signature> set1 = new ArraySet<Signature>(); 4586 for (Signature sig : s1) { 4587 set1.add(sig); 4588 } 4589 ArraySet<Signature> set2 = new ArraySet<Signature>(); 4590 for (Signature sig : s2) { 4591 set2.add(sig); 4592 } 4593 // Make sure s2 contains all signatures in s1. 4594 if (set1.equals(set2)) { 4595 return PackageManager.SIGNATURE_MATCH; 4596 } 4597 return PackageManager.SIGNATURE_NO_MATCH; 4598 } 4599 4600 /** 4601 * If the database version for this type of package (internal storage or 4602 * external storage) is less than the version where package signatures 4603 * were updated, return true. 4604 */ 4605 private boolean isCompatSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4606 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4607 return ver.databaseVersion < DatabaseVersion.SIGNATURE_END_ENTITY; 4608 } 4609 4610 /** 4611 * Used for backward compatibility to make sure any packages with 4612 * certificate chains get upgraded to the new style. {@code existingSigs} 4613 * will be in the old format (since they were stored on disk from before the 4614 * system upgrade) and {@code scannedSigs} will be in the newer format. 4615 */ 4616 private int compareSignaturesCompat(PackageSignatures existingSigs, 4617 PackageParser.Package scannedPkg) { 4618 if (!isCompatSignatureUpdateNeeded(scannedPkg)) { 4619 return PackageManager.SIGNATURE_NO_MATCH; 4620 } 4621 4622 ArraySet<Signature> existingSet = new ArraySet<Signature>(); 4623 for (Signature sig : existingSigs.mSignatures) { 4624 existingSet.add(sig); 4625 } 4626 ArraySet<Signature> scannedCompatSet = new ArraySet<Signature>(); 4627 for (Signature sig : scannedPkg.mSignatures) { 4628 try { 4629 Signature[] chainSignatures = sig.getChainSignatures(); 4630 for (Signature chainSig : chainSignatures) { 4631 scannedCompatSet.add(chainSig); 4632 } 4633 } catch (CertificateEncodingException e) { 4634 scannedCompatSet.add(sig); 4635 } 4636 } 4637 /* 4638 * Make sure the expanded scanned set contains all signatures in the 4639 * existing one. 4640 */ 4641 if (scannedCompatSet.equals(existingSet)) { 4642 // Migrate the old signatures to the new scheme. 4643 existingSigs.assignSignatures(scannedPkg.mSignatures); 4644 // The new KeySets will be re-added later in the scanning process. 4645 synchronized (mPackages) { 4646 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(scannedPkg.packageName); 4647 } 4648 return PackageManager.SIGNATURE_MATCH; 4649 } 4650 return PackageManager.SIGNATURE_NO_MATCH; 4651 } 4652 4653 private boolean isRecoverSignatureUpdateNeeded(PackageParser.Package scannedPkg) { 4654 final VersionInfo ver = getSettingsVersionForPackage(scannedPkg); 4655 return ver.databaseVersion < DatabaseVersion.SIGNATURE_MALFORMED_RECOVER; 4656 } 4657 4658 private int compareSignaturesRecover(PackageSignatures existingSigs, 4659 PackageParser.Package scannedPkg) { 4660 if (!isRecoverSignatureUpdateNeeded(scannedPkg)) { 4661 return PackageManager.SIGNATURE_NO_MATCH; 4662 } 4663 4664 String msg = null; 4665 try { 4666 if (Signature.areEffectiveMatch(existingSigs.mSignatures, scannedPkg.mSignatures)) { 4667 logCriticalInfo(Log.INFO, "Recovered effectively matching certificates for " 4668 + scannedPkg.packageName); 4669 return PackageManager.SIGNATURE_MATCH; 4670 } 4671 } catch (CertificateException e) { 4672 msg = e.getMessage(); 4673 } 4674 4675 logCriticalInfo(Log.INFO, 4676 "Failed to recover certificates for " + scannedPkg.packageName + ": " + msg); 4677 return PackageManager.SIGNATURE_NO_MATCH; 4678 } 4679 4680 @Override 4681 public List<String> getAllPackages() { 4682 synchronized (mPackages) { 4683 return new ArrayList<String>(mPackages.keySet()); 4684 } 4685 } 4686 4687 @Override 4688 public String[] getPackagesForUid(int uid) { 4689 uid = UserHandle.getAppId(uid); 4690 // reader 4691 synchronized (mPackages) { 4692 Object obj = mSettings.getUserIdLPr(uid); 4693 if (obj instanceof SharedUserSetting) { 4694 final SharedUserSetting sus = (SharedUserSetting) obj; 4695 final int N = sus.packages.size(); 4696 final String[] res = new String[N]; 4697 final Iterator<PackageSetting> it = sus.packages.iterator(); 4698 int i = 0; 4699 while (it.hasNext()) { 4700 res[i++] = it.next().name; 4701 } 4702 return res; 4703 } else if (obj instanceof PackageSetting) { 4704 final PackageSetting ps = (PackageSetting) obj; 4705 return new String[] { ps.name }; 4706 } 4707 } 4708 return null; 4709 } 4710 4711 @Override 4712 public String getNameForUid(int uid) { 4713 // reader 4714 synchronized (mPackages) { 4715 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4716 if (obj instanceof SharedUserSetting) { 4717 final SharedUserSetting sus = (SharedUserSetting) obj; 4718 return sus.name + ":" + sus.userId; 4719 } else if (obj instanceof PackageSetting) { 4720 final PackageSetting ps = (PackageSetting) obj; 4721 return ps.name; 4722 } 4723 } 4724 return null; 4725 } 4726 4727 @Override 4728 public int getUidForSharedUser(String sharedUserName) { 4729 if(sharedUserName == null) { 4730 return -1; 4731 } 4732 // reader 4733 synchronized (mPackages) { 4734 final SharedUserSetting suid = mSettings.getSharedUserLPw(sharedUserName, 0, 0, false); 4735 if (suid == null) { 4736 return -1; 4737 } 4738 return suid.userId; 4739 } 4740 } 4741 4742 @Override 4743 public int getFlagsForUid(int uid) { 4744 synchronized (mPackages) { 4745 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4746 if (obj instanceof SharedUserSetting) { 4747 final SharedUserSetting sus = (SharedUserSetting) obj; 4748 return sus.pkgFlags; 4749 } else if (obj instanceof PackageSetting) { 4750 final PackageSetting ps = (PackageSetting) obj; 4751 return ps.pkgFlags; 4752 } 4753 } 4754 return 0; 4755 } 4756 4757 @Override 4758 public int getPrivateFlagsForUid(int uid) { 4759 synchronized (mPackages) { 4760 Object obj = mSettings.getUserIdLPr(UserHandle.getAppId(uid)); 4761 if (obj instanceof SharedUserSetting) { 4762 final SharedUserSetting sus = (SharedUserSetting) obj; 4763 return sus.pkgPrivateFlags; 4764 } else if (obj instanceof PackageSetting) { 4765 final PackageSetting ps = (PackageSetting) obj; 4766 return ps.pkgPrivateFlags; 4767 } 4768 } 4769 return 0; 4770 } 4771 4772 @Override 4773 public boolean isUidPrivileged(int uid) { 4774 uid = UserHandle.getAppId(uid); 4775 // reader 4776 synchronized (mPackages) { 4777 Object obj = mSettings.getUserIdLPr(uid); 4778 if (obj instanceof SharedUserSetting) { 4779 final SharedUserSetting sus = (SharedUserSetting) obj; 4780 final Iterator<PackageSetting> it = sus.packages.iterator(); 4781 while (it.hasNext()) { 4782 if (it.next().isPrivileged()) { 4783 return true; 4784 } 4785 } 4786 } else if (obj instanceof PackageSetting) { 4787 final PackageSetting ps = (PackageSetting) obj; 4788 return ps.isPrivileged(); 4789 } 4790 } 4791 return false; 4792 } 4793 4794 @Override 4795 public String[] getAppOpPermissionPackages(String permissionName) { 4796 synchronized (mPackages) { 4797 ArraySet<String> pkgs = mAppOpPermissionPackages.get(permissionName); 4798 if (pkgs == null) { 4799 return null; 4800 } 4801 return pkgs.toArray(new String[pkgs.size()]); 4802 } 4803 } 4804 4805 @Override 4806 public ResolveInfo resolveIntent(Intent intent, String resolvedType, 4807 int flags, int userId) { 4808 try { 4809 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveIntent"); 4810 4811 if (!sUserManager.exists(userId)) return null; 4812 flags = updateFlagsForResolve(flags, userId, intent); 4813 enforceCrossUserPermission(Binder.getCallingUid(), userId, 4814 false /*requireFullPermission*/, false /*checkShell*/, "resolve intent"); 4815 4816 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 4817 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, 4818 flags, userId); 4819 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4820 4821 final ResolveInfo bestChoice = 4822 chooseBestActivity(intent, resolvedType, flags, query, userId); 4823 4824 if (isEphemeralAllowed(intent, query, userId)) { 4825 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "resolveEphemeral"); 4826 final EphemeralResolveInfo ai = 4827 getEphemeralResolveInfo(intent, resolvedType, userId); 4828 if (ai != null) { 4829 if (DEBUG_EPHEMERAL) { 4830 Slog.v(TAG, "Returning an EphemeralResolveInfo"); 4831 } 4832 bestChoice.ephemeralInstaller = mEphemeralInstallerInfo; 4833 bestChoice.ephemeralResolveInfo = ai; 4834 } 4835 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4836 } 4837 return bestChoice; 4838 } finally { 4839 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 4840 } 4841 } 4842 4843 @Override 4844 public void setLastChosenActivity(Intent intent, String resolvedType, int flags, 4845 IntentFilter filter, int match, ComponentName activity) { 4846 final int userId = UserHandle.getCallingUserId(); 4847 if (DEBUG_PREFERRED) { 4848 Log.v(TAG, "setLastChosenActivity intent=" + intent 4849 + " resolvedType=" + resolvedType 4850 + " flags=" + flags 4851 + " filter=" + filter 4852 + " match=" + match 4853 + " activity=" + activity); 4854 filter.dump(new PrintStreamPrinter(System.out), " "); 4855 } 4856 intent.setComponent(null); 4857 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4858 userId); 4859 // Find any earlier preferred or last chosen entries and nuke them 4860 findPreferredActivity(intent, resolvedType, 4861 flags, query, 0, false, true, false, userId); 4862 // Add the new activity as the last chosen for this filter 4863 addPreferredActivityInternal(filter, match, null, activity, false, userId, 4864 "Setting last chosen"); 4865 } 4866 4867 @Override 4868 public ResolveInfo getLastChosenActivity(Intent intent, String resolvedType, int flags) { 4869 final int userId = UserHandle.getCallingUserId(); 4870 if (DEBUG_PREFERRED) Log.v(TAG, "Querying last chosen activity for " + intent); 4871 final List<ResolveInfo> query = queryIntentActivitiesInternal(intent, resolvedType, flags, 4872 userId); 4873 return findPreferredActivity(intent, resolvedType, flags, query, 0, 4874 false, false, false, userId); 4875 } 4876 4877 4878 private boolean isEphemeralAllowed( 4879 Intent intent, List<ResolveInfo> resolvedActivites, int userId) { 4880 // Short circuit and return early if possible. 4881 if (DISABLE_EPHEMERAL_APPS) { 4882 return false; 4883 } 4884 final int callingUser = UserHandle.getCallingUserId(); 4885 if (callingUser != UserHandle.USER_SYSTEM) { 4886 return false; 4887 } 4888 if (mEphemeralResolverConnection == null) { 4889 return false; 4890 } 4891 if (intent.getComponent() != null) { 4892 return false; 4893 } 4894 if (intent.getPackage() != null) { 4895 return false; 4896 } 4897 final boolean isWebUri = hasWebURI(intent); 4898 if (!isWebUri) { 4899 return false; 4900 } 4901 // Deny ephemeral apps if the user chose _ALWAYS or _ALWAYS_ASK for intent resolution. 4902 synchronized (mPackages) { 4903 final int count = resolvedActivites.size(); 4904 for (int n = 0; n < count; n++) { 4905 ResolveInfo info = resolvedActivites.get(n); 4906 String packageName = info.activityInfo.packageName; 4907 PackageSetting ps = mSettings.mPackages.get(packageName); 4908 if (ps != null) { 4909 // Try to get the status from User settings first 4910 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 4911 int status = (int) (packedStatus >> 32); 4912 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS 4913 || status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 4914 if (DEBUG_EPHEMERAL) { 4915 Slog.v(TAG, "DENY ephemeral apps;" 4916 + " pkg: " + packageName + ", status: " + status); 4917 } 4918 return false; 4919 } 4920 } 4921 } 4922 } 4923 // We've exhausted all ways to deny ephemeral application; let the system look for them. 4924 return true; 4925 } 4926 4927 private EphemeralResolveInfo getEphemeralResolveInfo(Intent intent, String resolvedType, 4928 int userId) { 4929 MessageDigest digest = null; 4930 try { 4931 digest = MessageDigest.getInstance(EphemeralResolveInfo.SHA_ALGORITHM); 4932 } catch (NoSuchAlgorithmException e) { 4933 // If we can't create a digest, ignore ephemeral apps. 4934 return null; 4935 } 4936 4937 final byte[] hostBytes = intent.getData().getHost().getBytes(); 4938 final byte[] digestBytes = digest.digest(hostBytes); 4939 int shaPrefix = 4940 digestBytes[0] << 24 4941 | digestBytes[1] << 16 4942 | digestBytes[2] << 8 4943 | digestBytes[3] << 0; 4944 final List<EphemeralResolveInfo> ephemeralResolveInfoList = 4945 mEphemeralResolverConnection.getEphemeralResolveInfoList(shaPrefix); 4946 if (ephemeralResolveInfoList == null || ephemeralResolveInfoList.size() == 0) { 4947 // No hash prefix match; there are no ephemeral apps for this domain. 4948 return null; 4949 } 4950 for (int i = ephemeralResolveInfoList.size() - 1; i >= 0; --i) { 4951 EphemeralResolveInfo ephemeralApplication = ephemeralResolveInfoList.get(i); 4952 if (!Arrays.equals(digestBytes, ephemeralApplication.getDigestBytes())) { 4953 continue; 4954 } 4955 final List<IntentFilter> filters = ephemeralApplication.getFilters(); 4956 // No filters; this should never happen. 4957 if (filters.isEmpty()) { 4958 continue; 4959 } 4960 // We have a domain match; resolve the filters to see if anything matches. 4961 final EphemeralIntentResolver ephemeralResolver = new EphemeralIntentResolver(); 4962 for (int j = filters.size() - 1; j >= 0; --j) { 4963 final EphemeralResolveIntentInfo intentInfo = 4964 new EphemeralResolveIntentInfo(filters.get(j), ephemeralApplication); 4965 ephemeralResolver.addFilter(intentInfo); 4966 } 4967 List<EphemeralResolveInfo> matchedResolveInfoList = ephemeralResolver.queryIntent( 4968 intent, resolvedType, false /*defaultOnly*/, userId); 4969 if (!matchedResolveInfoList.isEmpty()) { 4970 return matchedResolveInfoList.get(0); 4971 } 4972 } 4973 // Hash or filter mis-match; no ephemeral apps for this domain. 4974 return null; 4975 } 4976 4977 private ResolveInfo chooseBestActivity(Intent intent, String resolvedType, 4978 int flags, List<ResolveInfo> query, int userId) { 4979 if (query != null) { 4980 final int N = query.size(); 4981 if (N == 1) { 4982 return query.get(0); 4983 } else if (N > 1) { 4984 final boolean debug = ((intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0); 4985 // If there is more than one activity with the same priority, 4986 // then let the user decide between them. 4987 ResolveInfo r0 = query.get(0); 4988 ResolveInfo r1 = query.get(1); 4989 if (DEBUG_INTENT_MATCHING || debug) { 4990 Slog.v(TAG, r0.activityInfo.name + "=" + r0.priority + " vs " 4991 + r1.activityInfo.name + "=" + r1.priority); 4992 } 4993 // If the first activity has a higher priority, or a different 4994 // default, then it is always desirable to pick it. 4995 if (r0.priority != r1.priority 4996 || r0.preferredOrder != r1.preferredOrder 4997 || r0.isDefault != r1.isDefault) { 4998 return query.get(0); 4999 } 5000 // If we have saved a preference for a preferred activity for 5001 // this Intent, use that. 5002 ResolveInfo ri = findPreferredActivity(intent, resolvedType, 5003 flags, query, r0.priority, true, false, debug, userId); 5004 if (ri != null) { 5005 return ri; 5006 } 5007 ri = new ResolveInfo(mResolveInfo); 5008 ri.activityInfo = new ActivityInfo(ri.activityInfo); 5009 ri.activityInfo.labelRes = ResolverActivity.getLabelRes(intent.getAction()); 5010 ri.activityInfo.applicationInfo = new ApplicationInfo( 5011 ri.activityInfo.applicationInfo); 5012 if (userId != 0) { 5013 ri.activityInfo.applicationInfo.uid = UserHandle.getUid(userId, 5014 UserHandle.getAppId(ri.activityInfo.applicationInfo.uid)); 5015 } 5016 // Make sure that the resolver is displayable in car mode 5017 if (ri.activityInfo.metaData == null) ri.activityInfo.metaData = new Bundle(); 5018 ri.activityInfo.metaData.putBoolean(Intent.METADATA_DOCK_HOME, true); 5019 return ri; 5020 } 5021 } 5022 return null; 5023 } 5024 5025 private ResolveInfo findPersistentPreferredActivityLP(Intent intent, String resolvedType, 5026 int flags, List<ResolveInfo> query, boolean debug, int userId) { 5027 final int N = query.size(); 5028 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 5029 .get(userId); 5030 // Get the list of persistent preferred activities that handle the intent 5031 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for presistent preferred activities..."); 5032 List<PersistentPreferredActivity> pprefs = ppir != null 5033 ? ppir.queryIntent(intent, resolvedType, 5034 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5035 : null; 5036 if (pprefs != null && pprefs.size() > 0) { 5037 final int M = pprefs.size(); 5038 for (int i=0; i<M; i++) { 5039 final PersistentPreferredActivity ppa = pprefs.get(i); 5040 if (DEBUG_PREFERRED || debug) { 5041 Slog.v(TAG, "Checking PersistentPreferredActivity ds=" 5042 + (ppa.countDataSchemes() > 0 ? ppa.getDataScheme(0) : "<none>") 5043 + "\n component=" + ppa.mComponent); 5044 ppa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5045 } 5046 final ActivityInfo ai = getActivityInfo(ppa.mComponent, 5047 flags | MATCH_DISABLED_COMPONENTS, userId); 5048 if (DEBUG_PREFERRED || debug) { 5049 Slog.v(TAG, "Found persistent preferred activity:"); 5050 if (ai != null) { 5051 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5052 } else { 5053 Slog.v(TAG, " null"); 5054 } 5055 } 5056 if (ai == null) { 5057 // This previously registered persistent preferred activity 5058 // component is no longer known. Ignore it and do NOT remove it. 5059 continue; 5060 } 5061 for (int j=0; j<N; j++) { 5062 final ResolveInfo ri = query.get(j); 5063 if (!ri.activityInfo.applicationInfo.packageName 5064 .equals(ai.applicationInfo.packageName)) { 5065 continue; 5066 } 5067 if (!ri.activityInfo.name.equals(ai.name)) { 5068 continue; 5069 } 5070 // Found a persistent preference that can handle the intent. 5071 if (DEBUG_PREFERRED || debug) { 5072 Slog.v(TAG, "Returning persistent preferred activity: " + 5073 ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5074 } 5075 return ri; 5076 } 5077 } 5078 } 5079 return null; 5080 } 5081 5082 // TODO: handle preferred activities missing while user has amnesia 5083 ResolveInfo findPreferredActivity(Intent intent, String resolvedType, int flags, 5084 List<ResolveInfo> query, int priority, boolean always, 5085 boolean removeMatches, boolean debug, int userId) { 5086 if (!sUserManager.exists(userId)) return null; 5087 flags = updateFlagsForResolve(flags, userId, intent); 5088 // writer 5089 synchronized (mPackages) { 5090 if (intent.getSelector() != null) { 5091 intent = intent.getSelector(); 5092 } 5093 if (DEBUG_PREFERRED) intent.addFlags(Intent.FLAG_DEBUG_LOG_RESOLUTION); 5094 5095 // Try to find a matching persistent preferred activity. 5096 ResolveInfo pri = findPersistentPreferredActivityLP(intent, resolvedType, flags, query, 5097 debug, userId); 5098 5099 // If a persistent preferred activity matched, use it. 5100 if (pri != null) { 5101 return pri; 5102 } 5103 5104 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 5105 // Get the list of preferred activities that handle the intent 5106 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Looking for preferred activities..."); 5107 List<PreferredActivity> prefs = pir != null 5108 ? pir.queryIntent(intent, resolvedType, 5109 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId) 5110 : null; 5111 if (prefs != null && prefs.size() > 0) { 5112 boolean changed = false; 5113 try { 5114 // First figure out how good the original match set is. 5115 // We will only allow preferred activities that came 5116 // from the same match quality. 5117 int match = 0; 5118 5119 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Figuring out best match..."); 5120 5121 final int N = query.size(); 5122 for (int j=0; j<N; j++) { 5123 final ResolveInfo ri = query.get(j); 5124 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Match for " + ri.activityInfo 5125 + ": 0x" + Integer.toHexString(match)); 5126 if (ri.match > match) { 5127 match = ri.match; 5128 } 5129 } 5130 5131 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Best match: 0x" 5132 + Integer.toHexString(match)); 5133 5134 match &= IntentFilter.MATCH_CATEGORY_MASK; 5135 final int M = prefs.size(); 5136 for (int i=0; i<M; i++) { 5137 final PreferredActivity pa = prefs.get(i); 5138 if (DEBUG_PREFERRED || debug) { 5139 Slog.v(TAG, "Checking PreferredActivity ds=" 5140 + (pa.countDataSchemes() > 0 ? pa.getDataScheme(0) : "<none>") 5141 + "\n component=" + pa.mPref.mComponent); 5142 pa.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5143 } 5144 if (pa.mPref.mMatch != match) { 5145 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping bad match " 5146 + Integer.toHexString(pa.mPref.mMatch)); 5147 continue; 5148 } 5149 // If it's not an "always" type preferred activity and that's what we're 5150 // looking for, skip it. 5151 if (always && !pa.mPref.mAlways) { 5152 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Skipping mAlways=false entry"); 5153 continue; 5154 } 5155 final ActivityInfo ai = getActivityInfo( 5156 pa.mPref.mComponent, flags | MATCH_DISABLED_COMPONENTS 5157 | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE, 5158 userId); 5159 if (DEBUG_PREFERRED || debug) { 5160 Slog.v(TAG, "Found preferred activity:"); 5161 if (ai != null) { 5162 ai.dump(new LogPrinter(Log.VERBOSE, TAG, Log.LOG_ID_SYSTEM), " "); 5163 } else { 5164 Slog.v(TAG, " null"); 5165 } 5166 } 5167 if (ai == null) { 5168 // This previously registered preferred activity 5169 // component is no longer known. Most likely an update 5170 // to the app was installed and in the new version this 5171 // component no longer exists. Clean it up by removing 5172 // it from the preferred activities list, and skip it. 5173 Slog.w(TAG, "Removing dangling preferred activity: " 5174 + pa.mPref.mComponent); 5175 pir.removeFilter(pa); 5176 changed = true; 5177 continue; 5178 } 5179 for (int j=0; j<N; j++) { 5180 final ResolveInfo ri = query.get(j); 5181 if (!ri.activityInfo.applicationInfo.packageName 5182 .equals(ai.applicationInfo.packageName)) { 5183 continue; 5184 } 5185 if (!ri.activityInfo.name.equals(ai.name)) { 5186 continue; 5187 } 5188 5189 if (removeMatches) { 5190 pir.removeFilter(pa); 5191 changed = true; 5192 if (DEBUG_PREFERRED) { 5193 Slog.v(TAG, "Removing match " + pa.mPref.mComponent); 5194 } 5195 break; 5196 } 5197 5198 // Okay we found a previously set preferred or last chosen app. 5199 // If the result set is different from when this 5200 // was created, we need to clear it and re-ask the 5201 // user their preference, if we're looking for an "always" type entry. 5202 if (always && !pa.mPref.sameSet(query)) { 5203 Slog.i(TAG, "Result set changed, dropping preferred activity for " 5204 + intent + " type " + resolvedType); 5205 if (DEBUG_PREFERRED) { 5206 Slog.v(TAG, "Removing preferred activity since set changed " 5207 + pa.mPref.mComponent); 5208 } 5209 pir.removeFilter(pa); 5210 // Re-add the filter as a "last chosen" entry (!always) 5211 PreferredActivity lastChosen = new PreferredActivity( 5212 pa, pa.mPref.mMatch, null, pa.mPref.mComponent, false); 5213 pir.addFilter(lastChosen); 5214 changed = true; 5215 return null; 5216 } 5217 5218 // Yay! Either the set matched or we're looking for the last chosen 5219 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "Returning preferred activity: " 5220 + ri.activityInfo.packageName + "/" + ri.activityInfo.name); 5221 return ri; 5222 } 5223 } 5224 } finally { 5225 if (changed) { 5226 if (DEBUG_PREFERRED) { 5227 Slog.v(TAG, "Preferred activity bookkeeping changed; writing restrictions"); 5228 } 5229 scheduleWritePackageRestrictionsLocked(userId); 5230 } 5231 } 5232 } 5233 } 5234 if (DEBUG_PREFERRED || debug) Slog.v(TAG, "No preferred activity to return"); 5235 return null; 5236 } 5237 5238 /* 5239 * Returns if intent can be forwarded from the sourceUserId to the targetUserId 5240 */ 5241 @Override 5242 public boolean canForwardTo(Intent intent, String resolvedType, int sourceUserId, 5243 int targetUserId) { 5244 mContext.enforceCallingOrSelfPermission( 5245 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 5246 List<CrossProfileIntentFilter> matches = 5247 getMatchingCrossProfileIntentFilters(intent, resolvedType, sourceUserId); 5248 if (matches != null) { 5249 int size = matches.size(); 5250 for (int i = 0; i < size; i++) { 5251 if (matches.get(i).getTargetUserId() == targetUserId) return true; 5252 } 5253 } 5254 if (hasWebURI(intent)) { 5255 // cross-profile app linking works only towards the parent. 5256 final UserInfo parent = getProfileParent(sourceUserId); 5257 synchronized(mPackages) { 5258 int flags = updateFlagsForResolve(0, parent.id, intent); 5259 CrossProfileDomainInfo xpDomainInfo = getCrossProfileDomainPreferredLpr( 5260 intent, resolvedType, flags, sourceUserId, parent.id); 5261 return xpDomainInfo != null; 5262 } 5263 } 5264 return false; 5265 } 5266 5267 private UserInfo getProfileParent(int userId) { 5268 final long identity = Binder.clearCallingIdentity(); 5269 try { 5270 return sUserManager.getProfileParent(userId); 5271 } finally { 5272 Binder.restoreCallingIdentity(identity); 5273 } 5274 } 5275 5276 private List<CrossProfileIntentFilter> getMatchingCrossProfileIntentFilters(Intent intent, 5277 String resolvedType, int userId) { 5278 CrossProfileIntentResolver resolver = mSettings.mCrossProfileIntentResolvers.get(userId); 5279 if (resolver != null) { 5280 return resolver.queryIntent(intent, resolvedType, false, userId); 5281 } 5282 return null; 5283 } 5284 5285 @Override 5286 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivities(Intent intent, 5287 String resolvedType, int flags, int userId) { 5288 try { 5289 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "queryIntentActivities"); 5290 5291 return new ParceledListSlice<>( 5292 queryIntentActivitiesInternal(intent, resolvedType, flags, userId)); 5293 } finally { 5294 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 5295 } 5296 } 5297 5298 private @NonNull List<ResolveInfo> queryIntentActivitiesInternal(Intent intent, 5299 String resolvedType, int flags, int userId) { 5300 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5301 flags = updateFlagsForResolve(flags, userId, intent); 5302 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5303 false /* requireFullPermission */, false /* checkShell */, 5304 "query intent activities"); 5305 ComponentName comp = intent.getComponent(); 5306 if (comp == null) { 5307 if (intent.getSelector() != null) { 5308 intent = intent.getSelector(); 5309 comp = intent.getComponent(); 5310 } 5311 } 5312 5313 if (comp != null) { 5314 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5315 final ActivityInfo ai = getActivityInfo(comp, flags, userId); 5316 if (ai != null) { 5317 final ResolveInfo ri = new ResolveInfo(); 5318 ri.activityInfo = ai; 5319 list.add(ri); 5320 } 5321 return list; 5322 } 5323 5324 // reader 5325 synchronized (mPackages) { 5326 final String pkgName = intent.getPackage(); 5327 if (pkgName == null) { 5328 List<CrossProfileIntentFilter> matchingFilters = 5329 getMatchingCrossProfileIntentFilters(intent, resolvedType, userId); 5330 // Check for results that need to skip the current profile. 5331 ResolveInfo xpResolveInfo = querySkipCurrentProfileIntents(matchingFilters, intent, 5332 resolvedType, flags, userId); 5333 if (xpResolveInfo != null) { 5334 List<ResolveInfo> result = new ArrayList<ResolveInfo>(1); 5335 result.add(xpResolveInfo); 5336 return filterIfNotSystemUser(result, userId); 5337 } 5338 5339 // Check for results in the current profile. 5340 List<ResolveInfo> result = mActivities.queryIntent( 5341 intent, resolvedType, flags, userId); 5342 result = filterIfNotSystemUser(result, userId); 5343 5344 // Check for cross profile results. 5345 boolean hasNonNegativePriorityResult = hasNonNegativePriority(result); 5346 xpResolveInfo = queryCrossProfileIntents( 5347 matchingFilters, intent, resolvedType, flags, userId, 5348 hasNonNegativePriorityResult); 5349 if (xpResolveInfo != null && isUserEnabled(xpResolveInfo.targetUserId)) { 5350 boolean isVisibleToUser = filterIfNotSystemUser( 5351 Collections.singletonList(xpResolveInfo), userId).size() > 0; 5352 if (isVisibleToUser) { 5353 result.add(xpResolveInfo); 5354 Collections.sort(result, mResolvePrioritySorter); 5355 } 5356 } 5357 if (hasWebURI(intent)) { 5358 CrossProfileDomainInfo xpDomainInfo = null; 5359 final UserInfo parent = getProfileParent(userId); 5360 if (parent != null) { 5361 xpDomainInfo = getCrossProfileDomainPreferredLpr(intent, resolvedType, 5362 flags, userId, parent.id); 5363 } 5364 if (xpDomainInfo != null) { 5365 if (xpResolveInfo != null) { 5366 // If we didn't remove it, the cross-profile ResolveInfo would be twice 5367 // in the result. 5368 result.remove(xpResolveInfo); 5369 } 5370 if (result.size() == 0) { 5371 result.add(xpDomainInfo.resolveInfo); 5372 return result; 5373 } 5374 } else if (result.size() <= 1) { 5375 return result; 5376 } 5377 result = filterCandidatesWithDomainPreferredActivitiesLPr(intent, flags, result, 5378 xpDomainInfo, userId); 5379 Collections.sort(result, mResolvePrioritySorter); 5380 } 5381 return result; 5382 } 5383 final PackageParser.Package pkg = mPackages.get(pkgName); 5384 if (pkg != null) { 5385 return filterIfNotSystemUser( 5386 mActivities.queryIntentForPackage( 5387 intent, resolvedType, flags, pkg.activities, userId), 5388 userId); 5389 } 5390 return new ArrayList<ResolveInfo>(); 5391 } 5392 } 5393 5394 private static class CrossProfileDomainInfo { 5395 /* ResolveInfo for IntentForwarderActivity to send the intent to the other profile */ 5396 ResolveInfo resolveInfo; 5397 /* Best domain verification status of the activities found in the other profile */ 5398 int bestDomainVerificationStatus; 5399 } 5400 5401 private CrossProfileDomainInfo getCrossProfileDomainPreferredLpr(Intent intent, 5402 String resolvedType, int flags, int sourceUserId, int parentUserId) { 5403 if (!sUserManager.hasUserRestriction(UserManager.ALLOW_PARENT_PROFILE_APP_LINKING, 5404 sourceUserId)) { 5405 return null; 5406 } 5407 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5408 resolvedType, flags, parentUserId); 5409 5410 if (resultTargetUser == null || resultTargetUser.isEmpty()) { 5411 return null; 5412 } 5413 CrossProfileDomainInfo result = null; 5414 int size = resultTargetUser.size(); 5415 for (int i = 0; i < size; i++) { 5416 ResolveInfo riTargetUser = resultTargetUser.get(i); 5417 // Intent filter verification is only for filters that specify a host. So don't return 5418 // those that handle all web uris. 5419 if (riTargetUser.handleAllWebDataURI) { 5420 continue; 5421 } 5422 String packageName = riTargetUser.activityInfo.packageName; 5423 PackageSetting ps = mSettings.mPackages.get(packageName); 5424 if (ps == null) { 5425 continue; 5426 } 5427 long verificationState = getDomainVerificationStatusLPr(ps, parentUserId); 5428 int status = (int)(verificationState >> 32); 5429 if (result == null) { 5430 result = new CrossProfileDomainInfo(); 5431 result.resolveInfo = createForwardingResolveInfoUnchecked(new IntentFilter(), 5432 sourceUserId, parentUserId); 5433 result.bestDomainVerificationStatus = status; 5434 } else { 5435 result.bestDomainVerificationStatus = bestDomainVerificationStatus(status, 5436 result.bestDomainVerificationStatus); 5437 } 5438 } 5439 // Don't consider matches with status NEVER across profiles. 5440 if (result != null && result.bestDomainVerificationStatus 5441 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5442 return null; 5443 } 5444 return result; 5445 } 5446 5447 /** 5448 * Verification statuses are ordered from the worse to the best, except for 5449 * INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER, which is the worse. 5450 */ 5451 private int bestDomainVerificationStatus(int status1, int status2) { 5452 if (status1 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5453 return status2; 5454 } 5455 if (status2 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5456 return status1; 5457 } 5458 return (int) MathUtils.max(status1, status2); 5459 } 5460 5461 private boolean isUserEnabled(int userId) { 5462 long callingId = Binder.clearCallingIdentity(); 5463 try { 5464 UserInfo userInfo = sUserManager.getUserInfo(userId); 5465 return userInfo != null && userInfo.isEnabled(); 5466 } finally { 5467 Binder.restoreCallingIdentity(callingId); 5468 } 5469 } 5470 5471 /** 5472 * Filter out activities with systemUserOnly flag set, when current user is not System. 5473 * 5474 * @return filtered list 5475 */ 5476 private List<ResolveInfo> filterIfNotSystemUser(List<ResolveInfo> resolveInfos, int userId) { 5477 if (userId == UserHandle.USER_SYSTEM) { 5478 return resolveInfos; 5479 } 5480 for (int i = resolveInfos.size() - 1; i >= 0; i--) { 5481 ResolveInfo info = resolveInfos.get(i); 5482 if ((info.activityInfo.flags & ActivityInfo.FLAG_SYSTEM_USER_ONLY) != 0) { 5483 resolveInfos.remove(i); 5484 } 5485 } 5486 return resolveInfos; 5487 } 5488 5489 /** 5490 * @param resolveInfos list of resolve infos in descending priority order 5491 * @return if the list contains a resolve info with non-negative priority 5492 */ 5493 private boolean hasNonNegativePriority(List<ResolveInfo> resolveInfos) { 5494 return resolveInfos.size() > 0 && resolveInfos.get(0).priority >= 0; 5495 } 5496 5497 private static boolean hasWebURI(Intent intent) { 5498 if (intent.getData() == null) { 5499 return false; 5500 } 5501 final String scheme = intent.getScheme(); 5502 if (TextUtils.isEmpty(scheme)) { 5503 return false; 5504 } 5505 return scheme.equals(IntentFilter.SCHEME_HTTP) || scheme.equals(IntentFilter.SCHEME_HTTPS); 5506 } 5507 5508 private List<ResolveInfo> filterCandidatesWithDomainPreferredActivitiesLPr(Intent intent, 5509 int matchFlags, List<ResolveInfo> candidates, CrossProfileDomainInfo xpDomainInfo, 5510 int userId) { 5511 final boolean debug = (intent.getFlags() & Intent.FLAG_DEBUG_LOG_RESOLUTION) != 0; 5512 5513 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5514 Slog.v(TAG, "Filtering results with preferred activities. Candidates count: " + 5515 candidates.size()); 5516 } 5517 5518 ArrayList<ResolveInfo> result = new ArrayList<ResolveInfo>(); 5519 ArrayList<ResolveInfo> alwaysList = new ArrayList<ResolveInfo>(); 5520 ArrayList<ResolveInfo> undefinedList = new ArrayList<ResolveInfo>(); 5521 ArrayList<ResolveInfo> alwaysAskList = new ArrayList<ResolveInfo>(); 5522 ArrayList<ResolveInfo> neverList = new ArrayList<ResolveInfo>(); 5523 ArrayList<ResolveInfo> matchAllList = new ArrayList<ResolveInfo>(); 5524 5525 synchronized (mPackages) { 5526 final int count = candidates.size(); 5527 // First, try to use linked apps. Partition the candidates into four lists: 5528 // one for the final results, one for the "do not use ever", one for "undefined status" 5529 // and finally one for "browser app type". 5530 for (int n=0; n<count; n++) { 5531 ResolveInfo info = candidates.get(n); 5532 String packageName = info.activityInfo.packageName; 5533 PackageSetting ps = mSettings.mPackages.get(packageName); 5534 if (ps != null) { 5535 // Add to the special match all list (Browser use case) 5536 if (info.handleAllWebDataURI) { 5537 matchAllList.add(info); 5538 continue; 5539 } 5540 // Try to get the status from User settings first 5541 long packedStatus = getDomainVerificationStatusLPr(ps, userId); 5542 int status = (int)(packedStatus >> 32); 5543 int linkGeneration = (int)(packedStatus & 0xFFFFFFFF); 5544 if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS) { 5545 if (DEBUG_DOMAIN_VERIFICATION) { 5546 Slog.i(TAG, " + always: " + info.activityInfo.packageName 5547 + " : linkgen=" + linkGeneration); 5548 } 5549 // Use link-enabled generation as preferredOrder, i.e. 5550 // prefer newly-enabled over earlier-enabled. 5551 info.preferredOrder = linkGeneration; 5552 alwaysList.add(info); 5553 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER) { 5554 if (DEBUG_DOMAIN_VERIFICATION) { 5555 Slog.i(TAG, " + never: " + info.activityInfo.packageName); 5556 } 5557 neverList.add(info); 5558 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS_ASK) { 5559 if (DEBUG_DOMAIN_VERIFICATION) { 5560 Slog.i(TAG, " + always-ask: " + info.activityInfo.packageName); 5561 } 5562 alwaysAskList.add(info); 5563 } else if (status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED || 5564 status == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK) { 5565 if (DEBUG_DOMAIN_VERIFICATION) { 5566 Slog.i(TAG, " + ask: " + info.activityInfo.packageName); 5567 } 5568 undefinedList.add(info); 5569 } 5570 } 5571 } 5572 5573 // We'll want to include browser possibilities in a few cases 5574 boolean includeBrowser = false; 5575 5576 // First try to add the "always" resolution(s) for the current user, if any 5577 if (alwaysList.size() > 0) { 5578 result.addAll(alwaysList); 5579 } else { 5580 // Add all undefined apps as we want them to appear in the disambiguation dialog. 5581 result.addAll(undefinedList); 5582 // Maybe add one for the other profile. 5583 if (xpDomainInfo != null && ( 5584 xpDomainInfo.bestDomainVerificationStatus 5585 != INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER)) { 5586 result.add(xpDomainInfo.resolveInfo); 5587 } 5588 includeBrowser = true; 5589 } 5590 5591 // The presence of any 'always ask' alternatives means we'll also offer browsers. 5592 // If there were 'always' entries their preferred order has been set, so we also 5593 // back that off to make the alternatives equivalent 5594 if (alwaysAskList.size() > 0) { 5595 for (ResolveInfo i : result) { 5596 i.preferredOrder = 0; 5597 } 5598 result.addAll(alwaysAskList); 5599 includeBrowser = true; 5600 } 5601 5602 if (includeBrowser) { 5603 // Also add browsers (all of them or only the default one) 5604 if (DEBUG_DOMAIN_VERIFICATION) { 5605 Slog.v(TAG, " ...including browsers in candidate set"); 5606 } 5607 if ((matchFlags & MATCH_ALL) != 0) { 5608 result.addAll(matchAllList); 5609 } else { 5610 // Browser/generic handling case. If there's a default browser, go straight 5611 // to that (but only if there is no other higher-priority match). 5612 final String defaultBrowserPackageName = getDefaultBrowserPackageName(userId); 5613 int maxMatchPrio = 0; 5614 ResolveInfo defaultBrowserMatch = null; 5615 final int numCandidates = matchAllList.size(); 5616 for (int n = 0; n < numCandidates; n++) { 5617 ResolveInfo info = matchAllList.get(n); 5618 // track the highest overall match priority... 5619 if (info.priority > maxMatchPrio) { 5620 maxMatchPrio = info.priority; 5621 } 5622 // ...and the highest-priority default browser match 5623 if (info.activityInfo.packageName.equals(defaultBrowserPackageName)) { 5624 if (defaultBrowserMatch == null 5625 || (defaultBrowserMatch.priority < info.priority)) { 5626 if (debug) { 5627 Slog.v(TAG, "Considering default browser match " + info); 5628 } 5629 defaultBrowserMatch = info; 5630 } 5631 } 5632 } 5633 if (defaultBrowserMatch != null 5634 && defaultBrowserMatch.priority >= maxMatchPrio 5635 && !TextUtils.isEmpty(defaultBrowserPackageName)) 5636 { 5637 if (debug) { 5638 Slog.v(TAG, "Default browser match " + defaultBrowserMatch); 5639 } 5640 result.add(defaultBrowserMatch); 5641 } else { 5642 result.addAll(matchAllList); 5643 } 5644 } 5645 5646 // If there is nothing selected, add all candidates and remove the ones that the user 5647 // has explicitly put into the INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_NEVER state 5648 if (result.size() == 0) { 5649 result.addAll(candidates); 5650 result.removeAll(neverList); 5651 } 5652 } 5653 } 5654 if (DEBUG_PREFERRED || DEBUG_DOMAIN_VERIFICATION) { 5655 Slog.v(TAG, "Filtered results with preferred activities. New candidates count: " + 5656 result.size()); 5657 for (ResolveInfo info : result) { 5658 Slog.v(TAG, " + " + info.activityInfo); 5659 } 5660 } 5661 return result; 5662 } 5663 5664 // Returns a packed value as a long: 5665 // 5666 // high 'int'-sized word: link status: undefined/ask/never/always. 5667 // low 'int'-sized word: relative priority among 'always' results. 5668 private long getDomainVerificationStatusLPr(PackageSetting ps, int userId) { 5669 long result = ps.getDomainVerificationStatusForUser(userId); 5670 // if none available, get the master status 5671 if (result >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 5672 if (ps.getIntentFilterVerificationInfo() != null) { 5673 result = ((long)ps.getIntentFilterVerificationInfo().getStatus()) << 32; 5674 } 5675 } 5676 return result; 5677 } 5678 5679 private ResolveInfo querySkipCurrentProfileIntents( 5680 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5681 int flags, int sourceUserId) { 5682 if (matchingFilters != null) { 5683 int size = matchingFilters.size(); 5684 for (int i = 0; i < size; i ++) { 5685 CrossProfileIntentFilter filter = matchingFilters.get(i); 5686 if ((filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0) { 5687 // Checking if there are activities in the target user that can handle the 5688 // intent. 5689 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5690 resolvedType, flags, sourceUserId); 5691 if (resolveInfo != null) { 5692 return resolveInfo; 5693 } 5694 } 5695 } 5696 } 5697 return null; 5698 } 5699 5700 // Return matching ResolveInfo in target user if any. 5701 private ResolveInfo queryCrossProfileIntents( 5702 List<CrossProfileIntentFilter> matchingFilters, Intent intent, String resolvedType, 5703 int flags, int sourceUserId, boolean matchInCurrentProfile) { 5704 if (matchingFilters != null) { 5705 // Two {@link CrossProfileIntentFilter}s can have the same targetUserId and 5706 // match the same intent. For performance reasons, it is better not to 5707 // run queryIntent twice for the same userId 5708 SparseBooleanArray alreadyTriedUserIds = new SparseBooleanArray(); 5709 int size = matchingFilters.size(); 5710 for (int i = 0; i < size; i++) { 5711 CrossProfileIntentFilter filter = matchingFilters.get(i); 5712 int targetUserId = filter.getTargetUserId(); 5713 boolean skipCurrentProfile = 5714 (filter.getFlags() & PackageManager.SKIP_CURRENT_PROFILE) != 0; 5715 boolean skipCurrentProfileIfNoMatchFound = 5716 (filter.getFlags() & PackageManager.ONLY_IF_NO_MATCH_FOUND) != 0; 5717 if (!skipCurrentProfile && !alreadyTriedUserIds.get(targetUserId) 5718 && (!skipCurrentProfileIfNoMatchFound || !matchInCurrentProfile)) { 5719 // Checking if there are activities in the target user that can handle the 5720 // intent. 5721 ResolveInfo resolveInfo = createForwardingResolveInfo(filter, intent, 5722 resolvedType, flags, sourceUserId); 5723 if (resolveInfo != null) return resolveInfo; 5724 alreadyTriedUserIds.put(targetUserId, true); 5725 } 5726 } 5727 } 5728 return null; 5729 } 5730 5731 /** 5732 * If the filter's target user can handle the intent and is enabled: returns a ResolveInfo that 5733 * will forward the intent to the filter's target user. 5734 * Otherwise, returns null. 5735 */ 5736 private ResolveInfo createForwardingResolveInfo(CrossProfileIntentFilter filter, Intent intent, 5737 String resolvedType, int flags, int sourceUserId) { 5738 int targetUserId = filter.getTargetUserId(); 5739 List<ResolveInfo> resultTargetUser = mActivities.queryIntent(intent, 5740 resolvedType, flags, targetUserId); 5741 if (resultTargetUser != null && isUserEnabled(targetUserId)) { 5742 // If all the matches in the target profile are suspended, return null. 5743 for (int i = resultTargetUser.size() - 1; i >= 0; i--) { 5744 if ((resultTargetUser.get(i).activityInfo.applicationInfo.flags 5745 & ApplicationInfo.FLAG_SUSPENDED) == 0) { 5746 return createForwardingResolveInfoUnchecked(filter, sourceUserId, 5747 targetUserId); 5748 } 5749 } 5750 } 5751 return null; 5752 } 5753 5754 private ResolveInfo createForwardingResolveInfoUnchecked(IntentFilter filter, 5755 int sourceUserId, int targetUserId) { 5756 ResolveInfo forwardingResolveInfo = new ResolveInfo(); 5757 long ident = Binder.clearCallingIdentity(); 5758 boolean targetIsProfile; 5759 try { 5760 targetIsProfile = sUserManager.getUserInfo(targetUserId).isManagedProfile(); 5761 } finally { 5762 Binder.restoreCallingIdentity(ident); 5763 } 5764 String className; 5765 if (targetIsProfile) { 5766 className = FORWARD_INTENT_TO_MANAGED_PROFILE; 5767 } else { 5768 className = FORWARD_INTENT_TO_PARENT; 5769 } 5770 ComponentName forwardingActivityComponentName = new ComponentName( 5771 mAndroidApplication.packageName, className); 5772 ActivityInfo forwardingActivityInfo = getActivityInfo(forwardingActivityComponentName, 0, 5773 sourceUserId); 5774 if (!targetIsProfile) { 5775 forwardingActivityInfo.showUserIcon = targetUserId; 5776 forwardingResolveInfo.noResourceId = true; 5777 } 5778 forwardingResolveInfo.activityInfo = forwardingActivityInfo; 5779 forwardingResolveInfo.priority = 0; 5780 forwardingResolveInfo.preferredOrder = 0; 5781 forwardingResolveInfo.match = 0; 5782 forwardingResolveInfo.isDefault = true; 5783 forwardingResolveInfo.filter = filter; 5784 forwardingResolveInfo.targetUserId = targetUserId; 5785 return forwardingResolveInfo; 5786 } 5787 5788 @Override 5789 public @NonNull ParceledListSlice<ResolveInfo> queryIntentActivityOptions(ComponentName caller, 5790 Intent[] specifics, String[] specificTypes, Intent intent, 5791 String resolvedType, int flags, int userId) { 5792 return new ParceledListSlice<>(queryIntentActivityOptionsInternal(caller, specifics, 5793 specificTypes, intent, resolvedType, flags, userId)); 5794 } 5795 5796 private @NonNull List<ResolveInfo> queryIntentActivityOptionsInternal(ComponentName caller, 5797 Intent[] specifics, String[] specificTypes, Intent intent, 5798 String resolvedType, int flags, int userId) { 5799 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5800 flags = updateFlagsForResolve(flags, userId, intent); 5801 enforceCrossUserPermission(Binder.getCallingUid(), userId, 5802 false /* requireFullPermission */, false /* checkShell */, 5803 "query intent activity options"); 5804 final String resultsAction = intent.getAction(); 5805 5806 final List<ResolveInfo> results = queryIntentActivitiesInternal(intent, resolvedType, flags 5807 | PackageManager.GET_RESOLVED_FILTER, userId); 5808 5809 if (DEBUG_INTENT_MATCHING) { 5810 Log.v(TAG, "Query " + intent + ": " + results); 5811 } 5812 5813 int specificsPos = 0; 5814 int N; 5815 5816 // todo: note that the algorithm used here is O(N^2). This 5817 // isn't a problem in our current environment, but if we start running 5818 // into situations where we have more than 5 or 10 matches then this 5819 // should probably be changed to something smarter... 5820 5821 // First we go through and resolve each of the specific items 5822 // that were supplied, taking care of removing any corresponding 5823 // duplicate items in the generic resolve list. 5824 if (specifics != null) { 5825 for (int i=0; i<specifics.length; i++) { 5826 final Intent sintent = specifics[i]; 5827 if (sintent == null) { 5828 continue; 5829 } 5830 5831 if (DEBUG_INTENT_MATCHING) { 5832 Log.v(TAG, "Specific #" + i + ": " + sintent); 5833 } 5834 5835 String action = sintent.getAction(); 5836 if (resultsAction != null && resultsAction.equals(action)) { 5837 // If this action was explicitly requested, then don't 5838 // remove things that have it. 5839 action = null; 5840 } 5841 5842 ResolveInfo ri = null; 5843 ActivityInfo ai = null; 5844 5845 ComponentName comp = sintent.getComponent(); 5846 if (comp == null) { 5847 ri = resolveIntent( 5848 sintent, 5849 specificTypes != null ? specificTypes[i] : null, 5850 flags, userId); 5851 if (ri == null) { 5852 continue; 5853 } 5854 if (ri == mResolveInfo) { 5855 // ACK! Must do something better with this. 5856 } 5857 ai = ri.activityInfo; 5858 comp = new ComponentName(ai.applicationInfo.packageName, 5859 ai.name); 5860 } else { 5861 ai = getActivityInfo(comp, flags, userId); 5862 if (ai == null) { 5863 continue; 5864 } 5865 } 5866 5867 // Look for any generic query activities that are duplicates 5868 // of this specific one, and remove them from the results. 5869 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Specific #" + i + ": " + ai); 5870 N = results.size(); 5871 int j; 5872 for (j=specificsPos; j<N; j++) { 5873 ResolveInfo sri = results.get(j); 5874 if ((sri.activityInfo.name.equals(comp.getClassName()) 5875 && sri.activityInfo.applicationInfo.packageName.equals( 5876 comp.getPackageName())) 5877 || (action != null && sri.filter.matchAction(action))) { 5878 results.remove(j); 5879 if (DEBUG_INTENT_MATCHING) Log.v( 5880 TAG, "Removing duplicate item from " + j 5881 + " due to specific " + specificsPos); 5882 if (ri == null) { 5883 ri = sri; 5884 } 5885 j--; 5886 N--; 5887 } 5888 } 5889 5890 // Add this specific item to its proper place. 5891 if (ri == null) { 5892 ri = new ResolveInfo(); 5893 ri.activityInfo = ai; 5894 } 5895 results.add(specificsPos, ri); 5896 ri.specificIndex = i; 5897 specificsPos++; 5898 } 5899 } 5900 5901 // Now we go through the remaining generic results and remove any 5902 // duplicate actions that are found here. 5903 N = results.size(); 5904 for (int i=specificsPos; i<N-1; i++) { 5905 final ResolveInfo rii = results.get(i); 5906 if (rii.filter == null) { 5907 continue; 5908 } 5909 5910 // Iterate over all of the actions of this result's intent 5911 // filter... typically this should be just one. 5912 final Iterator<String> it = rii.filter.actionsIterator(); 5913 if (it == null) { 5914 continue; 5915 } 5916 while (it.hasNext()) { 5917 final String action = it.next(); 5918 if (resultsAction != null && resultsAction.equals(action)) { 5919 // If this action was explicitly requested, then don't 5920 // remove things that have it. 5921 continue; 5922 } 5923 for (int j=i+1; j<N; j++) { 5924 final ResolveInfo rij = results.get(j); 5925 if (rij.filter != null && rij.filter.hasAction(action)) { 5926 results.remove(j); 5927 if (DEBUG_INTENT_MATCHING) Log.v( 5928 TAG, "Removing duplicate item from " + j 5929 + " due to action " + action + " at " + i); 5930 j--; 5931 N--; 5932 } 5933 } 5934 } 5935 5936 // If the caller didn't request filter information, drop it now 5937 // so we don't have to marshall/unmarshall it. 5938 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5939 rii.filter = null; 5940 } 5941 } 5942 5943 // Filter out the caller activity if so requested. 5944 if (caller != null) { 5945 N = results.size(); 5946 for (int i=0; i<N; i++) { 5947 ActivityInfo ainfo = results.get(i).activityInfo; 5948 if (caller.getPackageName().equals(ainfo.applicationInfo.packageName) 5949 && caller.getClassName().equals(ainfo.name)) { 5950 results.remove(i); 5951 break; 5952 } 5953 } 5954 } 5955 5956 // If the caller didn't request filter information, 5957 // drop them now so we don't have to 5958 // marshall/unmarshall it. 5959 if ((flags&PackageManager.GET_RESOLVED_FILTER) == 0) { 5960 N = results.size(); 5961 for (int i=0; i<N; i++) { 5962 results.get(i).filter = null; 5963 } 5964 } 5965 5966 if (DEBUG_INTENT_MATCHING) Log.v(TAG, "Result: " + results); 5967 return results; 5968 } 5969 5970 @Override 5971 public @NonNull ParceledListSlice<ResolveInfo> queryIntentReceivers(Intent intent, 5972 String resolvedType, int flags, int userId) { 5973 return new ParceledListSlice<>( 5974 queryIntentReceiversInternal(intent, resolvedType, flags, userId)); 5975 } 5976 5977 private @NonNull List<ResolveInfo> queryIntentReceiversInternal(Intent intent, 5978 String resolvedType, int flags, int userId) { 5979 if (!sUserManager.exists(userId)) return Collections.emptyList(); 5980 flags = updateFlagsForResolve(flags, userId, intent); 5981 ComponentName comp = intent.getComponent(); 5982 if (comp == null) { 5983 if (intent.getSelector() != null) { 5984 intent = intent.getSelector(); 5985 comp = intent.getComponent(); 5986 } 5987 } 5988 if (comp != null) { 5989 List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 5990 ActivityInfo ai = getReceiverInfo(comp, flags, userId); 5991 if (ai != null) { 5992 ResolveInfo ri = new ResolveInfo(); 5993 ri.activityInfo = ai; 5994 list.add(ri); 5995 } 5996 return list; 5997 } 5998 5999 // reader 6000 synchronized (mPackages) { 6001 String pkgName = intent.getPackage(); 6002 if (pkgName == null) { 6003 return mReceivers.queryIntent(intent, resolvedType, flags, userId); 6004 } 6005 final PackageParser.Package pkg = mPackages.get(pkgName); 6006 if (pkg != null) { 6007 return mReceivers.queryIntentForPackage(intent, resolvedType, flags, pkg.receivers, 6008 userId); 6009 } 6010 return Collections.emptyList(); 6011 } 6012 } 6013 6014 @Override 6015 public ResolveInfo resolveService(Intent intent, String resolvedType, int flags, int userId) { 6016 if (!sUserManager.exists(userId)) return null; 6017 flags = updateFlagsForResolve(flags, userId, intent); 6018 List<ResolveInfo> query = queryIntentServicesInternal(intent, resolvedType, flags, userId); 6019 if (query != null) { 6020 if (query.size() >= 1) { 6021 // If there is more than one service with the same priority, 6022 // just arbitrarily pick the first one. 6023 return query.get(0); 6024 } 6025 } 6026 return null; 6027 } 6028 6029 @Override 6030 public @NonNull ParceledListSlice<ResolveInfo> queryIntentServices(Intent intent, 6031 String resolvedType, int flags, int userId) { 6032 return new ParceledListSlice<>( 6033 queryIntentServicesInternal(intent, resolvedType, flags, userId)); 6034 } 6035 6036 private @NonNull List<ResolveInfo> queryIntentServicesInternal(Intent intent, 6037 String resolvedType, int flags, int userId) { 6038 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6039 flags = updateFlagsForResolve(flags, userId, intent); 6040 ComponentName comp = intent.getComponent(); 6041 if (comp == null) { 6042 if (intent.getSelector() != null) { 6043 intent = intent.getSelector(); 6044 comp = intent.getComponent(); 6045 } 6046 } 6047 if (comp != null) { 6048 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6049 final ServiceInfo si = getServiceInfo(comp, flags, userId); 6050 if (si != null) { 6051 final ResolveInfo ri = new ResolveInfo(); 6052 ri.serviceInfo = si; 6053 list.add(ri); 6054 } 6055 return list; 6056 } 6057 6058 // reader 6059 synchronized (mPackages) { 6060 String pkgName = intent.getPackage(); 6061 if (pkgName == null) { 6062 return mServices.queryIntent(intent, resolvedType, flags, userId); 6063 } 6064 final PackageParser.Package pkg = mPackages.get(pkgName); 6065 if (pkg != null) { 6066 return mServices.queryIntentForPackage(intent, resolvedType, flags, pkg.services, 6067 userId); 6068 } 6069 return Collections.emptyList(); 6070 } 6071 } 6072 6073 @Override 6074 public @NonNull ParceledListSlice<ResolveInfo> queryIntentContentProviders(Intent intent, 6075 String resolvedType, int flags, int userId) { 6076 return new ParceledListSlice<>( 6077 queryIntentContentProvidersInternal(intent, resolvedType, flags, userId)); 6078 } 6079 6080 private @NonNull List<ResolveInfo> queryIntentContentProvidersInternal( 6081 Intent intent, String resolvedType, int flags, int userId) { 6082 if (!sUserManager.exists(userId)) return Collections.emptyList(); 6083 flags = updateFlagsForResolve(flags, userId, intent); 6084 ComponentName comp = intent.getComponent(); 6085 if (comp == null) { 6086 if (intent.getSelector() != null) { 6087 intent = intent.getSelector(); 6088 comp = intent.getComponent(); 6089 } 6090 } 6091 if (comp != null) { 6092 final List<ResolveInfo> list = new ArrayList<ResolveInfo>(1); 6093 final ProviderInfo pi = getProviderInfo(comp, flags, userId); 6094 if (pi != null) { 6095 final ResolveInfo ri = new ResolveInfo(); 6096 ri.providerInfo = pi; 6097 list.add(ri); 6098 } 6099 return list; 6100 } 6101 6102 // reader 6103 synchronized (mPackages) { 6104 String pkgName = intent.getPackage(); 6105 if (pkgName == null) { 6106 return mProviders.queryIntent(intent, resolvedType, flags, userId); 6107 } 6108 final PackageParser.Package pkg = mPackages.get(pkgName); 6109 if (pkg != null) { 6110 return mProviders.queryIntentForPackage( 6111 intent, resolvedType, flags, pkg.providers, userId); 6112 } 6113 return Collections.emptyList(); 6114 } 6115 } 6116 6117 @Override 6118 public ParceledListSlice<PackageInfo> getInstalledPackages(int flags, int userId) { 6119 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6120 flags = updateFlagsForPackage(flags, userId, null); 6121 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6122 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6123 true /* requireFullPermission */, false /* checkShell */, 6124 "get installed packages"); 6125 6126 // writer 6127 synchronized (mPackages) { 6128 ArrayList<PackageInfo> list; 6129 if (listUninstalled) { 6130 list = new ArrayList<PackageInfo>(mSettings.mPackages.size()); 6131 for (PackageSetting ps : mSettings.mPackages.values()) { 6132 final PackageInfo pi; 6133 if (ps.pkg != null) { 6134 pi = generatePackageInfo(ps, flags, userId); 6135 } else { 6136 pi = generatePackageInfo(ps, flags, userId); 6137 } 6138 if (pi != null) { 6139 list.add(pi); 6140 } 6141 } 6142 } else { 6143 list = new ArrayList<PackageInfo>(mPackages.size()); 6144 for (PackageParser.Package p : mPackages.values()) { 6145 final PackageInfo pi = 6146 generatePackageInfo((PackageSetting)p.mExtras, flags, userId); 6147 if (pi != null) { 6148 list.add(pi); 6149 } 6150 } 6151 } 6152 6153 return new ParceledListSlice<PackageInfo>(list); 6154 } 6155 } 6156 6157 private void addPackageHoldingPermissions(ArrayList<PackageInfo> list, PackageSetting ps, 6158 String[] permissions, boolean[] tmp, int flags, int userId) { 6159 int numMatch = 0; 6160 final PermissionsState permissionsState = ps.getPermissionsState(); 6161 for (int i=0; i<permissions.length; i++) { 6162 final String permission = permissions[i]; 6163 if (permissionsState.hasPermission(permission, userId)) { 6164 tmp[i] = true; 6165 numMatch++; 6166 } else { 6167 tmp[i] = false; 6168 } 6169 } 6170 if (numMatch == 0) { 6171 return; 6172 } 6173 final PackageInfo pi; 6174 if (ps.pkg != null) { 6175 pi = generatePackageInfo(ps, flags, userId); 6176 } else { 6177 pi = generatePackageInfo(ps, flags, userId); 6178 } 6179 // The above might return null in cases of uninstalled apps or install-state 6180 // skew across users/profiles. 6181 if (pi != null) { 6182 if ((flags&PackageManager.GET_PERMISSIONS) == 0) { 6183 if (numMatch == permissions.length) { 6184 pi.requestedPermissions = permissions; 6185 } else { 6186 pi.requestedPermissions = new String[numMatch]; 6187 numMatch = 0; 6188 for (int i=0; i<permissions.length; i++) { 6189 if (tmp[i]) { 6190 pi.requestedPermissions[numMatch] = permissions[i]; 6191 numMatch++; 6192 } 6193 } 6194 } 6195 } 6196 list.add(pi); 6197 } 6198 } 6199 6200 @Override 6201 public ParceledListSlice<PackageInfo> getPackagesHoldingPermissions( 6202 String[] permissions, int flags, int userId) { 6203 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6204 flags = updateFlagsForPackage(flags, userId, permissions); 6205 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6206 6207 // writer 6208 synchronized (mPackages) { 6209 ArrayList<PackageInfo> list = new ArrayList<PackageInfo>(); 6210 boolean[] tmpBools = new boolean[permissions.length]; 6211 if (listUninstalled) { 6212 for (PackageSetting ps : mSettings.mPackages.values()) { 6213 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, userId); 6214 } 6215 } else { 6216 for (PackageParser.Package pkg : mPackages.values()) { 6217 PackageSetting ps = (PackageSetting)pkg.mExtras; 6218 if (ps != null) { 6219 addPackageHoldingPermissions(list, ps, permissions, tmpBools, flags, 6220 userId); 6221 } 6222 } 6223 } 6224 6225 return new ParceledListSlice<PackageInfo>(list); 6226 } 6227 } 6228 6229 @Override 6230 public ParceledListSlice<ApplicationInfo> getInstalledApplications(int flags, int userId) { 6231 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6232 flags = updateFlagsForApplication(flags, userId, null); 6233 final boolean listUninstalled = (flags & MATCH_UNINSTALLED_PACKAGES) != 0; 6234 6235 // writer 6236 synchronized (mPackages) { 6237 ArrayList<ApplicationInfo> list; 6238 if (listUninstalled) { 6239 list = new ArrayList<ApplicationInfo>(mSettings.mPackages.size()); 6240 for (PackageSetting ps : mSettings.mPackages.values()) { 6241 ApplicationInfo ai; 6242 if (ps.pkg != null) { 6243 ai = PackageParser.generateApplicationInfo(ps.pkg, flags, 6244 ps.readUserState(userId), userId); 6245 } else { 6246 ai = generateApplicationInfoFromSettingsLPw(ps.name, flags, userId); 6247 } 6248 if (ai != null) { 6249 list.add(ai); 6250 } 6251 } 6252 } else { 6253 list = new ArrayList<ApplicationInfo>(mPackages.size()); 6254 for (PackageParser.Package p : mPackages.values()) { 6255 if (p.mExtras != null) { 6256 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6257 ((PackageSetting)p.mExtras).readUserState(userId), userId); 6258 if (ai != null) { 6259 list.add(ai); 6260 } 6261 } 6262 } 6263 } 6264 6265 return new ParceledListSlice<ApplicationInfo>(list); 6266 } 6267 } 6268 6269 @Override 6270 public ParceledListSlice<EphemeralApplicationInfo> getEphemeralApplications(int userId) { 6271 if (DISABLE_EPHEMERAL_APPS) { 6272 return null; 6273 } 6274 6275 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6276 "getEphemeralApplications"); 6277 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6278 true /* requireFullPermission */, false /* checkShell */, 6279 "getEphemeralApplications"); 6280 synchronized (mPackages) { 6281 List<EphemeralApplicationInfo> ephemeralApps = mEphemeralApplicationRegistry 6282 .getEphemeralApplicationsLPw(userId); 6283 if (ephemeralApps != null) { 6284 return new ParceledListSlice<>(ephemeralApps); 6285 } 6286 } 6287 return null; 6288 } 6289 6290 @Override 6291 public boolean isEphemeralApplication(String packageName, int userId) { 6292 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6293 true /* requireFullPermission */, false /* checkShell */, 6294 "isEphemeral"); 6295 if (DISABLE_EPHEMERAL_APPS) { 6296 return false; 6297 } 6298 6299 if (!isCallerSameApp(packageName)) { 6300 return false; 6301 } 6302 synchronized (mPackages) { 6303 PackageParser.Package pkg = mPackages.get(packageName); 6304 if (pkg != null) { 6305 return pkg.applicationInfo.isEphemeralApp(); 6306 } 6307 } 6308 return false; 6309 } 6310 6311 @Override 6312 public byte[] getEphemeralApplicationCookie(String packageName, int userId) { 6313 if (DISABLE_EPHEMERAL_APPS) { 6314 return null; 6315 } 6316 6317 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6318 true /* requireFullPermission */, false /* checkShell */, 6319 "getCookie"); 6320 if (!isCallerSameApp(packageName)) { 6321 return null; 6322 } 6323 synchronized (mPackages) { 6324 return mEphemeralApplicationRegistry.getEphemeralApplicationCookieLPw( 6325 packageName, userId); 6326 } 6327 } 6328 6329 @Override 6330 public boolean setEphemeralApplicationCookie(String packageName, byte[] cookie, int userId) { 6331 if (DISABLE_EPHEMERAL_APPS) { 6332 return true; 6333 } 6334 6335 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6336 true /* requireFullPermission */, true /* checkShell */, 6337 "setCookie"); 6338 if (!isCallerSameApp(packageName)) { 6339 return false; 6340 } 6341 synchronized (mPackages) { 6342 return mEphemeralApplicationRegistry.setEphemeralApplicationCookieLPw( 6343 packageName, cookie, userId); 6344 } 6345 } 6346 6347 @Override 6348 public Bitmap getEphemeralApplicationIcon(String packageName, int userId) { 6349 if (DISABLE_EPHEMERAL_APPS) { 6350 return null; 6351 } 6352 6353 mContext.enforceCallingOrSelfPermission(Manifest.permission.ACCESS_EPHEMERAL_APPS, 6354 "getEphemeralApplicationIcon"); 6355 enforceCrossUserPermission(Binder.getCallingUid(), userId, 6356 true /* requireFullPermission */, false /* checkShell */, 6357 "getEphemeralApplicationIcon"); 6358 synchronized (mPackages) { 6359 return mEphemeralApplicationRegistry.getEphemeralApplicationIconLPw( 6360 packageName, userId); 6361 } 6362 } 6363 6364 private boolean isCallerSameApp(String packageName) { 6365 PackageParser.Package pkg = mPackages.get(packageName); 6366 return pkg != null 6367 && UserHandle.getAppId(Binder.getCallingUid()) == pkg.applicationInfo.uid; 6368 } 6369 6370 @Override 6371 public @NonNull ParceledListSlice<ApplicationInfo> getPersistentApplications(int flags) { 6372 return new ParceledListSlice<>(getPersistentApplicationsInternal(flags)); 6373 } 6374 6375 private @NonNull List<ApplicationInfo> getPersistentApplicationsInternal(int flags) { 6376 final ArrayList<ApplicationInfo> finalList = new ArrayList<ApplicationInfo>(); 6377 6378 // reader 6379 synchronized (mPackages) { 6380 final Iterator<PackageParser.Package> i = mPackages.values().iterator(); 6381 final int userId = UserHandle.getCallingUserId(); 6382 while (i.hasNext()) { 6383 final PackageParser.Package p = i.next(); 6384 if (p.applicationInfo == null) continue; 6385 6386 final boolean matchesUnaware = ((flags & MATCH_DIRECT_BOOT_UNAWARE) != 0) 6387 && !p.applicationInfo.isDirectBootAware(); 6388 final boolean matchesAware = ((flags & MATCH_DIRECT_BOOT_AWARE) != 0) 6389 && p.applicationInfo.isDirectBootAware(); 6390 6391 if ((p.applicationInfo.flags & ApplicationInfo.FLAG_PERSISTENT) != 0 6392 && (!mSafeMode || isSystemApp(p)) 6393 && (matchesUnaware || matchesAware)) { 6394 PackageSetting ps = mSettings.mPackages.get(p.packageName); 6395 if (ps != null) { 6396 ApplicationInfo ai = PackageParser.generateApplicationInfo(p, flags, 6397 ps.readUserState(userId), userId); 6398 if (ai != null) { 6399 finalList.add(ai); 6400 } 6401 } 6402 } 6403 } 6404 } 6405 6406 return finalList; 6407 } 6408 6409 @Override 6410 public ProviderInfo resolveContentProvider(String name, int flags, int userId) { 6411 if (!sUserManager.exists(userId)) return null; 6412 flags = updateFlagsForComponent(flags, userId, name); 6413 // reader 6414 synchronized (mPackages) { 6415 final PackageParser.Provider provider = mProvidersByAuthority.get(name); 6416 PackageSetting ps = provider != null 6417 ? mSettings.mPackages.get(provider.owner.packageName) 6418 : null; 6419 return ps != null 6420 && mSettings.isEnabledAndMatchLPr(provider.info, flags, userId) 6421 ? PackageParser.generateProviderInfo(provider, flags, 6422 ps.readUserState(userId), userId) 6423 : null; 6424 } 6425 } 6426 6427 /** 6428 * @deprecated 6429 */ 6430 @Deprecated 6431 public void querySyncProviders(List<String> outNames, List<ProviderInfo> outInfo) { 6432 // reader 6433 synchronized (mPackages) { 6434 final Iterator<Map.Entry<String, PackageParser.Provider>> i = mProvidersByAuthority 6435 .entrySet().iterator(); 6436 final int userId = UserHandle.getCallingUserId(); 6437 while (i.hasNext()) { 6438 Map.Entry<String, PackageParser.Provider> entry = i.next(); 6439 PackageParser.Provider p = entry.getValue(); 6440 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6441 6442 if (ps != null && p.syncable 6443 && (!mSafeMode || (p.info.applicationInfo.flags 6444 &ApplicationInfo.FLAG_SYSTEM) != 0)) { 6445 ProviderInfo info = PackageParser.generateProviderInfo(p, 0, 6446 ps.readUserState(userId), userId); 6447 if (info != null) { 6448 outNames.add(entry.getKey()); 6449 outInfo.add(info); 6450 } 6451 } 6452 } 6453 } 6454 } 6455 6456 @Override 6457 public @NonNull ParceledListSlice<ProviderInfo> queryContentProviders(String processName, 6458 int uid, int flags) { 6459 final int userId = processName != null ? UserHandle.getUserId(uid) 6460 : UserHandle.getCallingUserId(); 6461 if (!sUserManager.exists(userId)) return ParceledListSlice.emptyList(); 6462 flags = updateFlagsForComponent(flags, userId, processName); 6463 6464 ArrayList<ProviderInfo> finalList = null; 6465 // reader 6466 synchronized (mPackages) { 6467 final Iterator<PackageParser.Provider> i = mProviders.mProviders.values().iterator(); 6468 while (i.hasNext()) { 6469 final PackageParser.Provider p = i.next(); 6470 PackageSetting ps = mSettings.mPackages.get(p.owner.packageName); 6471 if (ps != null && p.info.authority != null 6472 && (processName == null 6473 || (p.info.processName.equals(processName) 6474 && UserHandle.isSameApp(p.info.applicationInfo.uid, uid))) 6475 && mSettings.isEnabledAndMatchLPr(p.info, flags, userId)) { 6476 if (finalList == null) { 6477 finalList = new ArrayList<ProviderInfo>(3); 6478 } 6479 ProviderInfo info = PackageParser.generateProviderInfo(p, flags, 6480 ps.readUserState(userId), userId); 6481 if (info != null) { 6482 finalList.add(info); 6483 } 6484 } 6485 } 6486 } 6487 6488 if (finalList != null) { 6489 Collections.sort(finalList, mProviderInitOrderSorter); 6490 return new ParceledListSlice<ProviderInfo>(finalList); 6491 } 6492 6493 return ParceledListSlice.emptyList(); 6494 } 6495 6496 @Override 6497 public InstrumentationInfo getInstrumentationInfo(ComponentName name, int flags) { 6498 // reader 6499 synchronized (mPackages) { 6500 final PackageParser.Instrumentation i = mInstrumentation.get(name); 6501 return PackageParser.generateInstrumentationInfo(i, flags); 6502 } 6503 } 6504 6505 @Override 6506 public @NonNull ParceledListSlice<InstrumentationInfo> queryInstrumentation( 6507 String targetPackage, int flags) { 6508 return new ParceledListSlice<>(queryInstrumentationInternal(targetPackage, flags)); 6509 } 6510 6511 private @NonNull List<InstrumentationInfo> queryInstrumentationInternal(String targetPackage, 6512 int flags) { 6513 ArrayList<InstrumentationInfo> finalList = new ArrayList<InstrumentationInfo>(); 6514 6515 // reader 6516 synchronized (mPackages) { 6517 final Iterator<PackageParser.Instrumentation> i = mInstrumentation.values().iterator(); 6518 while (i.hasNext()) { 6519 final PackageParser.Instrumentation p = i.next(); 6520 if (targetPackage == null 6521 || targetPackage.equals(p.info.targetPackage)) { 6522 InstrumentationInfo ii = PackageParser.generateInstrumentationInfo(p, 6523 flags); 6524 if (ii != null) { 6525 finalList.add(ii); 6526 } 6527 } 6528 } 6529 } 6530 6531 return finalList; 6532 } 6533 6534 private void createIdmapsForPackageLI(PackageParser.Package pkg) { 6535 ArrayMap<String, PackageParser.Package> overlays = mOverlays.get(pkg.packageName); 6536 if (overlays == null) { 6537 Slog.w(TAG, "Unable to create idmap for " + pkg.packageName + ": no overlay packages"); 6538 return; 6539 } 6540 for (PackageParser.Package opkg : overlays.values()) { 6541 // Not much to do if idmap fails: we already logged the error 6542 // and we certainly don't want to abort installation of pkg simply 6543 // because an overlay didn't fit properly. For these reasons, 6544 // ignore the return value of createIdmapForPackagePairLI. 6545 createIdmapForPackagePairLI(pkg, opkg); 6546 } 6547 } 6548 6549 private boolean createIdmapForPackagePairLI(PackageParser.Package pkg, 6550 PackageParser.Package opkg) { 6551 if (!opkg.mTrustedOverlay) { 6552 Slog.w(TAG, "Skipping target and overlay pair " + pkg.baseCodePath + " and " + 6553 opkg.baseCodePath + ": overlay not trusted"); 6554 return false; 6555 } 6556 ArrayMap<String, PackageParser.Package> overlaySet = mOverlays.get(pkg.packageName); 6557 if (overlaySet == null) { 6558 Slog.e(TAG, "was about to create idmap for " + pkg.baseCodePath + " and " + 6559 opkg.baseCodePath + " but target package has no known overlays"); 6560 return false; 6561 } 6562 final int sharedGid = UserHandle.getSharedAppGid(pkg.applicationInfo.uid); 6563 // TODO: generate idmap for split APKs 6564 try { 6565 mInstaller.idmap(pkg.baseCodePath, opkg.baseCodePath, sharedGid); 6566 } catch (InstallerException e) { 6567 Slog.e(TAG, "Failed to generate idmap for " + pkg.baseCodePath + " and " 6568 + opkg.baseCodePath); 6569 return false; 6570 } 6571 PackageParser.Package[] overlayArray = 6572 overlaySet.values().toArray(new PackageParser.Package[0]); 6573 Comparator<PackageParser.Package> cmp = new Comparator<PackageParser.Package>() { 6574 public int compare(PackageParser.Package p1, PackageParser.Package p2) { 6575 return p1.mOverlayPriority - p2.mOverlayPriority; 6576 } 6577 }; 6578 Arrays.sort(overlayArray, cmp); 6579 6580 pkg.applicationInfo.resourceDirs = new String[overlayArray.length]; 6581 int i = 0; 6582 for (PackageParser.Package p : overlayArray) { 6583 pkg.applicationInfo.resourceDirs[i++] = p.baseCodePath; 6584 } 6585 return true; 6586 } 6587 6588 private void scanDirTracedLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6589 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanDir"); 6590 try { 6591 scanDirLI(dir, parseFlags, scanFlags, currentTime); 6592 } finally { 6593 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6594 } 6595 } 6596 6597 private void scanDirLI(File dir, final int parseFlags, int scanFlags, long currentTime) { 6598 final File[] files = dir.listFiles(); 6599 if (ArrayUtils.isEmpty(files)) { 6600 Log.d(TAG, "No files in app dir " + dir); 6601 return; 6602 } 6603 6604 if (DEBUG_PACKAGE_SCANNING) { 6605 Log.d(TAG, "Scanning app dir " + dir + " scanFlags=" + scanFlags 6606 + " flags=0x" + Integer.toHexString(parseFlags)); 6607 } 6608 6609 for (File file : files) { 6610 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 6611 && !PackageInstallerService.isStageName(file.getName()); 6612 if (!isPackage) { 6613 // Ignore entries which are not packages 6614 continue; 6615 } 6616 try { 6617 scanPackageTracedLI(file, parseFlags | PackageParser.PARSE_MUST_BE_APK, 6618 scanFlags, currentTime, null); 6619 } catch (PackageManagerException e) { 6620 Slog.w(TAG, "Failed to parse " + file + ": " + e.getMessage()); 6621 6622 // Delete invalid userdata apps 6623 if ((parseFlags & PackageParser.PARSE_IS_SYSTEM) == 0 && 6624 e.error == PackageManager.INSTALL_FAILED_INVALID_APK) { 6625 logCriticalInfo(Log.WARN, "Deleting invalid package at " + file); 6626 removeCodePathLI(file); 6627 } 6628 } 6629 } 6630 } 6631 6632 private static File getSettingsProblemFile() { 6633 File dataDir = Environment.getDataDirectory(); 6634 File systemDir = new File(dataDir, "system"); 6635 File fname = new File(systemDir, "uiderrors.txt"); 6636 return fname; 6637 } 6638 6639 static void reportSettingsProblem(int priority, String msg) { 6640 logCriticalInfo(priority, msg); 6641 } 6642 6643 static void logCriticalInfo(int priority, String msg) { 6644 Slog.println(priority, TAG, msg); 6645 EventLogTags.writePmCriticalInfo(msg); 6646 try { 6647 File fname = getSettingsProblemFile(); 6648 FileOutputStream out = new FileOutputStream(fname, true); 6649 PrintWriter pw = new FastPrintWriter(out); 6650 SimpleDateFormat formatter = new SimpleDateFormat(); 6651 String dateString = formatter.format(new Date(System.currentTimeMillis())); 6652 pw.println(dateString + ": " + msg); 6653 pw.close(); 6654 FileUtils.setPermissions( 6655 fname.toString(), 6656 FileUtils.S_IRWXU|FileUtils.S_IRWXG|FileUtils.S_IROTH, 6657 -1, -1); 6658 } catch (java.io.IOException e) { 6659 } 6660 } 6661 6662 private void collectCertificatesLI(PackageSetting ps, PackageParser.Package pkg, File srcFile, 6663 final int policyFlags) throws PackageManagerException { 6664 if (ps != null 6665 && ps.codePath.equals(srcFile) 6666 && ps.timeStamp == srcFile.lastModified() 6667 && !isCompatSignatureUpdateNeeded(pkg) 6668 && !isRecoverSignatureUpdateNeeded(pkg)) { 6669 long mSigningKeySetId = ps.keySetData.getProperSigningKeySet(); 6670 KeySetManagerService ksms = mSettings.mKeySetManagerService; 6671 ArraySet<PublicKey> signingKs; 6672 synchronized (mPackages) { 6673 signingKs = ksms.getPublicKeysFromKeySetLPr(mSigningKeySetId); 6674 } 6675 if (ps.signatures.mSignatures != null 6676 && ps.signatures.mSignatures.length != 0 6677 && signingKs != null) { 6678 // Optimization: reuse the existing cached certificates 6679 // if the package appears to be unchanged. 6680 pkg.mSignatures = ps.signatures.mSignatures; 6681 pkg.mSigningKeys = signingKs; 6682 return; 6683 } 6684 6685 Slog.w(TAG, "PackageSetting for " + ps.name 6686 + " is missing signatures. Collecting certs again to recover them."); 6687 } else { 6688 Log.i(TAG, srcFile.toString() + " changed; collecting certs"); 6689 } 6690 6691 try { 6692 PackageParser.collectCertificates(pkg, policyFlags); 6693 } catch (PackageParserException e) { 6694 throw PackageManagerException.from(e); 6695 } 6696 } 6697 6698 /** 6699 * Traces a package scan. 6700 * @see #scanPackageLI(File, int, int, long, UserHandle) 6701 */ 6702 private PackageParser.Package scanPackageTracedLI(File scanFile, final int parseFlags, 6703 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 6704 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 6705 try { 6706 return scanPackageLI(scanFile, parseFlags, scanFlags, currentTime, user); 6707 } finally { 6708 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6709 } 6710 } 6711 6712 /** 6713 * Scans a package and returns the newly parsed package. 6714 * Returns {@code null} in case of errors and the error code is stored in mLastScanError 6715 */ 6716 private PackageParser.Package scanPackageLI(File scanFile, int parseFlags, int scanFlags, 6717 long currentTime, UserHandle user) throws PackageManagerException { 6718 if (DEBUG_INSTALL) Slog.d(TAG, "Parsing: " + scanFile); 6719 PackageParser pp = new PackageParser(); 6720 pp.setSeparateProcesses(mSeparateProcesses); 6721 pp.setOnlyCoreApps(mOnlyCore); 6722 pp.setDisplayMetrics(mMetrics); 6723 6724 if ((scanFlags & SCAN_TRUSTED_OVERLAY) != 0) { 6725 parseFlags |= PackageParser.PARSE_TRUSTED_OVERLAY; 6726 } 6727 6728 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 6729 final PackageParser.Package pkg; 6730 try { 6731 pkg = pp.parsePackage(scanFile, parseFlags); 6732 } catch (PackageParserException e) { 6733 throw PackageManagerException.from(e); 6734 } finally { 6735 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 6736 } 6737 6738 return scanPackageLI(pkg, scanFile, parseFlags, scanFlags, currentTime, user); 6739 } 6740 6741 /** 6742 * Scans a package and returns the newly parsed package. 6743 * @throws PackageManagerException on a parse error. 6744 */ 6745 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, File scanFile, 6746 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 6747 throws PackageManagerException { 6748 // If the package has children and this is the first dive in the function 6749 // we scan the package with the SCAN_CHECK_ONLY flag set to see whether all 6750 // packages (parent and children) would be successfully scanned before the 6751 // actual scan since scanning mutates internal state and we want to atomically 6752 // install the package and its children. 6753 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 6754 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 6755 scanFlags |= SCAN_CHECK_ONLY; 6756 } 6757 } else { 6758 scanFlags &= ~SCAN_CHECK_ONLY; 6759 } 6760 6761 // Scan the parent 6762 PackageParser.Package scannedPkg = scanPackageInternalLI(pkg, scanFile, policyFlags, 6763 scanFlags, currentTime, user); 6764 6765 // Scan the children 6766 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 6767 for (int i = 0; i < childCount; i++) { 6768 PackageParser.Package childPackage = pkg.childPackages.get(i); 6769 scanPackageInternalLI(childPackage, scanFile, policyFlags, scanFlags, 6770 currentTime, user); 6771 } 6772 6773 6774 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 6775 return scanPackageLI(pkg, scanFile, policyFlags, scanFlags, currentTime, user); 6776 } 6777 6778 return scannedPkg; 6779 } 6780 6781 /** 6782 * Scans a package and returns the newly parsed package. 6783 * @throws PackageManagerException on a parse error. 6784 */ 6785 private PackageParser.Package scanPackageInternalLI(PackageParser.Package pkg, File scanFile, 6786 int policyFlags, int scanFlags, long currentTime, UserHandle user) 6787 throws PackageManagerException { 6788 PackageSetting ps = null; 6789 PackageSetting updatedPkg; 6790 // reader 6791 synchronized (mPackages) { 6792 // Look to see if we already know about this package. 6793 String oldName = mSettings.mRenamedPackages.get(pkg.packageName); 6794 if (pkg.mOriginalPackages != null && pkg.mOriginalPackages.contains(oldName)) { 6795 // This package has been renamed to its original name. Let's 6796 // use that. 6797 ps = mSettings.peekPackageLPr(oldName); 6798 } 6799 // If there was no original package, see one for the real package name. 6800 if (ps == null) { 6801 ps = mSettings.peekPackageLPr(pkg.packageName); 6802 } 6803 // Check to see if this package could be hiding/updating a system 6804 // package. Must look for it either under the original or real 6805 // package name depending on our state. 6806 updatedPkg = mSettings.getDisabledSystemPkgLPr(ps != null ? ps.name : pkg.packageName); 6807 if (DEBUG_INSTALL && updatedPkg != null) Slog.d(TAG, "updatedPkg = " + updatedPkg); 6808 6809 // If this is a package we don't know about on the system partition, we 6810 // may need to remove disabled child packages on the system partition 6811 // or may need to not add child packages if the parent apk is updated 6812 // on the data partition and no longer defines this child package. 6813 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6814 // If this is a parent package for an updated system app and this system 6815 // app got an OTA update which no longer defines some of the child packages 6816 // we have to prune them from the disabled system packages. 6817 PackageSetting disabledPs = mSettings.getDisabledSystemPkgLPr(pkg.packageName); 6818 if (disabledPs != null) { 6819 final int scannedChildCount = (pkg.childPackages != null) 6820 ? pkg.childPackages.size() : 0; 6821 final int disabledChildCount = disabledPs.childPackageNames != null 6822 ? disabledPs.childPackageNames.size() : 0; 6823 for (int i = 0; i < disabledChildCount; i++) { 6824 String disabledChildPackageName = disabledPs.childPackageNames.get(i); 6825 boolean disabledPackageAvailable = false; 6826 for (int j = 0; j < scannedChildCount; j++) { 6827 PackageParser.Package childPkg = pkg.childPackages.get(j); 6828 if (childPkg.packageName.equals(disabledChildPackageName)) { 6829 disabledPackageAvailable = true; 6830 break; 6831 } 6832 } 6833 if (!disabledPackageAvailable) { 6834 mSettings.removeDisabledSystemPackageLPw(disabledChildPackageName); 6835 } 6836 } 6837 } 6838 } 6839 } 6840 6841 boolean updatedPkgBetter = false; 6842 // First check if this is a system package that may involve an update 6843 if (updatedPkg != null && (policyFlags & PackageParser.PARSE_IS_SYSTEM) != 0) { 6844 // If new package is not located in "/system/priv-app" (e.g. due to an OTA), 6845 // it needs to drop FLAG_PRIVILEGED. 6846 if (locationIsPrivileged(scanFile)) { 6847 updatedPkg.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6848 } else { 6849 updatedPkg.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 6850 } 6851 6852 if (ps != null && !ps.codePath.equals(scanFile)) { 6853 // The path has changed from what was last scanned... check the 6854 // version of the new path against what we have stored to determine 6855 // what to do. 6856 if (DEBUG_INSTALL) Slog.d(TAG, "Path changing from " + ps.codePath); 6857 if (pkg.mVersionCode <= ps.versionCode) { 6858 // The system package has been updated and the code path does not match 6859 // Ignore entry. Skip it. 6860 if (DEBUG_INSTALL) Slog.i(TAG, "Package " + ps.name + " at " + scanFile 6861 + " ignored: updated version " + ps.versionCode 6862 + " better than this " + pkg.mVersionCode); 6863 if (!updatedPkg.codePath.equals(scanFile)) { 6864 Slog.w(PackageManagerService.TAG, "Code path for hidden system pkg " 6865 + ps.name + " changing from " + updatedPkg.codePathString 6866 + " to " + scanFile); 6867 updatedPkg.codePath = scanFile; 6868 updatedPkg.codePathString = scanFile.toString(); 6869 updatedPkg.resourcePath = scanFile; 6870 updatedPkg.resourcePathString = scanFile.toString(); 6871 } 6872 updatedPkg.pkg = pkg; 6873 updatedPkg.versionCode = pkg.mVersionCode; 6874 6875 // Update the disabled system child packages to point to the package too. 6876 final int childCount = updatedPkg.childPackageNames != null 6877 ? updatedPkg.childPackageNames.size() : 0; 6878 for (int i = 0; i < childCount; i++) { 6879 String childPackageName = updatedPkg.childPackageNames.get(i); 6880 PackageSetting updatedChildPkg = mSettings.getDisabledSystemPkgLPr( 6881 childPackageName); 6882 if (updatedChildPkg != null) { 6883 updatedChildPkg.pkg = pkg; 6884 updatedChildPkg.versionCode = pkg.mVersionCode; 6885 } 6886 } 6887 6888 throw new PackageManagerException(Log.WARN, "Package " + ps.name + " at " 6889 + scanFile + " ignored: updated version " + ps.versionCode 6890 + " better than this " + pkg.mVersionCode); 6891 } else { 6892 // The current app on the system partition is better than 6893 // what we have updated to on the data partition; switch 6894 // back to the system partition version. 6895 // At this point, its safely assumed that package installation for 6896 // apps in system partition will go through. If not there won't be a working 6897 // version of the app 6898 // writer 6899 synchronized (mPackages) { 6900 // Just remove the loaded entries from package lists. 6901 mPackages.remove(ps.name); 6902 } 6903 6904 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6905 + " reverting from " + ps.codePathString 6906 + ": new version " + pkg.mVersionCode 6907 + " better than installed " + ps.versionCode); 6908 6909 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6910 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6911 synchronized (mInstallLock) { 6912 args.cleanUpResourcesLI(); 6913 } 6914 synchronized (mPackages) { 6915 mSettings.enableSystemPackageLPw(ps.name); 6916 } 6917 updatedPkgBetter = true; 6918 } 6919 } 6920 } 6921 6922 if (updatedPkg != null) { 6923 // An updated system app will not have the PARSE_IS_SYSTEM flag set 6924 // initially 6925 policyFlags |= PackageParser.PARSE_IS_SYSTEM; 6926 6927 // An updated privileged app will not have the PARSE_IS_PRIVILEGED 6928 // flag set initially 6929 if ((updatedPkg.pkgPrivateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0) { 6930 policyFlags |= PackageParser.PARSE_IS_PRIVILEGED; 6931 } 6932 } 6933 6934 // Verify certificates against what was last scanned 6935 collectCertificatesLI(ps, pkg, scanFile, policyFlags); 6936 6937 /* 6938 * A new system app appeared, but we already had a non-system one of the 6939 * same name installed earlier. 6940 */ 6941 boolean shouldHideSystemApp = false; 6942 if (updatedPkg == null && ps != null 6943 && (policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) != 0 && !isSystemApp(ps)) { 6944 /* 6945 * Check to make sure the signatures match first. If they don't, 6946 * wipe the installed application and its data. 6947 */ 6948 if (compareSignatures(ps.signatures.mSignatures, pkg.mSignatures) 6949 != PackageManager.SIGNATURE_MATCH) { 6950 logCriticalInfo(Log.WARN, "Package " + ps.name + " appeared on system, but" 6951 + " signatures don't match existing userdata copy; removing"); 6952 try (PackageFreezer freezer = freezePackage(pkg.packageName, 6953 "scanPackageInternalLI")) { 6954 deletePackageLIF(pkg.packageName, null, true, null, 0, null, false, null); 6955 } 6956 ps = null; 6957 } else { 6958 /* 6959 * If the newly-added system app is an older version than the 6960 * already installed version, hide it. It will be scanned later 6961 * and re-added like an update. 6962 */ 6963 if (pkg.mVersionCode <= ps.versionCode) { 6964 shouldHideSystemApp = true; 6965 logCriticalInfo(Log.INFO, "Package " + ps.name + " appeared at " + scanFile 6966 + " but new version " + pkg.mVersionCode + " better than installed " 6967 + ps.versionCode + "; hiding system"); 6968 } else { 6969 /* 6970 * The newly found system app is a newer version that the 6971 * one previously installed. Simply remove the 6972 * already-installed application and replace it with our own 6973 * while keeping the application data. 6974 */ 6975 logCriticalInfo(Log.WARN, "Package " + ps.name + " at " + scanFile 6976 + " reverting from " + ps.codePathString + ": new version " 6977 + pkg.mVersionCode + " better than installed " + ps.versionCode); 6978 InstallArgs args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 6979 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 6980 synchronized (mInstallLock) { 6981 args.cleanUpResourcesLI(); 6982 } 6983 } 6984 } 6985 } 6986 6987 // The apk is forward locked (not public) if its code and resources 6988 // are kept in different files. (except for app in either system or 6989 // vendor path). 6990 // TODO grab this value from PackageSettings 6991 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 6992 if (ps != null && !ps.codePath.equals(ps.resourcePath)) { 6993 policyFlags |= PackageParser.PARSE_FORWARD_LOCK; 6994 } 6995 } 6996 6997 // TODO: extend to support forward-locked splits 6998 String resourcePath = null; 6999 String baseResourcePath = null; 7000 if ((policyFlags & PackageParser.PARSE_FORWARD_LOCK) != 0 && !updatedPkgBetter) { 7001 if (ps != null && ps.resourcePathString != null) { 7002 resourcePath = ps.resourcePathString; 7003 baseResourcePath = ps.resourcePathString; 7004 } else { 7005 // Should not happen at all. Just log an error. 7006 Slog.e(TAG, "Resource path not set for package " + pkg.packageName); 7007 } 7008 } else { 7009 resourcePath = pkg.codePath; 7010 baseResourcePath = pkg.baseCodePath; 7011 } 7012 7013 // Set application objects path explicitly. 7014 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 7015 pkg.setApplicationInfoCodePath(pkg.codePath); 7016 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 7017 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 7018 pkg.setApplicationInfoResourcePath(resourcePath); 7019 pkg.setApplicationInfoBaseResourcePath(baseResourcePath); 7020 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 7021 7022 // Note that we invoke the following method only if we are about to unpack an application 7023 PackageParser.Package scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags 7024 | SCAN_UPDATE_SIGNATURE, currentTime, user); 7025 7026 /* 7027 * If the system app should be overridden by a previously installed 7028 * data, hide the system app now and let the /data/app scan pick it up 7029 * again. 7030 */ 7031 if (shouldHideSystemApp) { 7032 synchronized (mPackages) { 7033 mSettings.disableSystemPackageLPw(pkg.packageName, true); 7034 } 7035 } 7036 7037 return scannedPkg; 7038 } 7039 7040 private static String fixProcessName(String defProcessName, 7041 String processName, int uid) { 7042 if (processName == null) { 7043 return defProcessName; 7044 } 7045 return processName; 7046 } 7047 7048 private void verifySignaturesLP(PackageSetting pkgSetting, PackageParser.Package pkg) 7049 throws PackageManagerException { 7050 if (pkgSetting.signatures.mSignatures != null) { 7051 // Already existing package. Make sure signatures match 7052 boolean match = compareSignatures(pkgSetting.signatures.mSignatures, pkg.mSignatures) 7053 == PackageManager.SIGNATURE_MATCH; 7054 if (!match) { 7055 match = compareSignaturesCompat(pkgSetting.signatures, pkg) 7056 == PackageManager.SIGNATURE_MATCH; 7057 } 7058 if (!match) { 7059 match = compareSignaturesRecover(pkgSetting.signatures, pkg) 7060 == PackageManager.SIGNATURE_MATCH; 7061 } 7062 if (!match) { 7063 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 7064 + pkg.packageName + " signatures do not match the " 7065 + "previously installed version; ignoring!"); 7066 } 7067 } 7068 7069 // Check for shared user signatures 7070 if (pkgSetting.sharedUser != null && pkgSetting.sharedUser.signatures.mSignatures != null) { 7071 // Already existing package. Make sure signatures match 7072 boolean match = compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 7073 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 7074 if (!match) { 7075 match = compareSignaturesCompat(pkgSetting.sharedUser.signatures, pkg) 7076 == PackageManager.SIGNATURE_MATCH; 7077 } 7078 if (!match) { 7079 match = compareSignaturesRecover(pkgSetting.sharedUser.signatures, pkg) 7080 == PackageManager.SIGNATURE_MATCH; 7081 } 7082 if (!match) { 7083 throw new PackageManagerException(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 7084 "Package " + pkg.packageName 7085 + " has no signatures that match those in shared user " 7086 + pkgSetting.sharedUser.name + "; ignoring!"); 7087 } 7088 } 7089 } 7090 7091 /** 7092 * Enforces that only the system UID or root's UID can call a method exposed 7093 * via Binder. 7094 * 7095 * @param message used as message if SecurityException is thrown 7096 * @throws SecurityException if the caller is not system or root 7097 */ 7098 private static final void enforceSystemOrRoot(String message) { 7099 final int uid = Binder.getCallingUid(); 7100 if (uid != Process.SYSTEM_UID && uid != 0) { 7101 throw new SecurityException(message); 7102 } 7103 } 7104 7105 @Override 7106 public void performFstrimIfNeeded() { 7107 enforceSystemOrRoot("Only the system can request fstrim"); 7108 7109 // Before everything else, see whether we need to fstrim. 7110 try { 7111 IMountService ms = PackageHelper.getMountService(); 7112 if (ms != null) { 7113 final boolean isUpgrade = isUpgrade(); 7114 boolean doTrim = isUpgrade; 7115 if (doTrim) { 7116 Slog.w(TAG, "Running disk maintenance immediately due to system update"); 7117 } else { 7118 final long interval = android.provider.Settings.Global.getLong( 7119 mContext.getContentResolver(), 7120 android.provider.Settings.Global.FSTRIM_MANDATORY_INTERVAL, 7121 DEFAULT_MANDATORY_FSTRIM_INTERVAL); 7122 if (interval > 0) { 7123 final long timeSinceLast = System.currentTimeMillis() - ms.lastMaintenance(); 7124 if (timeSinceLast > interval) { 7125 doTrim = true; 7126 Slog.w(TAG, "No disk maintenance in " + timeSinceLast 7127 + "; running immediately"); 7128 } 7129 } 7130 } 7131 if (doTrim) { 7132 if (!isFirstBoot()) { 7133 try { 7134 ActivityManagerNative.getDefault().showBootMessage( 7135 mContext.getResources().getString( 7136 R.string.android_upgrading_fstrim), true); 7137 } catch (RemoteException e) { 7138 } 7139 } 7140 ms.runMaintenance(); 7141 } 7142 } else { 7143 Slog.e(TAG, "Mount service unavailable!"); 7144 } 7145 } catch (RemoteException e) { 7146 // Can't happen; MountService is local 7147 } 7148 } 7149 7150 @Override 7151 public void updatePackagesIfNeeded() { 7152 enforceSystemOrRoot("Only the system can request package update"); 7153 7154 // We need to re-extract after an OTA. 7155 boolean causeUpgrade = isUpgrade(); 7156 7157 // First boot or factory reset. 7158 // Note: we also handle devices that are upgrading to N right now as if it is their 7159 // first boot, as they do not have profile data. 7160 boolean causeFirstBoot = isFirstBoot() || mIsPreNUpgrade; 7161 7162 // We need to re-extract after a pruned cache, as AoT-ed files will be out of date. 7163 boolean causePrunedCache = VMRuntime.didPruneDalvikCache(); 7164 7165 if (!causeUpgrade && !causeFirstBoot && !causePrunedCache) { 7166 return; 7167 } 7168 7169 List<PackageParser.Package> pkgs; 7170 synchronized (mPackages) { 7171 pkgs = PackageManagerServiceUtils.getPackagesForDexopt(mPackages.values(), this); 7172 } 7173 7174 int curr = 0; 7175 int total = pkgs.size(); 7176 for (PackageParser.Package pkg : pkgs) { 7177 curr++; 7178 7179 if (!PackageDexOptimizer.canOptimizePackage(pkg)) { 7180 if (DEBUG_DEXOPT) { 7181 Log.i(TAG, "Skipping update of of non-optimizable app " + pkg.packageName); 7182 } 7183 continue; 7184 } 7185 7186 if (DEBUG_DEXOPT) { 7187 Log.i(TAG, "Extracting app " + curr + " of " + total + ": " + pkg.packageName); 7188 } 7189 7190 if (!isFirstBoot()) { 7191 try { 7192 ActivityManagerNative.getDefault().showBootMessage( 7193 mContext.getResources().getString(R.string.android_upgrading_apk, 7194 curr, total), true); 7195 } catch (RemoteException e) { 7196 } 7197 } 7198 7199 performDexOpt(pkg.packageName, 7200 null /* instructionSet */, 7201 true /* checkProfiles */, 7202 causeFirstBoot ? REASON_FIRST_BOOT : REASON_BOOT, 7203 false /* force */); 7204 } 7205 } 7206 7207 @Override 7208 public void notifyPackageUse(String packageName, int reason) { 7209 synchronized (mPackages) { 7210 PackageParser.Package p = mPackages.get(packageName); 7211 if (p == null) { 7212 return; 7213 } 7214 p.mLastPackageUsageTimeInMills[reason] = System.currentTimeMillis(); 7215 } 7216 } 7217 7218 // TODO: this is not used nor needed. Delete it. 7219 @Override 7220 public boolean performDexOptIfNeeded(String packageName, String instructionSet) { 7221 return performDexOptTraced(packageName, instructionSet, false /* checkProfiles */, 7222 getFullCompilerFilter(), false /* force */); 7223 } 7224 7225 @Override 7226 public boolean performDexOpt(String packageName, String instructionSet, 7227 boolean checkProfiles, int compileReason, boolean force) { 7228 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7229 getCompilerFilterForReason(compileReason), force); 7230 } 7231 7232 @Override 7233 public boolean performDexOptMode(String packageName, String instructionSet, 7234 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7235 return performDexOptTraced(packageName, instructionSet, checkProfiles, 7236 targetCompilerFilter, force); 7237 } 7238 7239 private boolean performDexOptTraced(String packageName, String instructionSet, 7240 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7241 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7242 try { 7243 return performDexOptInternal(packageName, instructionSet, checkProfiles, 7244 targetCompilerFilter, force); 7245 } finally { 7246 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7247 } 7248 } 7249 7250 // Run dexopt on a given package. Returns true if dexopt did not fail, i.e. 7251 // if the package can now be considered up to date for the given filter. 7252 private boolean performDexOptInternal(String packageName, String instructionSet, 7253 boolean checkProfiles, String targetCompilerFilter, boolean force) { 7254 PackageParser.Package p; 7255 final String targetInstructionSet; 7256 synchronized (mPackages) { 7257 p = mPackages.get(packageName); 7258 if (p == null) { 7259 return false; 7260 } 7261 mPackageUsage.write(false); 7262 7263 targetInstructionSet = instructionSet != null ? instructionSet : 7264 getPrimaryInstructionSet(p.applicationInfo); 7265 } 7266 long callingId = Binder.clearCallingIdentity(); 7267 try { 7268 synchronized (mInstallLock) { 7269 final String[] instructionSets = new String[] { targetInstructionSet }; 7270 int result = performDexOptInternalWithDependenciesLI(p, instructionSets, 7271 checkProfiles, targetCompilerFilter, force); 7272 return result != PackageDexOptimizer.DEX_OPT_FAILED; 7273 } 7274 } finally { 7275 Binder.restoreCallingIdentity(callingId); 7276 } 7277 } 7278 7279 public ArraySet<String> getOptimizablePackages() { 7280 ArraySet<String> pkgs = new ArraySet<String>(); 7281 synchronized (mPackages) { 7282 for (PackageParser.Package p : mPackages.values()) { 7283 if (PackageDexOptimizer.canOptimizePackage(p)) { 7284 pkgs.add(p.packageName); 7285 } 7286 } 7287 } 7288 return pkgs; 7289 } 7290 7291 private int performDexOptInternalWithDependenciesLI(PackageParser.Package p, 7292 String instructionSets[], boolean checkProfiles, String targetCompilerFilter, 7293 boolean force) { 7294 // Select the dex optimizer based on the force parameter. 7295 // Note: The force option is rarely used (cmdline input for testing, mostly), so it's OK to 7296 // allocate an object here. 7297 PackageDexOptimizer pdo = force 7298 ? new PackageDexOptimizer.ForcedUpdatePackageDexOptimizer(mPackageDexOptimizer) 7299 : mPackageDexOptimizer; 7300 7301 // Optimize all dependencies first. Note: we ignore the return value and march on 7302 // on errors. 7303 Collection<PackageParser.Package> deps = findSharedNonSystemLibraries(p); 7304 if (!deps.isEmpty()) { 7305 for (PackageParser.Package depPackage : deps) { 7306 // TODO: Analyze and investigate if we (should) profile libraries. 7307 // Currently this will do a full compilation of the library by default. 7308 pdo.performDexOpt(depPackage, instructionSets, false /* checkProfiles */, 7309 getCompilerFilterForReason(REASON_NON_SYSTEM_LIBRARY)); 7310 } 7311 } 7312 7313 return pdo.performDexOpt(p, instructionSets, checkProfiles, targetCompilerFilter); 7314 } 7315 7316 Collection<PackageParser.Package> findSharedNonSystemLibraries(PackageParser.Package p) { 7317 if (p.usesLibraries != null || p.usesOptionalLibraries != null) { 7318 ArrayList<PackageParser.Package> retValue = new ArrayList<>(); 7319 Set<String> collectedNames = new HashSet<>(); 7320 findSharedNonSystemLibrariesRecursive(p, retValue, collectedNames); 7321 7322 retValue.remove(p); 7323 7324 return retValue; 7325 } else { 7326 return Collections.emptyList(); 7327 } 7328 } 7329 7330 private void findSharedNonSystemLibrariesRecursive(PackageParser.Package p, 7331 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7332 if (!collectedNames.contains(p.packageName)) { 7333 collectedNames.add(p.packageName); 7334 collected.add(p); 7335 7336 if (p.usesLibraries != null) { 7337 findSharedNonSystemLibrariesRecursive(p.usesLibraries, collected, collectedNames); 7338 } 7339 if (p.usesOptionalLibraries != null) { 7340 findSharedNonSystemLibrariesRecursive(p.usesOptionalLibraries, collected, 7341 collectedNames); 7342 } 7343 } 7344 } 7345 7346 private void findSharedNonSystemLibrariesRecursive(Collection<String> libs, 7347 Collection<PackageParser.Package> collected, Set<String> collectedNames) { 7348 for (String libName : libs) { 7349 PackageParser.Package libPkg = findSharedNonSystemLibrary(libName); 7350 if (libPkg != null) { 7351 findSharedNonSystemLibrariesRecursive(libPkg, collected, collectedNames); 7352 } 7353 } 7354 } 7355 7356 private PackageParser.Package findSharedNonSystemLibrary(String libName) { 7357 synchronized (mPackages) { 7358 PackageManagerService.SharedLibraryEntry lib = mSharedLibraries.get(libName); 7359 if (lib != null && lib.apk != null) { 7360 return mPackages.get(lib.apk); 7361 } 7362 } 7363 return null; 7364 } 7365 7366 public void shutdown() { 7367 mPackageUsage.write(true); 7368 } 7369 7370 @Override 7371 public void forceDexOpt(String packageName) { 7372 enforceSystemOrRoot("forceDexOpt"); 7373 7374 PackageParser.Package pkg; 7375 synchronized (mPackages) { 7376 pkg = mPackages.get(packageName); 7377 if (pkg == null) { 7378 throw new IllegalArgumentException("Unknown package: " + packageName); 7379 } 7380 } 7381 7382 synchronized (mInstallLock) { 7383 final String[] instructionSets = new String[] { 7384 getPrimaryInstructionSet(pkg.applicationInfo) }; 7385 7386 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 7387 7388 // Whoever is calling forceDexOpt wants a fully compiled package. 7389 // Don't use profiles since that may cause compilation to be skipped. 7390 final int res = performDexOptInternalWithDependenciesLI(pkg, instructionSets, 7391 false /* checkProfiles */, getCompilerFilterForReason(REASON_FORCED_DEXOPT), 7392 true /* force */); 7393 7394 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7395 if (res != PackageDexOptimizer.DEX_OPT_PERFORMED) { 7396 throw new IllegalStateException("Failed to dexopt: " + res); 7397 } 7398 } 7399 } 7400 7401 private boolean verifyPackageUpdateLPr(PackageSetting oldPkg, PackageParser.Package newPkg) { 7402 if ((oldPkg.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0) { 7403 Slog.w(TAG, "Unable to update from " + oldPkg.name 7404 + " to " + newPkg.packageName 7405 + ": old package not in system partition"); 7406 return false; 7407 } else if (mPackages.get(oldPkg.name) != null) { 7408 Slog.w(TAG, "Unable to update from " + oldPkg.name 7409 + " to " + newPkg.packageName 7410 + ": old package still exists"); 7411 return false; 7412 } 7413 return true; 7414 } 7415 7416 void removeCodePathLI(File codePath) { 7417 if (codePath.isDirectory()) { 7418 try { 7419 mInstaller.rmPackageDir(codePath.getAbsolutePath()); 7420 } catch (InstallerException e) { 7421 Slog.w(TAG, "Failed to remove code path", e); 7422 } 7423 } else { 7424 codePath.delete(); 7425 } 7426 } 7427 7428 private int[] resolveUserIds(int userId) { 7429 return (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() : new int[] { userId }; 7430 } 7431 7432 private void clearAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7433 if (pkg == null) { 7434 Slog.wtf(TAG, "Package was null!", new Throwable()); 7435 return; 7436 } 7437 clearAppDataLeafLIF(pkg, userId, flags); 7438 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7439 for (int i = 0; i < childCount; i++) { 7440 clearAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7441 } 7442 } 7443 7444 private void clearAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7445 final PackageSetting ps; 7446 synchronized (mPackages) { 7447 ps = mSettings.mPackages.get(pkg.packageName); 7448 } 7449 for (int realUserId : resolveUserIds(userId)) { 7450 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7451 try { 7452 mInstaller.clearAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7453 ceDataInode); 7454 } catch (InstallerException e) { 7455 Slog.w(TAG, String.valueOf(e)); 7456 } 7457 } 7458 } 7459 7460 private void destroyAppDataLIF(PackageParser.Package pkg, int userId, int flags) { 7461 if (pkg == null) { 7462 Slog.wtf(TAG, "Package was null!", new Throwable()); 7463 return; 7464 } 7465 destroyAppDataLeafLIF(pkg, userId, flags); 7466 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7467 for (int i = 0; i < childCount; i++) { 7468 destroyAppDataLeafLIF(pkg.childPackages.get(i), userId, flags); 7469 } 7470 } 7471 7472 private void destroyAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags) { 7473 final PackageSetting ps; 7474 synchronized (mPackages) { 7475 ps = mSettings.mPackages.get(pkg.packageName); 7476 } 7477 for (int realUserId : resolveUserIds(userId)) { 7478 final long ceDataInode = (ps != null) ? ps.getCeDataInode(realUserId) : 0; 7479 try { 7480 mInstaller.destroyAppData(pkg.volumeUuid, pkg.packageName, realUserId, flags, 7481 ceDataInode); 7482 } catch (InstallerException e) { 7483 Slog.w(TAG, String.valueOf(e)); 7484 } 7485 } 7486 } 7487 7488 private void destroyAppProfilesLIF(PackageParser.Package pkg) { 7489 if (pkg == null) { 7490 Slog.wtf(TAG, "Package was null!", new Throwable()); 7491 return; 7492 } 7493 destroyAppProfilesLeafLIF(pkg); 7494 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7495 for (int i = 0; i < childCount; i++) { 7496 destroyAppProfilesLeafLIF(pkg.childPackages.get(i)); 7497 } 7498 } 7499 7500 private void destroyAppProfilesLeafLIF(PackageParser.Package pkg) { 7501 try { 7502 mInstaller.destroyAppProfiles(pkg.packageName); 7503 } catch (InstallerException e) { 7504 Slog.w(TAG, String.valueOf(e)); 7505 } 7506 } 7507 7508 private void clearAppProfilesLIF(PackageParser.Package pkg) { 7509 if (pkg == null) { 7510 Slog.wtf(TAG, "Package was null!", new Throwable()); 7511 return; 7512 } 7513 clearAppProfilesLeafLIF(pkg); 7514 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7515 for (int i = 0; i < childCount; i++) { 7516 clearAppProfilesLeafLIF(pkg.childPackages.get(i)); 7517 } 7518 } 7519 7520 private void clearAppProfilesLeafLIF(PackageParser.Package pkg) { 7521 try { 7522 mInstaller.clearAppProfiles(pkg.packageName); 7523 } catch (InstallerException e) { 7524 Slog.w(TAG, String.valueOf(e)); 7525 } 7526 } 7527 7528 private void setInstallAndUpdateTime(PackageParser.Package pkg, long firstInstallTime, 7529 long lastUpdateTime) { 7530 // Set parent install/update time 7531 PackageSetting ps = (PackageSetting) pkg.mExtras; 7532 if (ps != null) { 7533 ps.firstInstallTime = firstInstallTime; 7534 ps.lastUpdateTime = lastUpdateTime; 7535 } 7536 // Set children install/update time 7537 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7538 for (int i = 0; i < childCount; i++) { 7539 PackageParser.Package childPkg = pkg.childPackages.get(i); 7540 ps = (PackageSetting) childPkg.mExtras; 7541 if (ps != null) { 7542 ps.firstInstallTime = firstInstallTime; 7543 ps.lastUpdateTime = lastUpdateTime; 7544 } 7545 } 7546 } 7547 7548 private void addSharedLibraryLPw(ArraySet<String> usesLibraryFiles, SharedLibraryEntry file, 7549 PackageParser.Package changingLib) { 7550 if (file.path != null) { 7551 usesLibraryFiles.add(file.path); 7552 return; 7553 } 7554 PackageParser.Package p = mPackages.get(file.apk); 7555 if (changingLib != null && changingLib.packageName.equals(file.apk)) { 7556 // If we are doing this while in the middle of updating a library apk, 7557 // then we need to make sure to use that new apk for determining the 7558 // dependencies here. (We haven't yet finished committing the new apk 7559 // to the package manager state.) 7560 if (p == null || p.packageName.equals(changingLib.packageName)) { 7561 p = changingLib; 7562 } 7563 } 7564 if (p != null) { 7565 usesLibraryFiles.addAll(p.getAllCodePaths()); 7566 } 7567 } 7568 7569 private void updateSharedLibrariesLPw(PackageParser.Package pkg, 7570 PackageParser.Package changingLib) throws PackageManagerException { 7571 if (pkg.usesLibraries != null || pkg.usesOptionalLibraries != null) { 7572 final ArraySet<String> usesLibraryFiles = new ArraySet<>(); 7573 int N = pkg.usesLibraries != null ? pkg.usesLibraries.size() : 0; 7574 for (int i=0; i<N; i++) { 7575 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesLibraries.get(i)); 7576 if (file == null) { 7577 throw new PackageManagerException(INSTALL_FAILED_MISSING_SHARED_LIBRARY, 7578 "Package " + pkg.packageName + " requires unavailable shared library " 7579 + pkg.usesLibraries.get(i) + "; failing!"); 7580 } 7581 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7582 } 7583 N = pkg.usesOptionalLibraries != null ? pkg.usesOptionalLibraries.size() : 0; 7584 for (int i=0; i<N; i++) { 7585 final SharedLibraryEntry file = mSharedLibraries.get(pkg.usesOptionalLibraries.get(i)); 7586 if (file == null) { 7587 Slog.w(TAG, "Package " + pkg.packageName 7588 + " desires unavailable shared library " 7589 + pkg.usesOptionalLibraries.get(i) + "; ignoring!"); 7590 } else { 7591 addSharedLibraryLPw(usesLibraryFiles, file, changingLib); 7592 } 7593 } 7594 N = usesLibraryFiles.size(); 7595 if (N > 0) { 7596 pkg.usesLibraryFiles = usesLibraryFiles.toArray(new String[N]); 7597 } else { 7598 pkg.usesLibraryFiles = null; 7599 } 7600 } 7601 } 7602 7603 private static boolean hasString(List<String> list, List<String> which) { 7604 if (list == null) { 7605 return false; 7606 } 7607 for (int i=list.size()-1; i>=0; i--) { 7608 for (int j=which.size()-1; j>=0; j--) { 7609 if (which.get(j).equals(list.get(i))) { 7610 return true; 7611 } 7612 } 7613 } 7614 return false; 7615 } 7616 7617 private void updateAllSharedLibrariesLPw() { 7618 for (PackageParser.Package pkg : mPackages.values()) { 7619 try { 7620 updateSharedLibrariesLPw(pkg, null); 7621 } catch (PackageManagerException e) { 7622 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7623 } 7624 } 7625 } 7626 7627 private ArrayList<PackageParser.Package> updateAllSharedLibrariesLPw( 7628 PackageParser.Package changingPkg) { 7629 ArrayList<PackageParser.Package> res = null; 7630 for (PackageParser.Package pkg : mPackages.values()) { 7631 if (hasString(pkg.usesLibraries, changingPkg.libraryNames) 7632 || hasString(pkg.usesOptionalLibraries, changingPkg.libraryNames)) { 7633 if (res == null) { 7634 res = new ArrayList<PackageParser.Package>(); 7635 } 7636 res.add(pkg); 7637 try { 7638 updateSharedLibrariesLPw(pkg, changingPkg); 7639 } catch (PackageManagerException e) { 7640 Slog.e(TAG, "updateAllSharedLibrariesLPw failed: " + e.getMessage()); 7641 } 7642 } 7643 } 7644 return res; 7645 } 7646 7647 /** 7648 * Derive the value of the {@code cpuAbiOverride} based on the provided 7649 * value and an optional stored value from the package settings. 7650 */ 7651 private static String deriveAbiOverride(String abiOverride, PackageSetting settings) { 7652 String cpuAbiOverride = null; 7653 7654 if (NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(abiOverride)) { 7655 cpuAbiOverride = null; 7656 } else if (abiOverride != null) { 7657 cpuAbiOverride = abiOverride; 7658 } else if (settings != null) { 7659 cpuAbiOverride = settings.cpuAbiOverrideString; 7660 } 7661 7662 return cpuAbiOverride; 7663 } 7664 7665 private PackageParser.Package scanPackageTracedLI(PackageParser.Package pkg, 7666 final int policyFlags, int scanFlags, long currentTime, UserHandle user) 7667 throws PackageManagerException { 7668 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "scanPackage"); 7669 // If the package has children and this is the first dive in the function 7670 // we recursively scan the package with the SCAN_CHECK_ONLY flag set to see 7671 // whether all packages (parent and children) would be successfully scanned 7672 // before the actual scan since scanning mutates internal state and we want 7673 // to atomically install the package and its children. 7674 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7675 if (pkg.childPackages != null && pkg.childPackages.size() > 0) { 7676 scanFlags |= SCAN_CHECK_ONLY; 7677 } 7678 } else { 7679 scanFlags &= ~SCAN_CHECK_ONLY; 7680 } 7681 7682 final PackageParser.Package scannedPkg; 7683 try { 7684 // Scan the parent 7685 scannedPkg = scanPackageLI(pkg, policyFlags, scanFlags, currentTime, user); 7686 // Scan the children 7687 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 7688 for (int i = 0; i < childCount; i++) { 7689 PackageParser.Package childPkg = pkg.childPackages.get(i); 7690 scanPackageLI(childPkg, policyFlags, 7691 scanFlags, currentTime, user); 7692 } 7693 } finally { 7694 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 7695 } 7696 7697 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 7698 return scanPackageTracedLI(pkg, policyFlags, scanFlags, currentTime, user); 7699 } 7700 7701 return scannedPkg; 7702 } 7703 7704 private PackageParser.Package scanPackageLI(PackageParser.Package pkg, final int policyFlags, 7705 int scanFlags, long currentTime, UserHandle user) throws PackageManagerException { 7706 boolean success = false; 7707 try { 7708 final PackageParser.Package res = scanPackageDirtyLI(pkg, policyFlags, scanFlags, 7709 currentTime, user); 7710 success = true; 7711 return res; 7712 } finally { 7713 if (!success && (scanFlags & SCAN_DELETE_DATA_ON_FAILURES) != 0) { 7714 // DELETE_DATA_ON_FAILURES is only used by frozen paths 7715 destroyAppDataLIF(pkg, UserHandle.USER_ALL, 7716 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 7717 destroyAppProfilesLIF(pkg); 7718 } 7719 } 7720 } 7721 7722 /** 7723 * Returns {@code true} if the given file contains code. Otherwise {@code false}. 7724 */ 7725 private static boolean apkHasCode(String fileName) { 7726 StrictJarFile jarFile = null; 7727 try { 7728 jarFile = new StrictJarFile(fileName, 7729 false /*verify*/, false /*signatureSchemeRollbackProtectionsEnforced*/); 7730 return jarFile.findEntry("classes.dex") != null; 7731 } catch (IOException ignore) { 7732 } finally { 7733 try { 7734 jarFile.close(); 7735 } catch (IOException ignore) {} 7736 } 7737 return false; 7738 } 7739 7740 /** 7741 * Enforces code policy for the package. This ensures that if an APK has 7742 * declared hasCode="true" in its manifest that the APK actually contains 7743 * code. 7744 * 7745 * @throws PackageManagerException If bytecode could not be found when it should exist 7746 */ 7747 private static void enforceCodePolicy(PackageParser.Package pkg) 7748 throws PackageManagerException { 7749 final boolean shouldHaveCode = 7750 (pkg.applicationInfo.flags & ApplicationInfo.FLAG_HAS_CODE) != 0; 7751 if (shouldHaveCode && !apkHasCode(pkg.baseCodePath)) { 7752 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7753 "Package " + pkg.baseCodePath + " code is missing"); 7754 } 7755 7756 if (!ArrayUtils.isEmpty(pkg.splitCodePaths)) { 7757 for (int i = 0; i < pkg.splitCodePaths.length; i++) { 7758 final boolean splitShouldHaveCode = 7759 (pkg.splitFlags[i] & ApplicationInfo.FLAG_HAS_CODE) != 0; 7760 if (splitShouldHaveCode && !apkHasCode(pkg.splitCodePaths[i])) { 7761 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7762 "Package " + pkg.splitCodePaths[i] + " code is missing"); 7763 } 7764 } 7765 } 7766 } 7767 7768 private PackageParser.Package scanPackageDirtyLI(PackageParser.Package pkg, 7769 final int policyFlags, final int scanFlags, long currentTime, UserHandle user) 7770 throws PackageManagerException { 7771 final File scanFile = new File(pkg.codePath); 7772 if (pkg.applicationInfo.getCodePath() == null || 7773 pkg.applicationInfo.getResourcePath() == null) { 7774 // Bail out. The resource and code paths haven't been set. 7775 throw new PackageManagerException(INSTALL_FAILED_INVALID_APK, 7776 "Code and resource paths haven't been set correctly"); 7777 } 7778 7779 // Apply policy 7780 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM) != 0) { 7781 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_SYSTEM; 7782 if (pkg.applicationInfo.isDirectBootAware()) { 7783 // we're direct boot aware; set for all components 7784 for (PackageParser.Service s : pkg.services) { 7785 s.info.encryptionAware = s.info.directBootAware = true; 7786 } 7787 for (PackageParser.Provider p : pkg.providers) { 7788 p.info.encryptionAware = p.info.directBootAware = true; 7789 } 7790 for (PackageParser.Activity a : pkg.activities) { 7791 a.info.encryptionAware = a.info.directBootAware = true; 7792 } 7793 for (PackageParser.Activity r : pkg.receivers) { 7794 r.info.encryptionAware = r.info.directBootAware = true; 7795 } 7796 } 7797 } else { 7798 // Only allow system apps to be flagged as core apps. 7799 pkg.coreApp = false; 7800 // clear flags not applicable to regular apps 7801 pkg.applicationInfo.privateFlags &= 7802 ~ApplicationInfo.PRIVATE_FLAG_DEFAULT_TO_DEVICE_PROTECTED_STORAGE; 7803 pkg.applicationInfo.privateFlags &= 7804 ~ApplicationInfo.PRIVATE_FLAG_DIRECT_BOOT_AWARE; 7805 } 7806 pkg.mTrustedOverlay = (policyFlags&PackageParser.PARSE_TRUSTED_OVERLAY) != 0; 7807 7808 if ((policyFlags&PackageParser.PARSE_IS_PRIVILEGED) != 0) { 7809 pkg.applicationInfo.privateFlags |= ApplicationInfo.PRIVATE_FLAG_PRIVILEGED; 7810 } 7811 7812 if ((policyFlags & PackageParser.PARSE_ENFORCE_CODE) != 0) { 7813 enforceCodePolicy(pkg); 7814 } 7815 7816 if (mCustomResolverComponentName != null && 7817 mCustomResolverComponentName.getPackageName().equals(pkg.packageName)) { 7818 setUpCustomResolverActivity(pkg); 7819 } 7820 7821 if (pkg.packageName.equals("android")) { 7822 synchronized (mPackages) { 7823 if (mAndroidApplication != null) { 7824 Slog.w(TAG, "*************************************************"); 7825 Slog.w(TAG, "Core android package being redefined. Skipping."); 7826 Slog.w(TAG, " file=" + scanFile); 7827 Slog.w(TAG, "*************************************************"); 7828 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7829 "Core android package being redefined. Skipping."); 7830 } 7831 7832 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 7833 // Set up information for our fall-back user intent resolution activity. 7834 mPlatformPackage = pkg; 7835 pkg.mVersionCode = mSdkVersion; 7836 mAndroidApplication = pkg.applicationInfo; 7837 7838 if (!mResolverReplaced) { 7839 mResolveActivity.applicationInfo = mAndroidApplication; 7840 mResolveActivity.name = ResolverActivity.class.getName(); 7841 mResolveActivity.packageName = mAndroidApplication.packageName; 7842 mResolveActivity.processName = "system:ui"; 7843 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 7844 mResolveActivity.documentLaunchMode = ActivityInfo.DOCUMENT_LAUNCH_NEVER; 7845 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS; 7846 mResolveActivity.theme = R.style.Theme_Holo_Dialog_Alert; 7847 mResolveActivity.exported = true; 7848 mResolveActivity.enabled = true; 7849 mResolveInfo.activityInfo = mResolveActivity; 7850 mResolveInfo.priority = 0; 7851 mResolveInfo.preferredOrder = 0; 7852 mResolveInfo.match = 0; 7853 mResolveComponentName = new ComponentName( 7854 mAndroidApplication.packageName, mResolveActivity.name); 7855 } 7856 } 7857 } 7858 } 7859 7860 if (DEBUG_PACKAGE_SCANNING) { 7861 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7862 Log.d(TAG, "Scanning package " + pkg.packageName); 7863 } 7864 7865 synchronized (mPackages) { 7866 if (mPackages.containsKey(pkg.packageName) 7867 || mSharedLibraries.containsKey(pkg.packageName)) { 7868 throw new PackageManagerException(INSTALL_FAILED_DUPLICATE_PACKAGE, 7869 "Application package " + pkg.packageName 7870 + " already installed. Skipping duplicate."); 7871 } 7872 7873 // If we're only installing presumed-existing packages, require that the 7874 // scanned APK is both already known and at the path previously established 7875 // for it. Previously unknown packages we pick up normally, but if we have an 7876 // a priori expectation about this package's install presence, enforce it. 7877 // With a singular exception for new system packages. When an OTA contains 7878 // a new system package, we allow the codepath to change from a system location 7879 // to the user-installed location. If we don't allow this change, any newer, 7880 // user-installed version of the application will be ignored. 7881 if ((scanFlags & SCAN_REQUIRE_KNOWN) != 0) { 7882 if (mExpectingBetter.containsKey(pkg.packageName)) { 7883 logCriticalInfo(Log.WARN, 7884 "Relax SCAN_REQUIRE_KNOWN requirement for package " + pkg.packageName); 7885 } else { 7886 PackageSetting known = mSettings.peekPackageLPr(pkg.packageName); 7887 if (known != null) { 7888 if (DEBUG_PACKAGE_SCANNING) { 7889 Log.d(TAG, "Examining " + pkg.codePath 7890 + " and requiring known paths " + known.codePathString 7891 + " & " + known.resourcePathString); 7892 } 7893 if (!pkg.applicationInfo.getCodePath().equals(known.codePathString) 7894 || !pkg.applicationInfo.getResourcePath().equals( 7895 known.resourcePathString)) { 7896 throw new PackageManagerException(INSTALL_FAILED_PACKAGE_CHANGED, 7897 "Application package " + pkg.packageName 7898 + " found at " + pkg.applicationInfo.getCodePath() 7899 + " but expected at " + known.codePathString 7900 + "; ignoring."); 7901 } 7902 } 7903 } 7904 } 7905 } 7906 7907 // Initialize package source and resource directories 7908 File destCodeFile = new File(pkg.applicationInfo.getCodePath()); 7909 File destResourceFile = new File(pkg.applicationInfo.getResourcePath()); 7910 7911 SharedUserSetting suid = null; 7912 PackageSetting pkgSetting = null; 7913 7914 if (!isSystemApp(pkg)) { 7915 // Only system apps can use these features. 7916 pkg.mOriginalPackages = null; 7917 pkg.mRealPackage = null; 7918 pkg.mAdoptPermissions = null; 7919 } 7920 7921 // Getting the package setting may have a side-effect, so if we 7922 // are only checking if scan would succeed, stash a copy of the 7923 // old setting to restore at the end. 7924 PackageSetting nonMutatedPs = null; 7925 7926 // writer 7927 synchronized (mPackages) { 7928 if (pkg.mSharedUserId != null) { 7929 suid = mSettings.getSharedUserLPw(pkg.mSharedUserId, 0, 0, true); 7930 if (suid == null) { 7931 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 7932 "Creating application package " + pkg.packageName 7933 + " for shared user failed"); 7934 } 7935 if (DEBUG_PACKAGE_SCANNING) { 7936 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 7937 Log.d(TAG, "Shared UserID " + pkg.mSharedUserId + " (uid=" + suid.userId 7938 + "): packages=" + suid.packages); 7939 } 7940 } 7941 7942 // Check if we are renaming from an original package name. 7943 PackageSetting origPackage = null; 7944 String realName = null; 7945 if (pkg.mOriginalPackages != null) { 7946 // This package may need to be renamed to a previously 7947 // installed name. Let's check on that... 7948 final String renamed = mSettings.mRenamedPackages.get(pkg.mRealPackage); 7949 if (pkg.mOriginalPackages.contains(renamed)) { 7950 // This package had originally been installed as the 7951 // original name, and we have already taken care of 7952 // transitioning to the new one. Just update the new 7953 // one to continue using the old name. 7954 realName = pkg.mRealPackage; 7955 if (!pkg.packageName.equals(renamed)) { 7956 // Callers into this function may have already taken 7957 // care of renaming the package; only do it here if 7958 // it is not already done. 7959 pkg.setPackageName(renamed); 7960 } 7961 7962 } else { 7963 for (int i=pkg.mOriginalPackages.size()-1; i>=0; i--) { 7964 if ((origPackage = mSettings.peekPackageLPr( 7965 pkg.mOriginalPackages.get(i))) != null) { 7966 // We do have the package already installed under its 7967 // original name... should we use it? 7968 if (!verifyPackageUpdateLPr(origPackage, pkg)) { 7969 // New package is not compatible with original. 7970 origPackage = null; 7971 continue; 7972 } else if (origPackage.sharedUser != null) { 7973 // Make sure uid is compatible between packages. 7974 if (!origPackage.sharedUser.name.equals(pkg.mSharedUserId)) { 7975 Slog.w(TAG, "Unable to migrate data from " + origPackage.name 7976 + " to " + pkg.packageName + ": old uid " 7977 + origPackage.sharedUser.name 7978 + " differs from " + pkg.mSharedUserId); 7979 origPackage = null; 7980 continue; 7981 } 7982 // TODO: Add case when shared user id is added [b/28144775] 7983 } else { 7984 if (DEBUG_UPGRADE) Log.v(TAG, "Renaming new package " 7985 + pkg.packageName + " to old name " + origPackage.name); 7986 } 7987 break; 7988 } 7989 } 7990 } 7991 } 7992 7993 if (mTransferedPackages.contains(pkg.packageName)) { 7994 Slog.w(TAG, "Package " + pkg.packageName 7995 + " was transferred to another, but its .apk remains"); 7996 } 7997 7998 // See comments in nonMutatedPs declaration 7999 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8000 PackageSetting foundPs = mSettings.peekPackageLPr(pkg.packageName); 8001 if (foundPs != null) { 8002 nonMutatedPs = new PackageSetting(foundPs); 8003 } 8004 } 8005 8006 // Just create the setting, don't add it yet. For already existing packages 8007 // the PkgSetting exists already and doesn't have to be created. 8008 pkgSetting = mSettings.getPackageLPw(pkg, origPackage, realName, suid, destCodeFile, 8009 destResourceFile, pkg.applicationInfo.nativeLibraryRootDir, 8010 pkg.applicationInfo.primaryCpuAbi, 8011 pkg.applicationInfo.secondaryCpuAbi, 8012 pkg.applicationInfo.flags, pkg.applicationInfo.privateFlags, 8013 user, false); 8014 if (pkgSetting == null) { 8015 throw new PackageManagerException(INSTALL_FAILED_INSUFFICIENT_STORAGE, 8016 "Creating application package " + pkg.packageName + " failed"); 8017 } 8018 8019 if (pkgSetting.origPackage != null) { 8020 // If we are first transitioning from an original package, 8021 // fix up the new package's name now. We need to do this after 8022 // looking up the package under its new name, so getPackageLP 8023 // can take care of fiddling things correctly. 8024 pkg.setPackageName(origPackage.name); 8025 8026 // File a report about this. 8027 String msg = "New package " + pkgSetting.realName 8028 + " renamed to replace old package " + pkgSetting.name; 8029 reportSettingsProblem(Log.WARN, msg); 8030 8031 // Make a note of it. 8032 if ((scanFlags & SCAN_CHECK_ONLY) == 0) { 8033 mTransferedPackages.add(origPackage.name); 8034 } 8035 8036 // No longer need to retain this. 8037 pkgSetting.origPackage = null; 8038 } 8039 8040 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && realName != null) { 8041 // Make a note of it. 8042 mTransferedPackages.add(pkg.packageName); 8043 } 8044 8045 if (mSettings.isDisabledSystemPackageLPr(pkg.packageName)) { 8046 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_UPDATED_SYSTEM_APP; 8047 } 8048 8049 if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8050 // Check all shared libraries and map to their actual file path. 8051 // We only do this here for apps not on a system dir, because those 8052 // are the only ones that can fail an install due to this. We 8053 // will take care of the system apps by updating all of their 8054 // library paths after the scan is done. 8055 updateSharedLibrariesLPw(pkg, null); 8056 } 8057 8058 if (mFoundPolicyFile) { 8059 SELinuxMMAC.assignSeinfoValue(pkg); 8060 } 8061 8062 pkg.applicationInfo.uid = pkgSetting.appId; 8063 pkg.mExtras = pkgSetting; 8064 if (shouldCheckUpgradeKeySetLP(pkgSetting, scanFlags)) { 8065 if (checkUpgradeKeySetLP(pkgSetting, pkg)) { 8066 // We just determined the app is signed correctly, so bring 8067 // over the latest parsed certs. 8068 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8069 } else { 8070 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8071 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8072 "Package " + pkg.packageName + " upgrade keys do not match the " 8073 + "previously installed version"); 8074 } else { 8075 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8076 String msg = "System package " + pkg.packageName 8077 + " signature changed; retaining data."; 8078 reportSettingsProblem(Log.WARN, msg); 8079 } 8080 } 8081 } else { 8082 try { 8083 verifySignaturesLP(pkgSetting, pkg); 8084 // We just determined the app is signed correctly, so bring 8085 // over the latest parsed certs. 8086 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8087 } catch (PackageManagerException e) { 8088 if ((policyFlags & PackageParser.PARSE_IS_SYSTEM_DIR) == 0) { 8089 throw e; 8090 } 8091 // The signature has changed, but this package is in the system 8092 // image... let's recover! 8093 pkgSetting.signatures.mSignatures = pkg.mSignatures; 8094 // However... if this package is part of a shared user, but it 8095 // doesn't match the signature of the shared user, let's fail. 8096 // What this means is that you can't change the signatures 8097 // associated with an overall shared user, which doesn't seem all 8098 // that unreasonable. 8099 if (pkgSetting.sharedUser != null) { 8100 if (compareSignatures(pkgSetting.sharedUser.signatures.mSignatures, 8101 pkg.mSignatures) != PackageManager.SIGNATURE_MATCH) { 8102 throw new PackageManagerException( 8103 INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES, 8104 "Signature mismatch for shared user: " 8105 + pkgSetting.sharedUser); 8106 } 8107 } 8108 // File a report about this. 8109 String msg = "System package " + pkg.packageName 8110 + " signature changed; retaining data."; 8111 reportSettingsProblem(Log.WARN, msg); 8112 } 8113 } 8114 // Verify that this new package doesn't have any content providers 8115 // that conflict with existing packages. Only do this if the 8116 // package isn't already installed, since we don't want to break 8117 // things that are installed. 8118 if ((scanFlags & SCAN_NEW_INSTALL) != 0) { 8119 final int N = pkg.providers.size(); 8120 int i; 8121 for (i=0; i<N; i++) { 8122 PackageParser.Provider p = pkg.providers.get(i); 8123 if (p.info.authority != null) { 8124 String names[] = p.info.authority.split(";"); 8125 for (int j = 0; j < names.length; j++) { 8126 if (mProvidersByAuthority.containsKey(names[j])) { 8127 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8128 final String otherPackageName = 8129 ((other != null && other.getComponentName() != null) ? 8130 other.getComponentName().getPackageName() : "?"); 8131 throw new PackageManagerException( 8132 INSTALL_FAILED_CONFLICTING_PROVIDER, 8133 "Can't install because provider name " + names[j] 8134 + " (in package " + pkg.applicationInfo.packageName 8135 + ") is already used by " + otherPackageName); 8136 } 8137 } 8138 } 8139 } 8140 } 8141 8142 if ((scanFlags & SCAN_CHECK_ONLY) == 0 && pkg.mAdoptPermissions != null) { 8143 // This package wants to adopt ownership of permissions from 8144 // another package. 8145 for (int i = pkg.mAdoptPermissions.size() - 1; i >= 0; i--) { 8146 final String origName = pkg.mAdoptPermissions.get(i); 8147 final PackageSetting orig = mSettings.peekPackageLPr(origName); 8148 if (orig != null) { 8149 if (verifyPackageUpdateLPr(orig, pkg)) { 8150 Slog.i(TAG, "Adopting permissions from " + origName + " to " 8151 + pkg.packageName); 8152 mSettings.transferPermissionsLPw(origName, pkg.packageName); 8153 } 8154 } 8155 } 8156 } 8157 } 8158 8159 final String pkgName = pkg.packageName; 8160 8161 final long scanFileTime = scanFile.lastModified(); 8162 final boolean forceDex = (scanFlags & SCAN_FORCE_DEX) != 0; 8163 pkg.applicationInfo.processName = fixProcessName( 8164 pkg.applicationInfo.packageName, 8165 pkg.applicationInfo.processName, 8166 pkg.applicationInfo.uid); 8167 8168 if (pkg != mPlatformPackage) { 8169 // Get all of our default paths setup 8170 pkg.applicationInfo.initForUser(UserHandle.USER_SYSTEM); 8171 } 8172 8173 final String path = scanFile.getPath(); 8174 final String cpuAbiOverride = deriveAbiOverride(pkg.cpuAbiOverride, pkgSetting); 8175 8176 if ((scanFlags & SCAN_NEW_INSTALL) == 0) { 8177 derivePackageAbi(pkg, scanFile, cpuAbiOverride, true /* extract libs */); 8178 8179 // Some system apps still use directory structure for native libraries 8180 // in which case we might end up not detecting abi solely based on apk 8181 // structure. Try to detect abi based on directory structure. 8182 if (isSystemApp(pkg) && !pkg.isUpdatedSystemApp() && 8183 pkg.applicationInfo.primaryCpuAbi == null) { 8184 setBundledAppAbisAndRoots(pkg, pkgSetting); 8185 setNativeLibraryPaths(pkg); 8186 } 8187 8188 } else { 8189 if ((scanFlags & SCAN_MOVE) != 0) { 8190 // We haven't run dex-opt for this move (since we've moved the compiled output too) 8191 // but we already have this packages package info in the PackageSetting. We just 8192 // use that and derive the native library path based on the new codepath. 8193 pkg.applicationInfo.primaryCpuAbi = pkgSetting.primaryCpuAbiString; 8194 pkg.applicationInfo.secondaryCpuAbi = pkgSetting.secondaryCpuAbiString; 8195 } 8196 8197 // Set native library paths again. For moves, the path will be updated based on the 8198 // ABIs we've determined above. For non-moves, the path will be updated based on the 8199 // ABIs we determined during compilation, but the path will depend on the final 8200 // package path (after the rename away from the stage path). 8201 setNativeLibraryPaths(pkg); 8202 } 8203 8204 // This is a special case for the "system" package, where the ABI is 8205 // dictated by the zygote configuration (and init.rc). We should keep track 8206 // of this ABI so that we can deal with "normal" applications that run under 8207 // the same UID correctly. 8208 if (mPlatformPackage == pkg) { 8209 pkg.applicationInfo.primaryCpuAbi = VMRuntime.getRuntime().is64Bit() ? 8210 Build.SUPPORTED_64_BIT_ABIS[0] : Build.SUPPORTED_32_BIT_ABIS[0]; 8211 } 8212 8213 // If there's a mismatch between the abi-override in the package setting 8214 // and the abiOverride specified for the install. Warn about this because we 8215 // would've already compiled the app without taking the package setting into 8216 // account. 8217 if ((scanFlags & SCAN_NO_DEX) == 0 && (scanFlags & SCAN_NEW_INSTALL) != 0) { 8218 if (cpuAbiOverride == null && pkgSetting.cpuAbiOverrideString != null) { 8219 Slog.w(TAG, "Ignoring persisted ABI override " + cpuAbiOverride + 8220 " for package " + pkg.packageName); 8221 } 8222 } 8223 8224 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 8225 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 8226 pkgSetting.cpuAbiOverrideString = cpuAbiOverride; 8227 8228 // Copy the derived override back to the parsed package, so that we can 8229 // update the package settings accordingly. 8230 pkg.cpuAbiOverride = cpuAbiOverride; 8231 8232 if (DEBUG_ABI_SELECTION) { 8233 Slog.d(TAG, "Resolved nativeLibraryRoot for " + pkg.applicationInfo.packageName 8234 + " to root=" + pkg.applicationInfo.nativeLibraryRootDir + ", isa=" 8235 + pkg.applicationInfo.nativeLibraryRootRequiresIsa); 8236 } 8237 8238 // Push the derived path down into PackageSettings so we know what to 8239 // clean up at uninstall time. 8240 pkgSetting.legacyNativeLibraryPathString = pkg.applicationInfo.nativeLibraryRootDir; 8241 8242 if (DEBUG_ABI_SELECTION) { 8243 Log.d(TAG, "Abis for package[" + pkg.packageName + "] are" + 8244 " primary=" + pkg.applicationInfo.primaryCpuAbi + 8245 " secondary=" + pkg.applicationInfo.secondaryCpuAbi); 8246 } 8247 8248 if ((scanFlags & SCAN_BOOTING) == 0 && pkgSetting.sharedUser != null) { 8249 // We don't do this here during boot because we can do it all 8250 // at once after scanning all existing packages. 8251 // 8252 // We also do this *before* we perform dexopt on this package, so that 8253 // we can avoid redundant dexopts, and also to make sure we've got the 8254 // code and package path correct. 8255 adjustCpuAbisForSharedUserLPw(pkgSetting.sharedUser.packages, 8256 pkg, true /* boot complete */); 8257 } 8258 8259 if (mFactoryTest && pkg.requestedPermissions.contains( 8260 android.Manifest.permission.FACTORY_TEST)) { 8261 pkg.applicationInfo.flags |= ApplicationInfo.FLAG_FACTORY_TEST; 8262 } 8263 8264 ArrayList<PackageParser.Package> clientLibPkgs = null; 8265 8266 if ((scanFlags & SCAN_CHECK_ONLY) != 0) { 8267 if (nonMutatedPs != null) { 8268 synchronized (mPackages) { 8269 mSettings.mPackages.put(nonMutatedPs.name, nonMutatedPs); 8270 } 8271 } 8272 return pkg; 8273 } 8274 8275 // Only privileged apps and updated privileged apps can add child packages. 8276 if (pkg.childPackages != null && !pkg.childPackages.isEmpty()) { 8277 if ((policyFlags & PARSE_IS_PRIVILEGED) == 0) { 8278 throw new PackageManagerException("Only privileged apps and updated " 8279 + "privileged apps can add child packages. Ignoring package " 8280 + pkg.packageName); 8281 } 8282 final int childCount = pkg.childPackages.size(); 8283 for (int i = 0; i < childCount; i++) { 8284 PackageParser.Package childPkg = pkg.childPackages.get(i); 8285 if (mSettings.hasOtherDisabledSystemPkgWithChildLPr(pkg.packageName, 8286 childPkg.packageName)) { 8287 throw new PackageManagerException("Cannot override a child package of " 8288 + "another disabled system app. Ignoring package " + pkg.packageName); 8289 } 8290 } 8291 } 8292 8293 // writer 8294 synchronized (mPackages) { 8295 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 8296 // Only system apps can add new shared libraries. 8297 if (pkg.libraryNames != null) { 8298 for (int i=0; i<pkg.libraryNames.size(); i++) { 8299 String name = pkg.libraryNames.get(i); 8300 boolean allowed = false; 8301 if (pkg.isUpdatedSystemApp()) { 8302 // New library entries can only be added through the 8303 // system image. This is important to get rid of a lot 8304 // of nasty edge cases: for example if we allowed a non- 8305 // system update of the app to add a library, then uninstalling 8306 // the update would make the library go away, and assumptions 8307 // we made such as through app install filtering would now 8308 // have allowed apps on the device which aren't compatible 8309 // with it. Better to just have the restriction here, be 8310 // conservative, and create many fewer cases that can negatively 8311 // impact the user experience. 8312 final PackageSetting sysPs = mSettings 8313 .getDisabledSystemPkgLPr(pkg.packageName); 8314 if (sysPs.pkg != null && sysPs.pkg.libraryNames != null) { 8315 for (int j=0; j<sysPs.pkg.libraryNames.size(); j++) { 8316 if (name.equals(sysPs.pkg.libraryNames.get(j))) { 8317 allowed = true; 8318 break; 8319 } 8320 } 8321 } 8322 } else { 8323 allowed = true; 8324 } 8325 if (allowed) { 8326 if (!mSharedLibraries.containsKey(name)) { 8327 mSharedLibraries.put(name, new SharedLibraryEntry(null, pkg.packageName)); 8328 } else if (!name.equals(pkg.packageName)) { 8329 Slog.w(TAG, "Package " + pkg.packageName + " library " 8330 + name + " already exists; skipping"); 8331 } 8332 } else { 8333 Slog.w(TAG, "Package " + pkg.packageName + " declares lib " 8334 + name + " that is not declared on system image; skipping"); 8335 } 8336 } 8337 if ((scanFlags & SCAN_BOOTING) == 0) { 8338 // If we are not booting, we need to update any applications 8339 // that are clients of our shared library. If we are booting, 8340 // this will all be done once the scan is complete. 8341 clientLibPkgs = updateAllSharedLibrariesLPw(pkg); 8342 } 8343 } 8344 } 8345 } 8346 8347 if ((scanFlags & SCAN_BOOTING) != 0) { 8348 // No apps can run during boot scan, so they don't need to be frozen 8349 } else if ((scanFlags & SCAN_DONT_KILL_APP) != 0) { 8350 // Caller asked to not kill app, so it's probably not frozen 8351 } else if ((scanFlags & SCAN_IGNORE_FROZEN) != 0) { 8352 // Caller asked us to ignore frozen check for some reason; they 8353 // probably didn't know the package name 8354 } else { 8355 // We're doing major surgery on this package, so it better be frozen 8356 // right now to keep it from launching 8357 checkPackageFrozen(pkgName); 8358 } 8359 8360 // Also need to kill any apps that are dependent on the library. 8361 if (clientLibPkgs != null) { 8362 for (int i=0; i<clientLibPkgs.size(); i++) { 8363 PackageParser.Package clientPkg = clientLibPkgs.get(i); 8364 killApplication(clientPkg.applicationInfo.packageName, 8365 clientPkg.applicationInfo.uid, "update lib"); 8366 } 8367 } 8368 8369 // Make sure we're not adding any bogus keyset info 8370 KeySetManagerService ksms = mSettings.mKeySetManagerService; 8371 ksms.assertScannedPackageValid(pkg); 8372 8373 // writer 8374 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 8375 8376 boolean createIdmapFailed = false; 8377 synchronized (mPackages) { 8378 // We don't expect installation to fail beyond this point 8379 8380 // Add the new setting to mSettings 8381 mSettings.insertPackageSettingLPw(pkgSetting, pkg); 8382 // Add the new setting to mPackages 8383 mPackages.put(pkg.applicationInfo.packageName, pkg); 8384 // Make sure we don't accidentally delete its data. 8385 final Iterator<PackageCleanItem> iter = mSettings.mPackagesToBeCleaned.iterator(); 8386 while (iter.hasNext()) { 8387 PackageCleanItem item = iter.next(); 8388 if (pkgName.equals(item.packageName)) { 8389 iter.remove(); 8390 } 8391 } 8392 8393 // Take care of first install / last update times. 8394 if (currentTime != 0) { 8395 if (pkgSetting.firstInstallTime == 0) { 8396 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = currentTime; 8397 } else if ((scanFlags&SCAN_UPDATE_TIME) != 0) { 8398 pkgSetting.lastUpdateTime = currentTime; 8399 } 8400 } else if (pkgSetting.firstInstallTime == 0) { 8401 // We need *something*. Take time time stamp of the file. 8402 pkgSetting.firstInstallTime = pkgSetting.lastUpdateTime = scanFileTime; 8403 } else if ((policyFlags&PackageParser.PARSE_IS_SYSTEM_DIR) != 0) { 8404 if (scanFileTime != pkgSetting.timeStamp) { 8405 // A package on the system image has changed; consider this 8406 // to be an update. 8407 pkgSetting.lastUpdateTime = scanFileTime; 8408 } 8409 } 8410 8411 // Add the package's KeySets to the global KeySetManagerService 8412 ksms.addScannedPackageLPw(pkg); 8413 8414 int N = pkg.providers.size(); 8415 StringBuilder r = null; 8416 int i; 8417 for (i=0; i<N; i++) { 8418 PackageParser.Provider p = pkg.providers.get(i); 8419 p.info.processName = fixProcessName(pkg.applicationInfo.processName, 8420 p.info.processName, pkg.applicationInfo.uid); 8421 mProviders.addProvider(p); 8422 p.syncable = p.info.isSyncable; 8423 if (p.info.authority != null) { 8424 String names[] = p.info.authority.split(";"); 8425 p.info.authority = null; 8426 for (int j = 0; j < names.length; j++) { 8427 if (j == 1 && p.syncable) { 8428 // We only want the first authority for a provider to possibly be 8429 // syncable, so if we already added this provider using a different 8430 // authority clear the syncable flag. We copy the provider before 8431 // changing it because the mProviders object contains a reference 8432 // to a provider that we don't want to change. 8433 // Only do this for the second authority since the resulting provider 8434 // object can be the same for all future authorities for this provider. 8435 p = new PackageParser.Provider(p); 8436 p.syncable = false; 8437 } 8438 if (!mProvidersByAuthority.containsKey(names[j])) { 8439 mProvidersByAuthority.put(names[j], p); 8440 if (p.info.authority == null) { 8441 p.info.authority = names[j]; 8442 } else { 8443 p.info.authority = p.info.authority + ";" + names[j]; 8444 } 8445 if (DEBUG_PACKAGE_SCANNING) { 8446 if ((policyFlags & PackageParser.PARSE_CHATTY) != 0) 8447 Log.d(TAG, "Registered content provider: " + names[j] 8448 + ", className = " + p.info.name + ", isSyncable = " 8449 + p.info.isSyncable); 8450 } 8451 } else { 8452 PackageParser.Provider other = mProvidersByAuthority.get(names[j]); 8453 Slog.w(TAG, "Skipping provider name " + names[j] + 8454 " (in package " + pkg.applicationInfo.packageName + 8455 "): name already used by " 8456 + ((other != null && other.getComponentName() != null) 8457 ? other.getComponentName().getPackageName() : "?")); 8458 } 8459 } 8460 } 8461 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8462 if (r == null) { 8463 r = new StringBuilder(256); 8464 } else { 8465 r.append(' '); 8466 } 8467 r.append(p.info.name); 8468 } 8469 } 8470 if (r != null) { 8471 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Providers: " + r); 8472 } 8473 8474 N = pkg.services.size(); 8475 r = null; 8476 for (i=0; i<N; i++) { 8477 PackageParser.Service s = pkg.services.get(i); 8478 s.info.processName = fixProcessName(pkg.applicationInfo.processName, 8479 s.info.processName, pkg.applicationInfo.uid); 8480 mServices.addService(s); 8481 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8482 if (r == null) { 8483 r = new StringBuilder(256); 8484 } else { 8485 r.append(' '); 8486 } 8487 r.append(s.info.name); 8488 } 8489 } 8490 if (r != null) { 8491 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Services: " + r); 8492 } 8493 8494 N = pkg.receivers.size(); 8495 r = null; 8496 for (i=0; i<N; i++) { 8497 PackageParser.Activity a = pkg.receivers.get(i); 8498 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8499 a.info.processName, pkg.applicationInfo.uid); 8500 mReceivers.addActivity(a, "receiver"); 8501 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8502 if (r == null) { 8503 r = new StringBuilder(256); 8504 } else { 8505 r.append(' '); 8506 } 8507 r.append(a.info.name); 8508 } 8509 } 8510 if (r != null) { 8511 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Receivers: " + r); 8512 } 8513 8514 N = pkg.activities.size(); 8515 r = null; 8516 for (i=0; i<N; i++) { 8517 PackageParser.Activity a = pkg.activities.get(i); 8518 a.info.processName = fixProcessName(pkg.applicationInfo.processName, 8519 a.info.processName, pkg.applicationInfo.uid); 8520 mActivities.addActivity(a, "activity"); 8521 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8522 if (r == null) { 8523 r = new StringBuilder(256); 8524 } else { 8525 r.append(' '); 8526 } 8527 r.append(a.info.name); 8528 } 8529 } 8530 if (r != null) { 8531 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Activities: " + r); 8532 } 8533 8534 N = pkg.permissionGroups.size(); 8535 r = null; 8536 for (i=0; i<N; i++) { 8537 PackageParser.PermissionGroup pg = pkg.permissionGroups.get(i); 8538 PackageParser.PermissionGroup cur = mPermissionGroups.get(pg.info.name); 8539 if (cur == null) { 8540 mPermissionGroups.put(pg.info.name, pg); 8541 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8542 if (r == null) { 8543 r = new StringBuilder(256); 8544 } else { 8545 r.append(' '); 8546 } 8547 r.append(pg.info.name); 8548 } 8549 } else { 8550 Slog.w(TAG, "Permission group " + pg.info.name + " from package " 8551 + pg.info.packageName + " ignored: original from " 8552 + cur.info.packageName); 8553 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8554 if (r == null) { 8555 r = new StringBuilder(256); 8556 } else { 8557 r.append(' '); 8558 } 8559 r.append("DUP:"); 8560 r.append(pg.info.name); 8561 } 8562 } 8563 } 8564 if (r != null) { 8565 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permission Groups: " + r); 8566 } 8567 8568 N = pkg.permissions.size(); 8569 r = null; 8570 for (i=0; i<N; i++) { 8571 PackageParser.Permission p = pkg.permissions.get(i); 8572 8573 // Assume by default that we did not install this permission into the system. 8574 p.info.flags &= ~PermissionInfo.FLAG_INSTALLED; 8575 8576 // Now that permission groups have a special meaning, we ignore permission 8577 // groups for legacy apps to prevent unexpected behavior. In particular, 8578 // permissions for one app being granted to someone just becase they happen 8579 // to be in a group defined by another app (before this had no implications). 8580 if (pkg.applicationInfo.targetSdkVersion > Build.VERSION_CODES.LOLLIPOP_MR1) { 8581 p.group = mPermissionGroups.get(p.info.group); 8582 // Warn for a permission in an unknown group. 8583 if (p.info.group != null && p.group == null) { 8584 Slog.w(TAG, "Permission " + p.info.name + " from package " 8585 + p.info.packageName + " in an unknown group " + p.info.group); 8586 } 8587 } 8588 8589 ArrayMap<String, BasePermission> permissionMap = 8590 p.tree ? mSettings.mPermissionTrees 8591 : mSettings.mPermissions; 8592 BasePermission bp = permissionMap.get(p.info.name); 8593 8594 // Allow system apps to redefine non-system permissions 8595 if (bp != null && !Objects.equals(bp.sourcePackage, p.info.packageName)) { 8596 final boolean currentOwnerIsSystem = (bp.perm != null 8597 && isSystemApp(bp.perm.owner)); 8598 if (isSystemApp(p.owner)) { 8599 if (bp.type == BasePermission.TYPE_BUILTIN && bp.perm == null) { 8600 // It's a built-in permission and no owner, take ownership now 8601 bp.packageSetting = pkgSetting; 8602 bp.perm = p; 8603 bp.uid = pkg.applicationInfo.uid; 8604 bp.sourcePackage = p.info.packageName; 8605 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8606 } else if (!currentOwnerIsSystem) { 8607 String msg = "New decl " + p.owner + " of permission " 8608 + p.info.name + " is system; overriding " + bp.sourcePackage; 8609 reportSettingsProblem(Log.WARN, msg); 8610 bp = null; 8611 } 8612 } 8613 } 8614 8615 if (bp == null) { 8616 bp = new BasePermission(p.info.name, p.info.packageName, 8617 BasePermission.TYPE_NORMAL); 8618 permissionMap.put(p.info.name, bp); 8619 } 8620 8621 if (bp.perm == null) { 8622 if (bp.sourcePackage == null 8623 || bp.sourcePackage.equals(p.info.packageName)) { 8624 BasePermission tree = findPermissionTreeLP(p.info.name); 8625 if (tree == null 8626 || tree.sourcePackage.equals(p.info.packageName)) { 8627 bp.packageSetting = pkgSetting; 8628 bp.perm = p; 8629 bp.uid = pkg.applicationInfo.uid; 8630 bp.sourcePackage = p.info.packageName; 8631 p.info.flags |= PermissionInfo.FLAG_INSTALLED; 8632 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8633 if (r == null) { 8634 r = new StringBuilder(256); 8635 } else { 8636 r.append(' '); 8637 } 8638 r.append(p.info.name); 8639 } 8640 } else { 8641 Slog.w(TAG, "Permission " + p.info.name + " from package " 8642 + p.info.packageName + " ignored: base tree " 8643 + tree.name + " is from package " 8644 + tree.sourcePackage); 8645 } 8646 } else { 8647 Slog.w(TAG, "Permission " + p.info.name + " from package " 8648 + p.info.packageName + " ignored: original from " 8649 + bp.sourcePackage); 8650 } 8651 } else if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8652 if (r == null) { 8653 r = new StringBuilder(256); 8654 } else { 8655 r.append(' '); 8656 } 8657 r.append("DUP:"); 8658 r.append(p.info.name); 8659 } 8660 if (bp.perm == p) { 8661 bp.protectionLevel = p.info.protectionLevel; 8662 } 8663 } 8664 8665 if (r != null) { 8666 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Permissions: " + r); 8667 } 8668 8669 N = pkg.instrumentation.size(); 8670 r = null; 8671 for (i=0; i<N; i++) { 8672 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 8673 a.info.packageName = pkg.applicationInfo.packageName; 8674 a.info.sourceDir = pkg.applicationInfo.sourceDir; 8675 a.info.publicSourceDir = pkg.applicationInfo.publicSourceDir; 8676 a.info.splitSourceDirs = pkg.applicationInfo.splitSourceDirs; 8677 a.info.splitPublicSourceDirs = pkg.applicationInfo.splitPublicSourceDirs; 8678 a.info.dataDir = pkg.applicationInfo.dataDir; 8679 a.info.deviceProtectedDataDir = pkg.applicationInfo.deviceProtectedDataDir; 8680 a.info.credentialProtectedDataDir = pkg.applicationInfo.credentialProtectedDataDir; 8681 8682 // TODO: Update instrumentation.nativeLibraryDir as well ? Does it 8683 // need other information about the application, like the ABI and what not ? 8684 a.info.nativeLibraryDir = pkg.applicationInfo.nativeLibraryDir; 8685 mInstrumentation.put(a.getComponentName(), a); 8686 if ((policyFlags&PackageParser.PARSE_CHATTY) != 0) { 8687 if (r == null) { 8688 r = new StringBuilder(256); 8689 } else { 8690 r.append(' '); 8691 } 8692 r.append(a.info.name); 8693 } 8694 } 8695 if (r != null) { 8696 if (DEBUG_PACKAGE_SCANNING) Log.d(TAG, " Instrumentation: " + r); 8697 } 8698 8699 if (pkg.protectedBroadcasts != null) { 8700 N = pkg.protectedBroadcasts.size(); 8701 for (i=0; i<N; i++) { 8702 mProtectedBroadcasts.add(pkg.protectedBroadcasts.get(i)); 8703 } 8704 } 8705 8706 pkgSetting.setTimeStamp(scanFileTime); 8707 8708 // Create idmap files for pairs of (packages, overlay packages). 8709 // Note: "android", ie framework-res.apk, is handled by native layers. 8710 if (pkg.mOverlayTarget != null) { 8711 // This is an overlay package. 8712 if (pkg.mOverlayTarget != null && !pkg.mOverlayTarget.equals("android")) { 8713 if (!mOverlays.containsKey(pkg.mOverlayTarget)) { 8714 mOverlays.put(pkg.mOverlayTarget, 8715 new ArrayMap<String, PackageParser.Package>()); 8716 } 8717 ArrayMap<String, PackageParser.Package> map = mOverlays.get(pkg.mOverlayTarget); 8718 map.put(pkg.packageName, pkg); 8719 PackageParser.Package orig = mPackages.get(pkg.mOverlayTarget); 8720 if (orig != null && !createIdmapForPackagePairLI(orig, pkg)) { 8721 createIdmapFailed = true; 8722 } 8723 } 8724 } else if (mOverlays.containsKey(pkg.packageName) && 8725 !pkg.packageName.equals("android")) { 8726 // This is a regular package, with one or more known overlay packages. 8727 createIdmapsForPackageLI(pkg); 8728 } 8729 } 8730 8731 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 8732 8733 if (createIdmapFailed) { 8734 throw new PackageManagerException(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 8735 "scanPackageLI failed to createIdmap"); 8736 } 8737 return pkg; 8738 } 8739 8740 /** 8741 * Derive the ABI of a non-system package located at {@code scanFile}. This information 8742 * is derived purely on the basis of the contents of {@code scanFile} and 8743 * {@code cpuAbiOverride}. 8744 * 8745 * If {@code extractLibs} is true, native libraries are extracted from the app if required. 8746 */ 8747 private void derivePackageAbi(PackageParser.Package pkg, File scanFile, 8748 String cpuAbiOverride, boolean extractLibs) 8749 throws PackageManagerException { 8750 // TODO: We can probably be smarter about this stuff. For installed apps, 8751 // we can calculate this information at install time once and for all. For 8752 // system apps, we can probably assume that this information doesn't change 8753 // after the first boot scan. As things stand, we do lots of unnecessary work. 8754 8755 // Give ourselves some initial paths; we'll come back for another 8756 // pass once we've determined ABI below. 8757 setNativeLibraryPaths(pkg); 8758 8759 // We would never need to extract libs for forward-locked and external packages, 8760 // since the container service will do it for us. We shouldn't attempt to 8761 // extract libs from system app when it was not updated. 8762 if (pkg.isForwardLocked() || pkg.applicationInfo.isExternalAsec() || 8763 (isSystemApp(pkg) && !pkg.isUpdatedSystemApp())) { 8764 extractLibs = false; 8765 } 8766 8767 final String nativeLibraryRootStr = pkg.applicationInfo.nativeLibraryRootDir; 8768 final boolean useIsaSpecificSubdirs = pkg.applicationInfo.nativeLibraryRootRequiresIsa; 8769 8770 NativeLibraryHelper.Handle handle = null; 8771 try { 8772 handle = NativeLibraryHelper.Handle.create(pkg); 8773 // TODO(multiArch): This can be null for apps that didn't go through the 8774 // usual installation process. We can calculate it again, like we 8775 // do during install time. 8776 // 8777 // TODO(multiArch): Why do we need to rescan ASEC apps again ? It seems totally 8778 // unnecessary. 8779 final File nativeLibraryRoot = new File(nativeLibraryRootStr); 8780 8781 // Null out the abis so that they can be recalculated. 8782 pkg.applicationInfo.primaryCpuAbi = null; 8783 pkg.applicationInfo.secondaryCpuAbi = null; 8784 if (isMultiArch(pkg.applicationInfo)) { 8785 // Warn if we've set an abiOverride for multi-lib packages.. 8786 // By definition, we need to copy both 32 and 64 bit libraries for 8787 // such packages. 8788 if (pkg.cpuAbiOverride != null 8789 && !NativeLibraryHelper.CLEAR_ABI_OVERRIDE.equals(pkg.cpuAbiOverride)) { 8790 Slog.w(TAG, "Ignoring abiOverride for multi arch application."); 8791 } 8792 8793 int abi32 = PackageManager.NO_NATIVE_LIBRARIES; 8794 int abi64 = PackageManager.NO_NATIVE_LIBRARIES; 8795 if (Build.SUPPORTED_32_BIT_ABIS.length > 0) { 8796 if (extractLibs) { 8797 abi32 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8798 nativeLibraryRoot, Build.SUPPORTED_32_BIT_ABIS, 8799 useIsaSpecificSubdirs); 8800 } else { 8801 abi32 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_32_BIT_ABIS); 8802 } 8803 } 8804 8805 maybeThrowExceptionForMultiArchCopy( 8806 "Error unpackaging 32 bit native libs for multiarch app.", abi32); 8807 8808 if (Build.SUPPORTED_64_BIT_ABIS.length > 0) { 8809 if (extractLibs) { 8810 abi64 = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8811 nativeLibraryRoot, Build.SUPPORTED_64_BIT_ABIS, 8812 useIsaSpecificSubdirs); 8813 } else { 8814 abi64 = NativeLibraryHelper.findSupportedAbi(handle, Build.SUPPORTED_64_BIT_ABIS); 8815 } 8816 } 8817 8818 maybeThrowExceptionForMultiArchCopy( 8819 "Error unpackaging 64 bit native libs for multiarch app.", abi64); 8820 8821 if (abi64 >= 0) { 8822 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[abi64]; 8823 } 8824 8825 if (abi32 >= 0) { 8826 final String abi = Build.SUPPORTED_32_BIT_ABIS[abi32]; 8827 if (abi64 >= 0) { 8828 if (pkg.use32bitAbi) { 8829 pkg.applicationInfo.secondaryCpuAbi = pkg.applicationInfo.primaryCpuAbi; 8830 pkg.applicationInfo.primaryCpuAbi = abi; 8831 } else { 8832 pkg.applicationInfo.secondaryCpuAbi = abi; 8833 } 8834 } else { 8835 pkg.applicationInfo.primaryCpuAbi = abi; 8836 } 8837 } 8838 8839 } else { 8840 String[] abiList = (cpuAbiOverride != null) ? 8841 new String[] { cpuAbiOverride } : Build.SUPPORTED_ABIS; 8842 8843 // Enable gross and lame hacks for apps that are built with old 8844 // SDK tools. We must scan their APKs for renderscript bitcode and 8845 // not launch them if it's present. Don't bother checking on devices 8846 // that don't have 64 bit support. 8847 boolean needsRenderScriptOverride = false; 8848 if (Build.SUPPORTED_64_BIT_ABIS.length > 0 && cpuAbiOverride == null && 8849 NativeLibraryHelper.hasRenderscriptBitcode(handle)) { 8850 abiList = Build.SUPPORTED_32_BIT_ABIS; 8851 needsRenderScriptOverride = true; 8852 } 8853 8854 final int copyRet; 8855 if (extractLibs) { 8856 copyRet = NativeLibraryHelper.copyNativeBinariesForSupportedAbi(handle, 8857 nativeLibraryRoot, abiList, useIsaSpecificSubdirs); 8858 } else { 8859 copyRet = NativeLibraryHelper.findSupportedAbi(handle, abiList); 8860 } 8861 8862 if (copyRet < 0 && copyRet != PackageManager.NO_NATIVE_LIBRARIES) { 8863 throw new PackageManagerException(INSTALL_FAILED_INTERNAL_ERROR, 8864 "Error unpackaging native libs for app, errorCode=" + copyRet); 8865 } 8866 8867 if (copyRet >= 0) { 8868 pkg.applicationInfo.primaryCpuAbi = abiList[copyRet]; 8869 } else if (copyRet == PackageManager.NO_NATIVE_LIBRARIES && cpuAbiOverride != null) { 8870 pkg.applicationInfo.primaryCpuAbi = cpuAbiOverride; 8871 } else if (needsRenderScriptOverride) { 8872 pkg.applicationInfo.primaryCpuAbi = abiList[0]; 8873 } 8874 } 8875 } catch (IOException ioe) { 8876 Slog.e(TAG, "Unable to get canonical file " + ioe.toString()); 8877 } finally { 8878 IoUtils.closeQuietly(handle); 8879 } 8880 8881 // Now that we've calculated the ABIs and determined if it's an internal app, 8882 // we will go ahead and populate the nativeLibraryPath. 8883 setNativeLibraryPaths(pkg); 8884 } 8885 8886 /** 8887 * Adjusts ABIs for a set of packages belonging to a shared user so that they all match. 8888 * i.e, so that all packages can be run inside a single process if required. 8889 * 8890 * Optionally, callers can pass in a parsed package via {@code newPackage} in which case 8891 * this function will either try and make the ABI for all packages in {@code packagesForUser} 8892 * match {@code scannedPackage} or will update the ABI of {@code scannedPackage} to match 8893 * the ABI selected for {@code packagesForUser}. This variant is used when installing or 8894 * updating a package that belongs to a shared user. 8895 * 8896 * NOTE: We currently only match for the primary CPU abi string. Matching the secondary 8897 * adds unnecessary complexity. 8898 */ 8899 private void adjustCpuAbisForSharedUserLPw(Set<PackageSetting> packagesForUser, 8900 PackageParser.Package scannedPackage, boolean bootComplete) { 8901 String requiredInstructionSet = null; 8902 if (scannedPackage != null && scannedPackage.applicationInfo.primaryCpuAbi != null) { 8903 requiredInstructionSet = VMRuntime.getInstructionSet( 8904 scannedPackage.applicationInfo.primaryCpuAbi); 8905 } 8906 8907 PackageSetting requirer = null; 8908 for (PackageSetting ps : packagesForUser) { 8909 // If packagesForUser contains scannedPackage, we skip it. This will happen 8910 // when scannedPackage is an update of an existing package. Without this check, 8911 // we will never be able to change the ABI of any package belonging to a shared 8912 // user, even if it's compatible with other packages. 8913 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8914 if (ps.primaryCpuAbiString == null) { 8915 continue; 8916 } 8917 8918 final String instructionSet = VMRuntime.getInstructionSet(ps.primaryCpuAbiString); 8919 if (requiredInstructionSet != null && !instructionSet.equals(requiredInstructionSet)) { 8920 // We have a mismatch between instruction sets (say arm vs arm64) warn about 8921 // this but there's not much we can do. 8922 String errorMessage = "Instruction set mismatch, " 8923 + ((requirer == null) ? "[caller]" : requirer) 8924 + " requires " + requiredInstructionSet + " whereas " + ps 8925 + " requires " + instructionSet; 8926 Slog.w(TAG, errorMessage); 8927 } 8928 8929 if (requiredInstructionSet == null) { 8930 requiredInstructionSet = instructionSet; 8931 requirer = ps; 8932 } 8933 } 8934 } 8935 8936 if (requiredInstructionSet != null) { 8937 String adjustedAbi; 8938 if (requirer != null) { 8939 // requirer != null implies that either scannedPackage was null or that scannedPackage 8940 // did not require an ABI, in which case we have to adjust scannedPackage to match 8941 // the ABI of the set (which is the same as requirer's ABI) 8942 adjustedAbi = requirer.primaryCpuAbiString; 8943 if (scannedPackage != null) { 8944 scannedPackage.applicationInfo.primaryCpuAbi = adjustedAbi; 8945 } 8946 } else { 8947 // requirer == null implies that we're updating all ABIs in the set to 8948 // match scannedPackage. 8949 adjustedAbi = scannedPackage.applicationInfo.primaryCpuAbi; 8950 } 8951 8952 for (PackageSetting ps : packagesForUser) { 8953 if (scannedPackage == null || !scannedPackage.packageName.equals(ps.name)) { 8954 if (ps.primaryCpuAbiString != null) { 8955 continue; 8956 } 8957 8958 ps.primaryCpuAbiString = adjustedAbi; 8959 if (ps.pkg != null && ps.pkg.applicationInfo != null && 8960 !TextUtils.equals(adjustedAbi, ps.pkg.applicationInfo.primaryCpuAbi)) { 8961 ps.pkg.applicationInfo.primaryCpuAbi = adjustedAbi; 8962 Slog.i(TAG, "Adjusting ABI for " + ps.name + " to " + adjustedAbi 8963 + " (requirer=" 8964 + (requirer == null ? "null" : requirer.pkg.packageName) 8965 + ", scannedPackage=" 8966 + (scannedPackage != null ? scannedPackage.packageName : "null") 8967 + ")"); 8968 try { 8969 mInstaller.rmdex(ps.codePathString, 8970 getDexCodeInstructionSet(getPreferredInstructionSet())); 8971 } catch (InstallerException ignored) { 8972 } 8973 } 8974 } 8975 } 8976 } 8977 } 8978 8979 private void setUpCustomResolverActivity(PackageParser.Package pkg) { 8980 synchronized (mPackages) { 8981 mResolverReplaced = true; 8982 // Set up information for custom user intent resolution activity. 8983 mResolveActivity.applicationInfo = pkg.applicationInfo; 8984 mResolveActivity.name = mCustomResolverComponentName.getClassName(); 8985 mResolveActivity.packageName = pkg.applicationInfo.packageName; 8986 mResolveActivity.processName = pkg.applicationInfo.packageName; 8987 mResolveActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 8988 mResolveActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 8989 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 8990 mResolveActivity.theme = 0; 8991 mResolveActivity.exported = true; 8992 mResolveActivity.enabled = true; 8993 mResolveInfo.activityInfo = mResolveActivity; 8994 mResolveInfo.priority = 0; 8995 mResolveInfo.preferredOrder = 0; 8996 mResolveInfo.match = 0; 8997 mResolveComponentName = mCustomResolverComponentName; 8998 Slog.i(TAG, "Replacing default ResolverActivity with custom activity: " + 8999 mResolveComponentName); 9000 } 9001 } 9002 9003 private void setUpEphemeralInstallerActivityLP(ComponentName installerComponent) { 9004 final PackageParser.Package pkg = mPackages.get(installerComponent.getPackageName()); 9005 9006 // Set up information for ephemeral installer activity 9007 mEphemeralInstallerActivity.applicationInfo = pkg.applicationInfo; 9008 mEphemeralInstallerActivity.name = mEphemeralInstallerComponent.getClassName(); 9009 mEphemeralInstallerActivity.packageName = pkg.applicationInfo.packageName; 9010 mEphemeralInstallerActivity.processName = pkg.applicationInfo.packageName; 9011 mEphemeralInstallerActivity.launchMode = ActivityInfo.LAUNCH_MULTIPLE; 9012 mEphemeralInstallerActivity.flags = ActivityInfo.FLAG_EXCLUDE_FROM_RECENTS | 9013 ActivityInfo.FLAG_FINISH_ON_CLOSE_SYSTEM_DIALOGS; 9014 mEphemeralInstallerActivity.theme = 0; 9015 mEphemeralInstallerActivity.exported = true; 9016 mEphemeralInstallerActivity.enabled = true; 9017 mEphemeralInstallerInfo.activityInfo = mEphemeralInstallerActivity; 9018 mEphemeralInstallerInfo.priority = 0; 9019 mEphemeralInstallerInfo.preferredOrder = 0; 9020 mEphemeralInstallerInfo.match = 0; 9021 9022 if (DEBUG_EPHEMERAL) { 9023 Slog.d(TAG, "Set ephemeral installer activity: " + mEphemeralInstallerComponent); 9024 } 9025 } 9026 9027 private static String calculateBundledApkRoot(final String codePathString) { 9028 final File codePath = new File(codePathString); 9029 final File codeRoot; 9030 if (FileUtils.contains(Environment.getRootDirectory(), codePath)) { 9031 codeRoot = Environment.getRootDirectory(); 9032 } else if (FileUtils.contains(Environment.getOemDirectory(), codePath)) { 9033 codeRoot = Environment.getOemDirectory(); 9034 } else if (FileUtils.contains(Environment.getVendorDirectory(), codePath)) { 9035 codeRoot = Environment.getVendorDirectory(); 9036 } else { 9037 // Unrecognized code path; take its top real segment as the apk root: 9038 // e.g. /something/app/blah.apk => /something 9039 try { 9040 File f = codePath.getCanonicalFile(); 9041 File parent = f.getParentFile(); // non-null because codePath is a file 9042 File tmp; 9043 while ((tmp = parent.getParentFile()) != null) { 9044 f = parent; 9045 parent = tmp; 9046 } 9047 codeRoot = f; 9048 Slog.w(TAG, "Unrecognized code path " 9049 + codePath + " - using " + codeRoot); 9050 } catch (IOException e) { 9051 // Can't canonicalize the code path -- shenanigans? 9052 Slog.w(TAG, "Can't canonicalize code path " + codePath); 9053 return Environment.getRootDirectory().getPath(); 9054 } 9055 } 9056 return codeRoot.getPath(); 9057 } 9058 9059 /** 9060 * Derive and set the location of native libraries for the given package, 9061 * which varies depending on where and how the package was installed. 9062 */ 9063 private void setNativeLibraryPaths(PackageParser.Package pkg) { 9064 final ApplicationInfo info = pkg.applicationInfo; 9065 final String codePath = pkg.codePath; 9066 final File codeFile = new File(codePath); 9067 final boolean bundledApp = info.isSystemApp() && !info.isUpdatedSystemApp(); 9068 final boolean asecApp = info.isForwardLocked() || info.isExternalAsec(); 9069 9070 info.nativeLibraryRootDir = null; 9071 info.nativeLibraryRootRequiresIsa = false; 9072 info.nativeLibraryDir = null; 9073 info.secondaryNativeLibraryDir = null; 9074 9075 if (isApkFile(codeFile)) { 9076 // Monolithic install 9077 if (bundledApp) { 9078 // If "/system/lib64/apkname" exists, assume that is the per-package 9079 // native library directory to use; otherwise use "/system/lib/apkname". 9080 final String apkRoot = calculateBundledApkRoot(info.sourceDir); 9081 final boolean is64Bit = VMRuntime.is64BitInstructionSet( 9082 getPrimaryInstructionSet(info)); 9083 9084 // This is a bundled system app so choose the path based on the ABI. 9085 // if it's a 64 bit abi, use lib64 otherwise use lib32. Note that this 9086 // is just the default path. 9087 final String apkName = deriveCodePathName(codePath); 9088 final String libDir = is64Bit ? LIB64_DIR_NAME : LIB_DIR_NAME; 9089 info.nativeLibraryRootDir = Environment.buildPath(new File(apkRoot), libDir, 9090 apkName).getAbsolutePath(); 9091 9092 if (info.secondaryCpuAbi != null) { 9093 final String secondaryLibDir = is64Bit ? LIB_DIR_NAME : LIB64_DIR_NAME; 9094 info.secondaryNativeLibraryDir = Environment.buildPath(new File(apkRoot), 9095 secondaryLibDir, apkName).getAbsolutePath(); 9096 } 9097 } else if (asecApp) { 9098 info.nativeLibraryRootDir = new File(codeFile.getParentFile(), LIB_DIR_NAME) 9099 .getAbsolutePath(); 9100 } else { 9101 final String apkName = deriveCodePathName(codePath); 9102 info.nativeLibraryRootDir = new File(mAppLib32InstallDir, apkName) 9103 .getAbsolutePath(); 9104 } 9105 9106 info.nativeLibraryRootRequiresIsa = false; 9107 info.nativeLibraryDir = info.nativeLibraryRootDir; 9108 } else { 9109 // Cluster install 9110 info.nativeLibraryRootDir = new File(codeFile, LIB_DIR_NAME).getAbsolutePath(); 9111 info.nativeLibraryRootRequiresIsa = true; 9112 9113 info.nativeLibraryDir = new File(info.nativeLibraryRootDir, 9114 getPrimaryInstructionSet(info)).getAbsolutePath(); 9115 9116 if (info.secondaryCpuAbi != null) { 9117 info.secondaryNativeLibraryDir = new File(info.nativeLibraryRootDir, 9118 VMRuntime.getInstructionSet(info.secondaryCpuAbi)).getAbsolutePath(); 9119 } 9120 } 9121 } 9122 9123 /** 9124 * Calculate the abis and roots for a bundled app. These can uniquely 9125 * be determined from the contents of the system partition, i.e whether 9126 * it contains 64 or 32 bit shared libraries etc. We do not validate any 9127 * of this information, and instead assume that the system was built 9128 * sensibly. 9129 */ 9130 private void setBundledAppAbisAndRoots(PackageParser.Package pkg, 9131 PackageSetting pkgSetting) { 9132 final String apkName = deriveCodePathName(pkg.applicationInfo.getCodePath()); 9133 9134 // If "/system/lib64/apkname" exists, assume that is the per-package 9135 // native library directory to use; otherwise use "/system/lib/apkname". 9136 final String apkRoot = calculateBundledApkRoot(pkg.applicationInfo.sourceDir); 9137 setBundledAppAbi(pkg, apkRoot, apkName); 9138 // pkgSetting might be null during rescan following uninstall of updates 9139 // to a bundled app, so accommodate that possibility. The settings in 9140 // that case will be established later from the parsed package. 9141 // 9142 // If the settings aren't null, sync them up with what we've just derived. 9143 // note that apkRoot isn't stored in the package settings. 9144 if (pkgSetting != null) { 9145 pkgSetting.primaryCpuAbiString = pkg.applicationInfo.primaryCpuAbi; 9146 pkgSetting.secondaryCpuAbiString = pkg.applicationInfo.secondaryCpuAbi; 9147 } 9148 } 9149 9150 /** 9151 * Deduces the ABI of a bundled app and sets the relevant fields on the 9152 * parsed pkg object. 9153 * 9154 * @param apkRoot the root of the installed apk, something like {@code /system} or {@code /oem} 9155 * under which system libraries are installed. 9156 * @param apkName the name of the installed package. 9157 */ 9158 private static void setBundledAppAbi(PackageParser.Package pkg, String apkRoot, String apkName) { 9159 final File codeFile = new File(pkg.codePath); 9160 9161 final boolean has64BitLibs; 9162 final boolean has32BitLibs; 9163 if (isApkFile(codeFile)) { 9164 // Monolithic install 9165 has64BitLibs = (new File(apkRoot, new File(LIB64_DIR_NAME, apkName).getPath())).exists(); 9166 has32BitLibs = (new File(apkRoot, new File(LIB_DIR_NAME, apkName).getPath())).exists(); 9167 } else { 9168 // Cluster install 9169 final File rootDir = new File(codeFile, LIB_DIR_NAME); 9170 if (!ArrayUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS) 9171 && !TextUtils.isEmpty(Build.SUPPORTED_64_BIT_ABIS[0])) { 9172 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_64_BIT_ABIS[0]); 9173 has64BitLibs = (new File(rootDir, isa)).exists(); 9174 } else { 9175 has64BitLibs = false; 9176 } 9177 if (!ArrayUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS) 9178 && !TextUtils.isEmpty(Build.SUPPORTED_32_BIT_ABIS[0])) { 9179 final String isa = VMRuntime.getInstructionSet(Build.SUPPORTED_32_BIT_ABIS[0]); 9180 has32BitLibs = (new File(rootDir, isa)).exists(); 9181 } else { 9182 has32BitLibs = false; 9183 } 9184 } 9185 9186 if (has64BitLibs && !has32BitLibs) { 9187 // The package has 64 bit libs, but not 32 bit libs. Its primary 9188 // ABI should be 64 bit. We can safely assume here that the bundled 9189 // native libraries correspond to the most preferred ABI in the list. 9190 9191 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9192 pkg.applicationInfo.secondaryCpuAbi = null; 9193 } else if (has32BitLibs && !has64BitLibs) { 9194 // The package has 32 bit libs but not 64 bit libs. Its primary 9195 // ABI should be 32 bit. 9196 9197 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9198 pkg.applicationInfo.secondaryCpuAbi = null; 9199 } else if (has32BitLibs && has64BitLibs) { 9200 // The application has both 64 and 32 bit bundled libraries. We check 9201 // here that the app declares multiArch support, and warn if it doesn't. 9202 // 9203 // We will be lenient here and record both ABIs. The primary will be the 9204 // ABI that's higher on the list, i.e, a device that's configured to prefer 9205 // 64 bit apps will see a 64 bit primary ABI, 9206 9207 if ((pkg.applicationInfo.flags & ApplicationInfo.FLAG_MULTIARCH) == 0) { 9208 Slog.e(TAG, "Package " + pkg + " has multiple bundled libs, but is not multiarch."); 9209 } 9210 9211 if (VMRuntime.is64BitInstructionSet(getPreferredInstructionSet())) { 9212 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9213 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9214 } else { 9215 pkg.applicationInfo.primaryCpuAbi = Build.SUPPORTED_32_BIT_ABIS[0]; 9216 pkg.applicationInfo.secondaryCpuAbi = Build.SUPPORTED_64_BIT_ABIS[0]; 9217 } 9218 } else { 9219 pkg.applicationInfo.primaryCpuAbi = null; 9220 pkg.applicationInfo.secondaryCpuAbi = null; 9221 } 9222 } 9223 9224 private void killApplication(String pkgName, int appId, String reason) { 9225 // Request the ActivityManager to kill the process(only for existing packages) 9226 // so that we do not end up in a confused state while the user is still using the older 9227 // version of the application while the new one gets installed. 9228 final long token = Binder.clearCallingIdentity(); 9229 try { 9230 IActivityManager am = ActivityManagerNative.getDefault(); 9231 if (am != null) { 9232 try { 9233 am.killApplicationWithAppId(pkgName, appId, reason); 9234 } catch (RemoteException e) { 9235 } 9236 } 9237 } finally { 9238 Binder.restoreCallingIdentity(token); 9239 } 9240 } 9241 9242 private void removePackageLI(PackageParser.Package pkg, boolean chatty) { 9243 // Remove the parent package setting 9244 PackageSetting ps = (PackageSetting) pkg.mExtras; 9245 if (ps != null) { 9246 removePackageLI(ps, chatty); 9247 } 9248 // Remove the child package setting 9249 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9250 for (int i = 0; i < childCount; i++) { 9251 PackageParser.Package childPkg = pkg.childPackages.get(i); 9252 ps = (PackageSetting) childPkg.mExtras; 9253 if (ps != null) { 9254 removePackageLI(ps, chatty); 9255 } 9256 } 9257 } 9258 9259 void removePackageLI(PackageSetting ps, boolean chatty) { 9260 if (DEBUG_INSTALL) { 9261 if (chatty) 9262 Log.d(TAG, "Removing package " + ps.name); 9263 } 9264 9265 // writer 9266 synchronized (mPackages) { 9267 mPackages.remove(ps.name); 9268 final PackageParser.Package pkg = ps.pkg; 9269 if (pkg != null) { 9270 cleanPackageDataStructuresLILPw(pkg, chatty); 9271 } 9272 } 9273 } 9274 9275 void removeInstalledPackageLI(PackageParser.Package pkg, boolean chatty) { 9276 if (DEBUG_INSTALL) { 9277 if (chatty) 9278 Log.d(TAG, "Removing package " + pkg.applicationInfo.packageName); 9279 } 9280 9281 // writer 9282 synchronized (mPackages) { 9283 // Remove the parent package 9284 mPackages.remove(pkg.applicationInfo.packageName); 9285 cleanPackageDataStructuresLILPw(pkg, chatty); 9286 9287 // Remove the child packages 9288 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9289 for (int i = 0; i < childCount; i++) { 9290 PackageParser.Package childPkg = pkg.childPackages.get(i); 9291 mPackages.remove(childPkg.applicationInfo.packageName); 9292 cleanPackageDataStructuresLILPw(childPkg, chatty); 9293 } 9294 } 9295 } 9296 9297 void cleanPackageDataStructuresLILPw(PackageParser.Package pkg, boolean chatty) { 9298 int N = pkg.providers.size(); 9299 StringBuilder r = null; 9300 int i; 9301 for (i=0; i<N; i++) { 9302 PackageParser.Provider p = pkg.providers.get(i); 9303 mProviders.removeProvider(p); 9304 if (p.info.authority == null) { 9305 9306 /* There was another ContentProvider with this authority when 9307 * this app was installed so this authority is null, 9308 * Ignore it as we don't have to unregister the provider. 9309 */ 9310 continue; 9311 } 9312 String names[] = p.info.authority.split(";"); 9313 for (int j = 0; j < names.length; j++) { 9314 if (mProvidersByAuthority.get(names[j]) == p) { 9315 mProvidersByAuthority.remove(names[j]); 9316 if (DEBUG_REMOVE) { 9317 if (chatty) 9318 Log.d(TAG, "Unregistered content provider: " + names[j] 9319 + ", className = " + p.info.name + ", isSyncable = " 9320 + p.info.isSyncable); 9321 } 9322 } 9323 } 9324 if (DEBUG_REMOVE && chatty) { 9325 if (r == null) { 9326 r = new StringBuilder(256); 9327 } else { 9328 r.append(' '); 9329 } 9330 r.append(p.info.name); 9331 } 9332 } 9333 if (r != null) { 9334 if (DEBUG_REMOVE) Log.d(TAG, " Providers: " + r); 9335 } 9336 9337 N = pkg.services.size(); 9338 r = null; 9339 for (i=0; i<N; i++) { 9340 PackageParser.Service s = pkg.services.get(i); 9341 mServices.removeService(s); 9342 if (chatty) { 9343 if (r == null) { 9344 r = new StringBuilder(256); 9345 } else { 9346 r.append(' '); 9347 } 9348 r.append(s.info.name); 9349 } 9350 } 9351 if (r != null) { 9352 if (DEBUG_REMOVE) Log.d(TAG, " Services: " + r); 9353 } 9354 9355 N = pkg.receivers.size(); 9356 r = null; 9357 for (i=0; i<N; i++) { 9358 PackageParser.Activity a = pkg.receivers.get(i); 9359 mReceivers.removeActivity(a, "receiver"); 9360 if (DEBUG_REMOVE && chatty) { 9361 if (r == null) { 9362 r = new StringBuilder(256); 9363 } else { 9364 r.append(' '); 9365 } 9366 r.append(a.info.name); 9367 } 9368 } 9369 if (r != null) { 9370 if (DEBUG_REMOVE) Log.d(TAG, " Receivers: " + r); 9371 } 9372 9373 N = pkg.activities.size(); 9374 r = null; 9375 for (i=0; i<N; i++) { 9376 PackageParser.Activity a = pkg.activities.get(i); 9377 mActivities.removeActivity(a, "activity"); 9378 if (DEBUG_REMOVE && chatty) { 9379 if (r == null) { 9380 r = new StringBuilder(256); 9381 } else { 9382 r.append(' '); 9383 } 9384 r.append(a.info.name); 9385 } 9386 } 9387 if (r != null) { 9388 if (DEBUG_REMOVE) Log.d(TAG, " Activities: " + r); 9389 } 9390 9391 N = pkg.permissions.size(); 9392 r = null; 9393 for (i=0; i<N; i++) { 9394 PackageParser.Permission p = pkg.permissions.get(i); 9395 BasePermission bp = mSettings.mPermissions.get(p.info.name); 9396 if (bp == null) { 9397 bp = mSettings.mPermissionTrees.get(p.info.name); 9398 } 9399 if (bp != null && bp.perm == p) { 9400 bp.perm = null; 9401 if (DEBUG_REMOVE && chatty) { 9402 if (r == null) { 9403 r = new StringBuilder(256); 9404 } else { 9405 r.append(' '); 9406 } 9407 r.append(p.info.name); 9408 } 9409 } 9410 if ((p.info.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9411 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(p.info.name); 9412 if (appOpPkgs != null) { 9413 appOpPkgs.remove(pkg.packageName); 9414 } 9415 } 9416 } 9417 if (r != null) { 9418 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9419 } 9420 9421 N = pkg.requestedPermissions.size(); 9422 r = null; 9423 for (i=0; i<N; i++) { 9424 String perm = pkg.requestedPermissions.get(i); 9425 BasePermission bp = mSettings.mPermissions.get(perm); 9426 if (bp != null && (bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9427 ArraySet<String> appOpPkgs = mAppOpPermissionPackages.get(perm); 9428 if (appOpPkgs != null) { 9429 appOpPkgs.remove(pkg.packageName); 9430 if (appOpPkgs.isEmpty()) { 9431 mAppOpPermissionPackages.remove(perm); 9432 } 9433 } 9434 } 9435 } 9436 if (r != null) { 9437 if (DEBUG_REMOVE) Log.d(TAG, " Permissions: " + r); 9438 } 9439 9440 N = pkg.instrumentation.size(); 9441 r = null; 9442 for (i=0; i<N; i++) { 9443 PackageParser.Instrumentation a = pkg.instrumentation.get(i); 9444 mInstrumentation.remove(a.getComponentName()); 9445 if (DEBUG_REMOVE && chatty) { 9446 if (r == null) { 9447 r = new StringBuilder(256); 9448 } else { 9449 r.append(' '); 9450 } 9451 r.append(a.info.name); 9452 } 9453 } 9454 if (r != null) { 9455 if (DEBUG_REMOVE) Log.d(TAG, " Instrumentation: " + r); 9456 } 9457 9458 r = null; 9459 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_SYSTEM) != 0) { 9460 // Only system apps can hold shared libraries. 9461 if (pkg.libraryNames != null) { 9462 for (i=0; i<pkg.libraryNames.size(); i++) { 9463 String name = pkg.libraryNames.get(i); 9464 SharedLibraryEntry cur = mSharedLibraries.get(name); 9465 if (cur != null && cur.apk != null && cur.apk.equals(pkg.packageName)) { 9466 mSharedLibraries.remove(name); 9467 if (DEBUG_REMOVE && chatty) { 9468 if (r == null) { 9469 r = new StringBuilder(256); 9470 } else { 9471 r.append(' '); 9472 } 9473 r.append(name); 9474 } 9475 } 9476 } 9477 } 9478 } 9479 if (r != null) { 9480 if (DEBUG_REMOVE) Log.d(TAG, " Libraries: " + r); 9481 } 9482 } 9483 9484 private static boolean hasPermission(PackageParser.Package pkgInfo, String perm) { 9485 for (int i=pkgInfo.permissions.size()-1; i>=0; i--) { 9486 if (pkgInfo.permissions.get(i).info.name.equals(perm)) { 9487 return true; 9488 } 9489 } 9490 return false; 9491 } 9492 9493 static final int UPDATE_PERMISSIONS_ALL = 1<<0; 9494 static final int UPDATE_PERMISSIONS_REPLACE_PKG = 1<<1; 9495 static final int UPDATE_PERMISSIONS_REPLACE_ALL = 1<<2; 9496 9497 private void updatePermissionsLPw(PackageParser.Package pkg, int flags) { 9498 // Update the parent permissions 9499 updatePermissionsLPw(pkg.packageName, pkg, flags); 9500 // Update the child permissions 9501 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 9502 for (int i = 0; i < childCount; i++) { 9503 PackageParser.Package childPkg = pkg.childPackages.get(i); 9504 updatePermissionsLPw(childPkg.packageName, childPkg, flags); 9505 } 9506 } 9507 9508 private void updatePermissionsLPw(String changingPkg, PackageParser.Package pkgInfo, 9509 int flags) { 9510 final String volumeUuid = (pkgInfo != null) ? getVolumeUuidForPackage(pkgInfo) : null; 9511 updatePermissionsLPw(changingPkg, pkgInfo, volumeUuid, flags); 9512 } 9513 9514 private void updatePermissionsLPw(String changingPkg, 9515 PackageParser.Package pkgInfo, String replaceVolumeUuid, int flags) { 9516 // Make sure there are no dangling permission trees. 9517 Iterator<BasePermission> it = mSettings.mPermissionTrees.values().iterator(); 9518 while (it.hasNext()) { 9519 final BasePermission bp = it.next(); 9520 if (bp.packageSetting == null) { 9521 // We may not yet have parsed the package, so just see if 9522 // we still know about its settings. 9523 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9524 } 9525 if (bp.packageSetting == null) { 9526 Slog.w(TAG, "Removing dangling permission tree: " + bp.name 9527 + " from package " + bp.sourcePackage); 9528 it.remove(); 9529 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9530 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9531 Slog.i(TAG, "Removing old permission tree: " + bp.name 9532 + " from package " + bp.sourcePackage); 9533 flags |= UPDATE_PERMISSIONS_ALL; 9534 it.remove(); 9535 } 9536 } 9537 } 9538 9539 // Make sure all dynamic permissions have been assigned to a package, 9540 // and make sure there are no dangling permissions. 9541 it = mSettings.mPermissions.values().iterator(); 9542 while (it.hasNext()) { 9543 final BasePermission bp = it.next(); 9544 if (bp.type == BasePermission.TYPE_DYNAMIC) { 9545 if (DEBUG_SETTINGS) Log.v(TAG, "Dynamic permission: name=" 9546 + bp.name + " pkg=" + bp.sourcePackage 9547 + " info=" + bp.pendingInfo); 9548 if (bp.packageSetting == null && bp.pendingInfo != null) { 9549 final BasePermission tree = findPermissionTreeLP(bp.name); 9550 if (tree != null && tree.perm != null) { 9551 bp.packageSetting = tree.packageSetting; 9552 bp.perm = new PackageParser.Permission(tree.perm.owner, 9553 new PermissionInfo(bp.pendingInfo)); 9554 bp.perm.info.packageName = tree.perm.info.packageName; 9555 bp.perm.info.name = bp.name; 9556 bp.uid = tree.uid; 9557 } 9558 } 9559 } 9560 if (bp.packageSetting == null) { 9561 // We may not yet have parsed the package, so just see if 9562 // we still know about its settings. 9563 bp.packageSetting = mSettings.mPackages.get(bp.sourcePackage); 9564 } 9565 if (bp.packageSetting == null) { 9566 Slog.w(TAG, "Removing dangling permission: " + bp.name 9567 + " from package " + bp.sourcePackage); 9568 it.remove(); 9569 } else if (changingPkg != null && changingPkg.equals(bp.sourcePackage)) { 9570 if (pkgInfo == null || !hasPermission(pkgInfo, bp.name)) { 9571 Slog.i(TAG, "Removing old permission: " + bp.name 9572 + " from package " + bp.sourcePackage); 9573 flags |= UPDATE_PERMISSIONS_ALL; 9574 it.remove(); 9575 } 9576 } 9577 } 9578 9579 // Now update the permissions for all packages, in particular 9580 // replace the granted permissions of the system packages. 9581 if ((flags&UPDATE_PERMISSIONS_ALL) != 0) { 9582 for (PackageParser.Package pkg : mPackages.values()) { 9583 if (pkg != pkgInfo) { 9584 // Only replace for packages on requested volume 9585 final String volumeUuid = getVolumeUuidForPackage(pkg); 9586 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_ALL) != 0) 9587 && Objects.equals(replaceVolumeUuid, volumeUuid); 9588 grantPermissionsLPw(pkg, replace, changingPkg); 9589 } 9590 } 9591 } 9592 9593 if (pkgInfo != null) { 9594 // Only replace for packages on requested volume 9595 final String volumeUuid = getVolumeUuidForPackage(pkgInfo); 9596 final boolean replace = ((flags & UPDATE_PERMISSIONS_REPLACE_PKG) != 0) 9597 && Objects.equals(replaceVolumeUuid, volumeUuid); 9598 grantPermissionsLPw(pkgInfo, replace, changingPkg); 9599 } 9600 } 9601 9602 private void grantPermissionsLPw(PackageParser.Package pkg, boolean replace, 9603 String packageOfInterest) { 9604 // IMPORTANT: There are two types of permissions: install and runtime. 9605 // Install time permissions are granted when the app is installed to 9606 // all device users and users added in the future. Runtime permissions 9607 // are granted at runtime explicitly to specific users. Normal and signature 9608 // protected permissions are install time permissions. Dangerous permissions 9609 // are install permissions if the app's target SDK is Lollipop MR1 or older, 9610 // otherwise they are runtime permissions. This function does not manage 9611 // runtime permissions except for the case an app targeting Lollipop MR1 9612 // being upgraded to target a newer SDK, in which case dangerous permissions 9613 // are transformed from install time to runtime ones. 9614 9615 final PackageSetting ps = (PackageSetting) pkg.mExtras; 9616 if (ps == null) { 9617 return; 9618 } 9619 9620 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "grantPermissions"); 9621 9622 PermissionsState permissionsState = ps.getPermissionsState(); 9623 PermissionsState origPermissions = permissionsState; 9624 9625 final int[] currentUserIds = UserManagerService.getInstance().getUserIds(); 9626 9627 boolean runtimePermissionsRevoked = false; 9628 int[] changedRuntimePermissionUserIds = EMPTY_INT_ARRAY; 9629 9630 boolean changedInstallPermission = false; 9631 9632 if (replace) { 9633 ps.installPermissionsFixed = false; 9634 if (!ps.isSharedUser()) { 9635 origPermissions = new PermissionsState(permissionsState); 9636 permissionsState.reset(); 9637 } else { 9638 // We need to know only about runtime permission changes since the 9639 // calling code always writes the install permissions state but 9640 // the runtime ones are written only if changed. The only cases of 9641 // changed runtime permissions here are promotion of an install to 9642 // runtime and revocation of a runtime from a shared user. 9643 changedRuntimePermissionUserIds = revokeUnusedSharedUserPermissionsLPw( 9644 ps.sharedUser, UserManagerService.getInstance().getUserIds()); 9645 if (!ArrayUtils.isEmpty(changedRuntimePermissionUserIds)) { 9646 runtimePermissionsRevoked = true; 9647 } 9648 } 9649 } 9650 9651 permissionsState.setGlobalGids(mGlobalGids); 9652 9653 final int N = pkg.requestedPermissions.size(); 9654 for (int i=0; i<N; i++) { 9655 final String name = pkg.requestedPermissions.get(i); 9656 final BasePermission bp = mSettings.mPermissions.get(name); 9657 9658 if (DEBUG_INSTALL) { 9659 Log.i(TAG, "Package " + pkg.packageName + " checking " + name + ": " + bp); 9660 } 9661 9662 if (bp == null || bp.packageSetting == null) { 9663 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9664 Slog.w(TAG, "Unknown permission " + name 9665 + " in package " + pkg.packageName); 9666 } 9667 continue; 9668 } 9669 9670 final String perm = bp.name; 9671 boolean allowedSig = false; 9672 int grant = GRANT_DENIED; 9673 9674 // Keep track of app op permissions. 9675 if ((bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_APPOP) != 0) { 9676 ArraySet<String> pkgs = mAppOpPermissionPackages.get(bp.name); 9677 if (pkgs == null) { 9678 pkgs = new ArraySet<>(); 9679 mAppOpPermissionPackages.put(bp.name, pkgs); 9680 } 9681 pkgs.add(pkg.packageName); 9682 } 9683 9684 final int level = bp.protectionLevel & PermissionInfo.PROTECTION_MASK_BASE; 9685 final boolean appSupportsRuntimePermissions = pkg.applicationInfo.targetSdkVersion 9686 >= Build.VERSION_CODES.M; 9687 switch (level) { 9688 case PermissionInfo.PROTECTION_NORMAL: { 9689 // For all apps normal permissions are install time ones. 9690 grant = GRANT_INSTALL; 9691 } break; 9692 9693 case PermissionInfo.PROTECTION_DANGEROUS: { 9694 // If a permission review is required for legacy apps we represent 9695 // their permissions as always granted runtime ones since we need 9696 // to keep the review required permission flag per user while an 9697 // install permission's state is shared across all users. 9698 if (!appSupportsRuntimePermissions && !Build.PERMISSIONS_REVIEW_REQUIRED) { 9699 // For legacy apps dangerous permissions are install time ones. 9700 grant = GRANT_INSTALL; 9701 } else if (origPermissions.hasInstallPermission(bp.name)) { 9702 // For legacy apps that became modern, install becomes runtime. 9703 grant = GRANT_UPGRADE; 9704 } else if (mPromoteSystemApps 9705 && isSystemApp(ps) 9706 && mExistingSystemPackages.contains(ps.name)) { 9707 // For legacy system apps, install becomes runtime. 9708 // We cannot check hasInstallPermission() for system apps since those 9709 // permissions were granted implicitly and not persisted pre-M. 9710 grant = GRANT_UPGRADE; 9711 } else { 9712 // For modern apps keep runtime permissions unchanged. 9713 grant = GRANT_RUNTIME; 9714 } 9715 } break; 9716 9717 case PermissionInfo.PROTECTION_SIGNATURE: { 9718 // For all apps signature permissions are install time ones. 9719 allowedSig = grantSignaturePermission(perm, pkg, bp, origPermissions); 9720 if (allowedSig) { 9721 grant = GRANT_INSTALL; 9722 } 9723 } break; 9724 } 9725 9726 if (DEBUG_INSTALL) { 9727 Log.i(TAG, "Package " + pkg.packageName + " granting " + perm); 9728 } 9729 9730 if (grant != GRANT_DENIED) { 9731 if (!isSystemApp(ps) && ps.installPermissionsFixed) { 9732 // If this is an existing, non-system package, then 9733 // we can't add any new permissions to it. 9734 if (!allowedSig && !origPermissions.hasInstallPermission(perm)) { 9735 // Except... if this is a permission that was added 9736 // to the platform (note: need to only do this when 9737 // updating the platform). 9738 if (!isNewPlatformPermissionForPackage(perm, pkg)) { 9739 grant = GRANT_DENIED; 9740 } 9741 } 9742 } 9743 9744 switch (grant) { 9745 case GRANT_INSTALL: { 9746 // Revoke this as runtime permission to handle the case of 9747 // a runtime permission being downgraded to an install one. Also in permission review mode we keep dangerous permissions for legacy apps 9748 for (int userId : UserManagerService.getInstance().getUserIds()) { 9749 if (origPermissions.getRuntimePermissionState( 9750 bp.name, userId) != null) { 9751 // Revoke the runtime permission and clear the flags. 9752 origPermissions.revokeRuntimePermission(bp, userId); 9753 origPermissions.updatePermissionFlags(bp, userId, 9754 PackageManager.MASK_PERMISSION_FLAGS, 0); 9755 // If we revoked a permission permission, we have to write. 9756 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9757 changedRuntimePermissionUserIds, userId); 9758 } 9759 } 9760 // Grant an install permission. 9761 if (permissionsState.grantInstallPermission(bp) != 9762 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9763 changedInstallPermission = true; 9764 } 9765 } break; 9766 9767 case GRANT_RUNTIME: { 9768 // Grant previously granted runtime permissions. 9769 for (int userId : UserManagerService.getInstance().getUserIds()) { 9770 PermissionState permissionState = origPermissions 9771 .getRuntimePermissionState(bp.name, userId); 9772 int flags = permissionState != null 9773 ? permissionState.getFlags() : 0; 9774 if (origPermissions.hasRuntimePermission(bp.name, userId)) { 9775 if (permissionsState.grantRuntimePermission(bp, userId) == 9776 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9777 // If we cannot put the permission as it was, we have to write. 9778 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9779 changedRuntimePermissionUserIds, userId); 9780 } 9781 // If the app supports runtime permissions no need for a review. 9782 if (Build.PERMISSIONS_REVIEW_REQUIRED 9783 && appSupportsRuntimePermissions 9784 && (flags & PackageManager 9785 .FLAG_PERMISSION_REVIEW_REQUIRED) != 0) { 9786 flags &= ~PackageManager.FLAG_PERMISSION_REVIEW_REQUIRED; 9787 // Since we changed the flags, we have to write. 9788 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9789 changedRuntimePermissionUserIds, userId); 9790 } 9791 } else if (Build.PERMISSIONS_REVIEW_REQUIRED 9792 && !appSupportsRuntimePermissions) { 9793 // For legacy apps that need a permission review, every new 9794 // runtime permission is granted but it is pending a review. 9795 if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 9796 permissionsState.grantRuntimePermission(bp, userId); 9797 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 9798 // We changed the permission and flags, hence have to write. 9799 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9800 changedRuntimePermissionUserIds, userId); 9801 } 9802 } 9803 // Propagate the permission flags. 9804 permissionsState.updatePermissionFlags(bp, userId, flags, flags); 9805 } 9806 } break; 9807 9808 case GRANT_UPGRADE: { 9809 // Grant runtime permissions for a previously held install permission. 9810 PermissionState permissionState = origPermissions 9811 .getInstallPermissionState(bp.name); 9812 final int flags = permissionState != null ? permissionState.getFlags() : 0; 9813 9814 if (origPermissions.revokeInstallPermission(bp) 9815 != PermissionsState.PERMISSION_OPERATION_FAILURE) { 9816 // We will be transferring the permission flags, so clear them. 9817 origPermissions.updatePermissionFlags(bp, UserHandle.USER_ALL, 9818 PackageManager.MASK_PERMISSION_FLAGS, 0); 9819 changedInstallPermission = true; 9820 } 9821 9822 // If the permission is not to be promoted to runtime we ignore it and 9823 // also its other flags as they are not applicable to install permissions. 9824 if ((flags & PackageManager.FLAG_PERMISSION_REVOKE_ON_UPGRADE) == 0) { 9825 for (int userId : currentUserIds) { 9826 if (permissionsState.grantRuntimePermission(bp, userId) != 9827 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9828 // Transfer the permission flags. 9829 permissionsState.updatePermissionFlags(bp, userId, 9830 flags, flags); 9831 // If we granted the permission, we have to write. 9832 changedRuntimePermissionUserIds = ArrayUtils.appendInt( 9833 changedRuntimePermissionUserIds, userId); 9834 } 9835 } 9836 } 9837 } break; 9838 9839 default: { 9840 if (packageOfInterest == null 9841 || packageOfInterest.equals(pkg.packageName)) { 9842 Slog.w(TAG, "Not granting permission " + perm 9843 + " to package " + pkg.packageName 9844 + " because it was previously installed without"); 9845 } 9846 } break; 9847 } 9848 } else { 9849 if (permissionsState.revokeInstallPermission(bp) != 9850 PermissionsState.PERMISSION_OPERATION_FAILURE) { 9851 // Also drop the permission flags. 9852 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 9853 PackageManager.MASK_PERMISSION_FLAGS, 0); 9854 changedInstallPermission = true; 9855 Slog.i(TAG, "Un-granting permission " + perm 9856 + " from package " + pkg.packageName 9857 + " (protectionLevel=" + bp.protectionLevel 9858 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9859 + ")"); 9860 } else if ((bp.protectionLevel&PermissionInfo.PROTECTION_FLAG_APPOP) == 0) { 9861 // Don't print warning for app op permissions, since it is fine for them 9862 // not to be granted, there is a UI for the user to decide. 9863 if (packageOfInterest == null || packageOfInterest.equals(pkg.packageName)) { 9864 Slog.w(TAG, "Not granting permission " + perm 9865 + " to package " + pkg.packageName 9866 + " (protectionLevel=" + bp.protectionLevel 9867 + " flags=0x" + Integer.toHexString(pkg.applicationInfo.flags) 9868 + ")"); 9869 } 9870 } 9871 } 9872 } 9873 9874 if ((changedInstallPermission || replace) && !ps.installPermissionsFixed && 9875 !isSystemApp(ps) || isUpdatedSystemApp(ps)){ 9876 // This is the first that we have heard about this package, so the 9877 // permissions we have now selected are fixed until explicitly 9878 // changed. 9879 ps.installPermissionsFixed = true; 9880 } 9881 9882 // Persist the runtime permissions state for users with changes. If permissions 9883 // were revoked because no app in the shared user declares them we have to 9884 // write synchronously to avoid losing runtime permissions state. 9885 for (int userId : changedRuntimePermissionUserIds) { 9886 mSettings.writeRuntimePermissionsForUserLPr(userId, runtimePermissionsRevoked); 9887 } 9888 9889 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 9890 } 9891 9892 private boolean isNewPlatformPermissionForPackage(String perm, PackageParser.Package pkg) { 9893 boolean allowed = false; 9894 final int NP = PackageParser.NEW_PERMISSIONS.length; 9895 for (int ip=0; ip<NP; ip++) { 9896 final PackageParser.NewPermissionInfo npi 9897 = PackageParser.NEW_PERMISSIONS[ip]; 9898 if (npi.name.equals(perm) 9899 && pkg.applicationInfo.targetSdkVersion < npi.sdkVersion) { 9900 allowed = true; 9901 Log.i(TAG, "Auto-granting " + perm + " to old pkg " 9902 + pkg.packageName); 9903 break; 9904 } 9905 } 9906 return allowed; 9907 } 9908 9909 private boolean grantSignaturePermission(String perm, PackageParser.Package pkg, 9910 BasePermission bp, PermissionsState origPermissions) { 9911 boolean allowed; 9912 allowed = (compareSignatures( 9913 bp.packageSetting.signatures.mSignatures, pkg.mSignatures) 9914 == PackageManager.SIGNATURE_MATCH) 9915 || (compareSignatures(mPlatformPackage.mSignatures, pkg.mSignatures) 9916 == PackageManager.SIGNATURE_MATCH); 9917 if (!allowed && (bp.protectionLevel 9918 & PermissionInfo.PROTECTION_FLAG_PRIVILEGED) != 0) { 9919 if (isSystemApp(pkg)) { 9920 // For updated system applications, a system permission 9921 // is granted only if it had been defined by the original application. 9922 if (pkg.isUpdatedSystemApp()) { 9923 final PackageSetting sysPs = mSettings 9924 .getDisabledSystemPkgLPr(pkg.packageName); 9925 if (sysPs != null && sysPs.getPermissionsState().hasInstallPermission(perm)) { 9926 // If the original was granted this permission, we take 9927 // that grant decision as read and propagate it to the 9928 // update. 9929 if (sysPs.isPrivileged()) { 9930 allowed = true; 9931 } 9932 } else { 9933 // The system apk may have been updated with an older 9934 // version of the one on the data partition, but which 9935 // granted a new system permission that it didn't have 9936 // before. In this case we do want to allow the app to 9937 // now get the new permission if the ancestral apk is 9938 // privileged to get it. 9939 if (sysPs != null && sysPs.pkg != null && sysPs.isPrivileged()) { 9940 for (int j = 0; j < sysPs.pkg.requestedPermissions.size(); j++) { 9941 if (perm.equals(sysPs.pkg.requestedPermissions.get(j))) { 9942 allowed = true; 9943 break; 9944 } 9945 } 9946 } 9947 // Also if a privileged parent package on the system image or any of 9948 // its children requested a privileged permission, the updated child 9949 // packages can also get the permission. 9950 if (pkg.parentPackage != null) { 9951 final PackageSetting disabledSysParentPs = mSettings 9952 .getDisabledSystemPkgLPr(pkg.parentPackage.packageName); 9953 if (disabledSysParentPs != null && disabledSysParentPs.pkg != null 9954 && disabledSysParentPs.isPrivileged()) { 9955 if (isPackageRequestingPermission(disabledSysParentPs.pkg, perm)) { 9956 allowed = true; 9957 } else if (disabledSysParentPs.pkg.childPackages != null) { 9958 final int count = disabledSysParentPs.pkg.childPackages.size(); 9959 for (int i = 0; i < count; i++) { 9960 PackageParser.Package disabledSysChildPkg = 9961 disabledSysParentPs.pkg.childPackages.get(i); 9962 if (isPackageRequestingPermission(disabledSysChildPkg, 9963 perm)) { 9964 allowed = true; 9965 break; 9966 } 9967 } 9968 } 9969 } 9970 } 9971 } 9972 } else { 9973 allowed = isPrivilegedApp(pkg); 9974 } 9975 } 9976 } 9977 if (!allowed) { 9978 if (!allowed && (bp.protectionLevel 9979 & PermissionInfo.PROTECTION_FLAG_PRE23) != 0 9980 && pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 9981 // If this was a previously normal/dangerous permission that got moved 9982 // to a system permission as part of the runtime permission redesign, then 9983 // we still want to blindly grant it to old apps. 9984 allowed = true; 9985 } 9986 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_INSTALLER) != 0 9987 && pkg.packageName.equals(mRequiredInstallerPackage)) { 9988 // If this permission is to be granted to the system installer and 9989 // this app is an installer, then it gets the permission. 9990 allowed = true; 9991 } 9992 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_VERIFIER) != 0 9993 && pkg.packageName.equals(mRequiredVerifierPackage)) { 9994 // If this permission is to be granted to the system verifier and 9995 // this app is a verifier, then it gets the permission. 9996 allowed = true; 9997 } 9998 if (!allowed && (bp.protectionLevel 9999 & PermissionInfo.PROTECTION_FLAG_PREINSTALLED) != 0 10000 && isSystemApp(pkg)) { 10001 // Any pre-installed system app is allowed to get this permission. 10002 allowed = true; 10003 } 10004 if (!allowed && (bp.protectionLevel 10005 & PermissionInfo.PROTECTION_FLAG_DEVELOPMENT) != 0) { 10006 // For development permissions, a development permission 10007 // is granted only if it was already granted. 10008 allowed = origPermissions.hasInstallPermission(perm); 10009 } 10010 if (!allowed && (bp.protectionLevel & PermissionInfo.PROTECTION_FLAG_SETUP) != 0 10011 && pkg.packageName.equals(mSetupWizardPackage)) { 10012 // If this permission is to be granted to the system setup wizard and 10013 // this app is a setup wizard, then it gets the permission. 10014 allowed = true; 10015 } 10016 } 10017 return allowed; 10018 } 10019 10020 private boolean isPackageRequestingPermission(PackageParser.Package pkg, String permission) { 10021 final int permCount = pkg.requestedPermissions.size(); 10022 for (int j = 0; j < permCount; j++) { 10023 String requestedPermission = pkg.requestedPermissions.get(j); 10024 if (permission.equals(requestedPermission)) { 10025 return true; 10026 } 10027 } 10028 return false; 10029 } 10030 10031 final class ActivityIntentResolver 10032 extends IntentResolver<PackageParser.ActivityIntentInfo, ResolveInfo> { 10033 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10034 boolean defaultOnly, int userId) { 10035 if (!sUserManager.exists(userId)) return null; 10036 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10037 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10038 } 10039 10040 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10041 int userId) { 10042 if (!sUserManager.exists(userId)) return null; 10043 mFlags = flags; 10044 return super.queryIntent(intent, resolvedType, 10045 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10046 } 10047 10048 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10049 int flags, ArrayList<PackageParser.Activity> packageActivities, int userId) { 10050 if (!sUserManager.exists(userId)) return null; 10051 if (packageActivities == null) { 10052 return null; 10053 } 10054 mFlags = flags; 10055 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10056 final int N = packageActivities.size(); 10057 ArrayList<PackageParser.ActivityIntentInfo[]> listCut = 10058 new ArrayList<PackageParser.ActivityIntentInfo[]>(N); 10059 10060 ArrayList<PackageParser.ActivityIntentInfo> intentFilters; 10061 for (int i = 0; i < N; ++i) { 10062 intentFilters = packageActivities.get(i).intents; 10063 if (intentFilters != null && intentFilters.size() > 0) { 10064 PackageParser.ActivityIntentInfo[] array = 10065 new PackageParser.ActivityIntentInfo[intentFilters.size()]; 10066 intentFilters.toArray(array); 10067 listCut.add(array); 10068 } 10069 } 10070 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10071 } 10072 10073 /** 10074 * Finds a privileged activity that matches the specified activity names. 10075 */ 10076 private PackageParser.Activity findMatchingActivity( 10077 List<PackageParser.Activity> activityList, ActivityInfo activityInfo) { 10078 for (PackageParser.Activity sysActivity : activityList) { 10079 if (sysActivity.info.name.equals(activityInfo.name)) { 10080 return sysActivity; 10081 } 10082 if (sysActivity.info.name.equals(activityInfo.targetActivity)) { 10083 return sysActivity; 10084 } 10085 if (sysActivity.info.targetActivity != null) { 10086 if (sysActivity.info.targetActivity.equals(activityInfo.name)) { 10087 return sysActivity; 10088 } 10089 if (sysActivity.info.targetActivity.equals(activityInfo.targetActivity)) { 10090 return sysActivity; 10091 } 10092 } 10093 } 10094 return null; 10095 } 10096 10097 public class IterGenerator<E> { 10098 public Iterator<E> generate(ActivityIntentInfo info) { 10099 return null; 10100 } 10101 } 10102 10103 public class ActionIterGenerator extends IterGenerator<String> { 10104 @Override 10105 public Iterator<String> generate(ActivityIntentInfo info) { 10106 return info.actionsIterator(); 10107 } 10108 } 10109 10110 public class CategoriesIterGenerator extends IterGenerator<String> { 10111 @Override 10112 public Iterator<String> generate(ActivityIntentInfo info) { 10113 return info.categoriesIterator(); 10114 } 10115 } 10116 10117 public class SchemesIterGenerator extends IterGenerator<String> { 10118 @Override 10119 public Iterator<String> generate(ActivityIntentInfo info) { 10120 return info.schemesIterator(); 10121 } 10122 } 10123 10124 public class AuthoritiesIterGenerator extends IterGenerator<IntentFilter.AuthorityEntry> { 10125 @Override 10126 public Iterator<IntentFilter.AuthorityEntry> generate(ActivityIntentInfo info) { 10127 return info.authoritiesIterator(); 10128 } 10129 } 10130 10131 /** 10132 * <em>WARNING</em> for performance reasons, the passed in intentList WILL BE 10133 * MODIFIED. Do not pass in a list that should not be changed. 10134 */ 10135 private <T> void getIntentListSubset(List<ActivityIntentInfo> intentList, 10136 IterGenerator<T> generator, Iterator<T> searchIterator) { 10137 // loop through the set of actions; every one must be found in the intent filter 10138 while (searchIterator.hasNext()) { 10139 // we must have at least one filter in the list to consider a match 10140 if (intentList.size() == 0) { 10141 break; 10142 } 10143 10144 final T searchAction = searchIterator.next(); 10145 10146 // loop through the set of intent filters 10147 final Iterator<ActivityIntentInfo> intentIter = intentList.iterator(); 10148 while (intentIter.hasNext()) { 10149 final ActivityIntentInfo intentInfo = intentIter.next(); 10150 boolean selectionFound = false; 10151 10152 // loop through the intent filter's selection criteria; at least one 10153 // of them must match the searched criteria 10154 final Iterator<T> intentSelectionIter = generator.generate(intentInfo); 10155 while (intentSelectionIter != null && intentSelectionIter.hasNext()) { 10156 final T intentSelection = intentSelectionIter.next(); 10157 if (intentSelection != null && intentSelection.equals(searchAction)) { 10158 selectionFound = true; 10159 break; 10160 } 10161 } 10162 10163 // the selection criteria wasn't found in this filter's set; this filter 10164 // is not a potential match 10165 if (!selectionFound) { 10166 intentIter.remove(); 10167 } 10168 } 10169 } 10170 } 10171 10172 private boolean isProtectedAction(ActivityIntentInfo filter) { 10173 final Iterator<String> actionsIter = filter.actionsIterator(); 10174 while (actionsIter != null && actionsIter.hasNext()) { 10175 final String filterAction = actionsIter.next(); 10176 if (PROTECTED_ACTIONS.contains(filterAction)) { 10177 return true; 10178 } 10179 } 10180 return false; 10181 } 10182 10183 /** 10184 * Adjusts the priority of the given intent filter according to policy. 10185 * <p> 10186 * <ul> 10187 * <li>The priority for non privileged applications is capped to '0'</li> 10188 * <li>The priority for protected actions on privileged applications is capped to '0'</li> 10189 * <li>The priority for unbundled updates to privileged applications is capped to the 10190 * priority defined on the system partition</li> 10191 * </ul> 10192 * <p> 10193 * <em>NOTE:</em> There is one exception. For security reasons, the setup wizard is 10194 * allowed to obtain any priority on any action. 10195 */ 10196 private void adjustPriority( 10197 List<PackageParser.Activity> systemActivities, ActivityIntentInfo intent) { 10198 // nothing to do; priority is fine as-is 10199 if (intent.getPriority() <= 0) { 10200 return; 10201 } 10202 10203 final ActivityInfo activityInfo = intent.activity.info; 10204 final ApplicationInfo applicationInfo = activityInfo.applicationInfo; 10205 10206 final boolean privilegedApp = 10207 ((applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0); 10208 if (!privilegedApp) { 10209 // non-privileged applications can never define a priority >0 10210 Slog.w(TAG, "Non-privileged app; cap priority to 0;" 10211 + " package: " + applicationInfo.packageName 10212 + " activity: " + intent.activity.className 10213 + " origPrio: " + intent.getPriority()); 10214 intent.setPriority(0); 10215 return; 10216 } 10217 10218 if (systemActivities == null) { 10219 // the system package is not disabled; we're parsing the system partition 10220 if (isProtectedAction(intent)) { 10221 if (mDeferProtectedFilters) { 10222 // We can't deal with these just yet. No component should ever obtain a 10223 // >0 priority for a protected actions, with ONE exception -- the setup 10224 // wizard. The setup wizard, however, cannot be known until we're able to 10225 // query it for the category CATEGORY_SETUP_WIZARD. Which we can't do 10226 // until all intent filters have been processed. Chicken, meet egg. 10227 // Let the filter temporarily have a high priority and rectify the 10228 // priorities after all system packages have been scanned. 10229 mProtectedFilters.add(intent); 10230 if (DEBUG_FILTERS) { 10231 Slog.i(TAG, "Protected action; save for later;" 10232 + " package: " + applicationInfo.packageName 10233 + " activity: " + intent.activity.className 10234 + " origPrio: " + intent.getPriority()); 10235 } 10236 return; 10237 } else { 10238 if (DEBUG_FILTERS && mSetupWizardPackage == null) { 10239 Slog.i(TAG, "No setup wizard;" 10240 + " All protected intents capped to priority 0"); 10241 } 10242 if (intent.activity.info.packageName.equals(mSetupWizardPackage)) { 10243 if (DEBUG_FILTERS) { 10244 Slog.i(TAG, "Found setup wizard;" 10245 + " allow priority " + intent.getPriority() + ";" 10246 + " package: " + intent.activity.info.packageName 10247 + " activity: " + intent.activity.className 10248 + " priority: " + intent.getPriority()); 10249 } 10250 // setup wizard gets whatever it wants 10251 return; 10252 } 10253 Slog.w(TAG, "Protected action; cap priority to 0;" 10254 + " package: " + intent.activity.info.packageName 10255 + " activity: " + intent.activity.className 10256 + " origPrio: " + intent.getPriority()); 10257 intent.setPriority(0); 10258 return; 10259 } 10260 } 10261 // privileged apps on the system image get whatever priority they request 10262 return; 10263 } 10264 10265 // privileged app unbundled update ... try to find the same activity 10266 final PackageParser.Activity foundActivity = 10267 findMatchingActivity(systemActivities, activityInfo); 10268 if (foundActivity == null) { 10269 // this is a new activity; it cannot obtain >0 priority 10270 if (DEBUG_FILTERS) { 10271 Slog.i(TAG, "New activity; cap priority to 0;" 10272 + " package: " + applicationInfo.packageName 10273 + " activity: " + intent.activity.className 10274 + " origPrio: " + intent.getPriority()); 10275 } 10276 intent.setPriority(0); 10277 return; 10278 } 10279 10280 // found activity, now check for filter equivalence 10281 10282 // a shallow copy is enough; we modify the list, not its contents 10283 final List<ActivityIntentInfo> intentListCopy = 10284 new ArrayList<>(foundActivity.intents); 10285 final List<ActivityIntentInfo> foundFilters = findFilters(intent); 10286 10287 // find matching action subsets 10288 final Iterator<String> actionsIterator = intent.actionsIterator(); 10289 if (actionsIterator != null) { 10290 getIntentListSubset( 10291 intentListCopy, new ActionIterGenerator(), actionsIterator); 10292 if (intentListCopy.size() == 0) { 10293 // no more intents to match; we're not equivalent 10294 if (DEBUG_FILTERS) { 10295 Slog.i(TAG, "Mismatched action; cap priority to 0;" 10296 + " package: " + applicationInfo.packageName 10297 + " activity: " + intent.activity.className 10298 + " origPrio: " + intent.getPriority()); 10299 } 10300 intent.setPriority(0); 10301 return; 10302 } 10303 } 10304 10305 // find matching category subsets 10306 final Iterator<String> categoriesIterator = intent.categoriesIterator(); 10307 if (categoriesIterator != null) { 10308 getIntentListSubset(intentListCopy, new CategoriesIterGenerator(), 10309 categoriesIterator); 10310 if (intentListCopy.size() == 0) { 10311 // no more intents to match; we're not equivalent 10312 if (DEBUG_FILTERS) { 10313 Slog.i(TAG, "Mismatched category; cap priority to 0;" 10314 + " package: " + applicationInfo.packageName 10315 + " activity: " + intent.activity.className 10316 + " origPrio: " + intent.getPriority()); 10317 } 10318 intent.setPriority(0); 10319 return; 10320 } 10321 } 10322 10323 // find matching schemes subsets 10324 final Iterator<String> schemesIterator = intent.schemesIterator(); 10325 if (schemesIterator != null) { 10326 getIntentListSubset(intentListCopy, new SchemesIterGenerator(), 10327 schemesIterator); 10328 if (intentListCopy.size() == 0) { 10329 // no more intents to match; we're not equivalent 10330 if (DEBUG_FILTERS) { 10331 Slog.i(TAG, "Mismatched scheme; cap priority to 0;" 10332 + " package: " + applicationInfo.packageName 10333 + " activity: " + intent.activity.className 10334 + " origPrio: " + intent.getPriority()); 10335 } 10336 intent.setPriority(0); 10337 return; 10338 } 10339 } 10340 10341 // find matching authorities subsets 10342 final Iterator<IntentFilter.AuthorityEntry> 10343 authoritiesIterator = intent.authoritiesIterator(); 10344 if (authoritiesIterator != null) { 10345 getIntentListSubset(intentListCopy, 10346 new AuthoritiesIterGenerator(), 10347 authoritiesIterator); 10348 if (intentListCopy.size() == 0) { 10349 // no more intents to match; we're not equivalent 10350 if (DEBUG_FILTERS) { 10351 Slog.i(TAG, "Mismatched authority; cap priority to 0;" 10352 + " package: " + applicationInfo.packageName 10353 + " activity: " + intent.activity.className 10354 + " origPrio: " + intent.getPriority()); 10355 } 10356 intent.setPriority(0); 10357 return; 10358 } 10359 } 10360 10361 // we found matching filter(s); app gets the max priority of all intents 10362 int cappedPriority = 0; 10363 for (int i = intentListCopy.size() - 1; i >= 0; --i) { 10364 cappedPriority = Math.max(cappedPriority, intentListCopy.get(i).getPriority()); 10365 } 10366 if (intent.getPriority() > cappedPriority) { 10367 if (DEBUG_FILTERS) { 10368 Slog.i(TAG, "Found matching filter(s);" 10369 + " cap priority to " + cappedPriority + ";" 10370 + " package: " + applicationInfo.packageName 10371 + " activity: " + intent.activity.className 10372 + " origPrio: " + intent.getPriority()); 10373 } 10374 intent.setPriority(cappedPriority); 10375 return; 10376 } 10377 // all this for nothing; the requested priority was <= what was on the system 10378 } 10379 10380 public final void addActivity(PackageParser.Activity a, String type) { 10381 mActivities.put(a.getComponentName(), a); 10382 if (DEBUG_SHOW_INFO) 10383 Log.v( 10384 TAG, " " + type + " " + 10385 (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel : a.info.name) + ":"); 10386 if (DEBUG_SHOW_INFO) 10387 Log.v(TAG, " Class=" + a.info.name); 10388 final int NI = a.intents.size(); 10389 for (int j=0; j<NI; j++) { 10390 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10391 if ("activity".equals(type)) { 10392 final PackageSetting ps = 10393 mSettings.getDisabledSystemPkgLPr(intent.activity.info.packageName); 10394 final List<PackageParser.Activity> systemActivities = 10395 ps != null && ps.pkg != null ? ps.pkg.activities : null; 10396 adjustPriority(systemActivities, intent); 10397 } 10398 if (DEBUG_SHOW_INFO) { 10399 Log.v(TAG, " IntentFilter:"); 10400 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10401 } 10402 if (!intent.debugCheck()) { 10403 Log.w(TAG, "==> For Activity " + a.info.name); 10404 } 10405 addFilter(intent); 10406 } 10407 } 10408 10409 public final void removeActivity(PackageParser.Activity a, String type) { 10410 mActivities.remove(a.getComponentName()); 10411 if (DEBUG_SHOW_INFO) { 10412 Log.v(TAG, " " + type + " " 10413 + (a.info.nonLocalizedLabel != null ? a.info.nonLocalizedLabel 10414 : a.info.name) + ":"); 10415 Log.v(TAG, " Class=" + a.info.name); 10416 } 10417 final int NI = a.intents.size(); 10418 for (int j=0; j<NI; j++) { 10419 PackageParser.ActivityIntentInfo intent = a.intents.get(j); 10420 if (DEBUG_SHOW_INFO) { 10421 Log.v(TAG, " IntentFilter:"); 10422 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10423 } 10424 removeFilter(intent); 10425 } 10426 } 10427 10428 @Override 10429 protected boolean allowFilterResult( 10430 PackageParser.ActivityIntentInfo filter, List<ResolveInfo> dest) { 10431 ActivityInfo filterAi = filter.activity.info; 10432 for (int i=dest.size()-1; i>=0; i--) { 10433 ActivityInfo destAi = dest.get(i).activityInfo; 10434 if (destAi.name == filterAi.name 10435 && destAi.packageName == filterAi.packageName) { 10436 return false; 10437 } 10438 } 10439 return true; 10440 } 10441 10442 @Override 10443 protected ActivityIntentInfo[] newArray(int size) { 10444 return new ActivityIntentInfo[size]; 10445 } 10446 10447 @Override 10448 protected boolean isFilterStopped(PackageParser.ActivityIntentInfo filter, int userId) { 10449 if (!sUserManager.exists(userId)) return true; 10450 PackageParser.Package p = filter.activity.owner; 10451 if (p != null) { 10452 PackageSetting ps = (PackageSetting)p.mExtras; 10453 if (ps != null) { 10454 // System apps are never considered stopped for purposes of 10455 // filtering, because there may be no way for the user to 10456 // actually re-launch them. 10457 return (ps.pkgFlags&ApplicationInfo.FLAG_SYSTEM) == 0 10458 && ps.getStopped(userId); 10459 } 10460 } 10461 return false; 10462 } 10463 10464 @Override 10465 protected boolean isPackageForFilter(String packageName, 10466 PackageParser.ActivityIntentInfo info) { 10467 return packageName.equals(info.activity.owner.packageName); 10468 } 10469 10470 @Override 10471 protected ResolveInfo newResult(PackageParser.ActivityIntentInfo info, 10472 int match, int userId) { 10473 if (!sUserManager.exists(userId)) return null; 10474 if (!mSettings.isEnabledAndMatchLPr(info.activity.info, mFlags, userId)) { 10475 return null; 10476 } 10477 final PackageParser.Activity activity = info.activity; 10478 PackageSetting ps = (PackageSetting) activity.owner.mExtras; 10479 if (ps == null) { 10480 return null; 10481 } 10482 ActivityInfo ai = PackageParser.generateActivityInfo(activity, mFlags, 10483 ps.readUserState(userId), userId); 10484 if (ai == null) { 10485 return null; 10486 } 10487 final ResolveInfo res = new ResolveInfo(); 10488 res.activityInfo = ai; 10489 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10490 res.filter = info; 10491 } 10492 if (info != null) { 10493 res.handleAllWebDataURI = info.handleAllWebDataURI(); 10494 } 10495 res.priority = info.getPriority(); 10496 res.preferredOrder = activity.owner.mPreferredOrder; 10497 //System.out.println("Result: " + res.activityInfo.className + 10498 // " = " + res.priority); 10499 res.match = match; 10500 res.isDefault = info.hasDefault; 10501 res.labelRes = info.labelRes; 10502 res.nonLocalizedLabel = info.nonLocalizedLabel; 10503 if (userNeedsBadging(userId)) { 10504 res.noResourceId = true; 10505 } else { 10506 res.icon = info.icon; 10507 } 10508 res.iconResourceId = info.icon; 10509 res.system = res.activityInfo.applicationInfo.isSystemApp(); 10510 return res; 10511 } 10512 10513 @Override 10514 protected void sortResults(List<ResolveInfo> results) { 10515 Collections.sort(results, mResolvePrioritySorter); 10516 } 10517 10518 @Override 10519 protected void dumpFilter(PrintWriter out, String prefix, 10520 PackageParser.ActivityIntentInfo filter) { 10521 out.print(prefix); out.print( 10522 Integer.toHexString(System.identityHashCode(filter.activity))); 10523 out.print(' '); 10524 filter.activity.printComponentShortName(out); 10525 out.print(" filter "); 10526 out.println(Integer.toHexString(System.identityHashCode(filter))); 10527 } 10528 10529 @Override 10530 protected Object filterToLabel(PackageParser.ActivityIntentInfo filter) { 10531 return filter.activity; 10532 } 10533 10534 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10535 PackageParser.Activity activity = (PackageParser.Activity)label; 10536 out.print(prefix); out.print( 10537 Integer.toHexString(System.identityHashCode(activity))); 10538 out.print(' '); 10539 activity.printComponentShortName(out); 10540 if (count > 1) { 10541 out.print(" ("); out.print(count); out.print(" filters)"); 10542 } 10543 out.println(); 10544 } 10545 10546 // Keys are String (activity class name), values are Activity. 10547 private final ArrayMap<ComponentName, PackageParser.Activity> mActivities 10548 = new ArrayMap<ComponentName, PackageParser.Activity>(); 10549 private int mFlags; 10550 } 10551 10552 private final class ServiceIntentResolver 10553 extends IntentResolver<PackageParser.ServiceIntentInfo, ResolveInfo> { 10554 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10555 boolean defaultOnly, int userId) { 10556 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10557 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10558 } 10559 10560 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10561 int userId) { 10562 if (!sUserManager.exists(userId)) return null; 10563 mFlags = flags; 10564 return super.queryIntent(intent, resolvedType, 10565 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10566 } 10567 10568 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10569 int flags, ArrayList<PackageParser.Service> packageServices, int userId) { 10570 if (!sUserManager.exists(userId)) return null; 10571 if (packageServices == null) { 10572 return null; 10573 } 10574 mFlags = flags; 10575 final boolean defaultOnly = (flags&PackageManager.MATCH_DEFAULT_ONLY) != 0; 10576 final int N = packageServices.size(); 10577 ArrayList<PackageParser.ServiceIntentInfo[]> listCut = 10578 new ArrayList<PackageParser.ServiceIntentInfo[]>(N); 10579 10580 ArrayList<PackageParser.ServiceIntentInfo> intentFilters; 10581 for (int i = 0; i < N; ++i) { 10582 intentFilters = packageServices.get(i).intents; 10583 if (intentFilters != null && intentFilters.size() > 0) { 10584 PackageParser.ServiceIntentInfo[] array = 10585 new PackageParser.ServiceIntentInfo[intentFilters.size()]; 10586 intentFilters.toArray(array); 10587 listCut.add(array); 10588 } 10589 } 10590 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10591 } 10592 10593 public final void addService(PackageParser.Service s) { 10594 mServices.put(s.getComponentName(), s); 10595 if (DEBUG_SHOW_INFO) { 10596 Log.v(TAG, " " 10597 + (s.info.nonLocalizedLabel != null 10598 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10599 Log.v(TAG, " Class=" + s.info.name); 10600 } 10601 final int NI = s.intents.size(); 10602 int j; 10603 for (j=0; j<NI; j++) { 10604 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10605 if (DEBUG_SHOW_INFO) { 10606 Log.v(TAG, " IntentFilter:"); 10607 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10608 } 10609 if (!intent.debugCheck()) { 10610 Log.w(TAG, "==> For Service " + s.info.name); 10611 } 10612 addFilter(intent); 10613 } 10614 } 10615 10616 public final void removeService(PackageParser.Service s) { 10617 mServices.remove(s.getComponentName()); 10618 if (DEBUG_SHOW_INFO) { 10619 Log.v(TAG, " " + (s.info.nonLocalizedLabel != null 10620 ? s.info.nonLocalizedLabel : s.info.name) + ":"); 10621 Log.v(TAG, " Class=" + s.info.name); 10622 } 10623 final int NI = s.intents.size(); 10624 int j; 10625 for (j=0; j<NI; j++) { 10626 PackageParser.ServiceIntentInfo intent = s.intents.get(j); 10627 if (DEBUG_SHOW_INFO) { 10628 Log.v(TAG, " IntentFilter:"); 10629 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10630 } 10631 removeFilter(intent); 10632 } 10633 } 10634 10635 @Override 10636 protected boolean allowFilterResult( 10637 PackageParser.ServiceIntentInfo filter, List<ResolveInfo> dest) { 10638 ServiceInfo filterSi = filter.service.info; 10639 for (int i=dest.size()-1; i>=0; i--) { 10640 ServiceInfo destAi = dest.get(i).serviceInfo; 10641 if (destAi.name == filterSi.name 10642 && destAi.packageName == filterSi.packageName) { 10643 return false; 10644 } 10645 } 10646 return true; 10647 } 10648 10649 @Override 10650 protected PackageParser.ServiceIntentInfo[] newArray(int size) { 10651 return new PackageParser.ServiceIntentInfo[size]; 10652 } 10653 10654 @Override 10655 protected boolean isFilterStopped(PackageParser.ServiceIntentInfo filter, int userId) { 10656 if (!sUserManager.exists(userId)) return true; 10657 PackageParser.Package p = filter.service.owner; 10658 if (p != null) { 10659 PackageSetting ps = (PackageSetting)p.mExtras; 10660 if (ps != null) { 10661 // System apps are never considered stopped for purposes of 10662 // filtering, because there may be no way for the user to 10663 // actually re-launch them. 10664 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10665 && ps.getStopped(userId); 10666 } 10667 } 10668 return false; 10669 } 10670 10671 @Override 10672 protected boolean isPackageForFilter(String packageName, 10673 PackageParser.ServiceIntentInfo info) { 10674 return packageName.equals(info.service.owner.packageName); 10675 } 10676 10677 @Override 10678 protected ResolveInfo newResult(PackageParser.ServiceIntentInfo filter, 10679 int match, int userId) { 10680 if (!sUserManager.exists(userId)) return null; 10681 final PackageParser.ServiceIntentInfo info = (PackageParser.ServiceIntentInfo)filter; 10682 if (!mSettings.isEnabledAndMatchLPr(info.service.info, mFlags, userId)) { 10683 return null; 10684 } 10685 final PackageParser.Service service = info.service; 10686 PackageSetting ps = (PackageSetting) service.owner.mExtras; 10687 if (ps == null) { 10688 return null; 10689 } 10690 ServiceInfo si = PackageParser.generateServiceInfo(service, mFlags, 10691 ps.readUserState(userId), userId); 10692 if (si == null) { 10693 return null; 10694 } 10695 final ResolveInfo res = new ResolveInfo(); 10696 res.serviceInfo = si; 10697 if ((mFlags&PackageManager.GET_RESOLVED_FILTER) != 0) { 10698 res.filter = filter; 10699 } 10700 res.priority = info.getPriority(); 10701 res.preferredOrder = service.owner.mPreferredOrder; 10702 res.match = match; 10703 res.isDefault = info.hasDefault; 10704 res.labelRes = info.labelRes; 10705 res.nonLocalizedLabel = info.nonLocalizedLabel; 10706 res.icon = info.icon; 10707 res.system = res.serviceInfo.applicationInfo.isSystemApp(); 10708 return res; 10709 } 10710 10711 @Override 10712 protected void sortResults(List<ResolveInfo> results) { 10713 Collections.sort(results, mResolvePrioritySorter); 10714 } 10715 10716 @Override 10717 protected void dumpFilter(PrintWriter out, String prefix, 10718 PackageParser.ServiceIntentInfo filter) { 10719 out.print(prefix); out.print( 10720 Integer.toHexString(System.identityHashCode(filter.service))); 10721 out.print(' '); 10722 filter.service.printComponentShortName(out); 10723 out.print(" filter "); 10724 out.println(Integer.toHexString(System.identityHashCode(filter))); 10725 } 10726 10727 @Override 10728 protected Object filterToLabel(PackageParser.ServiceIntentInfo filter) { 10729 return filter.service; 10730 } 10731 10732 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10733 PackageParser.Service service = (PackageParser.Service)label; 10734 out.print(prefix); out.print( 10735 Integer.toHexString(System.identityHashCode(service))); 10736 out.print(' '); 10737 service.printComponentShortName(out); 10738 if (count > 1) { 10739 out.print(" ("); out.print(count); out.print(" filters)"); 10740 } 10741 out.println(); 10742 } 10743 10744// List<ResolveInfo> filterEnabled(List<ResolveInfo> resolveInfoList) { 10745// final Iterator<ResolveInfo> i = resolveInfoList.iterator(); 10746// final List<ResolveInfo> retList = Lists.newArrayList(); 10747// while (i.hasNext()) { 10748// final ResolveInfo resolveInfo = (ResolveInfo) i; 10749// if (isEnabledLP(resolveInfo.serviceInfo)) { 10750// retList.add(resolveInfo); 10751// } 10752// } 10753// return retList; 10754// } 10755 10756 // Keys are String (activity class name), values are Activity. 10757 private final ArrayMap<ComponentName, PackageParser.Service> mServices 10758 = new ArrayMap<ComponentName, PackageParser.Service>(); 10759 private int mFlags; 10760 }; 10761 10762 private final class ProviderIntentResolver 10763 extends IntentResolver<PackageParser.ProviderIntentInfo, ResolveInfo> { 10764 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, 10765 boolean defaultOnly, int userId) { 10766 mFlags = defaultOnly ? PackageManager.MATCH_DEFAULT_ONLY : 0; 10767 return super.queryIntent(intent, resolvedType, defaultOnly, userId); 10768 } 10769 10770 public List<ResolveInfo> queryIntent(Intent intent, String resolvedType, int flags, 10771 int userId) { 10772 if (!sUserManager.exists(userId)) 10773 return null; 10774 mFlags = flags; 10775 return super.queryIntent(intent, resolvedType, 10776 (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0, userId); 10777 } 10778 10779 public List<ResolveInfo> queryIntentForPackage(Intent intent, String resolvedType, 10780 int flags, ArrayList<PackageParser.Provider> packageProviders, int userId) { 10781 if (!sUserManager.exists(userId)) 10782 return null; 10783 if (packageProviders == null) { 10784 return null; 10785 } 10786 mFlags = flags; 10787 final boolean defaultOnly = (flags & PackageManager.MATCH_DEFAULT_ONLY) != 0; 10788 final int N = packageProviders.size(); 10789 ArrayList<PackageParser.ProviderIntentInfo[]> listCut = 10790 new ArrayList<PackageParser.ProviderIntentInfo[]>(N); 10791 10792 ArrayList<PackageParser.ProviderIntentInfo> intentFilters; 10793 for (int i = 0; i < N; ++i) { 10794 intentFilters = packageProviders.get(i).intents; 10795 if (intentFilters != null && intentFilters.size() > 0) { 10796 PackageParser.ProviderIntentInfo[] array = 10797 new PackageParser.ProviderIntentInfo[intentFilters.size()]; 10798 intentFilters.toArray(array); 10799 listCut.add(array); 10800 } 10801 } 10802 return super.queryIntentFromList(intent, resolvedType, defaultOnly, listCut, userId); 10803 } 10804 10805 public final void addProvider(PackageParser.Provider p) { 10806 if (mProviders.containsKey(p.getComponentName())) { 10807 Slog.w(TAG, "Provider " + p.getComponentName() + " already defined; ignoring"); 10808 return; 10809 } 10810 10811 mProviders.put(p.getComponentName(), p); 10812 if (DEBUG_SHOW_INFO) { 10813 Log.v(TAG, " " 10814 + (p.info.nonLocalizedLabel != null 10815 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10816 Log.v(TAG, " Class=" + p.info.name); 10817 } 10818 final int NI = p.intents.size(); 10819 int j; 10820 for (j = 0; j < NI; j++) { 10821 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10822 if (DEBUG_SHOW_INFO) { 10823 Log.v(TAG, " IntentFilter:"); 10824 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10825 } 10826 if (!intent.debugCheck()) { 10827 Log.w(TAG, "==> For Provider " + p.info.name); 10828 } 10829 addFilter(intent); 10830 } 10831 } 10832 10833 public final void removeProvider(PackageParser.Provider p) { 10834 mProviders.remove(p.getComponentName()); 10835 if (DEBUG_SHOW_INFO) { 10836 Log.v(TAG, " " + (p.info.nonLocalizedLabel != null 10837 ? p.info.nonLocalizedLabel : p.info.name) + ":"); 10838 Log.v(TAG, " Class=" + p.info.name); 10839 } 10840 final int NI = p.intents.size(); 10841 int j; 10842 for (j = 0; j < NI; j++) { 10843 PackageParser.ProviderIntentInfo intent = p.intents.get(j); 10844 if (DEBUG_SHOW_INFO) { 10845 Log.v(TAG, " IntentFilter:"); 10846 intent.dump(new LogPrinter(Log.VERBOSE, TAG), " "); 10847 } 10848 removeFilter(intent); 10849 } 10850 } 10851 10852 @Override 10853 protected boolean allowFilterResult( 10854 PackageParser.ProviderIntentInfo filter, List<ResolveInfo> dest) { 10855 ProviderInfo filterPi = filter.provider.info; 10856 for (int i = dest.size() - 1; i >= 0; i--) { 10857 ProviderInfo destPi = dest.get(i).providerInfo; 10858 if (destPi.name == filterPi.name 10859 && destPi.packageName == filterPi.packageName) { 10860 return false; 10861 } 10862 } 10863 return true; 10864 } 10865 10866 @Override 10867 protected PackageParser.ProviderIntentInfo[] newArray(int size) { 10868 return new PackageParser.ProviderIntentInfo[size]; 10869 } 10870 10871 @Override 10872 protected boolean isFilterStopped(PackageParser.ProviderIntentInfo filter, int userId) { 10873 if (!sUserManager.exists(userId)) 10874 return true; 10875 PackageParser.Package p = filter.provider.owner; 10876 if (p != null) { 10877 PackageSetting ps = (PackageSetting) p.mExtras; 10878 if (ps != null) { 10879 // System apps are never considered stopped for purposes of 10880 // filtering, because there may be no way for the user to 10881 // actually re-launch them. 10882 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) == 0 10883 && ps.getStopped(userId); 10884 } 10885 } 10886 return false; 10887 } 10888 10889 @Override 10890 protected boolean isPackageForFilter(String packageName, 10891 PackageParser.ProviderIntentInfo info) { 10892 return packageName.equals(info.provider.owner.packageName); 10893 } 10894 10895 @Override 10896 protected ResolveInfo newResult(PackageParser.ProviderIntentInfo filter, 10897 int match, int userId) { 10898 if (!sUserManager.exists(userId)) 10899 return null; 10900 final PackageParser.ProviderIntentInfo info = filter; 10901 if (!mSettings.isEnabledAndMatchLPr(info.provider.info, mFlags, userId)) { 10902 return null; 10903 } 10904 final PackageParser.Provider provider = info.provider; 10905 PackageSetting ps = (PackageSetting) provider.owner.mExtras; 10906 if (ps == null) { 10907 return null; 10908 } 10909 ProviderInfo pi = PackageParser.generateProviderInfo(provider, mFlags, 10910 ps.readUserState(userId), userId); 10911 if (pi == null) { 10912 return null; 10913 } 10914 final ResolveInfo res = new ResolveInfo(); 10915 res.providerInfo = pi; 10916 if ((mFlags & PackageManager.GET_RESOLVED_FILTER) != 0) { 10917 res.filter = filter; 10918 } 10919 res.priority = info.getPriority(); 10920 res.preferredOrder = provider.owner.mPreferredOrder; 10921 res.match = match; 10922 res.isDefault = info.hasDefault; 10923 res.labelRes = info.labelRes; 10924 res.nonLocalizedLabel = info.nonLocalizedLabel; 10925 res.icon = info.icon; 10926 res.system = res.providerInfo.applicationInfo.isSystemApp(); 10927 return res; 10928 } 10929 10930 @Override 10931 protected void sortResults(List<ResolveInfo> results) { 10932 Collections.sort(results, mResolvePrioritySorter); 10933 } 10934 10935 @Override 10936 protected void dumpFilter(PrintWriter out, String prefix, 10937 PackageParser.ProviderIntentInfo filter) { 10938 out.print(prefix); 10939 out.print( 10940 Integer.toHexString(System.identityHashCode(filter.provider))); 10941 out.print(' '); 10942 filter.provider.printComponentShortName(out); 10943 out.print(" filter "); 10944 out.println(Integer.toHexString(System.identityHashCode(filter))); 10945 } 10946 10947 @Override 10948 protected Object filterToLabel(PackageParser.ProviderIntentInfo filter) { 10949 return filter.provider; 10950 } 10951 10952 protected void dumpFilterLabel(PrintWriter out, String prefix, Object label, int count) { 10953 PackageParser.Provider provider = (PackageParser.Provider)label; 10954 out.print(prefix); out.print( 10955 Integer.toHexString(System.identityHashCode(provider))); 10956 out.print(' '); 10957 provider.printComponentShortName(out); 10958 if (count > 1) { 10959 out.print(" ("); out.print(count); out.print(" filters)"); 10960 } 10961 out.println(); 10962 } 10963 10964 private final ArrayMap<ComponentName, PackageParser.Provider> mProviders 10965 = new ArrayMap<ComponentName, PackageParser.Provider>(); 10966 private int mFlags; 10967 } 10968 10969 private static final class EphemeralIntentResolver 10970 extends IntentResolver<EphemeralResolveIntentInfo, EphemeralResolveInfo> { 10971 @Override 10972 protected EphemeralResolveIntentInfo[] newArray(int size) { 10973 return new EphemeralResolveIntentInfo[size]; 10974 } 10975 10976 @Override 10977 protected boolean isPackageForFilter(String packageName, EphemeralResolveIntentInfo info) { 10978 return true; 10979 } 10980 10981 @Override 10982 protected EphemeralResolveInfo newResult(EphemeralResolveIntentInfo info, int match, 10983 int userId) { 10984 if (!sUserManager.exists(userId)) { 10985 return null; 10986 } 10987 return info.getEphemeralResolveInfo(); 10988 } 10989 } 10990 10991 private static final Comparator<ResolveInfo> mResolvePrioritySorter = 10992 new Comparator<ResolveInfo>() { 10993 public int compare(ResolveInfo r1, ResolveInfo r2) { 10994 int v1 = r1.priority; 10995 int v2 = r2.priority; 10996 //System.out.println("Comparing: q1=" + q1 + " q2=" + q2); 10997 if (v1 != v2) { 10998 return (v1 > v2) ? -1 : 1; 10999 } 11000 v1 = r1.preferredOrder; 11001 v2 = r2.preferredOrder; 11002 if (v1 != v2) { 11003 return (v1 > v2) ? -1 : 1; 11004 } 11005 if (r1.isDefault != r2.isDefault) { 11006 return r1.isDefault ? -1 : 1; 11007 } 11008 v1 = r1.match; 11009 v2 = r2.match; 11010 //System.out.println("Comparing: m1=" + m1 + " m2=" + m2); 11011 if (v1 != v2) { 11012 return (v1 > v2) ? -1 : 1; 11013 } 11014 if (r1.system != r2.system) { 11015 return r1.system ? -1 : 1; 11016 } 11017 if (r1.activityInfo != null) { 11018 return r1.activityInfo.packageName.compareTo(r2.activityInfo.packageName); 11019 } 11020 if (r1.serviceInfo != null) { 11021 return r1.serviceInfo.packageName.compareTo(r2.serviceInfo.packageName); 11022 } 11023 if (r1.providerInfo != null) { 11024 return r1.providerInfo.packageName.compareTo(r2.providerInfo.packageName); 11025 } 11026 return 0; 11027 } 11028 }; 11029 11030 private static final Comparator<ProviderInfo> mProviderInitOrderSorter = 11031 new Comparator<ProviderInfo>() { 11032 public int compare(ProviderInfo p1, ProviderInfo p2) { 11033 final int v1 = p1.initOrder; 11034 final int v2 = p2.initOrder; 11035 return (v1 > v2) ? -1 : ((v1 < v2) ? 1 : 0); 11036 } 11037 }; 11038 11039 final void sendPackageBroadcast(final String action, final String pkg, final Bundle extras, 11040 final int flags, final String targetPkg, final IIntentReceiver finishedReceiver, 11041 final int[] userIds) { 11042 mHandler.post(new Runnable() { 11043 @Override 11044 public void run() { 11045 try { 11046 final IActivityManager am = ActivityManagerNative.getDefault(); 11047 if (am == null) return; 11048 final int[] resolvedUserIds; 11049 if (userIds == null) { 11050 resolvedUserIds = am.getRunningUserIds(); 11051 } else { 11052 resolvedUserIds = userIds; 11053 } 11054 for (int id : resolvedUserIds) { 11055 final Intent intent = new Intent(action, 11056 pkg != null ? Uri.fromParts("package", pkg, null) : null); 11057 if (extras != null) { 11058 intent.putExtras(extras); 11059 } 11060 if (targetPkg != null) { 11061 intent.setPackage(targetPkg); 11062 } 11063 // Modify the UID when posting to other users 11064 int uid = intent.getIntExtra(Intent.EXTRA_UID, -1); 11065 if (uid > 0 && UserHandle.getUserId(uid) != id) { 11066 uid = UserHandle.getUid(id, UserHandle.getAppId(uid)); 11067 intent.putExtra(Intent.EXTRA_UID, uid); 11068 } 11069 intent.putExtra(Intent.EXTRA_USER_HANDLE, id); 11070 intent.addFlags(Intent.FLAG_RECEIVER_REGISTERED_ONLY_BEFORE_BOOT | flags); 11071 if (DEBUG_BROADCASTS) { 11072 RuntimeException here = new RuntimeException("here"); 11073 here.fillInStackTrace(); 11074 Slog.d(TAG, "Sending to user " + id + ": " 11075 + intent.toShortString(false, true, false, false) 11076 + " " + intent.getExtras(), here); 11077 } 11078 am.broadcastIntent(null, intent, null, finishedReceiver, 11079 0, null, null, null, android.app.AppOpsManager.OP_NONE, 11080 null, finishedReceiver != null, false, id); 11081 } 11082 } catch (RemoteException ex) { 11083 } 11084 } 11085 }); 11086 } 11087 11088 /** 11089 * Check if the external storage media is available. This is true if there 11090 * is a mounted external storage medium or if the external storage is 11091 * emulated. 11092 */ 11093 private boolean isExternalMediaAvailable() { 11094 return mMediaMounted || Environment.isExternalStorageEmulated(); 11095 } 11096 11097 @Override 11098 public PackageCleanItem nextPackageToClean(PackageCleanItem lastPackage) { 11099 // writer 11100 synchronized (mPackages) { 11101 if (!isExternalMediaAvailable()) { 11102 // If the external storage is no longer mounted at this point, 11103 // the caller may not have been able to delete all of this 11104 // packages files and can not delete any more. Bail. 11105 return null; 11106 } 11107 final ArrayList<PackageCleanItem> pkgs = mSettings.mPackagesToBeCleaned; 11108 if (lastPackage != null) { 11109 pkgs.remove(lastPackage); 11110 } 11111 if (pkgs.size() > 0) { 11112 return pkgs.get(0); 11113 } 11114 } 11115 return null; 11116 } 11117 11118 void schedulePackageCleaning(String packageName, int userId, boolean andCode) { 11119 final Message msg = mHandler.obtainMessage(START_CLEANING_PACKAGE, 11120 userId, andCode ? 1 : 0, packageName); 11121 if (mSystemReady) { 11122 msg.sendToTarget(); 11123 } else { 11124 if (mPostSystemReadyMessages == null) { 11125 mPostSystemReadyMessages = new ArrayList<>(); 11126 } 11127 mPostSystemReadyMessages.add(msg); 11128 } 11129 } 11130 11131 void startCleaningPackages() { 11132 // reader 11133 if (!isExternalMediaAvailable()) { 11134 return; 11135 } 11136 synchronized (mPackages) { 11137 if (mSettings.mPackagesToBeCleaned.isEmpty()) { 11138 return; 11139 } 11140 } 11141 Intent intent = new Intent(PackageManager.ACTION_CLEAN_EXTERNAL_STORAGE); 11142 intent.setComponent(DEFAULT_CONTAINER_COMPONENT); 11143 IActivityManager am = ActivityManagerNative.getDefault(); 11144 if (am != null) { 11145 try { 11146 am.startService(null, intent, null, mContext.getOpPackageName(), 11147 UserHandle.USER_SYSTEM); 11148 } catch (RemoteException e) { 11149 } 11150 } 11151 } 11152 11153 @Override 11154 public void installPackageAsUser(String originPath, IPackageInstallObserver2 observer, 11155 int installFlags, String installerPackageName, int userId) { 11156 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, null); 11157 11158 final int callingUid = Binder.getCallingUid(); 11159 enforceCrossUserPermission(callingUid, userId, 11160 true /* requireFullPermission */, true /* checkShell */, "installPackageAsUser"); 11161 11162 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11163 try { 11164 if (observer != null) { 11165 observer.onPackageInstalled("", INSTALL_FAILED_USER_RESTRICTED, null, null); 11166 } 11167 } catch (RemoteException re) { 11168 } 11169 return; 11170 } 11171 11172 if ((callingUid == Process.SHELL_UID) || (callingUid == Process.ROOT_UID)) { 11173 installFlags |= PackageManager.INSTALL_FROM_ADB; 11174 11175 } else { 11176 // Caller holds INSTALL_PACKAGES permission, so we're less strict 11177 // about installerPackageName. 11178 11179 installFlags &= ~PackageManager.INSTALL_FROM_ADB; 11180 installFlags &= ~PackageManager.INSTALL_ALL_USERS; 11181 } 11182 11183 UserHandle user; 11184 if ((installFlags & PackageManager.INSTALL_ALL_USERS) != 0) { 11185 user = UserHandle.ALL; 11186 } else { 11187 user = new UserHandle(userId); 11188 } 11189 11190 // Only system components can circumvent runtime permissions when installing. 11191 if ((installFlags & PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS) != 0 11192 && mContext.checkCallingOrSelfPermission(Manifest.permission 11193 .INSTALL_GRANT_RUNTIME_PERMISSIONS) == PackageManager.PERMISSION_DENIED) { 11194 throw new SecurityException("You need the " 11195 + "android.permission.INSTALL_GRANT_RUNTIME_PERMISSIONS permission " 11196 + "to use the PackageManager.INSTALL_GRANT_RUNTIME_PERMISSIONS flag"); 11197 } 11198 11199 final File originFile = new File(originPath); 11200 final OriginInfo origin = OriginInfo.fromUntrustedFile(originFile); 11201 11202 final Message msg = mHandler.obtainMessage(INIT_COPY); 11203 final VerificationInfo verificationInfo = new VerificationInfo( 11204 null /*originatingUri*/, null /*referrer*/, -1 /*originatingUid*/, callingUid); 11205 final InstallParams params = new InstallParams(origin, null /*moveInfo*/, observer, 11206 installFlags, installerPackageName, null /*volumeUuid*/, verificationInfo, user, 11207 null /*packageAbiOverride*/, null /*grantedPermissions*/, 11208 null /*certificates*/); 11209 params.setTraceMethod("installAsUser").setTraceCookie(System.identityHashCode(params)); 11210 msg.obj = params; 11211 11212 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installAsUser", 11213 System.identityHashCode(msg.obj)); 11214 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11215 System.identityHashCode(msg.obj)); 11216 11217 mHandler.sendMessage(msg); 11218 } 11219 11220 void installStage(String packageName, File stagedDir, String stagedCid, 11221 IPackageInstallObserver2 observer, PackageInstaller.SessionParams sessionParams, 11222 String installerPackageName, int installerUid, UserHandle user, 11223 Certificate[][] certificates) { 11224 if (DEBUG_EPHEMERAL) { 11225 if ((sessionParams.installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11226 Slog.d(TAG, "Ephemeral install of " + packageName); 11227 } 11228 } 11229 final VerificationInfo verificationInfo = new VerificationInfo( 11230 sessionParams.originatingUri, sessionParams.referrerUri, 11231 sessionParams.originatingUid, installerUid); 11232 11233 final OriginInfo origin; 11234 if (stagedDir != null) { 11235 origin = OriginInfo.fromStagedFile(stagedDir); 11236 } else { 11237 origin = OriginInfo.fromStagedContainer(stagedCid); 11238 } 11239 11240 final Message msg = mHandler.obtainMessage(INIT_COPY); 11241 final InstallParams params = new InstallParams(origin, null, observer, 11242 sessionParams.installFlags, installerPackageName, sessionParams.volumeUuid, 11243 verificationInfo, user, sessionParams.abiOverride, 11244 sessionParams.grantedRuntimePermissions, certificates); 11245 params.setTraceMethod("installStage").setTraceCookie(System.identityHashCode(params)); 11246 msg.obj = params; 11247 11248 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "installStage", 11249 System.identityHashCode(msg.obj)); 11250 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 11251 System.identityHashCode(msg.obj)); 11252 11253 mHandler.sendMessage(msg); 11254 } 11255 11256 private void sendPackageAddedForUser(String packageName, PackageSetting pkgSetting, 11257 int userId) { 11258 final boolean isSystem = isSystemApp(pkgSetting) || isUpdatedSystemApp(pkgSetting); 11259 sendPackageAddedForUser(packageName, isSystem, pkgSetting.appId, userId); 11260 } 11261 11262 private void sendPackageAddedForUser(String packageName, boolean isSystem, 11263 int appId, int userId) { 11264 Bundle extras = new Bundle(1); 11265 extras.putInt(Intent.EXTRA_UID, UserHandle.getUid(userId, appId)); 11266 11267 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, 11268 packageName, extras, 0, null, null, new int[] {userId}); 11269 try { 11270 IActivityManager am = ActivityManagerNative.getDefault(); 11271 if (isSystem && am.isUserRunning(userId, 0)) { 11272 // The just-installed/enabled app is bundled on the system, so presumed 11273 // to be able to run automatically without needing an explicit launch. 11274 // Send it a BOOT_COMPLETED if it would ordinarily have gotten one. 11275 Intent bcIntent = new Intent(Intent.ACTION_BOOT_COMPLETED) 11276 .addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES) 11277 .setPackage(packageName); 11278 am.broadcastIntent(null, bcIntent, null, null, 0, null, null, null, 11279 android.app.AppOpsManager.OP_NONE, null, false, false, userId); 11280 } 11281 } catch (RemoteException e) { 11282 // shouldn't happen 11283 Slog.w(TAG, "Unable to bootstrap installed package", e); 11284 } 11285 } 11286 11287 @Override 11288 public boolean setApplicationHiddenSettingAsUser(String packageName, boolean hidden, 11289 int userId) { 11290 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11291 PackageSetting pkgSetting; 11292 final int uid = Binder.getCallingUid(); 11293 enforceCrossUserPermission(uid, userId, 11294 true /* requireFullPermission */, true /* checkShell */, 11295 "setApplicationHiddenSetting for user " + userId); 11296 11297 if (hidden && isPackageDeviceAdmin(packageName, userId)) { 11298 Slog.w(TAG, "Not hiding package " + packageName + ": has active device admin"); 11299 return false; 11300 } 11301 11302 long callingId = Binder.clearCallingIdentity(); 11303 try { 11304 boolean sendAdded = false; 11305 boolean sendRemoved = false; 11306 // writer 11307 synchronized (mPackages) { 11308 pkgSetting = mSettings.mPackages.get(packageName); 11309 if (pkgSetting == null) { 11310 return false; 11311 } 11312 if (pkgSetting.getHidden(userId) != hidden) { 11313 pkgSetting.setHidden(hidden, userId); 11314 mSettings.writePackageRestrictionsLPr(userId); 11315 if (hidden) { 11316 sendRemoved = true; 11317 } else { 11318 sendAdded = true; 11319 } 11320 } 11321 } 11322 if (sendAdded) { 11323 sendPackageAddedForUser(packageName, pkgSetting, userId); 11324 return true; 11325 } 11326 if (sendRemoved) { 11327 killApplication(packageName, UserHandle.getUid(userId, pkgSetting.appId), 11328 "hiding pkg"); 11329 sendApplicationHiddenForUser(packageName, pkgSetting, userId); 11330 return true; 11331 } 11332 } finally { 11333 Binder.restoreCallingIdentity(callingId); 11334 } 11335 return false; 11336 } 11337 11338 private void sendApplicationHiddenForUser(String packageName, PackageSetting pkgSetting, 11339 int userId) { 11340 final PackageRemovedInfo info = new PackageRemovedInfo(); 11341 info.removedPackage = packageName; 11342 info.removedUsers = new int[] {userId}; 11343 info.uid = UserHandle.getUid(userId, pkgSetting.appId); 11344 info.sendPackageRemovedBroadcasts(true /*killApp*/); 11345 } 11346 11347 private void sendPackagesSuspendedForUser(String[] pkgList, int userId, boolean suspended) { 11348 if (pkgList.length > 0) { 11349 Bundle extras = new Bundle(1); 11350 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 11351 11352 sendPackageBroadcast( 11353 suspended ? Intent.ACTION_PACKAGES_SUSPENDED 11354 : Intent.ACTION_PACKAGES_UNSUSPENDED, 11355 null, extras, Intent.FLAG_RECEIVER_REGISTERED_ONLY, null, null, 11356 new int[] {userId}); 11357 } 11358 } 11359 11360 /** 11361 * Returns true if application is not found or there was an error. Otherwise it returns 11362 * the hidden state of the package for the given user. 11363 */ 11364 @Override 11365 public boolean getApplicationHiddenSettingAsUser(String packageName, int userId) { 11366 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11367 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11368 true /* requireFullPermission */, false /* checkShell */, 11369 "getApplicationHidden for user " + userId); 11370 PackageSetting pkgSetting; 11371 long callingId = Binder.clearCallingIdentity(); 11372 try { 11373 // writer 11374 synchronized (mPackages) { 11375 pkgSetting = mSettings.mPackages.get(packageName); 11376 if (pkgSetting == null) { 11377 return true; 11378 } 11379 return pkgSetting.getHidden(userId); 11380 } 11381 } finally { 11382 Binder.restoreCallingIdentity(callingId); 11383 } 11384 } 11385 11386 /** 11387 * @hide 11388 */ 11389 @Override 11390 public int installExistingPackageAsUser(String packageName, int userId) { 11391 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.INSTALL_PACKAGES, 11392 null); 11393 PackageSetting pkgSetting; 11394 final int uid = Binder.getCallingUid(); 11395 enforceCrossUserPermission(uid, userId, 11396 true /* requireFullPermission */, true /* checkShell */, 11397 "installExistingPackage for user " + userId); 11398 if (isUserRestricted(userId, UserManager.DISALLOW_INSTALL_APPS)) { 11399 return PackageManager.INSTALL_FAILED_USER_RESTRICTED; 11400 } 11401 11402 long callingId = Binder.clearCallingIdentity(); 11403 try { 11404 boolean installed = false; 11405 11406 // writer 11407 synchronized (mPackages) { 11408 pkgSetting = mSettings.mPackages.get(packageName); 11409 if (pkgSetting == null) { 11410 return PackageManager.INSTALL_FAILED_INVALID_URI; 11411 } 11412 if (!pkgSetting.getInstalled(userId)) { 11413 pkgSetting.setInstalled(true, userId); 11414 pkgSetting.setHidden(false, userId); 11415 mSettings.writePackageRestrictionsLPr(userId); 11416 installed = true; 11417 } 11418 } 11419 11420 if (installed) { 11421 if (pkgSetting.pkg != null) { 11422 synchronized (mInstallLock) { 11423 // We don't need to freeze for a brand new install 11424 prepareAppDataAfterInstallLIF(pkgSetting.pkg); 11425 } 11426 } 11427 sendPackageAddedForUser(packageName, pkgSetting, userId); 11428 } 11429 } finally { 11430 Binder.restoreCallingIdentity(callingId); 11431 } 11432 11433 return PackageManager.INSTALL_SUCCEEDED; 11434 } 11435 11436 boolean isUserRestricted(int userId, String restrictionKey) { 11437 Bundle restrictions = sUserManager.getUserRestrictions(userId); 11438 if (restrictions.getBoolean(restrictionKey, false)) { 11439 Log.w(TAG, "User is restricted: " + restrictionKey); 11440 return true; 11441 } 11442 return false; 11443 } 11444 11445 @Override 11446 public String[] setPackagesSuspendedAsUser(String[] packageNames, boolean suspended, 11447 int userId) { 11448 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MANAGE_USERS, null); 11449 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11450 true /* requireFullPermission */, true /* checkShell */, 11451 "setPackagesSuspended for user " + userId); 11452 11453 if (ArrayUtils.isEmpty(packageNames)) { 11454 return packageNames; 11455 } 11456 11457 // List of package names for whom the suspended state has changed. 11458 List<String> changedPackages = new ArrayList<>(packageNames.length); 11459 // List of package names for whom the suspended state is not set as requested in this 11460 // method. 11461 List<String> unactionedPackages = new ArrayList<>(packageNames.length); 11462 for (int i = 0; i < packageNames.length; i++) { 11463 String packageName = packageNames[i]; 11464 long callingId = Binder.clearCallingIdentity(); 11465 try { 11466 boolean changed = false; 11467 final int appId; 11468 synchronized (mPackages) { 11469 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11470 if (pkgSetting == null) { 11471 Slog.w(TAG, "Could not find package setting for package \"" + packageName 11472 + "\". Skipping suspending/un-suspending."); 11473 unactionedPackages.add(packageName); 11474 continue; 11475 } 11476 appId = pkgSetting.appId; 11477 if (pkgSetting.getSuspended(userId) != suspended) { 11478 if (!canSuspendPackageForUserLocked(packageName, userId)) { 11479 unactionedPackages.add(packageName); 11480 continue; 11481 } 11482 pkgSetting.setSuspended(suspended, userId); 11483 mSettings.writePackageRestrictionsLPr(userId); 11484 changed = true; 11485 changedPackages.add(packageName); 11486 } 11487 } 11488 11489 if (changed && suspended) { 11490 killApplication(packageName, UserHandle.getUid(userId, appId), 11491 "suspending package"); 11492 } 11493 } finally { 11494 Binder.restoreCallingIdentity(callingId); 11495 } 11496 } 11497 11498 if (!changedPackages.isEmpty()) { 11499 sendPackagesSuspendedForUser(changedPackages.toArray( 11500 new String[changedPackages.size()]), userId, suspended); 11501 } 11502 11503 return unactionedPackages.toArray(new String[unactionedPackages.size()]); 11504 } 11505 11506 @Override 11507 public boolean isPackageSuspendedForUser(String packageName, int userId) { 11508 enforceCrossUserPermission(Binder.getCallingUid(), userId, 11509 true /* requireFullPermission */, false /* checkShell */, 11510 "isPackageSuspendedForUser for user " + userId); 11511 synchronized (mPackages) { 11512 final PackageSetting pkgSetting = mSettings.mPackages.get(packageName); 11513 if (pkgSetting == null) { 11514 throw new IllegalArgumentException("Unknown target package: " + packageName); 11515 } 11516 return pkgSetting.getSuspended(userId); 11517 } 11518 } 11519 11520 /** 11521 * TODO: cache and disallow blocking the active dialer. 11522 * 11523 * @see also DefaultPermissionGrantPolicy#grantDefaultSystemHandlerPermissions 11524 */ 11525 private boolean canSuspendPackageForUserLocked(String packageName, int userId) { 11526 if (isPackageDeviceAdmin(packageName, userId)) { 11527 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11528 + "\": has an active device admin"); 11529 return false; 11530 } 11531 11532 String activeLauncherPackageName = getActiveLauncherPackageName(userId); 11533 if (packageName.equals(activeLauncherPackageName)) { 11534 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11535 + "\": contains the active launcher"); 11536 return false; 11537 } 11538 11539 if (packageName.equals(mRequiredInstallerPackage)) { 11540 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11541 + "\": required for package installation"); 11542 return false; 11543 } 11544 11545 if (packageName.equals(mRequiredVerifierPackage)) { 11546 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11547 + "\": required for package verification"); 11548 return false; 11549 } 11550 11551 final PackageParser.Package pkg = mPackages.get(packageName); 11552 if (pkg != null && isPrivilegedApp(pkg)) { 11553 Slog.w(TAG, "Cannot suspend/un-suspend package \"" + packageName 11554 + "\": is a privileged app"); 11555 return false; 11556 } 11557 11558 return true; 11559 } 11560 11561 private String getActiveLauncherPackageName(int userId) { 11562 Intent intent = new Intent(Intent.ACTION_MAIN); 11563 intent.addCategory(Intent.CATEGORY_HOME); 11564 ResolveInfo resolveInfo = resolveIntent( 11565 intent, 11566 intent.resolveTypeIfNeeded(mContext.getContentResolver()), 11567 PackageManager.MATCH_DEFAULT_ONLY, 11568 userId); 11569 11570 return resolveInfo == null ? null : resolveInfo.activityInfo.packageName; 11571 } 11572 11573 @Override 11574 public void verifyPendingInstall(int id, int verificationCode) throws RemoteException { 11575 mContext.enforceCallingOrSelfPermission( 11576 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11577 "Only package verification agents can verify applications"); 11578 11579 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11580 final PackageVerificationResponse response = new PackageVerificationResponse( 11581 verificationCode, Binder.getCallingUid()); 11582 msg.arg1 = id; 11583 msg.obj = response; 11584 mHandler.sendMessage(msg); 11585 } 11586 11587 @Override 11588 public void extendVerificationTimeout(int id, int verificationCodeAtTimeout, 11589 long millisecondsToDelay) { 11590 mContext.enforceCallingOrSelfPermission( 11591 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 11592 "Only package verification agents can extend verification timeouts"); 11593 11594 final PackageVerificationState state = mPendingVerification.get(id); 11595 final PackageVerificationResponse response = new PackageVerificationResponse( 11596 verificationCodeAtTimeout, Binder.getCallingUid()); 11597 11598 if (millisecondsToDelay > PackageManager.MAXIMUM_VERIFICATION_TIMEOUT) { 11599 millisecondsToDelay = PackageManager.MAXIMUM_VERIFICATION_TIMEOUT; 11600 } 11601 if (millisecondsToDelay < 0) { 11602 millisecondsToDelay = 0; 11603 } 11604 if ((verificationCodeAtTimeout != PackageManager.VERIFICATION_ALLOW) 11605 && (verificationCodeAtTimeout != PackageManager.VERIFICATION_REJECT)) { 11606 verificationCodeAtTimeout = PackageManager.VERIFICATION_REJECT; 11607 } 11608 11609 if ((state != null) && !state.timeoutExtended()) { 11610 state.extendTimeout(); 11611 11612 final Message msg = mHandler.obtainMessage(PACKAGE_VERIFIED); 11613 msg.arg1 = id; 11614 msg.obj = response; 11615 mHandler.sendMessageDelayed(msg, millisecondsToDelay); 11616 } 11617 } 11618 11619 private void broadcastPackageVerified(int verificationId, Uri packageUri, 11620 int verificationCode, UserHandle user) { 11621 final Intent intent = new Intent(Intent.ACTION_PACKAGE_VERIFIED); 11622 intent.setDataAndType(packageUri, PACKAGE_MIME_TYPE); 11623 intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 11624 intent.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 11625 intent.putExtra(PackageManager.EXTRA_VERIFICATION_RESULT, verificationCode); 11626 11627 mContext.sendBroadcastAsUser(intent, user, 11628 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT); 11629 } 11630 11631 private ComponentName matchComponentForVerifier(String packageName, 11632 List<ResolveInfo> receivers) { 11633 ActivityInfo targetReceiver = null; 11634 11635 final int NR = receivers.size(); 11636 for (int i = 0; i < NR; i++) { 11637 final ResolveInfo info = receivers.get(i); 11638 if (info.activityInfo == null) { 11639 continue; 11640 } 11641 11642 if (packageName.equals(info.activityInfo.packageName)) { 11643 targetReceiver = info.activityInfo; 11644 break; 11645 } 11646 } 11647 11648 if (targetReceiver == null) { 11649 return null; 11650 } 11651 11652 return new ComponentName(targetReceiver.packageName, targetReceiver.name); 11653 } 11654 11655 private List<ComponentName> matchVerifiers(PackageInfoLite pkgInfo, 11656 List<ResolveInfo> receivers, final PackageVerificationState verificationState) { 11657 if (pkgInfo.verifiers.length == 0) { 11658 return null; 11659 } 11660 11661 final int N = pkgInfo.verifiers.length; 11662 final List<ComponentName> sufficientVerifiers = new ArrayList<ComponentName>(N + 1); 11663 for (int i = 0; i < N; i++) { 11664 final VerifierInfo verifierInfo = pkgInfo.verifiers[i]; 11665 11666 final ComponentName comp = matchComponentForVerifier(verifierInfo.packageName, 11667 receivers); 11668 if (comp == null) { 11669 continue; 11670 } 11671 11672 final int verifierUid = getUidForVerifier(verifierInfo); 11673 if (verifierUid == -1) { 11674 continue; 11675 } 11676 11677 if (DEBUG_VERIFY) { 11678 Slog.d(TAG, "Added sufficient verifier " + verifierInfo.packageName 11679 + " with the correct signature"); 11680 } 11681 sufficientVerifiers.add(comp); 11682 verificationState.addSufficientVerifier(verifierUid); 11683 } 11684 11685 return sufficientVerifiers; 11686 } 11687 11688 private int getUidForVerifier(VerifierInfo verifierInfo) { 11689 synchronized (mPackages) { 11690 final PackageParser.Package pkg = mPackages.get(verifierInfo.packageName); 11691 if (pkg == null) { 11692 return -1; 11693 } else if (pkg.mSignatures.length != 1) { 11694 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11695 + " has more than one signature; ignoring"); 11696 return -1; 11697 } 11698 11699 /* 11700 * If the public key of the package's signature does not match 11701 * our expected public key, then this is a different package and 11702 * we should skip. 11703 */ 11704 11705 final byte[] expectedPublicKey; 11706 try { 11707 final Signature verifierSig = pkg.mSignatures[0]; 11708 final PublicKey publicKey = verifierSig.getPublicKey(); 11709 expectedPublicKey = publicKey.getEncoded(); 11710 } catch (CertificateException e) { 11711 return -1; 11712 } 11713 11714 final byte[] actualPublicKey = verifierInfo.publicKey.getEncoded(); 11715 11716 if (!Arrays.equals(actualPublicKey, expectedPublicKey)) { 11717 Slog.i(TAG, "Verifier package " + verifierInfo.packageName 11718 + " does not have the expected public key; ignoring"); 11719 return -1; 11720 } 11721 11722 return pkg.applicationInfo.uid; 11723 } 11724 } 11725 11726 @Override 11727 public void finishPackageInstall(int token) { 11728 enforceSystemOrRoot("Only the system is allowed to finish installs"); 11729 11730 if (DEBUG_INSTALL) { 11731 Slog.v(TAG, "BM finishing package install for " + token); 11732 } 11733 Trace.asyncTraceEnd(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 11734 11735 final Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 11736 mHandler.sendMessage(msg); 11737 } 11738 11739 /** 11740 * Get the verification agent timeout. 11741 * 11742 * @return verification timeout in milliseconds 11743 */ 11744 private long getVerificationTimeout() { 11745 return android.provider.Settings.Global.getLong(mContext.getContentResolver(), 11746 android.provider.Settings.Global.PACKAGE_VERIFIER_TIMEOUT, 11747 DEFAULT_VERIFICATION_TIMEOUT); 11748 } 11749 11750 /** 11751 * Get the default verification agent response code. 11752 * 11753 * @return default verification response code 11754 */ 11755 private int getDefaultVerificationResponse() { 11756 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11757 android.provider.Settings.Global.PACKAGE_VERIFIER_DEFAULT_RESPONSE, 11758 DEFAULT_VERIFICATION_RESPONSE); 11759 } 11760 11761 /** 11762 * Check whether or not package verification has been enabled. 11763 * 11764 * @return true if verification should be performed 11765 */ 11766 private boolean isVerificationEnabled(int userId, int installFlags) { 11767 if (!DEFAULT_VERIFY_ENABLE) { 11768 return false; 11769 } 11770 // Ephemeral apps don't get the full verification treatment 11771 if ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0) { 11772 if (DEBUG_EPHEMERAL) { 11773 Slog.d(TAG, "INSTALL_EPHEMERAL so skipping verification"); 11774 } 11775 return false; 11776 } 11777 11778 boolean ensureVerifyAppsEnabled = isUserRestricted(userId, UserManager.ENSURE_VERIFY_APPS); 11779 11780 // Check if installing from ADB 11781 if ((installFlags & PackageManager.INSTALL_FROM_ADB) != 0) { 11782 // Do not run verification in a test harness environment 11783 if (ActivityManager.isRunningInTestHarness()) { 11784 return false; 11785 } 11786 if (ensureVerifyAppsEnabled) { 11787 return true; 11788 } 11789 // Check if the developer does not want package verification for ADB installs 11790 if (android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11791 android.provider.Settings.Global.PACKAGE_VERIFIER_INCLUDE_ADB, 1) == 0) { 11792 return false; 11793 } 11794 } 11795 11796 if (ensureVerifyAppsEnabled) { 11797 return true; 11798 } 11799 11800 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 11801 android.provider.Settings.Global.PACKAGE_VERIFIER_ENABLE, 1) == 1; 11802 } 11803 11804 @Override 11805 public void verifyIntentFilter(int id, int verificationCode, List<String> failedDomains) 11806 throws RemoteException { 11807 mContext.enforceCallingOrSelfPermission( 11808 Manifest.permission.INTENT_FILTER_VERIFICATION_AGENT, 11809 "Only intentfilter verification agents can verify applications"); 11810 11811 final Message msg = mHandler.obtainMessage(INTENT_FILTER_VERIFIED); 11812 final IntentFilterVerificationResponse response = new IntentFilterVerificationResponse( 11813 Binder.getCallingUid(), verificationCode, failedDomains); 11814 msg.arg1 = id; 11815 msg.obj = response; 11816 mHandler.sendMessage(msg); 11817 } 11818 11819 @Override 11820 public int getIntentVerificationStatus(String packageName, int userId) { 11821 synchronized (mPackages) { 11822 return mSettings.getIntentFilterVerificationStatusLPr(packageName, userId); 11823 } 11824 } 11825 11826 @Override 11827 public boolean updateIntentVerificationStatus(String packageName, int status, int userId) { 11828 mContext.enforceCallingOrSelfPermission( 11829 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11830 11831 boolean result = false; 11832 synchronized (mPackages) { 11833 result = mSettings.updateIntentFilterVerificationStatusLPw(packageName, status, userId); 11834 } 11835 if (result) { 11836 scheduleWritePackageRestrictionsLocked(userId); 11837 } 11838 return result; 11839 } 11840 11841 @Override 11842 public @NonNull ParceledListSlice<IntentFilterVerificationInfo> getIntentFilterVerifications( 11843 String packageName) { 11844 synchronized (mPackages) { 11845 return new ParceledListSlice<>(mSettings.getIntentFilterVerificationsLPr(packageName)); 11846 } 11847 } 11848 11849 @Override 11850 public @NonNull ParceledListSlice<IntentFilter> getAllIntentFilters(String packageName) { 11851 if (TextUtils.isEmpty(packageName)) { 11852 return ParceledListSlice.emptyList(); 11853 } 11854 synchronized (mPackages) { 11855 PackageParser.Package pkg = mPackages.get(packageName); 11856 if (pkg == null || pkg.activities == null) { 11857 return ParceledListSlice.emptyList(); 11858 } 11859 final int count = pkg.activities.size(); 11860 ArrayList<IntentFilter> result = new ArrayList<>(); 11861 for (int n=0; n<count; n++) { 11862 PackageParser.Activity activity = pkg.activities.get(n); 11863 if (activity.intents != null && activity.intents.size() > 0) { 11864 result.addAll(activity.intents); 11865 } 11866 } 11867 return new ParceledListSlice<>(result); 11868 } 11869 } 11870 11871 @Override 11872 public boolean setDefaultBrowserPackageName(String packageName, int userId) { 11873 mContext.enforceCallingOrSelfPermission( 11874 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 11875 11876 synchronized (mPackages) { 11877 boolean result = mSettings.setDefaultBrowserPackageNameLPw(packageName, userId); 11878 if (packageName != null) { 11879 result |= updateIntentVerificationStatus(packageName, 11880 PackageManager.INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ALWAYS, 11881 userId); 11882 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultBrowserLPr( 11883 packageName, userId); 11884 } 11885 return result; 11886 } 11887 } 11888 11889 @Override 11890 public String getDefaultBrowserPackageName(int userId) { 11891 synchronized (mPackages) { 11892 return mSettings.getDefaultBrowserPackageNameLPw(userId); 11893 } 11894 } 11895 11896 /** 11897 * Get the "allow unknown sources" setting. 11898 * 11899 * @return the current "allow unknown sources" setting 11900 */ 11901 private int getUnknownSourcesSettings() { 11902 return android.provider.Settings.Secure.getInt(mContext.getContentResolver(), 11903 android.provider.Settings.Secure.INSTALL_NON_MARKET_APPS, 11904 -1); 11905 } 11906 11907 @Override 11908 public void setInstallerPackageName(String targetPackage, String installerPackageName) { 11909 final int uid = Binder.getCallingUid(); 11910 // writer 11911 synchronized (mPackages) { 11912 PackageSetting targetPackageSetting = mSettings.mPackages.get(targetPackage); 11913 if (targetPackageSetting == null) { 11914 throw new IllegalArgumentException("Unknown target package: " + targetPackage); 11915 } 11916 11917 PackageSetting installerPackageSetting; 11918 if (installerPackageName != null) { 11919 installerPackageSetting = mSettings.mPackages.get(installerPackageName); 11920 if (installerPackageSetting == null) { 11921 throw new IllegalArgumentException("Unknown installer package: " 11922 + installerPackageName); 11923 } 11924 } else { 11925 installerPackageSetting = null; 11926 } 11927 11928 Signature[] callerSignature; 11929 Object obj = mSettings.getUserIdLPr(uid); 11930 if (obj != null) { 11931 if (obj instanceof SharedUserSetting) { 11932 callerSignature = ((SharedUserSetting)obj).signatures.mSignatures; 11933 } else if (obj instanceof PackageSetting) { 11934 callerSignature = ((PackageSetting)obj).signatures.mSignatures; 11935 } else { 11936 throw new SecurityException("Bad object " + obj + " for uid " + uid); 11937 } 11938 } else { 11939 throw new SecurityException("Unknown calling UID: " + uid); 11940 } 11941 11942 // Verify: can't set installerPackageName to a package that is 11943 // not signed with the same cert as the caller. 11944 if (installerPackageSetting != null) { 11945 if (compareSignatures(callerSignature, 11946 installerPackageSetting.signatures.mSignatures) 11947 != PackageManager.SIGNATURE_MATCH) { 11948 throw new SecurityException( 11949 "Caller does not have same cert as new installer package " 11950 + installerPackageName); 11951 } 11952 } 11953 11954 // Verify: if target already has an installer package, it must 11955 // be signed with the same cert as the caller. 11956 if (targetPackageSetting.installerPackageName != null) { 11957 PackageSetting setting = mSettings.mPackages.get( 11958 targetPackageSetting.installerPackageName); 11959 // If the currently set package isn't valid, then it's always 11960 // okay to change it. 11961 if (setting != null) { 11962 if (compareSignatures(callerSignature, 11963 setting.signatures.mSignatures) 11964 != PackageManager.SIGNATURE_MATCH) { 11965 throw new SecurityException( 11966 "Caller does not have same cert as old installer package " 11967 + targetPackageSetting.installerPackageName); 11968 } 11969 } 11970 } 11971 11972 // Okay! 11973 targetPackageSetting.installerPackageName = installerPackageName; 11974 if (installerPackageName != null) { 11975 mSettings.mInstallerPackages.add(installerPackageName); 11976 } 11977 scheduleWriteSettingsLocked(); 11978 } 11979 } 11980 11981 private void processPendingInstall(final InstallArgs args, final int currentStatus) { 11982 // Queue up an async operation since the package installation may take a little while. 11983 mHandler.post(new Runnable() { 11984 public void run() { 11985 mHandler.removeCallbacks(this); 11986 // Result object to be returned 11987 PackageInstalledInfo res = new PackageInstalledInfo(); 11988 res.setReturnCode(currentStatus); 11989 res.uid = -1; 11990 res.pkg = null; 11991 res.removedInfo = null; 11992 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 11993 args.doPreInstall(res.returnCode); 11994 synchronized (mInstallLock) { 11995 installPackageTracedLI(args, res); 11996 } 11997 args.doPostInstall(res.returnCode, res.uid); 11998 } 11999 12000 // A restore should be performed at this point if (a) the install 12001 // succeeded, (b) the operation is not an update, and (c) the new 12002 // package has not opted out of backup participation. 12003 final boolean update = res.removedInfo != null 12004 && res.removedInfo.removedPackage != null; 12005 final int flags = (res.pkg == null) ? 0 : res.pkg.applicationInfo.flags; 12006 boolean doRestore = !update 12007 && ((flags & ApplicationInfo.FLAG_ALLOW_BACKUP) != 0); 12008 12009 // Set up the post-install work request bookkeeping. This will be used 12010 // and cleaned up by the post-install event handling regardless of whether 12011 // there's a restore pass performed. Token values are >= 1. 12012 int token; 12013 if (mNextInstallToken < 0) mNextInstallToken = 1; 12014 token = mNextInstallToken++; 12015 12016 PostInstallData data = new PostInstallData(args, res); 12017 mRunningInstalls.put(token, data); 12018 if (DEBUG_INSTALL) Log.v(TAG, "+ starting restore round-trip " + token); 12019 12020 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED && doRestore) { 12021 // Pass responsibility to the Backup Manager. It will perform a 12022 // restore if appropriate, then pass responsibility back to the 12023 // Package Manager to run the post-install observer callbacks 12024 // and broadcasts. 12025 IBackupManager bm = IBackupManager.Stub.asInterface( 12026 ServiceManager.getService(Context.BACKUP_SERVICE)); 12027 if (bm != null) { 12028 if (DEBUG_INSTALL) Log.v(TAG, "token " + token 12029 + " to BM for possible restore"); 12030 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "restore", token); 12031 try { 12032 // TODO: http://b/22388012 12033 if (bm.isBackupServiceActive(UserHandle.USER_SYSTEM)) { 12034 bm.restoreAtInstall(res.pkg.applicationInfo.packageName, token); 12035 } else { 12036 doRestore = false; 12037 } 12038 } catch (RemoteException e) { 12039 // can't happen; the backup manager is local 12040 } catch (Exception e) { 12041 Slog.e(TAG, "Exception trying to enqueue restore", e); 12042 doRestore = false; 12043 } 12044 } else { 12045 Slog.e(TAG, "Backup Manager not found!"); 12046 doRestore = false; 12047 } 12048 } 12049 12050 if (!doRestore) { 12051 // No restore possible, or the Backup Manager was mysteriously not 12052 // available -- just fire the post-install work request directly. 12053 if (DEBUG_INSTALL) Log.v(TAG, "No restore - queue post-install for " + token); 12054 12055 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "postInstall", token); 12056 12057 Message msg = mHandler.obtainMessage(POST_INSTALL, token, 0); 12058 mHandler.sendMessage(msg); 12059 } 12060 } 12061 }); 12062 } 12063 12064 private abstract class HandlerParams { 12065 private static final int MAX_RETRIES = 4; 12066 12067 /** 12068 * Number of times startCopy() has been attempted and had a non-fatal 12069 * error. 12070 */ 12071 private int mRetries = 0; 12072 12073 /** User handle for the user requesting the information or installation. */ 12074 private final UserHandle mUser; 12075 String traceMethod; 12076 int traceCookie; 12077 12078 HandlerParams(UserHandle user) { 12079 mUser = user; 12080 } 12081 12082 UserHandle getUser() { 12083 return mUser; 12084 } 12085 12086 HandlerParams setTraceMethod(String traceMethod) { 12087 this.traceMethod = traceMethod; 12088 return this; 12089 } 12090 12091 HandlerParams setTraceCookie(int traceCookie) { 12092 this.traceCookie = traceCookie; 12093 return this; 12094 } 12095 12096 final boolean startCopy() { 12097 boolean res; 12098 try { 12099 if (DEBUG_INSTALL) Slog.i(TAG, "startCopy " + mUser + ": " + this); 12100 12101 if (++mRetries > MAX_RETRIES) { 12102 Slog.w(TAG, "Failed to invoke remote methods on default container service. Giving up"); 12103 mHandler.sendEmptyMessage(MCS_GIVE_UP); 12104 handleServiceError(); 12105 return false; 12106 } else { 12107 handleStartCopy(); 12108 res = true; 12109 } 12110 } catch (RemoteException e) { 12111 if (DEBUG_INSTALL) Slog.i(TAG, "Posting install MCS_RECONNECT"); 12112 mHandler.sendEmptyMessage(MCS_RECONNECT); 12113 res = false; 12114 } 12115 handleReturnCode(); 12116 return res; 12117 } 12118 12119 final void serviceError() { 12120 if (DEBUG_INSTALL) Slog.i(TAG, "serviceError"); 12121 handleServiceError(); 12122 handleReturnCode(); 12123 } 12124 12125 abstract void handleStartCopy() throws RemoteException; 12126 abstract void handleServiceError(); 12127 abstract void handleReturnCode(); 12128 } 12129 12130 class MeasureParams extends HandlerParams { 12131 private final PackageStats mStats; 12132 private boolean mSuccess; 12133 12134 private final IPackageStatsObserver mObserver; 12135 12136 public MeasureParams(PackageStats stats, IPackageStatsObserver observer) { 12137 super(new UserHandle(stats.userHandle)); 12138 mObserver = observer; 12139 mStats = stats; 12140 } 12141 12142 @Override 12143 public String toString() { 12144 return "MeasureParams{" 12145 + Integer.toHexString(System.identityHashCode(this)) 12146 + " " + mStats.packageName + "}"; 12147 } 12148 12149 @Override 12150 void handleStartCopy() throws RemoteException { 12151 synchronized (mInstallLock) { 12152 mSuccess = getPackageSizeInfoLI(mStats.packageName, mStats.userHandle, mStats); 12153 } 12154 12155 if (mSuccess) { 12156 final boolean mounted; 12157 if (Environment.isExternalStorageEmulated()) { 12158 mounted = true; 12159 } else { 12160 final String status = Environment.getExternalStorageState(); 12161 mounted = (Environment.MEDIA_MOUNTED.equals(status) 12162 || Environment.MEDIA_MOUNTED_READ_ONLY.equals(status)); 12163 } 12164 12165 if (mounted) { 12166 final UserEnvironment userEnv = new UserEnvironment(mStats.userHandle); 12167 12168 mStats.externalCacheSize = calculateDirectorySize(mContainerService, 12169 userEnv.buildExternalStorageAppCacheDirs(mStats.packageName)); 12170 12171 mStats.externalDataSize = calculateDirectorySize(mContainerService, 12172 userEnv.buildExternalStorageAppDataDirs(mStats.packageName)); 12173 12174 // Always subtract cache size, since it's a subdirectory 12175 mStats.externalDataSize -= mStats.externalCacheSize; 12176 12177 mStats.externalMediaSize = calculateDirectorySize(mContainerService, 12178 userEnv.buildExternalStorageAppMediaDirs(mStats.packageName)); 12179 12180 mStats.externalObbSize = calculateDirectorySize(mContainerService, 12181 userEnv.buildExternalStorageAppObbDirs(mStats.packageName)); 12182 } 12183 } 12184 } 12185 12186 @Override 12187 void handleReturnCode() { 12188 if (mObserver != null) { 12189 try { 12190 mObserver.onGetStatsCompleted(mStats, mSuccess); 12191 } catch (RemoteException e) { 12192 Slog.i(TAG, "Observer no longer exists."); 12193 } 12194 } 12195 } 12196 12197 @Override 12198 void handleServiceError() { 12199 Slog.e(TAG, "Could not measure application " + mStats.packageName 12200 + " external storage"); 12201 } 12202 } 12203 12204 private static long calculateDirectorySize(IMediaContainerService mcs, File[] paths) 12205 throws RemoteException { 12206 long result = 0; 12207 for (File path : paths) { 12208 result += mcs.calculateDirectorySize(path.getAbsolutePath()); 12209 } 12210 return result; 12211 } 12212 12213 private static void clearDirectory(IMediaContainerService mcs, File[] paths) { 12214 for (File path : paths) { 12215 try { 12216 mcs.clearDirectory(path.getAbsolutePath()); 12217 } catch (RemoteException e) { 12218 } 12219 } 12220 } 12221 12222 static class OriginInfo { 12223 /** 12224 * Location where install is coming from, before it has been 12225 * copied/renamed into place. This could be a single monolithic APK 12226 * file, or a cluster directory. This location may be untrusted. 12227 */ 12228 final File file; 12229 final String cid; 12230 12231 /** 12232 * Flag indicating that {@link #file} or {@link #cid} has already been 12233 * staged, meaning downstream users don't need to defensively copy the 12234 * contents. 12235 */ 12236 final boolean staged; 12237 12238 /** 12239 * Flag indicating that {@link #file} or {@link #cid} is an already 12240 * installed app that is being moved. 12241 */ 12242 final boolean existing; 12243 12244 final String resolvedPath; 12245 final File resolvedFile; 12246 12247 static OriginInfo fromNothing() { 12248 return new OriginInfo(null, null, false, false); 12249 } 12250 12251 static OriginInfo fromUntrustedFile(File file) { 12252 return new OriginInfo(file, null, false, false); 12253 } 12254 12255 static OriginInfo fromExistingFile(File file) { 12256 return new OriginInfo(file, null, false, true); 12257 } 12258 12259 static OriginInfo fromStagedFile(File file) { 12260 return new OriginInfo(file, null, true, false); 12261 } 12262 12263 static OriginInfo fromStagedContainer(String cid) { 12264 return new OriginInfo(null, cid, true, false); 12265 } 12266 12267 private OriginInfo(File file, String cid, boolean staged, boolean existing) { 12268 this.file = file; 12269 this.cid = cid; 12270 this.staged = staged; 12271 this.existing = existing; 12272 12273 if (cid != null) { 12274 resolvedPath = PackageHelper.getSdDir(cid); 12275 resolvedFile = new File(resolvedPath); 12276 } else if (file != null) { 12277 resolvedPath = file.getAbsolutePath(); 12278 resolvedFile = file; 12279 } else { 12280 resolvedPath = null; 12281 resolvedFile = null; 12282 } 12283 } 12284 } 12285 12286 static class MoveInfo { 12287 final int moveId; 12288 final String fromUuid; 12289 final String toUuid; 12290 final String packageName; 12291 final String dataAppName; 12292 final int appId; 12293 final String seinfo; 12294 final int targetSdkVersion; 12295 12296 public MoveInfo(int moveId, String fromUuid, String toUuid, String packageName, 12297 String dataAppName, int appId, String seinfo, int targetSdkVersion) { 12298 this.moveId = moveId; 12299 this.fromUuid = fromUuid; 12300 this.toUuid = toUuid; 12301 this.packageName = packageName; 12302 this.dataAppName = dataAppName; 12303 this.appId = appId; 12304 this.seinfo = seinfo; 12305 this.targetSdkVersion = targetSdkVersion; 12306 } 12307 } 12308 12309 static class VerificationInfo { 12310 /** A constant used to indicate that a uid value is not present. */ 12311 public static final int NO_UID = -1; 12312 12313 /** URI referencing where the package was downloaded from. */ 12314 final Uri originatingUri; 12315 12316 /** HTTP referrer URI associated with the originatingURI. */ 12317 final Uri referrer; 12318 12319 /** UID of the application that the install request originated from. */ 12320 final int originatingUid; 12321 12322 /** UID of application requesting the install */ 12323 final int installerUid; 12324 12325 VerificationInfo(Uri originatingUri, Uri referrer, int originatingUid, int installerUid) { 12326 this.originatingUri = originatingUri; 12327 this.referrer = referrer; 12328 this.originatingUid = originatingUid; 12329 this.installerUid = installerUid; 12330 } 12331 } 12332 12333 class InstallParams extends HandlerParams { 12334 final OriginInfo origin; 12335 final MoveInfo move; 12336 final IPackageInstallObserver2 observer; 12337 int installFlags; 12338 final String installerPackageName; 12339 final String volumeUuid; 12340 private InstallArgs mArgs; 12341 private int mRet; 12342 final String packageAbiOverride; 12343 final String[] grantedRuntimePermissions; 12344 final VerificationInfo verificationInfo; 12345 final Certificate[][] certificates; 12346 12347 InstallParams(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12348 int installFlags, String installerPackageName, String volumeUuid, 12349 VerificationInfo verificationInfo, UserHandle user, String packageAbiOverride, 12350 String[] grantedPermissions, Certificate[][] certificates) { 12351 super(user); 12352 this.origin = origin; 12353 this.move = move; 12354 this.observer = observer; 12355 this.installFlags = installFlags; 12356 this.installerPackageName = installerPackageName; 12357 this.volumeUuid = volumeUuid; 12358 this.verificationInfo = verificationInfo; 12359 this.packageAbiOverride = packageAbiOverride; 12360 this.grantedRuntimePermissions = grantedPermissions; 12361 this.certificates = certificates; 12362 } 12363 12364 @Override 12365 public String toString() { 12366 return "InstallParams{" + Integer.toHexString(System.identityHashCode(this)) 12367 + " file=" + origin.file + " cid=" + origin.cid + "}"; 12368 } 12369 12370 private int installLocationPolicy(PackageInfoLite pkgLite) { 12371 String packageName = pkgLite.packageName; 12372 int installLocation = pkgLite.installLocation; 12373 boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12374 // reader 12375 synchronized (mPackages) { 12376 // Currently installed package which the new package is attempting to replace or 12377 // null if no such package is installed. 12378 PackageParser.Package installedPkg = mPackages.get(packageName); 12379 // Package which currently owns the data which the new package will own if installed. 12380 // If an app is unstalled while keeping data (e.g., adb uninstall -k), installedPkg 12381 // will be null whereas dataOwnerPkg will contain information about the package 12382 // which was uninstalled while keeping its data. 12383 PackageParser.Package dataOwnerPkg = installedPkg; 12384 if (dataOwnerPkg == null) { 12385 PackageSetting ps = mSettings.mPackages.get(packageName); 12386 if (ps != null) { 12387 dataOwnerPkg = ps.pkg; 12388 } 12389 } 12390 12391 if (dataOwnerPkg != null) { 12392 // If installed, the package will get access to data left on the device by its 12393 // predecessor. As a security measure, this is permited only if this is not a 12394 // version downgrade or if the predecessor package is marked as debuggable and 12395 // a downgrade is explicitly requested. 12396 // 12397 // On debuggable platform builds, downgrades are permitted even for 12398 // non-debuggable packages to make testing easier. Debuggable platform builds do 12399 // not offer security guarantees and thus it's OK to disable some security 12400 // mechanisms to make debugging/testing easier on those builds. However, even on 12401 // debuggable builds downgrades of packages are permitted only if requested via 12402 // installFlags. This is because we aim to keep the behavior of debuggable 12403 // platform builds as close as possible to the behavior of non-debuggable 12404 // platform builds. 12405 final boolean downgradeRequested = 12406 (installFlags & PackageManager.INSTALL_ALLOW_DOWNGRADE) != 0; 12407 final boolean packageDebuggable = 12408 (dataOwnerPkg.applicationInfo.flags 12409 & ApplicationInfo.FLAG_DEBUGGABLE) != 0; 12410 final boolean downgradePermitted = 12411 (downgradeRequested) && ((Build.IS_DEBUGGABLE) || (packageDebuggable)); 12412 if (!downgradePermitted) { 12413 try { 12414 checkDowngrade(dataOwnerPkg, pkgLite); 12415 } catch (PackageManagerException e) { 12416 Slog.w(TAG, "Downgrade detected: " + e.getMessage()); 12417 return PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE; 12418 } 12419 } 12420 } 12421 12422 if (installedPkg != null) { 12423 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 12424 // Check for updated system application. 12425 if ((installedPkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) { 12426 if (onSd) { 12427 Slog.w(TAG, "Cannot install update to system app on sdcard"); 12428 return PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION; 12429 } 12430 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12431 } else { 12432 if (onSd) { 12433 // Install flag overrides everything. 12434 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12435 } 12436 // If current upgrade specifies particular preference 12437 if (installLocation == PackageInfo.INSTALL_LOCATION_INTERNAL_ONLY) { 12438 // Application explicitly specified internal. 12439 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12440 } else if (installLocation == PackageInfo.INSTALL_LOCATION_PREFER_EXTERNAL) { 12441 // App explictly prefers external. Let policy decide 12442 } else { 12443 // Prefer previous location 12444 if (isExternal(installedPkg)) { 12445 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12446 } 12447 return PackageHelper.RECOMMEND_INSTALL_INTERNAL; 12448 } 12449 } 12450 } else { 12451 // Invalid install. Return error code 12452 return PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS; 12453 } 12454 } 12455 } 12456 // All the special cases have been taken care of. 12457 // Return result based on recommended install location. 12458 if (onSd) { 12459 return PackageHelper.RECOMMEND_INSTALL_EXTERNAL; 12460 } 12461 return pkgLite.recommendedInstallLocation; 12462 } 12463 12464 /* 12465 * Invoke remote method to get package information and install 12466 * location values. Override install location based on default 12467 * policy if needed and then create install arguments based 12468 * on the install location. 12469 */ 12470 public void handleStartCopy() throws RemoteException { 12471 int ret = PackageManager.INSTALL_SUCCEEDED; 12472 12473 // If we're already staged, we've firmly committed to an install location 12474 if (origin.staged) { 12475 if (origin.file != null) { 12476 installFlags |= PackageManager.INSTALL_INTERNAL; 12477 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12478 } else if (origin.cid != null) { 12479 installFlags |= PackageManager.INSTALL_EXTERNAL; 12480 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12481 } else { 12482 throw new IllegalStateException("Invalid stage location"); 12483 } 12484 } 12485 12486 final boolean onSd = (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12487 final boolean onInt = (installFlags & PackageManager.INSTALL_INTERNAL) != 0; 12488 final boolean ephemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12489 PackageInfoLite pkgLite = null; 12490 12491 if (onInt && onSd) { 12492 // Check if both bits are set. 12493 Slog.w(TAG, "Conflicting flags specified for installing on both internal and external"); 12494 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12495 } else if (onSd && ephemeral) { 12496 Slog.w(TAG, "Conflicting flags specified for installing ephemeral on external"); 12497 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12498 } else { 12499 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, installFlags, 12500 packageAbiOverride); 12501 12502 if (DEBUG_EPHEMERAL && ephemeral) { 12503 Slog.v(TAG, "pkgLite for install: " + pkgLite); 12504 } 12505 12506 /* 12507 * If we have too little free space, try to free cache 12508 * before giving up. 12509 */ 12510 if (!origin.staged && pkgLite.recommendedInstallLocation 12511 == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12512 // TODO: focus freeing disk space on the target device 12513 final StorageManager storage = StorageManager.from(mContext); 12514 final long lowThreshold = storage.getStorageLowBytes( 12515 Environment.getDataDirectory()); 12516 12517 final long sizeBytes = mContainerService.calculateInstalledSize( 12518 origin.resolvedPath, isForwardLocked(), packageAbiOverride); 12519 12520 try { 12521 mInstaller.freeCache(null, sizeBytes + lowThreshold); 12522 pkgLite = mContainerService.getMinimalPackageInfo(origin.resolvedPath, 12523 installFlags, packageAbiOverride); 12524 } catch (InstallerException e) { 12525 Slog.w(TAG, "Failed to free cache", e); 12526 } 12527 12528 /* 12529 * The cache free must have deleted the file we 12530 * downloaded to install. 12531 * 12532 * TODO: fix the "freeCache" call to not delete 12533 * the file we care about. 12534 */ 12535 if (pkgLite.recommendedInstallLocation 12536 == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12537 pkgLite.recommendedInstallLocation 12538 = PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE; 12539 } 12540 } 12541 } 12542 12543 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12544 int loc = pkgLite.recommendedInstallLocation; 12545 if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_LOCATION) { 12546 ret = PackageManager.INSTALL_FAILED_INVALID_INSTALL_LOCATION; 12547 } else if (loc == PackageHelper.RECOMMEND_FAILED_ALREADY_EXISTS) { 12548 ret = PackageManager.INSTALL_FAILED_ALREADY_EXISTS; 12549 } else if (loc == PackageHelper.RECOMMEND_FAILED_INSUFFICIENT_STORAGE) { 12550 ret = PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12551 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_APK) { 12552 ret = PackageManager.INSTALL_FAILED_INVALID_APK; 12553 } else if (loc == PackageHelper.RECOMMEND_FAILED_INVALID_URI) { 12554 ret = PackageManager.INSTALL_FAILED_INVALID_URI; 12555 } else if (loc == PackageHelper.RECOMMEND_MEDIA_UNAVAILABLE) { 12556 ret = PackageManager.INSTALL_FAILED_MEDIA_UNAVAILABLE; 12557 } else { 12558 // Override with defaults if needed. 12559 loc = installLocationPolicy(pkgLite); 12560 if (loc == PackageHelper.RECOMMEND_FAILED_VERSION_DOWNGRADE) { 12561 ret = PackageManager.INSTALL_FAILED_VERSION_DOWNGRADE; 12562 } else if (!onSd && !onInt) { 12563 // Override install location with flags 12564 if (loc == PackageHelper.RECOMMEND_INSTALL_EXTERNAL) { 12565 // Set the flag to install on external media. 12566 installFlags |= PackageManager.INSTALL_EXTERNAL; 12567 installFlags &= ~PackageManager.INSTALL_INTERNAL; 12568 } else if (loc == PackageHelper.RECOMMEND_INSTALL_EPHEMERAL) { 12569 if (DEBUG_EPHEMERAL) { 12570 Slog.v(TAG, "...setting INSTALL_EPHEMERAL install flag"); 12571 } 12572 installFlags |= PackageManager.INSTALL_EPHEMERAL; 12573 installFlags &= ~(PackageManager.INSTALL_EXTERNAL 12574 |PackageManager.INSTALL_INTERNAL); 12575 } else { 12576 // Make sure the flag for installing on external 12577 // media is unset 12578 installFlags |= PackageManager.INSTALL_INTERNAL; 12579 installFlags &= ~PackageManager.INSTALL_EXTERNAL; 12580 } 12581 } 12582 } 12583 } 12584 12585 final InstallArgs args = createInstallArgs(this); 12586 mArgs = args; 12587 12588 if (ret == PackageManager.INSTALL_SUCCEEDED) { 12589 // TODO: http://b/22976637 12590 // Apps installed for "all" users use the device owner to verify the app 12591 UserHandle verifierUser = getUser(); 12592 if (verifierUser == UserHandle.ALL) { 12593 verifierUser = UserHandle.SYSTEM; 12594 } 12595 12596 /* 12597 * Determine if we have any installed package verifiers. If we 12598 * do, then we'll defer to them to verify the packages. 12599 */ 12600 final int requiredUid = mRequiredVerifierPackage == null ? -1 12601 : getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 12602 verifierUser.getIdentifier()); 12603 if (!origin.existing && requiredUid != -1 12604 && isVerificationEnabled(verifierUser.getIdentifier(), installFlags)) { 12605 final Intent verification = new Intent( 12606 Intent.ACTION_PACKAGE_NEEDS_VERIFICATION); 12607 verification.addFlags(Intent.FLAG_RECEIVER_FOREGROUND); 12608 verification.setDataAndType(Uri.fromFile(new File(origin.resolvedPath)), 12609 PACKAGE_MIME_TYPE); 12610 verification.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION); 12611 12612 // Query all live verifiers based on current user state 12613 final List<ResolveInfo> receivers = queryIntentReceiversInternal(verification, 12614 PACKAGE_MIME_TYPE, 0, verifierUser.getIdentifier()); 12615 12616 if (DEBUG_VERIFY) { 12617 Slog.d(TAG, "Found " + receivers.size() + " verifiers for intent " 12618 + verification.toString() + " with " + pkgLite.verifiers.length 12619 + " optional verifiers"); 12620 } 12621 12622 final int verificationId = mPendingVerificationToken++; 12623 12624 verification.putExtra(PackageManager.EXTRA_VERIFICATION_ID, verificationId); 12625 12626 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_PACKAGE, 12627 installerPackageName); 12628 12629 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALL_FLAGS, 12630 installFlags); 12631 12632 verification.putExtra(PackageManager.EXTRA_VERIFICATION_PACKAGE_NAME, 12633 pkgLite.packageName); 12634 12635 verification.putExtra(PackageManager.EXTRA_VERIFICATION_VERSION_CODE, 12636 pkgLite.versionCode); 12637 12638 if (verificationInfo != null) { 12639 if (verificationInfo.originatingUri != null) { 12640 verification.putExtra(Intent.EXTRA_ORIGINATING_URI, 12641 verificationInfo.originatingUri); 12642 } 12643 if (verificationInfo.referrer != null) { 12644 verification.putExtra(Intent.EXTRA_REFERRER, 12645 verificationInfo.referrer); 12646 } 12647 if (verificationInfo.originatingUid >= 0) { 12648 verification.putExtra(Intent.EXTRA_ORIGINATING_UID, 12649 verificationInfo.originatingUid); 12650 } 12651 if (verificationInfo.installerUid >= 0) { 12652 verification.putExtra(PackageManager.EXTRA_VERIFICATION_INSTALLER_UID, 12653 verificationInfo.installerUid); 12654 } 12655 } 12656 12657 final PackageVerificationState verificationState = new PackageVerificationState( 12658 requiredUid, args); 12659 12660 mPendingVerification.append(verificationId, verificationState); 12661 12662 final List<ComponentName> sufficientVerifiers = matchVerifiers(pkgLite, 12663 receivers, verificationState); 12664 12665 /* 12666 * If any sufficient verifiers were listed in the package 12667 * manifest, attempt to ask them. 12668 */ 12669 if (sufficientVerifiers != null) { 12670 final int N = sufficientVerifiers.size(); 12671 if (N == 0) { 12672 Slog.i(TAG, "Additional verifiers required, but none installed."); 12673 ret = PackageManager.INSTALL_FAILED_VERIFICATION_FAILURE; 12674 } else { 12675 for (int i = 0; i < N; i++) { 12676 final ComponentName verifierComponent = sufficientVerifiers.get(i); 12677 12678 final Intent sufficientIntent = new Intent(verification); 12679 sufficientIntent.setComponent(verifierComponent); 12680 mContext.sendBroadcastAsUser(sufficientIntent, verifierUser); 12681 } 12682 } 12683 } 12684 12685 final ComponentName requiredVerifierComponent = matchComponentForVerifier( 12686 mRequiredVerifierPackage, receivers); 12687 if (ret == PackageManager.INSTALL_SUCCEEDED 12688 && mRequiredVerifierPackage != null) { 12689 Trace.asyncTraceBegin( 12690 TRACE_TAG_PACKAGE_MANAGER, "verification", verificationId); 12691 /* 12692 * Send the intent to the required verification agent, 12693 * but only start the verification timeout after the 12694 * target BroadcastReceivers have run. 12695 */ 12696 verification.setComponent(requiredVerifierComponent); 12697 mContext.sendOrderedBroadcastAsUser(verification, verifierUser, 12698 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 12699 new BroadcastReceiver() { 12700 @Override 12701 public void onReceive(Context context, Intent intent) { 12702 final Message msg = mHandler 12703 .obtainMessage(CHECK_PENDING_VERIFICATION); 12704 msg.arg1 = verificationId; 12705 mHandler.sendMessageDelayed(msg, getVerificationTimeout()); 12706 } 12707 }, null, 0, null, null); 12708 12709 /* 12710 * We don't want the copy to proceed until verification 12711 * succeeds, so null out this field. 12712 */ 12713 mArgs = null; 12714 } 12715 } else { 12716 /* 12717 * No package verification is enabled, so immediately start 12718 * the remote call to initiate copy using temporary file. 12719 */ 12720 ret = args.copyApk(mContainerService, true); 12721 } 12722 } 12723 12724 mRet = ret; 12725 } 12726 12727 @Override 12728 void handleReturnCode() { 12729 // If mArgs is null, then MCS couldn't be reached. When it 12730 // reconnects, it will try again to install. At that point, this 12731 // will succeed. 12732 if (mArgs != null) { 12733 processPendingInstall(mArgs, mRet); 12734 } 12735 } 12736 12737 @Override 12738 void handleServiceError() { 12739 mArgs = createInstallArgs(this); 12740 mRet = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 12741 } 12742 12743 public boolean isForwardLocked() { 12744 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12745 } 12746 } 12747 12748 /** 12749 * Used during creation of InstallArgs 12750 * 12751 * @param installFlags package installation flags 12752 * @return true if should be installed on external storage 12753 */ 12754 private static boolean installOnExternalAsec(int installFlags) { 12755 if ((installFlags & PackageManager.INSTALL_INTERNAL) != 0) { 12756 return false; 12757 } 12758 if ((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) { 12759 return true; 12760 } 12761 return false; 12762 } 12763 12764 /** 12765 * Used during creation of InstallArgs 12766 * 12767 * @param installFlags package installation flags 12768 * @return true if should be installed as forward locked 12769 */ 12770 private static boolean installForwardLocked(int installFlags) { 12771 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12772 } 12773 12774 private InstallArgs createInstallArgs(InstallParams params) { 12775 if (params.move != null) { 12776 return new MoveInstallArgs(params); 12777 } else if (installOnExternalAsec(params.installFlags) || params.isForwardLocked()) { 12778 return new AsecInstallArgs(params); 12779 } else { 12780 return new FileInstallArgs(params); 12781 } 12782 } 12783 12784 /** 12785 * Create args that describe an existing installed package. Typically used 12786 * when cleaning up old installs, or used as a move source. 12787 */ 12788 private InstallArgs createInstallArgsForExisting(int installFlags, String codePath, 12789 String resourcePath, String[] instructionSets) { 12790 final boolean isInAsec; 12791 if (installOnExternalAsec(installFlags)) { 12792 /* Apps on SD card are always in ASEC containers. */ 12793 isInAsec = true; 12794 } else if (installForwardLocked(installFlags) 12795 && !codePath.startsWith(mDrmAppPrivateInstallDir.getAbsolutePath())) { 12796 /* 12797 * Forward-locked apps are only in ASEC containers if they're the 12798 * new style 12799 */ 12800 isInAsec = true; 12801 } else { 12802 isInAsec = false; 12803 } 12804 12805 if (isInAsec) { 12806 return new AsecInstallArgs(codePath, instructionSets, 12807 installOnExternalAsec(installFlags), installForwardLocked(installFlags)); 12808 } else { 12809 return new FileInstallArgs(codePath, resourcePath, instructionSets); 12810 } 12811 } 12812 12813 static abstract class InstallArgs { 12814 /** @see InstallParams#origin */ 12815 final OriginInfo origin; 12816 /** @see InstallParams#move */ 12817 final MoveInfo move; 12818 12819 final IPackageInstallObserver2 observer; 12820 // Always refers to PackageManager flags only 12821 final int installFlags; 12822 final String installerPackageName; 12823 final String volumeUuid; 12824 final UserHandle user; 12825 final String abiOverride; 12826 final String[] installGrantPermissions; 12827 /** If non-null, drop an async trace when the install completes */ 12828 final String traceMethod; 12829 final int traceCookie; 12830 final Certificate[][] certificates; 12831 12832 // The list of instruction sets supported by this app. This is currently 12833 // only used during the rmdex() phase to clean up resources. We can get rid of this 12834 // if we move dex files under the common app path. 12835 /* nullable */ String[] instructionSets; 12836 12837 InstallArgs(OriginInfo origin, MoveInfo move, IPackageInstallObserver2 observer, 12838 int installFlags, String installerPackageName, String volumeUuid, 12839 UserHandle user, String[] instructionSets, 12840 String abiOverride, String[] installGrantPermissions, 12841 String traceMethod, int traceCookie, Certificate[][] certificates) { 12842 this.origin = origin; 12843 this.move = move; 12844 this.installFlags = installFlags; 12845 this.observer = observer; 12846 this.installerPackageName = installerPackageName; 12847 this.volumeUuid = volumeUuid; 12848 this.user = user; 12849 this.instructionSets = instructionSets; 12850 this.abiOverride = abiOverride; 12851 this.installGrantPermissions = installGrantPermissions; 12852 this.traceMethod = traceMethod; 12853 this.traceCookie = traceCookie; 12854 this.certificates = certificates; 12855 } 12856 12857 abstract int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException; 12858 abstract int doPreInstall(int status); 12859 12860 /** 12861 * Rename package into final resting place. All paths on the given 12862 * scanned package should be updated to reflect the rename. 12863 */ 12864 abstract boolean doRename(int status, PackageParser.Package pkg, String oldCodePath); 12865 abstract int doPostInstall(int status, int uid); 12866 12867 /** @see PackageSettingBase#codePathString */ 12868 abstract String getCodePath(); 12869 /** @see PackageSettingBase#resourcePathString */ 12870 abstract String getResourcePath(); 12871 12872 // Need installer lock especially for dex file removal. 12873 abstract void cleanUpResourcesLI(); 12874 abstract boolean doPostDeleteLI(boolean delete); 12875 12876 /** 12877 * Called before the source arguments are copied. This is used mostly 12878 * for MoveParams when it needs to read the source file to put it in the 12879 * destination. 12880 */ 12881 int doPreCopy() { 12882 return PackageManager.INSTALL_SUCCEEDED; 12883 } 12884 12885 /** 12886 * Called after the source arguments are copied. This is used mostly for 12887 * MoveParams when it needs to read the source file to put it in the 12888 * destination. 12889 */ 12890 int doPostCopy(int uid) { 12891 return PackageManager.INSTALL_SUCCEEDED; 12892 } 12893 12894 protected boolean isFwdLocked() { 12895 return (installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0; 12896 } 12897 12898 protected boolean isExternalAsec() { 12899 return (installFlags & PackageManager.INSTALL_EXTERNAL) != 0; 12900 } 12901 12902 protected boolean isEphemeral() { 12903 return (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12904 } 12905 12906 UserHandle getUser() { 12907 return user; 12908 } 12909 } 12910 12911 private void removeDexFiles(List<String> allCodePaths, String[] instructionSets) { 12912 if (!allCodePaths.isEmpty()) { 12913 if (instructionSets == null) { 12914 throw new IllegalStateException("instructionSet == null"); 12915 } 12916 String[] dexCodeInstructionSets = getDexCodeInstructionSets(instructionSets); 12917 for (String codePath : allCodePaths) { 12918 for (String dexCodeInstructionSet : dexCodeInstructionSets) { 12919 try { 12920 mInstaller.rmdex(codePath, dexCodeInstructionSet); 12921 } catch (InstallerException ignored) { 12922 } 12923 } 12924 } 12925 } 12926 } 12927 12928 /** 12929 * Logic to handle installation of non-ASEC applications, including copying 12930 * and renaming logic. 12931 */ 12932 class FileInstallArgs extends InstallArgs { 12933 private File codeFile; 12934 private File resourceFile; 12935 12936 // Example topology: 12937 // /data/app/com.example/base.apk 12938 // /data/app/com.example/split_foo.apk 12939 // /data/app/com.example/lib/arm/libfoo.so 12940 // /data/app/com.example/lib/arm64/libfoo.so 12941 // /data/app/com.example/dalvik/arm/base.apk@classes.dex 12942 12943 /** New install */ 12944 FileInstallArgs(InstallParams params) { 12945 super(params.origin, params.move, params.observer, params.installFlags, 12946 params.installerPackageName, params.volumeUuid, 12947 params.getUser(), null /*instructionSets*/, params.packageAbiOverride, 12948 params.grantedRuntimePermissions, 12949 params.traceMethod, params.traceCookie, params.certificates); 12950 if (isFwdLocked()) { 12951 throw new IllegalArgumentException("Forward locking only supported in ASEC"); 12952 } 12953 } 12954 12955 /** Existing install */ 12956 FileInstallArgs(String codePath, String resourcePath, String[] instructionSets) { 12957 super(OriginInfo.fromNothing(), null, null, 0, null, null, null, instructionSets, 12958 null, null, null, 0, null /*certificates*/); 12959 this.codeFile = (codePath != null) ? new File(codePath) : null; 12960 this.resourceFile = (resourcePath != null) ? new File(resourcePath) : null; 12961 } 12962 12963 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12964 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "copyApk"); 12965 try { 12966 return doCopyApk(imcs, temp); 12967 } finally { 12968 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 12969 } 12970 } 12971 12972 private int doCopyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 12973 if (origin.staged) { 12974 if (DEBUG_INSTALL) Slog.d(TAG, origin.file + " already staged; skipping copy"); 12975 codeFile = origin.file; 12976 resourceFile = origin.file; 12977 return PackageManager.INSTALL_SUCCEEDED; 12978 } 12979 12980 try { 12981 final boolean isEphemeral = (installFlags & PackageManager.INSTALL_EPHEMERAL) != 0; 12982 final File tempDir = 12983 mInstallerService.allocateStageDirLegacy(volumeUuid, isEphemeral); 12984 codeFile = tempDir; 12985 resourceFile = tempDir; 12986 } catch (IOException e) { 12987 Slog.w(TAG, "Failed to create copy file: " + e); 12988 return PackageManager.INSTALL_FAILED_INSUFFICIENT_STORAGE; 12989 } 12990 12991 final IParcelFileDescriptorFactory target = new IParcelFileDescriptorFactory.Stub() { 12992 @Override 12993 public ParcelFileDescriptor open(String name, int mode) throws RemoteException { 12994 if (!FileUtils.isValidExtFilename(name)) { 12995 throw new IllegalArgumentException("Invalid filename: " + name); 12996 } 12997 try { 12998 final File file = new File(codeFile, name); 12999 final FileDescriptor fd = Os.open(file.getAbsolutePath(), 13000 O_RDWR | O_CREAT, 0644); 13001 Os.chmod(file.getAbsolutePath(), 0644); 13002 return new ParcelFileDescriptor(fd); 13003 } catch (ErrnoException e) { 13004 throw new RemoteException("Failed to open: " + e.getMessage()); 13005 } 13006 } 13007 }; 13008 13009 int ret = PackageManager.INSTALL_SUCCEEDED; 13010 ret = imcs.copyPackage(origin.file.getAbsolutePath(), target); 13011 if (ret != PackageManager.INSTALL_SUCCEEDED) { 13012 Slog.e(TAG, "Failed to copy package"); 13013 return ret; 13014 } 13015 13016 final File libraryRoot = new File(codeFile, LIB_DIR_NAME); 13017 NativeLibraryHelper.Handle handle = null; 13018 try { 13019 handle = NativeLibraryHelper.Handle.create(codeFile); 13020 ret = NativeLibraryHelper.copyNativeBinariesWithOverride(handle, libraryRoot, 13021 abiOverride); 13022 } catch (IOException e) { 13023 Slog.e(TAG, "Copying native libraries failed", e); 13024 ret = PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13025 } finally { 13026 IoUtils.closeQuietly(handle); 13027 } 13028 13029 return ret; 13030 } 13031 13032 int doPreInstall(int status) { 13033 if (status != PackageManager.INSTALL_SUCCEEDED) { 13034 cleanUp(); 13035 } 13036 return status; 13037 } 13038 13039 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13040 if (status != PackageManager.INSTALL_SUCCEEDED) { 13041 cleanUp(); 13042 return false; 13043 } 13044 13045 final File targetDir = codeFile.getParentFile(); 13046 final File beforeCodeFile = codeFile; 13047 final File afterCodeFile = getNextCodePath(targetDir, pkg.packageName); 13048 13049 if (DEBUG_INSTALL) Slog.d(TAG, "Renaming " + beforeCodeFile + " to " + afterCodeFile); 13050 try { 13051 Os.rename(beforeCodeFile.getAbsolutePath(), afterCodeFile.getAbsolutePath()); 13052 } catch (ErrnoException e) { 13053 Slog.w(TAG, "Failed to rename", e); 13054 return false; 13055 } 13056 13057 if (!SELinux.restoreconRecursive(afterCodeFile)) { 13058 Slog.w(TAG, "Failed to restorecon"); 13059 return false; 13060 } 13061 13062 // Reflect the rename internally 13063 codeFile = afterCodeFile; 13064 resourceFile = afterCodeFile; 13065 13066 // Reflect the rename in scanned details 13067 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13068 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13069 afterCodeFile, pkg.baseCodePath)); 13070 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13071 afterCodeFile, pkg.splitCodePaths)); 13072 13073 // Reflect the rename in app info 13074 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13075 pkg.setApplicationInfoCodePath(pkg.codePath); 13076 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13077 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13078 pkg.setApplicationInfoResourcePath(pkg.codePath); 13079 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13080 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13081 13082 return true; 13083 } 13084 13085 int doPostInstall(int status, int uid) { 13086 if (status != PackageManager.INSTALL_SUCCEEDED) { 13087 cleanUp(); 13088 } 13089 return status; 13090 } 13091 13092 @Override 13093 String getCodePath() { 13094 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13095 } 13096 13097 @Override 13098 String getResourcePath() { 13099 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13100 } 13101 13102 private boolean cleanUp() { 13103 if (codeFile == null || !codeFile.exists()) { 13104 return false; 13105 } 13106 13107 removeCodePathLI(codeFile); 13108 13109 if (resourceFile != null && !FileUtils.contains(codeFile, resourceFile)) { 13110 resourceFile.delete(); 13111 } 13112 13113 return true; 13114 } 13115 13116 void cleanUpResourcesLI() { 13117 // Try enumerating all code paths before deleting 13118 List<String> allCodePaths = Collections.EMPTY_LIST; 13119 if (codeFile != null && codeFile.exists()) { 13120 try { 13121 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13122 allCodePaths = pkg.getAllCodePaths(); 13123 } catch (PackageParserException e) { 13124 // Ignored; we tried our best 13125 } 13126 } 13127 13128 cleanUp(); 13129 removeDexFiles(allCodePaths, instructionSets); 13130 } 13131 13132 boolean doPostDeleteLI(boolean delete) { 13133 // XXX err, shouldn't we respect the delete flag? 13134 cleanUpResourcesLI(); 13135 return true; 13136 } 13137 } 13138 13139 private boolean isAsecExternal(String cid) { 13140 final String asecPath = PackageHelper.getSdFilesystem(cid); 13141 return !asecPath.startsWith(mAsecInternalPath); 13142 } 13143 13144 private static void maybeThrowExceptionForMultiArchCopy(String message, int copyRet) throws 13145 PackageManagerException { 13146 if (copyRet < 0) { 13147 if (copyRet != PackageManager.NO_NATIVE_LIBRARIES && 13148 copyRet != PackageManager.INSTALL_FAILED_NO_MATCHING_ABIS) { 13149 throw new PackageManagerException(copyRet, message); 13150 } 13151 } 13152 } 13153 13154 /** 13155 * Extract the MountService "container ID" from the full code path of an 13156 * .apk. 13157 */ 13158 static String cidFromCodePath(String fullCodePath) { 13159 int eidx = fullCodePath.lastIndexOf("/"); 13160 String subStr1 = fullCodePath.substring(0, eidx); 13161 int sidx = subStr1.lastIndexOf("/"); 13162 return subStr1.substring(sidx+1, eidx); 13163 } 13164 13165 /** 13166 * Logic to handle installation of ASEC applications, including copying and 13167 * renaming logic. 13168 */ 13169 class AsecInstallArgs extends InstallArgs { 13170 static final String RES_FILE_NAME = "pkg.apk"; 13171 static final String PUBLIC_RES_FILE_NAME = "res.zip"; 13172 13173 String cid; 13174 String packagePath; 13175 String resourcePath; 13176 13177 /** New install */ 13178 AsecInstallArgs(InstallParams params) { 13179 super(params.origin, params.move, params.observer, params.installFlags, 13180 params.installerPackageName, params.volumeUuid, 13181 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13182 params.grantedRuntimePermissions, 13183 params.traceMethod, params.traceCookie, params.certificates); 13184 } 13185 13186 /** Existing install */ 13187 AsecInstallArgs(String fullCodePath, String[] instructionSets, 13188 boolean isExternal, boolean isForwardLocked) { 13189 super(OriginInfo.fromNothing(), null, null, (isExternal ? INSTALL_EXTERNAL : 0) 13190 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13191 instructionSets, null, null, null, 0, null /*certificates*/); 13192 // Hackily pretend we're still looking at a full code path 13193 if (!fullCodePath.endsWith(RES_FILE_NAME)) { 13194 fullCodePath = new File(fullCodePath, RES_FILE_NAME).getAbsolutePath(); 13195 } 13196 13197 // Extract cid from fullCodePath 13198 int eidx = fullCodePath.lastIndexOf("/"); 13199 String subStr1 = fullCodePath.substring(0, eidx); 13200 int sidx = subStr1.lastIndexOf("/"); 13201 cid = subStr1.substring(sidx+1, eidx); 13202 setMountPath(subStr1); 13203 } 13204 13205 AsecInstallArgs(String cid, String[] instructionSets, boolean isForwardLocked) { 13206 super(OriginInfo.fromNothing(), null, null, (isAsecExternal(cid) ? INSTALL_EXTERNAL : 0) 13207 | (isForwardLocked ? INSTALL_FORWARD_LOCK : 0), null, null, null, 13208 instructionSets, null, null, null, 0, null /*certificates*/); 13209 this.cid = cid; 13210 setMountPath(PackageHelper.getSdDir(cid)); 13211 } 13212 13213 void createCopyFile() { 13214 cid = mInstallerService.allocateExternalStageCidLegacy(); 13215 } 13216 13217 int copyApk(IMediaContainerService imcs, boolean temp) throws RemoteException { 13218 if (origin.staged && origin.cid != null) { 13219 if (DEBUG_INSTALL) Slog.d(TAG, origin.cid + " already staged; skipping copy"); 13220 cid = origin.cid; 13221 setMountPath(PackageHelper.getSdDir(cid)); 13222 return PackageManager.INSTALL_SUCCEEDED; 13223 } 13224 13225 if (temp) { 13226 createCopyFile(); 13227 } else { 13228 /* 13229 * Pre-emptively destroy the container since it's destroyed if 13230 * copying fails due to it existing anyway. 13231 */ 13232 PackageHelper.destroySdDir(cid); 13233 } 13234 13235 final String newMountPath = imcs.copyPackageToContainer( 13236 origin.file.getAbsolutePath(), cid, getEncryptKey(), isExternalAsec(), 13237 isFwdLocked(), deriveAbiOverride(abiOverride, null /* settings */)); 13238 13239 if (newMountPath != null) { 13240 setMountPath(newMountPath); 13241 return PackageManager.INSTALL_SUCCEEDED; 13242 } else { 13243 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13244 } 13245 } 13246 13247 @Override 13248 String getCodePath() { 13249 return packagePath; 13250 } 13251 13252 @Override 13253 String getResourcePath() { 13254 return resourcePath; 13255 } 13256 13257 int doPreInstall(int status) { 13258 if (status != PackageManager.INSTALL_SUCCEEDED) { 13259 // Destroy container 13260 PackageHelper.destroySdDir(cid); 13261 } else { 13262 boolean mounted = PackageHelper.isContainerMounted(cid); 13263 if (!mounted) { 13264 String newMountPath = PackageHelper.mountSdDir(cid, getEncryptKey(), 13265 Process.SYSTEM_UID); 13266 if (newMountPath != null) { 13267 setMountPath(newMountPath); 13268 } else { 13269 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13270 } 13271 } 13272 } 13273 return status; 13274 } 13275 13276 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13277 String newCacheId = getNextCodePath(oldCodePath, pkg.packageName, "/" + RES_FILE_NAME); 13278 String newMountPath = null; 13279 if (PackageHelper.isContainerMounted(cid)) { 13280 // Unmount the container 13281 if (!PackageHelper.unMountSdDir(cid)) { 13282 Slog.i(TAG, "Failed to unmount " + cid + " before renaming"); 13283 return false; 13284 } 13285 } 13286 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13287 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId + 13288 " which might be stale. Will try to clean up."); 13289 // Clean up the stale container and proceed to recreate. 13290 if (!PackageHelper.destroySdDir(newCacheId)) { 13291 Slog.e(TAG, "Very strange. Cannot clean up stale container " + newCacheId); 13292 return false; 13293 } 13294 // Successfully cleaned up stale container. Try to rename again. 13295 if (!PackageHelper.renameSdDir(cid, newCacheId)) { 13296 Slog.e(TAG, "Failed to rename " + cid + " to " + newCacheId 13297 + " inspite of cleaning it up."); 13298 return false; 13299 } 13300 } 13301 if (!PackageHelper.isContainerMounted(newCacheId)) { 13302 Slog.w(TAG, "Mounting container " + newCacheId); 13303 newMountPath = PackageHelper.mountSdDir(newCacheId, 13304 getEncryptKey(), Process.SYSTEM_UID); 13305 } else { 13306 newMountPath = PackageHelper.getSdDir(newCacheId); 13307 } 13308 if (newMountPath == null) { 13309 Slog.w(TAG, "Failed to get cache path for " + newCacheId); 13310 return false; 13311 } 13312 Log.i(TAG, "Succesfully renamed " + cid + 13313 " to " + newCacheId + 13314 " at new path: " + newMountPath); 13315 cid = newCacheId; 13316 13317 final File beforeCodeFile = new File(packagePath); 13318 setMountPath(newMountPath); 13319 final File afterCodeFile = new File(packagePath); 13320 13321 // Reflect the rename in scanned details 13322 pkg.setCodePath(afterCodeFile.getAbsolutePath()); 13323 pkg.setBaseCodePath(FileUtils.rewriteAfterRename(beforeCodeFile, 13324 afterCodeFile, pkg.baseCodePath)); 13325 pkg.setSplitCodePaths(FileUtils.rewriteAfterRename(beforeCodeFile, 13326 afterCodeFile, pkg.splitCodePaths)); 13327 13328 // Reflect the rename in app info 13329 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13330 pkg.setApplicationInfoCodePath(pkg.codePath); 13331 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13332 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13333 pkg.setApplicationInfoResourcePath(pkg.codePath); 13334 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13335 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13336 13337 return true; 13338 } 13339 13340 private void setMountPath(String mountPath) { 13341 final File mountFile = new File(mountPath); 13342 13343 final File monolithicFile = new File(mountFile, RES_FILE_NAME); 13344 if (monolithicFile.exists()) { 13345 packagePath = monolithicFile.getAbsolutePath(); 13346 if (isFwdLocked()) { 13347 resourcePath = new File(mountFile, PUBLIC_RES_FILE_NAME).getAbsolutePath(); 13348 } else { 13349 resourcePath = packagePath; 13350 } 13351 } else { 13352 packagePath = mountFile.getAbsolutePath(); 13353 resourcePath = packagePath; 13354 } 13355 } 13356 13357 int doPostInstall(int status, int uid) { 13358 if (status != PackageManager.INSTALL_SUCCEEDED) { 13359 cleanUp(); 13360 } else { 13361 final int groupOwner; 13362 final String protectedFile; 13363 if (isFwdLocked()) { 13364 groupOwner = UserHandle.getSharedAppGid(uid); 13365 protectedFile = RES_FILE_NAME; 13366 } else { 13367 groupOwner = -1; 13368 protectedFile = null; 13369 } 13370 13371 if (uid < Process.FIRST_APPLICATION_UID 13372 || !PackageHelper.fixSdPermissions(cid, groupOwner, protectedFile)) { 13373 Slog.e(TAG, "Failed to finalize " + cid); 13374 PackageHelper.destroySdDir(cid); 13375 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13376 } 13377 13378 boolean mounted = PackageHelper.isContainerMounted(cid); 13379 if (!mounted) { 13380 PackageHelper.mountSdDir(cid, getEncryptKey(), Process.myUid()); 13381 } 13382 } 13383 return status; 13384 } 13385 13386 private void cleanUp() { 13387 if (DEBUG_SD_INSTALL) Slog.i(TAG, "cleanUp"); 13388 13389 // Destroy secure container 13390 PackageHelper.destroySdDir(cid); 13391 } 13392 13393 private List<String> getAllCodePaths() { 13394 final File codeFile = new File(getCodePath()); 13395 if (codeFile != null && codeFile.exists()) { 13396 try { 13397 final PackageLite pkg = PackageParser.parsePackageLite(codeFile, 0); 13398 return pkg.getAllCodePaths(); 13399 } catch (PackageParserException e) { 13400 // Ignored; we tried our best 13401 } 13402 } 13403 return Collections.EMPTY_LIST; 13404 } 13405 13406 void cleanUpResourcesLI() { 13407 // Enumerate all code paths before deleting 13408 cleanUpResourcesLI(getAllCodePaths()); 13409 } 13410 13411 private void cleanUpResourcesLI(List<String> allCodePaths) { 13412 cleanUp(); 13413 removeDexFiles(allCodePaths, instructionSets); 13414 } 13415 13416 String getPackageName() { 13417 return getAsecPackageName(cid); 13418 } 13419 13420 boolean doPostDeleteLI(boolean delete) { 13421 if (DEBUG_SD_INSTALL) Slog.i(TAG, "doPostDeleteLI() del=" + delete); 13422 final List<String> allCodePaths = getAllCodePaths(); 13423 boolean mounted = PackageHelper.isContainerMounted(cid); 13424 if (mounted) { 13425 // Unmount first 13426 if (PackageHelper.unMountSdDir(cid)) { 13427 mounted = false; 13428 } 13429 } 13430 if (!mounted && delete) { 13431 cleanUpResourcesLI(allCodePaths); 13432 } 13433 return !mounted; 13434 } 13435 13436 @Override 13437 int doPreCopy() { 13438 if (isFwdLocked()) { 13439 if (!PackageHelper.fixSdPermissions(cid, getPackageUid(DEFAULT_CONTAINER_PACKAGE, 13440 MATCH_SYSTEM_ONLY, UserHandle.USER_SYSTEM), RES_FILE_NAME)) { 13441 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13442 } 13443 } 13444 13445 return PackageManager.INSTALL_SUCCEEDED; 13446 } 13447 13448 @Override 13449 int doPostCopy(int uid) { 13450 if (isFwdLocked()) { 13451 if (uid < Process.FIRST_APPLICATION_UID 13452 || !PackageHelper.fixSdPermissions(cid, UserHandle.getSharedAppGid(uid), 13453 RES_FILE_NAME)) { 13454 Slog.e(TAG, "Failed to finalize " + cid); 13455 PackageHelper.destroySdDir(cid); 13456 return PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 13457 } 13458 } 13459 13460 return PackageManager.INSTALL_SUCCEEDED; 13461 } 13462 } 13463 13464 /** 13465 * Logic to handle movement of existing installed applications. 13466 */ 13467 class MoveInstallArgs extends InstallArgs { 13468 private File codeFile; 13469 private File resourceFile; 13470 13471 /** New install */ 13472 MoveInstallArgs(InstallParams params) { 13473 super(params.origin, params.move, params.observer, params.installFlags, 13474 params.installerPackageName, params.volumeUuid, 13475 params.getUser(), null /* instruction sets */, params.packageAbiOverride, 13476 params.grantedRuntimePermissions, 13477 params.traceMethod, params.traceCookie, params.certificates); 13478 } 13479 13480 int copyApk(IMediaContainerService imcs, boolean temp) { 13481 if (DEBUG_INSTALL) Slog.d(TAG, "Moving " + move.packageName + " from " 13482 + move.fromUuid + " to " + move.toUuid); 13483 synchronized (mInstaller) { 13484 try { 13485 mInstaller.moveCompleteApp(move.fromUuid, move.toUuid, move.packageName, 13486 move.dataAppName, move.appId, move.seinfo, move.targetSdkVersion); 13487 } catch (InstallerException e) { 13488 Slog.w(TAG, "Failed to move app", e); 13489 return PackageManager.INSTALL_FAILED_INTERNAL_ERROR; 13490 } 13491 } 13492 13493 codeFile = new File(Environment.getDataAppDirectory(move.toUuid), move.dataAppName); 13494 resourceFile = codeFile; 13495 if (DEBUG_INSTALL) Slog.d(TAG, "codeFile after move is " + codeFile); 13496 13497 return PackageManager.INSTALL_SUCCEEDED; 13498 } 13499 13500 int doPreInstall(int status) { 13501 if (status != PackageManager.INSTALL_SUCCEEDED) { 13502 cleanUp(move.toUuid); 13503 } 13504 return status; 13505 } 13506 13507 boolean doRename(int status, PackageParser.Package pkg, String oldCodePath) { 13508 if (status != PackageManager.INSTALL_SUCCEEDED) { 13509 cleanUp(move.toUuid); 13510 return false; 13511 } 13512 13513 // Reflect the move in app info 13514 pkg.setApplicationVolumeUuid(pkg.volumeUuid); 13515 pkg.setApplicationInfoCodePath(pkg.codePath); 13516 pkg.setApplicationInfoBaseCodePath(pkg.baseCodePath); 13517 pkg.setApplicationInfoSplitCodePaths(pkg.splitCodePaths); 13518 pkg.setApplicationInfoResourcePath(pkg.codePath); 13519 pkg.setApplicationInfoBaseResourcePath(pkg.baseCodePath); 13520 pkg.setApplicationInfoSplitResourcePaths(pkg.splitCodePaths); 13521 13522 return true; 13523 } 13524 13525 int doPostInstall(int status, int uid) { 13526 if (status == PackageManager.INSTALL_SUCCEEDED) { 13527 cleanUp(move.fromUuid); 13528 } else { 13529 cleanUp(move.toUuid); 13530 } 13531 return status; 13532 } 13533 13534 @Override 13535 String getCodePath() { 13536 return (codeFile != null) ? codeFile.getAbsolutePath() : null; 13537 } 13538 13539 @Override 13540 String getResourcePath() { 13541 return (resourceFile != null) ? resourceFile.getAbsolutePath() : null; 13542 } 13543 13544 private boolean cleanUp(String volumeUuid) { 13545 final File codeFile = new File(Environment.getDataAppDirectory(volumeUuid), 13546 move.dataAppName); 13547 Slog.d(TAG, "Cleaning up " + move.packageName + " on " + volumeUuid); 13548 final int[] userIds = sUserManager.getUserIds(); 13549 synchronized (mInstallLock) { 13550 // Clean up both app data and code 13551 // All package moves are frozen until finished 13552 for (int userId : userIds) { 13553 try { 13554 mInstaller.destroyAppData(volumeUuid, move.packageName, userId, 13555 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 0); 13556 } catch (InstallerException e) { 13557 Slog.w(TAG, String.valueOf(e)); 13558 } 13559 } 13560 removeCodePathLI(codeFile); 13561 } 13562 return true; 13563 } 13564 13565 void cleanUpResourcesLI() { 13566 throw new UnsupportedOperationException(); 13567 } 13568 13569 boolean doPostDeleteLI(boolean delete) { 13570 throw new UnsupportedOperationException(); 13571 } 13572 } 13573 13574 static String getAsecPackageName(String packageCid) { 13575 int idx = packageCid.lastIndexOf("-"); 13576 if (idx == -1) { 13577 return packageCid; 13578 } 13579 return packageCid.substring(0, idx); 13580 } 13581 13582 // Utility method used to create code paths based on package name and available index. 13583 private static String getNextCodePath(String oldCodePath, String prefix, String suffix) { 13584 String idxStr = ""; 13585 int idx = 1; 13586 // Fall back to default value of idx=1 if prefix is not 13587 // part of oldCodePath 13588 if (oldCodePath != null) { 13589 String subStr = oldCodePath; 13590 // Drop the suffix right away 13591 if (suffix != null && subStr.endsWith(suffix)) { 13592 subStr = subStr.substring(0, subStr.length() - suffix.length()); 13593 } 13594 // If oldCodePath already contains prefix find out the 13595 // ending index to either increment or decrement. 13596 int sidx = subStr.lastIndexOf(prefix); 13597 if (sidx != -1) { 13598 subStr = subStr.substring(sidx + prefix.length()); 13599 if (subStr != null) { 13600 if (subStr.startsWith(INSTALL_PACKAGE_SUFFIX)) { 13601 subStr = subStr.substring(INSTALL_PACKAGE_SUFFIX.length()); 13602 } 13603 try { 13604 idx = Integer.parseInt(subStr); 13605 if (idx <= 1) { 13606 idx++; 13607 } else { 13608 idx--; 13609 } 13610 } catch(NumberFormatException e) { 13611 } 13612 } 13613 } 13614 } 13615 idxStr = INSTALL_PACKAGE_SUFFIX + Integer.toString(idx); 13616 return prefix + idxStr; 13617 } 13618 13619 private File getNextCodePath(File targetDir, String packageName) { 13620 int suffix = 1; 13621 File result; 13622 do { 13623 result = new File(targetDir, packageName + "-" + suffix); 13624 suffix++; 13625 } while (result.exists()); 13626 return result; 13627 } 13628 13629 // Utility method that returns the relative package path with respect 13630 // to the installation directory. Like say for /data/data/com.test-1.apk 13631 // string com.test-1 is returned. 13632 static String deriveCodePathName(String codePath) { 13633 if (codePath == null) { 13634 return null; 13635 } 13636 final File codeFile = new File(codePath); 13637 final String name = codeFile.getName(); 13638 if (codeFile.isDirectory()) { 13639 return name; 13640 } else if (name.endsWith(".apk") || name.endsWith(".tmp")) { 13641 final int lastDot = name.lastIndexOf('.'); 13642 return name.substring(0, lastDot); 13643 } else { 13644 Slog.w(TAG, "Odd, " + codePath + " doesn't look like an APK"); 13645 return null; 13646 } 13647 } 13648 13649 static class PackageInstalledInfo { 13650 String name; 13651 int uid; 13652 // The set of users that originally had this package installed. 13653 int[] origUsers; 13654 // The set of users that now have this package installed. 13655 int[] newUsers; 13656 PackageParser.Package pkg; 13657 int returnCode; 13658 String returnMsg; 13659 PackageRemovedInfo removedInfo; 13660 ArrayMap<String, PackageInstalledInfo> addedChildPackages; 13661 13662 public void setError(int code, String msg) { 13663 setReturnCode(code); 13664 setReturnMessage(msg); 13665 Slog.w(TAG, msg); 13666 } 13667 13668 public void setError(String msg, PackageParserException e) { 13669 setReturnCode(e.error); 13670 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13671 Slog.w(TAG, msg, e); 13672 } 13673 13674 public void setError(String msg, PackageManagerException e) { 13675 returnCode = e.error; 13676 setReturnMessage(ExceptionUtils.getCompleteMessage(msg, e)); 13677 Slog.w(TAG, msg, e); 13678 } 13679 13680 public void setReturnCode(int returnCode) { 13681 this.returnCode = returnCode; 13682 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13683 for (int i = 0; i < childCount; i++) { 13684 addedChildPackages.valueAt(i).returnCode = returnCode; 13685 } 13686 } 13687 13688 private void setReturnMessage(String returnMsg) { 13689 this.returnMsg = returnMsg; 13690 final int childCount = (addedChildPackages != null) ? addedChildPackages.size() : 0; 13691 for (int i = 0; i < childCount; i++) { 13692 addedChildPackages.valueAt(i).returnMsg = returnMsg; 13693 } 13694 } 13695 13696 // In some error cases we want to convey more info back to the observer 13697 String origPackage; 13698 String origPermission; 13699 } 13700 13701 /* 13702 * Install a non-existing package. 13703 */ 13704 private void installNewPackageLIF(PackageParser.Package pkg, final int policyFlags, 13705 int scanFlags, UserHandle user, String installerPackageName, String volumeUuid, 13706 PackageInstalledInfo res) { 13707 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installNewPackage"); 13708 13709 // Remember this for later, in case we need to rollback this install 13710 String pkgName = pkg.packageName; 13711 13712 if (DEBUG_INSTALL) Slog.d(TAG, "installNewPackageLI: " + pkg); 13713 13714 synchronized(mPackages) { 13715 if (mSettings.mRenamedPackages.containsKey(pkgName)) { 13716 // A package with the same name is already installed, though 13717 // it has been renamed to an older name. The package we 13718 // are trying to install should be installed as an update to 13719 // the existing one, but that has not been requested, so bail. 13720 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13721 + " without first uninstalling package running as " 13722 + mSettings.mRenamedPackages.get(pkgName)); 13723 return; 13724 } 13725 if (mPackages.containsKey(pkgName)) { 13726 // Don't allow installation over an existing package with the same name. 13727 res.setError(INSTALL_FAILED_ALREADY_EXISTS, "Attempt to re-install " + pkgName 13728 + " without first uninstalling."); 13729 return; 13730 } 13731 } 13732 13733 try { 13734 PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 13735 System.currentTimeMillis(), user); 13736 13737 updateSettingsLI(newPackage, installerPackageName, null, res, user); 13738 13739 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 13740 prepareAppDataAfterInstallLIF(newPackage); 13741 13742 } else { 13743 // Remove package from internal structures, but keep around any 13744 // data that might have already existed 13745 deletePackageLIF(pkgName, UserHandle.ALL, false, null, 13746 PackageManager.DELETE_KEEP_DATA, res.removedInfo, true, null); 13747 } 13748 } catch (PackageManagerException e) { 13749 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13750 } 13751 13752 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 13753 } 13754 13755 private boolean shouldCheckUpgradeKeySetLP(PackageSetting oldPs, int scanFlags) { 13756 // Can't rotate keys during boot or if sharedUser. 13757 if (oldPs == null || (scanFlags&SCAN_INITIAL) != 0 || oldPs.sharedUser != null 13758 || !oldPs.keySetData.isUsingUpgradeKeySets()) { 13759 return false; 13760 } 13761 // app is using upgradeKeySets; make sure all are valid 13762 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13763 long[] upgradeKeySets = oldPs.keySetData.getUpgradeKeySets(); 13764 for (int i = 0; i < upgradeKeySets.length; i++) { 13765 if (!ksms.isIdValidKeySetId(upgradeKeySets[i])) { 13766 Slog.wtf(TAG, "Package " 13767 + (oldPs.name != null ? oldPs.name : "<null>") 13768 + " contains upgrade-key-set reference to unknown key-set: " 13769 + upgradeKeySets[i] 13770 + " reverting to signatures check."); 13771 return false; 13772 } 13773 } 13774 return true; 13775 } 13776 13777 private boolean checkUpgradeKeySetLP(PackageSetting oldPS, PackageParser.Package newPkg) { 13778 // Upgrade keysets are being used. Determine if new package has a superset of the 13779 // required keys. 13780 long[] upgradeKeySets = oldPS.keySetData.getUpgradeKeySets(); 13781 KeySetManagerService ksms = mSettings.mKeySetManagerService; 13782 for (int i = 0; i < upgradeKeySets.length; i++) { 13783 Set<PublicKey> upgradeSet = ksms.getPublicKeysFromKeySetLPr(upgradeKeySets[i]); 13784 if (upgradeSet != null && newPkg.mSigningKeys.containsAll(upgradeSet)) { 13785 return true; 13786 } 13787 } 13788 return false; 13789 } 13790 13791 private void replacePackageLIF(PackageParser.Package pkg, final int policyFlags, int scanFlags, 13792 UserHandle user, String installerPackageName, PackageInstalledInfo res) { 13793 final boolean isEphemeral = (policyFlags & PackageParser.PARSE_IS_EPHEMERAL) != 0; 13794 13795 final PackageParser.Package oldPackage; 13796 final String pkgName = pkg.packageName; 13797 final int[] allUsers; 13798 13799 // First find the old package info and check signatures 13800 synchronized(mPackages) { 13801 oldPackage = mPackages.get(pkgName); 13802 final boolean oldIsEphemeral = oldPackage.applicationInfo.isEphemeralApp(); 13803 if (isEphemeral && !oldIsEphemeral) { 13804 // can't downgrade from full to ephemeral 13805 Slog.w(TAG, "Can't replace app with ephemeral: " + pkgName); 13806 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 13807 return; 13808 } 13809 if (DEBUG_INSTALL) Slog.d(TAG, "replacePackageLI: new=" + pkg + ", old=" + oldPackage); 13810 final PackageSetting ps = mSettings.mPackages.get(pkgName); 13811 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 13812 if (!checkUpgradeKeySetLP(ps, pkg)) { 13813 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13814 "New package not signed by keys specified by upgrade-keysets: " 13815 + pkgName); 13816 return; 13817 } 13818 } else { 13819 // default to original signature matching 13820 if (compareSignatures(oldPackage.mSignatures, pkg.mSignatures) 13821 != PackageManager.SIGNATURE_MATCH) { 13822 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, 13823 "New package has a different signature: " + pkgName); 13824 return; 13825 } 13826 } 13827 13828 // Check for shared user id changes 13829 String invalidPackageName = 13830 getParentOrChildPackageChangedSharedUser(oldPackage, pkg); 13831 if (invalidPackageName != null) { 13832 res.setError(INSTALL_FAILED_SHARED_USER_INCOMPATIBLE, 13833 "Package " + invalidPackageName + " tried to change user " 13834 + oldPackage.mSharedUserId); 13835 return; 13836 } 13837 13838 // In case of rollback, remember per-user/profile install state 13839 allUsers = sUserManager.getUserIds(); 13840 } 13841 13842 // Update what is removed 13843 res.removedInfo = new PackageRemovedInfo(); 13844 res.removedInfo.uid = oldPackage.applicationInfo.uid; 13845 res.removedInfo.removedPackage = oldPackage.packageName; 13846 res.removedInfo.isUpdate = true; 13847 final int childCount = (oldPackage.childPackages != null) 13848 ? oldPackage.childPackages.size() : 0; 13849 for (int i = 0; i < childCount; i++) { 13850 boolean childPackageUpdated = false; 13851 PackageParser.Package childPkg = oldPackage.childPackages.get(i); 13852 if (res.addedChildPackages != null) { 13853 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 13854 if (childRes != null) { 13855 childRes.removedInfo.uid = childPkg.applicationInfo.uid; 13856 childRes.removedInfo.removedPackage = childPkg.packageName; 13857 childRes.removedInfo.isUpdate = true; 13858 childPackageUpdated = true; 13859 } 13860 } 13861 if (!childPackageUpdated) { 13862 PackageRemovedInfo childRemovedRes = new PackageRemovedInfo(); 13863 childRemovedRes.removedPackage = childPkg.packageName; 13864 childRemovedRes.isUpdate = false; 13865 childRemovedRes.dataRemoved = true; 13866 synchronized (mPackages) { 13867 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 13868 if (childPs != null) { 13869 childRemovedRes.origUsers = childPs.queryInstalledUsers(allUsers, true); 13870 } 13871 } 13872 if (res.removedInfo.removedChildPackages == null) { 13873 res.removedInfo.removedChildPackages = new ArrayMap<>(); 13874 } 13875 res.removedInfo.removedChildPackages.put(childPkg.packageName, childRemovedRes); 13876 } 13877 } 13878 13879 boolean sysPkg = (isSystemApp(oldPackage)); 13880 if (sysPkg) { 13881 // Set the system/privileged flags as needed 13882 final boolean privileged = 13883 (oldPackage.applicationInfo.privateFlags 13884 & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 13885 final int systemPolicyFlags = policyFlags 13886 | PackageParser.PARSE_IS_SYSTEM 13887 | (privileged ? PackageParser.PARSE_IS_PRIVILEGED : 0); 13888 13889 replaceSystemPackageLIF(oldPackage, pkg, systemPolicyFlags, scanFlags, 13890 user, allUsers, installerPackageName, res); 13891 } else { 13892 replaceNonSystemPackageLIF(oldPackage, pkg, policyFlags, scanFlags, 13893 user, allUsers, installerPackageName, res); 13894 } 13895 } 13896 13897 public List<String> getPreviousCodePaths(String packageName) { 13898 final PackageSetting ps = mSettings.mPackages.get(packageName); 13899 final List<String> result = new ArrayList<String>(); 13900 if (ps != null && ps.oldCodePaths != null) { 13901 result.addAll(ps.oldCodePaths); 13902 } 13903 return result; 13904 } 13905 13906 private void replaceNonSystemPackageLIF(PackageParser.Package deletedPackage, 13907 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 13908 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 13909 if (DEBUG_INSTALL) Slog.d(TAG, "replaceNonSystemPackageLI: new=" + pkg + ", old=" 13910 + deletedPackage); 13911 13912 String pkgName = deletedPackage.packageName; 13913 boolean deletedPkg = true; 13914 boolean addedPkg = false; 13915 boolean updatedSettings = false; 13916 final boolean killApp = (scanFlags & SCAN_DONT_KILL_APP) == 0; 13917 final int deleteFlags = PackageManager.DELETE_KEEP_DATA 13918 | (killApp ? 0 : PackageManager.DELETE_DONT_KILL_APP); 13919 13920 final long origUpdateTime = (pkg.mExtras != null) 13921 ? ((PackageSetting)pkg.mExtras).lastUpdateTime : 0; 13922 13923 // First delete the existing package while retaining the data directory 13924 if (!deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13925 res.removedInfo, true, pkg)) { 13926 // If the existing package wasn't successfully deleted 13927 res.setError(INSTALL_FAILED_REPLACE_COULDNT_DELETE, "replaceNonSystemPackageLI"); 13928 deletedPkg = false; 13929 } else { 13930 // Successfully deleted the old package; proceed with replace. 13931 13932 // If deleted package lived in a container, give users a chance to 13933 // relinquish resources before killing. 13934 if (deletedPackage.isForwardLocked() || isExternal(deletedPackage)) { 13935 if (DEBUG_INSTALL) { 13936 Slog.i(TAG, "upgrading pkg " + deletedPackage + " is ASEC-hosted -> UNAVAILABLE"); 13937 } 13938 final int[] uidArray = new int[] { deletedPackage.applicationInfo.uid }; 13939 final ArrayList<String> pkgList = new ArrayList<String>(1); 13940 pkgList.add(deletedPackage.applicationInfo.packageName); 13941 sendResourcesChangedBroadcast(false, true, pkgList, uidArray, null); 13942 } 13943 13944 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 13945 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 13946 clearAppProfilesLIF(pkg); 13947 13948 try { 13949 final PackageParser.Package newPackage = scanPackageTracedLI(pkg, policyFlags, 13950 scanFlags | SCAN_UPDATE_TIME, System.currentTimeMillis(), user); 13951 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 13952 13953 // Update the in-memory copy of the previous code paths. 13954 PackageSetting ps = mSettings.mPackages.get(pkgName); 13955 if (!killApp) { 13956 if (ps.oldCodePaths == null) { 13957 ps.oldCodePaths = new ArraySet<>(); 13958 } 13959 Collections.addAll(ps.oldCodePaths, deletedPackage.baseCodePath); 13960 if (deletedPackage.splitCodePaths != null) { 13961 Collections.addAll(ps.oldCodePaths, deletedPackage.splitCodePaths); 13962 } 13963 } else { 13964 ps.oldCodePaths = null; 13965 } 13966 if (ps.childPackageNames != null) { 13967 for (int i = ps.childPackageNames.size() - 1; i >= 0; --i) { 13968 final String childPkgName = ps.childPackageNames.get(i); 13969 final PackageSetting childPs = mSettings.mPackages.get(childPkgName); 13970 childPs.oldCodePaths = ps.oldCodePaths; 13971 } 13972 } 13973 prepareAppDataAfterInstallLIF(newPackage); 13974 addedPkg = true; 13975 } catch (PackageManagerException e) { 13976 res.setError("Package couldn't be installed in " + pkg.codePath, e); 13977 } 13978 } 13979 13980 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 13981 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, rolling pack: " + pkgName); 13982 13983 // Revert all internal state mutations and added folders for the failed install 13984 if (addedPkg) { 13985 deletePackageLIF(pkgName, null, true, allUsers, deleteFlags, 13986 res.removedInfo, true, null); 13987 } 13988 13989 // Restore the old package 13990 if (deletedPkg) { 13991 if (DEBUG_INSTALL) Slog.d(TAG, "Install failed, reinstalling: " + deletedPackage); 13992 File restoreFile = new File(deletedPackage.codePath); 13993 // Parse old package 13994 boolean oldExternal = isExternal(deletedPackage); 13995 int oldParseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY | 13996 (deletedPackage.isForwardLocked() ? PackageParser.PARSE_FORWARD_LOCK : 0) | 13997 (oldExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0); 13998 int oldScanFlags = SCAN_UPDATE_SIGNATURE | SCAN_UPDATE_TIME; 13999 try { 14000 scanPackageTracedLI(restoreFile, oldParseFlags, oldScanFlags, origUpdateTime, 14001 null); 14002 } catch (PackageManagerException e) { 14003 Slog.e(TAG, "Failed to restore package : " + pkgName + " after failed upgrade: " 14004 + e.getMessage()); 14005 return; 14006 } 14007 14008 synchronized (mPackages) { 14009 // Ensure the installer package name up to date 14010 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14011 14012 // Update permissions for restored package 14013 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14014 14015 mSettings.writeLPr(); 14016 } 14017 14018 Slog.i(TAG, "Successfully restored package : " + pkgName + " after failed upgrade"); 14019 } 14020 } else { 14021 synchronized (mPackages) { 14022 PackageSetting ps = mSettings.peekPackageLPr(pkg.packageName); 14023 if (ps != null) { 14024 res.removedInfo.removedForAllUsers = mPackages.get(ps.name) == null; 14025 if (res.removedInfo.removedChildPackages != null) { 14026 final int childCount = res.removedInfo.removedChildPackages.size(); 14027 // Iterate in reverse as we may modify the collection 14028 for (int i = childCount - 1; i >= 0; i--) { 14029 String childPackageName = res.removedInfo.removedChildPackages.keyAt(i); 14030 if (res.addedChildPackages.containsKey(childPackageName)) { 14031 res.removedInfo.removedChildPackages.removeAt(i); 14032 } else { 14033 PackageRemovedInfo childInfo = res.removedInfo 14034 .removedChildPackages.valueAt(i); 14035 childInfo.removedForAllUsers = mPackages.get( 14036 childInfo.removedPackage) == null; 14037 } 14038 } 14039 } 14040 } 14041 } 14042 } 14043 } 14044 14045 private void replaceSystemPackageLIF(PackageParser.Package deletedPackage, 14046 PackageParser.Package pkg, final int policyFlags, int scanFlags, UserHandle user, 14047 int[] allUsers, String installerPackageName, PackageInstalledInfo res) { 14048 if (DEBUG_INSTALL) Slog.d(TAG, "replaceSystemPackageLI: new=" + pkg 14049 + ", old=" + deletedPackage); 14050 14051 final boolean disabledSystem; 14052 14053 // Remove existing system package 14054 removePackageLI(deletedPackage, true); 14055 14056 disabledSystem = disableSystemPackageLPw(deletedPackage, pkg); 14057 if (!disabledSystem) { 14058 // We didn't need to disable the .apk as a current system package, 14059 // which means we are replacing another update that is already 14060 // installed. We need to make sure to delete the older one's .apk. 14061 res.removedInfo.args = createInstallArgsForExisting(0, 14062 deletedPackage.applicationInfo.getCodePath(), 14063 deletedPackage.applicationInfo.getResourcePath(), 14064 getAppDexInstructionSets(deletedPackage.applicationInfo)); 14065 } else { 14066 res.removedInfo.args = null; 14067 } 14068 14069 // Successfully disabled the old package. Now proceed with re-installation 14070 clearAppDataLIF(pkg, UserHandle.USER_ALL, StorageManager.FLAG_STORAGE_DE 14071 | StorageManager.FLAG_STORAGE_CE | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 14072 clearAppProfilesLIF(pkg); 14073 14074 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14075 pkg.setApplicationInfoFlags(ApplicationInfo.FLAG_UPDATED_SYSTEM_APP, 14076 ApplicationInfo.FLAG_UPDATED_SYSTEM_APP); 14077 14078 PackageParser.Package newPackage = null; 14079 try { 14080 // Add the package to the internal data structures 14081 newPackage = scanPackageTracedLI(pkg, policyFlags, scanFlags, 0, user); 14082 14083 // Set the update and install times 14084 PackageSetting deletedPkgSetting = (PackageSetting) deletedPackage.mExtras; 14085 setInstallAndUpdateTime(newPackage, deletedPkgSetting.firstInstallTime, 14086 System.currentTimeMillis()); 14087 14088 // Update the package dynamic state if succeeded 14089 if (res.returnCode == PackageManager.INSTALL_SUCCEEDED) { 14090 // Now that the install succeeded make sure we remove data 14091 // directories for any child package the update removed. 14092 final int deletedChildCount = (deletedPackage.childPackages != null) 14093 ? deletedPackage.childPackages.size() : 0; 14094 final int newChildCount = (newPackage.childPackages != null) 14095 ? newPackage.childPackages.size() : 0; 14096 for (int i = 0; i < deletedChildCount; i++) { 14097 PackageParser.Package deletedChildPkg = deletedPackage.childPackages.get(i); 14098 boolean childPackageDeleted = true; 14099 for (int j = 0; j < newChildCount; j++) { 14100 PackageParser.Package newChildPkg = newPackage.childPackages.get(j); 14101 if (deletedChildPkg.packageName.equals(newChildPkg.packageName)) { 14102 childPackageDeleted = false; 14103 break; 14104 } 14105 } 14106 if (childPackageDeleted) { 14107 PackageSetting ps = mSettings.getDisabledSystemPkgLPr( 14108 deletedChildPkg.packageName); 14109 if (ps != null && res.removedInfo.removedChildPackages != null) { 14110 PackageRemovedInfo removedChildRes = res.removedInfo 14111 .removedChildPackages.get(deletedChildPkg.packageName); 14112 removePackageDataLIF(ps, allUsers, removedChildRes, 0, false); 14113 removedChildRes.removedForAllUsers = mPackages.get(ps.name) == null; 14114 } 14115 } 14116 } 14117 14118 updateSettingsLI(newPackage, installerPackageName, allUsers, res, user); 14119 prepareAppDataAfterInstallLIF(newPackage); 14120 } 14121 } catch (PackageManagerException e) { 14122 res.setReturnCode(INSTALL_FAILED_INTERNAL_ERROR); 14123 res.setError("Package couldn't be installed in " + pkg.codePath, e); 14124 } 14125 14126 if (res.returnCode != PackageManager.INSTALL_SUCCEEDED) { 14127 // Re installation failed. Restore old information 14128 // Remove new pkg information 14129 if (newPackage != null) { 14130 removeInstalledPackageLI(newPackage, true); 14131 } 14132 // Add back the old system package 14133 try { 14134 scanPackageTracedLI(deletedPackage, policyFlags, SCAN_UPDATE_SIGNATURE, 0, user); 14135 } catch (PackageManagerException e) { 14136 Slog.e(TAG, "Failed to restore original package: " + e.getMessage()); 14137 } 14138 14139 synchronized (mPackages) { 14140 if (disabledSystem) { 14141 enableSystemPackageLPw(deletedPackage); 14142 } 14143 14144 // Ensure the installer package name up to date 14145 setInstallerPackageNameLPw(deletedPackage, installerPackageName); 14146 14147 // Update permissions for restored package 14148 updatePermissionsLPw(deletedPackage, UPDATE_PERMISSIONS_ALL); 14149 14150 mSettings.writeLPr(); 14151 } 14152 14153 Slog.i(TAG, "Successfully restored package : " + deletedPackage.packageName 14154 + " after failed upgrade"); 14155 } 14156 } 14157 14158 /** 14159 * Checks whether the parent or any of the child packages have a change shared 14160 * user. For a package to be a valid update the shred users of the parent and 14161 * the children should match. We may later support changing child shared users. 14162 * @param oldPkg The updated package. 14163 * @param newPkg The update package. 14164 * @return The shared user that change between the versions. 14165 */ 14166 private String getParentOrChildPackageChangedSharedUser(PackageParser.Package oldPkg, 14167 PackageParser.Package newPkg) { 14168 // Check parent shared user 14169 if (!Objects.equals(oldPkg.mSharedUserId, newPkg.mSharedUserId)) { 14170 return newPkg.packageName; 14171 } 14172 // Check child shared users 14173 final int oldChildCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14174 final int newChildCount = (newPkg.childPackages != null) ? newPkg.childPackages.size() : 0; 14175 for (int i = 0; i < newChildCount; i++) { 14176 PackageParser.Package newChildPkg = newPkg.childPackages.get(i); 14177 // If this child was present, did it have the same shared user? 14178 for (int j = 0; j < oldChildCount; j++) { 14179 PackageParser.Package oldChildPkg = oldPkg.childPackages.get(j); 14180 if (newChildPkg.packageName.equals(oldChildPkg.packageName) 14181 && !Objects.equals(newChildPkg.mSharedUserId, oldChildPkg.mSharedUserId)) { 14182 return newChildPkg.packageName; 14183 } 14184 } 14185 } 14186 return null; 14187 } 14188 14189 private void removeNativeBinariesLI(PackageSetting ps) { 14190 // Remove the lib path for the parent package 14191 if (ps != null) { 14192 NativeLibraryHelper.removeNativeBinariesLI(ps.legacyNativeLibraryPathString); 14193 // Remove the lib path for the child packages 14194 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 14195 for (int i = 0; i < childCount; i++) { 14196 PackageSetting childPs = null; 14197 synchronized (mPackages) { 14198 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 14199 } 14200 if (childPs != null) { 14201 NativeLibraryHelper.removeNativeBinariesLI(childPs 14202 .legacyNativeLibraryPathString); 14203 } 14204 } 14205 } 14206 } 14207 14208 private void enableSystemPackageLPw(PackageParser.Package pkg) { 14209 // Enable the parent package 14210 mSettings.enableSystemPackageLPw(pkg.packageName); 14211 // Enable the child packages 14212 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14213 for (int i = 0; i < childCount; i++) { 14214 PackageParser.Package childPkg = pkg.childPackages.get(i); 14215 mSettings.enableSystemPackageLPw(childPkg.packageName); 14216 } 14217 } 14218 14219 private boolean disableSystemPackageLPw(PackageParser.Package oldPkg, 14220 PackageParser.Package newPkg) { 14221 // Disable the parent package (parent always replaced) 14222 boolean disabled = mSettings.disableSystemPackageLPw(oldPkg.packageName, true); 14223 // Disable the child packages 14224 final int childCount = (oldPkg.childPackages != null) ? oldPkg.childPackages.size() : 0; 14225 for (int i = 0; i < childCount; i++) { 14226 PackageParser.Package childPkg = oldPkg.childPackages.get(i); 14227 final boolean replace = newPkg.hasChildPackage(childPkg.packageName); 14228 disabled |= mSettings.disableSystemPackageLPw(childPkg.packageName, replace); 14229 } 14230 return disabled; 14231 } 14232 14233 private void setInstallerPackageNameLPw(PackageParser.Package pkg, 14234 String installerPackageName) { 14235 // Enable the parent package 14236 mSettings.setInstallerPackageName(pkg.packageName, installerPackageName); 14237 // Enable the child packages 14238 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14239 for (int i = 0; i < childCount; i++) { 14240 PackageParser.Package childPkg = pkg.childPackages.get(i); 14241 mSettings.setInstallerPackageName(childPkg.packageName, installerPackageName); 14242 } 14243 } 14244 14245 private int[] revokeUnusedSharedUserPermissionsLPw(SharedUserSetting su, int[] allUserIds) { 14246 // Collect all used permissions in the UID 14247 ArraySet<String> usedPermissions = new ArraySet<>(); 14248 final int packageCount = su.packages.size(); 14249 for (int i = 0; i < packageCount; i++) { 14250 PackageSetting ps = su.packages.valueAt(i); 14251 if (ps.pkg == null) { 14252 continue; 14253 } 14254 final int requestedPermCount = ps.pkg.requestedPermissions.size(); 14255 for (int j = 0; j < requestedPermCount; j++) { 14256 String permission = ps.pkg.requestedPermissions.get(j); 14257 BasePermission bp = mSettings.mPermissions.get(permission); 14258 if (bp != null) { 14259 usedPermissions.add(permission); 14260 } 14261 } 14262 } 14263 14264 PermissionsState permissionsState = su.getPermissionsState(); 14265 // Prune install permissions 14266 List<PermissionState> installPermStates = permissionsState.getInstallPermissionStates(); 14267 final int installPermCount = installPermStates.size(); 14268 for (int i = installPermCount - 1; i >= 0; i--) { 14269 PermissionState permissionState = installPermStates.get(i); 14270 if (!usedPermissions.contains(permissionState.getName())) { 14271 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14272 if (bp != null) { 14273 permissionsState.revokeInstallPermission(bp); 14274 permissionsState.updatePermissionFlags(bp, UserHandle.USER_ALL, 14275 PackageManager.MASK_PERMISSION_FLAGS, 0); 14276 } 14277 } 14278 } 14279 14280 int[] runtimePermissionChangedUserIds = EmptyArray.INT; 14281 14282 // Prune runtime permissions 14283 for (int userId : allUserIds) { 14284 List<PermissionState> runtimePermStates = permissionsState 14285 .getRuntimePermissionStates(userId); 14286 final int runtimePermCount = runtimePermStates.size(); 14287 for (int i = runtimePermCount - 1; i >= 0; i--) { 14288 PermissionState permissionState = runtimePermStates.get(i); 14289 if (!usedPermissions.contains(permissionState.getName())) { 14290 BasePermission bp = mSettings.mPermissions.get(permissionState.getName()); 14291 if (bp != null) { 14292 permissionsState.revokeRuntimePermission(bp, userId); 14293 permissionsState.updatePermissionFlags(bp, userId, 14294 PackageManager.MASK_PERMISSION_FLAGS, 0); 14295 runtimePermissionChangedUserIds = ArrayUtils.appendInt( 14296 runtimePermissionChangedUserIds, userId); 14297 } 14298 } 14299 } 14300 } 14301 14302 return runtimePermissionChangedUserIds; 14303 } 14304 14305 private void updateSettingsLI(PackageParser.Package newPackage, String installerPackageName, 14306 int[] allUsers, PackageInstalledInfo res, UserHandle user) { 14307 // Update the parent package setting 14308 updateSettingsInternalLI(newPackage, installerPackageName, allUsers, res.origUsers, 14309 res, user); 14310 // Update the child packages setting 14311 final int childCount = (newPackage.childPackages != null) 14312 ? newPackage.childPackages.size() : 0; 14313 for (int i = 0; i < childCount; i++) { 14314 PackageParser.Package childPackage = newPackage.childPackages.get(i); 14315 PackageInstalledInfo childRes = res.addedChildPackages.get(childPackage.packageName); 14316 updateSettingsInternalLI(childPackage, installerPackageName, allUsers, 14317 childRes.origUsers, childRes, user); 14318 } 14319 } 14320 14321 private void updateSettingsInternalLI(PackageParser.Package newPackage, 14322 String installerPackageName, int[] allUsers, int[] installedForUsers, 14323 PackageInstalledInfo res, UserHandle user) { 14324 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "updateSettings"); 14325 14326 String pkgName = newPackage.packageName; 14327 synchronized (mPackages) { 14328 //write settings. the installStatus will be incomplete at this stage. 14329 //note that the new package setting would have already been 14330 //added to mPackages. It hasn't been persisted yet. 14331 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_INCOMPLETE); 14332 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14333 mSettings.writeLPr(); 14334 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14335 } 14336 14337 if (DEBUG_INSTALL) Slog.d(TAG, "New package installed in " + newPackage.codePath); 14338 synchronized (mPackages) { 14339 updatePermissionsLPw(newPackage.packageName, newPackage, 14340 UPDATE_PERMISSIONS_REPLACE_PKG | (newPackage.permissions.size() > 0 14341 ? UPDATE_PERMISSIONS_ALL : 0)); 14342 // For system-bundled packages, we assume that installing an upgraded version 14343 // of the package implies that the user actually wants to run that new code, 14344 // so we enable the package. 14345 PackageSetting ps = mSettings.mPackages.get(pkgName); 14346 final int userId = user.getIdentifier(); 14347 if (ps != null) { 14348 if (isSystemApp(newPackage)) { 14349 if (DEBUG_INSTALL) { 14350 Slog.d(TAG, "Implicitly enabling system package on upgrade: " + pkgName); 14351 } 14352 // Enable system package for requested users 14353 if (res.origUsers != null) { 14354 for (int origUserId : res.origUsers) { 14355 if (userId == UserHandle.USER_ALL || userId == origUserId) { 14356 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, 14357 origUserId, installerPackageName); 14358 } 14359 } 14360 } 14361 // Also convey the prior install/uninstall state 14362 if (allUsers != null && installedForUsers != null) { 14363 for (int currentUserId : allUsers) { 14364 final boolean installed = ArrayUtils.contains( 14365 installedForUsers, currentUserId); 14366 if (DEBUG_INSTALL) { 14367 Slog.d(TAG, " user " + currentUserId + " => " + installed); 14368 } 14369 ps.setInstalled(installed, currentUserId); 14370 } 14371 // these install state changes will be persisted in the 14372 // upcoming call to mSettings.writeLPr(). 14373 } 14374 } 14375 // It's implied that when a user requests installation, they want the app to be 14376 // installed and enabled. 14377 if (userId != UserHandle.USER_ALL) { 14378 ps.setInstalled(true, userId); 14379 ps.setEnabled(COMPONENT_ENABLED_STATE_DEFAULT, userId, installerPackageName); 14380 } 14381 } 14382 res.name = pkgName; 14383 res.uid = newPackage.applicationInfo.uid; 14384 res.pkg = newPackage; 14385 mSettings.setInstallStatus(pkgName, PackageSettingBase.PKG_INSTALL_COMPLETE); 14386 mSettings.setInstallerPackageName(pkgName, installerPackageName); 14387 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14388 //to update install status 14389 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "writeSettings"); 14390 mSettings.writeLPr(); 14391 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14392 } 14393 14394 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14395 } 14396 14397 private void installPackageTracedLI(InstallArgs args, PackageInstalledInfo res) { 14398 try { 14399 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "installPackage"); 14400 installPackageLI(args, res); 14401 } finally { 14402 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14403 } 14404 } 14405 14406 private void installPackageLI(InstallArgs args, PackageInstalledInfo res) { 14407 final int installFlags = args.installFlags; 14408 final String installerPackageName = args.installerPackageName; 14409 final String volumeUuid = args.volumeUuid; 14410 final File tmpPackageFile = new File(args.getCodePath()); 14411 final boolean forwardLocked = ((installFlags & PackageManager.INSTALL_FORWARD_LOCK) != 0); 14412 final boolean onExternal = (((installFlags & PackageManager.INSTALL_EXTERNAL) != 0) 14413 || (args.volumeUuid != null)); 14414 final boolean ephemeral = ((installFlags & PackageManager.INSTALL_EPHEMERAL) != 0); 14415 boolean replace = false; 14416 int scanFlags = SCAN_NEW_INSTALL | SCAN_UPDATE_SIGNATURE; 14417 if (args.move != null) { 14418 // moving a complete application; perform an initial scan on the new install location 14419 scanFlags |= SCAN_INITIAL; 14420 } 14421 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 14422 scanFlags |= SCAN_DONT_KILL_APP; 14423 } 14424 14425 // Result object to be returned 14426 res.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14427 14428 if (DEBUG_INSTALL) Slog.d(TAG, "installPackageLI: path=" + tmpPackageFile); 14429 14430 // Sanity check 14431 if (ephemeral && (forwardLocked || onExternal)) { 14432 Slog.i(TAG, "Incompatible ephemeral install; fwdLocked=" + forwardLocked 14433 + " external=" + onExternal); 14434 res.setReturnCode(PackageManager.INSTALL_FAILED_EPHEMERAL_INVALID); 14435 return; 14436 } 14437 14438 // Retrieve PackageSettings and parse package 14439 final int parseFlags = mDefParseFlags | PackageParser.PARSE_CHATTY 14440 | PackageParser.PARSE_ENFORCE_CODE 14441 | (forwardLocked ? PackageParser.PARSE_FORWARD_LOCK : 0) 14442 | (onExternal ? PackageParser.PARSE_EXTERNAL_STORAGE : 0) 14443 | (ephemeral ? PackageParser.PARSE_IS_EPHEMERAL : 0); 14444 PackageParser pp = new PackageParser(); 14445 pp.setSeparateProcesses(mSeparateProcesses); 14446 pp.setDisplayMetrics(mMetrics); 14447 14448 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "parsePackage"); 14449 final PackageParser.Package pkg; 14450 try { 14451 pkg = pp.parsePackage(tmpPackageFile, parseFlags); 14452 } catch (PackageParserException e) { 14453 res.setError("Failed parse during installPackageLI", e); 14454 return; 14455 } finally { 14456 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14457 } 14458 14459 // If we are installing a clustered package add results for the children 14460 if (pkg.childPackages != null) { 14461 synchronized (mPackages) { 14462 final int childCount = pkg.childPackages.size(); 14463 for (int i = 0; i < childCount; i++) { 14464 PackageParser.Package childPkg = pkg.childPackages.get(i); 14465 PackageInstalledInfo childRes = new PackageInstalledInfo(); 14466 childRes.setReturnCode(PackageManager.INSTALL_SUCCEEDED); 14467 childRes.pkg = childPkg; 14468 childRes.name = childPkg.packageName; 14469 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14470 if (childPs != null) { 14471 childRes.origUsers = childPs.queryInstalledUsers( 14472 sUserManager.getUserIds(), true); 14473 } 14474 if ((mPackages.containsKey(childPkg.packageName))) { 14475 childRes.removedInfo = new PackageRemovedInfo(); 14476 childRes.removedInfo.removedPackage = childPkg.packageName; 14477 } 14478 if (res.addedChildPackages == null) { 14479 res.addedChildPackages = new ArrayMap<>(); 14480 } 14481 res.addedChildPackages.put(childPkg.packageName, childRes); 14482 } 14483 } 14484 } 14485 14486 // If package doesn't declare API override, mark that we have an install 14487 // time CPU ABI override. 14488 if (TextUtils.isEmpty(pkg.cpuAbiOverride)) { 14489 pkg.cpuAbiOverride = args.abiOverride; 14490 } 14491 14492 String pkgName = res.name = pkg.packageName; 14493 if ((pkg.applicationInfo.flags&ApplicationInfo.FLAG_TEST_ONLY) != 0) { 14494 if ((installFlags & PackageManager.INSTALL_ALLOW_TEST) == 0) { 14495 res.setError(INSTALL_FAILED_TEST_ONLY, "installPackageLI"); 14496 return; 14497 } 14498 } 14499 14500 try { 14501 // either use what we've been given or parse directly from the APK 14502 if (args.certificates != null) { 14503 try { 14504 PackageParser.populateCertificates(pkg, args.certificates); 14505 } catch (PackageParserException e) { 14506 // there was something wrong with the certificates we were given; 14507 // try to pull them from the APK 14508 PackageParser.collectCertificates(pkg, parseFlags); 14509 } 14510 } else { 14511 PackageParser.collectCertificates(pkg, parseFlags); 14512 } 14513 } catch (PackageParserException e) { 14514 res.setError("Failed collect during installPackageLI", e); 14515 return; 14516 } 14517 14518 // Get rid of all references to package scan path via parser. 14519 pp = null; 14520 String oldCodePath = null; 14521 boolean systemApp = false; 14522 synchronized (mPackages) { 14523 // Check if installing already existing package 14524 if ((installFlags & PackageManager.INSTALL_REPLACE_EXISTING) != 0) { 14525 String oldName = mSettings.mRenamedPackages.get(pkgName); 14526 if (pkg.mOriginalPackages != null 14527 && pkg.mOriginalPackages.contains(oldName) 14528 && mPackages.containsKey(oldName)) { 14529 // This package is derived from an original package, 14530 // and this device has been updating from that original 14531 // name. We must continue using the original name, so 14532 // rename the new package here. 14533 pkg.setPackageName(oldName); 14534 pkgName = pkg.packageName; 14535 replace = true; 14536 if (DEBUG_INSTALL) Slog.d(TAG, "Replacing existing renamed package: oldName=" 14537 + oldName + " pkgName=" + pkgName); 14538 } else if (mPackages.containsKey(pkgName)) { 14539 // This package, under its official name, already exists 14540 // on the device; we should replace it. 14541 replace = true; 14542 if (DEBUG_INSTALL) Slog.d(TAG, "Replace existing pacakge: " + pkgName); 14543 } 14544 14545 // Child packages are installed through the parent package 14546 if (pkg.parentPackage != null) { 14547 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14548 "Package " + pkg.packageName + " is child of package " 14549 + pkg.parentPackage.parentPackage + ". Child packages " 14550 + "can be updated only through the parent package."); 14551 return; 14552 } 14553 14554 if (replace) { 14555 // Prevent apps opting out from runtime permissions 14556 PackageParser.Package oldPackage = mPackages.get(pkgName); 14557 final int oldTargetSdk = oldPackage.applicationInfo.targetSdkVersion; 14558 final int newTargetSdk = pkg.applicationInfo.targetSdkVersion; 14559 if (oldTargetSdk > Build.VERSION_CODES.LOLLIPOP_MR1 14560 && newTargetSdk <= Build.VERSION_CODES.LOLLIPOP_MR1) { 14561 res.setError(PackageManager.INSTALL_FAILED_PERMISSION_MODEL_DOWNGRADE, 14562 "Package " + pkg.packageName + " new target SDK " + newTargetSdk 14563 + " doesn't support runtime permissions but the old" 14564 + " target SDK " + oldTargetSdk + " does."); 14565 return; 14566 } 14567 14568 // Prevent installing of child packages 14569 if (oldPackage.parentPackage != null) { 14570 res.setError(PackageManager.INSTALL_PARSE_FAILED_BAD_PACKAGE_NAME, 14571 "Package " + pkg.packageName + " is child of package " 14572 + oldPackage.parentPackage + ". Child packages " 14573 + "can be updated only through the parent package."); 14574 return; 14575 } 14576 } 14577 } 14578 14579 PackageSetting ps = mSettings.mPackages.get(pkgName); 14580 if (ps != null) { 14581 if (DEBUG_INSTALL) Slog.d(TAG, "Existing package: " + ps); 14582 14583 // Quick sanity check that we're signed correctly if updating; 14584 // we'll check this again later when scanning, but we want to 14585 // bail early here before tripping over redefined permissions. 14586 if (shouldCheckUpgradeKeySetLP(ps, scanFlags)) { 14587 if (!checkUpgradeKeySetLP(ps, pkg)) { 14588 res.setError(INSTALL_FAILED_UPDATE_INCOMPATIBLE, "Package " 14589 + pkg.packageName + " upgrade keys do not match the " 14590 + "previously installed version"); 14591 return; 14592 } 14593 } else { 14594 try { 14595 verifySignaturesLP(ps, pkg); 14596 } catch (PackageManagerException e) { 14597 res.setError(e.error, e.getMessage()); 14598 return; 14599 } 14600 } 14601 14602 oldCodePath = mSettings.mPackages.get(pkgName).codePathString; 14603 if (ps.pkg != null && ps.pkg.applicationInfo != null) { 14604 systemApp = (ps.pkg.applicationInfo.flags & 14605 ApplicationInfo.FLAG_SYSTEM) != 0; 14606 } 14607 res.origUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14608 } 14609 14610 // Check whether the newly-scanned package wants to define an already-defined perm 14611 int N = pkg.permissions.size(); 14612 for (int i = N-1; i >= 0; i--) { 14613 PackageParser.Permission perm = pkg.permissions.get(i); 14614 BasePermission bp = mSettings.mPermissions.get(perm.info.name); 14615 if (bp != null) { 14616 // If the defining package is signed with our cert, it's okay. This 14617 // also includes the "updating the same package" case, of course. 14618 // "updating same package" could also involve key-rotation. 14619 final boolean sigsOk; 14620 if (bp.sourcePackage.equals(pkg.packageName) 14621 && (bp.packageSetting instanceof PackageSetting) 14622 && (shouldCheckUpgradeKeySetLP((PackageSetting) bp.packageSetting, 14623 scanFlags))) { 14624 sigsOk = checkUpgradeKeySetLP((PackageSetting) bp.packageSetting, pkg); 14625 } else { 14626 sigsOk = compareSignatures(bp.packageSetting.signatures.mSignatures, 14627 pkg.mSignatures) == PackageManager.SIGNATURE_MATCH; 14628 } 14629 if (!sigsOk) { 14630 // If the owning package is the system itself, we log but allow 14631 // install to proceed; we fail the install on all other permission 14632 // redefinitions. 14633 if (!bp.sourcePackage.equals("android")) { 14634 res.setError(INSTALL_FAILED_DUPLICATE_PERMISSION, "Package " 14635 + pkg.packageName + " attempting to redeclare permission " 14636 + perm.info.name + " already owned by " + bp.sourcePackage); 14637 res.origPermission = perm.info.name; 14638 res.origPackage = bp.sourcePackage; 14639 return; 14640 } else { 14641 Slog.w(TAG, "Package " + pkg.packageName 14642 + " attempting to redeclare system permission " 14643 + perm.info.name + "; ignoring new declaration"); 14644 pkg.permissions.remove(i); 14645 } 14646 } 14647 } 14648 } 14649 } 14650 14651 if (systemApp) { 14652 if (onExternal) { 14653 // Abort update; system app can't be replaced with app on sdcard 14654 res.setError(INSTALL_FAILED_INVALID_INSTALL_LOCATION, 14655 "Cannot install updates to system apps on sdcard"); 14656 return; 14657 } else if (ephemeral) { 14658 // Abort update; system app can't be replaced with an ephemeral app 14659 res.setError(INSTALL_FAILED_EPHEMERAL_INVALID, 14660 "Cannot update a system app with an ephemeral app"); 14661 return; 14662 } 14663 } 14664 14665 if (args.move != null) { 14666 // We did an in-place move, so dex is ready to roll 14667 scanFlags |= SCAN_NO_DEX; 14668 scanFlags |= SCAN_MOVE; 14669 14670 synchronized (mPackages) { 14671 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14672 if (ps == null) { 14673 res.setError(INSTALL_FAILED_INTERNAL_ERROR, 14674 "Missing settings for moved package " + pkgName); 14675 } 14676 14677 // We moved the entire application as-is, so bring over the 14678 // previously derived ABI information. 14679 pkg.applicationInfo.primaryCpuAbi = ps.primaryCpuAbiString; 14680 pkg.applicationInfo.secondaryCpuAbi = ps.secondaryCpuAbiString; 14681 } 14682 14683 } else if (!forwardLocked && !pkg.applicationInfo.isExternalAsec()) { 14684 // Enable SCAN_NO_DEX flag to skip dexopt at a later stage 14685 scanFlags |= SCAN_NO_DEX; 14686 14687 try { 14688 String abiOverride = (TextUtils.isEmpty(pkg.cpuAbiOverride) ? 14689 args.abiOverride : pkg.cpuAbiOverride); 14690 derivePackageAbi(pkg, new File(pkg.codePath), abiOverride, 14691 true /* extract libs */); 14692 } catch (PackageManagerException pme) { 14693 Slog.e(TAG, "Error deriving application ABI", pme); 14694 res.setError(INSTALL_FAILED_INTERNAL_ERROR, "Error deriving application ABI"); 14695 return; 14696 } 14697 14698 Trace.traceBegin(TRACE_TAG_PACKAGE_MANAGER, "dexopt"); 14699 // Do not run PackageDexOptimizer through the local performDexOpt 14700 // method because `pkg` is not in `mPackages` yet. 14701 int result = mPackageDexOptimizer.performDexOpt(pkg, null /* instructionSets */, 14702 false /* checkProfiles */, getCompilerFilterForReason(REASON_INSTALL)); 14703 Trace.traceEnd(TRACE_TAG_PACKAGE_MANAGER); 14704 if (result == PackageDexOptimizer.DEX_OPT_FAILED) { 14705 String msg = "Extracting package failed for " + pkgName; 14706 res.setError(INSTALL_FAILED_DEXOPT, msg); 14707 return; 14708 } 14709 14710 // Notify BackgroundDexOptService that the package has been changed. 14711 // If this is an update of a package which used to fail to compile, 14712 // BDOS will remove it from its blacklist. 14713 BackgroundDexOptService.notifyPackageChanged(pkg.packageName); 14714 } 14715 14716 if (!args.doRename(res.returnCode, pkg, oldCodePath)) { 14717 res.setError(INSTALL_FAILED_INSUFFICIENT_STORAGE, "Failed rename"); 14718 return; 14719 } 14720 14721 startIntentFilterVerifications(args.user.getIdentifier(), replace, pkg); 14722 14723 try (PackageFreezer freezer = freezePackageForInstall(pkgName, installFlags, 14724 "installPackageLI")) { 14725 if (replace) { 14726 replacePackageLIF(pkg, parseFlags, scanFlags | SCAN_REPLACING, args.user, 14727 installerPackageName, res); 14728 } else { 14729 installNewPackageLIF(pkg, parseFlags, scanFlags | SCAN_DELETE_DATA_ON_FAILURES, 14730 args.user, installerPackageName, volumeUuid, res); 14731 } 14732 } 14733 synchronized (mPackages) { 14734 final PackageSetting ps = mSettings.mPackages.get(pkgName); 14735 if (ps != null) { 14736 res.newUsers = ps.queryInstalledUsers(sUserManager.getUserIds(), true); 14737 } 14738 14739 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14740 for (int i = 0; i < childCount; i++) { 14741 PackageParser.Package childPkg = pkg.childPackages.get(i); 14742 PackageInstalledInfo childRes = res.addedChildPackages.get(childPkg.packageName); 14743 PackageSetting childPs = mSettings.peekPackageLPr(childPkg.packageName); 14744 if (childPs != null) { 14745 childRes.newUsers = childPs.queryInstalledUsers( 14746 sUserManager.getUserIds(), true); 14747 } 14748 } 14749 } 14750 } 14751 14752 private void startIntentFilterVerifications(int userId, boolean replacing, 14753 PackageParser.Package pkg) { 14754 if (mIntentFilterVerifierComponent == null) { 14755 Slog.w(TAG, "No IntentFilter verification will not be done as " 14756 + "there is no IntentFilterVerifier available!"); 14757 return; 14758 } 14759 14760 final int verifierUid = getPackageUid( 14761 mIntentFilterVerifierComponent.getPackageName(), 14762 MATCH_DEBUG_TRIAGED_MISSING, 14763 (userId == UserHandle.USER_ALL) ? UserHandle.USER_SYSTEM : userId); 14764 14765 Message msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14766 msg.obj = new IFVerificationParams(pkg, replacing, userId, verifierUid); 14767 mHandler.sendMessage(msg); 14768 14769 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 14770 for (int i = 0; i < childCount; i++) { 14771 PackageParser.Package childPkg = pkg.childPackages.get(i); 14772 msg = mHandler.obtainMessage(START_INTENT_FILTER_VERIFICATIONS); 14773 msg.obj = new IFVerificationParams(childPkg, replacing, userId, verifierUid); 14774 mHandler.sendMessage(msg); 14775 } 14776 } 14777 14778 private void verifyIntentFiltersIfNeeded(int userId, int verifierUid, boolean replacing, 14779 PackageParser.Package pkg) { 14780 int size = pkg.activities.size(); 14781 if (size == 0) { 14782 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14783 "No activity, so no need to verify any IntentFilter!"); 14784 return; 14785 } 14786 14787 final boolean hasDomainURLs = hasDomainURLs(pkg); 14788 if (!hasDomainURLs) { 14789 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14790 "No domain URLs, so no need to verify any IntentFilter!"); 14791 return; 14792 } 14793 14794 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Checking for userId:" + userId 14795 + " if any IntentFilter from the " + size 14796 + " Activities needs verification ..."); 14797 14798 int count = 0; 14799 final String packageName = pkg.packageName; 14800 14801 synchronized (mPackages) { 14802 // If this is a new install and we see that we've already run verification for this 14803 // package, we have nothing to do: it means the state was restored from backup. 14804 if (!replacing) { 14805 IntentFilterVerificationInfo ivi = 14806 mSettings.getIntentFilterVerificationLPr(packageName); 14807 if (ivi != null) { 14808 if (DEBUG_DOMAIN_VERIFICATION) { 14809 Slog.i(TAG, "Package " + packageName+ " already verified: status=" 14810 + ivi.getStatusString()); 14811 } 14812 return; 14813 } 14814 } 14815 14816 // If any filters need to be verified, then all need to be. 14817 boolean needToVerify = false; 14818 for (PackageParser.Activity a : pkg.activities) { 14819 for (ActivityIntentInfo filter : a.intents) { 14820 if (filter.needsVerification() && needsNetworkVerificationLPr(filter)) { 14821 if (DEBUG_DOMAIN_VERIFICATION) { 14822 Slog.d(TAG, "Intent filter needs verification, so processing all filters"); 14823 } 14824 needToVerify = true; 14825 break; 14826 } 14827 } 14828 } 14829 14830 if (needToVerify) { 14831 final int verificationId = mIntentFilterVerificationToken++; 14832 for (PackageParser.Activity a : pkg.activities) { 14833 for (ActivityIntentInfo filter : a.intents) { 14834 if (filter.handlesWebUris(true) && needsNetworkVerificationLPr(filter)) { 14835 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, 14836 "Verification needed for IntentFilter:" + filter.toString()); 14837 mIntentFilterVerifier.addOneIntentFilterVerification( 14838 verifierUid, userId, verificationId, filter, packageName); 14839 count++; 14840 } 14841 } 14842 } 14843 } 14844 } 14845 14846 if (count > 0) { 14847 if (DEBUG_DOMAIN_VERIFICATION) Slog.d(TAG, "Starting " + count 14848 + " IntentFilter verification" + (count > 1 ? "s" : "") 14849 + " for userId:" + userId); 14850 mIntentFilterVerifier.startVerifications(userId); 14851 } else { 14852 if (DEBUG_DOMAIN_VERIFICATION) { 14853 Slog.d(TAG, "No filters or not all autoVerify for " + packageName); 14854 } 14855 } 14856 } 14857 14858 private boolean needsNetworkVerificationLPr(ActivityIntentInfo filter) { 14859 final ComponentName cn = filter.activity.getComponentName(); 14860 final String packageName = cn.getPackageName(); 14861 14862 IntentFilterVerificationInfo ivi = mSettings.getIntentFilterVerificationLPr( 14863 packageName); 14864 if (ivi == null) { 14865 return true; 14866 } 14867 int status = ivi.getStatus(); 14868 switch (status) { 14869 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED: 14870 case INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_ASK: 14871 return true; 14872 14873 default: 14874 // Nothing to do 14875 return false; 14876 } 14877 } 14878 14879 private static boolean isMultiArch(ApplicationInfo info) { 14880 return (info.flags & ApplicationInfo.FLAG_MULTIARCH) != 0; 14881 } 14882 14883 private static boolean isExternal(PackageParser.Package pkg) { 14884 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14885 } 14886 14887 private static boolean isExternal(PackageSetting ps) { 14888 return (ps.pkgFlags & ApplicationInfo.FLAG_EXTERNAL_STORAGE) != 0; 14889 } 14890 14891 private static boolean isEphemeral(PackageParser.Package pkg) { 14892 return pkg.applicationInfo.isEphemeralApp(); 14893 } 14894 14895 private static boolean isEphemeral(PackageSetting ps) { 14896 return ps.pkg != null && isEphemeral(ps.pkg); 14897 } 14898 14899 private static boolean isSystemApp(PackageParser.Package pkg) { 14900 return (pkg.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0; 14901 } 14902 14903 private static boolean isPrivilegedApp(PackageParser.Package pkg) { 14904 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_PRIVILEGED) != 0; 14905 } 14906 14907 private static boolean hasDomainURLs(PackageParser.Package pkg) { 14908 return (pkg.applicationInfo.privateFlags & ApplicationInfo.PRIVATE_FLAG_HAS_DOMAIN_URLS) != 0; 14909 } 14910 14911 private static boolean isSystemApp(PackageSetting ps) { 14912 return (ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0; 14913 } 14914 14915 private static boolean isUpdatedSystemApp(PackageSetting ps) { 14916 return (ps.pkgFlags & ApplicationInfo.FLAG_UPDATED_SYSTEM_APP) != 0; 14917 } 14918 14919 private int packageFlagsToInstallFlags(PackageSetting ps) { 14920 int installFlags = 0; 14921 if (isEphemeral(ps)) { 14922 installFlags |= PackageManager.INSTALL_EPHEMERAL; 14923 } 14924 if (isExternal(ps) && TextUtils.isEmpty(ps.volumeUuid)) { 14925 // This existing package was an external ASEC install when we have 14926 // the external flag without a UUID 14927 installFlags |= PackageManager.INSTALL_EXTERNAL; 14928 } 14929 if (ps.isForwardLocked()) { 14930 installFlags |= PackageManager.INSTALL_FORWARD_LOCK; 14931 } 14932 return installFlags; 14933 } 14934 14935 private String getVolumeUuidForPackage(PackageParser.Package pkg) { 14936 if (isExternal(pkg)) { 14937 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14938 return StorageManager.UUID_PRIMARY_PHYSICAL; 14939 } else { 14940 return pkg.volumeUuid; 14941 } 14942 } else { 14943 return StorageManager.UUID_PRIVATE_INTERNAL; 14944 } 14945 } 14946 14947 private VersionInfo getSettingsVersionForPackage(PackageParser.Package pkg) { 14948 if (isExternal(pkg)) { 14949 if (TextUtils.isEmpty(pkg.volumeUuid)) { 14950 return mSettings.getExternalVersion(); 14951 } else { 14952 return mSettings.findOrCreateVersion(pkg.volumeUuid); 14953 } 14954 } else { 14955 return mSettings.getInternalVersion(); 14956 } 14957 } 14958 14959 private void deleteTempPackageFiles() { 14960 final FilenameFilter filter = new FilenameFilter() { 14961 public boolean accept(File dir, String name) { 14962 return name.startsWith("vmdl") && name.endsWith(".tmp"); 14963 } 14964 }; 14965 for (File file : mDrmAppPrivateInstallDir.listFiles(filter)) { 14966 file.delete(); 14967 } 14968 } 14969 14970 @Override 14971 public void deletePackageAsUser(String packageName, IPackageDeleteObserver observer, int userId, 14972 int flags) { 14973 deletePackage(packageName, new LegacyPackageDeleteObserver(observer).getBinder(), userId, 14974 flags); 14975 } 14976 14977 @Override 14978 public void deletePackage(final String packageName, 14979 final IPackageDeleteObserver2 observer, final int userId, final int deleteFlags) { 14980 mContext.enforceCallingOrSelfPermission( 14981 android.Manifest.permission.DELETE_PACKAGES, null); 14982 Preconditions.checkNotNull(packageName); 14983 Preconditions.checkNotNull(observer); 14984 final int uid = Binder.getCallingUid(); 14985 final boolean deleteAllUsers = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0; 14986 final int[] users = deleteAllUsers ? sUserManager.getUserIds() : new int[]{ userId }; 14987 if (UserHandle.getUserId(uid) != userId || (deleteAllUsers && users.length > 1)) { 14988 mContext.enforceCallingOrSelfPermission( 14989 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, 14990 "deletePackage for user " + userId); 14991 } 14992 14993 if (isUserRestricted(userId, UserManager.DISALLOW_UNINSTALL_APPS)) { 14994 try { 14995 observer.onPackageDeleted(packageName, 14996 PackageManager.DELETE_FAILED_USER_RESTRICTED, null); 14997 } catch (RemoteException re) { 14998 } 14999 return; 15000 } 15001 15002 if (!deleteAllUsers && getBlockUninstallForUser(packageName, userId)) { 15003 try { 15004 observer.onPackageDeleted(packageName, 15005 PackageManager.DELETE_FAILED_OWNER_BLOCKED, null); 15006 } catch (RemoteException re) { 15007 } 15008 return; 15009 } 15010 15011 if (DEBUG_REMOVE) { 15012 Slog.d(TAG, "deletePackageAsUser: pkg=" + packageName + " user=" + userId 15013 + " deleteAllUsers: " + deleteAllUsers ); 15014 } 15015 // Queue up an async operation since the package deletion may take a little while. 15016 mHandler.post(new Runnable() { 15017 public void run() { 15018 mHandler.removeCallbacks(this); 15019 int returnCode; 15020 if (!deleteAllUsers) { 15021 returnCode = deletePackageX(packageName, userId, deleteFlags); 15022 } else { 15023 int[] blockUninstallUserIds = getBlockUninstallForUsers(packageName, users); 15024 // If nobody is blocking uninstall, proceed with delete for all users 15025 if (ArrayUtils.isEmpty(blockUninstallUserIds)) { 15026 returnCode = deletePackageX(packageName, userId, deleteFlags); 15027 } else { 15028 // Otherwise uninstall individually for users with blockUninstalls=false 15029 final int userFlags = deleteFlags & ~PackageManager.DELETE_ALL_USERS; 15030 for (int userId : users) { 15031 if (!ArrayUtils.contains(blockUninstallUserIds, userId)) { 15032 returnCode = deletePackageX(packageName, userId, userFlags); 15033 if (returnCode != PackageManager.DELETE_SUCCEEDED) { 15034 Slog.w(TAG, "Package delete failed for user " + userId 15035 + ", returnCode " + returnCode); 15036 } 15037 } 15038 } 15039 // The app has only been marked uninstalled for certain users. 15040 // We still need to report that delete was blocked 15041 returnCode = PackageManager.DELETE_FAILED_OWNER_BLOCKED; 15042 } 15043 } 15044 try { 15045 observer.onPackageDeleted(packageName, returnCode, null); 15046 } catch (RemoteException e) { 15047 Log.i(TAG, "Observer no longer exists."); 15048 } //end catch 15049 } //end run 15050 }); 15051 } 15052 15053 private int[] getBlockUninstallForUsers(String packageName, int[] userIds) { 15054 int[] result = EMPTY_INT_ARRAY; 15055 for (int userId : userIds) { 15056 if (getBlockUninstallForUser(packageName, userId)) { 15057 result = ArrayUtils.appendInt(result, userId); 15058 } 15059 } 15060 return result; 15061 } 15062 15063 @Override 15064 public boolean isPackageDeviceAdminOnAnyUser(String packageName) { 15065 return isPackageDeviceAdmin(packageName, UserHandle.USER_ALL); 15066 } 15067 15068 private boolean isPackageDeviceAdmin(String packageName, int userId) { 15069 IDevicePolicyManager dpm = IDevicePolicyManager.Stub.asInterface( 15070 ServiceManager.getService(Context.DEVICE_POLICY_SERVICE)); 15071 try { 15072 if (dpm != null) { 15073 final ComponentName deviceOwnerComponentName = dpm.getDeviceOwnerComponent( 15074 /* callingUserOnly =*/ false); 15075 final String deviceOwnerPackageName = deviceOwnerComponentName == null ? null 15076 : deviceOwnerComponentName.getPackageName(); 15077 // Does the package contains the device owner? 15078 // TODO Do we have to do it even if userId != UserHandle.USER_ALL? Otherwise, 15079 // this check is probably not needed, since DO should be registered as a device 15080 // admin on some user too. (Original bug for this: b/17657954) 15081 if (packageName.equals(deviceOwnerPackageName)) { 15082 return true; 15083 } 15084 // Does it contain a device admin for any user? 15085 int[] users; 15086 if (userId == UserHandle.USER_ALL) { 15087 users = sUserManager.getUserIds(); 15088 } else { 15089 users = new int[]{userId}; 15090 } 15091 for (int i = 0; i < users.length; ++i) { 15092 if (dpm.packageHasActiveAdmins(packageName, users[i])) { 15093 return true; 15094 } 15095 } 15096 } 15097 } catch (RemoteException e) { 15098 } 15099 return false; 15100 } 15101 15102 private boolean shouldKeepUninstalledPackageLPr(String packageName) { 15103 return mKeepUninstalledPackages != null && mKeepUninstalledPackages.contains(packageName); 15104 } 15105 15106 /** 15107 * This method is an internal method that could be get invoked either 15108 * to delete an installed package or to clean up a failed installation. 15109 * After deleting an installed package, a broadcast is sent to notify any 15110 * listeners that the package has been removed. For cleaning up a failed 15111 * installation, the broadcast is not necessary since the package's 15112 * installation wouldn't have sent the initial broadcast either 15113 * The key steps in deleting a package are 15114 * deleting the package information in internal structures like mPackages, 15115 * deleting the packages base directories through installd 15116 * updating mSettings to reflect current status 15117 * persisting settings for later use 15118 * sending a broadcast if necessary 15119 */ 15120 private int deletePackageX(String packageName, int userId, int deleteFlags) { 15121 final PackageRemovedInfo info = new PackageRemovedInfo(); 15122 final boolean res; 15123 15124 final UserHandle removeForUser = (deleteFlags & PackageManager.DELETE_ALL_USERS) != 0 15125 ? UserHandle.ALL : new UserHandle(userId); 15126 15127 if (isPackageDeviceAdmin(packageName, removeForUser.getIdentifier())) { 15128 Slog.w(TAG, "Not removing package " + packageName + ": has active device admin"); 15129 return PackageManager.DELETE_FAILED_DEVICE_POLICY_MANAGER; 15130 } 15131 15132 PackageSetting uninstalledPs = null; 15133 15134 // for the uninstall-updates case and restricted profiles, remember the per- 15135 // user handle installed state 15136 int[] allUsers; 15137 synchronized (mPackages) { 15138 uninstalledPs = mSettings.mPackages.get(packageName); 15139 if (uninstalledPs == null) { 15140 Slog.w(TAG, "Not removing non-existent package " + packageName); 15141 return PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15142 } 15143 allUsers = sUserManager.getUserIds(); 15144 info.origUsers = uninstalledPs.queryInstalledUsers(allUsers, true); 15145 } 15146 15147 synchronized (mInstallLock) { 15148 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageX: pkg=" + packageName + " user=" + userId); 15149 try (PackageFreezer freezer = freezePackageForDelete(packageName, deleteFlags, 15150 "deletePackageX")) { 15151 res = deletePackageLIF(packageName, removeForUser, true, allUsers, 15152 deleteFlags | REMOVE_CHATTY, info, true, null); 15153 } 15154 synchronized (mPackages) { 15155 if (res) { 15156 mEphemeralApplicationRegistry.onPackageUninstalledLPw(uninstalledPs.pkg); 15157 } 15158 } 15159 } 15160 15161 if (res) { 15162 final boolean killApp = (deleteFlags & PackageManager.DELETE_DONT_KILL_APP) == 0; 15163 info.sendPackageRemovedBroadcasts(killApp); 15164 info.sendSystemPackageUpdatedBroadcasts(); 15165 info.sendSystemPackageAppearedBroadcasts(); 15166 } 15167 // Force a gc here. 15168 Runtime.getRuntime().gc(); 15169 // Delete the resources here after sending the broadcast to let 15170 // other processes clean up before deleting resources. 15171 if (info.args != null) { 15172 synchronized (mInstallLock) { 15173 info.args.doPostDeleteLI(true); 15174 } 15175 } 15176 15177 return res ? PackageManager.DELETE_SUCCEEDED : PackageManager.DELETE_FAILED_INTERNAL_ERROR; 15178 } 15179 15180 class PackageRemovedInfo { 15181 String removedPackage; 15182 int uid = -1; 15183 int removedAppId = -1; 15184 int[] origUsers; 15185 int[] removedUsers = null; 15186 boolean isRemovedPackageSystemUpdate = false; 15187 boolean isUpdate; 15188 boolean dataRemoved; 15189 boolean removedForAllUsers; 15190 // Clean up resources deleted packages. 15191 InstallArgs args = null; 15192 ArrayMap<String, PackageRemovedInfo> removedChildPackages; 15193 ArrayMap<String, PackageInstalledInfo> appearedChildPackages; 15194 15195 void sendPackageRemovedBroadcasts(boolean killApp) { 15196 sendPackageRemovedBroadcastInternal(killApp); 15197 final int childCount = removedChildPackages != null ? removedChildPackages.size() : 0; 15198 for (int i = 0; i < childCount; i++) { 15199 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15200 childInfo.sendPackageRemovedBroadcastInternal(killApp); 15201 } 15202 } 15203 15204 void sendSystemPackageUpdatedBroadcasts() { 15205 if (isRemovedPackageSystemUpdate) { 15206 sendSystemPackageUpdatedBroadcastsInternal(); 15207 final int childCount = (removedChildPackages != null) 15208 ? removedChildPackages.size() : 0; 15209 for (int i = 0; i < childCount; i++) { 15210 PackageRemovedInfo childInfo = removedChildPackages.valueAt(i); 15211 if (childInfo.isRemovedPackageSystemUpdate) { 15212 childInfo.sendSystemPackageUpdatedBroadcastsInternal(); 15213 } 15214 } 15215 } 15216 } 15217 15218 void sendSystemPackageAppearedBroadcasts() { 15219 final int packageCount = (appearedChildPackages != null) 15220 ? appearedChildPackages.size() : 0; 15221 for (int i = 0; i < packageCount; i++) { 15222 PackageInstalledInfo installedInfo = appearedChildPackages.valueAt(i); 15223 for (int userId : installedInfo.newUsers) { 15224 sendPackageAddedForUser(installedInfo.name, true, 15225 UserHandle.getAppId(installedInfo.uid), userId); 15226 } 15227 } 15228 } 15229 15230 private void sendSystemPackageUpdatedBroadcastsInternal() { 15231 Bundle extras = new Bundle(2); 15232 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15233 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15234 sendPackageBroadcast(Intent.ACTION_PACKAGE_ADDED, removedPackage, 15235 extras, 0, null, null, null); 15236 sendPackageBroadcast(Intent.ACTION_PACKAGE_REPLACED, removedPackage, 15237 extras, 0, null, null, null); 15238 sendPackageBroadcast(Intent.ACTION_MY_PACKAGE_REPLACED, null, 15239 null, 0, removedPackage, null, null); 15240 } 15241 15242 private void sendPackageRemovedBroadcastInternal(boolean killApp) { 15243 Bundle extras = new Bundle(2); 15244 extras.putInt(Intent.EXTRA_UID, removedAppId >= 0 ? removedAppId : uid); 15245 extras.putBoolean(Intent.EXTRA_DATA_REMOVED, dataRemoved); 15246 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, !killApp); 15247 if (isUpdate || isRemovedPackageSystemUpdate) { 15248 extras.putBoolean(Intent.EXTRA_REPLACING, true); 15249 } 15250 extras.putBoolean(Intent.EXTRA_REMOVED_FOR_ALL_USERS, removedForAllUsers); 15251 if (removedPackage != null) { 15252 sendPackageBroadcast(Intent.ACTION_PACKAGE_REMOVED, removedPackage, 15253 extras, 0, null, null, removedUsers); 15254 if (dataRemoved && !isRemovedPackageSystemUpdate) { 15255 sendPackageBroadcast(Intent.ACTION_PACKAGE_FULLY_REMOVED, 15256 removedPackage, extras, 0, null, null, removedUsers); 15257 } 15258 } 15259 if (removedAppId >= 0) { 15260 sendPackageBroadcast(Intent.ACTION_UID_REMOVED, null, extras, 0, null, null, 15261 removedUsers); 15262 } 15263 } 15264 } 15265 15266 /* 15267 * This method deletes the package from internal data structures. If the DONT_DELETE_DATA 15268 * flag is not set, the data directory is removed as well. 15269 * make sure this flag is set for partially installed apps. If not its meaningless to 15270 * delete a partially installed application. 15271 */ 15272 private void removePackageDataLIF(PackageSetting ps, int[] allUserHandles, 15273 PackageRemovedInfo outInfo, int flags, boolean writeSettings) { 15274 String packageName = ps.name; 15275 if (DEBUG_REMOVE) Slog.d(TAG, "removePackageDataLI: " + ps); 15276 // Retrieve object to delete permissions for shared user later on 15277 final PackageParser.Package deletedPkg; 15278 final PackageSetting deletedPs; 15279 // reader 15280 synchronized (mPackages) { 15281 deletedPkg = mPackages.get(packageName); 15282 deletedPs = mSettings.mPackages.get(packageName); 15283 if (outInfo != null) { 15284 outInfo.removedPackage = packageName; 15285 outInfo.removedUsers = deletedPs != null 15286 ? deletedPs.queryInstalledUsers(sUserManager.getUserIds(), true) 15287 : null; 15288 } 15289 } 15290 15291 removePackageLI(ps, (flags & REMOVE_CHATTY) != 0); 15292 15293 if ((flags & PackageManager.DELETE_KEEP_DATA) == 0) { 15294 destroyAppDataLIF(deletedPkg, UserHandle.USER_ALL, 15295 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15296 destroyAppProfilesLIF(deletedPkg); 15297 if (outInfo != null) { 15298 outInfo.dataRemoved = true; 15299 } 15300 schedulePackageCleaning(packageName, UserHandle.USER_ALL, true); 15301 } 15302 15303 // writer 15304 synchronized (mPackages) { 15305 if (deletedPs != null) { 15306 if ((flags&PackageManager.DELETE_KEEP_DATA) == 0) { 15307 clearIntentFilterVerificationsLPw(deletedPs.name, UserHandle.USER_ALL); 15308 clearDefaultBrowserIfNeeded(packageName); 15309 if (outInfo != null) { 15310 mSettings.mKeySetManagerService.removeAppKeySetDataLPw(packageName); 15311 outInfo.removedAppId = mSettings.removePackageLPw(packageName); 15312 } 15313 updatePermissionsLPw(deletedPs.name, null, 0); 15314 if (deletedPs.sharedUser != null) { 15315 // Remove permissions associated with package. Since runtime 15316 // permissions are per user we have to kill the removed package 15317 // or packages running under the shared user of the removed 15318 // package if revoking the permissions requested only by the removed 15319 // package is successful and this causes a change in gids. 15320 for (int userId : UserManagerService.getInstance().getUserIds()) { 15321 final int userIdToKill = mSettings.updateSharedUserPermsLPw(deletedPs, 15322 userId); 15323 if (userIdToKill == UserHandle.USER_ALL 15324 || userIdToKill >= UserHandle.USER_SYSTEM) { 15325 // If gids changed for this user, kill all affected packages. 15326 mHandler.post(new Runnable() { 15327 @Override 15328 public void run() { 15329 // This has to happen with no lock held. 15330 killApplication(deletedPs.name, deletedPs.appId, 15331 KILL_APP_REASON_GIDS_CHANGED); 15332 } 15333 }); 15334 break; 15335 } 15336 } 15337 } 15338 clearPackagePreferredActivitiesLPw(deletedPs.name, UserHandle.USER_ALL); 15339 } 15340 // make sure to preserve per-user disabled state if this removal was just 15341 // a downgrade of a system app to the factory package 15342 if (allUserHandles != null && outInfo != null && outInfo.origUsers != null) { 15343 if (DEBUG_REMOVE) { 15344 Slog.d(TAG, "Propagating install state across downgrade"); 15345 } 15346 for (int userId : allUserHandles) { 15347 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15348 if (DEBUG_REMOVE) { 15349 Slog.d(TAG, " user " + userId + " => " + installed); 15350 } 15351 ps.setInstalled(installed, userId); 15352 } 15353 } 15354 } 15355 // can downgrade to reader 15356 if (writeSettings) { 15357 // Save settings now 15358 mSettings.writeLPr(); 15359 } 15360 } 15361 if (outInfo != null) { 15362 // A user ID was deleted here. Go through all users and remove it 15363 // from KeyStore. 15364 removeKeystoreDataIfNeeded(UserHandle.USER_ALL, outInfo.removedAppId); 15365 } 15366 } 15367 15368 static boolean locationIsPrivileged(File path) { 15369 try { 15370 final String privilegedAppDir = new File(Environment.getRootDirectory(), "priv-app") 15371 .getCanonicalPath(); 15372 return path.getCanonicalPath().startsWith(privilegedAppDir); 15373 } catch (IOException e) { 15374 Slog.e(TAG, "Unable to access code path " + path); 15375 } 15376 return false; 15377 } 15378 15379 /* 15380 * Tries to delete system package. 15381 */ 15382 private boolean deleteSystemPackageLIF(PackageParser.Package deletedPkg, 15383 PackageSetting deletedPs, int[] allUserHandles, int flags, PackageRemovedInfo outInfo, 15384 boolean writeSettings) { 15385 if (deletedPs.parentPackageName != null) { 15386 Slog.w(TAG, "Attempt to delete child system package " + deletedPkg.packageName); 15387 return false; 15388 } 15389 15390 final boolean applyUserRestrictions 15391 = (allUserHandles != null) && (outInfo.origUsers != null); 15392 final PackageSetting disabledPs; 15393 // Confirm if the system package has been updated 15394 // An updated system app can be deleted. This will also have to restore 15395 // the system pkg from system partition 15396 // reader 15397 synchronized (mPackages) { 15398 disabledPs = mSettings.getDisabledSystemPkgLPr(deletedPs.name); 15399 } 15400 15401 if (DEBUG_REMOVE) Slog.d(TAG, "deleteSystemPackageLI: newPs=" + deletedPkg.packageName 15402 + " disabledPs=" + disabledPs); 15403 15404 if (disabledPs == null) { 15405 Slog.w(TAG, "Attempt to delete unknown system package "+ deletedPkg.packageName); 15406 return false; 15407 } else if (DEBUG_REMOVE) { 15408 Slog.d(TAG, "Deleting system pkg from data partition"); 15409 } 15410 15411 if (DEBUG_REMOVE) { 15412 if (applyUserRestrictions) { 15413 Slog.d(TAG, "Remembering install states:"); 15414 for (int userId : allUserHandles) { 15415 final boolean finstalled = ArrayUtils.contains(outInfo.origUsers, userId); 15416 Slog.d(TAG, " u=" + userId + " inst=" + finstalled); 15417 } 15418 } 15419 } 15420 15421 // Delete the updated package 15422 outInfo.isRemovedPackageSystemUpdate = true; 15423 if (outInfo.removedChildPackages != null) { 15424 final int childCount = (deletedPs.childPackageNames != null) 15425 ? deletedPs.childPackageNames.size() : 0; 15426 for (int i = 0; i < childCount; i++) { 15427 String childPackageName = deletedPs.childPackageNames.get(i); 15428 if (disabledPs.childPackageNames != null && disabledPs.childPackageNames 15429 .contains(childPackageName)) { 15430 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15431 childPackageName); 15432 if (childInfo != null) { 15433 childInfo.isRemovedPackageSystemUpdate = true; 15434 } 15435 } 15436 } 15437 } 15438 15439 if (disabledPs.versionCode < deletedPs.versionCode) { 15440 // Delete data for downgrades 15441 flags &= ~PackageManager.DELETE_KEEP_DATA; 15442 } else { 15443 // Preserve data by setting flag 15444 flags |= PackageManager.DELETE_KEEP_DATA; 15445 } 15446 15447 boolean ret = deleteInstalledPackageLIF(deletedPs, true, flags, allUserHandles, 15448 outInfo, writeSettings, disabledPs.pkg); 15449 if (!ret) { 15450 return false; 15451 } 15452 15453 // writer 15454 synchronized (mPackages) { 15455 // Reinstate the old system package 15456 enableSystemPackageLPw(disabledPs.pkg); 15457 // Remove any native libraries from the upgraded package. 15458 removeNativeBinariesLI(deletedPs); 15459 } 15460 15461 // Install the system package 15462 if (DEBUG_REMOVE) Slog.d(TAG, "Re-installing system package: " + disabledPs); 15463 int parseFlags = mDefParseFlags 15464 | PackageParser.PARSE_MUST_BE_APK 15465 | PackageParser.PARSE_IS_SYSTEM 15466 | PackageParser.PARSE_IS_SYSTEM_DIR; 15467 if (locationIsPrivileged(disabledPs.codePath)) { 15468 parseFlags |= PackageParser.PARSE_IS_PRIVILEGED; 15469 } 15470 15471 final PackageParser.Package newPkg; 15472 try { 15473 newPkg = scanPackageTracedLI(disabledPs.codePath, parseFlags, SCAN_NO_PATHS, 0, null); 15474 } catch (PackageManagerException e) { 15475 Slog.w(TAG, "Failed to restore system package:" + deletedPkg.packageName + ": " 15476 + e.getMessage()); 15477 return false; 15478 } 15479 15480 prepareAppDataAfterInstallLIF(newPkg); 15481 15482 // writer 15483 synchronized (mPackages) { 15484 PackageSetting ps = mSettings.mPackages.get(newPkg.packageName); 15485 15486 // Propagate the permissions state as we do not want to drop on the floor 15487 // runtime permissions. The update permissions method below will take 15488 // care of removing obsolete permissions and grant install permissions. 15489 ps.getPermissionsState().copyFrom(deletedPs.getPermissionsState()); 15490 updatePermissionsLPw(newPkg.packageName, newPkg, 15491 UPDATE_PERMISSIONS_ALL | UPDATE_PERMISSIONS_REPLACE_PKG); 15492 15493 if (applyUserRestrictions) { 15494 if (DEBUG_REMOVE) { 15495 Slog.d(TAG, "Propagating install state across reinstall"); 15496 } 15497 for (int userId : allUserHandles) { 15498 final boolean installed = ArrayUtils.contains(outInfo.origUsers, userId); 15499 if (DEBUG_REMOVE) { 15500 Slog.d(TAG, " user " + userId + " => " + installed); 15501 } 15502 ps.setInstalled(installed, userId); 15503 15504 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 15505 } 15506 // Regardless of writeSettings we need to ensure that this restriction 15507 // state propagation is persisted 15508 mSettings.writeAllUsersPackageRestrictionsLPr(); 15509 } 15510 // can downgrade to reader here 15511 if (writeSettings) { 15512 mSettings.writeLPr(); 15513 } 15514 } 15515 return true; 15516 } 15517 15518 private boolean deleteInstalledPackageLIF(PackageSetting ps, 15519 boolean deleteCodeAndResources, int flags, int[] allUserHandles, 15520 PackageRemovedInfo outInfo, boolean writeSettings, 15521 PackageParser.Package replacingPackage) { 15522 synchronized (mPackages) { 15523 if (outInfo != null) { 15524 outInfo.uid = ps.appId; 15525 } 15526 15527 if (outInfo != null && outInfo.removedChildPackages != null) { 15528 final int childCount = (ps.childPackageNames != null) 15529 ? ps.childPackageNames.size() : 0; 15530 for (int i = 0; i < childCount; i++) { 15531 String childPackageName = ps.childPackageNames.get(i); 15532 PackageSetting childPs = mSettings.mPackages.get(childPackageName); 15533 if (childPs == null) { 15534 return false; 15535 } 15536 PackageRemovedInfo childInfo = outInfo.removedChildPackages.get( 15537 childPackageName); 15538 if (childInfo != null) { 15539 childInfo.uid = childPs.appId; 15540 } 15541 } 15542 } 15543 } 15544 15545 // Delete package data from internal structures and also remove data if flag is set 15546 removePackageDataLIF(ps, allUserHandles, outInfo, flags, writeSettings); 15547 15548 // Delete the child packages data 15549 final int childCount = (ps.childPackageNames != null) ? ps.childPackageNames.size() : 0; 15550 for (int i = 0; i < childCount; i++) { 15551 PackageSetting childPs; 15552 synchronized (mPackages) { 15553 childPs = mSettings.peekPackageLPr(ps.childPackageNames.get(i)); 15554 } 15555 if (childPs != null) { 15556 PackageRemovedInfo childOutInfo = (outInfo != null 15557 && outInfo.removedChildPackages != null) 15558 ? outInfo.removedChildPackages.get(childPs.name) : null; 15559 final int deleteFlags = (flags & DELETE_KEEP_DATA) != 0 15560 && (replacingPackage != null 15561 && !replacingPackage.hasChildPackage(childPs.name)) 15562 ? flags & ~DELETE_KEEP_DATA : flags; 15563 removePackageDataLIF(childPs, allUserHandles, childOutInfo, 15564 deleteFlags, writeSettings); 15565 } 15566 } 15567 15568 // Delete application code and resources only for parent packages 15569 if (ps.parentPackageName == null) { 15570 if (deleteCodeAndResources && (outInfo != null)) { 15571 outInfo.args = createInstallArgsForExisting(packageFlagsToInstallFlags(ps), 15572 ps.codePathString, ps.resourcePathString, getAppDexInstructionSets(ps)); 15573 if (DEBUG_SD_INSTALL) Slog.i(TAG, "args=" + outInfo.args); 15574 } 15575 } 15576 15577 return true; 15578 } 15579 15580 @Override 15581 public boolean setBlockUninstallForUser(String packageName, boolean blockUninstall, 15582 int userId) { 15583 mContext.enforceCallingOrSelfPermission( 15584 android.Manifest.permission.DELETE_PACKAGES, null); 15585 synchronized (mPackages) { 15586 PackageSetting ps = mSettings.mPackages.get(packageName); 15587 if (ps == null) { 15588 Log.i(TAG, "Package doesn't exist in set block uninstall " + packageName); 15589 return false; 15590 } 15591 if (!ps.getInstalled(userId)) { 15592 // Can't block uninstall for an app that is not installed or enabled. 15593 Log.i(TAG, "Package not installed in set block uninstall " + packageName); 15594 return false; 15595 } 15596 ps.setBlockUninstall(blockUninstall, userId); 15597 mSettings.writePackageRestrictionsLPr(userId); 15598 } 15599 return true; 15600 } 15601 15602 @Override 15603 public boolean getBlockUninstallForUser(String packageName, int userId) { 15604 synchronized (mPackages) { 15605 PackageSetting ps = mSettings.mPackages.get(packageName); 15606 if (ps == null) { 15607 Log.i(TAG, "Package doesn't exist in get block uninstall " + packageName); 15608 return false; 15609 } 15610 return ps.getBlockUninstall(userId); 15611 } 15612 } 15613 15614 @Override 15615 public boolean setRequiredForSystemUser(String packageName, boolean systemUserApp) { 15616 int callingUid = Binder.getCallingUid(); 15617 if (callingUid != Process.SYSTEM_UID && callingUid != Process.ROOT_UID) { 15618 throw new SecurityException( 15619 "setRequiredForSystemUser can only be run by the system or root"); 15620 } 15621 synchronized (mPackages) { 15622 PackageSetting ps = mSettings.mPackages.get(packageName); 15623 if (ps == null) { 15624 Log.w(TAG, "Package doesn't exist: " + packageName); 15625 return false; 15626 } 15627 if (systemUserApp) { 15628 ps.pkgPrivateFlags |= ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15629 } else { 15630 ps.pkgPrivateFlags &= ~ApplicationInfo.PRIVATE_FLAG_REQUIRED_FOR_SYSTEM_USER; 15631 } 15632 mSettings.writeLPr(); 15633 } 15634 return true; 15635 } 15636 15637 /* 15638 * This method handles package deletion in general 15639 */ 15640 private boolean deletePackageLIF(String packageName, UserHandle user, 15641 boolean deleteCodeAndResources, int[] allUserHandles, int flags, 15642 PackageRemovedInfo outInfo, boolean writeSettings, 15643 PackageParser.Package replacingPackage) { 15644 if (packageName == null) { 15645 Slog.w(TAG, "Attempt to delete null packageName."); 15646 return false; 15647 } 15648 15649 if (DEBUG_REMOVE) Slog.d(TAG, "deletePackageLI: " + packageName + " user " + user); 15650 15651 PackageSetting ps; 15652 15653 synchronized (mPackages) { 15654 ps = mSettings.mPackages.get(packageName); 15655 if (ps == null) { 15656 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 15657 return false; 15658 } 15659 15660 if (ps.parentPackageName != null && (!isSystemApp(ps) 15661 || (flags & PackageManager.DELETE_SYSTEM_APP) != 0)) { 15662 if (DEBUG_REMOVE) { 15663 Slog.d(TAG, "Uninstalled child package:" + packageName + " for user:" 15664 + ((user == null) ? UserHandle.USER_ALL : user)); 15665 } 15666 final int removedUserId = (user != null) ? user.getIdentifier() 15667 : UserHandle.USER_ALL; 15668 if (!clearPackageStateForUserLIF(ps, removedUserId, outInfo)) { 15669 return false; 15670 } 15671 markPackageUninstalledForUserLPw(ps, user); 15672 scheduleWritePackageRestrictionsLocked(user); 15673 return true; 15674 } 15675 } 15676 15677 if (((!isSystemApp(ps) || (flags&PackageManager.DELETE_SYSTEM_APP) != 0) && user != null 15678 && user.getIdentifier() != UserHandle.USER_ALL)) { 15679 // The caller is asking that the package only be deleted for a single 15680 // user. To do this, we just mark its uninstalled state and delete 15681 // its data. If this is a system app, we only allow this to happen if 15682 // they have set the special DELETE_SYSTEM_APP which requests different 15683 // semantics than normal for uninstalling system apps. 15684 markPackageUninstalledForUserLPw(ps, user); 15685 15686 if (!isSystemApp(ps)) { 15687 // Do not uninstall the APK if an app should be cached 15688 boolean keepUninstalledPackage = shouldKeepUninstalledPackageLPr(packageName); 15689 if (ps.isAnyInstalled(sUserManager.getUserIds()) || keepUninstalledPackage) { 15690 // Other user still have this package installed, so all 15691 // we need to do is clear this user's data and save that 15692 // it is uninstalled. 15693 if (DEBUG_REMOVE) Slog.d(TAG, "Still installed by other users"); 15694 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15695 return false; 15696 } 15697 scheduleWritePackageRestrictionsLocked(user); 15698 return true; 15699 } else { 15700 // We need to set it back to 'installed' so the uninstall 15701 // broadcasts will be sent correctly. 15702 if (DEBUG_REMOVE) Slog.d(TAG, "Not installed by other users, full delete"); 15703 ps.setInstalled(true, user.getIdentifier()); 15704 } 15705 } else { 15706 // This is a system app, so we assume that the 15707 // other users still have this package installed, so all 15708 // we need to do is clear this user's data and save that 15709 // it is uninstalled. 15710 if (DEBUG_REMOVE) Slog.d(TAG, "Deleting system app"); 15711 if (!clearPackageStateForUserLIF(ps, user.getIdentifier(), outInfo)) { 15712 return false; 15713 } 15714 scheduleWritePackageRestrictionsLocked(user); 15715 return true; 15716 } 15717 } 15718 15719 // If we are deleting a composite package for all users, keep track 15720 // of result for each child. 15721 if (ps.childPackageNames != null && outInfo != null) { 15722 synchronized (mPackages) { 15723 final int childCount = ps.childPackageNames.size(); 15724 outInfo.removedChildPackages = new ArrayMap<>(childCount); 15725 for (int i = 0; i < childCount; i++) { 15726 String childPackageName = ps.childPackageNames.get(i); 15727 PackageRemovedInfo childInfo = new PackageRemovedInfo(); 15728 childInfo.removedPackage = childPackageName; 15729 outInfo.removedChildPackages.put(childPackageName, childInfo); 15730 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15731 if (childPs != null) { 15732 childInfo.origUsers = childPs.queryInstalledUsers(allUserHandles, true); 15733 } 15734 } 15735 } 15736 } 15737 15738 boolean ret = false; 15739 if (isSystemApp(ps)) { 15740 if (DEBUG_REMOVE) Slog.d(TAG, "Removing system package: " + ps.name); 15741 // When an updated system application is deleted we delete the existing resources 15742 // as well and fall back to existing code in system partition 15743 ret = deleteSystemPackageLIF(ps.pkg, ps, allUserHandles, flags, outInfo, writeSettings); 15744 } else { 15745 if (DEBUG_REMOVE) Slog.d(TAG, "Removing non-system package: " + ps.name); 15746 ret = deleteInstalledPackageLIF(ps, deleteCodeAndResources, flags, allUserHandles, 15747 outInfo, writeSettings, replacingPackage); 15748 } 15749 15750 // Take a note whether we deleted the package for all users 15751 if (outInfo != null) { 15752 outInfo.removedForAllUsers = mPackages.get(ps.name) == null; 15753 if (outInfo.removedChildPackages != null) { 15754 synchronized (mPackages) { 15755 final int childCount = outInfo.removedChildPackages.size(); 15756 for (int i = 0; i < childCount; i++) { 15757 PackageRemovedInfo childInfo = outInfo.removedChildPackages.valueAt(i); 15758 if (childInfo != null) { 15759 childInfo.removedForAllUsers = mPackages.get( 15760 childInfo.removedPackage) == null; 15761 } 15762 } 15763 } 15764 } 15765 // If we uninstalled an update to a system app there may be some 15766 // child packages that appeared as they are declared in the system 15767 // app but were not declared in the update. 15768 if (isSystemApp(ps)) { 15769 synchronized (mPackages) { 15770 PackageSetting updatedPs = mSettings.peekPackageLPr(ps.name); 15771 final int childCount = (updatedPs.childPackageNames != null) 15772 ? updatedPs.childPackageNames.size() : 0; 15773 for (int i = 0; i < childCount; i++) { 15774 String childPackageName = updatedPs.childPackageNames.get(i); 15775 if (outInfo.removedChildPackages == null 15776 || outInfo.removedChildPackages.indexOfKey(childPackageName) < 0) { 15777 PackageSetting childPs = mSettings.peekPackageLPr(childPackageName); 15778 if (childPs == null) { 15779 continue; 15780 } 15781 PackageInstalledInfo installRes = new PackageInstalledInfo(); 15782 installRes.name = childPackageName; 15783 installRes.newUsers = childPs.queryInstalledUsers(allUserHandles, true); 15784 installRes.pkg = mPackages.get(childPackageName); 15785 installRes.uid = childPs.pkg.applicationInfo.uid; 15786 if (outInfo.appearedChildPackages == null) { 15787 outInfo.appearedChildPackages = new ArrayMap<>(); 15788 } 15789 outInfo.appearedChildPackages.put(childPackageName, installRes); 15790 } 15791 } 15792 } 15793 } 15794 } 15795 15796 return ret; 15797 } 15798 15799 private void markPackageUninstalledForUserLPw(PackageSetting ps, UserHandle user) { 15800 final int[] userIds = (user == null || user.getIdentifier() == UserHandle.USER_ALL) 15801 ? sUserManager.getUserIds() : new int[] {user.getIdentifier()}; 15802 for (int nextUserId : userIds) { 15803 if (DEBUG_REMOVE) { 15804 Slog.d(TAG, "Marking package:" + ps.name + " uninstalled for user:" + nextUserId); 15805 } 15806 ps.setUserState(nextUserId, 0, COMPONENT_ENABLED_STATE_DEFAULT, 15807 false /*installed*/, true /*stopped*/, true /*notLaunched*/, 15808 false /*hidden*/, false /*suspended*/, null, null, null, 15809 false /*blockUninstall*/, 15810 ps.readUserState(nextUserId).domainVerificationStatus, 0); 15811 } 15812 } 15813 15814 private boolean clearPackageStateForUserLIF(PackageSetting ps, int userId, 15815 PackageRemovedInfo outInfo) { 15816 final PackageParser.Package pkg; 15817 synchronized (mPackages) { 15818 pkg = mPackages.get(ps.name); 15819 } 15820 15821 final int[] userIds = (userId == UserHandle.USER_ALL) ? sUserManager.getUserIds() 15822 : new int[] {userId}; 15823 for (int nextUserId : userIds) { 15824 if (DEBUG_REMOVE) { 15825 Slog.d(TAG, "Updating package:" + ps.name + " install state for user:" 15826 + nextUserId); 15827 } 15828 15829 destroyAppDataLIF(pkg, userId, 15830 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 15831 removeKeystoreDataIfNeeded(nextUserId, ps.appId); 15832 schedulePackageCleaning(ps.name, nextUserId, false); 15833 synchronized (mPackages) { 15834 if (clearPackagePreferredActivitiesLPw(ps.name, nextUserId)) { 15835 scheduleWritePackageRestrictionsLocked(nextUserId); 15836 } 15837 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, nextUserId); 15838 } 15839 } 15840 15841 if (outInfo != null) { 15842 outInfo.removedPackage = ps.name; 15843 outInfo.removedAppId = ps.appId; 15844 outInfo.removedUsers = userIds; 15845 } 15846 15847 return true; 15848 } 15849 15850 private final class ClearStorageConnection implements ServiceConnection { 15851 IMediaContainerService mContainerService; 15852 15853 @Override 15854 public void onServiceConnected(ComponentName name, IBinder service) { 15855 synchronized (this) { 15856 mContainerService = IMediaContainerService.Stub.asInterface(service); 15857 notifyAll(); 15858 } 15859 } 15860 15861 @Override 15862 public void onServiceDisconnected(ComponentName name) { 15863 } 15864 } 15865 15866 private void clearExternalStorageDataSync(String packageName, int userId, boolean allData) { 15867 if (DEFAULT_CONTAINER_PACKAGE.equals(packageName)) return; 15868 15869 final boolean mounted; 15870 if (Environment.isExternalStorageEmulated()) { 15871 mounted = true; 15872 } else { 15873 final String status = Environment.getExternalStorageState(); 15874 15875 mounted = status.equals(Environment.MEDIA_MOUNTED) 15876 || status.equals(Environment.MEDIA_MOUNTED_READ_ONLY); 15877 } 15878 15879 if (!mounted) { 15880 return; 15881 } 15882 15883 final Intent containerIntent = new Intent().setComponent(DEFAULT_CONTAINER_COMPONENT); 15884 int[] users; 15885 if (userId == UserHandle.USER_ALL) { 15886 users = sUserManager.getUserIds(); 15887 } else { 15888 users = new int[] { userId }; 15889 } 15890 final ClearStorageConnection conn = new ClearStorageConnection(); 15891 if (mContext.bindServiceAsUser( 15892 containerIntent, conn, Context.BIND_AUTO_CREATE, UserHandle.SYSTEM)) { 15893 try { 15894 for (int curUser : users) { 15895 long timeout = SystemClock.uptimeMillis() + 5000; 15896 synchronized (conn) { 15897 long now = SystemClock.uptimeMillis(); 15898 while (conn.mContainerService == null && now < timeout) { 15899 try { 15900 conn.wait(timeout - now); 15901 } catch (InterruptedException e) { 15902 } 15903 } 15904 } 15905 if (conn.mContainerService == null) { 15906 return; 15907 } 15908 15909 final UserEnvironment userEnv = new UserEnvironment(curUser); 15910 clearDirectory(conn.mContainerService, 15911 userEnv.buildExternalStorageAppCacheDirs(packageName)); 15912 if (allData) { 15913 clearDirectory(conn.mContainerService, 15914 userEnv.buildExternalStorageAppDataDirs(packageName)); 15915 clearDirectory(conn.mContainerService, 15916 userEnv.buildExternalStorageAppMediaDirs(packageName)); 15917 } 15918 } 15919 } finally { 15920 mContext.unbindService(conn); 15921 } 15922 } 15923 } 15924 15925 @Override 15926 public void clearApplicationProfileData(String packageName) { 15927 enforceSystemOrRoot("Only the system can clear all profile data"); 15928 15929 final PackageParser.Package pkg; 15930 synchronized (mPackages) { 15931 pkg = mPackages.get(packageName); 15932 } 15933 15934 try (PackageFreezer freezer = freezePackage(packageName, "clearApplicationProfileData")) { 15935 synchronized (mInstallLock) { 15936 clearAppProfilesLIF(pkg); 15937 } 15938 } 15939 } 15940 15941 @Override 15942 public void clearApplicationUserData(final String packageName, 15943 final IPackageDataObserver observer, final int userId) { 15944 mContext.enforceCallingOrSelfPermission( 15945 android.Manifest.permission.CLEAR_APP_USER_DATA, null); 15946 15947 enforceCrossUserPermission(Binder.getCallingUid(), userId, 15948 true /* requireFullPermission */, false /* checkShell */, "clear application data"); 15949 15950 final DevicePolicyManagerInternal dpmi = LocalServices 15951 .getService(DevicePolicyManagerInternal.class); 15952 if (dpmi != null && dpmi.hasDeviceOwnerOrProfileOwner(packageName, userId)) { 15953 throw new SecurityException("Cannot clear data for a device owner or a profile owner"); 15954 } 15955 // Queue up an async operation since the package deletion may take a little while. 15956 mHandler.post(new Runnable() { 15957 public void run() { 15958 mHandler.removeCallbacks(this); 15959 final boolean succeeded; 15960 try (PackageFreezer freezer = freezePackage(packageName, 15961 "clearApplicationUserData")) { 15962 synchronized (mInstallLock) { 15963 succeeded = clearApplicationUserDataLIF(packageName, userId); 15964 } 15965 clearExternalStorageDataSync(packageName, userId, true); 15966 } 15967 if (succeeded) { 15968 // invoke DeviceStorageMonitor's update method to clear any notifications 15969 DeviceStorageMonitorInternal dsm = LocalServices 15970 .getService(DeviceStorageMonitorInternal.class); 15971 if (dsm != null) { 15972 dsm.checkMemory(); 15973 } 15974 } 15975 if(observer != null) { 15976 try { 15977 observer.onRemoveCompleted(packageName, succeeded); 15978 } catch (RemoteException e) { 15979 Log.i(TAG, "Observer no longer exists."); 15980 } 15981 } //end if observer 15982 } //end run 15983 }); 15984 } 15985 15986 private boolean clearApplicationUserDataLIF(String packageName, int userId) { 15987 if (packageName == null) { 15988 Slog.w(TAG, "Attempt to delete null packageName."); 15989 return false; 15990 } 15991 15992 // Try finding details about the requested package 15993 PackageParser.Package pkg; 15994 synchronized (mPackages) { 15995 pkg = mPackages.get(packageName); 15996 if (pkg == null) { 15997 final PackageSetting ps = mSettings.mPackages.get(packageName); 15998 if (ps != null) { 15999 pkg = ps.pkg; 16000 } 16001 } 16002 16003 if (pkg == null) { 16004 Slog.w(TAG, "Package named '" + packageName + "' doesn't exist."); 16005 return false; 16006 } 16007 16008 PackageSetting ps = (PackageSetting) pkg.mExtras; 16009 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16010 } 16011 16012 clearAppDataLIF(pkg, userId, 16013 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 16014 16015 final int appId = UserHandle.getAppId(pkg.applicationInfo.uid); 16016 removeKeystoreDataIfNeeded(userId, appId); 16017 16018 final UserManager um = mContext.getSystemService(UserManager.class); 16019 final int flags; 16020 if (um.isUserUnlocked(userId)) { 16021 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 16022 } else if (um.isUserRunning(userId)) { 16023 flags = StorageManager.FLAG_STORAGE_DE; 16024 } else { 16025 flags = 0; 16026 } 16027 prepareAppDataContentsLIF(pkg, userId, flags); 16028 16029 return true; 16030 } 16031 16032 /** 16033 * Reverts user permission state changes (permissions and flags) in 16034 * all packages for a given user. 16035 * 16036 * @param userId The device user for which to do a reset. 16037 */ 16038 private void resetUserChangesToRuntimePermissionsAndFlagsLPw(int userId) { 16039 final int packageCount = mPackages.size(); 16040 for (int i = 0; i < packageCount; i++) { 16041 PackageParser.Package pkg = mPackages.valueAt(i); 16042 PackageSetting ps = (PackageSetting) pkg.mExtras; 16043 resetUserChangesToRuntimePermissionsAndFlagsLPw(ps, userId); 16044 } 16045 } 16046 16047 /** 16048 * Reverts user permission state changes (permissions and flags). 16049 * 16050 * @param ps The package for which to reset. 16051 * @param userId The device user for which to do a reset. 16052 */ 16053 private void resetUserChangesToRuntimePermissionsAndFlagsLPw( 16054 final PackageSetting ps, final int userId) { 16055 if (ps.pkg == null) { 16056 return; 16057 } 16058 16059 // These are flags that can change base on user actions. 16060 final int userSettableMask = FLAG_PERMISSION_USER_SET 16061 | FLAG_PERMISSION_USER_FIXED 16062 | FLAG_PERMISSION_REVOKE_ON_UPGRADE 16063 | FLAG_PERMISSION_REVIEW_REQUIRED; 16064 16065 final int policyOrSystemFlags = FLAG_PERMISSION_SYSTEM_FIXED 16066 | FLAG_PERMISSION_POLICY_FIXED; 16067 16068 boolean writeInstallPermissions = false; 16069 boolean writeRuntimePermissions = false; 16070 16071 final int permissionCount = ps.pkg.requestedPermissions.size(); 16072 for (int i = 0; i < permissionCount; i++) { 16073 String permission = ps.pkg.requestedPermissions.get(i); 16074 16075 BasePermission bp = mSettings.mPermissions.get(permission); 16076 if (bp == null) { 16077 continue; 16078 } 16079 16080 // If shared user we just reset the state to which only this app contributed. 16081 if (ps.sharedUser != null) { 16082 boolean used = false; 16083 final int packageCount = ps.sharedUser.packages.size(); 16084 for (int j = 0; j < packageCount; j++) { 16085 PackageSetting pkg = ps.sharedUser.packages.valueAt(j); 16086 if (pkg.pkg != null && !pkg.pkg.packageName.equals(ps.pkg.packageName) 16087 && pkg.pkg.requestedPermissions.contains(permission)) { 16088 used = true; 16089 break; 16090 } 16091 } 16092 if (used) { 16093 continue; 16094 } 16095 } 16096 16097 PermissionsState permissionsState = ps.getPermissionsState(); 16098 16099 final int oldFlags = permissionsState.getPermissionFlags(bp.name, userId); 16100 16101 // Always clear the user settable flags. 16102 final boolean hasInstallState = permissionsState.getInstallPermissionState( 16103 bp.name) != null; 16104 // If permission review is enabled and this is a legacy app, mark the 16105 // permission as requiring a review as this is the initial state. 16106 int flags = 0; 16107 if (Build.PERMISSIONS_REVIEW_REQUIRED 16108 && ps.pkg.applicationInfo.targetSdkVersion < Build.VERSION_CODES.M) { 16109 flags |= FLAG_PERMISSION_REVIEW_REQUIRED; 16110 } 16111 if (permissionsState.updatePermissionFlags(bp, userId, userSettableMask, flags)) { 16112 if (hasInstallState) { 16113 writeInstallPermissions = true; 16114 } else { 16115 writeRuntimePermissions = true; 16116 } 16117 } 16118 16119 // Below is only runtime permission handling. 16120 if (!bp.isRuntime()) { 16121 continue; 16122 } 16123 16124 // Never clobber system or policy. 16125 if ((oldFlags & policyOrSystemFlags) != 0) { 16126 continue; 16127 } 16128 16129 // If this permission was granted by default, make sure it is. 16130 if ((oldFlags & FLAG_PERMISSION_GRANTED_BY_DEFAULT) != 0) { 16131 if (permissionsState.grantRuntimePermission(bp, userId) 16132 != PERMISSION_OPERATION_FAILURE) { 16133 writeRuntimePermissions = true; 16134 } 16135 // If permission review is enabled the permissions for a legacy apps 16136 // are represented as constantly granted runtime ones, so don't revoke. 16137 } else if ((flags & FLAG_PERMISSION_REVIEW_REQUIRED) == 0) { 16138 // Otherwise, reset the permission. 16139 final int revokeResult = permissionsState.revokeRuntimePermission(bp, userId); 16140 switch (revokeResult) { 16141 case PERMISSION_OPERATION_SUCCESS: 16142 case PERMISSION_OPERATION_SUCCESS_GIDS_CHANGED: { 16143 writeRuntimePermissions = true; 16144 final int appId = ps.appId; 16145 mHandler.post(new Runnable() { 16146 @Override 16147 public void run() { 16148 killUid(appId, userId, KILL_APP_REASON_PERMISSIONS_REVOKED); 16149 } 16150 }); 16151 } break; 16152 } 16153 } 16154 } 16155 16156 // Synchronously write as we are taking permissions away. 16157 if (writeRuntimePermissions) { 16158 mSettings.writeRuntimePermissionsForUserLPr(userId, true); 16159 } 16160 16161 // Synchronously write as we are taking permissions away. 16162 if (writeInstallPermissions) { 16163 mSettings.writeLPr(); 16164 } 16165 } 16166 16167 /** 16168 * Remove entries from the keystore daemon. Will only remove it if the 16169 * {@code appId} is valid. 16170 */ 16171 private static void removeKeystoreDataIfNeeded(int userId, int appId) { 16172 if (appId < 0) { 16173 return; 16174 } 16175 16176 final KeyStore keyStore = KeyStore.getInstance(); 16177 if (keyStore != null) { 16178 if (userId == UserHandle.USER_ALL) { 16179 for (final int individual : sUserManager.getUserIds()) { 16180 keyStore.clearUid(UserHandle.getUid(individual, appId)); 16181 } 16182 } else { 16183 keyStore.clearUid(UserHandle.getUid(userId, appId)); 16184 } 16185 } else { 16186 Slog.w(TAG, "Could not contact keystore to clear entries for app id " + appId); 16187 } 16188 } 16189 16190 @Override 16191 public void deleteApplicationCacheFiles(final String packageName, 16192 final IPackageDataObserver observer) { 16193 final int userId = UserHandle.getCallingUserId(); 16194 deleteApplicationCacheFilesAsUser(packageName, userId, observer); 16195 } 16196 16197 @Override 16198 public void deleteApplicationCacheFilesAsUser(final String packageName, final int userId, 16199 final IPackageDataObserver observer) { 16200 mContext.enforceCallingOrSelfPermission( 16201 android.Manifest.permission.DELETE_CACHE_FILES, null); 16202 enforceCrossUserPermission(Binder.getCallingUid(), userId, 16203 /* requireFullPermission= */ true, /* checkShell= */ false, 16204 "delete application cache files"); 16205 16206 final PackageParser.Package pkg; 16207 synchronized (mPackages) { 16208 pkg = mPackages.get(packageName); 16209 } 16210 16211 // Queue up an async operation since the package deletion may take a little while. 16212 mHandler.post(new Runnable() { 16213 public void run() { 16214 synchronized (mInstallLock) { 16215 final int flags = StorageManager.FLAG_STORAGE_DE 16216 | StorageManager.FLAG_STORAGE_CE; 16217 // We're only clearing cache files, so we don't care if the 16218 // app is unfrozen and still able to run 16219 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CACHE_ONLY); 16220 clearAppDataLIF(pkg, userId, flags | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 16221 } 16222 clearExternalStorageDataSync(packageName, userId, false); 16223 if (observer != null) { 16224 try { 16225 observer.onRemoveCompleted(packageName, true); 16226 } catch (RemoteException e) { 16227 Log.i(TAG, "Observer no longer exists."); 16228 } 16229 } 16230 } 16231 }); 16232 } 16233 16234 @Override 16235 public void getPackageSizeInfo(final String packageName, int userHandle, 16236 final IPackageStatsObserver observer) { 16237 mContext.enforceCallingOrSelfPermission( 16238 android.Manifest.permission.GET_PACKAGE_SIZE, null); 16239 if (packageName == null) { 16240 throw new IllegalArgumentException("Attempt to get size of null packageName"); 16241 } 16242 16243 PackageStats stats = new PackageStats(packageName, userHandle); 16244 16245 /* 16246 * Queue up an async operation since the package measurement may take a 16247 * little while. 16248 */ 16249 Message msg = mHandler.obtainMessage(INIT_COPY); 16250 msg.obj = new MeasureParams(stats, observer); 16251 mHandler.sendMessage(msg); 16252 } 16253 16254 private boolean getPackageSizeInfoLI(String packageName, int userId, PackageStats stats) { 16255 final PackageSetting ps; 16256 synchronized (mPackages) { 16257 ps = mSettings.mPackages.get(packageName); 16258 if (ps == null) { 16259 Slog.w(TAG, "Failed to find settings for " + packageName); 16260 return false; 16261 } 16262 } 16263 try { 16264 mInstaller.getAppSize(ps.volumeUuid, packageName, userId, 16265 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE, 16266 ps.getCeDataInode(userId), ps.codePathString, stats); 16267 } catch (InstallerException e) { 16268 Slog.w(TAG, String.valueOf(e)); 16269 return false; 16270 } 16271 16272 // For now, ignore code size of packages on system partition 16273 if (isSystemApp(ps) && !isUpdatedSystemApp(ps)) { 16274 stats.codeSize = 0; 16275 } 16276 16277 return true; 16278 } 16279 16280 private int getUidTargetSdkVersionLockedLPr(int uid) { 16281 Object obj = mSettings.getUserIdLPr(uid); 16282 if (obj instanceof SharedUserSetting) { 16283 final SharedUserSetting sus = (SharedUserSetting) obj; 16284 int vers = Build.VERSION_CODES.CUR_DEVELOPMENT; 16285 final Iterator<PackageSetting> it = sus.packages.iterator(); 16286 while (it.hasNext()) { 16287 final PackageSetting ps = it.next(); 16288 if (ps.pkg != null) { 16289 int v = ps.pkg.applicationInfo.targetSdkVersion; 16290 if (v < vers) vers = v; 16291 } 16292 } 16293 return vers; 16294 } else if (obj instanceof PackageSetting) { 16295 final PackageSetting ps = (PackageSetting) obj; 16296 if (ps.pkg != null) { 16297 return ps.pkg.applicationInfo.targetSdkVersion; 16298 } 16299 } 16300 return Build.VERSION_CODES.CUR_DEVELOPMENT; 16301 } 16302 16303 @Override 16304 public void addPreferredActivity(IntentFilter filter, int match, 16305 ComponentName[] set, ComponentName activity, int userId) { 16306 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16307 "Adding preferred"); 16308 } 16309 16310 private void addPreferredActivityInternal(IntentFilter filter, int match, 16311 ComponentName[] set, ComponentName activity, boolean always, int userId, 16312 String opname) { 16313 // writer 16314 int callingUid = Binder.getCallingUid(); 16315 enforceCrossUserPermission(callingUid, userId, 16316 true /* requireFullPermission */, false /* checkShell */, "add preferred activity"); 16317 if (filter.countActions() == 0) { 16318 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16319 return; 16320 } 16321 synchronized (mPackages) { 16322 if (mContext.checkCallingOrSelfPermission( 16323 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16324 != PackageManager.PERMISSION_GRANTED) { 16325 if (getUidTargetSdkVersionLockedLPr(callingUid) 16326 < Build.VERSION_CODES.FROYO) { 16327 Slog.w(TAG, "Ignoring addPreferredActivity() from uid " 16328 + callingUid); 16329 return; 16330 } 16331 mContext.enforceCallingOrSelfPermission( 16332 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16333 } 16334 16335 PreferredIntentResolver pir = mSettings.editPreferredActivitiesLPw(userId); 16336 Slog.i(TAG, opname + " activity " + activity.flattenToShortString() + " for user " 16337 + userId + ":"); 16338 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16339 pir.addFilter(new PreferredActivity(filter, match, set, activity, always)); 16340 scheduleWritePackageRestrictionsLocked(userId); 16341 } 16342 } 16343 16344 @Override 16345 public void replacePreferredActivity(IntentFilter filter, int match, 16346 ComponentName[] set, ComponentName activity, int userId) { 16347 if (filter.countActions() != 1) { 16348 throw new IllegalArgumentException( 16349 "replacePreferredActivity expects filter to have only 1 action."); 16350 } 16351 if (filter.countDataAuthorities() != 0 16352 || filter.countDataPaths() != 0 16353 || filter.countDataSchemes() > 1 16354 || filter.countDataTypes() != 0) { 16355 throw new IllegalArgumentException( 16356 "replacePreferredActivity expects filter to have no data authorities, " + 16357 "paths, or types; and at most one scheme."); 16358 } 16359 16360 final int callingUid = Binder.getCallingUid(); 16361 enforceCrossUserPermission(callingUid, userId, 16362 true /* requireFullPermission */, false /* checkShell */, 16363 "replace preferred activity"); 16364 synchronized (mPackages) { 16365 if (mContext.checkCallingOrSelfPermission( 16366 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16367 != PackageManager.PERMISSION_GRANTED) { 16368 if (getUidTargetSdkVersionLockedLPr(callingUid) 16369 < Build.VERSION_CODES.FROYO) { 16370 Slog.w(TAG, "Ignoring replacePreferredActivity() from uid " 16371 + Binder.getCallingUid()); 16372 return; 16373 } 16374 mContext.enforceCallingOrSelfPermission( 16375 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16376 } 16377 16378 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16379 if (pir != null) { 16380 // Get all of the existing entries that exactly match this filter. 16381 ArrayList<PreferredActivity> existing = pir.findFilters(filter); 16382 if (existing != null && existing.size() == 1) { 16383 PreferredActivity cur = existing.get(0); 16384 if (DEBUG_PREFERRED) { 16385 Slog.i(TAG, "Checking replace of preferred:"); 16386 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16387 if (!cur.mPref.mAlways) { 16388 Slog.i(TAG, " -- CUR; not mAlways!"); 16389 } else { 16390 Slog.i(TAG, " -- CUR: mMatch=" + cur.mPref.mMatch); 16391 Slog.i(TAG, " -- CUR: mSet=" 16392 + Arrays.toString(cur.mPref.mSetComponents)); 16393 Slog.i(TAG, " -- CUR: mComponent=" + cur.mPref.mShortComponent); 16394 Slog.i(TAG, " -- NEW: mMatch=" 16395 + (match&IntentFilter.MATCH_CATEGORY_MASK)); 16396 Slog.i(TAG, " -- CUR: mSet=" + Arrays.toString(set)); 16397 Slog.i(TAG, " -- CUR: mComponent=" + activity.flattenToShortString()); 16398 } 16399 } 16400 if (cur.mPref.mAlways && cur.mPref.mComponent.equals(activity) 16401 && cur.mPref.mMatch == (match&IntentFilter.MATCH_CATEGORY_MASK) 16402 && cur.mPref.sameSet(set)) { 16403 // Setting the preferred activity to what it happens to be already 16404 if (DEBUG_PREFERRED) { 16405 Slog.i(TAG, "Replacing with same preferred activity " 16406 + cur.mPref.mShortComponent + " for user " 16407 + userId + ":"); 16408 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16409 } 16410 return; 16411 } 16412 } 16413 16414 if (existing != null) { 16415 if (DEBUG_PREFERRED) { 16416 Slog.i(TAG, existing.size() + " existing preferred matches for:"); 16417 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16418 } 16419 for (int i = 0; i < existing.size(); i++) { 16420 PreferredActivity pa = existing.get(i); 16421 if (DEBUG_PREFERRED) { 16422 Slog.i(TAG, "Removing existing preferred activity " 16423 + pa.mPref.mComponent + ":"); 16424 pa.dump(new LogPrinter(Log.INFO, TAG), " "); 16425 } 16426 pir.removeFilter(pa); 16427 } 16428 } 16429 } 16430 addPreferredActivityInternal(filter, match, set, activity, true, userId, 16431 "Replacing preferred"); 16432 } 16433 } 16434 16435 @Override 16436 public void clearPackagePreferredActivities(String packageName) { 16437 final int uid = Binder.getCallingUid(); 16438 // writer 16439 synchronized (mPackages) { 16440 PackageParser.Package pkg = mPackages.get(packageName); 16441 if (pkg == null || pkg.applicationInfo.uid != uid) { 16442 if (mContext.checkCallingOrSelfPermission( 16443 android.Manifest.permission.SET_PREFERRED_APPLICATIONS) 16444 != PackageManager.PERMISSION_GRANTED) { 16445 if (getUidTargetSdkVersionLockedLPr(Binder.getCallingUid()) 16446 < Build.VERSION_CODES.FROYO) { 16447 Slog.w(TAG, "Ignoring clearPackagePreferredActivities() from uid " 16448 + Binder.getCallingUid()); 16449 return; 16450 } 16451 mContext.enforceCallingOrSelfPermission( 16452 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16453 } 16454 } 16455 16456 int user = UserHandle.getCallingUserId(); 16457 if (clearPackagePreferredActivitiesLPw(packageName, user)) { 16458 scheduleWritePackageRestrictionsLocked(user); 16459 } 16460 } 16461 } 16462 16463 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16464 boolean clearPackagePreferredActivitiesLPw(String packageName, int userId) { 16465 ArrayList<PreferredActivity> removed = null; 16466 boolean changed = false; 16467 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 16468 final int thisUserId = mSettings.mPreferredActivities.keyAt(i); 16469 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 16470 if (userId != UserHandle.USER_ALL && userId != thisUserId) { 16471 continue; 16472 } 16473 Iterator<PreferredActivity> it = pir.filterIterator(); 16474 while (it.hasNext()) { 16475 PreferredActivity pa = it.next(); 16476 // Mark entry for removal only if it matches the package name 16477 // and the entry is of type "always". 16478 if (packageName == null || 16479 (pa.mPref.mComponent.getPackageName().equals(packageName) 16480 && pa.mPref.mAlways)) { 16481 if (removed == null) { 16482 removed = new ArrayList<PreferredActivity>(); 16483 } 16484 removed.add(pa); 16485 } 16486 } 16487 if (removed != null) { 16488 for (int j=0; j<removed.size(); j++) { 16489 PreferredActivity pa = removed.get(j); 16490 pir.removeFilter(pa); 16491 } 16492 changed = true; 16493 } 16494 } 16495 return changed; 16496 } 16497 16498 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16499 private void clearIntentFilterVerificationsLPw(int userId) { 16500 final int packageCount = mPackages.size(); 16501 for (int i = 0; i < packageCount; i++) { 16502 PackageParser.Package pkg = mPackages.valueAt(i); 16503 clearIntentFilterVerificationsLPw(pkg.packageName, userId); 16504 } 16505 } 16506 16507 /** This method takes a specific user id as well as UserHandle.USER_ALL. */ 16508 void clearIntentFilterVerificationsLPw(String packageName, int userId) { 16509 if (userId == UserHandle.USER_ALL) { 16510 if (mSettings.removeIntentFilterVerificationLPw(packageName, 16511 sUserManager.getUserIds())) { 16512 for (int oneUserId : sUserManager.getUserIds()) { 16513 scheduleWritePackageRestrictionsLocked(oneUserId); 16514 } 16515 } 16516 } else { 16517 if (mSettings.removeIntentFilterVerificationLPw(packageName, userId)) { 16518 scheduleWritePackageRestrictionsLocked(userId); 16519 } 16520 } 16521 } 16522 16523 void clearDefaultBrowserIfNeeded(String packageName) { 16524 for (int oneUserId : sUserManager.getUserIds()) { 16525 String defaultBrowserPackageName = getDefaultBrowserPackageName(oneUserId); 16526 if (TextUtils.isEmpty(defaultBrowserPackageName)) continue; 16527 if (packageName.equals(defaultBrowserPackageName)) { 16528 setDefaultBrowserPackageName(null, oneUserId); 16529 } 16530 } 16531 } 16532 16533 @Override 16534 public void resetApplicationPreferences(int userId) { 16535 mContext.enforceCallingOrSelfPermission( 16536 android.Manifest.permission.SET_PREFERRED_APPLICATIONS, null); 16537 // writer 16538 synchronized (mPackages) { 16539 final long identity = Binder.clearCallingIdentity(); 16540 try { 16541 clearPackagePreferredActivitiesLPw(null, userId); 16542 mSettings.applyDefaultPreferredAppsLPw(this, userId); 16543 // TODO: We have to reset the default SMS and Phone. This requires 16544 // significant refactoring to keep all default apps in the package 16545 // manager (cleaner but more work) or have the services provide 16546 // callbacks to the package manager to request a default app reset. 16547 applyFactoryDefaultBrowserLPw(userId); 16548 clearIntentFilterVerificationsLPw(userId); 16549 primeDomainVerificationsLPw(userId); 16550 resetUserChangesToRuntimePermissionsAndFlagsLPw(userId); 16551 scheduleWritePackageRestrictionsLocked(userId); 16552 } finally { 16553 Binder.restoreCallingIdentity(identity); 16554 } 16555 } 16556 } 16557 16558 @Override 16559 public int getPreferredActivities(List<IntentFilter> outFilters, 16560 List<ComponentName> outActivities, String packageName) { 16561 16562 int num = 0; 16563 final int userId = UserHandle.getCallingUserId(); 16564 // reader 16565 synchronized (mPackages) { 16566 PreferredIntentResolver pir = mSettings.mPreferredActivities.get(userId); 16567 if (pir != null) { 16568 final Iterator<PreferredActivity> it = pir.filterIterator(); 16569 while (it.hasNext()) { 16570 final PreferredActivity pa = it.next(); 16571 if (packageName == null 16572 || (pa.mPref.mComponent.getPackageName().equals(packageName) 16573 && pa.mPref.mAlways)) { 16574 if (outFilters != null) { 16575 outFilters.add(new IntentFilter(pa)); 16576 } 16577 if (outActivities != null) { 16578 outActivities.add(pa.mPref.mComponent); 16579 } 16580 } 16581 } 16582 } 16583 } 16584 16585 return num; 16586 } 16587 16588 @Override 16589 public void addPersistentPreferredActivity(IntentFilter filter, ComponentName activity, 16590 int userId) { 16591 int callingUid = Binder.getCallingUid(); 16592 if (callingUid != Process.SYSTEM_UID) { 16593 throw new SecurityException( 16594 "addPersistentPreferredActivity can only be run by the system"); 16595 } 16596 if (filter.countActions() == 0) { 16597 Slog.w(TAG, "Cannot set a preferred activity with no filter actions"); 16598 return; 16599 } 16600 synchronized (mPackages) { 16601 Slog.i(TAG, "Adding persistent preferred activity " + activity + " for user " + userId + 16602 ":"); 16603 filter.dump(new LogPrinter(Log.INFO, TAG), " "); 16604 mSettings.editPersistentPreferredActivitiesLPw(userId).addFilter( 16605 new PersistentPreferredActivity(filter, activity)); 16606 scheduleWritePackageRestrictionsLocked(userId); 16607 } 16608 } 16609 16610 @Override 16611 public void clearPackagePersistentPreferredActivities(String packageName, int userId) { 16612 int callingUid = Binder.getCallingUid(); 16613 if (callingUid != Process.SYSTEM_UID) { 16614 throw new SecurityException( 16615 "clearPackagePersistentPreferredActivities can only be run by the system"); 16616 } 16617 ArrayList<PersistentPreferredActivity> removed = null; 16618 boolean changed = false; 16619 synchronized (mPackages) { 16620 for (int i=0; i<mSettings.mPersistentPreferredActivities.size(); i++) { 16621 final int thisUserId = mSettings.mPersistentPreferredActivities.keyAt(i); 16622 PersistentPreferredIntentResolver ppir = mSettings.mPersistentPreferredActivities 16623 .valueAt(i); 16624 if (userId != thisUserId) { 16625 continue; 16626 } 16627 Iterator<PersistentPreferredActivity> it = ppir.filterIterator(); 16628 while (it.hasNext()) { 16629 PersistentPreferredActivity ppa = it.next(); 16630 // Mark entry for removal only if it matches the package name. 16631 if (ppa.mComponent.getPackageName().equals(packageName)) { 16632 if (removed == null) { 16633 removed = new ArrayList<PersistentPreferredActivity>(); 16634 } 16635 removed.add(ppa); 16636 } 16637 } 16638 if (removed != null) { 16639 for (int j=0; j<removed.size(); j++) { 16640 PersistentPreferredActivity ppa = removed.get(j); 16641 ppir.removeFilter(ppa); 16642 } 16643 changed = true; 16644 } 16645 } 16646 16647 if (changed) { 16648 scheduleWritePackageRestrictionsLocked(userId); 16649 } 16650 } 16651 } 16652 16653 /** 16654 * Common machinery for picking apart a restored XML blob and passing 16655 * it to a caller-supplied functor to be applied to the running system. 16656 */ 16657 private void restoreFromXml(XmlPullParser parser, int userId, 16658 String expectedStartTag, BlobXmlRestorer functor) 16659 throws IOException, XmlPullParserException { 16660 int type; 16661 while ((type = parser.next()) != XmlPullParser.START_TAG 16662 && type != XmlPullParser.END_DOCUMENT) { 16663 } 16664 if (type != XmlPullParser.START_TAG) { 16665 // oops didn't find a start tag?! 16666 if (DEBUG_BACKUP) { 16667 Slog.e(TAG, "Didn't find start tag during restore"); 16668 } 16669 return; 16670 } 16671Slog.v(TAG, ":: restoreFromXml() : got to tag " + parser.getName()); 16672 // this is supposed to be TAG_PREFERRED_BACKUP 16673 if (!expectedStartTag.equals(parser.getName())) { 16674 if (DEBUG_BACKUP) { 16675 Slog.e(TAG, "Found unexpected tag " + parser.getName()); 16676 } 16677 return; 16678 } 16679 16680 // skip interfering stuff, then we're aligned with the backing implementation 16681 while ((type = parser.next()) == XmlPullParser.TEXT) { } 16682Slog.v(TAG, ":: stepped forward, applying functor at tag " + parser.getName()); 16683 functor.apply(parser, userId); 16684 } 16685 16686 private interface BlobXmlRestorer { 16687 public void apply(XmlPullParser parser, int userId) throws IOException, XmlPullParserException; 16688 } 16689 16690 /** 16691 * Non-Binder method, support for the backup/restore mechanism: write the 16692 * full set of preferred activities in its canonical XML format. Returns the 16693 * XML output as a byte array, or null if there is none. 16694 */ 16695 @Override 16696 public byte[] getPreferredActivityBackup(int userId) { 16697 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16698 throw new SecurityException("Only the system may call getPreferredActivityBackup()"); 16699 } 16700 16701 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16702 try { 16703 final XmlSerializer serializer = new FastXmlSerializer(); 16704 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16705 serializer.startDocument(null, true); 16706 serializer.startTag(null, TAG_PREFERRED_BACKUP); 16707 16708 synchronized (mPackages) { 16709 mSettings.writePreferredActivitiesLPr(serializer, userId, true); 16710 } 16711 16712 serializer.endTag(null, TAG_PREFERRED_BACKUP); 16713 serializer.endDocument(); 16714 serializer.flush(); 16715 } catch (Exception e) { 16716 if (DEBUG_BACKUP) { 16717 Slog.e(TAG, "Unable to write preferred activities for backup", e); 16718 } 16719 return null; 16720 } 16721 16722 return dataStream.toByteArray(); 16723 } 16724 16725 @Override 16726 public void restorePreferredActivities(byte[] backup, int userId) { 16727 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16728 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16729 } 16730 16731 try { 16732 final XmlPullParser parser = Xml.newPullParser(); 16733 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16734 restoreFromXml(parser, userId, TAG_PREFERRED_BACKUP, 16735 new BlobXmlRestorer() { 16736 @Override 16737 public void apply(XmlPullParser parser, int userId) 16738 throws XmlPullParserException, IOException { 16739 synchronized (mPackages) { 16740 mSettings.readPreferredActivitiesLPw(parser, userId); 16741 } 16742 } 16743 } ); 16744 } catch (Exception e) { 16745 if (DEBUG_BACKUP) { 16746 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16747 } 16748 } 16749 } 16750 16751 /** 16752 * Non-Binder method, support for the backup/restore mechanism: write the 16753 * default browser (etc) settings in its canonical XML format. Returns the default 16754 * browser XML representation as a byte array, or null if there is none. 16755 */ 16756 @Override 16757 public byte[] getDefaultAppsBackup(int userId) { 16758 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16759 throw new SecurityException("Only the system may call getDefaultAppsBackup()"); 16760 } 16761 16762 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16763 try { 16764 final XmlSerializer serializer = new FastXmlSerializer(); 16765 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16766 serializer.startDocument(null, true); 16767 serializer.startTag(null, TAG_DEFAULT_APPS); 16768 16769 synchronized (mPackages) { 16770 mSettings.writeDefaultAppsLPr(serializer, userId); 16771 } 16772 16773 serializer.endTag(null, TAG_DEFAULT_APPS); 16774 serializer.endDocument(); 16775 serializer.flush(); 16776 } catch (Exception e) { 16777 if (DEBUG_BACKUP) { 16778 Slog.e(TAG, "Unable to write default apps for backup", e); 16779 } 16780 return null; 16781 } 16782 16783 return dataStream.toByteArray(); 16784 } 16785 16786 @Override 16787 public void restoreDefaultApps(byte[] backup, int userId) { 16788 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16789 throw new SecurityException("Only the system may call restoreDefaultApps()"); 16790 } 16791 16792 try { 16793 final XmlPullParser parser = Xml.newPullParser(); 16794 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16795 restoreFromXml(parser, userId, TAG_DEFAULT_APPS, 16796 new BlobXmlRestorer() { 16797 @Override 16798 public void apply(XmlPullParser parser, int userId) 16799 throws XmlPullParserException, IOException { 16800 synchronized (mPackages) { 16801 mSettings.readDefaultAppsLPw(parser, userId); 16802 } 16803 } 16804 } ); 16805 } catch (Exception e) { 16806 if (DEBUG_BACKUP) { 16807 Slog.e(TAG, "Exception restoring default apps: " + e.getMessage()); 16808 } 16809 } 16810 } 16811 16812 @Override 16813 public byte[] getIntentFilterVerificationBackup(int userId) { 16814 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16815 throw new SecurityException("Only the system may call getIntentFilterVerificationBackup()"); 16816 } 16817 16818 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16819 try { 16820 final XmlSerializer serializer = new FastXmlSerializer(); 16821 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16822 serializer.startDocument(null, true); 16823 serializer.startTag(null, TAG_INTENT_FILTER_VERIFICATION); 16824 16825 synchronized (mPackages) { 16826 mSettings.writeAllDomainVerificationsLPr(serializer, userId); 16827 } 16828 16829 serializer.endTag(null, TAG_INTENT_FILTER_VERIFICATION); 16830 serializer.endDocument(); 16831 serializer.flush(); 16832 } catch (Exception e) { 16833 if (DEBUG_BACKUP) { 16834 Slog.e(TAG, "Unable to write default apps for backup", e); 16835 } 16836 return null; 16837 } 16838 16839 return dataStream.toByteArray(); 16840 } 16841 16842 @Override 16843 public void restoreIntentFilterVerification(byte[] backup, int userId) { 16844 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16845 throw new SecurityException("Only the system may call restorePreferredActivities()"); 16846 } 16847 16848 try { 16849 final XmlPullParser parser = Xml.newPullParser(); 16850 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16851 restoreFromXml(parser, userId, TAG_INTENT_FILTER_VERIFICATION, 16852 new BlobXmlRestorer() { 16853 @Override 16854 public void apply(XmlPullParser parser, int userId) 16855 throws XmlPullParserException, IOException { 16856 synchronized (mPackages) { 16857 mSettings.readAllDomainVerificationsLPr(parser, userId); 16858 mSettings.writeLPr(); 16859 } 16860 } 16861 } ); 16862 } catch (Exception e) { 16863 if (DEBUG_BACKUP) { 16864 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16865 } 16866 } 16867 } 16868 16869 @Override 16870 public byte[] getPermissionGrantBackup(int userId) { 16871 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16872 throw new SecurityException("Only the system may call getPermissionGrantBackup()"); 16873 } 16874 16875 ByteArrayOutputStream dataStream = new ByteArrayOutputStream(); 16876 try { 16877 final XmlSerializer serializer = new FastXmlSerializer(); 16878 serializer.setOutput(dataStream, StandardCharsets.UTF_8.name()); 16879 serializer.startDocument(null, true); 16880 serializer.startTag(null, TAG_PERMISSION_BACKUP); 16881 16882 synchronized (mPackages) { 16883 serializeRuntimePermissionGrantsLPr(serializer, userId); 16884 } 16885 16886 serializer.endTag(null, TAG_PERMISSION_BACKUP); 16887 serializer.endDocument(); 16888 serializer.flush(); 16889 } catch (Exception e) { 16890 if (DEBUG_BACKUP) { 16891 Slog.e(TAG, "Unable to write default apps for backup", e); 16892 } 16893 return null; 16894 } 16895 16896 return dataStream.toByteArray(); 16897 } 16898 16899 @Override 16900 public void restorePermissionGrants(byte[] backup, int userId) { 16901 if (Binder.getCallingUid() != Process.SYSTEM_UID) { 16902 throw new SecurityException("Only the system may call restorePermissionGrants()"); 16903 } 16904 16905 try { 16906 final XmlPullParser parser = Xml.newPullParser(); 16907 parser.setInput(new ByteArrayInputStream(backup), StandardCharsets.UTF_8.name()); 16908 restoreFromXml(parser, userId, TAG_PERMISSION_BACKUP, 16909 new BlobXmlRestorer() { 16910 @Override 16911 public void apply(XmlPullParser parser, int userId) 16912 throws XmlPullParserException, IOException { 16913 synchronized (mPackages) { 16914 processRestoredPermissionGrantsLPr(parser, userId); 16915 } 16916 } 16917 } ); 16918 } catch (Exception e) { 16919 if (DEBUG_BACKUP) { 16920 Slog.e(TAG, "Exception restoring preferred activities: " + e.getMessage()); 16921 } 16922 } 16923 } 16924 16925 private void serializeRuntimePermissionGrantsLPr(XmlSerializer serializer, final int userId) 16926 throws IOException { 16927 serializer.startTag(null, TAG_ALL_GRANTS); 16928 16929 final int N = mSettings.mPackages.size(); 16930 for (int i = 0; i < N; i++) { 16931 final PackageSetting ps = mSettings.mPackages.valueAt(i); 16932 boolean pkgGrantsKnown = false; 16933 16934 PermissionsState packagePerms = ps.getPermissionsState(); 16935 16936 for (PermissionState state : packagePerms.getRuntimePermissionStates(userId)) { 16937 final int grantFlags = state.getFlags(); 16938 // only look at grants that are not system/policy fixed 16939 if ((grantFlags & SYSTEM_RUNTIME_GRANT_MASK) == 0) { 16940 final boolean isGranted = state.isGranted(); 16941 // And only back up the user-twiddled state bits 16942 if (isGranted || (grantFlags & USER_RUNTIME_GRANT_MASK) != 0) { 16943 final String packageName = mSettings.mPackages.keyAt(i); 16944 if (!pkgGrantsKnown) { 16945 serializer.startTag(null, TAG_GRANT); 16946 serializer.attribute(null, ATTR_PACKAGE_NAME, packageName); 16947 pkgGrantsKnown = true; 16948 } 16949 16950 final boolean userSet = 16951 (grantFlags & FLAG_PERMISSION_USER_SET) != 0; 16952 final boolean userFixed = 16953 (grantFlags & FLAG_PERMISSION_USER_FIXED) != 0; 16954 final boolean revoke = 16955 (grantFlags & FLAG_PERMISSION_REVOKE_ON_UPGRADE) != 0; 16956 16957 serializer.startTag(null, TAG_PERMISSION); 16958 serializer.attribute(null, ATTR_PERMISSION_NAME, state.getName()); 16959 if (isGranted) { 16960 serializer.attribute(null, ATTR_IS_GRANTED, "true"); 16961 } 16962 if (userSet) { 16963 serializer.attribute(null, ATTR_USER_SET, "true"); 16964 } 16965 if (userFixed) { 16966 serializer.attribute(null, ATTR_USER_FIXED, "true"); 16967 } 16968 if (revoke) { 16969 serializer.attribute(null, ATTR_REVOKE_ON_UPGRADE, "true"); 16970 } 16971 serializer.endTag(null, TAG_PERMISSION); 16972 } 16973 } 16974 } 16975 16976 if (pkgGrantsKnown) { 16977 serializer.endTag(null, TAG_GRANT); 16978 } 16979 } 16980 16981 serializer.endTag(null, TAG_ALL_GRANTS); 16982 } 16983 16984 private void processRestoredPermissionGrantsLPr(XmlPullParser parser, int userId) 16985 throws XmlPullParserException, IOException { 16986 String pkgName = null; 16987 int outerDepth = parser.getDepth(); 16988 int type; 16989 while ((type = parser.next()) != XmlPullParser.END_DOCUMENT 16990 && (type != XmlPullParser.END_TAG || parser.getDepth() > outerDepth)) { 16991 if (type == XmlPullParser.END_TAG || type == XmlPullParser.TEXT) { 16992 continue; 16993 } 16994 16995 final String tagName = parser.getName(); 16996 if (tagName.equals(TAG_GRANT)) { 16997 pkgName = parser.getAttributeValue(null, ATTR_PACKAGE_NAME); 16998 if (DEBUG_BACKUP) { 16999 Slog.v(TAG, "+++ Restoring grants for package " + pkgName); 17000 } 17001 } else if (tagName.equals(TAG_PERMISSION)) { 17002 17003 final boolean isGranted = "true".equals(parser.getAttributeValue(null, ATTR_IS_GRANTED)); 17004 final String permName = parser.getAttributeValue(null, ATTR_PERMISSION_NAME); 17005 17006 int newFlagSet = 0; 17007 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_SET))) { 17008 newFlagSet |= FLAG_PERMISSION_USER_SET; 17009 } 17010 if ("true".equals(parser.getAttributeValue(null, ATTR_USER_FIXED))) { 17011 newFlagSet |= FLAG_PERMISSION_USER_FIXED; 17012 } 17013 if ("true".equals(parser.getAttributeValue(null, ATTR_REVOKE_ON_UPGRADE))) { 17014 newFlagSet |= FLAG_PERMISSION_REVOKE_ON_UPGRADE; 17015 } 17016 if (DEBUG_BACKUP) { 17017 Slog.v(TAG, " + Restoring grant: pkg=" + pkgName + " perm=" + permName 17018 + " granted=" + isGranted + " bits=0x" + Integer.toHexString(newFlagSet)); 17019 } 17020 final PackageSetting ps = mSettings.mPackages.get(pkgName); 17021 if (ps != null) { 17022 // Already installed so we apply the grant immediately 17023 if (DEBUG_BACKUP) { 17024 Slog.v(TAG, " + already installed; applying"); 17025 } 17026 PermissionsState perms = ps.getPermissionsState(); 17027 BasePermission bp = mSettings.mPermissions.get(permName); 17028 if (bp != null) { 17029 if (isGranted) { 17030 perms.grantRuntimePermission(bp, userId); 17031 } 17032 if (newFlagSet != 0) { 17033 perms.updatePermissionFlags(bp, userId, USER_RUNTIME_GRANT_MASK, newFlagSet); 17034 } 17035 } 17036 } else { 17037 // Need to wait for post-restore install to apply the grant 17038 if (DEBUG_BACKUP) { 17039 Slog.v(TAG, " - not yet installed; saving for later"); 17040 } 17041 mSettings.processRestoredPermissionGrantLPr(pkgName, permName, 17042 isGranted, newFlagSet, userId); 17043 } 17044 } else { 17045 PackageManagerService.reportSettingsProblem(Log.WARN, 17046 "Unknown element under <" + TAG_PERMISSION_BACKUP + ">: " + tagName); 17047 XmlUtils.skipCurrentTag(parser); 17048 } 17049 } 17050 17051 scheduleWriteSettingsLocked(); 17052 mSettings.writeRuntimePermissionsForUserLPr(userId, false); 17053 } 17054 17055 @Override 17056 public void addCrossProfileIntentFilter(IntentFilter intentFilter, String ownerPackage, 17057 int sourceUserId, int targetUserId, int flags) { 17058 mContext.enforceCallingOrSelfPermission( 17059 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17060 int callingUid = Binder.getCallingUid(); 17061 enforceOwnerRights(ownerPackage, callingUid); 17062 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17063 if (intentFilter.countActions() == 0) { 17064 Slog.w(TAG, "Cannot set a crossProfile intent filter with no filter actions"); 17065 return; 17066 } 17067 synchronized (mPackages) { 17068 CrossProfileIntentFilter newFilter = new CrossProfileIntentFilter(intentFilter, 17069 ownerPackage, targetUserId, flags); 17070 CrossProfileIntentResolver resolver = 17071 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17072 ArrayList<CrossProfileIntentFilter> existing = resolver.findFilters(intentFilter); 17073 // We have all those whose filter is equal. Now checking if the rest is equal as well. 17074 if (existing != null) { 17075 int size = existing.size(); 17076 for (int i = 0; i < size; i++) { 17077 if (newFilter.equalsIgnoreFilter(existing.get(i))) { 17078 return; 17079 } 17080 } 17081 } 17082 resolver.addFilter(newFilter); 17083 scheduleWritePackageRestrictionsLocked(sourceUserId); 17084 } 17085 } 17086 17087 @Override 17088 public void clearCrossProfileIntentFilters(int sourceUserId, String ownerPackage) { 17089 mContext.enforceCallingOrSelfPermission( 17090 android.Manifest.permission.INTERACT_ACROSS_USERS_FULL, null); 17091 int callingUid = Binder.getCallingUid(); 17092 enforceOwnerRights(ownerPackage, callingUid); 17093 enforceShellRestriction(UserManager.DISALLOW_DEBUGGING_FEATURES, callingUid, sourceUserId); 17094 synchronized (mPackages) { 17095 CrossProfileIntentResolver resolver = 17096 mSettings.editCrossProfileIntentResolverLPw(sourceUserId); 17097 ArraySet<CrossProfileIntentFilter> set = 17098 new ArraySet<CrossProfileIntentFilter>(resolver.filterSet()); 17099 for (CrossProfileIntentFilter filter : set) { 17100 if (filter.getOwnerPackage().equals(ownerPackage)) { 17101 resolver.removeFilter(filter); 17102 } 17103 } 17104 scheduleWritePackageRestrictionsLocked(sourceUserId); 17105 } 17106 } 17107 17108 // Enforcing that callingUid is owning pkg on userId 17109 private void enforceOwnerRights(String pkg, int callingUid) { 17110 // The system owns everything. 17111 if (UserHandle.getAppId(callingUid) == Process.SYSTEM_UID) { 17112 return; 17113 } 17114 int callingUserId = UserHandle.getUserId(callingUid); 17115 PackageInfo pi = getPackageInfo(pkg, 0, callingUserId); 17116 if (pi == null) { 17117 throw new IllegalArgumentException("Unknown package " + pkg + " on user " 17118 + callingUserId); 17119 } 17120 if (!UserHandle.isSameApp(pi.applicationInfo.uid, callingUid)) { 17121 throw new SecurityException("Calling uid " + callingUid 17122 + " does not own package " + pkg); 17123 } 17124 } 17125 17126 @Override 17127 public ComponentName getHomeActivities(List<ResolveInfo> allHomeCandidates) { 17128 return getHomeActivitiesAsUser(allHomeCandidates, UserHandle.getCallingUserId()); 17129 } 17130 17131 private Intent getHomeIntent() { 17132 Intent intent = new Intent(Intent.ACTION_MAIN); 17133 intent.addCategory(Intent.CATEGORY_HOME); 17134 return intent; 17135 } 17136 17137 private IntentFilter getHomeFilter() { 17138 IntentFilter filter = new IntentFilter(Intent.ACTION_MAIN); 17139 filter.addCategory(Intent.CATEGORY_HOME); 17140 filter.addCategory(Intent.CATEGORY_DEFAULT); 17141 return filter; 17142 } 17143 17144 ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 17145 int userId) { 17146 Intent intent = getHomeIntent(); 17147 List<ResolveInfo> list = queryIntentActivitiesInternal(intent, null, 17148 PackageManager.GET_META_DATA, userId); 17149 ResolveInfo preferred = findPreferredActivity(intent, null, 0, list, 0, 17150 true, false, false, userId); 17151 17152 allHomeCandidates.clear(); 17153 if (list != null) { 17154 for (ResolveInfo ri : list) { 17155 allHomeCandidates.add(ri); 17156 } 17157 } 17158 return (preferred == null || preferred.activityInfo == null) 17159 ? null 17160 : new ComponentName(preferred.activityInfo.packageName, 17161 preferred.activityInfo.name); 17162 } 17163 17164 @Override 17165 public void setHomeActivity(ComponentName comp, int userId) { 17166 ArrayList<ResolveInfo> homeActivities = new ArrayList<>(); 17167 getHomeActivitiesAsUser(homeActivities, userId); 17168 17169 boolean found = false; 17170 17171 final int size = homeActivities.size(); 17172 final ComponentName[] set = new ComponentName[size]; 17173 for (int i = 0; i < size; i++) { 17174 final ResolveInfo candidate = homeActivities.get(i); 17175 final ActivityInfo info = candidate.activityInfo; 17176 final ComponentName activityName = new ComponentName(info.packageName, info.name); 17177 set[i] = activityName; 17178 if (!found && activityName.equals(comp)) { 17179 found = true; 17180 } 17181 } 17182 if (!found) { 17183 throw new IllegalArgumentException("Component " + comp + " cannot be home on user " 17184 + userId); 17185 } 17186 replacePreferredActivity(getHomeFilter(), IntentFilter.MATCH_CATEGORY_EMPTY, 17187 set, comp, userId); 17188 } 17189 17190 private @Nullable String getSetupWizardPackageName() { 17191 final Intent intent = new Intent(Intent.ACTION_MAIN); 17192 intent.addCategory(Intent.CATEGORY_SETUP_WIZARD); 17193 17194 final List<ResolveInfo> matches = queryIntentActivitiesInternal(intent, null, 17195 MATCH_SYSTEM_ONLY | MATCH_DIRECT_BOOT_AWARE | MATCH_DIRECT_BOOT_UNAWARE 17196 | MATCH_DISABLED_COMPONENTS, 17197 UserHandle.myUserId()); 17198 if (matches.size() == 1) { 17199 return matches.get(0).getComponentInfo().packageName; 17200 } else { 17201 Slog.e(TAG, "There should probably be exactly one setup wizard; found " + matches.size() 17202 + ": matches=" + matches); 17203 return null; 17204 } 17205 } 17206 17207 @Override 17208 public void setApplicationEnabledSetting(String appPackageName, 17209 int newState, int flags, int userId, String callingPackage) { 17210 if (!sUserManager.exists(userId)) return; 17211 if (callingPackage == null) { 17212 callingPackage = Integer.toString(Binder.getCallingUid()); 17213 } 17214 setEnabledSetting(appPackageName, null, newState, flags, userId, callingPackage); 17215 } 17216 17217 @Override 17218 public void setComponentEnabledSetting(ComponentName componentName, 17219 int newState, int flags, int userId) { 17220 if (!sUserManager.exists(userId)) return; 17221 setEnabledSetting(componentName.getPackageName(), 17222 componentName.getClassName(), newState, flags, userId, null); 17223 } 17224 17225 private void setEnabledSetting(final String packageName, String className, int newState, 17226 final int flags, int userId, String callingPackage) { 17227 if (!(newState == COMPONENT_ENABLED_STATE_DEFAULT 17228 || newState == COMPONENT_ENABLED_STATE_ENABLED 17229 || newState == COMPONENT_ENABLED_STATE_DISABLED 17230 || newState == COMPONENT_ENABLED_STATE_DISABLED_USER 17231 || newState == COMPONENT_ENABLED_STATE_DISABLED_UNTIL_USED)) { 17232 throw new IllegalArgumentException("Invalid new component state: " 17233 + newState); 17234 } 17235 PackageSetting pkgSetting; 17236 final int uid = Binder.getCallingUid(); 17237 final int permission; 17238 if (uid == Process.SYSTEM_UID) { 17239 permission = PackageManager.PERMISSION_GRANTED; 17240 } else { 17241 permission = mContext.checkCallingOrSelfPermission( 17242 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17243 } 17244 enforceCrossUserPermission(uid, userId, 17245 false /* requireFullPermission */, true /* checkShell */, "set enabled"); 17246 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17247 boolean sendNow = false; 17248 boolean isApp = (className == null); 17249 String componentName = isApp ? packageName : className; 17250 int packageUid = -1; 17251 ArrayList<String> components; 17252 17253 // writer 17254 synchronized (mPackages) { 17255 pkgSetting = mSettings.mPackages.get(packageName); 17256 if (pkgSetting == null) { 17257 if (className == null) { 17258 throw new IllegalArgumentException("Unknown package: " + packageName); 17259 } 17260 throw new IllegalArgumentException( 17261 "Unknown component: " + packageName + "/" + className); 17262 } 17263 // Allow root and verify that userId is not being specified by a different user 17264 if (!allowedByPermission && !UserHandle.isSameApp(uid, pkgSetting.appId)) { 17265 throw new SecurityException( 17266 "Permission Denial: attempt to change component state from pid=" 17267 + Binder.getCallingPid() 17268 + ", uid=" + uid + ", package uid=" + pkgSetting.appId); 17269 } 17270 if (className == null) { 17271 // We're dealing with an application/package level state change 17272 if (pkgSetting.getEnabled(userId) == newState) { 17273 // Nothing to do 17274 return; 17275 } 17276 if (newState == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT 17277 || newState == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) { 17278 // Don't care about who enables an app. 17279 callingPackage = null; 17280 } 17281 pkgSetting.setEnabled(newState, userId, callingPackage); 17282 // pkgSetting.pkg.mSetEnabled = newState; 17283 } else { 17284 // We're dealing with a component level state change 17285 // First, verify that this is a valid class name. 17286 PackageParser.Package pkg = pkgSetting.pkg; 17287 if (pkg == null || !pkg.hasComponentClassName(className)) { 17288 if (pkg != null && 17289 pkg.applicationInfo.targetSdkVersion >= 17290 Build.VERSION_CODES.JELLY_BEAN) { 17291 throw new IllegalArgumentException("Component class " + className 17292 + " does not exist in " + packageName); 17293 } else { 17294 Slog.w(TAG, "Failed setComponentEnabledSetting: component class " 17295 + className + " does not exist in " + packageName); 17296 } 17297 } 17298 switch (newState) { 17299 case COMPONENT_ENABLED_STATE_ENABLED: 17300 if (!pkgSetting.enableComponentLPw(className, userId)) { 17301 return; 17302 } 17303 break; 17304 case COMPONENT_ENABLED_STATE_DISABLED: 17305 if (!pkgSetting.disableComponentLPw(className, userId)) { 17306 return; 17307 } 17308 break; 17309 case COMPONENT_ENABLED_STATE_DEFAULT: 17310 if (!pkgSetting.restoreComponentLPw(className, userId)) { 17311 return; 17312 } 17313 break; 17314 default: 17315 Slog.e(TAG, "Invalid new component state: " + newState); 17316 return; 17317 } 17318 } 17319 scheduleWritePackageRestrictionsLocked(userId); 17320 components = mPendingBroadcasts.get(userId, packageName); 17321 final boolean newPackage = components == null; 17322 if (newPackage) { 17323 components = new ArrayList<String>(); 17324 } 17325 if (!components.contains(componentName)) { 17326 components.add(componentName); 17327 } 17328 if ((flags&PackageManager.DONT_KILL_APP) == 0) { 17329 sendNow = true; 17330 // Purge entry from pending broadcast list if another one exists already 17331 // since we are sending one right away. 17332 mPendingBroadcasts.remove(userId, packageName); 17333 } else { 17334 if (newPackage) { 17335 mPendingBroadcasts.put(userId, packageName, components); 17336 } 17337 if (!mHandler.hasMessages(SEND_PENDING_BROADCAST)) { 17338 // Schedule a message 17339 mHandler.sendEmptyMessageDelayed(SEND_PENDING_BROADCAST, BROADCAST_DELAY); 17340 } 17341 } 17342 } 17343 17344 long callingId = Binder.clearCallingIdentity(); 17345 try { 17346 if (sendNow) { 17347 packageUid = UserHandle.getUid(userId, pkgSetting.appId); 17348 sendPackageChangedBroadcast(packageName, 17349 (flags&PackageManager.DONT_KILL_APP) != 0, components, packageUid); 17350 } 17351 } finally { 17352 Binder.restoreCallingIdentity(callingId); 17353 } 17354 } 17355 17356 @Override 17357 public void flushPackageRestrictionsAsUser(int userId) { 17358 if (!sUserManager.exists(userId)) { 17359 return; 17360 } 17361 enforceCrossUserPermission(Binder.getCallingUid(), userId, false /* requireFullPermission*/, 17362 false /* checkShell */, "flushPackageRestrictions"); 17363 synchronized (mPackages) { 17364 mSettings.writePackageRestrictionsLPr(userId); 17365 mDirtyUsers.remove(userId); 17366 if (mDirtyUsers.isEmpty()) { 17367 mHandler.removeMessages(WRITE_PACKAGE_RESTRICTIONS); 17368 } 17369 } 17370 } 17371 17372 private void sendPackageChangedBroadcast(String packageName, 17373 boolean killFlag, ArrayList<String> componentNames, int packageUid) { 17374 if (DEBUG_INSTALL) 17375 Log.v(TAG, "Sending package changed: package=" + packageName + " components=" 17376 + componentNames); 17377 Bundle extras = new Bundle(4); 17378 extras.putString(Intent.EXTRA_CHANGED_COMPONENT_NAME, componentNames.get(0)); 17379 String nameList[] = new String[componentNames.size()]; 17380 componentNames.toArray(nameList); 17381 extras.putStringArray(Intent.EXTRA_CHANGED_COMPONENT_NAME_LIST, nameList); 17382 extras.putBoolean(Intent.EXTRA_DONT_KILL_APP, killFlag); 17383 extras.putInt(Intent.EXTRA_UID, packageUid); 17384 // If this is not reporting a change of the overall package, then only send it 17385 // to registered receivers. We don't want to launch a swath of apps for every 17386 // little component state change. 17387 final int flags = !componentNames.contains(packageName) 17388 ? Intent.FLAG_RECEIVER_REGISTERED_ONLY : 0; 17389 sendPackageBroadcast(Intent.ACTION_PACKAGE_CHANGED, packageName, extras, flags, null, null, 17390 new int[] {UserHandle.getUserId(packageUid)}); 17391 } 17392 17393 @Override 17394 public void setPackageStoppedState(String packageName, boolean stopped, int userId) { 17395 if (!sUserManager.exists(userId)) return; 17396 final int uid = Binder.getCallingUid(); 17397 final int permission = mContext.checkCallingOrSelfPermission( 17398 android.Manifest.permission.CHANGE_COMPONENT_ENABLED_STATE); 17399 final boolean allowedByPermission = (permission == PackageManager.PERMISSION_GRANTED); 17400 enforceCrossUserPermission(uid, userId, 17401 true /* requireFullPermission */, true /* checkShell */, "stop package"); 17402 // writer 17403 synchronized (mPackages) { 17404 if (mSettings.setPackageStoppedStateLPw(this, packageName, stopped, 17405 allowedByPermission, uid, userId)) { 17406 scheduleWritePackageRestrictionsLocked(userId); 17407 } 17408 } 17409 } 17410 17411 @Override 17412 public String getInstallerPackageName(String packageName) { 17413 // reader 17414 synchronized (mPackages) { 17415 return mSettings.getInstallerPackageNameLPr(packageName); 17416 } 17417 } 17418 17419 @Override 17420 public int getApplicationEnabledSetting(String packageName, int userId) { 17421 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17422 int uid = Binder.getCallingUid(); 17423 enforceCrossUserPermission(uid, userId, 17424 false /* requireFullPermission */, false /* checkShell */, "get enabled"); 17425 // reader 17426 synchronized (mPackages) { 17427 return mSettings.getApplicationEnabledSettingLPr(packageName, userId); 17428 } 17429 } 17430 17431 @Override 17432 public int getComponentEnabledSetting(ComponentName componentName, int userId) { 17433 if (!sUserManager.exists(userId)) return COMPONENT_ENABLED_STATE_DISABLED; 17434 int uid = Binder.getCallingUid(); 17435 enforceCrossUserPermission(uid, userId, 17436 false /* requireFullPermission */, false /* checkShell */, "get component enabled"); 17437 // reader 17438 synchronized (mPackages) { 17439 return mSettings.getComponentEnabledSettingLPr(componentName, userId); 17440 } 17441 } 17442 17443 @Override 17444 public void enterSafeMode() { 17445 enforceSystemOrRoot("Only the system can request entering safe mode"); 17446 17447 if (!mSystemReady) { 17448 mSafeMode = true; 17449 } 17450 } 17451 17452 @Override 17453 public void systemReady() { 17454 mSystemReady = true; 17455 17456 // Read the compatibilty setting when the system is ready. 17457 boolean compatibilityModeEnabled = android.provider.Settings.Global.getInt( 17458 mContext.getContentResolver(), 17459 android.provider.Settings.Global.COMPATIBILITY_MODE, 1) == 1; 17460 PackageParser.setCompatibilityModeEnabled(compatibilityModeEnabled); 17461 if (DEBUG_SETTINGS) { 17462 Log.d(TAG, "compatibility mode:" + compatibilityModeEnabled); 17463 } 17464 17465 int[] grantPermissionsUserIds = EMPTY_INT_ARRAY; 17466 17467 synchronized (mPackages) { 17468 // Verify that all of the preferred activity components actually 17469 // exist. It is possible for applications to be updated and at 17470 // that point remove a previously declared activity component that 17471 // had been set as a preferred activity. We try to clean this up 17472 // the next time we encounter that preferred activity, but it is 17473 // possible for the user flow to never be able to return to that 17474 // situation so here we do a sanity check to make sure we haven't 17475 // left any junk around. 17476 ArrayList<PreferredActivity> removed = new ArrayList<PreferredActivity>(); 17477 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 17478 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 17479 removed.clear(); 17480 for (PreferredActivity pa : pir.filterSet()) { 17481 if (mActivities.mActivities.get(pa.mPref.mComponent) == null) { 17482 removed.add(pa); 17483 } 17484 } 17485 if (removed.size() > 0) { 17486 for (int r=0; r<removed.size(); r++) { 17487 PreferredActivity pa = removed.get(r); 17488 Slog.w(TAG, "Removing dangling preferred activity: " 17489 + pa.mPref.mComponent); 17490 pir.removeFilter(pa); 17491 } 17492 mSettings.writePackageRestrictionsLPr( 17493 mSettings.mPreferredActivities.keyAt(i)); 17494 } 17495 } 17496 17497 for (int userId : UserManagerService.getInstance().getUserIds()) { 17498 if (!mSettings.areDefaultRuntimePermissionsGrantedLPr(userId)) { 17499 grantPermissionsUserIds = ArrayUtils.appendInt( 17500 grantPermissionsUserIds, userId); 17501 } 17502 } 17503 } 17504 sUserManager.systemReady(); 17505 17506 // If we upgraded grant all default permissions before kicking off. 17507 for (int userId : grantPermissionsUserIds) { 17508 mDefaultPermissionPolicy.grantDefaultPermissions(userId); 17509 } 17510 17511 // Kick off any messages waiting for system ready 17512 if (mPostSystemReadyMessages != null) { 17513 for (Message msg : mPostSystemReadyMessages) { 17514 msg.sendToTarget(); 17515 } 17516 mPostSystemReadyMessages = null; 17517 } 17518 17519 // Watch for external volumes that come and go over time 17520 final StorageManager storage = mContext.getSystemService(StorageManager.class); 17521 storage.registerListener(mStorageListener); 17522 17523 mInstallerService.systemReady(); 17524 mPackageDexOptimizer.systemReady(); 17525 17526 MountServiceInternal mountServiceInternal = LocalServices.getService( 17527 MountServiceInternal.class); 17528 mountServiceInternal.addExternalStoragePolicy( 17529 new MountServiceInternal.ExternalStorageMountPolicy() { 17530 @Override 17531 public int getMountMode(int uid, String packageName) { 17532 if (Process.isIsolated(uid)) { 17533 return Zygote.MOUNT_EXTERNAL_NONE; 17534 } 17535 if (checkUidPermission(WRITE_MEDIA_STORAGE, uid) == PERMISSION_GRANTED) { 17536 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17537 } 17538 if (checkUidPermission(READ_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17539 return Zygote.MOUNT_EXTERNAL_DEFAULT; 17540 } 17541 if (checkUidPermission(WRITE_EXTERNAL_STORAGE, uid) == PERMISSION_DENIED) { 17542 return Zygote.MOUNT_EXTERNAL_READ; 17543 } 17544 return Zygote.MOUNT_EXTERNAL_WRITE; 17545 } 17546 17547 @Override 17548 public boolean hasExternalStorage(int uid, String packageName) { 17549 return true; 17550 } 17551 }); 17552 17553 // Now that we're mostly running, clean up stale users and apps 17554 reconcileUsers(StorageManager.UUID_PRIVATE_INTERNAL); 17555 reconcileApps(StorageManager.UUID_PRIVATE_INTERNAL); 17556 } 17557 17558 @Override 17559 public boolean isSafeMode() { 17560 return mSafeMode; 17561 } 17562 17563 @Override 17564 public boolean hasSystemUidErrors() { 17565 return mHasSystemUidErrors; 17566 } 17567 17568 static String arrayToString(int[] array) { 17569 StringBuffer buf = new StringBuffer(128); 17570 buf.append('['); 17571 if (array != null) { 17572 for (int i=0; i<array.length; i++) { 17573 if (i > 0) buf.append(", "); 17574 buf.append(array[i]); 17575 } 17576 } 17577 buf.append(']'); 17578 return buf.toString(); 17579 } 17580 17581 static class DumpState { 17582 public static final int DUMP_LIBS = 1 << 0; 17583 public static final int DUMP_FEATURES = 1 << 1; 17584 public static final int DUMP_ACTIVITY_RESOLVERS = 1 << 2; 17585 public static final int DUMP_SERVICE_RESOLVERS = 1 << 3; 17586 public static final int DUMP_RECEIVER_RESOLVERS = 1 << 4; 17587 public static final int DUMP_CONTENT_RESOLVERS = 1 << 5; 17588 public static final int DUMP_PERMISSIONS = 1 << 6; 17589 public static final int DUMP_PACKAGES = 1 << 7; 17590 public static final int DUMP_SHARED_USERS = 1 << 8; 17591 public static final int DUMP_MESSAGES = 1 << 9; 17592 public static final int DUMP_PROVIDERS = 1 << 10; 17593 public static final int DUMP_VERIFIERS = 1 << 11; 17594 public static final int DUMP_PREFERRED = 1 << 12; 17595 public static final int DUMP_PREFERRED_XML = 1 << 13; 17596 public static final int DUMP_KEYSETS = 1 << 14; 17597 public static final int DUMP_VERSION = 1 << 15; 17598 public static final int DUMP_INSTALLS = 1 << 16; 17599 public static final int DUMP_INTENT_FILTER_VERIFIERS = 1 << 17; 17600 public static final int DUMP_DOMAIN_PREFERRED = 1 << 18; 17601 public static final int DUMP_FROZEN = 1 << 19; 17602 17603 public static final int OPTION_SHOW_FILTERS = 1 << 0; 17604 17605 private int mTypes; 17606 17607 private int mOptions; 17608 17609 private boolean mTitlePrinted; 17610 17611 private SharedUserSetting mSharedUser; 17612 17613 public boolean isDumping(int type) { 17614 if (mTypes == 0 && type != DUMP_PREFERRED_XML) { 17615 return true; 17616 } 17617 17618 return (mTypes & type) != 0; 17619 } 17620 17621 public void setDump(int type) { 17622 mTypes |= type; 17623 } 17624 17625 public boolean isOptionEnabled(int option) { 17626 return (mOptions & option) != 0; 17627 } 17628 17629 public void setOptionEnabled(int option) { 17630 mOptions |= option; 17631 } 17632 17633 public boolean onTitlePrinted() { 17634 final boolean printed = mTitlePrinted; 17635 mTitlePrinted = true; 17636 return printed; 17637 } 17638 17639 public boolean getTitlePrinted() { 17640 return mTitlePrinted; 17641 } 17642 17643 public void setTitlePrinted(boolean enabled) { 17644 mTitlePrinted = enabled; 17645 } 17646 17647 public SharedUserSetting getSharedUser() { 17648 return mSharedUser; 17649 } 17650 17651 public void setSharedUser(SharedUserSetting user) { 17652 mSharedUser = user; 17653 } 17654 } 17655 17656 @Override 17657 public void onShellCommand(FileDescriptor in, FileDescriptor out, 17658 FileDescriptor err, String[] args, ResultReceiver resultReceiver) { 17659 (new PackageManagerShellCommand(this)).exec( 17660 this, in, out, err, args, resultReceiver); 17661 } 17662 17663 @Override 17664 protected void dump(FileDescriptor fd, PrintWriter pw, String[] args) { 17665 if (mContext.checkCallingOrSelfPermission(android.Manifest.permission.DUMP) 17666 != PackageManager.PERMISSION_GRANTED) { 17667 pw.println("Permission Denial: can't dump ActivityManager from from pid=" 17668 + Binder.getCallingPid() 17669 + ", uid=" + Binder.getCallingUid() 17670 + " without permission " 17671 + android.Manifest.permission.DUMP); 17672 return; 17673 } 17674 17675 DumpState dumpState = new DumpState(); 17676 boolean fullPreferred = false; 17677 boolean checkin = false; 17678 17679 String packageName = null; 17680 ArraySet<String> permissionNames = null; 17681 17682 int opti = 0; 17683 while (opti < args.length) { 17684 String opt = args[opti]; 17685 if (opt == null || opt.length() <= 0 || opt.charAt(0) != '-') { 17686 break; 17687 } 17688 opti++; 17689 17690 if ("-a".equals(opt)) { 17691 // Right now we only know how to print all. 17692 } else if ("-h".equals(opt)) { 17693 pw.println("Package manager dump options:"); 17694 pw.println(" [-h] [-f] [--checkin] [cmd] ..."); 17695 pw.println(" --checkin: dump for a checkin"); 17696 pw.println(" -f: print details of intent filters"); 17697 pw.println(" -h: print this help"); 17698 pw.println(" cmd may be one of:"); 17699 pw.println(" l[ibraries]: list known shared libraries"); 17700 pw.println(" f[eatures]: list device features"); 17701 pw.println(" k[eysets]: print known keysets"); 17702 pw.println(" r[esolvers] [activity|service|receiver|content]: dump intent resolvers"); 17703 pw.println(" perm[issions]: dump permissions"); 17704 pw.println(" permission [name ...]: dump declaration and use of given permission"); 17705 pw.println(" pref[erred]: print preferred package settings"); 17706 pw.println(" preferred-xml [--full]: print preferred package settings as xml"); 17707 pw.println(" prov[iders]: dump content providers"); 17708 pw.println(" p[ackages]: dump installed packages"); 17709 pw.println(" s[hared-users]: dump shared user IDs"); 17710 pw.println(" m[essages]: print collected runtime messages"); 17711 pw.println(" v[erifiers]: print package verifier info"); 17712 pw.println(" d[omain-preferred-apps]: print domains preferred apps"); 17713 pw.println(" i[ntent-filter-verifiers]|ifv: print intent filter verifier info"); 17714 pw.println(" version: print database version info"); 17715 pw.println(" write: write current settings now"); 17716 pw.println(" installs: details about install sessions"); 17717 pw.println(" check-permission <permission> <package> [<user>]: does pkg hold perm?"); 17718 pw.println(" <package.name>: info about given package"); 17719 return; 17720 } else if ("--checkin".equals(opt)) { 17721 checkin = true; 17722 } else if ("-f".equals(opt)) { 17723 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17724 } else { 17725 pw.println("Unknown argument: " + opt + "; use -h for help"); 17726 } 17727 } 17728 17729 // Is the caller requesting to dump a particular piece of data? 17730 if (opti < args.length) { 17731 String cmd = args[opti]; 17732 opti++; 17733 // Is this a package name? 17734 if ("android".equals(cmd) || cmd.contains(".")) { 17735 packageName = cmd; 17736 // When dumping a single package, we always dump all of its 17737 // filter information since the amount of data will be reasonable. 17738 dumpState.setOptionEnabled(DumpState.OPTION_SHOW_FILTERS); 17739 } else if ("check-permission".equals(cmd)) { 17740 if (opti >= args.length) { 17741 pw.println("Error: check-permission missing permission argument"); 17742 return; 17743 } 17744 String perm = args[opti]; 17745 opti++; 17746 if (opti >= args.length) { 17747 pw.println("Error: check-permission missing package argument"); 17748 return; 17749 } 17750 String pkg = args[opti]; 17751 opti++; 17752 int user = UserHandle.getUserId(Binder.getCallingUid()); 17753 if (opti < args.length) { 17754 try { 17755 user = Integer.parseInt(args[opti]); 17756 } catch (NumberFormatException e) { 17757 pw.println("Error: check-permission user argument is not a number: " 17758 + args[opti]); 17759 return; 17760 } 17761 } 17762 pw.println(checkPermission(perm, pkg, user)); 17763 return; 17764 } else if ("l".equals(cmd) || "libraries".equals(cmd)) { 17765 dumpState.setDump(DumpState.DUMP_LIBS); 17766 } else if ("f".equals(cmd) || "features".equals(cmd)) { 17767 dumpState.setDump(DumpState.DUMP_FEATURES); 17768 } else if ("r".equals(cmd) || "resolvers".equals(cmd)) { 17769 if (opti >= args.length) { 17770 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS 17771 | DumpState.DUMP_SERVICE_RESOLVERS 17772 | DumpState.DUMP_RECEIVER_RESOLVERS 17773 | DumpState.DUMP_CONTENT_RESOLVERS); 17774 } else { 17775 while (opti < args.length) { 17776 String name = args[opti]; 17777 if ("a".equals(name) || "activity".equals(name)) { 17778 dumpState.setDump(DumpState.DUMP_ACTIVITY_RESOLVERS); 17779 } else if ("s".equals(name) || "service".equals(name)) { 17780 dumpState.setDump(DumpState.DUMP_SERVICE_RESOLVERS); 17781 } else if ("r".equals(name) || "receiver".equals(name)) { 17782 dumpState.setDump(DumpState.DUMP_RECEIVER_RESOLVERS); 17783 } else if ("c".equals(name) || "content".equals(name)) { 17784 dumpState.setDump(DumpState.DUMP_CONTENT_RESOLVERS); 17785 } else { 17786 pw.println("Error: unknown resolver table type: " + name); 17787 return; 17788 } 17789 opti++; 17790 } 17791 } 17792 } else if ("perm".equals(cmd) || "permissions".equals(cmd)) { 17793 dumpState.setDump(DumpState.DUMP_PERMISSIONS); 17794 } else if ("permission".equals(cmd)) { 17795 if (opti >= args.length) { 17796 pw.println("Error: permission requires permission name"); 17797 return; 17798 } 17799 permissionNames = new ArraySet<>(); 17800 while (opti < args.length) { 17801 permissionNames.add(args[opti]); 17802 opti++; 17803 } 17804 dumpState.setDump(DumpState.DUMP_PERMISSIONS 17805 | DumpState.DUMP_PACKAGES | DumpState.DUMP_SHARED_USERS); 17806 } else if ("pref".equals(cmd) || "preferred".equals(cmd)) { 17807 dumpState.setDump(DumpState.DUMP_PREFERRED); 17808 } else if ("preferred-xml".equals(cmd)) { 17809 dumpState.setDump(DumpState.DUMP_PREFERRED_XML); 17810 if (opti < args.length && "--full".equals(args[opti])) { 17811 fullPreferred = true; 17812 opti++; 17813 } 17814 } else if ("d".equals(cmd) || "domain-preferred-apps".equals(cmd)) { 17815 dumpState.setDump(DumpState.DUMP_DOMAIN_PREFERRED); 17816 } else if ("p".equals(cmd) || "packages".equals(cmd)) { 17817 dumpState.setDump(DumpState.DUMP_PACKAGES); 17818 } else if ("s".equals(cmd) || "shared-users".equals(cmd)) { 17819 dumpState.setDump(DumpState.DUMP_SHARED_USERS); 17820 } else if ("prov".equals(cmd) || "providers".equals(cmd)) { 17821 dumpState.setDump(DumpState.DUMP_PROVIDERS); 17822 } else if ("m".equals(cmd) || "messages".equals(cmd)) { 17823 dumpState.setDump(DumpState.DUMP_MESSAGES); 17824 } else if ("v".equals(cmd) || "verifiers".equals(cmd)) { 17825 dumpState.setDump(DumpState.DUMP_VERIFIERS); 17826 } else if ("i".equals(cmd) || "ifv".equals(cmd) 17827 || "intent-filter-verifiers".equals(cmd)) { 17828 dumpState.setDump(DumpState.DUMP_INTENT_FILTER_VERIFIERS); 17829 } else if ("version".equals(cmd)) { 17830 dumpState.setDump(DumpState.DUMP_VERSION); 17831 } else if ("k".equals(cmd) || "keysets".equals(cmd)) { 17832 dumpState.setDump(DumpState.DUMP_KEYSETS); 17833 } else if ("installs".equals(cmd)) { 17834 dumpState.setDump(DumpState.DUMP_INSTALLS); 17835 } else if ("frozen".equals(cmd)) { 17836 dumpState.setDump(DumpState.DUMP_FROZEN); 17837 } else if ("write".equals(cmd)) { 17838 synchronized (mPackages) { 17839 mSettings.writeLPr(); 17840 pw.println("Settings written."); 17841 return; 17842 } 17843 } 17844 } 17845 17846 if (checkin) { 17847 pw.println("vers,1"); 17848 } 17849 17850 // reader 17851 synchronized (mPackages) { 17852 if (dumpState.isDumping(DumpState.DUMP_VERSION) && packageName == null) { 17853 if (!checkin) { 17854 if (dumpState.onTitlePrinted()) 17855 pw.println(); 17856 pw.println("Database versions:"); 17857 mSettings.dumpVersionLPr(new IndentingPrintWriter(pw, " ")); 17858 } 17859 } 17860 17861 if (dumpState.isDumping(DumpState.DUMP_VERIFIERS) && packageName == null) { 17862 if (!checkin) { 17863 if (dumpState.onTitlePrinted()) 17864 pw.println(); 17865 pw.println("Verifiers:"); 17866 pw.print(" Required: "); 17867 pw.print(mRequiredVerifierPackage); 17868 pw.print(" (uid="); 17869 pw.print(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17870 UserHandle.USER_SYSTEM)); 17871 pw.println(")"); 17872 } else if (mRequiredVerifierPackage != null) { 17873 pw.print("vrfy,"); pw.print(mRequiredVerifierPackage); 17874 pw.print(","); 17875 pw.println(getPackageUid(mRequiredVerifierPackage, MATCH_DEBUG_TRIAGED_MISSING, 17876 UserHandle.USER_SYSTEM)); 17877 } 17878 } 17879 17880 if (dumpState.isDumping(DumpState.DUMP_INTENT_FILTER_VERIFIERS) && 17881 packageName == null) { 17882 if (mIntentFilterVerifierComponent != null) { 17883 String verifierPackageName = mIntentFilterVerifierComponent.getPackageName(); 17884 if (!checkin) { 17885 if (dumpState.onTitlePrinted()) 17886 pw.println(); 17887 pw.println("Intent Filter Verifier:"); 17888 pw.print(" Using: "); 17889 pw.print(verifierPackageName); 17890 pw.print(" (uid="); 17891 pw.print(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17892 UserHandle.USER_SYSTEM)); 17893 pw.println(")"); 17894 } else if (verifierPackageName != null) { 17895 pw.print("ifv,"); pw.print(verifierPackageName); 17896 pw.print(","); 17897 pw.println(getPackageUid(verifierPackageName, MATCH_DEBUG_TRIAGED_MISSING, 17898 UserHandle.USER_SYSTEM)); 17899 } 17900 } else { 17901 pw.println(); 17902 pw.println("No Intent Filter Verifier available!"); 17903 } 17904 } 17905 17906 if (dumpState.isDumping(DumpState.DUMP_LIBS) && packageName == null) { 17907 boolean printedHeader = false; 17908 final Iterator<String> it = mSharedLibraries.keySet().iterator(); 17909 while (it.hasNext()) { 17910 String name = it.next(); 17911 SharedLibraryEntry ent = mSharedLibraries.get(name); 17912 if (!checkin) { 17913 if (!printedHeader) { 17914 if (dumpState.onTitlePrinted()) 17915 pw.println(); 17916 pw.println("Libraries:"); 17917 printedHeader = true; 17918 } 17919 pw.print(" "); 17920 } else { 17921 pw.print("lib,"); 17922 } 17923 pw.print(name); 17924 if (!checkin) { 17925 pw.print(" -> "); 17926 } 17927 if (ent.path != null) { 17928 if (!checkin) { 17929 pw.print("(jar) "); 17930 pw.print(ent.path); 17931 } else { 17932 pw.print(",jar,"); 17933 pw.print(ent.path); 17934 } 17935 } else { 17936 if (!checkin) { 17937 pw.print("(apk) "); 17938 pw.print(ent.apk); 17939 } else { 17940 pw.print(",apk,"); 17941 pw.print(ent.apk); 17942 } 17943 } 17944 pw.println(); 17945 } 17946 } 17947 17948 if (dumpState.isDumping(DumpState.DUMP_FEATURES) && packageName == null) { 17949 if (dumpState.onTitlePrinted()) 17950 pw.println(); 17951 if (!checkin) { 17952 pw.println("Features:"); 17953 } 17954 17955 for (FeatureInfo feat : mAvailableFeatures.values()) { 17956 if (checkin) { 17957 pw.print("feat,"); 17958 pw.print(feat.name); 17959 pw.print(","); 17960 pw.println(feat.version); 17961 } else { 17962 pw.print(" "); 17963 pw.print(feat.name); 17964 if (feat.version > 0) { 17965 pw.print(" version="); 17966 pw.print(feat.version); 17967 } 17968 pw.println(); 17969 } 17970 } 17971 } 17972 17973 if (!checkin && dumpState.isDumping(DumpState.DUMP_ACTIVITY_RESOLVERS)) { 17974 if (mActivities.dump(pw, dumpState.getTitlePrinted() ? "\nActivity Resolver Table:" 17975 : "Activity Resolver Table:", " ", packageName, 17976 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17977 dumpState.setTitlePrinted(true); 17978 } 17979 } 17980 if (!checkin && dumpState.isDumping(DumpState.DUMP_RECEIVER_RESOLVERS)) { 17981 if (mReceivers.dump(pw, dumpState.getTitlePrinted() ? "\nReceiver Resolver Table:" 17982 : "Receiver Resolver Table:", " ", packageName, 17983 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17984 dumpState.setTitlePrinted(true); 17985 } 17986 } 17987 if (!checkin && dumpState.isDumping(DumpState.DUMP_SERVICE_RESOLVERS)) { 17988 if (mServices.dump(pw, dumpState.getTitlePrinted() ? "\nService Resolver Table:" 17989 : "Service Resolver Table:", " ", packageName, 17990 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17991 dumpState.setTitlePrinted(true); 17992 } 17993 } 17994 if (!checkin && dumpState.isDumping(DumpState.DUMP_CONTENT_RESOLVERS)) { 17995 if (mProviders.dump(pw, dumpState.getTitlePrinted() ? "\nProvider Resolver Table:" 17996 : "Provider Resolver Table:", " ", packageName, 17997 dumpState.isOptionEnabled(DumpState.OPTION_SHOW_FILTERS), true)) { 17998 dumpState.setTitlePrinted(true); 17999 } 18000 } 18001 18002 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED)) { 18003 for (int i=0; i<mSettings.mPreferredActivities.size(); i++) { 18004 PreferredIntentResolver pir = mSettings.mPreferredActivities.valueAt(i); 18005 int user = mSettings.mPreferredActivities.keyAt(i); 18006 if (pir.dump(pw, 18007 dumpState.getTitlePrinted() 18008 ? "\nPreferred Activities User " + user + ":" 18009 : "Preferred Activities User " + user + ":", " ", 18010 packageName, true, false)) { 18011 dumpState.setTitlePrinted(true); 18012 } 18013 } 18014 } 18015 18016 if (!checkin && dumpState.isDumping(DumpState.DUMP_PREFERRED_XML)) { 18017 pw.flush(); 18018 FileOutputStream fout = new FileOutputStream(fd); 18019 BufferedOutputStream str = new BufferedOutputStream(fout); 18020 XmlSerializer serializer = new FastXmlSerializer(); 18021 try { 18022 serializer.setOutput(str, StandardCharsets.UTF_8.name()); 18023 serializer.startDocument(null, true); 18024 serializer.setFeature( 18025 "http://xmlpull.org/v1/doc/features.html#indent-output", true); 18026 mSettings.writePreferredActivitiesLPr(serializer, 0, fullPreferred); 18027 serializer.endDocument(); 18028 serializer.flush(); 18029 } catch (IllegalArgumentException e) { 18030 pw.println("Failed writing: " + e); 18031 } catch (IllegalStateException e) { 18032 pw.println("Failed writing: " + e); 18033 } catch (IOException e) { 18034 pw.println("Failed writing: " + e); 18035 } 18036 } 18037 18038 if (!checkin 18039 && dumpState.isDumping(DumpState.DUMP_DOMAIN_PREFERRED) 18040 && packageName == null) { 18041 pw.println(); 18042 int count = mSettings.mPackages.size(); 18043 if (count == 0) { 18044 pw.println("No applications!"); 18045 pw.println(); 18046 } else { 18047 final String prefix = " "; 18048 Collection<PackageSetting> allPackageSettings = mSettings.mPackages.values(); 18049 if (allPackageSettings.size() == 0) { 18050 pw.println("No domain preferred apps!"); 18051 pw.println(); 18052 } else { 18053 pw.println("App verification status:"); 18054 pw.println(); 18055 count = 0; 18056 for (PackageSetting ps : allPackageSettings) { 18057 IntentFilterVerificationInfo ivi = ps.getIntentFilterVerificationInfo(); 18058 if (ivi == null || ivi.getPackageName() == null) continue; 18059 pw.println(prefix + "Package: " + ivi.getPackageName()); 18060 pw.println(prefix + "Domains: " + ivi.getDomainsString()); 18061 pw.println(prefix + "Status: " + ivi.getStatusString()); 18062 pw.println(); 18063 count++; 18064 } 18065 if (count == 0) { 18066 pw.println(prefix + "No app verification established."); 18067 pw.println(); 18068 } 18069 for (int userId : sUserManager.getUserIds()) { 18070 pw.println("App linkages for user " + userId + ":"); 18071 pw.println(); 18072 count = 0; 18073 for (PackageSetting ps : allPackageSettings) { 18074 final long status = ps.getDomainVerificationStatusForUser(userId); 18075 if (status >> 32 == INTENT_FILTER_DOMAIN_VERIFICATION_STATUS_UNDEFINED) { 18076 continue; 18077 } 18078 pw.println(prefix + "Package: " + ps.name); 18079 pw.println(prefix + "Domains: " + dumpDomainString(ps.name)); 18080 String statusStr = IntentFilterVerificationInfo. 18081 getStatusStringFromValue(status); 18082 pw.println(prefix + "Status: " + statusStr); 18083 pw.println(); 18084 count++; 18085 } 18086 if (count == 0) { 18087 pw.println(prefix + "No configured app linkages."); 18088 pw.println(); 18089 } 18090 } 18091 } 18092 } 18093 } 18094 18095 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS)) { 18096 mSettings.dumpPermissionsLPr(pw, packageName, permissionNames, dumpState); 18097 if (packageName == null && permissionNames == null) { 18098 for (int iperm=0; iperm<mAppOpPermissionPackages.size(); iperm++) { 18099 if (iperm == 0) { 18100 if (dumpState.onTitlePrinted()) 18101 pw.println(); 18102 pw.println("AppOp Permissions:"); 18103 } 18104 pw.print(" AppOp Permission "); 18105 pw.print(mAppOpPermissionPackages.keyAt(iperm)); 18106 pw.println(":"); 18107 ArraySet<String> pkgs = mAppOpPermissionPackages.valueAt(iperm); 18108 for (int ipkg=0; ipkg<pkgs.size(); ipkg++) { 18109 pw.print(" "); pw.println(pkgs.valueAt(ipkg)); 18110 } 18111 } 18112 } 18113 } 18114 18115 if (!checkin && dumpState.isDumping(DumpState.DUMP_PROVIDERS)) { 18116 boolean printedSomething = false; 18117 for (PackageParser.Provider p : mProviders.mProviders.values()) { 18118 if (packageName != null && !packageName.equals(p.info.packageName)) { 18119 continue; 18120 } 18121 if (!printedSomething) { 18122 if (dumpState.onTitlePrinted()) 18123 pw.println(); 18124 pw.println("Registered ContentProviders:"); 18125 printedSomething = true; 18126 } 18127 pw.print(" "); p.printComponentShortName(pw); pw.println(":"); 18128 pw.print(" "); pw.println(p.toString()); 18129 } 18130 printedSomething = false; 18131 for (Map.Entry<String, PackageParser.Provider> entry : 18132 mProvidersByAuthority.entrySet()) { 18133 PackageParser.Provider p = entry.getValue(); 18134 if (packageName != null && !packageName.equals(p.info.packageName)) { 18135 continue; 18136 } 18137 if (!printedSomething) { 18138 if (dumpState.onTitlePrinted()) 18139 pw.println(); 18140 pw.println("ContentProvider Authorities:"); 18141 printedSomething = true; 18142 } 18143 pw.print(" ["); pw.print(entry.getKey()); pw.println("]:"); 18144 pw.print(" "); pw.println(p.toString()); 18145 if (p.info != null && p.info.applicationInfo != null) { 18146 final String appInfo = p.info.applicationInfo.toString(); 18147 pw.print(" applicationInfo="); pw.println(appInfo); 18148 } 18149 } 18150 } 18151 18152 if (!checkin && dumpState.isDumping(DumpState.DUMP_KEYSETS)) { 18153 mSettings.mKeySetManagerService.dumpLPr(pw, packageName, dumpState); 18154 } 18155 18156 if (dumpState.isDumping(DumpState.DUMP_PACKAGES)) { 18157 mSettings.dumpPackagesLPr(pw, packageName, permissionNames, dumpState, checkin); 18158 } 18159 18160 if (dumpState.isDumping(DumpState.DUMP_SHARED_USERS)) { 18161 mSettings.dumpSharedUsersLPr(pw, packageName, permissionNames, dumpState, checkin); 18162 } 18163 18164 if (!checkin && dumpState.isDumping(DumpState.DUMP_PERMISSIONS) && packageName == null) { 18165 mSettings.dumpRestoredPermissionGrantsLPr(pw, dumpState); 18166 } 18167 18168 if (!checkin && dumpState.isDumping(DumpState.DUMP_INSTALLS) && packageName == null) { 18169 // XXX should handle packageName != null by dumping only install data that 18170 // the given package is involved with. 18171 if (dumpState.onTitlePrinted()) pw.println(); 18172 mInstallerService.dump(new IndentingPrintWriter(pw, " ", 120)); 18173 } 18174 18175 if (!checkin && dumpState.isDumping(DumpState.DUMP_FROZEN) && packageName == null) { 18176 // XXX should handle packageName != null by dumping only install data that 18177 // the given package is involved with. 18178 if (dumpState.onTitlePrinted()) pw.println(); 18179 18180 final IndentingPrintWriter ipw = new IndentingPrintWriter(pw, " ", 120); 18181 ipw.println(); 18182 ipw.println("Frozen packages:"); 18183 ipw.increaseIndent(); 18184 if (mFrozenPackages.size() == 0) { 18185 ipw.println("(none)"); 18186 } else { 18187 for (int i = 0; i < mFrozenPackages.size(); i++) { 18188 ipw.println(mFrozenPackages.valueAt(i)); 18189 } 18190 } 18191 ipw.decreaseIndent(); 18192 } 18193 18194 if (!checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES) && packageName == null) { 18195 if (dumpState.onTitlePrinted()) pw.println(); 18196 mSettings.dumpReadMessagesLPr(pw, dumpState); 18197 18198 pw.println(); 18199 pw.println("Package warning messages:"); 18200 BufferedReader in = null; 18201 String line = null; 18202 try { 18203 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18204 while ((line = in.readLine()) != null) { 18205 if (line.contains("ignored: updated version")) continue; 18206 pw.println(line); 18207 } 18208 } catch (IOException ignored) { 18209 } finally { 18210 IoUtils.closeQuietly(in); 18211 } 18212 } 18213 18214 if (checkin && dumpState.isDumping(DumpState.DUMP_MESSAGES)) { 18215 BufferedReader in = null; 18216 String line = null; 18217 try { 18218 in = new BufferedReader(new FileReader(getSettingsProblemFile())); 18219 while ((line = in.readLine()) != null) { 18220 if (line.contains("ignored: updated version")) continue; 18221 pw.print("msg,"); 18222 pw.println(line); 18223 } 18224 } catch (IOException ignored) { 18225 } finally { 18226 IoUtils.closeQuietly(in); 18227 } 18228 } 18229 } 18230 } 18231 18232 private String dumpDomainString(String packageName) { 18233 List<IntentFilterVerificationInfo> iviList = getIntentFilterVerifications(packageName) 18234 .getList(); 18235 List<IntentFilter> filters = getAllIntentFilters(packageName).getList(); 18236 18237 ArraySet<String> result = new ArraySet<>(); 18238 if (iviList.size() > 0) { 18239 for (IntentFilterVerificationInfo ivi : iviList) { 18240 for (String host : ivi.getDomains()) { 18241 result.add(host); 18242 } 18243 } 18244 } 18245 if (filters != null && filters.size() > 0) { 18246 for (IntentFilter filter : filters) { 18247 if (filter.hasCategory(Intent.CATEGORY_BROWSABLE) 18248 && (filter.hasDataScheme(IntentFilter.SCHEME_HTTP) || 18249 filter.hasDataScheme(IntentFilter.SCHEME_HTTPS))) { 18250 result.addAll(filter.getHostsList()); 18251 } 18252 } 18253 } 18254 18255 StringBuilder sb = new StringBuilder(result.size() * 16); 18256 for (String domain : result) { 18257 if (sb.length() > 0) sb.append(" "); 18258 sb.append(domain); 18259 } 18260 return sb.toString(); 18261 } 18262 18263 // ------- apps on sdcard specific code ------- 18264 static final boolean DEBUG_SD_INSTALL = false; 18265 18266 private static final String SD_ENCRYPTION_KEYSTORE_NAME = "AppsOnSD"; 18267 18268 private static final String SD_ENCRYPTION_ALGORITHM = "AES"; 18269 18270 private boolean mMediaMounted = false; 18271 18272 static String getEncryptKey() { 18273 try { 18274 String sdEncKey = SystemKeyStore.getInstance().retrieveKeyHexString( 18275 SD_ENCRYPTION_KEYSTORE_NAME); 18276 if (sdEncKey == null) { 18277 sdEncKey = SystemKeyStore.getInstance().generateNewKeyHexString(128, 18278 SD_ENCRYPTION_ALGORITHM, SD_ENCRYPTION_KEYSTORE_NAME); 18279 if (sdEncKey == null) { 18280 Slog.e(TAG, "Failed to create encryption keys"); 18281 return null; 18282 } 18283 } 18284 return sdEncKey; 18285 } catch (NoSuchAlgorithmException nsae) { 18286 Slog.e(TAG, "Failed to create encryption keys with exception: " + nsae); 18287 return null; 18288 } catch (IOException ioe) { 18289 Slog.e(TAG, "Failed to retrieve encryption keys with exception: " + ioe); 18290 return null; 18291 } 18292 } 18293 18294 /* 18295 * Update media status on PackageManager. 18296 */ 18297 @Override 18298 public void updateExternalMediaStatus(final boolean mediaStatus, final boolean reportStatus) { 18299 int callingUid = Binder.getCallingUid(); 18300 if (callingUid != 0 && callingUid != Process.SYSTEM_UID) { 18301 throw new SecurityException("Media status can only be updated by the system"); 18302 } 18303 // reader; this apparently protects mMediaMounted, but should probably 18304 // be a different lock in that case. 18305 synchronized (mPackages) { 18306 Log.i(TAG, "Updating external media status from " 18307 + (mMediaMounted ? "mounted" : "unmounted") + " to " 18308 + (mediaStatus ? "mounted" : "unmounted")); 18309 if (DEBUG_SD_INSTALL) 18310 Log.i(TAG, "updateExternalMediaStatus:: mediaStatus=" + mediaStatus 18311 + ", mMediaMounted=" + mMediaMounted); 18312 if (mediaStatus == mMediaMounted) { 18313 final Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 18314 : 0, -1); 18315 mHandler.sendMessage(msg); 18316 return; 18317 } 18318 mMediaMounted = mediaStatus; 18319 } 18320 // Queue up an async operation since the package installation may take a 18321 // little while. 18322 mHandler.post(new Runnable() { 18323 public void run() { 18324 updateExternalMediaStatusInner(mediaStatus, reportStatus, true); 18325 } 18326 }); 18327 } 18328 18329 /** 18330 * Called by MountService when the initial ASECs to scan are available. 18331 * Should block until all the ASEC containers are finished being scanned. 18332 */ 18333 public void scanAvailableAsecs() { 18334 updateExternalMediaStatusInner(true, false, false); 18335 } 18336 18337 /* 18338 * Collect information of applications on external media, map them against 18339 * existing containers and update information based on current mount status. 18340 * Please note that we always have to report status if reportStatus has been 18341 * set to true especially when unloading packages. 18342 */ 18343 private void updateExternalMediaStatusInner(boolean isMounted, boolean reportStatus, 18344 boolean externalStorage) { 18345 ArrayMap<AsecInstallArgs, String> processCids = new ArrayMap<>(); 18346 int[] uidArr = EmptyArray.INT; 18347 18348 final String[] list = PackageHelper.getSecureContainerList(); 18349 if (ArrayUtils.isEmpty(list)) { 18350 Log.i(TAG, "No secure containers found"); 18351 } else { 18352 // Process list of secure containers and categorize them 18353 // as active or stale based on their package internal state. 18354 18355 // reader 18356 synchronized (mPackages) { 18357 for (String cid : list) { 18358 // Leave stages untouched for now; installer service owns them 18359 if (PackageInstallerService.isStageName(cid)) continue; 18360 18361 if (DEBUG_SD_INSTALL) 18362 Log.i(TAG, "Processing container " + cid); 18363 String pkgName = getAsecPackageName(cid); 18364 if (pkgName == null) { 18365 Slog.i(TAG, "Found stale container " + cid + " with no package name"); 18366 continue; 18367 } 18368 if (DEBUG_SD_INSTALL) 18369 Log.i(TAG, "Looking for pkg : " + pkgName); 18370 18371 final PackageSetting ps = mSettings.mPackages.get(pkgName); 18372 if (ps == null) { 18373 Slog.i(TAG, "Found stale container " + cid + " with no matching settings"); 18374 continue; 18375 } 18376 18377 /* 18378 * Skip packages that are not external if we're unmounting 18379 * external storage. 18380 */ 18381 if (externalStorage && !isMounted && !isExternal(ps)) { 18382 continue; 18383 } 18384 18385 final AsecInstallArgs args = new AsecInstallArgs(cid, 18386 getAppDexInstructionSets(ps), ps.isForwardLocked()); 18387 // The package status is changed only if the code path 18388 // matches between settings and the container id. 18389 if (ps.codePathString != null 18390 && ps.codePathString.startsWith(args.getCodePath())) { 18391 if (DEBUG_SD_INSTALL) { 18392 Log.i(TAG, "Container : " + cid + " corresponds to pkg : " + pkgName 18393 + " at code path: " + ps.codePathString); 18394 } 18395 18396 // We do have a valid package installed on sdcard 18397 processCids.put(args, ps.codePathString); 18398 final int uid = ps.appId; 18399 if (uid != -1) { 18400 uidArr = ArrayUtils.appendInt(uidArr, uid); 18401 } 18402 } else { 18403 Slog.i(TAG, "Found stale container " + cid + ": expected codePath=" 18404 + ps.codePathString); 18405 } 18406 } 18407 } 18408 18409 Arrays.sort(uidArr); 18410 } 18411 18412 // Process packages with valid entries. 18413 if (isMounted) { 18414 if (DEBUG_SD_INSTALL) 18415 Log.i(TAG, "Loading packages"); 18416 loadMediaPackages(processCids, uidArr, externalStorage); 18417 startCleaningPackages(); 18418 mInstallerService.onSecureContainersAvailable(); 18419 } else { 18420 if (DEBUG_SD_INSTALL) 18421 Log.i(TAG, "Unloading packages"); 18422 unloadMediaPackages(processCids, uidArr, reportStatus); 18423 } 18424 } 18425 18426 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18427 ArrayList<ApplicationInfo> infos, IIntentReceiver finishedReceiver) { 18428 final int size = infos.size(); 18429 final String[] packageNames = new String[size]; 18430 final int[] packageUids = new int[size]; 18431 for (int i = 0; i < size; i++) { 18432 final ApplicationInfo info = infos.get(i); 18433 packageNames[i] = info.packageName; 18434 packageUids[i] = info.uid; 18435 } 18436 sendResourcesChangedBroadcast(mediaStatus, replacing, packageNames, packageUids, 18437 finishedReceiver); 18438 } 18439 18440 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18441 ArrayList<String> pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18442 sendResourcesChangedBroadcast(mediaStatus, replacing, 18443 pkgList.toArray(new String[pkgList.size()]), uidArr, finishedReceiver); 18444 } 18445 18446 private void sendResourcesChangedBroadcast(boolean mediaStatus, boolean replacing, 18447 String[] pkgList, int uidArr[], IIntentReceiver finishedReceiver) { 18448 int size = pkgList.length; 18449 if (size > 0) { 18450 // Send broadcasts here 18451 Bundle extras = new Bundle(); 18452 extras.putStringArray(Intent.EXTRA_CHANGED_PACKAGE_LIST, pkgList); 18453 if (uidArr != null) { 18454 extras.putIntArray(Intent.EXTRA_CHANGED_UID_LIST, uidArr); 18455 } 18456 if (replacing) { 18457 extras.putBoolean(Intent.EXTRA_REPLACING, replacing); 18458 } 18459 String action = mediaStatus ? Intent.ACTION_EXTERNAL_APPLICATIONS_AVAILABLE 18460 : Intent.ACTION_EXTERNAL_APPLICATIONS_UNAVAILABLE; 18461 sendPackageBroadcast(action, null, extras, 0, null, finishedReceiver, null); 18462 } 18463 } 18464 18465 /* 18466 * Look at potentially valid container ids from processCids If package 18467 * information doesn't match the one on record or package scanning fails, 18468 * the cid is added to list of removeCids. We currently don't delete stale 18469 * containers. 18470 */ 18471 private void loadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int[] uidArr, 18472 boolean externalStorage) { 18473 ArrayList<String> pkgList = new ArrayList<String>(); 18474 Set<AsecInstallArgs> keys = processCids.keySet(); 18475 18476 for (AsecInstallArgs args : keys) { 18477 String codePath = processCids.get(args); 18478 if (DEBUG_SD_INSTALL) 18479 Log.i(TAG, "Loading container : " + args.cid); 18480 int retCode = PackageManager.INSTALL_FAILED_CONTAINER_ERROR; 18481 try { 18482 // Make sure there are no container errors first. 18483 if (args.doPreInstall(PackageManager.INSTALL_SUCCEEDED) != PackageManager.INSTALL_SUCCEEDED) { 18484 Slog.e(TAG, "Failed to mount cid : " + args.cid 18485 + " when installing from sdcard"); 18486 continue; 18487 } 18488 // Check code path here. 18489 if (codePath == null || !codePath.startsWith(args.getCodePath())) { 18490 Slog.e(TAG, "Container " + args.cid + " cachepath " + args.getCodePath() 18491 + " does not match one in settings " + codePath); 18492 continue; 18493 } 18494 // Parse package 18495 int parseFlags = mDefParseFlags; 18496 if (args.isExternalAsec()) { 18497 parseFlags |= PackageParser.PARSE_EXTERNAL_STORAGE; 18498 } 18499 if (args.isFwdLocked()) { 18500 parseFlags |= PackageParser.PARSE_FORWARD_LOCK; 18501 } 18502 18503 synchronized (mInstallLock) { 18504 PackageParser.Package pkg = null; 18505 try { 18506 // Sadly we don't know the package name yet to freeze it 18507 pkg = scanPackageTracedLI(new File(codePath), parseFlags, 18508 SCAN_IGNORE_FROZEN, 0, null); 18509 } catch (PackageManagerException e) { 18510 Slog.w(TAG, "Failed to scan " + codePath + ": " + e.getMessage()); 18511 } 18512 // Scan the package 18513 if (pkg != null) { 18514 /* 18515 * TODO why is the lock being held? doPostInstall is 18516 * called in other places without the lock. This needs 18517 * to be straightened out. 18518 */ 18519 // writer 18520 synchronized (mPackages) { 18521 retCode = PackageManager.INSTALL_SUCCEEDED; 18522 pkgList.add(pkg.packageName); 18523 // Post process args 18524 args.doPostInstall(PackageManager.INSTALL_SUCCEEDED, 18525 pkg.applicationInfo.uid); 18526 } 18527 } else { 18528 Slog.i(TAG, "Failed to install pkg from " + codePath + " from sdcard"); 18529 } 18530 } 18531 18532 } finally { 18533 if (retCode != PackageManager.INSTALL_SUCCEEDED) { 18534 Log.w(TAG, "Container " + args.cid + " is stale, retCode=" + retCode); 18535 } 18536 } 18537 } 18538 // writer 18539 synchronized (mPackages) { 18540 // If the platform SDK has changed since the last time we booted, 18541 // we need to re-grant app permission to catch any new ones that 18542 // appear. This is really a hack, and means that apps can in some 18543 // cases get permissions that the user didn't initially explicitly 18544 // allow... it would be nice to have some better way to handle 18545 // this situation. 18546 final VersionInfo ver = externalStorage ? mSettings.getExternalVersion() 18547 : mSettings.getInternalVersion(); 18548 final String volumeUuid = externalStorage ? StorageManager.UUID_PRIMARY_PHYSICAL 18549 : StorageManager.UUID_PRIVATE_INTERNAL; 18550 18551 int updateFlags = UPDATE_PERMISSIONS_ALL; 18552 if (ver.sdkVersion != mSdkVersion) { 18553 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18554 + mSdkVersion + "; regranting permissions for external"); 18555 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18556 } 18557 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18558 18559 // Yay, everything is now upgraded 18560 ver.forceCurrent(); 18561 18562 // can downgrade to reader 18563 // Persist settings 18564 mSettings.writeLPr(); 18565 } 18566 // Send a broadcast to let everyone know we are done processing 18567 if (pkgList.size() > 0) { 18568 sendResourcesChangedBroadcast(true, false, pkgList, uidArr, null); 18569 } 18570 } 18571 18572 /* 18573 * Utility method to unload a list of specified containers 18574 */ 18575 private void unloadAllContainers(Set<AsecInstallArgs> cidArgs) { 18576 // Just unmount all valid containers. 18577 for (AsecInstallArgs arg : cidArgs) { 18578 synchronized (mInstallLock) { 18579 arg.doPostDeleteLI(false); 18580 } 18581 } 18582 } 18583 18584 /* 18585 * Unload packages mounted on external media. This involves deleting package 18586 * data from internal structures, sending broadcasts about disabled packages, 18587 * gc'ing to free up references, unmounting all secure containers 18588 * corresponding to packages on external media, and posting a 18589 * UPDATED_MEDIA_STATUS message if status has been requested. Please note 18590 * that we always have to post this message if status has been requested no 18591 * matter what. 18592 */ 18593 private void unloadMediaPackages(ArrayMap<AsecInstallArgs, String> processCids, int uidArr[], 18594 final boolean reportStatus) { 18595 if (DEBUG_SD_INSTALL) 18596 Log.i(TAG, "unloading media packages"); 18597 ArrayList<String> pkgList = new ArrayList<String>(); 18598 ArrayList<AsecInstallArgs> failedList = new ArrayList<AsecInstallArgs>(); 18599 final Set<AsecInstallArgs> keys = processCids.keySet(); 18600 for (AsecInstallArgs args : keys) { 18601 String pkgName = args.getPackageName(); 18602 if (DEBUG_SD_INSTALL) 18603 Log.i(TAG, "Trying to unload pkg : " + pkgName); 18604 // Delete package internally 18605 PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18606 synchronized (mInstallLock) { 18607 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18608 final boolean res; 18609 try (PackageFreezer freezer = freezePackageForDelete(pkgName, deleteFlags, 18610 "unloadMediaPackages")) { 18611 res = deletePackageLIF(pkgName, null, false, null, deleteFlags, outInfo, false, 18612 null); 18613 } 18614 if (res) { 18615 pkgList.add(pkgName); 18616 } else { 18617 Slog.e(TAG, "Failed to delete pkg from sdcard : " + pkgName); 18618 failedList.add(args); 18619 } 18620 } 18621 } 18622 18623 // reader 18624 synchronized (mPackages) { 18625 // We didn't update the settings after removing each package; 18626 // write them now for all packages. 18627 mSettings.writeLPr(); 18628 } 18629 18630 // We have to absolutely send UPDATED_MEDIA_STATUS only 18631 // after confirming that all the receivers processed the ordered 18632 // broadcast when packages get disabled, force a gc to clean things up. 18633 // and unload all the containers. 18634 if (pkgList.size() > 0) { 18635 sendResourcesChangedBroadcast(false, false, pkgList, uidArr, 18636 new IIntentReceiver.Stub() { 18637 public void performReceive(Intent intent, int resultCode, String data, 18638 Bundle extras, boolean ordered, boolean sticky, 18639 int sendingUser) throws RemoteException { 18640 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, 18641 reportStatus ? 1 : 0, 1, keys); 18642 mHandler.sendMessage(msg); 18643 } 18644 }); 18645 } else { 18646 Message msg = mHandler.obtainMessage(UPDATED_MEDIA_STATUS, reportStatus ? 1 : 0, -1, 18647 keys); 18648 mHandler.sendMessage(msg); 18649 } 18650 } 18651 18652 private void loadPrivatePackages(final VolumeInfo vol) { 18653 mHandler.post(new Runnable() { 18654 @Override 18655 public void run() { 18656 loadPrivatePackagesInner(vol); 18657 } 18658 }); 18659 } 18660 18661 private void loadPrivatePackagesInner(VolumeInfo vol) { 18662 final String volumeUuid = vol.fsUuid; 18663 if (TextUtils.isEmpty(volumeUuid)) { 18664 Slog.e(TAG, "Loading internal storage is probably a mistake; ignoring"); 18665 return; 18666 } 18667 18668 final ArrayList<PackageFreezer> freezers = new ArrayList<>(); 18669 final ArrayList<ApplicationInfo> loaded = new ArrayList<>(); 18670 final int parseFlags = mDefParseFlags | PackageParser.PARSE_EXTERNAL_STORAGE; 18671 18672 final VersionInfo ver; 18673 final List<PackageSetting> packages; 18674 synchronized (mPackages) { 18675 ver = mSettings.findOrCreateVersion(volumeUuid); 18676 packages = mSettings.getVolumePackagesLPr(volumeUuid); 18677 } 18678 18679 for (PackageSetting ps : packages) { 18680 freezers.add(freezePackage(ps.name, "loadPrivatePackagesInner")); 18681 synchronized (mInstallLock) { 18682 final PackageParser.Package pkg; 18683 try { 18684 pkg = scanPackageTracedLI(ps.codePath, parseFlags, SCAN_INITIAL, 0, null); 18685 loaded.add(pkg.applicationInfo); 18686 18687 } catch (PackageManagerException e) { 18688 Slog.w(TAG, "Failed to scan " + ps.codePath + ": " + e.getMessage()); 18689 } 18690 18691 if (!Build.FINGERPRINT.equals(ver.fingerprint)) { 18692 clearAppDataLIF(ps.pkg, UserHandle.USER_ALL, 18693 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE 18694 | Installer.FLAG_CLEAR_CODE_CACHE_ONLY); 18695 } 18696 } 18697 } 18698 18699 // Reconcile app data for all started/unlocked users 18700 final StorageManager sm = mContext.getSystemService(StorageManager.class); 18701 final UserManager um = mContext.getSystemService(UserManager.class); 18702 for (UserInfo user : um.getUsers()) { 18703 final int flags; 18704 if (um.isUserUnlocked(user.id)) { 18705 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 18706 } else if (um.isUserRunning(user.id)) { 18707 flags = StorageManager.FLAG_STORAGE_DE; 18708 } else { 18709 continue; 18710 } 18711 18712 sm.prepareUserStorage(volumeUuid, user.id, user.serialNumber, flags); 18713 synchronized (mInstallLock) { 18714 reconcileAppsDataLI(volumeUuid, user.id, flags); 18715 } 18716 } 18717 18718 synchronized (mPackages) { 18719 int updateFlags = UPDATE_PERMISSIONS_ALL; 18720 if (ver.sdkVersion != mSdkVersion) { 18721 logCriticalInfo(Log.INFO, "Platform changed from " + ver.sdkVersion + " to " 18722 + mSdkVersion + "; regranting permissions for " + volumeUuid); 18723 updateFlags |= UPDATE_PERMISSIONS_REPLACE_PKG | UPDATE_PERMISSIONS_REPLACE_ALL; 18724 } 18725 updatePermissionsLPw(null, null, volumeUuid, updateFlags); 18726 18727 // Yay, everything is now upgraded 18728 ver.forceCurrent(); 18729 18730 mSettings.writeLPr(); 18731 } 18732 18733 for (PackageFreezer freezer : freezers) { 18734 freezer.close(); 18735 } 18736 18737 if (DEBUG_INSTALL) Slog.d(TAG, "Loaded packages " + loaded); 18738 sendResourcesChangedBroadcast(true, false, loaded, null); 18739 } 18740 18741 private void unloadPrivatePackages(final VolumeInfo vol) { 18742 mHandler.post(new Runnable() { 18743 @Override 18744 public void run() { 18745 unloadPrivatePackagesInner(vol); 18746 } 18747 }); 18748 } 18749 18750 private void unloadPrivatePackagesInner(VolumeInfo vol) { 18751 final String volumeUuid = vol.fsUuid; 18752 if (TextUtils.isEmpty(volumeUuid)) { 18753 Slog.e(TAG, "Unloading internal storage is probably a mistake; ignoring"); 18754 return; 18755 } 18756 18757 final ArrayList<ApplicationInfo> unloaded = new ArrayList<>(); 18758 synchronized (mInstallLock) { 18759 synchronized (mPackages) { 18760 final List<PackageSetting> packages = mSettings.getVolumePackagesLPr(volumeUuid); 18761 for (PackageSetting ps : packages) { 18762 if (ps.pkg == null) continue; 18763 18764 final ApplicationInfo info = ps.pkg.applicationInfo; 18765 final int deleteFlags = PackageManager.DELETE_KEEP_DATA; 18766 final PackageRemovedInfo outInfo = new PackageRemovedInfo(); 18767 18768 try (PackageFreezer freezer = freezePackageForDelete(ps.name, deleteFlags, 18769 "unloadPrivatePackagesInner")) { 18770 if (deletePackageLIF(ps.name, null, false, null, deleteFlags, outInfo, 18771 false, null)) { 18772 unloaded.add(info); 18773 } else { 18774 Slog.w(TAG, "Failed to unload " + ps.codePath); 18775 } 18776 } 18777 } 18778 18779 mSettings.writeLPr(); 18780 } 18781 } 18782 18783 if (DEBUG_INSTALL) Slog.d(TAG, "Unloaded packages " + unloaded); 18784 sendResourcesChangedBroadcast(false, false, unloaded, null); 18785 } 18786 18787 /** 18788 * Prepare storage areas for given user on all mounted devices. 18789 */ 18790 void prepareUserData(int userId, int userSerial, int flags) { 18791 synchronized (mInstallLock) { 18792 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18793 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18794 final String volumeUuid = vol.getFsUuid(); 18795 prepareUserDataLI(volumeUuid, userId, userSerial, flags, true); 18796 } 18797 } 18798 } 18799 18800 private void prepareUserDataLI(String volumeUuid, int userId, int userSerial, int flags, 18801 boolean allowRecover) { 18802 // Prepare storage and verify that serial numbers are consistent; if 18803 // there's a mismatch we need to destroy to avoid leaking data 18804 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18805 try { 18806 storage.prepareUserStorage(volumeUuid, userId, userSerial, flags); 18807 18808 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0 && !mOnlyCore) { 18809 UserManagerService.enforceSerialNumber( 18810 Environment.getDataUserDeDirectory(volumeUuid, userId), userSerial); 18811 } 18812 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0 && !mOnlyCore) { 18813 UserManagerService.enforceSerialNumber( 18814 Environment.getDataUserCeDirectory(volumeUuid, userId), userSerial); 18815 } 18816 18817 synchronized (mInstallLock) { 18818 mInstaller.createUserData(volumeUuid, userId, userSerial, flags); 18819 } 18820 } catch (Exception e) { 18821 logCriticalInfo(Log.WARN, "Destroying user " + userId + " on volume " + volumeUuid 18822 + " because we failed to prepare: " + e); 18823 destroyUserDataLI(volumeUuid, userId, 18824 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18825 18826 if (allowRecover) { 18827 // Try one last time; if we fail again we're really in trouble 18828 prepareUserDataLI(volumeUuid, userId, userSerial, flags, false); 18829 } 18830 } 18831 } 18832 18833 /** 18834 * Destroy storage areas for given user on all mounted devices. 18835 */ 18836 void destroyUserData(int userId, int flags) { 18837 synchronized (mInstallLock) { 18838 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18839 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18840 final String volumeUuid = vol.getFsUuid(); 18841 destroyUserDataLI(volumeUuid, userId, flags); 18842 } 18843 } 18844 } 18845 18846 private void destroyUserDataLI(String volumeUuid, int userId, int flags) { 18847 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18848 try { 18849 // Clean up app data, profile data, and media data 18850 mInstaller.destroyUserData(volumeUuid, userId, flags); 18851 18852 // Clean up system data 18853 if (Objects.equals(volumeUuid, StorageManager.UUID_PRIVATE_INTERNAL)) { 18854 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 18855 FileUtils.deleteContentsAndDir(Environment.getUserSystemDirectory(userId)); 18856 FileUtils.deleteContentsAndDir(Environment.getDataSystemDeDirectory(userId)); 18857 } 18858 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 18859 FileUtils.deleteContentsAndDir(Environment.getDataSystemCeDirectory(userId)); 18860 } 18861 } 18862 18863 // Data with special labels is now gone, so finish the job 18864 storage.destroyUserStorage(volumeUuid, userId, flags); 18865 18866 } catch (Exception e) { 18867 logCriticalInfo(Log.WARN, 18868 "Failed to destroy user " + userId + " on volume " + volumeUuid + ": " + e); 18869 } 18870 } 18871 18872 /** 18873 * Examine all users present on given mounted volume, and destroy data 18874 * belonging to users that are no longer valid, or whose user ID has been 18875 * recycled. 18876 */ 18877 private void reconcileUsers(String volumeUuid) { 18878 final List<File> files = new ArrayList<>(); 18879 Collections.addAll(files, FileUtils 18880 .listFilesOrEmpty(Environment.getDataUserDeDirectory(volumeUuid))); 18881 Collections.addAll(files, FileUtils 18882 .listFilesOrEmpty(Environment.getDataUserCeDirectory(volumeUuid))); 18883 for (File file : files) { 18884 if (!file.isDirectory()) continue; 18885 18886 final int userId; 18887 final UserInfo info; 18888 try { 18889 userId = Integer.parseInt(file.getName()); 18890 info = sUserManager.getUserInfo(userId); 18891 } catch (NumberFormatException e) { 18892 Slog.w(TAG, "Invalid user directory " + file); 18893 continue; 18894 } 18895 18896 boolean destroyUser = false; 18897 if (info == null) { 18898 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18899 + " because no matching user was found"); 18900 destroyUser = true; 18901 } else if (!mOnlyCore) { 18902 try { 18903 UserManagerService.enforceSerialNumber(file, info.serialNumber); 18904 } catch (IOException e) { 18905 logCriticalInfo(Log.WARN, "Destroying user directory " + file 18906 + " because we failed to enforce serial number: " + e); 18907 destroyUser = true; 18908 } 18909 } 18910 18911 if (destroyUser) { 18912 synchronized (mInstallLock) { 18913 destroyUserDataLI(volumeUuid, userId, 18914 StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE); 18915 } 18916 } 18917 } 18918 } 18919 18920 private void assertPackageKnown(String volumeUuid, String packageName) 18921 throws PackageManagerException { 18922 synchronized (mPackages) { 18923 final PackageSetting ps = mSettings.mPackages.get(packageName); 18924 if (ps == null) { 18925 throw new PackageManagerException("Package " + packageName + " is unknown"); 18926 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18927 throw new PackageManagerException( 18928 "Package " + packageName + " found on unknown volume " + volumeUuid 18929 + "; expected volume " + ps.volumeUuid); 18930 } 18931 } 18932 } 18933 18934 private void assertPackageKnownAndInstalled(String volumeUuid, String packageName, int userId) 18935 throws PackageManagerException { 18936 synchronized (mPackages) { 18937 final PackageSetting ps = mSettings.mPackages.get(packageName); 18938 if (ps == null) { 18939 throw new PackageManagerException("Package " + packageName + " is unknown"); 18940 } else if (!TextUtils.equals(volumeUuid, ps.volumeUuid)) { 18941 throw new PackageManagerException( 18942 "Package " + packageName + " found on unknown volume " + volumeUuid 18943 + "; expected volume " + ps.volumeUuid); 18944 } else if (!ps.getInstalled(userId)) { 18945 throw new PackageManagerException( 18946 "Package " + packageName + " not installed for user " + userId); 18947 } 18948 } 18949 } 18950 18951 /** 18952 * Examine all apps present on given mounted volume, and destroy apps that 18953 * aren't expected, either due to uninstallation or reinstallation on 18954 * another volume. 18955 */ 18956 private void reconcileApps(String volumeUuid) { 18957 final File[] files = FileUtils 18958 .listFilesOrEmpty(Environment.getDataAppDirectory(volumeUuid)); 18959 for (File file : files) { 18960 final boolean isPackage = (isApkFile(file) || file.isDirectory()) 18961 && !PackageInstallerService.isStageName(file.getName()); 18962 if (!isPackage) { 18963 // Ignore entries which are not packages 18964 continue; 18965 } 18966 18967 try { 18968 final PackageLite pkg = PackageParser.parsePackageLite(file, 18969 PackageParser.PARSE_MUST_BE_APK); 18970 assertPackageKnown(volumeUuid, pkg.packageName); 18971 18972 } catch (PackageParserException | PackageManagerException e) { 18973 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 18974 synchronized (mInstallLock) { 18975 removeCodePathLI(file); 18976 } 18977 } 18978 } 18979 } 18980 18981 /** 18982 * Reconcile all app data for the given user. 18983 * <p> 18984 * Verifies that directories exist and that ownership and labeling is 18985 * correct for all installed apps on all mounted volumes. 18986 */ 18987 void reconcileAppsData(int userId, int flags) { 18988 final StorageManager storage = mContext.getSystemService(StorageManager.class); 18989 for (VolumeInfo vol : storage.getWritablePrivateVolumes()) { 18990 final String volumeUuid = vol.getFsUuid(); 18991 synchronized (mInstallLock) { 18992 reconcileAppsDataLI(volumeUuid, userId, flags); 18993 } 18994 } 18995 } 18996 18997 /** 18998 * Reconcile all app data on given mounted volume. 18999 * <p> 19000 * Destroys app data that isn't expected, either due to uninstallation or 19001 * reinstallation on another volume. 19002 * <p> 19003 * Verifies that directories exist and that ownership and labeling is 19004 * correct for all installed apps. 19005 */ 19006 private void reconcileAppsDataLI(String volumeUuid, int userId, int flags) { 19007 Slog.v(TAG, "reconcileAppsData for " + volumeUuid + " u" + userId + " 0x" 19008 + Integer.toHexString(flags)); 19009 19010 final File ceDir = Environment.getDataUserCeDirectory(volumeUuid, userId); 19011 final File deDir = Environment.getDataUserDeDirectory(volumeUuid, userId); 19012 19013 boolean restoreconNeeded = false; 19014 19015 // First look for stale data that doesn't belong, and check if things 19016 // have changed since we did our last restorecon 19017 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19018 if (!isUserKeyUnlocked(userId)) { 19019 throw new RuntimeException( 19020 "Yikes, someone asked us to reconcile CE storage while " + userId 19021 + " was still locked; this would have caused massive data loss!"); 19022 } 19023 19024 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(ceDir); 19025 19026 final File[] files = FileUtils.listFilesOrEmpty(ceDir); 19027 for (File file : files) { 19028 final String packageName = file.getName(); 19029 try { 19030 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19031 } catch (PackageManagerException e) { 19032 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19033 try { 19034 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19035 StorageManager.FLAG_STORAGE_CE, 0); 19036 } catch (InstallerException e2) { 19037 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19038 } 19039 } 19040 } 19041 } 19042 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19043 restoreconNeeded |= SELinuxMMAC.isRestoreconNeeded(deDir); 19044 19045 final File[] files = FileUtils.listFilesOrEmpty(deDir); 19046 for (File file : files) { 19047 final String packageName = file.getName(); 19048 try { 19049 assertPackageKnownAndInstalled(volumeUuid, packageName, userId); 19050 } catch (PackageManagerException e) { 19051 logCriticalInfo(Log.WARN, "Destroying " + file + " due to: " + e); 19052 try { 19053 mInstaller.destroyAppData(volumeUuid, packageName, userId, 19054 StorageManager.FLAG_STORAGE_DE, 0); 19055 } catch (InstallerException e2) { 19056 logCriticalInfo(Log.WARN, "Failed to destroy: " + e2); 19057 } 19058 } 19059 } 19060 } 19061 19062 // Ensure that data directories are ready to roll for all packages 19063 // installed for this volume and user 19064 final List<PackageSetting> packages; 19065 synchronized (mPackages) { 19066 packages = mSettings.getVolumePackagesLPr(volumeUuid); 19067 } 19068 int preparedCount = 0; 19069 for (PackageSetting ps : packages) { 19070 final String packageName = ps.name; 19071 if (ps.pkg == null) { 19072 Slog.w(TAG, "Odd, missing scanned package " + packageName); 19073 // TODO: might be due to legacy ASEC apps; we should circle back 19074 // and reconcile again once they're scanned 19075 continue; 19076 } 19077 19078 if (ps.getInstalled(userId)) { 19079 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19080 19081 if (maybeMigrateAppDataLIF(ps.pkg, userId)) { 19082 // We may have just shuffled around app data directories, so 19083 // prepare them one more time 19084 prepareAppDataLIF(ps.pkg, userId, flags, restoreconNeeded); 19085 } 19086 19087 preparedCount++; 19088 } 19089 } 19090 19091 if (restoreconNeeded) { 19092 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19093 SELinuxMMAC.setRestoreconDone(ceDir); 19094 } 19095 if ((flags & StorageManager.FLAG_STORAGE_DE) != 0) { 19096 SELinuxMMAC.setRestoreconDone(deDir); 19097 } 19098 } 19099 19100 Slog.v(TAG, "reconcileAppsData finished " + preparedCount 19101 + " packages; restoreconNeeded was " + restoreconNeeded); 19102 } 19103 19104 /** 19105 * Prepare app data for the given app just after it was installed or 19106 * upgraded. This method carefully only touches users that it's installed 19107 * for, and it forces a restorecon to handle any seinfo changes. 19108 * <p> 19109 * Verifies that directories exist and that ownership and labeling is 19110 * correct for all installed apps. If there is an ownership mismatch, it 19111 * will try recovering system apps by wiping data; third-party app data is 19112 * left intact. 19113 * <p> 19114 * <em>Note: To avoid a deadlock, do not call this method with {@code mPackages} lock held</em> 19115 */ 19116 private void prepareAppDataAfterInstallLIF(PackageParser.Package pkg) { 19117 final PackageSetting ps; 19118 synchronized (mPackages) { 19119 ps = mSettings.mPackages.get(pkg.packageName); 19120 mSettings.writeKernelMappingLPr(ps); 19121 } 19122 19123 final UserManager um = mContext.getSystemService(UserManager.class); 19124 for (UserInfo user : um.getUsers()) { 19125 final int flags; 19126 if (um.isUserUnlocked(user.id)) { 19127 flags = StorageManager.FLAG_STORAGE_DE | StorageManager.FLAG_STORAGE_CE; 19128 } else if (um.isUserRunning(user.id)) { 19129 flags = StorageManager.FLAG_STORAGE_DE; 19130 } else { 19131 continue; 19132 } 19133 19134 if (ps.getInstalled(user.id)) { 19135 // Whenever an app changes, force a restorecon of its data 19136 // TODO: when user data is locked, mark that we're still dirty 19137 prepareAppDataLIF(pkg, user.id, flags, true); 19138 } 19139 } 19140 } 19141 19142 /** 19143 * Prepare app data for the given app. 19144 * <p> 19145 * Verifies that directories exist and that ownership and labeling is 19146 * correct for all installed apps. If there is an ownership mismatch, this 19147 * will try recovering system apps by wiping data; third-party app data is 19148 * left intact. 19149 */ 19150 private void prepareAppDataLIF(PackageParser.Package pkg, int userId, int flags, 19151 boolean restoreconNeeded) { 19152 if (pkg == null) { 19153 Slog.wtf(TAG, "Package was null!", new Throwable()); 19154 return; 19155 } 19156 prepareAppDataLeafLIF(pkg, userId, flags, restoreconNeeded); 19157 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19158 for (int i = 0; i < childCount; i++) { 19159 prepareAppDataLeafLIF(pkg.childPackages.get(i), userId, flags, restoreconNeeded); 19160 } 19161 } 19162 19163 private void prepareAppDataLeafLIF(PackageParser.Package pkg, int userId, int flags, 19164 boolean restoreconNeeded) { 19165 if (DEBUG_APP_DATA) { 19166 Slog.v(TAG, "prepareAppData for " + pkg.packageName + " u" + userId + " 0x" 19167 + Integer.toHexString(flags) + (restoreconNeeded ? " restoreconNeeded" : "")); 19168 } 19169 19170 final String volumeUuid = pkg.volumeUuid; 19171 final String packageName = pkg.packageName; 19172 final ApplicationInfo app = pkg.applicationInfo; 19173 final int appId = UserHandle.getAppId(app.uid); 19174 19175 Preconditions.checkNotNull(app.seinfo); 19176 19177 try { 19178 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19179 appId, app.seinfo, app.targetSdkVersion); 19180 } catch (InstallerException e) { 19181 if (app.isSystemApp()) { 19182 logCriticalInfo(Log.ERROR, "Failed to create app data for " + packageName 19183 + ", but trying to recover: " + e); 19184 destroyAppDataLeafLIF(pkg, userId, flags); 19185 try { 19186 mInstaller.createAppData(volumeUuid, packageName, userId, flags, 19187 appId, app.seinfo, app.targetSdkVersion); 19188 logCriticalInfo(Log.DEBUG, "Recovery succeeded!"); 19189 } catch (InstallerException e2) { 19190 logCriticalInfo(Log.DEBUG, "Recovery failed!"); 19191 } 19192 } else { 19193 Slog.e(TAG, "Failed to create app data for " + packageName + ": " + e); 19194 } 19195 } 19196 19197 if (restoreconNeeded) { 19198 try { 19199 mInstaller.restoreconAppData(volumeUuid, packageName, userId, flags, appId, 19200 app.seinfo); 19201 } catch (InstallerException e) { 19202 Slog.e(TAG, "Failed to restorecon for " + packageName + ": " + e); 19203 } 19204 } 19205 19206 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19207 try { 19208 // CE storage is unlocked right now, so read out the inode and 19209 // remember for use later when it's locked 19210 // TODO: mark this structure as dirty so we persist it! 19211 final long ceDataInode = mInstaller.getAppDataInode(volumeUuid, packageName, userId, 19212 StorageManager.FLAG_STORAGE_CE); 19213 synchronized (mPackages) { 19214 final PackageSetting ps = mSettings.mPackages.get(packageName); 19215 if (ps != null) { 19216 ps.setCeDataInode(ceDataInode, userId); 19217 } 19218 } 19219 } catch (InstallerException e) { 19220 Slog.e(TAG, "Failed to find inode for " + packageName + ": " + e); 19221 } 19222 } 19223 19224 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19225 } 19226 19227 private void prepareAppDataContentsLIF(PackageParser.Package pkg, int userId, int flags) { 19228 if (pkg == null) { 19229 Slog.wtf(TAG, "Package was null!", new Throwable()); 19230 return; 19231 } 19232 prepareAppDataContentsLeafLIF(pkg, userId, flags); 19233 final int childCount = (pkg.childPackages != null) ? pkg.childPackages.size() : 0; 19234 for (int i = 0; i < childCount; i++) { 19235 prepareAppDataContentsLeafLIF(pkg.childPackages.get(i), userId, flags); 19236 } 19237 } 19238 19239 private void prepareAppDataContentsLeafLIF(PackageParser.Package pkg, int userId, int flags) { 19240 final String volumeUuid = pkg.volumeUuid; 19241 final String packageName = pkg.packageName; 19242 final ApplicationInfo app = pkg.applicationInfo; 19243 19244 if ((flags & StorageManager.FLAG_STORAGE_CE) != 0) { 19245 // Create a native library symlink only if we have native libraries 19246 // and if the native libraries are 32 bit libraries. We do not provide 19247 // this symlink for 64 bit libraries. 19248 if (app.primaryCpuAbi != null && !VMRuntime.is64BitAbi(app.primaryCpuAbi)) { 19249 final String nativeLibPath = app.nativeLibraryDir; 19250 try { 19251 mInstaller.linkNativeLibraryDirectory(volumeUuid, packageName, 19252 nativeLibPath, userId); 19253 } catch (InstallerException e) { 19254 Slog.e(TAG, "Failed to link native for " + packageName + ": " + e); 19255 } 19256 } 19257 } 19258 } 19259 19260 /** 19261 * For system apps on non-FBE devices, this method migrates any existing 19262 * CE/DE data to match the {@code defaultToDeviceProtectedStorage} flag 19263 * requested by the app. 19264 */ 19265 private boolean maybeMigrateAppDataLIF(PackageParser.Package pkg, int userId) { 19266 if (pkg.isSystemApp() && !StorageManager.isFileEncryptedNativeOrEmulated() 19267 && PackageManager.APPLY_DEFAULT_TO_DEVICE_PROTECTED_STORAGE) { 19268 final int storageTarget = pkg.applicationInfo.isDefaultToDeviceProtectedStorage() 19269 ? StorageManager.FLAG_STORAGE_DE : StorageManager.FLAG_STORAGE_CE; 19270 try { 19271 mInstaller.migrateAppData(pkg.volumeUuid, pkg.packageName, userId, 19272 storageTarget); 19273 } catch (InstallerException e) { 19274 logCriticalInfo(Log.WARN, 19275 "Failed to migrate " + pkg.packageName + ": " + e.getMessage()); 19276 } 19277 return true; 19278 } else { 19279 return false; 19280 } 19281 } 19282 19283 public PackageFreezer freezePackage(String packageName, String killReason) { 19284 return new PackageFreezer(packageName, killReason); 19285 } 19286 19287 public PackageFreezer freezePackageForInstall(String packageName, int installFlags, 19288 String killReason) { 19289 if ((installFlags & PackageManager.INSTALL_DONT_KILL_APP) != 0) { 19290 return new PackageFreezer(); 19291 } else { 19292 return freezePackage(packageName, killReason); 19293 } 19294 } 19295 19296 public PackageFreezer freezePackageForDelete(String packageName, int deleteFlags, 19297 String killReason) { 19298 if ((deleteFlags & PackageManager.DELETE_DONT_KILL_APP) != 0) { 19299 return new PackageFreezer(); 19300 } else { 19301 return freezePackage(packageName, killReason); 19302 } 19303 } 19304 19305 /** 19306 * Class that freezes and kills the given package upon creation, and 19307 * unfreezes it upon closing. This is typically used when doing surgery on 19308 * app code/data to prevent the app from running while you're working. 19309 */ 19310 private class PackageFreezer implements AutoCloseable { 19311 private final String mPackageName; 19312 private final PackageFreezer[] mChildren; 19313 19314 private final boolean mWeFroze; 19315 19316 private final AtomicBoolean mClosed = new AtomicBoolean(); 19317 private final CloseGuard mCloseGuard = CloseGuard.get(); 19318 19319 /** 19320 * Create and return a stub freezer that doesn't actually do anything, 19321 * typically used when someone requested 19322 * {@link PackageManager#INSTALL_DONT_KILL_APP} or 19323 * {@link PackageManager#DELETE_DONT_KILL_APP}. 19324 */ 19325 public PackageFreezer() { 19326 mPackageName = null; 19327 mChildren = null; 19328 mWeFroze = false; 19329 mCloseGuard.open("close"); 19330 } 19331 19332 public PackageFreezer(String packageName, String killReason) { 19333 synchronized (mPackages) { 19334 mPackageName = packageName; 19335 mWeFroze = mFrozenPackages.add(mPackageName); 19336 19337 final PackageSetting ps = mSettings.mPackages.get(mPackageName); 19338 if (ps != null) { 19339 killApplication(ps.name, ps.appId, killReason); 19340 } 19341 19342 final PackageParser.Package p = mPackages.get(packageName); 19343 if (p != null && p.childPackages != null) { 19344 final int N = p.childPackages.size(); 19345 mChildren = new PackageFreezer[N]; 19346 for (int i = 0; i < N; i++) { 19347 mChildren[i] = new PackageFreezer(p.childPackages.get(i).packageName, 19348 killReason); 19349 } 19350 } else { 19351 mChildren = null; 19352 } 19353 } 19354 mCloseGuard.open("close"); 19355 } 19356 19357 @Override 19358 protected void finalize() throws Throwable { 19359 try { 19360 mCloseGuard.warnIfOpen(); 19361 close(); 19362 } finally { 19363 super.finalize(); 19364 } 19365 } 19366 19367 @Override 19368 public void close() { 19369 mCloseGuard.close(); 19370 if (mClosed.compareAndSet(false, true)) { 19371 synchronized (mPackages) { 19372 if (mWeFroze) { 19373 mFrozenPackages.remove(mPackageName); 19374 } 19375 19376 if (mChildren != null) { 19377 for (PackageFreezer freezer : mChildren) { 19378 freezer.close(); 19379 } 19380 } 19381 } 19382 } 19383 } 19384 } 19385 19386 /** 19387 * Verify that given package is currently frozen. 19388 */ 19389 private void checkPackageFrozen(String packageName) { 19390 synchronized (mPackages) { 19391 if (!mFrozenPackages.contains(packageName)) { 19392 Slog.wtf(TAG, "Expected " + packageName + " to be frozen!", new Throwable()); 19393 } 19394 } 19395 } 19396 19397 @Override 19398 public int movePackage(final String packageName, final String volumeUuid) { 19399 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19400 19401 final int moveId = mNextMoveId.getAndIncrement(); 19402 mHandler.post(new Runnable() { 19403 @Override 19404 public void run() { 19405 try { 19406 movePackageInternal(packageName, volumeUuid, moveId); 19407 } catch (PackageManagerException e) { 19408 Slog.w(TAG, "Failed to move " + packageName, e); 19409 mMoveCallbacks.notifyStatusChanged(moveId, 19410 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19411 } 19412 } 19413 }); 19414 return moveId; 19415 } 19416 19417 private void movePackageInternal(final String packageName, final String volumeUuid, 19418 final int moveId) throws PackageManagerException { 19419 final UserHandle user = new UserHandle(UserHandle.getCallingUserId()); 19420 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19421 final PackageManager pm = mContext.getPackageManager(); 19422 19423 final boolean currentAsec; 19424 final String currentVolumeUuid; 19425 final File codeFile; 19426 final String installerPackageName; 19427 final String packageAbiOverride; 19428 final int appId; 19429 final String seinfo; 19430 final String label; 19431 final int targetSdkVersion; 19432 final PackageFreezer freezer; 19433 19434 // reader 19435 synchronized (mPackages) { 19436 final PackageParser.Package pkg = mPackages.get(packageName); 19437 final PackageSetting ps = mSettings.mPackages.get(packageName); 19438 if (pkg == null || ps == null) { 19439 throw new PackageManagerException(MOVE_FAILED_DOESNT_EXIST, "Missing package"); 19440 } 19441 19442 if (pkg.applicationInfo.isSystemApp()) { 19443 throw new PackageManagerException(MOVE_FAILED_SYSTEM_PACKAGE, 19444 "Cannot move system application"); 19445 } 19446 19447 if (pkg.applicationInfo.isExternalAsec()) { 19448 currentAsec = true; 19449 currentVolumeUuid = StorageManager.UUID_PRIMARY_PHYSICAL; 19450 } else if (pkg.applicationInfo.isForwardLocked()) { 19451 currentAsec = true; 19452 currentVolumeUuid = "forward_locked"; 19453 } else { 19454 currentAsec = false; 19455 currentVolumeUuid = ps.volumeUuid; 19456 19457 final File probe = new File(pkg.codePath); 19458 final File probeOat = new File(probe, "oat"); 19459 if (!probe.isDirectory() || !probeOat.isDirectory()) { 19460 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19461 "Move only supported for modern cluster style installs"); 19462 } 19463 } 19464 19465 if (Objects.equals(currentVolumeUuid, volumeUuid)) { 19466 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19467 "Package already moved to " + volumeUuid); 19468 } 19469 if (pkg.applicationInfo.isInternal() && isPackageDeviceAdminOnAnyUser(packageName)) { 19470 throw new PackageManagerException(MOVE_FAILED_DEVICE_ADMIN, 19471 "Device admin cannot be moved"); 19472 } 19473 19474 if (mFrozenPackages.contains(packageName)) { 19475 throw new PackageManagerException(MOVE_FAILED_OPERATION_PENDING, 19476 "Failed to move already frozen package"); 19477 } 19478 19479 codeFile = new File(pkg.codePath); 19480 installerPackageName = ps.installerPackageName; 19481 packageAbiOverride = ps.cpuAbiOverrideString; 19482 appId = UserHandle.getAppId(pkg.applicationInfo.uid); 19483 seinfo = pkg.applicationInfo.seinfo; 19484 label = String.valueOf(pm.getApplicationLabel(pkg.applicationInfo)); 19485 targetSdkVersion = pkg.applicationInfo.targetSdkVersion; 19486 freezer = new PackageFreezer(packageName, "movePackageInternal"); 19487 } 19488 19489 final Bundle extras = new Bundle(); 19490 extras.putString(Intent.EXTRA_PACKAGE_NAME, packageName); 19491 extras.putString(Intent.EXTRA_TITLE, label); 19492 mMoveCallbacks.notifyCreated(moveId, extras); 19493 19494 int installFlags; 19495 final boolean moveCompleteApp; 19496 final File measurePath; 19497 19498 if (Objects.equals(StorageManager.UUID_PRIVATE_INTERNAL, volumeUuid)) { 19499 installFlags = INSTALL_INTERNAL; 19500 moveCompleteApp = !currentAsec; 19501 measurePath = Environment.getDataAppDirectory(volumeUuid); 19502 } else if (Objects.equals(StorageManager.UUID_PRIMARY_PHYSICAL, volumeUuid)) { 19503 installFlags = INSTALL_EXTERNAL; 19504 moveCompleteApp = false; 19505 measurePath = storage.getPrimaryPhysicalVolume().getPath(); 19506 } else { 19507 final VolumeInfo volume = storage.findVolumeByUuid(volumeUuid); 19508 if (volume == null || volume.getType() != VolumeInfo.TYPE_PRIVATE 19509 || !volume.isMountedWritable()) { 19510 freezer.close(); 19511 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19512 "Move location not mounted private volume"); 19513 } 19514 19515 Preconditions.checkState(!currentAsec); 19516 19517 installFlags = INSTALL_INTERNAL; 19518 moveCompleteApp = true; 19519 measurePath = Environment.getDataAppDirectory(volumeUuid); 19520 } 19521 19522 final PackageStats stats = new PackageStats(null, -1); 19523 synchronized (mInstaller) { 19524 if (!getPackageSizeInfoLI(packageName, -1, stats)) { 19525 freezer.close(); 19526 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19527 "Failed to measure package size"); 19528 } 19529 } 19530 19531 if (DEBUG_INSTALL) Slog.d(TAG, "Measured code size " + stats.codeSize + ", data size " 19532 + stats.dataSize); 19533 19534 final long startFreeBytes = measurePath.getFreeSpace(); 19535 final long sizeBytes; 19536 if (moveCompleteApp) { 19537 sizeBytes = stats.codeSize + stats.dataSize; 19538 } else { 19539 sizeBytes = stats.codeSize; 19540 } 19541 19542 if (sizeBytes > storage.getStorageBytesUntilLow(measurePath)) { 19543 freezer.close(); 19544 throw new PackageManagerException(MOVE_FAILED_INTERNAL_ERROR, 19545 "Not enough free space to move"); 19546 } 19547 19548 mMoveCallbacks.notifyStatusChanged(moveId, 10); 19549 19550 final CountDownLatch installedLatch = new CountDownLatch(1); 19551 final IPackageInstallObserver2 installObserver = new IPackageInstallObserver2.Stub() { 19552 @Override 19553 public void onUserActionRequired(Intent intent) throws RemoteException { 19554 throw new IllegalStateException(); 19555 } 19556 19557 @Override 19558 public void onPackageInstalled(String basePackageName, int returnCode, String msg, 19559 Bundle extras) throws RemoteException { 19560 if (DEBUG_INSTALL) Slog.d(TAG, "Install result for move: " 19561 + PackageManager.installStatusToString(returnCode, msg)); 19562 19563 installedLatch.countDown(); 19564 freezer.close(); 19565 19566 final int status = PackageManager.installStatusToPublicStatus(returnCode); 19567 switch (status) { 19568 case PackageInstaller.STATUS_SUCCESS: 19569 mMoveCallbacks.notifyStatusChanged(moveId, 19570 PackageManager.MOVE_SUCCEEDED); 19571 break; 19572 case PackageInstaller.STATUS_FAILURE_STORAGE: 19573 mMoveCallbacks.notifyStatusChanged(moveId, 19574 PackageManager.MOVE_FAILED_INSUFFICIENT_STORAGE); 19575 break; 19576 default: 19577 mMoveCallbacks.notifyStatusChanged(moveId, 19578 PackageManager.MOVE_FAILED_INTERNAL_ERROR); 19579 break; 19580 } 19581 } 19582 }; 19583 19584 final MoveInfo move; 19585 if (moveCompleteApp) { 19586 // Kick off a thread to report progress estimates 19587 new Thread() { 19588 @Override 19589 public void run() { 19590 while (true) { 19591 try { 19592 if (installedLatch.await(1, TimeUnit.SECONDS)) { 19593 break; 19594 } 19595 } catch (InterruptedException ignored) { 19596 } 19597 19598 final long deltaFreeBytes = startFreeBytes - measurePath.getFreeSpace(); 19599 final int progress = 10 + (int) MathUtils.constrain( 19600 ((deltaFreeBytes * 80) / sizeBytes), 0, 80); 19601 mMoveCallbacks.notifyStatusChanged(moveId, progress); 19602 } 19603 } 19604 }.start(); 19605 19606 final String dataAppName = codeFile.getName(); 19607 move = new MoveInfo(moveId, currentVolumeUuid, volumeUuid, packageName, 19608 dataAppName, appId, seinfo, targetSdkVersion); 19609 } else { 19610 move = null; 19611 } 19612 19613 installFlags |= PackageManager.INSTALL_REPLACE_EXISTING; 19614 19615 final Message msg = mHandler.obtainMessage(INIT_COPY); 19616 final OriginInfo origin = OriginInfo.fromExistingFile(codeFile); 19617 final InstallParams params = new InstallParams(origin, move, installObserver, installFlags, 19618 installerPackageName, volumeUuid, null /*verificationInfo*/, user, 19619 packageAbiOverride, null /*grantedPermissions*/, null /*certificates*/); 19620 params.setTraceMethod("movePackage").setTraceCookie(System.identityHashCode(params)); 19621 msg.obj = params; 19622 19623 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "movePackage", 19624 System.identityHashCode(msg.obj)); 19625 Trace.asyncTraceBegin(TRACE_TAG_PACKAGE_MANAGER, "queueInstall", 19626 System.identityHashCode(msg.obj)); 19627 19628 mHandler.sendMessage(msg); 19629 } 19630 19631 @Override 19632 public int movePrimaryStorage(String volumeUuid) throws RemoteException { 19633 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.MOVE_PACKAGE, null); 19634 19635 final int realMoveId = mNextMoveId.getAndIncrement(); 19636 final Bundle extras = new Bundle(); 19637 extras.putString(VolumeRecord.EXTRA_FS_UUID, volumeUuid); 19638 mMoveCallbacks.notifyCreated(realMoveId, extras); 19639 19640 final IPackageMoveObserver callback = new IPackageMoveObserver.Stub() { 19641 @Override 19642 public void onCreated(int moveId, Bundle extras) { 19643 // Ignored 19644 } 19645 19646 @Override 19647 public void onStatusChanged(int moveId, int status, long estMillis) { 19648 mMoveCallbacks.notifyStatusChanged(realMoveId, status, estMillis); 19649 } 19650 }; 19651 19652 final StorageManager storage = mContext.getSystemService(StorageManager.class); 19653 storage.setPrimaryStorageUuid(volumeUuid, callback); 19654 return realMoveId; 19655 } 19656 19657 @Override 19658 public int getMoveStatus(int moveId) { 19659 mContext.enforceCallingOrSelfPermission( 19660 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19661 return mMoveCallbacks.mLastStatus.get(moveId); 19662 } 19663 19664 @Override 19665 public void registerMoveCallback(IPackageMoveObserver callback) { 19666 mContext.enforceCallingOrSelfPermission( 19667 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19668 mMoveCallbacks.register(callback); 19669 } 19670 19671 @Override 19672 public void unregisterMoveCallback(IPackageMoveObserver callback) { 19673 mContext.enforceCallingOrSelfPermission( 19674 android.Manifest.permission.MOUNT_UNMOUNT_FILESYSTEMS, null); 19675 mMoveCallbacks.unregister(callback); 19676 } 19677 19678 @Override 19679 public boolean setInstallLocation(int loc) { 19680 mContext.enforceCallingOrSelfPermission(android.Manifest.permission.WRITE_SECURE_SETTINGS, 19681 null); 19682 if (getInstallLocation() == loc) { 19683 return true; 19684 } 19685 if (loc == PackageHelper.APP_INSTALL_AUTO || loc == PackageHelper.APP_INSTALL_INTERNAL 19686 || loc == PackageHelper.APP_INSTALL_EXTERNAL) { 19687 android.provider.Settings.Global.putInt(mContext.getContentResolver(), 19688 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, loc); 19689 return true; 19690 } 19691 return false; 19692 } 19693 19694 @Override 19695 public int getInstallLocation() { 19696 return android.provider.Settings.Global.getInt(mContext.getContentResolver(), 19697 android.provider.Settings.Global.DEFAULT_INSTALL_LOCATION, 19698 PackageHelper.APP_INSTALL_AUTO); 19699 } 19700 19701 /** Called by UserManagerService */ 19702 void cleanUpUser(UserManagerService userManager, int userHandle) { 19703 synchronized (mPackages) { 19704 mDirtyUsers.remove(userHandle); 19705 mUserNeedsBadging.delete(userHandle); 19706 mSettings.removeUserLPw(userHandle); 19707 mPendingBroadcasts.remove(userHandle); 19708 mEphemeralApplicationRegistry.onUserRemovedLPw(userHandle); 19709 removeUnusedPackagesLPw(userManager, userHandle); 19710 } 19711 } 19712 19713 /** 19714 * We're removing userHandle and would like to remove any downloaded packages 19715 * that are no longer in use by any other user. 19716 * @param userHandle the user being removed 19717 */ 19718 private void removeUnusedPackagesLPw(UserManagerService userManager, final int userHandle) { 19719 final boolean DEBUG_CLEAN_APKS = false; 19720 int [] users = userManager.getUserIds(); 19721 Iterator<PackageSetting> psit = mSettings.mPackages.values().iterator(); 19722 while (psit.hasNext()) { 19723 PackageSetting ps = psit.next(); 19724 if (ps.pkg == null) { 19725 continue; 19726 } 19727 final String packageName = ps.pkg.packageName; 19728 // Skip over if system app 19729 if ((ps.pkgFlags & ApplicationInfo.FLAG_SYSTEM) != 0) { 19730 continue; 19731 } 19732 if (DEBUG_CLEAN_APKS) { 19733 Slog.i(TAG, "Checking package " + packageName); 19734 } 19735 boolean keep = shouldKeepUninstalledPackageLPr(packageName); 19736 if (keep) { 19737 if (DEBUG_CLEAN_APKS) { 19738 Slog.i(TAG, " Keeping package " + packageName + " - requested by DO"); 19739 } 19740 } else { 19741 for (int i = 0; i < users.length; i++) { 19742 if (users[i] != userHandle && ps.getInstalled(users[i])) { 19743 keep = true; 19744 if (DEBUG_CLEAN_APKS) { 19745 Slog.i(TAG, " Keeping package " + packageName + " for user " 19746 + users[i]); 19747 } 19748 break; 19749 } 19750 } 19751 } 19752 if (!keep) { 19753 if (DEBUG_CLEAN_APKS) { 19754 Slog.i(TAG, " Removing package " + packageName); 19755 } 19756 mHandler.post(new Runnable() { 19757 public void run() { 19758 deletePackageX(packageName, userHandle, 0); 19759 } //end run 19760 }); 19761 } 19762 } 19763 } 19764 19765 /** Called by UserManagerService */ 19766 void createNewUser(int userHandle) { 19767 synchronized (mInstallLock) { 19768 mSettings.createNewUserLI(this, mInstaller, userHandle); 19769 } 19770 synchronized (mPackages) { 19771 applyFactoryDefaultBrowserLPw(userHandle); 19772 primeDomainVerificationsLPw(userHandle); 19773 } 19774 } 19775 19776 void newUserCreated(final int userHandle) { 19777 mDefaultPermissionPolicy.grantDefaultPermissions(userHandle); 19778 // If permission review for legacy apps is required, we represent 19779 // dagerous permissions for such apps as always granted runtime 19780 // permissions to keep per user flag state whether review is needed. 19781 // Hence, if a new user is added we have to propagate dangerous 19782 // permission grants for these legacy apps. 19783 if (Build.PERMISSIONS_REVIEW_REQUIRED) { 19784 updatePermissionsLPw(null, null, UPDATE_PERMISSIONS_ALL 19785 | UPDATE_PERMISSIONS_REPLACE_ALL); 19786 } 19787 } 19788 19789 @Override 19790 public VerifierDeviceIdentity getVerifierDeviceIdentity() throws RemoteException { 19791 mContext.enforceCallingOrSelfPermission( 19792 android.Manifest.permission.PACKAGE_VERIFICATION_AGENT, 19793 "Only package verification agents can read the verifier device identity"); 19794 19795 synchronized (mPackages) { 19796 return mSettings.getVerifierDeviceIdentityLPw(); 19797 } 19798 } 19799 19800 @Override 19801 public void setPermissionEnforced(String permission, boolean enforced) { 19802 // TODO: Now that we no longer change GID for storage, this should to away. 19803 mContext.enforceCallingOrSelfPermission(Manifest.permission.GRANT_RUNTIME_PERMISSIONS, 19804 "setPermissionEnforced"); 19805 if (READ_EXTERNAL_STORAGE.equals(permission)) { 19806 synchronized (mPackages) { 19807 if (mSettings.mReadExternalStorageEnforced == null 19808 || mSettings.mReadExternalStorageEnforced != enforced) { 19809 mSettings.mReadExternalStorageEnforced = enforced; 19810 mSettings.writeLPr(); 19811 } 19812 } 19813 // kill any non-foreground processes so we restart them and 19814 // grant/revoke the GID. 19815 final IActivityManager am = ActivityManagerNative.getDefault(); 19816 if (am != null) { 19817 final long token = Binder.clearCallingIdentity(); 19818 try { 19819 am.killProcessesBelowForeground("setPermissionEnforcement"); 19820 } catch (RemoteException e) { 19821 } finally { 19822 Binder.restoreCallingIdentity(token); 19823 } 19824 } 19825 } else { 19826 throw new IllegalArgumentException("No selective enforcement for " + permission); 19827 } 19828 } 19829 19830 @Override 19831 @Deprecated 19832 public boolean isPermissionEnforced(String permission) { 19833 return true; 19834 } 19835 19836 @Override 19837 public boolean isStorageLow() { 19838 final long token = Binder.clearCallingIdentity(); 19839 try { 19840 final DeviceStorageMonitorInternal 19841 dsm = LocalServices.getService(DeviceStorageMonitorInternal.class); 19842 if (dsm != null) { 19843 return dsm.isMemoryLow(); 19844 } else { 19845 return false; 19846 } 19847 } finally { 19848 Binder.restoreCallingIdentity(token); 19849 } 19850 } 19851 19852 @Override 19853 public IPackageInstaller getPackageInstaller() { 19854 return mInstallerService; 19855 } 19856 19857 private boolean userNeedsBadging(int userId) { 19858 int index = mUserNeedsBadging.indexOfKey(userId); 19859 if (index < 0) { 19860 final UserInfo userInfo; 19861 final long token = Binder.clearCallingIdentity(); 19862 try { 19863 userInfo = sUserManager.getUserInfo(userId); 19864 } finally { 19865 Binder.restoreCallingIdentity(token); 19866 } 19867 final boolean b; 19868 if (userInfo != null && userInfo.isManagedProfile()) { 19869 b = true; 19870 } else { 19871 b = false; 19872 } 19873 mUserNeedsBadging.put(userId, b); 19874 return b; 19875 } 19876 return mUserNeedsBadging.valueAt(index); 19877 } 19878 19879 @Override 19880 public KeySet getKeySetByAlias(String packageName, String alias) { 19881 if (packageName == null || alias == null) { 19882 return null; 19883 } 19884 synchronized(mPackages) { 19885 final PackageParser.Package pkg = mPackages.get(packageName); 19886 if (pkg == null) { 19887 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19888 throw new IllegalArgumentException("Unknown package: " + packageName); 19889 } 19890 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19891 return new KeySet(ksms.getKeySetByAliasAndPackageNameLPr(packageName, alias)); 19892 } 19893 } 19894 19895 @Override 19896 public KeySet getSigningKeySet(String packageName) { 19897 if (packageName == null) { 19898 return null; 19899 } 19900 synchronized(mPackages) { 19901 final PackageParser.Package pkg = mPackages.get(packageName); 19902 if (pkg == null) { 19903 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19904 throw new IllegalArgumentException("Unknown package: " + packageName); 19905 } 19906 if (pkg.applicationInfo.uid != Binder.getCallingUid() 19907 && Process.SYSTEM_UID != Binder.getCallingUid()) { 19908 throw new SecurityException("May not access signing KeySet of other apps."); 19909 } 19910 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19911 return new KeySet(ksms.getSigningKeySetByPackageNameLPr(packageName)); 19912 } 19913 } 19914 19915 @Override 19916 public boolean isPackageSignedByKeySet(String packageName, KeySet ks) { 19917 if (packageName == null || ks == null) { 19918 return false; 19919 } 19920 synchronized(mPackages) { 19921 final PackageParser.Package pkg = mPackages.get(packageName); 19922 if (pkg == null) { 19923 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19924 throw new IllegalArgumentException("Unknown package: " + packageName); 19925 } 19926 IBinder ksh = ks.getToken(); 19927 if (ksh instanceof KeySetHandle) { 19928 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19929 return ksms.packageIsSignedByLPr(packageName, (KeySetHandle) ksh); 19930 } 19931 return false; 19932 } 19933 } 19934 19935 @Override 19936 public boolean isPackageSignedByKeySetExactly(String packageName, KeySet ks) { 19937 if (packageName == null || ks == null) { 19938 return false; 19939 } 19940 synchronized(mPackages) { 19941 final PackageParser.Package pkg = mPackages.get(packageName); 19942 if (pkg == null) { 19943 Slog.w(TAG, "KeySet requested for unknown package: " + packageName); 19944 throw new IllegalArgumentException("Unknown package: " + packageName); 19945 } 19946 IBinder ksh = ks.getToken(); 19947 if (ksh instanceof KeySetHandle) { 19948 KeySetManagerService ksms = mSettings.mKeySetManagerService; 19949 return ksms.packageIsSignedByExactlyLPr(packageName, (KeySetHandle) ksh); 19950 } 19951 return false; 19952 } 19953 } 19954 19955 private void deletePackageIfUnusedLPr(final String packageName) { 19956 PackageSetting ps = mSettings.mPackages.get(packageName); 19957 if (ps == null) { 19958 return; 19959 } 19960 if (!ps.isAnyInstalled(sUserManager.getUserIds())) { 19961 // TODO Implement atomic delete if package is unused 19962 // It is currently possible that the package will be deleted even if it is installed 19963 // after this method returns. 19964 mHandler.post(new Runnable() { 19965 public void run() { 19966 deletePackageX(packageName, 0, PackageManager.DELETE_ALL_USERS); 19967 } 19968 }); 19969 } 19970 } 19971 19972 /** 19973 * Check and throw if the given before/after packages would be considered a 19974 * downgrade. 19975 */ 19976 private static void checkDowngrade(PackageParser.Package before, PackageInfoLite after) 19977 throws PackageManagerException { 19978 if (after.versionCode < before.mVersionCode) { 19979 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19980 "Update version code " + after.versionCode + " is older than current " 19981 + before.mVersionCode); 19982 } else if (after.versionCode == before.mVersionCode) { 19983 if (after.baseRevisionCode < before.baseRevisionCode) { 19984 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19985 "Update base revision code " + after.baseRevisionCode 19986 + " is older than current " + before.baseRevisionCode); 19987 } 19988 19989 if (!ArrayUtils.isEmpty(after.splitNames)) { 19990 for (int i = 0; i < after.splitNames.length; i++) { 19991 final String splitName = after.splitNames[i]; 19992 final int j = ArrayUtils.indexOf(before.splitNames, splitName); 19993 if (j != -1) { 19994 if (after.splitRevisionCodes[i] < before.splitRevisionCodes[j]) { 19995 throw new PackageManagerException(INSTALL_FAILED_VERSION_DOWNGRADE, 19996 "Update split " + splitName + " revision code " 19997 + after.splitRevisionCodes[i] + " is older than current " 19998 + before.splitRevisionCodes[j]); 19999 } 20000 } 20001 } 20002 } 20003 } 20004 } 20005 20006 private static class MoveCallbacks extends Handler { 20007 private static final int MSG_CREATED = 1; 20008 private static final int MSG_STATUS_CHANGED = 2; 20009 20010 private final RemoteCallbackList<IPackageMoveObserver> 20011 mCallbacks = new RemoteCallbackList<>(); 20012 20013 private final SparseIntArray mLastStatus = new SparseIntArray(); 20014 20015 public MoveCallbacks(Looper looper) { 20016 super(looper); 20017 } 20018 20019 public void register(IPackageMoveObserver callback) { 20020 mCallbacks.register(callback); 20021 } 20022 20023 public void unregister(IPackageMoveObserver callback) { 20024 mCallbacks.unregister(callback); 20025 } 20026 20027 @Override 20028 public void handleMessage(Message msg) { 20029 final SomeArgs args = (SomeArgs) msg.obj; 20030 final int n = mCallbacks.beginBroadcast(); 20031 for (int i = 0; i < n; i++) { 20032 final IPackageMoveObserver callback = mCallbacks.getBroadcastItem(i); 20033 try { 20034 invokeCallback(callback, msg.what, args); 20035 } catch (RemoteException ignored) { 20036 } 20037 } 20038 mCallbacks.finishBroadcast(); 20039 args.recycle(); 20040 } 20041 20042 private void invokeCallback(IPackageMoveObserver callback, int what, SomeArgs args) 20043 throws RemoteException { 20044 switch (what) { 20045 case MSG_CREATED: { 20046 callback.onCreated(args.argi1, (Bundle) args.arg2); 20047 break; 20048 } 20049 case MSG_STATUS_CHANGED: { 20050 callback.onStatusChanged(args.argi1, args.argi2, (long) args.arg3); 20051 break; 20052 } 20053 } 20054 } 20055 20056 private void notifyCreated(int moveId, Bundle extras) { 20057 Slog.v(TAG, "Move " + moveId + " created " + extras.toString()); 20058 20059 final SomeArgs args = SomeArgs.obtain(); 20060 args.argi1 = moveId; 20061 args.arg2 = extras; 20062 obtainMessage(MSG_CREATED, args).sendToTarget(); 20063 } 20064 20065 private void notifyStatusChanged(int moveId, int status) { 20066 notifyStatusChanged(moveId, status, -1); 20067 } 20068 20069 private void notifyStatusChanged(int moveId, int status, long estMillis) { 20070 Slog.v(TAG, "Move " + moveId + " status " + status); 20071 20072 final SomeArgs args = SomeArgs.obtain(); 20073 args.argi1 = moveId; 20074 args.argi2 = status; 20075 args.arg3 = estMillis; 20076 obtainMessage(MSG_STATUS_CHANGED, args).sendToTarget(); 20077 20078 synchronized (mLastStatus) { 20079 mLastStatus.put(moveId, status); 20080 } 20081 } 20082 } 20083 20084 private final static class OnPermissionChangeListeners extends Handler { 20085 private static final int MSG_ON_PERMISSIONS_CHANGED = 1; 20086 20087 private final RemoteCallbackList<IOnPermissionsChangeListener> mPermissionListeners = 20088 new RemoteCallbackList<>(); 20089 20090 public OnPermissionChangeListeners(Looper looper) { 20091 super(looper); 20092 } 20093 20094 @Override 20095 public void handleMessage(Message msg) { 20096 switch (msg.what) { 20097 case MSG_ON_PERMISSIONS_CHANGED: { 20098 final int uid = msg.arg1; 20099 handleOnPermissionsChanged(uid); 20100 } break; 20101 } 20102 } 20103 20104 public void addListenerLocked(IOnPermissionsChangeListener listener) { 20105 mPermissionListeners.register(listener); 20106 20107 } 20108 20109 public void removeListenerLocked(IOnPermissionsChangeListener listener) { 20110 mPermissionListeners.unregister(listener); 20111 } 20112 20113 public void onPermissionsChanged(int uid) { 20114 if (mPermissionListeners.getRegisteredCallbackCount() > 0) { 20115 obtainMessage(MSG_ON_PERMISSIONS_CHANGED, uid, 0).sendToTarget(); 20116 } 20117 } 20118 20119 private void handleOnPermissionsChanged(int uid) { 20120 final int count = mPermissionListeners.beginBroadcast(); 20121 try { 20122 for (int i = 0; i < count; i++) { 20123 IOnPermissionsChangeListener callback = mPermissionListeners 20124 .getBroadcastItem(i); 20125 try { 20126 callback.onPermissionsChanged(uid); 20127 } catch (RemoteException e) { 20128 Log.e(TAG, "Permission listener is dead", e); 20129 } 20130 } 20131 } finally { 20132 mPermissionListeners.finishBroadcast(); 20133 } 20134 } 20135 } 20136 20137 private class PackageManagerInternalImpl extends PackageManagerInternal { 20138 @Override 20139 public void setLocationPackagesProvider(PackagesProvider provider) { 20140 synchronized (mPackages) { 20141 mDefaultPermissionPolicy.setLocationPackagesProviderLPw(provider); 20142 } 20143 } 20144 20145 @Override 20146 public void setVoiceInteractionPackagesProvider(PackagesProvider provider) { 20147 synchronized (mPackages) { 20148 mDefaultPermissionPolicy.setVoiceInteractionPackagesProviderLPw(provider); 20149 } 20150 } 20151 20152 @Override 20153 public void setSmsAppPackagesProvider(PackagesProvider provider) { 20154 synchronized (mPackages) { 20155 mDefaultPermissionPolicy.setSmsAppPackagesProviderLPw(provider); 20156 } 20157 } 20158 20159 @Override 20160 public void setDialerAppPackagesProvider(PackagesProvider provider) { 20161 synchronized (mPackages) { 20162 mDefaultPermissionPolicy.setDialerAppPackagesProviderLPw(provider); 20163 } 20164 } 20165 20166 @Override 20167 public void setSimCallManagerPackagesProvider(PackagesProvider provider) { 20168 synchronized (mPackages) { 20169 mDefaultPermissionPolicy.setSimCallManagerPackagesProviderLPw(provider); 20170 } 20171 } 20172 20173 @Override 20174 public void setSyncAdapterPackagesprovider(SyncAdapterPackagesProvider provider) { 20175 synchronized (mPackages) { 20176 mDefaultPermissionPolicy.setSyncAdapterPackagesProviderLPw(provider); 20177 } 20178 } 20179 20180 @Override 20181 public void grantDefaultPermissionsToDefaultSmsApp(String packageName, int userId) { 20182 synchronized (mPackages) { 20183 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSmsAppLPr( 20184 packageName, userId); 20185 } 20186 } 20187 20188 @Override 20189 public void grantDefaultPermissionsToDefaultDialerApp(String packageName, int userId) { 20190 synchronized (mPackages) { 20191 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultDialerAppLPr( 20192 packageName, userId); 20193 } 20194 } 20195 20196 @Override 20197 public void grantDefaultPermissionsToDefaultSimCallManager(String packageName, int userId) { 20198 synchronized (mPackages) { 20199 mDefaultPermissionPolicy.grantDefaultPermissionsToDefaultSimCallManagerLPr( 20200 packageName, userId); 20201 } 20202 } 20203 20204 @Override 20205 public void setKeepUninstalledPackages(final List<String> packageList) { 20206 Preconditions.checkNotNull(packageList); 20207 List<String> removedFromList = null; 20208 synchronized (mPackages) { 20209 if (mKeepUninstalledPackages != null) { 20210 final int packagesCount = mKeepUninstalledPackages.size(); 20211 for (int i = 0; i < packagesCount; i++) { 20212 String oldPackage = mKeepUninstalledPackages.get(i); 20213 if (packageList != null && packageList.contains(oldPackage)) { 20214 continue; 20215 } 20216 if (removedFromList == null) { 20217 removedFromList = new ArrayList<>(); 20218 } 20219 removedFromList.add(oldPackage); 20220 } 20221 } 20222 mKeepUninstalledPackages = new ArrayList<>(packageList); 20223 if (removedFromList != null) { 20224 final int removedCount = removedFromList.size(); 20225 for (int i = 0; i < removedCount; i++) { 20226 deletePackageIfUnusedLPr(removedFromList.get(i)); 20227 } 20228 } 20229 } 20230 } 20231 20232 @Override 20233 public boolean isPermissionsReviewRequired(String packageName, int userId) { 20234 synchronized (mPackages) { 20235 // If we do not support permission review, done. 20236 if (!Build.PERMISSIONS_REVIEW_REQUIRED) { 20237 return false; 20238 } 20239 20240 PackageSetting packageSetting = mSettings.mPackages.get(packageName); 20241 if (packageSetting == null) { 20242 return false; 20243 } 20244 20245 // Permission review applies only to apps not supporting the new permission model. 20246 if (packageSetting.pkg.applicationInfo.targetSdkVersion >= Build.VERSION_CODES.M) { 20247 return false; 20248 } 20249 20250 // Legacy apps have the permission and get user consent on launch. 20251 PermissionsState permissionsState = packageSetting.getPermissionsState(); 20252 return permissionsState.isPermissionReviewRequired(userId); 20253 } 20254 } 20255 20256 @Override 20257 public ApplicationInfo getApplicationInfo(String packageName, int userId) { 20258 return PackageManagerService.this.getApplicationInfo(packageName, 0 /*flags*/, userId); 20259 } 20260 20261 @Override 20262 public ComponentName getHomeActivitiesAsUser(List<ResolveInfo> allHomeCandidates, 20263 int userId) { 20264 return PackageManagerService.this.getHomeActivitiesAsUser(allHomeCandidates, userId); 20265 } 20266 } 20267 20268 @Override 20269 public void grantDefaultPermissionsToEnabledCarrierApps(String[] packageNames, int userId) { 20270 enforceSystemOrPhoneCaller("grantPermissionsToEnabledCarrierApps"); 20271 synchronized (mPackages) { 20272 final long identity = Binder.clearCallingIdentity(); 20273 try { 20274 mDefaultPermissionPolicy.grantDefaultPermissionsToEnabledCarrierAppsLPr( 20275 packageNames, userId); 20276 } finally { 20277 Binder.restoreCallingIdentity(identity); 20278 } 20279 } 20280 } 20281 20282 private static void enforceSystemOrPhoneCaller(String tag) { 20283 int callingUid = Binder.getCallingUid(); 20284 if (callingUid != Process.PHONE_UID && callingUid != Process.SYSTEM_UID) { 20285 throw new SecurityException( 20286 "Cannot call " + tag + " from UID " + callingUid); 20287 } 20288 } 20289 20290 boolean isHistoricalPackageUsageAvailable() { 20291 return mPackageUsage.isHistoricalPackageUsageAvailable(); 20292 } 20293 20294 /** 20295 * Return a <b>copy</b> of the collection of packages known to the package manager. 20296 * @return A copy of the values of mPackages. 20297 */ 20298 Collection<PackageParser.Package> getPackages() { 20299 synchronized (mPackages) { 20300 return new ArrayList<>(mPackages.values()); 20301 } 20302 } 20303 20304 /** 20305 * Logs process start information (including base APK hash) to the security log. 20306 * @hide 20307 */ 20308 public void logAppProcessStartIfNeeded(String processName, int uid, String seinfo, 20309 String apkFile, int pid) { 20310 if (!SecurityLog.isLoggingEnabled()) { 20311 return; 20312 } 20313 Bundle data = new Bundle(); 20314 data.putLong("startTimestamp", System.currentTimeMillis()); 20315 data.putString("processName", processName); 20316 data.putInt("uid", uid); 20317 data.putString("seinfo", seinfo); 20318 data.putString("apkFile", apkFile); 20319 data.putInt("pid", pid); 20320 Message msg = mProcessLoggingHandler.obtainMessage( 20321 ProcessLoggingHandler.LOG_APP_PROCESS_START_MSG); 20322 msg.setData(data); 20323 mProcessLoggingHandler.sendMessage(msg); 20324 } 20325} 20326